From dc04ed305c9578ad805674c0ce697e6223357f8e Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 24 Jan 2022 23:30:08 +0800 Subject: [PATCH 001/490] adq ini file with default value false --- src/libs/antares/study/area/area.h | 2 ++ src/libs/antares/study/area/list.cpp | 14 ++++++++++++++ src/libs/antares/study/cleaner/cleaner-v20.cpp | 2 ++ 3 files changed, 18 insertions(+) diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 5be1b4ec35..0157a9c898 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -347,6 +347,8 @@ class Area final : private Yuni::NonCopyable bool saveAreaOptimisationIniFile(const Area& area, const Yuni::Clob& buffer); +bool saveAreaAdequancyPatchIniFile(const Area& area, const Yuni::Clob& buffer); + /*! ** \brief A list of areas ** diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 833bf7084a..d4cfe97691 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -203,6 +203,11 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << "optimization.ini"; ret = saveAreaOptimisationIniFile(area, buffer) and ret; + //Adequancy ini + buffer.clear() << folder << SEP << "input" << SEP << "areas" << SEP << area.id << SEP + << "adequancy_patch.ini"; + ret = saveAreaAdequancyPatchIniFile(area, buffer) and ret; + // Reserves: primary, strategic, dsm, d-1... buffer.clear() << folder << SEP << "input" << SEP << "reserves" << SEP << area.id << ".txt"; ret = area.reserves.saveToCSVFile(buffer) and ret; @@ -323,6 +328,15 @@ bool saveAreaOptimisationIniFile(const Area& area, const Clob& buffer) return ini.save(buffer); } +bool saveAreaAdequancyPatchIniFile(const Area& area, const Clob& buffer) +{ + IniFile ini; + IniFile::Section* section = ini.addSection("adequancy-patch"); + bool bUseAdequancyPatch = false; //adq: this should be later replaced with area.bUseAdequancyPatch + section->add("use-adequancy-patch", static_cast(bUseAdequancyPatch)); + return ini.save(buffer); +} + AreaList::AreaList(Study& study) : byIndex(nullptr), pStudy(study) { } diff --git a/src/libs/antares/study/cleaner/cleaner-v20.cpp b/src/libs/antares/study/cleaner/cleaner-v20.cpp index ceaf35257a..18b06f0071 100644 --- a/src/libs/antares/study/cleaner/cleaner-v20.cpp +++ b/src/libs/antares/study/cleaner/cleaner-v20.cpp @@ -195,6 +195,8 @@ static void PreflightVersion20_area(PathList& e, PathList& p, const Area* area, e.add(buffer); buffer.clear() << "input/areas/" << id << "/optimization.ini"; e.add(buffer); + buffer.clear() << "input/areas/" << id << "/adequancy_patch.ini"; + e.add(buffer); // Interconnections buffer.clear() << "input/links/" << id; From aad78aeb3e672995a3bcecc53a0dff62556f31fd Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Tue, 25 Jan 2022 00:08:18 +0800 Subject: [PATCH 002/490] typo --- src/libs/antares/study/area/area.h | 2 +- src/libs/antares/study/area/list.cpp | 14 +++++++------- src/libs/antares/study/cleaner/cleaner-v20.cpp | 2 +- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 0157a9c898..e42b96edd6 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -347,7 +347,7 @@ class Area final : private Yuni::NonCopyable bool saveAreaOptimisationIniFile(const Area& area, const Yuni::Clob& buffer); -bool saveAreaAdequancyPatchIniFile(const Area& area, const Yuni::Clob& buffer); +bool saveAreaAdequacyPatchIniFile(const Area& area, const Yuni::Clob& buffer); /*! ** \brief A list of areas diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index d4cfe97691..b1bb9436ec 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -203,10 +203,10 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << "optimization.ini"; ret = saveAreaOptimisationIniFile(area, buffer) and ret; - //Adequancy ini + //Adequacy ini buffer.clear() << folder << SEP << "input" << SEP << "areas" << SEP << area.id << SEP - << "adequancy_patch.ini"; - ret = saveAreaAdequancyPatchIniFile(area, buffer) and ret; + << "adequacy_patch.ini"; + ret = saveAreaAdequacyPatchIniFile(area, buffer) and ret; // Reserves: primary, strategic, dsm, d-1... buffer.clear() << folder << SEP << "input" << SEP << "reserves" << SEP << area.id << ".txt"; @@ -328,12 +328,12 @@ bool saveAreaOptimisationIniFile(const Area& area, const Clob& buffer) return ini.save(buffer); } -bool saveAreaAdequancyPatchIniFile(const Area& area, const Clob& buffer) +bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) { IniFile ini; - IniFile::Section* section = ini.addSection("adequancy-patch"); - bool bUseAdequancyPatch = false; //adq: this should be later replaced with area.bUseAdequancyPatch - section->add("use-adequancy-patch", static_cast(bUseAdequancyPatch)); + IniFile::Section* section = ini.addSection("adequacy-patch"); + bool bUseAdequacyPatch = false; //adq: this should be later replaced with area.bUseAdequacyPatch + section->add("use-adequacy-patch", static_cast(bUseAdequacyPatch)); return ini.save(buffer); } diff --git a/src/libs/antares/study/cleaner/cleaner-v20.cpp b/src/libs/antares/study/cleaner/cleaner-v20.cpp index 18b06f0071..b57e00d3b1 100644 --- a/src/libs/antares/study/cleaner/cleaner-v20.cpp +++ b/src/libs/antares/study/cleaner/cleaner-v20.cpp @@ -195,7 +195,7 @@ static void PreflightVersion20_area(PathList& e, PathList& p, const Area* area, e.add(buffer); buffer.clear() << "input/areas/" << id << "/optimization.ini"; e.add(buffer); - buffer.clear() << "input/areas/" << id << "/adequancy_patch.ini"; + buffer.clear() << "input/areas/" << id << "/adequacy_patch.ini"; e.add(buffer); // Interconnections From a97c7677100685aa547a417c469c94d0b5a0fd8c Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 25 Jan 2022 20:49:50 +0100 Subject: [PATCH 003/490] created the option button(false/true) for adequacy patch and updated the ref-guide --- docs/reference-guide/1-reference-guide.md | 1 + src/libs/antares/study/parameters.cpp | 6 ++++++ src/libs/antares/study/parameters.h | 3 +++ .../options/optimization/optimization.cpp | 20 +++++++++++++++++++ .../options/optimization/optimization.h | 1 + 5 files changed, 31 insertions(+) diff --git a/docs/reference-guide/1-reference-guide.md b/docs/reference-guide/1-reference-guide.md index b3667d8eb1..ab502738f7 100644 --- a/docs/reference-guide/1-reference-guide.md +++ b/docs/reference-guide/1-reference-guide.md @@ -384,6 +384,7 @@ given back their regular capacities (infinite for those being set on "set to inf - _Strategic reserve (include / ignore)_ - _Spinning reserve (include / ignore)_ - _Export mps (false/true)_ + - _Adequacy patch (false/true)_ - _Simplex optimization range # 4_ _(day / week)_ - _Unfeasible problems behavior (Error Dry/ Error Verbose/ Warning Dry/ Warning Verbose_ diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 8626c8f477..ff98fc570d 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -304,6 +304,7 @@ void Parameters::reset() simplexOptimizationRange = sorWeek; include.exportMPS = false; + include.adequacyPatch = false; // parameter-reset method include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -548,6 +549,8 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, return value.to(d.include.reserve.primary); if (key == "include-exportmps") return value.to(d.include.exportMPS); + if (key == "include-adequacypatch") + return value.to(d.include.adequacyPatch); if (key == "include-exportstructure") return value.to(d.include.exportStructure); if (key == "include-unfeasible-problem-behavior") @@ -1541,6 +1544,8 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) logs.info() << " :: ignoring min up/down time for thermal clusters"; if (!include.exportMPS) logs.info() << " :: ignoring export mps"; + if (!include.adequacyPatch) // Windows-LogViewer + logs.info() << " :: ignoring adequacy patch"; if (!include.exportStructure) logs.info() << " :: ignoring export structure"; if (!include.hurdleCosts) @@ -1700,6 +1705,7 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-primaryreserve", include.reserve.primary); section->add("include-exportmps", include.exportMPS); + section->add("include-adequacypatch", include.adequacyPatch); // generaldata.ini, parameters.ini file section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 4d18ed3357..7a2910667f 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -416,6 +416,9 @@ class Parameters final //! a flag to export all mps files bool exportMPS; + //! a flag to use Adequacy patch + bool adequacyPatch; + //! a flag to export structure needed for Antares XPansion bool exportStructure; diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index 907838b991..e59ece7695 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -308,6 +308,22 @@ Optimization::Optimization(wxWindow* parent) : pBtnExportMPS = button; } + // Adequacy patch + { + label = Component::CreateLabel(this, wxT("Adequacy patch")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuSpecify, + PopupInfo(study.parameters.include.adequacyPatch, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatch = button; + } + + // Unfeasible problem behavior { label = Component::CreateLabel(this, wxT("Unfeasible problem behavior")); @@ -427,6 +443,7 @@ void Optimization::onResetToDefault(void*) study.parameters.include.reserve.primary = true; study.parameters.include.reserve.spinning = true; study.parameters.include.exportMPS = false; + study.parameters.include.adequacyPatch = false; study.parameters.simplexOptimizationRange = Data::sorWeek; study.parameters.include.unfeasibleProblemBehavior @@ -474,6 +491,9 @@ void Optimization::refresh() ResetButton(pBtnSpinningReserve, study.parameters.include.reserve.spinning); // Export mps ResetButtonSpecify(pBtnExportMPS, study.parameters.include.exportMPS); + // Export adequacy patch + ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); + // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index 2ec80bc48b..94df8da3f7 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -115,6 +115,7 @@ class Optimization final : public wxDialog Component::Button* pBtnSimplexOptimizationRange; Component::Button* pBtnExportMPS; + Component::Button* pBtnAdequacyPatch; Component::Button* pBtnUnfeasibleProblemBehavior; bool* pTargetRef; From 57a9c44884628f329c8e7647b79fe3be3c805541 Mon Sep 17 00:00:00 2001 From: milos Date: Wed, 26 Jan 2022 15:56:12 +0100 Subject: [PATCH 004/490] typo --- src/libs/antares/study/parameters.cpp | 6 +++--- .../simulator/windows/options/optimization/optimization.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index ff98fc570d..3737cb50c4 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -304,7 +304,7 @@ void Parameters::reset() simplexOptimizationRange = sorWeek; include.exportMPS = false; - include.adequacyPatch = false; // parameter-reset method + include.adequacyPatch = false; include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -1544,7 +1544,7 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) logs.info() << " :: ignoring min up/down time for thermal clusters"; if (!include.exportMPS) logs.info() << " :: ignoring export mps"; - if (!include.adequacyPatch) // Windows-LogViewer + if (!include.adequacyPatch) logs.info() << " :: ignoring adequacy patch"; if (!include.exportStructure) logs.info() << " :: ignoring export structure"; @@ -1705,7 +1705,7 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-primaryreserve", include.reserve.primary); section->add("include-exportmps", include.exportMPS); - section->add("include-adequacypatch", include.adequacyPatch); // generaldata.ini, parameters.ini file + section->add("include-adequacypatch", include.adequacyPatch); section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index e59ece7695..b8c4168ec8 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -491,7 +491,7 @@ void Optimization::refresh() ResetButton(pBtnSpinningReserve, study.parameters.include.reserve.spinning); // Export mps ResetButtonSpecify(pBtnExportMPS, study.parameters.include.exportMPS); - // Export adequacy patch + // Adequacy patch ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); From 68f44679ecb7a71f7530260eafe0b6b623f90f87 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 27 Jan 2022 18:46:05 +0800 Subject: [PATCH 005/490] ui selector --- src/libs/antares/study/area/area.cpp | 3 +++ src/libs/antares/study/area/area.h | 2 ++ src/libs/antares/study/area/list.cpp | 27 +++++++++++++++++-- src/ui/simulator/application/study.cpp | 1 + src/ui/simulator/application/study.h | 5 ++++ .../windows/inspector/accumulator.hxx | 13 +++++++++ src/ui/simulator/windows/inspector/frame.cpp | 7 +++++ src/ui/simulator/windows/inspector/frame.h | 2 ++ .../windows/inspector/property.update.cpp | 11 ++++++++ 9 files changed, 69 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index cefa226157..7fcf8ed8d7 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,6 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), + bUseAdequacyPatch(false), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -70,6 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), + bUseAdequacyPatch(false), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -89,6 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), + bUseAdequacyPatch(false), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index e42b96edd6..804b663c8a 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -225,6 +225,8 @@ class Area final : private Yuni::NonCopyable uint index; //! Enabled bool enabled; + //! Use adequacy patch for this area + bool bUseAdequacyPatch; /*@}*/ //! \name Associate data */ diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index b1bb9436ec..114c73d75b 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -332,8 +332,7 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) { IniFile ini; IniFile::Section* section = ini.addSection("adequacy-patch"); - bool bUseAdequacyPatch = false; //adq: this should be later replaced with area.bUseAdequacyPatch - section->add("use-adequacy-patch", static_cast(bUseAdequacyPatch)); + section->add("use-adequacy-patch", static_cast(area.bUseAdequacyPatch)); return ini.save(buffer); } @@ -1051,6 +1050,30 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, area.renewable.list.flush(); } + // Adequacy patch + if (study.header.version >= 820) + { + buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP + << "adequacy_patch.ini"; + IniFile ini; + if (ini.open(buffer)) + { + auto* section = ini.find("adequacy-patch"); + 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 == "use-adequacy-patch") + { + area.bUseAdequacyPatch = value; + continue; + } + } + } + } + // Nodal Optimization if (study.header.version >= 330) { diff --git a/src/ui/simulator/application/study.cpp b/src/ui/simulator/application/study.cpp index 908c98eb53..2780386b13 100644 --- a/src/ui/simulator/application/study.cpp +++ b/src/ui/simulator/application/study.cpp @@ -90,6 +90,7 @@ Event OnStudyLinkDelete; Event OnStudySimulationSettingsChanged; Event OnStudyNodalOptimizationChanged; +Event OnStudyAreaUseAdequacyPatchChanged; Event OnStudyThermalClusterCommonSettingsChanged; Event OnStudyThermalClusterRenamed; diff --git a/src/ui/simulator/application/study.h b/src/ui/simulator/application/study.h index c1a228a0de..f757b129a3 100644 --- a/src/ui/simulator/application/study.h +++ b/src/ui/simulator/application/study.h @@ -266,6 +266,11 @@ extern Yuni::Event OnStudyConstraintModified; */ extern Yuni::Event OnStudyNodalOptimizationChanged; +/*! +** \brief Event: The area use adequacy patch settings have been changed +*/ +extern Yuni::Event OnStudyAreaUseAdequacyPatchChanged; + /*! ** \brief Event: The simulation settings have been changed */ diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index d00f46bb66..ee7e690ddf 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -906,6 +906,19 @@ struct PAreaUnsuppliedEnergyCost } }; +struct PAreaAdequacyPatch +{ + typedef bool Type; + static Type Value(const Data::Area* area) + { + return area->bUseAdequacyPatch; + } + static wxString ConvertToString(const Type v) + { + return v ? wxT("True") : wxT("False"); + } +}; + template struct PAreaResortStatus { diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 4acdac5ae7..46ba937686 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -397,6 +397,9 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGAreaResort, new wxBoolProperty(wxT("other dispatch. power"), wxT("area.other_dispatch_power"), false)); + pPGAreaAdequacyPatchTitle = Category(pg, wxT("Adequacy Patch"), wxT("area.adequacy_patch_title")); + pPGAreaAUsedequacyPatch = page->Append(new wxBoolProperty(wxT("use adequacy patch"), wxT("area.use_adequacy_patch"), false)); + pPGAreaLocalization = Category(pg, wxT("Localization"), wxT("area.localization")); P_INT("x", "area.x"); P_INT("y", "area.y"); @@ -785,6 +788,9 @@ void Frame::apply(const InspectorData::Ptr& data) pPGAreaName->SetValueFromString(wxStringFromUTF8((*(data->areas.begin()))->name)); // Area color Accumulator::Apply(pPGAreaColor, data->areas); + // Adequacy patch + if (!multiple) + Accumulator::Apply(pPGAreaAUsedequacyPatch, data->areas); // Area position if (!multiple) { @@ -835,6 +841,7 @@ void Frame::apply(const InspectorData::Ptr& data) } pPGAreaOptimization->Hide(hide); pPGAreaResort->Hide(hide); + pPGAreaAdequacyPatchTitle->Hide(hide); pPGAreaLocalization->Hide(hide || multiple); pPGAreaDeps->Hide(hide); diff --git a/src/ui/simulator/windows/inspector/frame.h b/src/ui/simulator/windows/inspector/frame.h index 807dd7c73d..622575c42e 100644 --- a/src/ui/simulator/windows/inspector/frame.h +++ b/src/ui/simulator/windows/inspector/frame.h @@ -184,6 +184,8 @@ class Frame final : public Antares::Component::Panel, public Yuni::IEventObserve wxPGProperty* pPGUnsupplied; wxPGProperty* pPGSpilled; wxPGProperty* pPGAreaName; + wxPGProperty* pPGAreaAdequacyPatchTitle; + wxPGProperty* pPGAreaAUsedequacyPatch; wxPGProperty* pPGAreaColor; wxPGProperty* pPGAreaLinks; wxPGProperty* pPGAreaPlants; diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 434a1ec68d..00d1143bc8 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -172,6 +172,17 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, OnStudyNodalOptimizationChanged(); return true; } + if (name == "area.use_adequacy_patch") + { + auto* area = *i; + if (area) + { + area->bUseAdequacyPatch = value.GetBool(); + OnStudyAreaUseAdequacyPatchChanged(); + return true; + } + return false; + } if (name == "area.links_count") return false; if (name == "area.cluster_count") From 82bd7c7b9ccbc8bc53ae38abb150a83c2a613be4 Mon Sep 17 00:00:00 2001 From: "Hugo ANTOINE (RTEi)" Date: Thu, 27 Jan 2022 23:01:36 +0100 Subject: [PATCH 006/490] deleted boolean cast & clang-format on new files --- src/libs/antares/study/area/list.cpp | 18 +++++++++++------- src/libs/antares/study/cleaner/cleaner-v20.cpp | 12 +++++++++--- src/libs/antares/study/parameters.cpp | 8 +++++--- src/libs/antares/study/parameters.h | 2 +- .../options/optimization/optimization.cpp | 2 -- 5 files changed, 26 insertions(+), 16 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index b1bb9436ec..0123c81a99 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -203,7 +203,7 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << "optimization.ini"; ret = saveAreaOptimisationIniFile(area, buffer) and ret; - //Adequacy ini + // Adequacy ini buffer.clear() << folder << SEP << "input" << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; ret = saveAreaAdequacyPatchIniFile(area, buffer) and ret; @@ -315,9 +315,12 @@ bool saveAreaOptimisationIniFile(const Area& area, const Clob& buffer) IniFile ini; IniFile::Section* section = ini.addSection("nodal optimization"); - section->add("non-dispatchable-power", static_cast(area.nodalOptimization & anoNonDispatchPower)); - section->add("dispatchable-hydro-power", static_cast(area.nodalOptimization & anoDispatchHydroPower)); - section->add("other-dispatchable-power", static_cast(area.nodalOptimization & anoOtherDispatchPower)); + section->add("non-dispatchable-power", + static_cast(area.nodalOptimization & anoNonDispatchPower)); + section->add("dispatchable-hydro-power", + static_cast(area.nodalOptimization & anoDispatchHydroPower)); + section->add("other-dispatchable-power", + static_cast(area.nodalOptimization & anoOtherDispatchPower)); section->add("spread-unsupplied-energy-cost", area.spreadUnsuppliedEnergyCost); section->add("spread-spilled-energy-cost", area.spreadSpilledEnergyCost); @@ -332,8 +335,9 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) { IniFile ini; IniFile::Section* section = ini.addSection("adequacy-patch"); - bool bUseAdequacyPatch = false; //adq: this should be later replaced with area.bUseAdequacyPatch - section->add("use-adequacy-patch", static_cast(bUseAdequacyPatch)); + bool bUseAdequacyPatch = false; // adq: this should be later replaced with + // area.bUseAdequacyPatch + section->add("use-adequacy-patch", bUseAdequacyPatch)); return ini.save(buffer); } @@ -1531,7 +1535,7 @@ bool AreaList::renameArea(const AreaName& oldid, const AreaName& newid, const Ar assert(oldCount == a.links.size() and "We must have the same number of items in the list"); #endif }); - + area->buildLinksIndexes(); return true; diff --git a/src/libs/antares/study/cleaner/cleaner-v20.cpp b/src/libs/antares/study/cleaner/cleaner-v20.cpp index b57e00d3b1..c2f1988f84 100644 --- a/src/libs/antares/study/cleaner/cleaner-v20.cpp +++ b/src/libs/antares/study/cleaner/cleaner-v20.cpp @@ -215,14 +215,20 @@ static void PreflightVersion20_interco(PathList& p, const Area* area, StringT& b { auto& link = *(i->second); // Parameters - buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << link.with->id << "_parameters" << ".txt"; + buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << link.with->id + << "_parameters" + << ".txt"; p.add(buffer); // Indirect capacities - buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << "capacities" << SEP << link.with->id << "_direct" << ".txt"; + buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << "capacities" + << 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"; + buffer.clear() << "input" << SEP << "links" << SEP << link.from->id << SEP << "capacities" + << SEP << link.with->id << "_indirect" + << ".txt"; p.add(buffer); } } diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 3737cb50c4..ea1715c289 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -87,7 +87,8 @@ static bool ConvertCStrToListTimeSeries(const String& value, uint& v) return true; } -static bool ConvertStringToRenewableGenerationModelling(const AnyString& text, RenewableGenerationModelling & out) +static bool ConvertStringToRenewableGenerationModelling(const AnyString& text, + RenewableGenerationModelling& out) { CString<24, false> s = text; s.trim(); @@ -734,7 +735,8 @@ static bool SGDIntLoadFamily_OtherPreferences(Parameters& d, } // Renewable generation modelling if (key == "renewable-generation-modelling") - return ConvertStringToRenewableGenerationModelling(value, d.renewableGeneration.rgModelling); + return ConvertStringToRenewableGenerationModelling(value, + d.renewableGeneration.rgModelling); return false; } @@ -1705,7 +1707,7 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-primaryreserve", include.reserve.primary); section->add("include-exportmps", include.exportMPS); - section->add("include-adequacypatch", include.adequacyPatch); + section->add("include-adequacypatch", include.adequacyPatch); section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 7a2910667f..425202168c 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -146,7 +146,7 @@ class Parameters final /*! ** \brief Try to detect then fix refresh intervals - */ + */ void fixRefreshIntervals(); /*! diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index b8c4168ec8..effea6481a 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -323,7 +323,6 @@ Optimization::Optimization(wxWindow* parent) : pBtnAdequacyPatch = button; } - // Unfeasible problem behavior { label = Component::CreateLabel(this, wxT("Unfeasible problem behavior")); @@ -494,7 +493,6 @@ void Optimization::refresh() // Adequacy patch ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); - // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( Data::getIcon(study.parameters.include.unfeasibleProblemBehavior)); From b11bf5af41747317e579ec74d01dc9b853972db5 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 28 Jan 2022 08:33:35 +0800 Subject: [PATCH 007/490] clang format --- src/ui/simulator/windows/inspector/frame.cpp | 23 +++++++++++-------- .../windows/inspector/property.update.cpp | 3 ++- 2 files changed, 16 insertions(+), 10 deletions(-) diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 46ba937686..82147a3c62 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -397,8 +397,10 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGAreaResort, new wxBoolProperty(wxT("other dispatch. power"), wxT("area.other_dispatch_power"), false)); - pPGAreaAdequacyPatchTitle = Category(pg, wxT("Adequacy Patch"), wxT("area.adequacy_patch_title")); - pPGAreaAUsedequacyPatch = page->Append(new wxBoolProperty(wxT("use adequacy patch"), wxT("area.use_adequacy_patch"), false)); + pPGAreaAdequacyPatchTitle + = Category(pg, wxT("Adequacy Patch"), wxT("area.adequacy_patch_title")); + pPGAreaAUsedequacyPatch = page->Append( + new wxBoolProperty(wxT("use adequacy patch"), wxT("area.use_adequacy_patch"), false)); pPGAreaLocalization = Category(pg, wxT("Localization"), wxT("area.localization")); P_INT("x", "area.x"); @@ -534,12 +536,12 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGThClusterReliabilityModel = Category(pg, wxT("Timeseries generation"), wxT("cluster.reliabilitymodel")); pPGThClusterDoGenerateTS = P_ENUM("Generate timeseries", "cluster.gen-ts", localGenTS.data()) - pPGThClusterVolatilityForced = P_FLOAT("Volatility (forced)", "cluster.forcedVolatility"); + 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); - // --- RENEWABLE CLUSTERS --- pPGRnClusterSeparator = Group(pg, wxEmptyString, wxEmptyString); Group(pg, wxT("RENEWABLE CLUSTERS"), wxT("rn-cluster.title")); @@ -550,7 +552,7 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : for (uint i = 0; i != arrayRnClusterGroupCount; ++i) RnGroupChoices.Add(arrayRnClusterGroup[i], i); pPGRnClusterGroup = page->Append( - new wxEditEnumProperty(wxT("group"), wxT("rn-cluster.group"), RnGroupChoices, wxEmptyString)); + new wxEditEnumProperty(wxT("group"), wxT("rn-cluster.group"), RnGroupChoices, wxEmptyString)); pPGRnClusterArea = P_STRING("area", "rn-cluster.area"); pg->DisableProperty(pPGRnClusterArea); @@ -947,8 +949,10 @@ void Frame::apply(const InspectorData::Ptr& data) // CO2 Accumulator::Apply(pPGThClusterCO2, data->ThClusters); // Volatility - Accumulator::Apply(pPGThClusterVolatilityPlanned, data->ThClusters); - Accumulator::Apply(pPGThClusterVolatilityForced, data->ThClusters); + Accumulator::Apply(pPGThClusterVolatilityPlanned, + data->ThClusters); + Accumulator::Apply(pPGThClusterVolatilityForced, + data->ThClusters); // Laws Accumulator::Apply(pPGThClusterLawPlanned, data->ThClusters); Accumulator::Apply(pPGThClusterLawForced, data->ThClusters); @@ -968,7 +972,8 @@ void Frame::apply(const InspectorData::Ptr& data) AccumulatorCheck::ApplyTextColor(pPGThClusterMinStablePower, data->ThClusters); // check Min. Stable Power with thermal modulation - AccumulatorCheck::ApplyTextColor(pPGThClusterSpinning, data->ThClusters); + AccumulatorCheck::ApplyTextColor(pPGThClusterSpinning, + data->ThClusters); } pPGThClusterParams->Hide(hide); @@ -991,7 +996,7 @@ void Frame::apply(const InspectorData::Ptr& data) { p->SetLabel(wxT("RENEWABLE CLUSTER")); pPGRnClusterName->SetValueFromString( - wxStringFromUTF8((*(data->RnClusters.begin()))->name())); + wxStringFromUTF8((*(data->RnClusters.begin()))->name())); } else p->SetLabel(wxString() << data->RnClusters.size() << wxT(" RENEWABLE CLUSTERS")); diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 00d1143bc8..dcc9800e2b 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -937,7 +937,8 @@ bool InspectorGrid::onPropertyChanging_ThermalCluster(wxPGProperty*, { long index = value.GetLong(); - Data::LocalTSGenerationBehavior behavior = Data::LocalTSGenerationBehavior::useGlobalParameter; + Data::LocalTSGenerationBehavior behavior + = Data::LocalTSGenerationBehavior::useGlobalParameter; switch (index) { From 64210e3f5a935c18911cd8666b5222b0ef25f0d9 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 4 Feb 2022 18:43:04 +0800 Subject: [PATCH 008/490] adq patch mode --- src/libs/antares/study/area/area.cpp | 6 +-- src/libs/antares/study/area/area.h | 2 +- src/libs/antares/study/area/list.cpp | 38 +++++++++++++++++-- src/libs/antares/study/fwd.h | 15 ++++++++ .../windows/inspector/accumulator.hxx | 25 ++++++++++-- src/ui/simulator/windows/inspector/frame.cpp | 5 +-- src/ui/simulator/windows/inspector/frame.h | 2 +- .../windows/inspector/property.update.cpp | 15 +++++++- 8 files changed, 90 insertions(+), 18 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index 7fcf8ed8d7..39cfd511b2 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,7 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), - bUseAdequacyPatch(false), + adequacyPatchMode(Data::adqmNotUsed), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -71,7 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), - bUseAdequacyPatch(false), + adequacyPatchMode(Data::adqmNotUsed), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -91,7 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), - bUseAdequacyPatch(false), + adequacyPatchMode(Data::adqmNotUsed), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 804b663c8a..117d8c6162 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -226,7 +226,7 @@ class Area final : private Yuni::NonCopyable //! Enabled bool enabled; //! Use adequacy patch for this area - bool bUseAdequacyPatch; + Data::AdequacyPatchMode adequacyPatchMode; /*@}*/ //! \name Associate data */ diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index d0fdf05877..9e25f4ee3a 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -335,7 +335,23 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) { IniFile ini; IniFile::Section* section = ini.addSection("adequacy-patch"); - section->add("use-adequacy-patch", area.bUseAdequacyPatch); + int value; + switch(area.adequacyPatchMode) + { + case Data::adqmNotUsed: + value = 0; + break; + case Data::adqmUsedAsPhysicalArea: + value = 1; + break; + case Data::adqmUsedAsVirtualArea: + value = 2; + break; + default: + value = 0; + break; + } + section->add("adequacy-patch-mode", value); return ini.save(buffer); } @@ -1064,13 +1080,27 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, auto* section = ini.find("adequacy-patch"); 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 == "use-adequacy-patch") + if (tmp == "adequacy-patch-mode") { - area.bUseAdequacyPatch = value; + auto value = p->value.to(); + switch(value) + { + case 0: + area.adequacyPatchMode = Data::adqmNotUsed; + break; + case 1: + area.adequacyPatchMode = Data::adqmUsedAsPhysicalArea; + break; + case 2: + area.adequacyPatchMode = Data::adqmUsedAsVirtualArea; + break; + default: + area.adequacyPatchMode = Data::adqmNotUsed; + break; + } continue; } } diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 4370c6da2e..0aded4a908 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -116,6 +116,21 @@ enum StudyMode }; // enum StudyMode + +/*! +** \brief Types of Adequacy patch mode +*/ +enum AdequacyPatchMode +{ + //! Area out of the adq-patch (area does not use adq-patch) + adqmNotUsed = 0, + //! Physical Area in the adq-patch (physical area use adq-patch) + adqmUsedAsPhysicalArea, + //! Virtual Area in the adq-patch (virtual area use adq-patch) + adqmUsedAsVirtualArea + +}; // enum AdequacyPatchMode + /* ** \brief Simplex optimizations */ diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index ee7e690ddf..fabf6fedf6 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -322,6 +322,12 @@ static const wxChar* studyMode[] = {wxT("Economy"), #endif nullptr}; + +static const wxChar* adequacyPatchMode[] = {wxT("Not used"), + wxT("Physical area"), + wxT("Virtual area"), + nullptr}; + struct Unique { template @@ -906,19 +912,30 @@ struct PAreaUnsuppliedEnergyCost } }; -struct PAreaAdequacyPatch + +struct PAdequacyPatchMode { - typedef bool Type; + typedef Data::AdequacyPatchMode Type; static Type Value(const Data::Area* area) { - return area->bUseAdequacyPatch; + return area->adequacyPatchMode; } static wxString ConvertToString(const Type v) { - return v ? wxT("True") : wxT("False"); + switch (v) + { + case Data::adqmNotUsed: + return wxT("Not used"); + case Data::adqmUsedAsPhysicalArea: + return wxT("Physical area"); + case Data::adqmUsedAsVirtualArea: + return wxT("Virtual area"); + } + return wxEmptyString; } }; + template struct PAreaResortStatus { diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 82147a3c62..1a29cafa95 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -399,8 +399,7 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGAreaAdequacyPatchTitle = Category(pg, wxT("Adequacy Patch"), wxT("area.adequacy_patch_title")); - pPGAreaAUsedequacyPatch = page->Append( - new wxBoolProperty(wxT("use adequacy patch"), wxT("area.use_adequacy_patch"), false)); + pPGAreaAdequacyPatchMode = page->Append(new wxEnumProperty(wxT("adequacy patch mode"), wxT("area.adequacy_patch_mode"), adequacyPatchMode)); pPGAreaLocalization = Category(pg, wxT("Localization"), wxT("area.localization")); P_INT("x", "area.x"); @@ -792,7 +791,7 @@ void Frame::apply(const InspectorData::Ptr& data) Accumulator::Apply(pPGAreaColor, data->areas); // Adequacy patch if (!multiple) - Accumulator::Apply(pPGAreaAUsedequacyPatch, data->areas); + Accumulator::Apply(pPGAreaAdequacyPatchMode, data->areas); // Area position if (!multiple) { diff --git a/src/ui/simulator/windows/inspector/frame.h b/src/ui/simulator/windows/inspector/frame.h index 622575c42e..6f2e1b6275 100644 --- a/src/ui/simulator/windows/inspector/frame.h +++ b/src/ui/simulator/windows/inspector/frame.h @@ -185,7 +185,7 @@ class Frame final : public Antares::Component::Panel, public Yuni::IEventObserve wxPGProperty* pPGSpilled; wxPGProperty* pPGAreaName; wxPGProperty* pPGAreaAdequacyPatchTitle; - wxPGProperty* pPGAreaAUsedequacyPatch; + wxPGProperty* pPGAreaAdequacyPatchMode; wxPGProperty* pPGAreaColor; wxPGProperty* pPGAreaLinks; wxPGProperty* pPGAreaPlants; diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index dcc9800e2b..8ebe278626 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -172,12 +172,23 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, OnStudyNodalOptimizationChanged(); return true; } - if (name == "area.use_adequacy_patch") + if (name == "area.adequacy_patch_mode") { auto* area = *i; if (area) { - area->bUseAdequacyPatch = value.GetBool(); + String s; + wxStringToString(value.GetString(), s); + s.toLower(); + s.trim(); + + if (s == "not used" || s == "0") + area->adequacyPatchMode = Data::adqmNotUsed; + else if (s == "physical area" || s == "1") + area->adequacyPatchMode = Data::adqmUsedAsPhysicalArea; + else if (s == "virtual area" || s == "2") + area->adequacyPatchMode = Data::adqmUsedAsVirtualArea; + OnStudyAreaUseAdequacyPatchChanged(); return true; } From a047df94f7ba00c5404b6caaef49743f7babd5f7 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 4 Feb 2022 18:48:55 +0800 Subject: [PATCH 009/490] clang format --- src/libs/antares/study/area/list.cpp | 20 +++++++++---------- src/libs/antares/study/fwd.h | 7 +++---- .../windows/inspector/accumulator.hxx | 9 ++------- src/ui/simulator/windows/inspector/frame.cpp | 3 ++- 4 files changed, 17 insertions(+), 22 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 9e25f4ee3a..cab0a45841 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -336,18 +336,18 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) IniFile ini; IniFile::Section* section = ini.addSection("adequacy-patch"); int value; - switch(area.adequacyPatchMode) + switch (area.adequacyPatchMode) { - case Data::adqmNotUsed: + case Data::adqmNotUsed: value = 0; break; - case Data::adqmUsedAsPhysicalArea: + case Data::adqmUsedAsPhysicalArea: value = 1; break; - case Data::adqmUsedAsVirtualArea: + case Data::adqmUsedAsVirtualArea: value = 2; break; - default: + default: value = 0; break; } @@ -1086,18 +1086,18 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, if (tmp == "adequacy-patch-mode") { auto value = p->value.to(); - switch(value) + switch (value) { - case 0: + case 0: area.adequacyPatchMode = Data::adqmNotUsed; break; - case 1: + case 1: area.adequacyPatchMode = Data::adqmUsedAsPhysicalArea; break; - case 2: + case 2: area.adequacyPatchMode = Data::adqmUsedAsVirtualArea; break; - default: + default: area.adequacyPatchMode = Data::adqmNotUsed; break; } diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 0aded4a908..6cfdc45f20 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -116,7 +116,6 @@ enum StudyMode }; // enum StudyMode - /*! ** \brief Types of Adequacy patch mode */ @@ -519,12 +518,12 @@ const char* NumberOfCoresModeToCString(NumberOfCoresMode ncores); NumberOfCoresMode StringToNumberOfCoresMode(const AnyString& text); /* -* Renewable generation modelling -*/ + * Renewable generation modelling + */ enum RenewableGenerationModelling { rgAggregated = 0, // Default - rgClusters, // Using renewable clusters + rgClusters, // Using renewable clusters rgUnknown, }; diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index fabf6fedf6..7b631d49f4 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -322,11 +322,8 @@ static const wxChar* studyMode[] = {wxT("Economy"), #endif nullptr}; - -static const wxChar* adequacyPatchMode[] = {wxT("Not used"), - wxT("Physical area"), - wxT("Virtual area"), - nullptr}; +static const wxChar* adequacyPatchMode[] + = {wxT("Not used"), wxT("Physical area"), wxT("Virtual area"), nullptr}; struct Unique { @@ -912,7 +909,6 @@ struct PAreaUnsuppliedEnergyCost } }; - struct PAdequacyPatchMode { typedef Data::AdequacyPatchMode Type; @@ -935,7 +931,6 @@ struct PAdequacyPatchMode } }; - template struct PAreaResortStatus { diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 1a29cafa95..42a95a9acb 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -399,7 +399,8 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGAreaAdequacyPatchTitle = Category(pg, wxT("Adequacy Patch"), wxT("area.adequacy_patch_title")); - pPGAreaAdequacyPatchMode = page->Append(new wxEnumProperty(wxT("adequacy patch mode"), wxT("area.adequacy_patch_mode"), adequacyPatchMode)); + pPGAreaAdequacyPatchMode = page->Append(new wxEnumProperty( + wxT("adequacy patch mode"), wxT("area.adequacy_patch_mode"), adequacyPatchMode)); pPGAreaLocalization = Category(pg, wxT("Localization"), wxT("area.localization")); P_INT("x", "area.x"); From a7c1711b0e03668cb524bfaea69f0126d52a04f3 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 4 Feb 2022 16:38:23 +0100 Subject: [PATCH 010/490] added new header file for DENS --- .../economy/domesticUnsupliedEnergy.h | 289 ++++++++++++++++++ 1 file changed, 289 insertions(+) create mode 100644 src/solver/variable/economy/domesticUnsupliedEnergy.h diff --git a/src/solver/variable/economy/domesticUnsupliedEnergy.h b/src/solver/variable/economy/domesticUnsupliedEnergy.h new file mode 100644 index 0000000000..2f5bd0fe5a --- /dev/null +++ b/src/solver/variable/economy/domesticUnsupliedEnergy.h @@ -0,0 +1,289 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 const char* Caption() + { + return "UNSP. ENRG"; + } + //! Unit + static const char* Unit() + { + return "MWh"; + } + //! The short description of the variable + static const char* 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); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + // Next variable + 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(); + 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__ From 31a1f9d607e76f6246169ad8f6fbe79c2cd056cf Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 4 Feb 2022 18:08:31 +0100 Subject: [PATCH 011/490] changes to the filles --- src/solver/cmake/variable.cmake | 1 + src/solver/variable/adequacy/all.h | 4 +++ src/solver/variable/economy/all.h | 4 +++ .../economy/domesticUnsupliedEnergy.h | 26 +++++++++---------- 4 files changed, 22 insertions(+), 13 deletions(-) diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 953de4178e..d20642a835 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -129,6 +129,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/waterValue.h variable/economy/hydroCost.h variable/economy/unsupliedEnergy.h + variable/economy/domesticUnsupliedEnergy.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/variable/adequacy/all.h b/src/solver/variable/adequacy/all.h index b5dc154cff..5d5eca7345 100644 --- a/src/solver/variable/adequacy/all.h +++ b/src/solver/variable/adequacy/all.h @@ -57,6 +57,7 @@ #include "../economy/waterValue.h" #include "../economy/hydroCost.h" #include "../economy/unsupliedEnergy.h" +#include "../economy/domesticUnsupliedEnergy.h" #include "../adequacy/spilledEnergy.h" #include "../economy/productionByDispatchablePlant.h" #include "../economy/productionByRenewablePlant.h" @@ -135,6 +136,7 @@ typedef // Prices -class UnsupliedEnergy - : public Variable::IVariable, NextT, VCardUnsupliedEnergy> +class DomesticUnsupliedEnergy + : public Variable::IVariable, NextT, VCardDomesticUnsupliedEnergy> { public: //! Type of the next static variable typedef NextT NextType; //! VCard - typedef VCardUnsupliedEnergy VCardType; + typedef VCardDomesticUnsupliedEnergy VCardType; //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; + typedef Variable::IVariable, NextT, VCardType> AncestorType; //! List of expected results typedef typename VCardType::ResultsType ResultsType; @@ -138,7 +138,7 @@ class UnsupliedEnergy }; public: - ~UnsupliedEnergy() + ~DomesticUnsupliedEnergy() { delete[] pValuesForTheCurrentYear; } @@ -279,11 +279,11 @@ class UnsupliedEnergy typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; unsigned int pNbYearsParallel; -}; // class UnsupliedEnergy +}; // class DomesticUnsupliedEnergy } // namespace Economy } // namespace Variable } // namespace Solver } // namespace Antares -#endif // __SOLVER_VARIABLE_ECONOMY_UnsupliedEnergy_H__ +#endif // __SOLVER_VARIABLE_ECONOMY_DomesticUnsupliedEnergy_H__ From d959d03b4a7d5cedd066f1ce0f3188cc37984b13 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 7 Feb 2022 18:51:44 +0800 Subject: [PATCH 012/490] syntax error --- src/solver/variable/adequacy/all.h | 4 ++-- src/solver/variable/economy/all.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/solver/variable/adequacy/all.h b/src/solver/variable/adequacy/all.h index 5d5eca7345..2173a3bb91 100644 --- a/src/solver/variable/adequacy/all.h +++ b/src/solver/variable/adequacy/all.h @@ -145,7 +145,7 @@ typedef // Prices Variable::Economy::Marge // OP. MRG // Links >>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -217,7 +217,7 @@ typedef // Prices Variable::Economy::DispatchableGenMargin, Common::SpatialAggregate< Variable::Economy:: - Marge>>>>>>>>>>>>>>>>>>>>>>>>>>>> + Marge>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 5b60bf2a0d..ad1d0c8939 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -161,7 +161,7 @@ typedef // Prices // MBO 25/02/2016 - refs: #55 // Links >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -241,7 +241,7 @@ typedef // Prices Common::SpatialAggregate< NbOfDispatchedUnits // MBO 25/02/2016 - // refs: #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< From 349aec6247fce69d98c313214652210119fa4374 Mon Sep 17 00:00:00 2001 From: milos Date: Mon, 7 Feb 2022 15:12:39 +0100 Subject: [PATCH 013/490] bring back original all.h for adequacy --- src/solver/variable/adequacy/all.h | 8 ++------ 1 file changed, 2 insertions(+), 6 deletions(-) diff --git a/src/solver/variable/adequacy/all.h b/src/solver/variable/adequacy/all.h index 2173a3bb91..b5dc154cff 100644 --- a/src/solver/variable/adequacy/all.h +++ b/src/solver/variable/adequacy/all.h @@ -57,7 +57,6 @@ #include "../economy/waterValue.h" #include "../economy/hydroCost.h" #include "../economy/unsupliedEnergy.h" -#include "../economy/domesticUnsupliedEnergy.h" #include "../adequacy/spilledEnergy.h" #include "../economy/productionByDispatchablePlant.h" #include "../economy/productionByRenewablePlant.h" @@ -136,7 +135,6 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -201,8 +199,6 @@ typedef // Prices Variable::Economy::HydroCost, Common::SpatialAggregate< Variable::Economy::UnsupliedEnergy, - Common::SpatialAggregate< - Variable::Economy::DomesticUnsupliedEnergy, Common::SpatialAggregate< Variable::Adequacy::SpilledEnergy, // LOLD @@ -217,7 +213,7 @@ typedef // Prices Variable::Economy::DispatchableGenMargin, Common::SpatialAggregate< Variable::Economy:: - Marge>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + Marge>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< From 8a7ecd1c7385d81d25ce12eb3e74699ee35ed66a Mon Sep 17 00:00:00 2001 From: milos Date: Mon, 7 Feb 2022 15:13:03 +0100 Subject: [PATCH 014/490] clang format --- src/solver/variable/economy/all.h | 70 +++++++++---------- .../economy/domesticUnsupliedEnergy.h | 2 +- 2 files changed, 36 insertions(+), 36 deletions(-) diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index ad1d0c8939..1f0e43b007 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -145,23 +145,23 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -216,32 +216,32 @@ typedef // Prices Common::SpatialAggregate< UnsupliedEnergy, Common::SpatialAggregate< - DomesticUnsupliedEnergy, - Common::SpatialAggregate< - SpilledEnergy, - // LOLD + DomesticUnsupliedEnergy, Common::SpatialAggregate< - LOLD, + SpilledEnergy, + // LOLD Common::SpatialAggregate< - LOLP, - + LOLD, Common::SpatialAggregate< - AvailableDispatchGen, + LOLP, + Common::SpatialAggregate< - DispatchableGenMargin, + AvailableDispatchGen, Common::SpatialAggregate< - Marge, - - // Detail Prices + DispatchableGenMargin, Common::SpatialAggregate< - NonProportionalCost, // MBO 13/05/2014 - - // refs: #21 + Marge, - // Number Of Dispatched Units + // Detail Prices Common::SpatialAggregate< - NbOfDispatchedUnits // MBO 25/02/2016 - - // refs: #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + NonProportionalCost, // MBO 13/05/2014 - + // refs: #21 + + // Number Of Dispatched Units + Common::SpatialAggregate< + NbOfDispatchedUnits // MBO 25/02/2016 + // - refs: #55 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< diff --git a/src/solver/variable/economy/domesticUnsupliedEnergy.h b/src/solver/variable/economy/domesticUnsupliedEnergy.h index c36ed13d90..f13e938801 100644 --- a/src/solver/variable/economy/domesticUnsupliedEnergy.h +++ b/src/solver/variable/economy/domesticUnsupliedEnergy.h @@ -64,7 +64,7 @@ struct VCardDomesticUnsupliedEnergy ResultsType; //! The VCard to look for for calculating spatial aggregates - typedef VCardDomesticUnsupliedEnergy VCardForSpatialAggregate; + typedef VCardDomesticUnsupliedEnergy VCardForSpatialAggregate; enum { From c4237ab77d9f5b5d8a132dd7a71aa06ab40b46d6 Mon Sep 17 00:00:00 2001 From: milos Date: Mon, 7 Feb 2022 17:07:07 +0100 Subject: [PATCH 015/490] assigning dummy values to DENS --- src/solver/variable/economy/domesticUnsupliedEnergy.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/solver/variable/economy/domesticUnsupliedEnergy.h b/src/solver/variable/economy/domesticUnsupliedEnergy.h index f13e938801..131998b88c 100644 --- a/src/solver/variable/economy/domesticUnsupliedEnergy.h +++ b/src/solver/variable/economy/domesticUnsupliedEnergy.h @@ -98,7 +98,7 @@ struct VCardDomesticUnsupliedEnergy }; // class VCard /*! -** \brief C02 Average value of the overrall UnsupliedEnergy emissions expected from all +** \brief C02 Average value of the overrall DomesticUnsupliedEnergy emissions expected from all ** the thermal dispatchable clusters */ template @@ -235,10 +235,10 @@ class DomesticUnsupliedEnergy void hourForEachArea(State& state, unsigned int numSpace) { - // Total UnsupliedEnergy emissions - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = - // Current Hydro Storage generation - state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; + // Total DomesticUnsupliedEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = 123; // Connect to DENS values in the similar manner like below + // state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; // Next variable NextType::hourForEachArea(state, numSpace); From 3bacd69b8c17ca4886c5f916e375489b3f7b74da Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 10 Feb 2022 10:04:06 +0800 Subject: [PATCH 016/490] minor name change --- src/libs/antares/study/area/area.cpp | 6 +++--- src/libs/antares/study/area/list.cpp | 14 +++++++------- src/libs/antares/study/fwd.h | 12 ++++++------ src/ui/simulator/windows/inspector/accumulator.hxx | 14 +++++++------- .../windows/inspector/property.update.cpp | 12 ++++++------ 5 files changed, 29 insertions(+), 29 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index 39cfd511b2..3aaeada626 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,7 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), - adequacyPatchMode(Data::adqmNotUsed), + adequacyPatchMode(Data::adqmVirtualArea), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -71,7 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), - adequacyPatchMode(Data::adqmNotUsed), + adequacyPatchMode(Data::adqmVirtualArea), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -91,7 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), - adequacyPatchMode(Data::adqmNotUsed), + adequacyPatchMode(Data::adqmVirtualArea), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index cab0a45841..802ee9ecf1 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -338,13 +338,13 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) int value; switch (area.adequacyPatchMode) { - case Data::adqmNotUsed: + case Data::adqmVirtualArea: value = 0; break; - case Data::adqmUsedAsPhysicalArea: + case Data::adqmPhysicalAreaOutsideAdqPatch: value = 1; break; - case Data::adqmUsedAsVirtualArea: + case Data::adqmPhysicalAreaInsideAdqPatch: value = 2; break; default: @@ -1089,16 +1089,16 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, switch (value) { case 0: - area.adequacyPatchMode = Data::adqmNotUsed; + area.adequacyPatchMode = Data::adqmVirtualArea; break; case 1: - area.adequacyPatchMode = Data::adqmUsedAsPhysicalArea; + area.adequacyPatchMode = Data::adqmPhysicalAreaOutsideAdqPatch; break; case 2: - area.adequacyPatchMode = Data::adqmUsedAsVirtualArea; + area.adequacyPatchMode = Data::adqmPhysicalAreaInsideAdqPatch; break; default: - area.adequacyPatchMode = Data::adqmNotUsed; + area.adequacyPatchMode = Data::adqmVirtualArea; break; } continue; diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 6cfdc45f20..b4485eaab1 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -121,12 +121,12 @@ enum StudyMode */ enum AdequacyPatchMode { - //! Area out of the adq-patch (area does not use adq-patch) - adqmNotUsed = 0, - //! Physical Area in the adq-patch (physical area use adq-patch) - adqmUsedAsPhysicalArea, - //! Virtual Area in the adq-patch (virtual area use adq-patch) - adqmUsedAsVirtualArea + //! Virtual area in adq patch + adqmVirtualArea = 0, + //! Physical Area outside the adq-patch + adqmPhysicalAreaOutsideAdqPatch, + //! Physical Area inside the adq-patch + adqmPhysicalAreaInsideAdqPatch }; // enum AdequacyPatchMode diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index 7b631d49f4..1e6bb88f3f 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -323,7 +323,7 @@ static const wxChar* studyMode[] = {wxT("Economy"), nullptr}; static const wxChar* adequacyPatchMode[] - = {wxT("Not used"), wxT("Physical area"), wxT("Virtual area"), nullptr}; + = {wxT("virtual area"), wxT("physical area outside patch"), wxT("physical area inside patch"), nullptr}; struct Unique { @@ -920,12 +920,12 @@ struct PAdequacyPatchMode { switch (v) { - case Data::adqmNotUsed: - return wxT("Not used"); - case Data::adqmUsedAsPhysicalArea: - return wxT("Physical area"); - case Data::adqmUsedAsVirtualArea: - return wxT("Virtual area"); + case Data::adqmVirtualArea: + return wxT("virtual area"); + case Data::adqmPhysicalAreaOutsideAdqPatch: + return wxT("physical area outside patch"); + case Data::adqmPhysicalAreaInsideAdqPatch: + return wxT("physical area inside patch"); } return wxEmptyString; } diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 8ebe278626..08128dc5a1 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -182,12 +182,12 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, s.toLower(); s.trim(); - if (s == "not used" || s == "0") - area->adequacyPatchMode = Data::adqmNotUsed; - else if (s == "physical area" || s == "1") - area->adequacyPatchMode = Data::adqmUsedAsPhysicalArea; - else if (s == "virtual area" || s == "2") - area->adequacyPatchMode = Data::adqmUsedAsVirtualArea; + if (s == "virtual area" || s == "0") + area->adequacyPatchMode = Data::adqmVirtualArea; + else if (s == "physical area outside patch" || s == "1") + area->adequacyPatchMode = Data::adqmPhysicalAreaOutsideAdqPatch; + else if (s == "physical area inside patch" || s == "2") + area->adequacyPatchMode = Data::adqmPhysicalAreaInsideAdqPatch; OnStudyAreaUseAdequacyPatchChanged(); return true; From 9cbeab81d5874ddd73a385f44c8c61c8849b461a Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 11 Feb 2022 09:45:10 +0800 Subject: [PATCH 017/490] default value 1 --- src/libs/antares/study/area/area.cpp | 6 +++--- src/libs/antares/study/area/list.cpp | 4 ++-- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index 3aaeada626..f9d60e3d50 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,7 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), - adequacyPatchMode(Data::adqmVirtualArea), + adequacyPatchMode(Data::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -71,7 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), - adequacyPatchMode(Data::adqmVirtualArea), + adequacyPatchMode(Data::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -91,7 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), - adequacyPatchMode(Data::adqmVirtualArea), + adequacyPatchMode(Data::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 802ee9ecf1..546d452295 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -348,7 +348,7 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) value = 2; break; default: - value = 0; + value = 1; //default adqmPhysicalAreaOutsideAdqPatch break; } section->add("adequacy-patch-mode", value); @@ -1098,7 +1098,7 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, area.adequacyPatchMode = Data::adqmPhysicalAreaInsideAdqPatch; break; default: - area.adequacyPatchMode = Data::adqmVirtualArea; + area.adequacyPatchMode = Data::adqmPhysicalAreaOutsideAdqPatch; break; } continue; From da8eca91c95f89b949e8f59ed4ccc593b3d0aa2e Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 11 Feb 2022 13:15:07 +0800 Subject: [PATCH 018/490] typo --- src/solver/cmake/variable.cmake | 2 +- src/solver/variable/economy/all.h | 6 ++--- ...iedEnergy.h => domesticUnsuppliedEnergy.h} | 26 +++++++++---------- 3 files changed, 17 insertions(+), 17 deletions(-) rename src/solver/variable/economy/{domesticUnsupliedEnergy.h => domesticUnsuppliedEnergy.h} (91%) diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index d20642a835..84197f5502 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -129,7 +129,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/waterValue.h variable/economy/hydroCost.h variable/economy/unsupliedEnergy.h - variable/economy/domesticUnsupliedEnergy.h + variable/economy/domesticUnsuppliedEnergy.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 1f0e43b007..526624a4bb 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -59,7 +59,7 @@ #include "waterValue.h" #include "hydroCost.h" #include "unsupliedEnergy.h" -#include "domesticUnsupliedEnergy.h" +#include "domesticUnsuppliedEnergy.h" #include "spilledEnergy.h" #include "lold.h" @@ -145,7 +145,7 @@ typedef // Prices -class DomesticUnsupliedEnergy - : public Variable::IVariable, NextT, VCardDomesticUnsupliedEnergy> +class DomesticUnsuppliedEnergy + : public Variable::IVariable, NextT, VCardDomesticUnsuppliedEnergy> { public: //! Type of the next static variable typedef NextT NextType; //! VCard - typedef VCardDomesticUnsupliedEnergy VCardType; + typedef VCardDomesticUnsuppliedEnergy VCardType; //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; + typedef Variable::IVariable, NextT, VCardType> AncestorType; //! List of expected results typedef typename VCardType::ResultsType ResultsType; @@ -138,7 +138,7 @@ class DomesticUnsupliedEnergy }; public: - ~DomesticUnsupliedEnergy() + ~DomesticUnsuppliedEnergy() { delete[] pValuesForTheCurrentYear; } @@ -235,7 +235,7 @@ class DomesticUnsupliedEnergy void hourForEachArea(State& state, unsigned int numSpace) { - // Total DomesticUnsupliedEnergy emissions + // Total DomesticUnsuppliedEnergy emissions pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 123; // Connect to DENS values in the similar manner like below // state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; @@ -279,11 +279,11 @@ class DomesticUnsupliedEnergy typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; unsigned int pNbYearsParallel; -}; // class DomesticUnsupliedEnergy +}; // class DomesticUnsuppliedEnergy } // namespace Economy } // namespace Variable } // namespace Solver } // namespace Antares -#endif // __SOLVER_VARIABLE_ECONOMY_DomesticUnsupliedEnergy_H__ +#endif // __SOLVER_VARIABLE_ECONOMY_DomesticUnsuppliedEnergy_H__ From 238aa5ee4a1fd32d41d61fcf61409886dab0f739 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 11 Feb 2022 11:20:38 +0100 Subject: [PATCH 019/490] column name change and typo --- src/solver/variable/economy/all.h | 2 +- src/solver/variable/economy/domesticUnsuppliedEnergy.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 526624a4bb..e3fc2fc401 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -145,7 +145,7 @@ typedef // Prices Date: Fri, 11 Feb 2022 11:40:57 +0100 Subject: [PATCH 020/490] change dens dummy value to zero --- src/solver/variable/economy/domesticUnsuppliedEnergy.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/variable/economy/domesticUnsuppliedEnergy.h b/src/solver/variable/economy/domesticUnsuppliedEnergy.h index af009159e2..9877a4a818 100644 --- a/src/solver/variable/economy/domesticUnsuppliedEnergy.h +++ b/src/solver/variable/economy/domesticUnsuppliedEnergy.h @@ -237,7 +237,7 @@ class DomesticUnsuppliedEnergy { // Total DomesticUnsuppliedEnergy emissions pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = 123; // Connect to DENS values in the similar manner like below + = 0; // Connect to DENS values in the similar manner like below // state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; // Next variable From 48d8d04e5301576840c12dd9d38105bfe18d270d Mon Sep 17 00:00:00 2001 From: hugo-antoine-rtei <73881097+hugo-antoine-rtei@users.noreply.github.com> Date: Thu, 3 Mar 2022 03:20:18 +0100 Subject: [PATCH 021/490] Adequacy patch: 2 rounds run / boundary update / output (#10) * created AdequacyFirstStep attribute * reference fix * save DENS value from 1st run * add ::SIM_RenseignementProblemeHebdo before 2nd run * save DENS in result and show in UI * refacto minor * solution for upperbound update (#11) * draft solution for upperbound update * refacto * minor refacto * clean * clean * DENS only for type 2 area * review modif Co-authored-by: rtei-pw Co-authored-by: rtei-pw <92968374+rtei-pw@users.noreply.github.com> --- .../opt_gestion_des_bornes_cas_lineaire.cpp | 9 +++++ src/solver/simulation/economy.cpp | 33 ++++++++++++++++++- .../simulation/sim_alloc_probleme_hebdo.cpp | 5 +++ .../simulation/sim_calcul_economique.cpp | 4 +++ .../sim_structure_probleme_economique.h | 7 +++- .../economy/domesticUnsuppliedEnergy.h | 3 +- 6 files changed, 57 insertions(+), 4 deletions(-) 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 aa0eb810b4..cefdce58b8 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -401,9 +401,18 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob else Xmax[Var] = 0.; + // adq patch: update ENS <= DENS in 2nd run + if (ProblemeHebdo->UseAdequacyPatch == true + && ProblemeHebdo->AdequacyFirstStep == false) + if (ProblemeHebdo->AreaAdequacyPatchMode[Pays] + == Data::adqmPhysicalAreaInsideAdqPatch) + Xmax[Var] + = ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]; + ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo] = 0.0; + AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo]); AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 12d12a2e79..82381f5914 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -146,7 +146,38 @@ bool Economy::year(Progression::Task& progression, try { - OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + if (pProblemesHebdo[numSpace]->UseAdequacyPatch) + { + pProblemesHebdo[numSpace]->AdequacyFirstStep = true; + OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + pProblemesHebdo[numSpace]->AdequacyFirstStep = false; + + for (int pays = 0; pays < pProblemesHebdo[numSpace]->NombreDePays; ++pays) + { + if (pProblemesHebdo[numSpace]->AreaAdequacyPatchMode[pays] + == Data::adqmPhysicalAreaInsideAdqPatch) + memcpy( + pProblemesHebdo[numSpace]->ResultatsHoraires[pays]->ValeursHorairesDENS, + pProblemesHebdo[numSpace] + ->ResultatsHoraires[pays] + ->ValeursHorairesDeDefaillancePositive, + pProblemesHebdo[numSpace]->NombreDePasDeTemps * sizeof(double)); + else + memset( + pProblemesHebdo[numSpace]->ResultatsHoraires[pays]->ValeursHorairesDENS, + 0, + pProblemesHebdo[numSpace]->NombreDePasDeTemps * sizeof(double)); + } + + ::SIM_RenseignementProblemeHebdo( + *pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); // todo ? correct + OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + } + else + { + OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + } + DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index 275036eabe..8ddd747dbc 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -59,6 +59,7 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps problem.BruitSurCoutHydraulique[p] = (double*)MemAlloc(8784 * sizeof(double)); problem.NomsDesPays = (const char**)MemAlloc(nbPays * sizeof(char*)); + problem.AreaAdequacyPatchMode = (int*)MemAlloc(nbPays * sizeof(int)); problem.PaysExtremiteDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); problem.PaysOrigineDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); @@ -460,6 +461,8 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); + problem.ResultatsHoraires[k]->ValeursHorairesDENS + = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown @@ -588,6 +591,7 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) uint nbPays = study.areas.size(); MemFree(problem.NomsDesPays); + MemFree(problem.AreaAdequacyPatchMode); MemFree(problem.PaysExtremiteDeLInterconnexion); MemFree(problem.PaysOrigineDeLInterconnexion); @@ -845,6 +849,7 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.PaliersThermiquesDuPays[k]->PuissanceDisponibleEtCout); MemFree(problem.PaliersThermiquesDuPays[k]); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 44130ce2bb..95f55b772c 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -63,6 +63,9 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.hydroHotStart = (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart); + problem.UseAdequacyPatch = parameters.include.adequacyPatch; + problem.AdequacyFirstStep = parameters.include.adequacyPatch; + problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP) ? OUI_ANTARES @@ -111,6 +114,7 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, auto& area = *(study.areas[i]); problem.NomsDesPays[i] = area.id.c_str(); + problem.AreaAdequacyPatchMode[i] = area.adequacyPatchMode; problem.CoutDeDefaillancePositive[i] = area.thermal.unsuppliedEnergyCost; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 87cfa5b4b6..3b76e2c9be 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -423,6 +423,7 @@ typedef struct typedef struct { double* ValeursHorairesDeDefaillancePositive; + double* ValeursHorairesDENS; // adq patch DENS double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; @@ -478,6 +479,7 @@ struct PROBLEME_HEBDO char OptimisationAvecCoutsDeDemarrage; int NombreDePays; const char** NomsDesPays; + int* AreaAdequacyPatchMode; int NombreDePaliersThermiques; int NombreDInterconnexions; @@ -572,6 +574,10 @@ struct PROBLEME_HEBDO double* previousYearFinalLevels; ALL_MUST_RUN_GENERATION** AllMustRunGeneration; + /* Adequacy Patch */ + bool UseAdequacyPatch; + bool AdequacyFirstStep; + optimizationStatistics optimizationStatistics_object; /* Hydro management */ double* CoefficientEcretementPMaxHydraulique; @@ -587,7 +593,6 @@ struct PROBLEME_HEBDO double* coutOptimalSolution2; COUTS_MARGINAUX_ZONES_DE_RESERVE** CoutsMarginauxDesContraintesDeReserveParZone; - /* Unused for now, will be used in future revisions */ #if 0 char SecondeOptimisationRelaxee; diff --git a/src/solver/variable/economy/domesticUnsuppliedEnergy.h b/src/solver/variable/economy/domesticUnsuppliedEnergy.h index 9877a4a818..8e8ee55cfe 100644 --- a/src/solver/variable/economy/domesticUnsuppliedEnergy.h +++ b/src/solver/variable/economy/domesticUnsuppliedEnergy.h @@ -237,8 +237,7 @@ class DomesticUnsuppliedEnergy { // Total DomesticUnsuppliedEnergy emissions pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = 0; // Connect to DENS values in the similar manner like below - // state.hourlyResults->ValeursHorairesDeDefaillancePositive[state.hourInTheWeek]; + = state.hourlyResults->ValeursHorairesDENS[state.hourInTheWeek]; // Next variable NextType::hourForEachArea(state, numSpace); From 4e0c1a940013e03ae9cd5c2b19fc7a9c5430fb59 Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Thu, 3 Mar 2022 03:22:00 +0100 Subject: [PATCH 022/490] NTC constraints management (#8) * set NTC constraints to 0 in a dummy if loop * Small changes to the dummy loops * insert adqPatchMode data in PROBLEME_HEBDO struct * 0<->0 connections allowed * implement specifications logic into NTC constraint * shift SetNTCForAdequacyFirstStep to separate *.cpp * clang format * Hugo's comments implementation * clean --- src/libs/antares/study/fwd.h | 16 ++++ src/solver/cmake/solver.cmake | 2 + src/solver/optimisation/adequacy_patch.cpp | 74 +++++++++++++++++++ src/solver/optimisation/adequacy_patch.h | 56 ++++++++++++++ .../opt_gestion_des_bornes_cas_lineaire.cpp | 34 ++++++++- .../simulation/sim_alloc_probleme_hebdo.cpp | 4 + .../simulation/sim_calcul_economique.cpp | 2 + .../sim_structure_probleme_economique.h | 2 + 8 files changed, 187 insertions(+), 3 deletions(-) create mode 100644 src/solver/optimisation/adequacy_patch.cpp create mode 100644 src/solver/optimisation/adequacy_patch.h diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index b4485eaab1..1e9ac45b07 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -130,6 +130,22 @@ enum AdequacyPatchMode }; // enum AdequacyPatchMode +/*! +** \brief Setting NTC for Adequacy patch first step +*/ +enum NTC +{ + //! Leave NTC local values + leaveLocalValues = 0, + //! Set NTC to zero + setToZero, + //! set only start->end NTC to zero + setStartEndToZero, + //! set only end->start NTC to zero + setEndStartToZero + +}; // enum NTC + /* ** \brief Simplex optimizations */ diff --git a/src/solver/cmake/solver.cmake b/src/solver/cmake/solver.cmake index 2ccc061cb8..e179d610fa 100644 --- a/src/solver/cmake/solver.cmake +++ b/src/solver/cmake/solver.cmake @@ -52,6 +52,8 @@ set(RTESOLVER_OPT optimisation/renseigner_donnees_couts_demarrage.cpp optimisation/opt_export_structure.h optimisation/opt_export_structure.cpp + optimisation/adequacy_patch.h + optimisation/adequacy_patch.cpp utils/ortools_utils.h utils/ortools_utils.cpp diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp new file mode 100644 index 0000000000..d4ea738f42 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -0,0 +1,74 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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/simulation.h" +#include "adequacy_patch.h" + +using namespace Antares; +using namespace Antares::Data; + +uint SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, + uint StartNodeAdequacyPatchType, + uint EndNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) +{ + if (AdequacyFirstStep) + { + if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch + && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch) + return Data::setToZero; + else if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch + && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch) + { + if (SetToZero12LinksForAdequacyPatch) + return Data::setToZero; + else + return Data::setEndStartToZero; + } + else if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch + && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch) + { + if (SetToZero12LinksForAdequacyPatch) + return Data::setToZero; + else + return Data::setStartEndToZero; + } + else if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch + && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch) + { + if (SetToZero11LinksForAdequacyPatch) + return Data::setToZero; + else + return Data::leaveLocalValues; + } + else + return Data::leaveLocalValues; + } + else + return Data::leaveLocalValues; +} diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h new file mode 100644 index 0000000000..5dd7220271 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch.h @@ -0,0 +1,56 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_ADEQUACY_FUNCTIONS_H__ +#define __SOLVER_ADEQUACY_FUNCTIONS_H__ + +/*! + * Determines if a link capacity needs to be set to 0. Only changes something if used during the + * AdequacyFirstStep. + * + * @param AdequacyFirstStep boolean for the first run of the optimization used by the adequacy patch + * + * @param StartNodeAdequacyPatchType uint: The adq type of the node at the start of the link. + * + * @param EndNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 + * towards nodes of adq type 2 + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 + * towards nodes of adq type 1 + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ +uint SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, + uint StartNodeAdequacyPatchType, + uint EndNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); + +#endif /* __SOLVER_ADEQUACY_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 cefdce58b8..5e03a4b61a 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -34,6 +34,7 @@ #include "../simulation/sim_extern_variables_globales.h" #include "opt_fonctions.h" +#include "adequacy_patch.h" #include #include #include @@ -140,6 +141,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; + bool AdequacyFirstStep; + uint SetToZeroLinkNTCForAdequacyPatchFirstStep; VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; @@ -160,6 +163,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax = ProblemeAResoudre->Xmax; TypeDeVariable = ProblemeAResoudre->TypeDeVariable; + AdequacyFirstStep = true; // ProblemeHebdo->AdequacyFirstStep; + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; @@ -177,10 +182,33 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + SetToZeroLinkNTCForAdequacyPatchFirstStep + = SetNTCForAdequacyFirstStep(AdequacyFirstStep, + ProblemeHebdo->StartAreaAdequacyPatchType[Interco], + ProblemeHebdo->EndAreaAdequacyPatchType[Interco], + true, + true); + if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setToZero) + { + Xmax[Var] = 0.; + Xmin[Var] = 0.; + } + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setStartEndToZero) + { + Xmax[Var] = 0.; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + } + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setEndStartToZero) + { + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = 0.; + } + else + { + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + } if (Math::Infinite(Xmax[Var]) == 1) { if (Math::Infinite(Xmin[Var]) == -1) diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index 8ddd747dbc..d184683451 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -63,6 +63,8 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps problem.PaysExtremiteDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); problem.PaysOrigineDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); + problem.StartAreaAdequacyPatchType = (int*)MemAlloc(linkCount * sizeof(int)); + problem.EndAreaAdequacyPatchType = (int*)MemAlloc(linkCount * sizeof(int)); problem.CoutDeTransport = (COUTS_DE_TRANSPORT**)MemAlloc(linkCount * sizeof(void*)); problem.IndexDebutIntercoOrigine = (int*)MemAlloc(nbPays * sizeof(int)); problem.IndexDebutIntercoExtremite = (int*)MemAlloc(nbPays * sizeof(int)); @@ -595,6 +597,8 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.PaysExtremiteDeLInterconnexion); MemFree(problem.PaysOrigineDeLInterconnexion); + MemFree(problem.StartAreaAdequacyPatchType); + MemFree(problem.EndAreaAdequacyPatchType); MemFree(problem.IndexDebutIntercoOrigine); MemFree(problem.IndexDebutIntercoExtremite); MemFree(problem.IndexSuivantIntercoOrigine); diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 95f55b772c..1b05302c8e 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -188,7 +188,9 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, { auto& link = *(study.runtime->areaLink[i]); problem.PaysOrigineDeLInterconnexion[i] = link.from->index; + problem.StartAreaAdequacyPatchType[i] = link.from->adequacyPatchMode; problem.PaysExtremiteDeLInterconnexion[i] = link.with->index; + problem.EndAreaAdequacyPatchType[i] = link.with->adequacyPatchMode; } for (uint i = 0; i < study.runtime->bindingConstraintCount; ++i) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 3b76e2c9be..003dbcd590 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -485,6 +485,8 @@ struct PROBLEME_HEBDO int NombreDInterconnexions; int* PaysOrigineDeLInterconnexion; int* PaysExtremiteDeLInterconnexion; + int* StartAreaAdequacyPatchType; + int* EndAreaAdequacyPatchType; COUTS_DE_TRANSPORT** CoutDeTransport; VALEURS_DE_NTC_ET_RESISTANCES** ValeursDeNTC; From 6ebdd667fd71ce908e30010f9f84ebe6b64c559d Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Tue, 8 Mar 2022 07:37:28 +0100 Subject: [PATCH 023/490] UI NTC selector for adequacy patch (#12) * update reference guide * add options to problem.hebdo * ui options for ntc constraints for adequacy patch * naming and comments improvements * ref.guide description improvement * plug UI into SetNTCForAdequacyFirstStep --- docs/reference-guide/1-reference-guide.md | 2 + src/libs/antares/study/parameters.cpp | 10 +++ src/libs/antares/study/parameters.h | 8 ++ .../opt_gestion_des_bornes_cas_lineaire.cpp | 6 +- .../simulation/sim_calcul_economique.cpp | 2 + .../sim_structure_probleme_economique.h | 2 + .../options/optimization/optimization.cpp | 86 +++++++++++++++++++ .../options/optimization/optimization.h | 3 + 8 files changed, 116 insertions(+), 3 deletions(-) diff --git a/docs/reference-guide/1-reference-guide.md b/docs/reference-guide/1-reference-guide.md index ab502738f7..36303e7a85 100644 --- a/docs/reference-guide/1-reference-guide.md +++ b/docs/reference-guide/1-reference-guide.md @@ -385,6 +385,8 @@ given back their regular capacities (infinite for those being set on "set to inf - _Spinning reserve (include / ignore)_ - _Export mps (false/true)_ - _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)_ - _Simplex optimization range # 4_ _(day / week)_ - _Unfeasible problems behavior (Error Dry/ Error Verbose/ Warning Dry/ Warning Verbose_ diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index ea1715c289..aae0392f3c 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -306,6 +306,8 @@ void Parameters::reset() include.exportMPS = false; include.adequacyPatch = false; + setToZero12LinksForAdequacyPatch = true; + setToZero11LinksForAdequacyPatch = true; include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -552,6 +554,10 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, return value.to(d.include.exportMPS); if (key == "include-adequacypatch") return value.to(d.include.adequacyPatch); + if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch") + return value.to(d.setToZero12LinksForAdequacyPatch); + if (key == "set-to-null-ntc-between-physical-out-for-first-step-adq-patch") + return value.to(d.setToZero11LinksForAdequacyPatch); if (key == "include-exportstructure") return value.to(d.include.exportStructure); if (key == "include-unfeasible-problem-behavior") @@ -1708,6 +1714,10 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-exportmps", include.exportMPS); section->add("include-adequacypatch", include.adequacyPatch); + section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch", + setToZero12LinksForAdequacyPatch); + section->add("set-to-null-ntc-between-physical-out-for-first-step-adq-patch", + setToZero11LinksForAdequacyPatch); section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 425202168c..532d806507 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -505,6 +505,14 @@ class Parameters final SimplexOptimization simplexOptimizationRange; //@} + //! 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. + bool setToZero12LinksForAdequacyPatch; + //! 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. + bool setToZero11LinksForAdequacyPatch; + //! \name Scenariio Builder - Rules //@{ //! The current active rules for building scenarios (useful if building mode == custom) 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 5e03a4b61a..ec8a1f58bd 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -163,7 +163,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax = ProblemeAResoudre->Xmax; TypeDeVariable = ProblemeAResoudre->TypeDeVariable; - AdequacyFirstStep = true; // ProblemeHebdo->AdequacyFirstStep; + AdequacyFirstStep = ProblemeHebdo->AdequacyFirstStep; for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { @@ -186,8 +186,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob = SetNTCForAdequacyFirstStep(AdequacyFirstStep, ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - true, - true); + ProblemeHebdo->Ntc12, + ProblemeHebdo->Ntc11); if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setToZero) { diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 1b05302c8e..e221bc6dcd 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -65,6 +65,8 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.UseAdequacyPatch = parameters.include.adequacyPatch; problem.AdequacyFirstStep = parameters.include.adequacyPatch; + problem.Ntc12 = parameters.setToZero12LinksForAdequacyPatch; + problem.Ntc11 = parameters.setToZero11LinksForAdequacyPatch; problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 003dbcd590..5a776c0775 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -579,6 +579,8 @@ struct PROBLEME_HEBDO /* Adequacy Patch */ bool UseAdequacyPatch; bool AdequacyFirstStep; + bool Ntc12; + bool Ntc11; optimizationStatistics optimizationStatistics_object; /* Hydro management */ diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index effea6481a..99d89729dd 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -61,6 +61,21 @@ static void ResetButton(Component::Button* button, bool value) } } +static void ResetButtonAdequacyPatch(Component::Button* button, bool value) +{ + assert(button != NULL); + if (value) + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to null")); + } + else + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + } +} + static void ResetButtonSpecify(Component::Button* button, bool value) { assert(button != NULL); @@ -322,6 +337,37 @@ Optimization::Optimization(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatch = button; } + // Transmission capacities (NTC) from physical areas outside adequacy patch (area type 1) to + // physical areas inside adequacy patch (area type 2). Used in the first step of adequacy patch + // local matching rule. + { + label = Component::CreateLabel(this, wxT("NTC from physical areas outside to physical areas inside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchNTC12 = button; + } + // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). + // Used in the first step of adequacy patch local matching rule. + { + label = Component::CreateLabel(this, wxT("NTC between physical areas outside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchNTC11 = button; + } // Unfeasible problem behavior { @@ -443,6 +489,8 @@ void Optimization::onResetToDefault(void*) study.parameters.include.reserve.spinning = true; study.parameters.include.exportMPS = false; study.parameters.include.adequacyPatch = false; + study.parameters.setToZero12LinksForAdequacyPatch = true; + study.parameters.setToZero11LinksForAdequacyPatch = true; study.parameters.simplexOptimizationRange = Data::sorWeek; study.parameters.include.unfeasibleProblemBehavior @@ -492,6 +540,14 @@ void Optimization::refresh() ResetButtonSpecify(pBtnExportMPS, study.parameters.include.exportMPS); // Adequacy patch ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); + // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside + // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, + study.parameters.setToZero12LinksForAdequacyPatch); + // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of + // adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, + study.parameters.setToZero11LinksForAdequacyPatch); // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( @@ -536,6 +592,36 @@ void Optimization::onPopupMenu(Component::Button&, wxMenu& menu, void*, const Po this); } +void Optimization::onPopupMenuAdequacyPatch(Component::Button&, + wxMenu& menu, + void*, + const PopupInfo& info) +{ + pTargetRef = &info.rval; + wxMenuItem* it; + + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("set to null"), + "images/16x16/light_orange.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(Optimization::onSelectModeInclude), + nullptr, + this); + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("local values (") << info.text << wxT(")"), + "images/16x16/light_green.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(Optimization::onSelectModeIgnore), + nullptr, + this); +} + void Optimization::onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index 94df8da3f7..ae27c47c60 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -98,6 +98,7 @@ class Optimization final : public wxDialog void onPopupMenuTransmissionCapacities(Component::Button&, wxMenu& menu, void*); void onPopupMenuLinkType(Component::Button&, wxMenu& menu, void*); void onPopupMenuUnfeasibleBehavior(Component::Button&, wxMenu& menu, void*); + void onPopupMenuAdequacyPatch(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); void onInternalMotion(wxMouseEvent&); @@ -116,6 +117,8 @@ class Optimization final : public wxDialog Component::Button* pBtnExportMPS; Component::Button* pBtnAdequacyPatch; + Component::Button* pBtnAdequacyPatchNTC12; + Component::Button* pBtnAdequacyPatchNTC11; Component::Button* pBtnUnfeasibleProblemBehavior; bool* pTargetRef; From f3e4162109fd6bf14805a3d4a3641bc3d3a562e2 Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Wed, 9 Mar 2022 01:34:01 +0100 Subject: [PATCH 024/490] Rte comments 1. 2. 11. implementation (#20) * name changes in domesticUnsuppliedEnergy.h * 11. enumeration --- src/solver/simulation/sim_alloc_probleme_hebdo.cpp | 9 ++++++--- .../simulation/sim_structure_probleme_economique.h | 8 +++++--- src/solver/variable/economy/domesticUnsuppliedEnergy.h | 4 ++-- 3 files changed, 13 insertions(+), 8 deletions(-) diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index d184683451..3c26068328 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -59,12 +59,15 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps problem.BruitSurCoutHydraulique[p] = (double*)MemAlloc(8784 * sizeof(double)); problem.NomsDesPays = (const char**)MemAlloc(nbPays * sizeof(char*)); - problem.AreaAdequacyPatchMode = (int*)MemAlloc(nbPays * sizeof(int)); + problem.AreaAdequacyPatchMode + = (Data::AdequacyPatch::AdequacyPatchMode*)MemAlloc(nbPays * sizeof(int)); problem.PaysExtremiteDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); problem.PaysOrigineDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); - problem.StartAreaAdequacyPatchType = (int*)MemAlloc(linkCount * sizeof(int)); - problem.EndAreaAdequacyPatchType = (int*)MemAlloc(linkCount * sizeof(int)); + problem.StartAreaAdequacyPatchType + = (Data::AdequacyPatch::AdequacyPatchMode*)MemAlloc(linkCount * sizeof(int)); + problem.EndAreaAdequacyPatchType + = (Data::AdequacyPatch::AdequacyPatchMode*)MemAlloc(linkCount * sizeof(int)); problem.CoutDeTransport = (COUTS_DE_TRANSPORT**)MemAlloc(linkCount * sizeof(void*)); problem.IndexDebutIntercoOrigine = (int*)MemAlloc(nbPays * sizeof(int)); problem.IndexDebutIntercoExtremite = (int*)MemAlloc(nbPays * sizeof(int)); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 5a776c0775..176c54d2e1 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -37,6 +37,8 @@ #include +using namespace Antares::Data::AdequacyPatch; + typedef struct { int* NumeroDeVariableDeLInterconnexion; @@ -479,14 +481,14 @@ struct PROBLEME_HEBDO char OptimisationAvecCoutsDeDemarrage; int NombreDePays; const char** NomsDesPays; - int* AreaAdequacyPatchMode; + AdequacyPatchMode* AreaAdequacyPatchMode; int NombreDePaliersThermiques; int NombreDInterconnexions; int* PaysOrigineDeLInterconnexion; int* PaysExtremiteDeLInterconnexion; - int* StartAreaAdequacyPatchType; - int* EndAreaAdequacyPatchType; + AdequacyPatchMode* StartAreaAdequacyPatchType; + AdequacyPatchMode* EndAreaAdequacyPatchType; COUTS_DE_TRANSPORT** CoutDeTransport; VALEURS_DE_NTC_ET_RESISTANCES** ValeursDeNTC; diff --git a/src/solver/variable/economy/domesticUnsuppliedEnergy.h b/src/solver/variable/economy/domesticUnsuppliedEnergy.h index 8e8ee55cfe..c25e4eb217 100644 --- a/src/solver/variable/economy/domesticUnsuppliedEnergy.h +++ b/src/solver/variable/economy/domesticUnsuppliedEnergy.h @@ -42,7 +42,7 @@ struct VCardDomesticUnsuppliedEnergy //! Caption static const char* Caption() { - return "LOCAL UNSP. ENRG"; + return "DENS"; } //! Unit static const char* Unit() @@ -52,7 +52,7 @@ struct VCardDomesticUnsuppliedEnergy //! The short description of the variable static const char* Description() { - return "Domestic Energy Not Served (demand that cannot be satisfied before exchange)"; + return "Domestic Unsupplied Energy (demand that cannot be satisfied without interconnections/links)"; } //! The expecte results From 234a75e9b424afa99ee1d516b9402f369db1c9ef Mon Sep 17 00:00:00 2001 From: rtei-pw <92968374+rtei-pw@users.noreply.github.com> Date: Wed, 9 Mar 2022 13:30:01 +0800 Subject: [PATCH 025/490] review modif 3. 5. 7, 8 (#16) * 5. consider previously set bounds * 7. remove not multiple * 8. add todo arround SIM_ * 3. namespace * 4. change Start&End to Origine&Extremity * 3. bis fix Co-authored-by: milos --- src/libs/antares/study/area/area.cpp | 6 +- src/libs/antares/study/area/area.h | 2 +- src/libs/antares/study/area/list.cpp | 14 ++-- src/libs/antares/study/fwd.h | 71 +++++++++++-------- src/solver/optimisation/adequacy_patch.cpp | 35 ++++----- .../opt_gestion_des_bornes_cas_lineaire.cpp | 13 ++-- src/solver/simulation/economy.cpp | 6 +- .../windows/inspector/accumulator.hxx | 8 +-- src/ui/simulator/windows/inspector/frame.cpp | 3 +- .../windows/inspector/property.update.cpp | 35 ++++----- 10 files changed, 104 insertions(+), 89 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index f9d60e3d50..da7d734762 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,7 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), - adequacyPatchMode(Data::adqmPhysicalAreaOutsideAdqPatch), + adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -71,7 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), - adequacyPatchMode(Data::adqmPhysicalAreaOutsideAdqPatch), + adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -91,7 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), - adequacyPatchMode(Data::adqmPhysicalAreaOutsideAdqPatch), + adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 117d8c6162..916eb0ab8d 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -226,7 +226,7 @@ class Area final : private Yuni::NonCopyable //! Enabled bool enabled; //! Use adequacy patch for this area - Data::AdequacyPatchMode adequacyPatchMode; + Data::AdequacyPatch::AdequacyPatchMode adequacyPatchMode; /*@}*/ //! \name Associate data */ diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 546d452295..9322d4e414 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -338,13 +338,13 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) int value; switch (area.adequacyPatchMode) { - case Data::adqmVirtualArea: + case Data::AdequacyPatch::adqmVirtualArea: value = 0; break; - case Data::adqmPhysicalAreaOutsideAdqPatch: + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: value = 1; break; - case Data::adqmPhysicalAreaInsideAdqPatch: + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: value = 2; break; default: @@ -1089,16 +1089,16 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, switch (value) { case 0: - area.adequacyPatchMode = Data::adqmVirtualArea; + area.adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; break; case 1: - area.adequacyPatchMode = Data::adqmPhysicalAreaOutsideAdqPatch; + area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; break; case 2: - area.adequacyPatchMode = Data::adqmPhysicalAreaInsideAdqPatch; + area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; break; default: - area.adequacyPatchMode = Data::adqmPhysicalAreaOutsideAdqPatch; + area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; break; } continue; diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 1e9ac45b07..65beb32549 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -116,36 +116,6 @@ enum StudyMode }; // enum StudyMode -/*! -** \brief Types of Adequacy patch mode -*/ -enum AdequacyPatchMode -{ - //! Virtual area in adq patch - adqmVirtualArea = 0, - //! Physical Area outside the adq-patch - adqmPhysicalAreaOutsideAdqPatch, - //! Physical Area inside the adq-patch - adqmPhysicalAreaInsideAdqPatch - -}; // enum AdequacyPatchMode - -/*! -** \brief Setting NTC for Adequacy patch first step -*/ -enum NTC -{ - //! Leave NTC local values - leaveLocalValues = 0, - //! Set NTC to zero - setToZero, - //! set only start->end NTC to zero - setStartEndToZero, - //! set only end->start NTC to zero - setEndStartToZero - -}; // enum NTC - /* ** \brief Simplex optimizations */ @@ -587,4 +557,45 @@ class Sets; } // namespace Data } // namespace Antares +namespace Antares +{ +namespace Data +{ +namespace AdequacyPatch +{ + +/*! +** \brief Types of Adequacy patch mode +*/ +enum AdequacyPatchMode +{ + //! Virtual area in adq patch + adqmVirtualArea = 0, + //! Physical Area outside the adq-patch + adqmPhysicalAreaOutsideAdqPatch, + //! Physical Area inside the adq-patch + adqmPhysicalAreaInsideAdqPatch + +}; // enum AdequacyPatchMode + +/*! +** \brief Setting NTC for Adequacy patch first step +*/ +enum NTC +{ + //! Leave NTC local values + leaveLocalValues = 0, + //! Set NTC to zero + setToZero, + //! set only origine->extremity NTC to zero + setOrigineExtremityToZero, + //! set only extremity->origine NTC to zero + setExtremityOrigineToZero + +}; // enum NTC + +} // namespace AdequacyPatch +} // namespace Data +} // namespace Antares + #endif // __ANTARES_LIBS_STUDY_FWD_H__ diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index d4ea738f42..d8dc9800ce 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -30,6 +30,7 @@ using namespace Antares; using namespace Antares::Data; +using namespace Antares::Data::AdequacyPatch; uint SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, uint StartNodeAdequacyPatchType, @@ -39,36 +40,36 @@ uint SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, { if (AdequacyFirstStep) { - if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch - && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch) - return Data::setToZero; - else if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch - && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch) + if (StartNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch + && EndNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) + return setToZero; + else if (StartNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch + && EndNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) { if (SetToZero12LinksForAdequacyPatch) - return Data::setToZero; + return setToZero; else - return Data::setEndStartToZero; + return setExtremityOrigineToZero; } - else if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaInsideAdqPatch - && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch) + else if (StartNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch + && EndNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) { if (SetToZero12LinksForAdequacyPatch) - return Data::setToZero; + return setToZero; else - return Data::setStartEndToZero; + return setOrigineExtremityToZero; } - else if (StartNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch - && EndNodeAdequacyPatchType == Data::adqmPhysicalAreaOutsideAdqPatch) + else if (StartNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch + && EndNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) { if (SetToZero11LinksForAdequacyPatch) - return Data::setToZero; + return setToZero; else - return Data::leaveLocalValues; + return leaveLocalValues; } else - return Data::leaveLocalValues; + return leaveLocalValues; } else - return Data::leaveLocalValues; + return leaveLocalValues; } 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 ec8a1f58bd..9c6d02631c 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -189,17 +189,17 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob ProblemeHebdo->Ntc12, ProblemeHebdo->Ntc11); - if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setToZero) + if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) { Xmax[Var] = 0.; Xmin[Var] = 0.; } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setStartEndToZero) + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setOrigineExtremityToZero) { Xmax[Var] = 0.; Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::setEndStartToZero) + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setExtremityOrigineToZero) { Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin[Var] = 0.; @@ -433,9 +433,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob if (ProblemeHebdo->UseAdequacyPatch == true && ProblemeHebdo->AdequacyFirstStep == false) if (ProblemeHebdo->AreaAdequacyPatchMode[Pays] - == Data::adqmPhysicalAreaInsideAdqPatch) - Xmax[Var] - = ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]; + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + Xmax[Var] = min( + Xmax[Var], + ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo] diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 82381f5914..a46e98eb77 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -155,7 +155,7 @@ bool Economy::year(Progression::Task& progression, for (int pays = 0; pays < pProblemesHebdo[numSpace]->NombreDePays; ++pays) { if (pProblemesHebdo[numSpace]->AreaAdequacyPatchMode[pays] - == Data::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) memcpy( pProblemesHebdo[numSpace]->ResultatsHoraires[pays]->ValeursHorairesDENS, pProblemesHebdo[numSpace] @@ -169,8 +169,10 @@ bool Economy::year(Progression::Task& progression, pProblemesHebdo[numSpace]->NombreDePasDeTemps * sizeof(double)); } + // TODO check if we need to cut SIM_RenseignementProblemeHebdo and just pick out the + // part that we need ::SIM_RenseignementProblemeHebdo( - *pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); // todo ? correct + *pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); } else diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index 1e6bb88f3f..0fc3bdd5eb 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -911,7 +911,7 @@ struct PAreaUnsuppliedEnergyCost struct PAdequacyPatchMode { - typedef Data::AdequacyPatchMode Type; + typedef Data::AdequacyPatch::AdequacyPatchMode Type; static Type Value(const Data::Area* area) { return area->adequacyPatchMode; @@ -920,11 +920,11 @@ struct PAdequacyPatchMode { switch (v) { - case Data::adqmVirtualArea: + case Data::AdequacyPatch::adqmVirtualArea: return wxT("virtual area"); - case Data::adqmPhysicalAreaOutsideAdqPatch: + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: return wxT("physical area outside patch"); - case Data::adqmPhysicalAreaInsideAdqPatch: + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: return wxT("physical area inside patch"); } return wxEmptyString; diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 42a95a9acb..ab52dd0573 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -791,8 +791,7 @@ void Frame::apply(const InspectorData::Ptr& data) // Area color Accumulator::Apply(pPGAreaColor, data->areas); // Adequacy patch - if (!multiple) - Accumulator::Apply(pPGAreaAdequacyPatchMode, data->areas); + Accumulator::Apply(pPGAreaAdequacyPatchMode, data->areas); // Area position if (!multiple) { diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 08128dc5a1..29ac1067dc 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -174,25 +174,26 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, } if (name == "area.adequacy_patch_mode") { - auto* area = *i; - if (area) + for (; i != end; ++i) { - String s; - wxStringToString(value.GetString(), s); - s.toLower(); - s.trim(); - - if (s == "virtual area" || s == "0") - area->adequacyPatchMode = Data::adqmVirtualArea; - else if (s == "physical area outside patch" || s == "1") - area->adequacyPatchMode = Data::adqmPhysicalAreaOutsideAdqPatch; - else if (s == "physical area inside patch" || s == "2") - area->adequacyPatchMode = Data::adqmPhysicalAreaInsideAdqPatch; - - OnStudyAreaUseAdequacyPatchChanged(); - return true; + auto* area = *i; + if (area) + { + String s; + wxStringToString(value.GetString(), s); + s.toLower(); + s.trim(); + + if (s == "virtual area" || s == "0") + area->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + else if (s == "physical area outside patch" || s == "1") + area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + else if (s == "physical area inside patch" || s == "2") + area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + } } - return false; + OnStudyAreaUseAdequacyPatchChanged(); + return true; } if (name == "area.links_count") return false; From 87044fece3f3385c614280aafced72aac3734c14 Mon Sep 17 00:00:00 2001 From: milos Date: Wed, 9 Mar 2022 13:30:36 +0100 Subject: [PATCH 026/490] 10. make adq struct --- .../opt_gestion_des_bornes_cas_lineaire.cpp | 13 +++++-------- src/solver/simulation/economy.cpp | 6 +++--- src/solver/simulation/sim_calcul_economique.cpp | 8 ++++---- .../simulation/sim_structure_probleme_economique.h | 11 +++++++---- 4 files changed, 19 insertions(+), 19 deletions(-) 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 9c6d02631c..26994bacf2 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -141,7 +141,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; - bool AdequacyFirstStep; uint SetToZeroLinkNTCForAdequacyPatchFirstStep; VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; @@ -163,8 +162,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax = ProblemeAResoudre->Xmax; TypeDeVariable = ProblemeAResoudre->TypeDeVariable; - AdequacyFirstStep = ProblemeHebdo->AdequacyFirstStep; - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; @@ -183,11 +180,11 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; SetToZeroLinkNTCForAdequacyPatchFirstStep - = SetNTCForAdequacyFirstStep(AdequacyFirstStep, + = SetNTCForAdequacyFirstStep(ProblemeHebdo->adqPatch.AdequacyFirstStep, ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - ProblemeHebdo->Ntc12, - ProblemeHebdo->Ntc11); + ProblemeHebdo->adqPatch.Ntc12, + ProblemeHebdo->adqPatch.Ntc11); if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) { @@ -430,8 +427,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax[Var] = 0.; // adq patch: update ENS <= DENS in 2nd run - if (ProblemeHebdo->UseAdequacyPatch == true - && ProblemeHebdo->AdequacyFirstStep == false) + if (ProblemeHebdo->adqPatch.UseAdequacyPatch == true + && ProblemeHebdo->adqPatch.AdequacyFirstStep == false) if (ProblemeHebdo->AreaAdequacyPatchMode[Pays] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) Xmax[Var] = min( diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index a46e98eb77..86d291347b 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -146,11 +146,11 @@ bool Economy::year(Progression::Task& progression, try { - if (pProblemesHebdo[numSpace]->UseAdequacyPatch) + if (pProblemesHebdo[numSpace]->adqPatch.UseAdequacyPatch) { - pProblemesHebdo[numSpace]->AdequacyFirstStep = true; + pProblemesHebdo[numSpace]->adqPatch.AdequacyFirstStep = true; OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); - pProblemesHebdo[numSpace]->AdequacyFirstStep = false; + pProblemesHebdo[numSpace]->adqPatch.AdequacyFirstStep = false; for (int pays = 0; pays < pProblemesHebdo[numSpace]->NombreDePays; ++pays) { diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index e221bc6dcd..192bc5270f 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -63,10 +63,10 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.hydroHotStart = (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart); - problem.UseAdequacyPatch = parameters.include.adequacyPatch; - problem.AdequacyFirstStep = parameters.include.adequacyPatch; - problem.Ntc12 = parameters.setToZero12LinksForAdequacyPatch; - problem.Ntc11 = parameters.setToZero11LinksForAdequacyPatch; + problem.adqPatch.UseAdequacyPatch = parameters.include.adequacyPatch; + problem.adqPatch.AdequacyFirstStep = parameters.include.adequacyPatch; + problem.adqPatch.Ntc12 = parameters.setToZero12LinksForAdequacyPatch; + problem.adqPatch.Ntc11 = parameters.setToZero11LinksForAdequacyPatch; problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 176c54d2e1..449c70df5c 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -579,10 +579,13 @@ struct PROBLEME_HEBDO ALL_MUST_RUN_GENERATION** AllMustRunGeneration; /* Adequacy Patch */ - bool UseAdequacyPatch; - bool AdequacyFirstStep; - bool Ntc12; - bool Ntc11; + struct AdequacyPatchStruct + { + bool UseAdequacyPatch; + bool AdequacyFirstStep; + bool Ntc12; + bool Ntc11; + } adqPatch; optimizationStatistics optimizationStatistics_object; /* Hydro management */ From ba382cf9eeed94236e041ccea3eba10d2f79d986 Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Fri, 11 Mar 2022 06:04:11 +0100 Subject: [PATCH 027/490] 11. additional changes for comment 11 (#22) --- src/solver/optimisation/adequacy_patch.cpp | 10 +++++----- src/solver/optimisation/adequacy_patch.h | 10 +++++----- .../opt_gestion_des_bornes_cas_lineaire.cpp | 2 +- 3 files changed, 11 insertions(+), 11 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index d8dc9800ce..9a1e9a519b 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -32,11 +32,11 @@ using namespace Antares; using namespace Antares::Data; using namespace Antares::Data::AdequacyPatch; -uint SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, - uint StartNodeAdequacyPatchType, - uint EndNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch) +NTC SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, + AdequacyPatchMode StartNodeAdequacyPatchType, + AdequacyPatchMode EndNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) { if (AdequacyFirstStep) { diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 5dd7220271..e150ff6d4c 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -47,10 +47,10 @@ * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -uint SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, - uint StartNodeAdequacyPatchType, - uint EndNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch); +NTC SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, + AdequacyPatchMode StartNodeAdequacyPatchType, + AdequacyPatchMode EndNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); #endif /* __SOLVER_ADEQUACY_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 9c6d02631c..5a81bd28a4 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -142,7 +142,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmax; int* TypeDeVariable; bool AdequacyFirstStep; - uint SetToZeroLinkNTCForAdequacyPatchFirstStep; + Data::AdequacyPatch::NTC SetToZeroLinkNTCForAdequacyPatchFirstStep; VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; From 7e922178c4c0b264c552cb77ba474f9f88b81e28 Mon Sep 17 00:00:00 2001 From: "Hugo ANTOINE (RTEi)" Date: Tue, 15 Mar 2022 00:04:24 +0100 Subject: [PATCH 028/490] 10. make adqPatch pointer --- .../opt_gestion_des_bornes_cas_lineaire.cpp | 9 ++++----- src/solver/simulation/economy.cpp | 6 +++--- src/solver/simulation/sim_calcul_economique.cpp | 10 ++++++---- .../sim_structure_probleme_economique.h | 16 +++++++++------- 4 files changed, 22 insertions(+), 19 deletions(-) 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 26994bacf2..7e8ec6a3b6 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -180,11 +180,11 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; SetToZeroLinkNTCForAdequacyPatchFirstStep - = SetNTCForAdequacyFirstStep(ProblemeHebdo->adqPatch.AdequacyFirstStep, + = SetNTCForAdequacyFirstStep(ProblemeHebdo->adqPatch->AdequacyFirstStep, ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - ProblemeHebdo->adqPatch.Ntc12, - ProblemeHebdo->adqPatch.Ntc11); + ProblemeHebdo->adqPatch->Ntc12, + ProblemeHebdo->adqPatch->Ntc11); if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) { @@ -427,8 +427,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax[Var] = 0.; // adq patch: update ENS <= DENS in 2nd run - if (ProblemeHebdo->adqPatch.UseAdequacyPatch == true - && ProblemeHebdo->adqPatch.AdequacyFirstStep == false) + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false) if (ProblemeHebdo->AreaAdequacyPatchMode[Pays] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) Xmax[Var] = min( diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 86d291347b..30f48e7f37 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -146,11 +146,11 @@ bool Economy::year(Progression::Task& progression, try { - if (pProblemesHebdo[numSpace]->adqPatch.UseAdequacyPatch) + if (pProblemesHebdo[numSpace]->adqPatch) { - pProblemesHebdo[numSpace]->adqPatch.AdequacyFirstStep = true; + pProblemesHebdo[numSpace]->adqPatch->AdequacyFirstStep = true; OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); - pProblemesHebdo[numSpace]->adqPatch.AdequacyFirstStep = false; + pProblemesHebdo[numSpace]->adqPatch->AdequacyFirstStep = false; for (int pays = 0; pays < pProblemesHebdo[numSpace]->NombreDePays; ++pays) { diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 192bc5270f..9442d670a8 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -63,10 +63,12 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.hydroHotStart = (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart); - problem.adqPatch.UseAdequacyPatch = parameters.include.adequacyPatch; - problem.adqPatch.AdequacyFirstStep = parameters.include.adequacyPatch; - problem.adqPatch.Ntc12 = parameters.setToZero12LinksForAdequacyPatch; - problem.adqPatch.Ntc11 = parameters.setToZero11LinksForAdequacyPatch; + if (parameters.include.adequacyPatch){ + problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); + // AdequacyFirstStep will be initialized during the economy solve + problem.adqPatch->Ntc12 = parameters.setToZero12LinksForAdequacyPatch; + problem.adqPatch->Ntc11 = parameters.setToZero11LinksForAdequacyPatch; + } problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 449c70df5c..1f4a65b650 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -35,6 +35,7 @@ #define GROSSES_VARIABLES NON_ANTARES #define COEFF_GROSSES_VARIABLES 100 +#include #include using namespace Antares::Data::AdequacyPatch; @@ -472,6 +473,13 @@ typedef struct double* CoutsMarginauxHorairesDeLaReserveParZone; } COUTS_MARGINAUX_ZONES_DE_RESERVE; +struct AdequacyPatchParameters +{ + bool AdequacyFirstStep; + bool Ntc12; + bool Ntc11; +}; + struct PROBLEME_HEBDO { /* Business problem */ @@ -579,13 +587,7 @@ struct PROBLEME_HEBDO ALL_MUST_RUN_GENERATION** AllMustRunGeneration; /* Adequacy Patch */ - struct AdequacyPatchStruct - { - bool UseAdequacyPatch; - bool AdequacyFirstStep; - bool Ntc12; - bool Ntc11; - } adqPatch; + std::unique_ptr adqPatch = nullptr; optimizationStatistics optimizationStatistics_object; /* Hydro management */ From 644aa0de021841de94035878850ecb9ba3cc79f5 Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 15 Mar 2022 11:22:42 +0100 Subject: [PATCH 029/490] group adq parameters in a sub category --- .../options/optimization/optimization.cpp | 88 +++++++++++-------- 1 file changed, 51 insertions(+), 37 deletions(-) diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index 99d89729dd..b5eaeef8db 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -46,6 +46,21 @@ namespace Window { namespace Options { +static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) +{ + if (margintop) + { + sizer->AddSpacer(25); + sizer->AddSpacer(25); + } + + auto* label = Component::CreateLabel(parent, text, true); + + sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + sizer->AddSpacer(5); + sizer->AddSpacer(5); + sizer->AddSpacer(5); +} static void ResetButton(Component::Button* button, bool value) { assert(button != NULL); @@ -322,7 +337,43 @@ Optimization::Optimization(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnExportMPS = button; } + // Unfeasible problem behavior + { + label = Component::CreateLabel(this, wxT("Unfeasible problem behavior")); + const Data::UnfeasibleProblemBehavior& defaultValue + = Data::UnfeasibleProblemBehavior::ERROR_DRY; + button = new Component::Button( + this, Data::getDisplayName(defaultValue), Data::getIcon(defaultValue)); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, &Optimization::onPopupMenuUnfeasibleBehavior); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnUnfeasibleProblemBehavior = button; + } + + // Simplex optimization range + { + label = Component::CreateLabel(this, wxT("Simplex optimization range")); + button = new Component::Button(this, wxT("Day"), "images/16x16/calendar_day.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + button->onPopupMenu(this, &Optimization::onPopupMenuSimplex); + + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnSimplexOptimizationRange = button; + } + if (0) + { + label = Component::CreateLabel( + this, wxT("Weekly binding constraints will be ignored"), false, false, -1); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->AddSpacer(2); + } + SubTitle(this, s, wxT("Adeqaucy Patch")); // Adequacy patch { label = Component::CreateLabel(this, wxT("Adequacy patch")); @@ -369,43 +420,6 @@ Optimization::Optimization(wxWindow* parent) : pBtnAdequacyPatchNTC11 = button; } - // Unfeasible problem behavior - { - label = Component::CreateLabel(this, wxT("Unfeasible problem behavior")); - - const Data::UnfeasibleProblemBehavior& defaultValue - = Data::UnfeasibleProblemBehavior::ERROR_DRY; - button = new Component::Button( - this, Data::getDisplayName(defaultValue), Data::getIcon(defaultValue)); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, &Optimization::onPopupMenuUnfeasibleBehavior); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnUnfeasibleProblemBehavior = button; - } - - // Simplex optimization range - { - label = Component::CreateLabel(this, wxT("Simplex optimization range")); - button = new Component::Button(this, wxT("Day"), "images/16x16/calendar_day.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - button->onPopupMenu(this, &Optimization::onPopupMenuSimplex); - - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnSimplexOptimizationRange = button; - } - if (0) - { - label = Component::CreateLabel( - this, wxT("Weekly binding constraints will be ignored"), false, false, -1); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->AddSpacer(2); - } - { s->AddSpacer(2); s->Add(105, 2); From 9c64e0351969d4886bfcdf5396204d238902dc96 Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 15 Mar 2022 12:53:34 +0100 Subject: [PATCH 030/490] bug fix --- .../opt_gestion_des_bornes_cas_lineaire.cpp | 19 ++++++++++++------- 1 file changed, 12 insertions(+), 7 deletions(-) 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 52c78d92cb..cb89f12559 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -178,13 +178,18 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - - SetToZeroLinkNTCForAdequacyPatchFirstStep - = SetNTCForAdequacyFirstStep(ProblemeHebdo->adqPatch->AdequacyFirstStep, - ProblemeHebdo->StartAreaAdequacyPatchType[Interco], - ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - ProblemeHebdo->adqPatch->Ntc12, - ProblemeHebdo->adqPatch->Ntc11); + + if (ProblemeHebdo->adqPatch) + { + SetToZeroLinkNTCForAdequacyPatchFirstStep + = SetNTCForAdequacyFirstStep(ProblemeHebdo->adqPatch->AdequacyFirstStep, + ProblemeHebdo->StartAreaAdequacyPatchType[Interco], + ProblemeHebdo->EndAreaAdequacyPatchType[Interco], + ProblemeHebdo->adqPatch->Ntc12, + ProblemeHebdo->adqPatch->Ntc11); + } + else + SetToZeroLinkNTCForAdequacyPatchFirstStep = Data::AdequacyPatch::leaveLocalValues; if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) { From 54092ee71fac7a31f0971e06525f5a9e25e18a62 Mon Sep 17 00:00:00 2001 From: "Hugo ANTOINE (RTEi)" Date: Tue, 15 Mar 2022 13:28:56 +0100 Subject: [PATCH 031/490] small typo --- .../simulator/windows/options/optimization/optimization.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index b5eaeef8db..08559b16dd 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -373,10 +373,10 @@ Optimization::Optimization(wxWindow* parent) : s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->AddSpacer(2); } - SubTitle(this, s, wxT("Adeqaucy Patch")); + SubTitle(this, s, wxT("Adequacy Patch")); // Adequacy patch { - label = Component::CreateLabel(this, wxT("Adequacy patch")); + label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); button->SetBackgroundColour(bgColor); button->menu(true); From 6e3322708ac2055fee10be88fa9bf5dc319081de Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 11:07:33 +0100 Subject: [PATCH 032/490] change NTC name and avoid using directives --- src/libs/antares/study/fwd.h | 4 ++-- src/solver/optimisation/adequacy_patch.cpp | 12 ++++++------ src/solver/optimisation/adequacy_patch.h | 11 ++++++----- .../opt_gestion_des_bornes_cas_lineaire.cpp | 3 ++- 4 files changed, 16 insertions(+), 14 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 65beb32549..5b70500acf 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -579,9 +579,9 @@ enum AdequacyPatchMode }; // enum AdequacyPatchMode /*! -** \brief Setting NTC for Adequacy patch first step +** \brief Setting Link Capacity (NTC) for Adequacy patch first step */ -enum NTC +enum LinkCapacityForAdequacyPatchFirstStep { //! Leave NTC local values leaveLocalValues = 0, diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 9a1e9a519b..70120cbda7 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -30,13 +30,13 @@ using namespace Antares; using namespace Antares::Data; -using namespace Antares::Data::AdequacyPatch; -NTC SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, - AdequacyPatchMode StartNodeAdequacyPatchType, - AdequacyPatchMode EndNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch) +AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + bool AdequacyFirstStep, + AdequacyPatch::AdequacyPatchMode StartNodeAdequacyPatchType, + AdequacyPatch::AdequacyPatchMode EndNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) { if (AdequacyFirstStep) { diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index e150ff6d4c..9436e0e8b8 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -47,10 +47,11 @@ * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -NTC SetNTCForAdequacyFirstStep(bool AdequacyFirstStep, - AdequacyPatchMode StartNodeAdequacyPatchType, - AdequacyPatchMode EndNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch); +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + bool AdequacyFirstStep, + AdequacyPatchMode StartNodeAdequacyPatchType, + AdequacyPatchMode EndNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); #endif /* __SOLVER_ADEQUACY_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 cb89f12559..56cc472db9 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -141,7 +141,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; - Data::AdequacyPatch::NTC SetToZeroLinkNTCForAdequacyPatchFirstStep; + Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep + SetToZeroLinkNTCForAdequacyPatchFirstStep; VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; From d06c2bd08c5e04ecab56d1831c71064f1800dd78 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 11:30:05 +0100 Subject: [PATCH 033/490] placed NTC function inside a AdqPatch namespace --- src/solver/optimisation/adequacy_patch.cpp | 13 ++++++++++--- src/solver/optimisation/adequacy_patch.h | 11 +++++++++++ .../opt_gestion_des_bornes_cas_lineaire.cpp | 11 ++++++----- 3 files changed, 27 insertions(+), 8 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 70120cbda7..823a16186b 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -28,9 +28,12 @@ #include "../simulation/simulation.h" #include "adequacy_patch.h" -using namespace Antares; -using namespace Antares::Data; - +namespace Antares +{ +namespace Data +{ +namespace AdequacyPatch +{ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatch::AdequacyPatchMode StartNodeAdequacyPatchType, @@ -73,3 +76,7 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( else return leaveLocalValues; } + +} // namespace AdequacyPatch +} // namespace Data +} // namespace Antares diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 9436e0e8b8..12b0fd1ffd 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -28,6 +28,13 @@ #ifndef __SOLVER_ADEQUACY_FUNCTIONS_H__ #define __SOLVER_ADEQUACY_FUNCTIONS_H__ +namespace Antares +{ +namespace Data +{ +namespace AdequacyPatch +{ + /*! * Determines if a link capacity needs to be set to 0. Only changes something if used during the * AdequacyFirstStep. @@ -54,4 +61,8 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch); +} // namespace AdequacyPatch +} // namespace Data +} // namespace Antares + #endif /* __SOLVER_ADEQUACY_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 56cc472db9..e62b8c2f97 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -183,11 +183,12 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob if (ProblemeHebdo->adqPatch) { SetToZeroLinkNTCForAdequacyPatchFirstStep - = SetNTCForAdequacyFirstStep(ProblemeHebdo->adqPatch->AdequacyFirstStep, - ProblemeHebdo->StartAreaAdequacyPatchType[Interco], - ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - ProblemeHebdo->adqPatch->Ntc12, - ProblemeHebdo->adqPatch->Ntc11); + = Antares::Data::AdequacyPatch::SetNTCForAdequacyFirstStep( + ProblemeHebdo->adqPatch->AdequacyFirstStep, + ProblemeHebdo->StartAreaAdequacyPatchType[Interco], + ProblemeHebdo->EndAreaAdequacyPatchType[Interco], + ProblemeHebdo->adqPatch->Ntc12, + ProblemeHebdo->adqPatch->Ntc11); } else SetToZeroLinkNTCForAdequacyPatchFirstStep = Data::AdequacyPatch::leaveLocalValues; From c236df846f1b9754f3952285186e30a2375dda43 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 11:47:59 +0100 Subject: [PATCH 034/490] rename Ntc11 & Ntc12 to be more expressive --- .../opt_gestion_des_bornes_cas_lineaire.cpp | 7 ++++--- src/solver/simulation/sim_calcul_economique.cpp | 13 ++++++++----- .../simulation/sim_structure_probleme_economique.h | 4 ++-- 3 files changed, 14 insertions(+), 10 deletions(-) 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 e62b8c2f97..ac2198e011 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -179,7 +179,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - + if (ProblemeHebdo->adqPatch) { SetToZeroLinkNTCForAdequacyPatchFirstStep @@ -187,8 +187,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob ProblemeHebdo->adqPatch->AdequacyFirstStep, ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - ProblemeHebdo->adqPatch->Ntc12, - ProblemeHebdo->adqPatch->Ntc11); + ProblemeHebdo->adqPatch + ->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); } else SetToZeroLinkNTCForAdequacyPatchFirstStep = Data::AdequacyPatch::leaveLocalValues; diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index d4458cfbeb..8a2a6c650c 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -63,11 +63,14 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.hydroHotStart = (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart); - if (parameters.include.adequacyPatch){ - problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); - // AdequacyFirstStep will be initialized during the economy solve - problem.adqPatch->Ntc12 = parameters.setToZero12LinksForAdequacyPatch; - problem.adqPatch->Ntc11 = parameters.setToZero11LinksForAdequacyPatch; + if (parameters.include.adequacyPatch) + { + problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); + // AdequacyFirstStep will be initialized during the economy solve + problem.adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq + = parameters.setToZero12LinksForAdequacyPatch; + problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq + = parameters.setToZero11LinksForAdequacyPatch; } problem.WaterValueAccurate diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 1f4a65b650..2fac676fe4 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -476,8 +476,8 @@ typedef struct struct AdequacyPatchParameters { bool AdequacyFirstStep; - bool Ntc12; - bool Ntc11; + bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; }; struct PROBLEME_HEBDO From 0564e7d920bee776c168c6c32c9226127a0174f9 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 12:44:21 +0100 Subject: [PATCH 035/490] change End and Start in ntc function --- src/solver/optimisation/adequacy_patch.cpp | 20 ++++++++++---------- src/solver/optimisation/adequacy_patch.h | 4 ++-- 2 files changed, 12 insertions(+), 12 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 823a16186b..d8a7f5706e 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -36,34 +36,34 @@ namespace AdequacyPatch { AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, - AdequacyPatch::AdequacyPatchMode StartNodeAdequacyPatchType, - AdequacyPatch::AdequacyPatchMode EndNodeAdequacyPatchType, + AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch) { if (AdequacyFirstStep) { - if (StartNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch - && EndNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) + if (OriginNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch + && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) return setToZero; - else if (StartNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch - && EndNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) + else if (OriginNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch + && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) { if (SetToZero12LinksForAdequacyPatch) return setToZero; else return setExtremityOrigineToZero; } - else if (StartNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch - && EndNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) + else if (OriginNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch + && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) { if (SetToZero12LinksForAdequacyPatch) return setToZero; else return setOrigineExtremityToZero; } - else if (StartNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch - && EndNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) + else if (OriginNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch + && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) { if (SetToZero11LinksForAdequacyPatch) return setToZero; diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 12b0fd1ffd..8150dba9b8 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -56,8 +56,8 @@ namespace AdequacyPatch */ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, - AdequacyPatchMode StartNodeAdequacyPatchType, - AdequacyPatchMode EndNodeAdequacyPatchType, + AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch); From 8b49d45ccdc97557b287eb43cc946b53c534e381 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 14:58:03 +0100 Subject: [PATCH 036/490] use map for SetNTCForAdequacyFirstStep function --- src/solver/optimisation/adequacy_patch.cpp | 59 ++++++++++++---------- 1 file changed, 32 insertions(+), 27 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index d8a7f5706e..4a195e1a1b 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -27,6 +27,7 @@ #include "../simulation/simulation.h" #include "adequacy_patch.h" +#include namespace Antares { @@ -43,33 +44,37 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( { if (AdequacyFirstStep) { - if (OriginNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch - && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) - return setToZero; - else if (OriginNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch - && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch) - { - if (SetToZero12LinksForAdequacyPatch) - return setToZero; - else - return setExtremityOrigineToZero; - } - else if (OriginNodeAdequacyPatchType == adqmPhysicalAreaInsideAdqPatch - && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) - { - if (SetToZero12LinksForAdequacyPatch) - return setToZero; - else - return setOrigineExtremityToZero; - } - else if (OriginNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch - && ExtremityNodeAdequacyPatchType == adqmPhysicalAreaOutsideAdqPatch) - { - if (SetToZero11LinksForAdequacyPatch) - return setToZero; - else - return leaveLocalValues; - } + std::map, + LinkCapacityForAdequacyPatchFirstStep> + behaviorMap; + + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), + setToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), + (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), + (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), + (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues)); + behaviorMap.insert( + std::make_pair(std::make_pair(adqmVirtualArea, adqmVirtualArea), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmVirtualArea, adqmPhysicalAreaOutsideAdqPatch), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmVirtualArea, adqmPhysicalAreaInsideAdqPatch), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + + auto search = behaviorMap.find( + std::make_pair(OriginNodeAdequacyPatchType, ExtremityNodeAdequacyPatchType)); + if (search != behaviorMap.end()) + return search->second; else return leaveLocalValues; } From fb94c9bd9e7f3a8603b0150e09ee590f8f524f65 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 17:55:37 +0100 Subject: [PATCH 037/490] use map for SetNTCForAdqFirstStep function update! --- src/solver/optimisation/adequacy_patch.cpp | 63 ++++++++++--------- src/solver/optimisation/adequacy_patch.h | 32 +++++++--- .../opt_gestion_des_bornes_cas_lineaire.cpp | 10 ++- 3 files changed, 64 insertions(+), 41 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 4a195e1a1b..9f4af73a44 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -39,38 +39,11 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch) + std::map, LinkCapacityForAdequacyPatchFirstStep> + &behaviorMap) { if (AdequacyFirstStep) { - std::map, - LinkCapacityForAdequacyPatchFirstStep> - behaviorMap; - - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), - setToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), - (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), - (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), - (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues)); - behaviorMap.insert( - std::make_pair(std::make_pair(adqmVirtualArea, adqmVirtualArea), leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmVirtualArea, adqmPhysicalAreaOutsideAdqPatch), leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmVirtualArea), leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmVirtualArea, adqmPhysicalAreaInsideAdqPatch), leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmVirtualArea), leaveLocalValues)); - auto search = behaviorMap.find( std::make_pair(OriginNodeAdequacyPatchType, ExtremityNodeAdequacyPatchType)); if (search != behaviorMap.end()) @@ -82,6 +55,38 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( return leaveLocalValues; } +std::map, LinkCapacityForAdequacyPatchFirstStep> + GenerateLinkRestrictionMapForAdqFirstStep(bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) +{ + std::map, LinkCapacityForAdequacyPatchFirstStep> + behaviorMap; + + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), + (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), + (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), + (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues)); + behaviorMap.insert( + std::make_pair(std::make_pair(adqmVirtualArea, adqmVirtualArea), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmVirtualArea, adqmPhysicalAreaOutsideAdqPatch), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmVirtualArea, adqmPhysicalAreaInsideAdqPatch), leaveLocalValues)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + + return behaviorMap; +} + } // namespace AdequacyPatch } // namespace Data } // namespace Antares diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 8150dba9b8..0df6561921 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -41,15 +41,12 @@ namespace AdequacyPatch * * @param AdequacyFirstStep boolean for the first run of the optimization used by the adequacy patch * - * @param StartNodeAdequacyPatchType uint: The adq type of the node at the start of the link. + * @param OriginNodeAdequacyPatchType uint: The adq type of the node at the start of the link. * - * @param EndNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 - * towards nodes of adq type 2 - * - * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 - * towards nodes of adq type 1 + * @param behaviorMap map: map containing link capacity restrictions for every possible combination + * of adq types for node at start and node at end of the link. * * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. @@ -58,8 +55,25 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch); + std::map, LinkCapacityForAdequacyPatchFirstStep> + &behaviorMap); + +/*! + * Generates map containing all possible relations of start&end area adq patch mode taking into + * consideration user interface input options. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 + * towards nodes of adq type 2 + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 + * towards nodes of adq type 1 + * + * @return map defining link capacity restrictions is constructed according to the start&end area + * adequacy patch mode and user interface input options (first two function parameters). + */ +std::map, LinkCapacityForAdequacyPatchFirstStep> + GenerateLinkRestrictionMapForAdqFirstStep(bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); } // namespace AdequacyPatch } // namespace Data 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 ac2198e011..b3051b9f51 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -143,6 +143,12 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob int* TypeDeVariable; Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; + std::map, LinkCapacityForAdequacyPatchFirstStep> + BehaviorMap; + if (ProblemeHebdo->adqPatch) + BehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; @@ -187,9 +193,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob ProblemeHebdo->adqPatch->AdequacyFirstStep, ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - ProblemeHebdo->adqPatch - ->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); + BehaviorMap); } else SetToZeroLinkNTCForAdequacyPatchFirstStep = Data::AdequacyPatch::leaveLocalValues; From 967e72193a329583105f65b2c953cf3b11bafd2d Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 18:31:37 +0100 Subject: [PATCH 038/490] make type std::pair --- src/solver/optimisation/adequacy_patch.cpp | 6 +++--- src/solver/optimisation/adequacy_patch.h | 6 ++++-- .../optimisation/opt_gestion_des_bornes_cas_lineaire.cpp | 2 +- 3 files changed, 8 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 9f4af73a44..f453572bea 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -39,7 +39,7 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map, LinkCapacityForAdequacyPatchFirstStep> + std::map &behaviorMap) { if (AdequacyFirstStep) @@ -55,11 +55,11 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( return leaveLocalValues; } -std::map, LinkCapacityForAdequacyPatchFirstStep> +std::map GenerateLinkRestrictionMapForAdqFirstStep(bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch) { - std::map, LinkCapacityForAdequacyPatchFirstStep> + std::map behaviorMap; behaviorMap.insert(std::make_pair( diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 0df6561921..57ba346b15 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -28,6 +28,8 @@ #ifndef __SOLVER_ADEQUACY_FUNCTIONS_H__ #define __SOLVER_ADEQUACY_FUNCTIONS_H__ +typedef std::pair adqPair; + namespace Antares { namespace Data @@ -55,7 +57,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map, LinkCapacityForAdequacyPatchFirstStep> + std::map &behaviorMap); /*! @@ -71,7 +73,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( * @return map defining link capacity restrictions is constructed according to the start&end area * adequacy patch mode and user interface input options (first two function parameters). */ -std::map, LinkCapacityForAdequacyPatchFirstStep> +std::map GenerateLinkRestrictionMapForAdqFirstStep(bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch); 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 b3051b9f51..804e8bfe34 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -143,7 +143,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob int* TypeDeVariable; Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; - std::map, LinkCapacityForAdequacyPatchFirstStep> + std::map BehaviorMap; if (ProblemeHebdo->adqPatch) BehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( From 1405265963bd4952c3ac3b88d3f4b433902b16b4 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 18:44:57 +0100 Subject: [PATCH 039/490] clang format --- src/solver/optimisation/adequacy_patch.cpp | 12 +++++------- src/solver/optimisation/adequacy_patch.h | 9 ++++----- .../opt_gestion_des_bornes_cas_lineaire.cpp | 3 +-- 3 files changed, 10 insertions(+), 14 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index f453572bea..065f49e6bd 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -39,8 +39,7 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map - &behaviorMap) + std::map& behaviorMap) { if (AdequacyFirstStep) { @@ -55,12 +54,11 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( return leaveLocalValues; } -std::map - GenerateLinkRestrictionMapForAdqFirstStep(bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch) +std::map GenerateLinkRestrictionMapForAdqFirstStep( + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) { - std::map - behaviorMap; + std::map behaviorMap; behaviorMap.insert(std::make_pair( std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setToZero)); diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 57ba346b15..e9edb14762 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -57,8 +57,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( bool AdequacyFirstStep, AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map - &behaviorMap); + std::map& behaviorMap); /*! * Generates map containing all possible relations of start&end area adq patch mode taking into @@ -73,9 +72,9 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( * @return map defining link capacity restrictions is constructed according to the start&end area * adequacy patch mode and user interface input options (first two function parameters). */ -std::map - GenerateLinkRestrictionMapForAdqFirstStep(bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch); +std::map GenerateLinkRestrictionMapForAdqFirstStep( + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); } // namespace AdequacyPatch } // namespace Data 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 804e8bfe34..390285265e 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -143,8 +143,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob int* TypeDeVariable; Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; - std::map - BehaviorMap; + std::map BehaviorMap; if (ProblemeHebdo->adqPatch) BehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, From f736845f5558e32ca4cc49c726b8a2f82afe6611 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 18 Mar 2022 20:49:46 +0100 Subject: [PATCH 040/490] make setBounds(No)AdqPatch functions --- src/solver/optimisation/adequacy_patch.cpp | 63 ++++++++++++++++--- src/solver/optimisation/adequacy_patch.h | 28 +++++++-- .../opt_gestion_des_bornes_cas_lineaire.cpp | 41 ++---------- 3 files changed, 82 insertions(+), 50 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 065f49e6bd..13b4442a24 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -36,20 +36,14 @@ namespace Data namespace AdequacyPatch { AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( - bool AdequacyFirstStep, AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, std::map& behaviorMap) { - if (AdequacyFirstStep) - { - auto search = behaviorMap.find( - std::make_pair(OriginNodeAdequacyPatchType, ExtremityNodeAdequacyPatchType)); - if (search != behaviorMap.end()) - return search->second; - else - return leaveLocalValues; - } + auto search = behaviorMap.find( + std::make_pair(OriginNodeAdequacyPatchType, ExtremityNodeAdequacyPatchType)); + if (search != behaviorMap.end()) + return search->second; else return leaveLocalValues; } @@ -85,6 +79,55 @@ std::map GenerateLinkRestriction return behaviorMap; } +void setBoundsAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo, + std::map& behaviorMap) +{ + Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep + SetToZeroLinkNTCForAdequacyPatchFirstStep; + + SetToZeroLinkNTCForAdequacyPatchFirstStep + = Antares::Data::AdequacyPatch::SetNTCForAdequacyFirstStep( + ProblemeHebdo->StartAreaAdequacyPatchType[Interco], + ProblemeHebdo->EndAreaAdequacyPatchType[Interco], + behaviorMap); + + if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) + { + Xmax = 0.; + Xmin = 0.; + } + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep + == Data::AdequacyPatch::setOrigineExtremityToZero) + { + Xmax = 0.; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + } + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep + == Data::AdequacyPatch::setExtremityOrigineToZero) + { + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = 0.; + } + else + { + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + } +} + +void setBoundsNoAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco) +{ + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); +} + } // namespace AdequacyPatch } // namespace Data } // namespace Antares diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index e9edb14762..1ae6f34911 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -38,10 +38,7 @@ namespace AdequacyPatch { /*! - * Determines if a link capacity needs to be set to 0. Only changes something if used during the - * AdequacyFirstStep. - * - * @param AdequacyFirstStep boolean for the first run of the optimization used by the adequacy patch + * Determines restriction type for transmission links for first step of adequacy patch. * * @param OriginNodeAdequacyPatchType uint: The adq type of the node at the start of the link. * @@ -54,7 +51,6 @@ namespace AdequacyPatch * adq purposes. */ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( - bool AdequacyFirstStep, AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, std::map& behaviorMap); @@ -76,6 +72,28 @@ std::map GenerateLinkRestriction bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch); +/*! + * Sets link bounds for first step of adequacy patch. + * + * @return double: upper and lower link bounds. + */ +void setBoundsAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo, + std::map& behaviorMap); + +/*! + * Sets link bounds when adequacy patch is not used or when first step of adequacy patch is false. + * + * @return double: upper and lower link bounds + */ +void setBoundsNoAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco); + } // namespace AdequacyPatch } // namespace Data } // namespace Antares 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 390285265e..548a96e001 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -141,11 +141,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; - Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep - SetToZeroLinkNTCForAdequacyPatchFirstStep; - std::map BehaviorMap; - if (ProblemeHebdo->adqPatch) - BehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( + std::map AdqPatchBehaviorMap; + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) + AdqPatchBehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); @@ -185,38 +183,11 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - if (ProblemeHebdo->adqPatch) - { - SetToZeroLinkNTCForAdequacyPatchFirstStep - = Antares::Data::AdequacyPatch::SetNTCForAdequacyFirstStep( - ProblemeHebdo->adqPatch->AdequacyFirstStep, - ProblemeHebdo->StartAreaAdequacyPatchType[Interco], - ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - BehaviorMap); - } + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) + setBoundsAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo, AdqPatchBehaviorMap); else - SetToZeroLinkNTCForAdequacyPatchFirstStep = Data::AdequacyPatch::leaveLocalValues; + setBoundsNoAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco); - if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) - { - Xmax[Var] = 0.; - Xmin[Var] = 0.; - } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setOrigineExtremityToZero) - { - Xmax[Var] = 0.; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setExtremityOrigineToZero) - { - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = 0.; - } - else - { - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - } if (Math::Infinite(Xmax[Var]) == 1) { if (Math::Infinite(Xmin[Var]) == -1) From ea2576420b6f4c2a614bb6cf05ce5bedd676cfa1 Mon Sep 17 00:00:00 2001 From: rtei-pw <92968374+rtei-pw@users.noreply.github.com> Date: Sat, 19 Mar 2022 10:17:46 +0800 Subject: [PATCH 041/490] r2 review changes part 1 (#30) * review: These two ifs can be merged into one. * review: Create a new function called OPT_OptimisationHebdomadaireAdqPatch, call it here. * review: domestic unsupplied energy (comment) --- .../opt_gestion_des_bornes_cas_lineaire.cpp | 20 ++++--- src/solver/simulation/economy.cpp | 56 ++++++++++--------- .../sim_structure_probleme_economique.h | 2 +- 3 files changed, 42 insertions(+), 36 deletions(-) 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 cb89f12559..0dc2c0bed4 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -178,7 +178,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - + if (ProblemeHebdo->adqPatch) { SetToZeroLinkNTCForAdequacyPatchFirstStep @@ -196,12 +196,14 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax[Var] = 0.; Xmin[Var] = 0.; } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setOrigineExtremityToZero) + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep + == Data::AdequacyPatch::setOrigineExtremityToZero) { Xmax[Var] = 0.; Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setExtremityOrigineToZero) + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep + == Data::AdequacyPatch::setExtremityOrigineToZero) { Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin[Var] = 0.; @@ -432,12 +434,12 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax[Var] = 0.; // adq patch: update ENS <= DENS in 2nd run - if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false) - if (ProblemeHebdo->AreaAdequacyPatchMode[Pays] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - Xmax[Var] = min( - Xmax[Var], - ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false + && ProblemeHebdo->AreaAdequacyPatchMode[Pays] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + Xmax[Var] + = min(Xmax[Var], + ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo] diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 30f48e7f37..9ad9c81ed1 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -112,6 +112,34 @@ bool Economy::simulationBegin() return true; } +void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, + Variable::State& state, + uint numSpace, + int hourInTheYear) +{ + pProblemeHebdo->adqPatch->AdequacyFirstStep = true; + OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); + pProblemeHebdo->adqPatch->AdequacyFirstStep = false; + + for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) + { + if (pProblemeHebdo->AreaAdequacyPatchMode[pays] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + memcpy(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, + pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, + pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); + else + memset(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, + 0, + pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); + } + + // TODO check if we need to cut SIM_RenseignementProblemeHebdo and just pick out the + // part that we need + ::SIM_RenseignementProblemeHebdo(*pProblemeHebdo, state, numSpace, hourInTheYear); + OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); +} + bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, @@ -148,32 +176,8 @@ bool Economy::year(Progression::Task& progression, { if (pProblemesHebdo[numSpace]->adqPatch) { - pProblemesHebdo[numSpace]->adqPatch->AdequacyFirstStep = true; - OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); - pProblemesHebdo[numSpace]->adqPatch->AdequacyFirstStep = false; - - for (int pays = 0; pays < pProblemesHebdo[numSpace]->NombreDePays; ++pays) - { - if (pProblemesHebdo[numSpace]->AreaAdequacyPatchMode[pays] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - memcpy( - pProblemesHebdo[numSpace]->ResultatsHoraires[pays]->ValeursHorairesDENS, - pProblemesHebdo[numSpace] - ->ResultatsHoraires[pays] - ->ValeursHorairesDeDefaillancePositive, - pProblemesHebdo[numSpace]->NombreDePasDeTemps * sizeof(double)); - else - memset( - pProblemesHebdo[numSpace]->ResultatsHoraires[pays]->ValeursHorairesDENS, - 0, - pProblemesHebdo[numSpace]->NombreDePasDeTemps * sizeof(double)); - } - - // TODO check if we need to cut SIM_RenseignementProblemeHebdo and just pick out the - // part that we need - ::SIM_RenseignementProblemeHebdo( - *pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); - OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + OPT_OptimisationHebdomadaireAdqPatch( + pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); } else { diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 1f4a65b650..327e4a6478 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -426,7 +426,7 @@ typedef struct typedef struct { double* ValeursHorairesDeDefaillancePositive; - double* ValeursHorairesDENS; // adq patch DENS + double* ValeursHorairesDENS; // adq patch domestic unsupplied energy double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; From 5b5dee27386880b8ffbea45e7ca1eec4d8265d72 Mon Sep 17 00:00:00 2001 From: milos Date: Sat, 19 Mar 2022 22:57:08 +0100 Subject: [PATCH 042/490] adq-patch is only for studyMode == economy --- src/libs/antares/exception/LoadingError.cpp | 5 +++++ src/libs/antares/exception/LoadingError.hpp | 7 +++++++ src/solver/application.cpp | 12 ++++++++++++ 3 files changed, 24 insertions(+) diff --git a/src/libs/antares/exception/LoadingError.cpp b/src/libs/antares/exception/LoadingError.cpp index 82ba825ca3..1d6982dd7c 100644 --- a/src/libs/antares/exception/LoadingError.cpp +++ b/src/libs/antares/exception/LoadingError.cpp @@ -123,5 +123,10 @@ CommandLineArguments::CommandLineArguments(uint errors) : { } +IncompatibleStudyModeForAdqPatch::IncompatibleStudyModeForAdqPatch() : + LoadingError("Adequacy Patch can only be used with Economy Simulation Mode") +{ +} + } // namespace Error } // namespace Antares diff --git a/src/libs/antares/exception/LoadingError.hpp b/src/libs/antares/exception/LoadingError.hpp index 2181cef0aa..844d5b99b7 100644 --- a/src/libs/antares/exception/LoadingError.hpp +++ b/src/libs/antares/exception/LoadingError.hpp @@ -166,5 +166,12 @@ class CommandLineArguments : public LoadingError public: explicit CommandLineArguments(uint errors); }; + +class IncompatibleStudyModeForAdqPatch : public LoadingError +{ +public: + IncompatibleStudyModeForAdqPatch(); +}; + } // namespace Error } // namespace Antares diff --git a/src/solver/application.cpp b/src/solver/application.cpp index e3b212fd3d..1b4cb0f884 100644 --- a/src/solver/application.cpp +++ b/src/solver/application.cpp @@ -84,6 +84,16 @@ void checkSimplexRangeHydroHeuristic(Antares::Data::SimplexOptimization optRange } } +// Adequacy Patch can only be used with Economy Study/Simulation Mode. +void checkAdqPatchStudyModeEconomuOnly(const bool adqPatchOn, + const Antares::Data::StudyMode studyMode) +{ + if ((studyMode != Antares::Data::StudyMode::stdmEconomy) && adqPatchOn) + { + throw Error::IncompatibleStudyModeForAdqPatch(); + } +} + void checkMinStablePower(bool tsGenThermal, const Antares::Data::AreaList& areas) { if (tsGenThermal) @@ -239,6 +249,8 @@ void Application::prepare(int argc, char* argv[]) checkSimplexRangeHydroHeuristic(pParameters->simplexOptimizationRange, pStudy->areas); + checkAdqPatchStudyModeEconomuOnly(pParameters->include.adequacyPatch, pParameters->mode); + bool tsGenThermal = (0 != (pStudy->parameters.timeSeriesToGenerate & Antares::Data::TimeSeries::timeSeriesThermal)); From 8d05c1831ae6ad420362aebcfda947b3fb565ddd Mon Sep 17 00:00:00 2001 From: milos Date: Mon, 21 Mar 2022 08:47:45 +0100 Subject: [PATCH 043/490] move behaviorMap to AdequacyPatchParameters struct --- src/solver/optimisation/adequacy_patch.cpp | 6 +++--- src/solver/optimisation/adequacy_patch.h | 16 ++++++---------- .../opt_gestion_des_bornes_cas_lineaire.cpp | 9 ++------- src/solver/simulation/economy.cpp | 4 ++++ src/solver/simulation/sim_calcul_economique.cpp | 1 + .../sim_structure_probleme_economique.h | 3 +++ 6 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 13b4442a24..c9c5d8ac6a 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -35,6 +35,7 @@ namespace Data { namespace AdequacyPatch { + AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, @@ -83,8 +84,7 @@ void setBoundsAdqPatch(double& Xmax, double& Xmin, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco, - PROBLEME_HEBDO* ProblemeHebdo, - std::map& behaviorMap) + PROBLEME_HEBDO* ProblemeHebdo) { Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; @@ -93,7 +93,7 @@ void setBoundsAdqPatch(double& Xmax, = Antares::Data::AdequacyPatch::SetNTCForAdequacyFirstStep( ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], - behaviorMap); + ProblemeHebdo->adqPatch->AdqBehaviorMap); if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) { diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 1ae6f34911..2379f25d8b 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -28,8 +28,6 @@ #ifndef __SOLVER_ADEQUACY_FUNCTIONS_H__ #define __SOLVER_ADEQUACY_FUNCTIONS_H__ -typedef std::pair adqPair; - namespace Antares { namespace Data @@ -44,8 +42,8 @@ namespace AdequacyPatch * * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param behaviorMap map: map containing link capacity restrictions for every possible combination - * of adq types for node at start and node at end of the link. + * @param behaviorMap std::map: map containing link capacity restrictions for every possible + * combination of adq types for node at start and node at end of the link. * * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. @@ -65,8 +63,9 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 * towards nodes of adq type 1 * - * @return map defining link capacity restrictions is constructed according to the start&end area - * adequacy patch mode and user interface input options (first two function parameters). + * @return std::map: map defining link capacity restrictions is constructed according to the + * start&end area adequacy patch mode and user interface input options (first two function + * parameters). */ std::map GenerateLinkRestrictionMapForAdqFirstStep( bool SetToZero12LinksForAdequacyPatch, @@ -75,19 +74,16 @@ std::map GenerateLinkRestriction /*! * Sets link bounds for first step of adequacy patch. * - * @return double: upper and lower link bounds. */ void setBoundsAdqPatch(double& Xmax, double& Xmin, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco, - PROBLEME_HEBDO* ProblemeHebdo, - std::map& behaviorMap); + PROBLEME_HEBDO* ProblemeHebdo); /*! * Sets link bounds when adequacy patch is not used or when first step of adequacy patch is false. * - * @return double: upper and lower link bounds */ void setBoundsNoAdqPatch(double& Xmax, double& Xmin, 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 35ce66d5c9..c48f490067 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -141,12 +141,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; - std::map AdqPatchBehaviorMap; - if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) - AdqPatchBehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); - + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PALIERS_THERMIQUES* PaliersThermiquesDuPays; @@ -184,7 +179,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) - setBoundsAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo, AdqPatchBehaviorMap); + setBoundsAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); else setBoundsNoAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco); diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 9ad9c81ed1..a4c1b1466c 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -35,6 +35,7 @@ #include "simulation.h" #include "../optimisation/opt_fonctions.h" #include "common-eco-adq.h" +#include "../optimisation/adequacy_patch.h" using namespace Yuni; @@ -118,6 +119,9 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, int hourInTheYear) { pProblemeHebdo->adqPatch->AdequacyFirstStep = true; + pProblemeHebdo->adqPatch->AdqBehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( + pProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, + pProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); pProblemeHebdo->adqPatch->AdequacyFirstStep = false; diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 8a2a6c650c..66b66c93f4 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -67,6 +67,7 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, { problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); // AdequacyFirstStep will be initialized during the economy solve + // AdqBehaviorMap will be initialized during the economy solve problem.adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq = parameters.setToZero12LinksForAdequacyPatch; problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index c76590389c..d4bee6049b 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -37,8 +37,10 @@ #include #include +#include using namespace Antares::Data::AdequacyPatch; +typedef std::pair adqPair; typedef struct { @@ -478,6 +480,7 @@ struct AdequacyPatchParameters bool AdequacyFirstStep; bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; + std::map AdqBehaviorMap; }; struct PROBLEME_HEBDO From ce995e34e4203485846b6625bd2a881d5e7f6696 Mon Sep 17 00:00:00 2001 From: "Hugo ANTOINE (RTEi)" Date: Tue, 22 Mar 2022 23:07:51 +0100 Subject: [PATCH 044/490] attempt at making map creation clearer --- src/solver/optimisation/adequacy_patch.cpp | 34 +++++++++++++++------- 1 file changed, 24 insertions(+), 10 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index c9c5d8ac6a..9fccb0592a 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -54,18 +54,10 @@ std::map GenerateLinkRestriction bool SetToZero11LinksForAdequacyPatch) { std::map behaviorMap; - + // No transfer of energy possible between physical areas part of the adequacy patch behaviorMap.insert(std::make_pair( std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), - (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), - (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), - (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues)); + // all else remains the same behaviorMap.insert( std::make_pair(std::make_pair(adqmVirtualArea, adqmVirtualArea), leaveLocalValues)); behaviorMap.insert(std::make_pair( @@ -76,6 +68,28 @@ std::map GenerateLinkRestriction std::make_pair(adqmVirtualArea, adqmPhysicalAreaInsideAdqPatch), leaveLocalValues)); behaviorMap.insert(std::make_pair( std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + // except if the options SetToZero12LinksForAdequacyPatch and/or SetToZero11LinksForAdequacyPatch are + if (SetToZero12LinksForAdequacyPatch){ + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), setToZero)); + } + else{ + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setExtremityOrigineToZero)); + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), setOrigineExtremityToZero)); + } + + if (SetToZero11LinksForAdequacyPatch){ + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), setToZero)); + } + else { + behaviorMap.insert(std::make_pair( + std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), leaveLocalValues)); + } return behaviorMap; } From c1293057796d030a1b2374bd975002bb74f29672 Mon Sep 17 00:00:00 2001 From: "Hugo ANTOINE (RTEi)" Date: Tue, 22 Mar 2022 23:37:24 +0100 Subject: [PATCH 045/490] using just the Antares::Data namespace --- src/solver/optimisation/adequacy_patch.cpp | 50 +++++++++------------- src/solver/optimisation/adequacy_patch.h | 10 +---- 2 files changed, 22 insertions(+), 38 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 9fccb0592a..92c2e93912 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -29,17 +29,12 @@ #include "adequacy_patch.h" #include -namespace Antares -{ -namespace Data -{ -namespace AdequacyPatch -{ +using namespace Antares::Data; AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map& behaviorMap) + std::map& behaviorMap) { auto search = behaviorMap.find( std::make_pair(OriginNodeAdequacyPatchType, ExtremityNodeAdequacyPatchType)); @@ -49,46 +44,46 @@ AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( return leaveLocalValues; } -std::map GenerateLinkRestrictionMapForAdqFirstStep( +std::map GenerateLinkRestrictionMapForAdqFirstStep( bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch) { - std::map behaviorMap; + std::map behaviorMap; // No transfer of energy possible between physical areas part of the adequacy patch behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setToZero)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::setToZero)); // all else remains the same behaviorMap.insert( - std::make_pair(std::make_pair(adqmVirtualArea, adqmVirtualArea), leaveLocalValues)); + std::make_pair(std::make_pair(AdequacyPatch::adqmVirtualArea, AdequacyPatch::adqmVirtualArea), AdequacyPatch::leaveLocalValues)); behaviorMap.insert(std::make_pair( - std::make_pair(adqmVirtualArea, adqmPhysicalAreaOutsideAdqPatch), leaveLocalValues)); + std::make_pair(AdequacyPatch::adqmVirtualArea, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::leaveLocalValues)); behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmVirtualArea), AdequacyPatch::leaveLocalValues)); behaviorMap.insert(std::make_pair( - std::make_pair(adqmVirtualArea, adqmPhysicalAreaInsideAdqPatch), leaveLocalValues)); + std::make_pair(AdequacyPatch::adqmVirtualArea, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::leaveLocalValues)); behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmVirtualArea), leaveLocalValues)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmVirtualArea), AdequacyPatch::leaveLocalValues)); // except if the options SetToZero12LinksForAdequacyPatch and/or SetToZero11LinksForAdequacyPatch are if (SetToZero12LinksForAdequacyPatch){ behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setToZero)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::setToZero)); behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), setToZero)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::setToZero)); } else{ behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaInsideAdqPatch), setExtremityOrigineToZero)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::setExtremityOrigineToZero)); behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaInsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), setOrigineExtremityToZero)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::setOrigineExtremityToZero)); } if (SetToZero11LinksForAdequacyPatch){ behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), setToZero)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::setToZero)); } else { behaviorMap.insert(std::make_pair( - std::make_pair(adqmPhysicalAreaOutsideAdqPatch, adqmPhysicalAreaOutsideAdqPatch), leaveLocalValues)); + std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::leaveLocalValues)); } return behaviorMap; @@ -100,28 +95,28 @@ void setBoundsAdqPatch(double& Xmax, const int Interco, PROBLEME_HEBDO* ProblemeHebdo) { - Data::AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep + AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; SetToZeroLinkNTCForAdequacyPatchFirstStep - = Antares::Data::AdequacyPatch::SetNTCForAdequacyFirstStep( + = SetNTCForAdequacyFirstStep( ProblemeHebdo->StartAreaAdequacyPatchType[Interco], ProblemeHebdo->EndAreaAdequacyPatchType[Interco], ProblemeHebdo->adqPatch->AdqBehaviorMap); - if (SetToZeroLinkNTCForAdequacyPatchFirstStep == Data::AdequacyPatch::setToZero) + if (SetToZeroLinkNTCForAdequacyPatchFirstStep == AdequacyPatch::setToZero) { Xmax = 0.; Xmin = 0.; } else if (SetToZeroLinkNTCForAdequacyPatchFirstStep - == Data::AdequacyPatch::setOrigineExtremityToZero) + == AdequacyPatch::setOrigineExtremityToZero) { Xmax = 0.; Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } else if (SetToZeroLinkNTCForAdequacyPatchFirstStep - == Data::AdequacyPatch::setExtremityOrigineToZero) + == AdequacyPatch::setExtremityOrigineToZero) { Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin = 0.; @@ -142,6 +137,3 @@ void setBoundsNoAdqPatch(double& Xmax, Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } -} // namespace AdequacyPatch -} // namespace Data -} // namespace Antares diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 2379f25d8b..2c3032a6d6 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -28,12 +28,7 @@ #ifndef __SOLVER_ADEQUACY_FUNCTIONS_H__ #define __SOLVER_ADEQUACY_FUNCTIONS_H__ -namespace Antares -{ -namespace Data -{ -namespace AdequacyPatch -{ +using namespace Antares::Data; /*! * Determines restriction type for transmission links for first step of adequacy patch. @@ -90,8 +85,5 @@ void setBoundsNoAdqPatch(double& Xmax, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco); -} // namespace AdequacyPatch -} // namespace Data -} // namespace Antares #endif /* __SOLVER_ADEQUACY_FUNCTIONS_H__ */ From ecb812d7f3cf01943b2ae988cfd5259f50d5ffa7 Mon Sep 17 00:00:00 2001 From: rtei-pw <92968374+rtei-pw@users.noreply.github.com> Date: Sat, 26 Mar 2022 14:47:50 +0800 Subject: [PATCH 046/490] adq runtime data (#35) * adq runtime data * conflict --- src/solver/optimisation/adequacy_patch.cpp | 4 +-- .../opt_gestion_des_bornes_cas_lineaire.cpp | 2 +- src/solver/simulation/economy.cpp | 2 +- .../simulation/sim_alloc_probleme_hebdo.cpp | 11 ------- .../simulation/sim_calcul_economique.cpp | 7 +++-- .../sim_structure_probleme_economique.h | 29 ++++++++++++++++--- 6 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 92c2e93912..fb3ad69d8b 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -100,8 +100,8 @@ void setBoundsAdqPatch(double& Xmax, SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( - ProblemeHebdo->StartAreaAdequacyPatchType[Interco], - ProblemeHebdo->EndAreaAdequacyPatchType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], ProblemeHebdo->adqPatch->AdqBehaviorMap); if (SetToZeroLinkNTCForAdequacyPatchFirstStep == AdequacyPatch::setToZero) 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 c48f490067..608b4efef6 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -405,7 +405,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob // adq patch: update ENS <= DENS in 2nd run if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false - && ProblemeHebdo->AreaAdequacyPatchMode[Pays] + && ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Pays] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) Xmax[Var] = min(Xmax[Var], diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index a4c1b1466c..7a5dcb4dca 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -127,7 +127,7 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) { - if (pProblemeHebdo->AreaAdequacyPatchMode[pays] + if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) memcpy(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index 3c26068328..d08b5f778f 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -59,15 +59,8 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps problem.BruitSurCoutHydraulique[p] = (double*)MemAlloc(8784 * sizeof(double)); problem.NomsDesPays = (const char**)MemAlloc(nbPays * sizeof(char*)); - problem.AreaAdequacyPatchMode - = (Data::AdequacyPatch::AdequacyPatchMode*)MemAlloc(nbPays * sizeof(int)); - problem.PaysExtremiteDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); problem.PaysOrigineDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); - problem.StartAreaAdequacyPatchType - = (Data::AdequacyPatch::AdequacyPatchMode*)MemAlloc(linkCount * sizeof(int)); - problem.EndAreaAdequacyPatchType - = (Data::AdequacyPatch::AdequacyPatchMode*)MemAlloc(linkCount * sizeof(int)); problem.CoutDeTransport = (COUTS_DE_TRANSPORT**)MemAlloc(linkCount * sizeof(void*)); problem.IndexDebutIntercoOrigine = (int*)MemAlloc(nbPays * sizeof(int)); problem.IndexDebutIntercoExtremite = (int*)MemAlloc(nbPays * sizeof(int)); @@ -596,12 +589,8 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) uint nbPays = study.areas.size(); MemFree(problem.NomsDesPays); - MemFree(problem.AreaAdequacyPatchMode); - MemFree(problem.PaysExtremiteDeLInterconnexion); MemFree(problem.PaysOrigineDeLInterconnexion); - MemFree(problem.StartAreaAdequacyPatchType); - MemFree(problem.EndAreaAdequacyPatchType); MemFree(problem.IndexDebutIntercoOrigine); MemFree(problem.IndexDebutIntercoExtremite); MemFree(problem.IndexSuivantIntercoOrigine); diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 66b66c93f4..dcb127adfe 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -74,6 +74,10 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, = parameters.setToZero11LinksForAdequacyPatch; } + if (parameters.include.adequacyPatch){ + problem.adequacyPatchRuntimeData.initialize(study); + } + problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP) ? OUI_ANTARES @@ -122,7 +126,6 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, auto& area = *(study.areas[i]); problem.NomsDesPays[i] = area.id.c_str(); - problem.AreaAdequacyPatchMode[i] = area.adequacyPatchMode; problem.CoutDeDefaillancePositive[i] = area.thermal.unsuppliedEnergyCost; @@ -196,9 +199,7 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, { auto& link = *(study.runtime->areaLink[i]); problem.PaysOrigineDeLInterconnexion[i] = link.from->index; - problem.StartAreaAdequacyPatchType[i] = link.from->adequacyPatchMode; problem.PaysExtremiteDeLInterconnexion[i] = link.with->index; - problem.EndAreaAdequacyPatchType[i] = link.with->adequacyPatchMode; } for (uint i = 0; i < study.runtime->bindingConstraintCount; ++i) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index d4bee6049b..cff0640691 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -31,6 +31,7 @@ #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" #define GROSSES_VARIABLES NON_ANTARES #define COEFF_GROSSES_VARIABLES 100 @@ -322,6 +323,28 @@ typedef struct constraint on final level*/ } ENERGIES_ET_PUISSANCES_HYDRAULIQUES; +class AdequacyPatchRuntimeData +{ +public: + std::vector areaMode; + std::vector originAreaType; + std::vector extremityAreaType; + void initialize(Antares::Data::Study& study) + { + for (uint i = 0; i != study.areas.size(); ++i) + { + auto& area = *(study.areas[i]); + areaMode.push_back(area.adequacyPatchMode); + } + for (uint i = 0; i < study.runtime->interconnectionsCount; ++i) + { + auto& link = *(study.runtime->areaLink[i]); + originAreaType.push_back(link.from->adequacyPatchMode); + extremityAreaType.push_back(link.with->adequacyPatchMode); + } + } +}; + class computeTimeStepLevel { private: @@ -492,14 +515,11 @@ struct PROBLEME_HEBDO char OptimisationAvecCoutsDeDemarrage; int NombreDePays; const char** NomsDesPays; - AdequacyPatchMode* AreaAdequacyPatchMode; int NombreDePaliersThermiques; int NombreDInterconnexions; int* PaysOrigineDeLInterconnexion; int* PaysExtremiteDeLInterconnexion; - AdequacyPatchMode* StartAreaAdequacyPatchType; - AdequacyPatchMode* EndAreaAdequacyPatchType; COUTS_DE_TRANSPORT** CoutDeTransport; VALEURS_DE_NTC_ET_RESISTANCES** ValeursDeNTC; @@ -591,7 +611,8 @@ struct PROBLEME_HEBDO /* Adequacy Patch */ std::unique_ptr adqPatch = nullptr; - + AdequacyPatchRuntimeData adequacyPatchRuntimeData; + optimizationStatistics optimizationStatistics_object; /* Hydro management */ double* CoefficientEcretementPMaxHydraulique; From 9bcd5d1938a6498aa8e623842ab57d796d0c3450 Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Mon, 28 Mar 2022 07:45:20 +0200 Subject: [PATCH 047/490] RTE Comment implementation 3 (#34) * typo Economy * add comment to explain type 1 and type 2 for adq * using namespace AdequacyPatch inside adq_patch.cpp * if there is no area in the adq-patch throw error * divide to smaller functions SetNTCForAdqFirstStep * clang * check that adq patch is on in error handling * bug fix --- src/libs/antares/exception/LoadingError.cpp | 5 + src/libs/antares/exception/LoadingError.hpp | 6 + src/solver/application.cpp | 25 +++- src/solver/optimisation/adequacy_patch.cpp | 133 +++++++++--------- src/solver/optimisation/adequacy_patch.h | 52 ++++--- src/solver/simulation/economy.cpp | 4 - .../sim_structure_probleme_economique.h | 3 - 7 files changed, 139 insertions(+), 89 deletions(-) diff --git a/src/libs/antares/exception/LoadingError.cpp b/src/libs/antares/exception/LoadingError.cpp index 1d6982dd7c..8fc9d1fe75 100644 --- a/src/libs/antares/exception/LoadingError.cpp +++ b/src/libs/antares/exception/LoadingError.cpp @@ -128,5 +128,10 @@ IncompatibleStudyModeForAdqPatch::IncompatibleStudyModeForAdqPatch() : { } +NoAreaInsideAdqPatchMode::NoAreaInsideAdqPatchMode() : + LoadingError("Minimum one area must be inside adequacy patch mode when using adequacy patch") +{ +} + } // namespace Error } // namespace Antares diff --git a/src/libs/antares/exception/LoadingError.hpp b/src/libs/antares/exception/LoadingError.hpp index 844d5b99b7..44d269b029 100644 --- a/src/libs/antares/exception/LoadingError.hpp +++ b/src/libs/antares/exception/LoadingError.hpp @@ -173,5 +173,11 @@ class IncompatibleStudyModeForAdqPatch : public LoadingError IncompatibleStudyModeForAdqPatch(); }; +class NoAreaInsideAdqPatchMode : public LoadingError +{ +public: + NoAreaInsideAdqPatchMode(); +}; + } // namespace Error } // namespace Antares diff --git a/src/solver/application.cpp b/src/solver/application.cpp index 1b4cb0f884..1218221aa5 100644 --- a/src/solver/application.cpp +++ b/src/solver/application.cpp @@ -85,7 +85,7 @@ void checkSimplexRangeHydroHeuristic(Antares::Data::SimplexOptimization optRange } // Adequacy Patch can only be used with Economy Study/Simulation Mode. -void checkAdqPatchStudyModeEconomuOnly(const bool adqPatchOn, +void checkAdqPatchStudyModeEconomyOnly(const bool adqPatchOn, const Antares::Data::StudyMode studyMode) { if ((studyMode != Antares::Data::StudyMode::stdmEconomy) && adqPatchOn) @@ -93,6 +93,26 @@ void checkAdqPatchStudyModeEconomuOnly(const bool adqPatchOn, throw Error::IncompatibleStudyModeForAdqPatch(); } } +// When Adequacy Patch is on at least one area must be inside Adequacy patch mode. +void checkAdqPatchContainsAdqPatchArea(const bool adqPatchOn, const Antares::Data::AreaList& areas) +{ + if (adqPatchOn) + { + bool containsAdqArea = false; + for (uint i = 0; i < areas.size(); ++i) + { + const auto& area = *(areas.byIndex[i]); + if (area.adequacyPatchMode + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + containsAdqArea = true; + break; + } + } + if (!containsAdqArea) + throw Error::NoAreaInsideAdqPatchMode(); + } +} void checkMinStablePower(bool tsGenThermal, const Antares::Data::AreaList& areas) { @@ -249,7 +269,8 @@ void Application::prepare(int argc, char* argv[]) checkSimplexRangeHydroHeuristic(pParameters->simplexOptimizationRange, pStudy->areas); - checkAdqPatchStudyModeEconomuOnly(pParameters->include.adequacyPatch, pParameters->mode); + checkAdqPatchStudyModeEconomyOnly(pParameters->include.adequacyPatch, pParameters->mode); + checkAdqPatchContainsAdqPatchArea(pParameters->include.adequacyPatch, pStudy->areas); bool tsGenThermal = (0 != (pStudy->parameters.timeSeriesToGenerate diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index fb3ad69d8b..8aa7914c07 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -27,66 +27,77 @@ #include "../simulation/simulation.h" #include "adequacy_patch.h" -#include -using namespace Antares::Data; +using namespace Antares::Data::AdequacyPatch; -AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( - AdequacyPatch::AdequacyPatchMode OriginNodeAdequacyPatchType, - AdequacyPatch::AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map& behaviorMap) +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) { - auto search = behaviorMap.find( - std::make_pair(OriginNodeAdequacyPatchType, ExtremityNodeAdequacyPatchType)); - if (search != behaviorMap.end()) - return search->second; - else - return leaveLocalValues; + LinkCapacityForAdequacyPatchFirstStep returnNTC; + + switch (OriginNodeAdequacyPatchType) + { + case adqmPhysicalAreaInsideAdqPatch: + returnNTC = SetNTCForAdequacyFirstStepOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, + SetToZero12LinksForAdequacyPatch); + break; + case adqmPhysicalAreaOutsideAdqPatch: + returnNTC + = SetNTCForAdequacyFirstStepOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, + SetToZero12LinksForAdequacyPatch, + SetToZero11LinksForAdequacyPatch); + break; + default: + returnNTC = leaveLocalValues; + break; + } + return returnNTC; +} + +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch) +{ + LinkCapacityForAdequacyPatchFirstStep returnNTC; + + switch (ExtremityNodeAdequacyPatchType) + { + case adqmPhysicalAreaInsideAdqPatch: + returnNTC = setToZero; + break; + case adqmPhysicalAreaOutsideAdqPatch: + returnNTC = (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero; + break; + default: + returnNTC = leaveLocalValues; + break; + } + return returnNTC; } -std::map GenerateLinkRestrictionMapForAdqFirstStep( +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch) { - std::map behaviorMap; - // No transfer of energy possible between physical areas part of the adequacy patch - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::setToZero)); - // all else remains the same - behaviorMap.insert( - std::make_pair(std::make_pair(AdequacyPatch::adqmVirtualArea, AdequacyPatch::adqmVirtualArea), AdequacyPatch::leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmVirtualArea, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmVirtualArea), AdequacyPatch::leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmVirtualArea, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::leaveLocalValues)); - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmVirtualArea), AdequacyPatch::leaveLocalValues)); - // except if the options SetToZero12LinksForAdequacyPatch and/or SetToZero11LinksForAdequacyPatch are - if (SetToZero12LinksForAdequacyPatch){ - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::setToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::setToZero)); - } - else{ - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaInsideAdqPatch), AdequacyPatch::setExtremityOrigineToZero)); - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaInsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::setOrigineExtremityToZero)); - } + LinkCapacityForAdequacyPatchFirstStep returnNTC; - if (SetToZero11LinksForAdequacyPatch){ - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::setToZero)); - } - else { - behaviorMap.insert(std::make_pair( - std::make_pair(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch, AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), AdequacyPatch::leaveLocalValues)); + switch (ExtremityNodeAdequacyPatchType) + { + case adqmPhysicalAreaInsideAdqPatch: + returnNTC = (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero; + break; + case adqmPhysicalAreaOutsideAdqPatch: + returnNTC = (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues; + break; + default: + returnNTC = leaveLocalValues; + break; } - - return behaviorMap; + return returnNTC; } void setBoundsAdqPatch(double& Xmax, @@ -95,28 +106,25 @@ void setBoundsAdqPatch(double& Xmax, const int Interco, PROBLEME_HEBDO* ProblemeHebdo) { - AdequacyPatch::LinkCapacityForAdequacyPatchFirstStep - SetToZeroLinkNTCForAdequacyPatchFirstStep; + LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; - SetToZeroLinkNTCForAdequacyPatchFirstStep - = SetNTCForAdequacyFirstStep( - ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], - ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], - ProblemeHebdo->adqPatch->AdqBehaviorMap); + SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( + ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); - if (SetToZeroLinkNTCForAdequacyPatchFirstStep == AdequacyPatch::setToZero) + if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setToZero) { Xmax = 0.; Xmin = 0.; } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep - == AdequacyPatch::setOrigineExtremityToZero) + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setOrigineExtremityToZero) { Xmax = 0.; Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep - == AdequacyPatch::setExtremityOrigineToZero) + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setExtremityOrigineToZero) { Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin = 0.; @@ -136,4 +144,3 @@ void setBoundsNoAdqPatch(double& Xmax, Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } - diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 2c3032a6d6..6df2ab802a 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -37,8 +37,11 @@ using namespace Antares::Data; * * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param behaviorMap std::map: map containing link capacity restrictions for every possible - * combination of adq types for node at start and node at end of the link. + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * (type 1). * * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. @@ -46,44 +49,59 @@ using namespace Antares::Data; LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, - std::map& behaviorMap); + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); + +/*! + * Determines restriction type for transmission links for first step of adequacy patch, when start + * node is inside adq path (type 2). + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch); /*! - * Generates map containing all possible relations of start&end area adq patch mode taking into - * consideration user interface input options. + * Determines restriction type for transmission links for first step of adequacy patch, when start + * node is outside adq path (type 1). + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 - * towards nodes of adq type 2 + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). * - * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links from nodes of adq type 1 - * towards nodes of adq type 1 + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * (type 1). * - * @return std::map: map defining link capacity restrictions is constructed according to the - * start&end area adequacy patch mode and user interface input options (first two function - * parameters). + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. */ -std::map GenerateLinkRestrictionMapForAdqFirstStep( +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool SetToZero12LinksForAdequacyPatch, bool SetToZero11LinksForAdequacyPatch); /*! * Sets link bounds for first step of adequacy patch. - * */ void setBoundsAdqPatch(double& Xmax, double& Xmin, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco, PROBLEME_HEBDO* ProblemeHebdo); - /*! * Sets link bounds when adequacy patch is not used or when first step of adequacy patch is false. - * */ void setBoundsNoAdqPatch(double& Xmax, double& Xmin, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco); - #endif /* __SOLVER_ADEQUACY_FUNCTIONS_H__ */ diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 7a5dcb4dca..b37f3dd7a9 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -35,7 +35,6 @@ #include "simulation.h" #include "../optimisation/opt_fonctions.h" #include "common-eco-adq.h" -#include "../optimisation/adequacy_patch.h" using namespace Yuni; @@ -119,9 +118,6 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, int hourInTheYear) { pProblemeHebdo->adqPatch->AdequacyFirstStep = true; - pProblemeHebdo->adqPatch->AdqBehaviorMap = GenerateLinkRestrictionMapForAdqFirstStep( - pProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, - pProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); pProblemeHebdo->adqPatch->AdequacyFirstStep = false; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index cff0640691..e915e28171 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -38,10 +38,8 @@ #include #include -#include using namespace Antares::Data::AdequacyPatch; -typedef std::pair adqPair; typedef struct { @@ -503,7 +501,6 @@ struct AdequacyPatchParameters bool AdequacyFirstStep; bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; - std::map AdqBehaviorMap; }; struct PROBLEME_HEBDO From 42b722aa30a576a85d42a56491c9a412d440590c Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 7 Apr 2022 11:33:44 +0200 Subject: [PATCH 048/490] transfer adq options to new tab --- docs/reference-guide/1-reference-guide.md | 2 + .../simulator/application/main/internal-ids.h | 1 + src/ui/simulator/application/main/main.cpp | 2 + src/ui/simulator/application/main/main.h | 2 + src/ui/simulator/application/main/menu.cpp | 5 + src/ui/simulator/application/main/options.cpp | 8 + src/ui/simulator/cmake/windows-options.cmake | 2 + .../options/adequacy-patch/adequacyPatch.cpp | 444 ++++++++++++++++++ .../options/adequacy-patch/adequacyPatch.h | 97 ++++ 9 files changed, 563 insertions(+) create mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp create mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h diff --git a/docs/reference-guide/1-reference-guide.md b/docs/reference-guide/1-reference-guide.md index 36303e7a85..625134b2ba 100644 --- a/docs/reference-guide/1-reference-guide.md +++ b/docs/reference-guide/1-reference-guide.md @@ -366,6 +366,8 @@ 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}}}$$ +- **Adequacy Patch** + - **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. diff --git a/src/ui/simulator/application/main/internal-ids.h b/src/ui/simulator/application/main/internal-ids.h index d1d0f1a476..52bbc4d7b9 100644 --- a/src/ui/simulator/application/main/internal-ids.h +++ b/src/ui/simulator/application/main/internal-ids.h @@ -132,6 +132,7 @@ enum MenusID mnIDOptionConfigureDistricts, mnIDOptionConfigureMCScenarioBuilder, mnIDOptionConfigureMCScenarioPlaylist, + mnIDOptionConfigureAdequacyPatch, mnIDOptionOptimizationPrefs, mnIDOptionAdvanced, //@} diff --git a/src/ui/simulator/application/main/main.cpp b/src/ui/simulator/application/main/main.cpp index 2786b94079..ce02d6161e 100644 --- a/src/ui/simulator/application/main/main.cpp +++ b/src/ui/simulator/application/main/main.cpp @@ -157,6 +157,7 @@ EVT_MENU(mnIDOptionConfigureLinksTrimming, ApplWnd::evtOnOptionsSelectLinksTrimm EVT_MENU(mnIDOptionConfigureDistricts, ApplWnd::evtOnOptionsDistricts) EVT_MENU(mnIDOptionConfigureMCScenarioPlaylist, ApplWnd::evtOnOptionsMCPlaylist) EVT_MENU(mnIDOptionConfigureMCScenarioBuilder, ApplWnd::evtOnOptionsMCScenarioBuilder) +EVT_MENU(mnIDOptionConfigureAdequacyPatch, ApplWnd::evtOnOptionsAdequacyPatch) EVT_MENU(mnIDOptionOptimizationPrefs, ApplWnd::evtOnOptionsOptimizationPrefs) EVT_MENU(mnIDOptionAdvanced, ApplWnd::evtOnOptionsAdvanced) @@ -514,6 +515,7 @@ void ApplWnd::evtOnUpdateGUIAfterStudyIO(bool opened) // Options EnableItem(menu, mnIDOptionConfigureMCScenarioBuilder, opened); EnableItem(menu, mnIDOptionConfigureMCScenarioPlaylist, opened); + EnableItem(menu, mnIDOptionConfigureAdequacyPatch, opened); EnableItem(menu, mnIDOptionOptimizationPrefs, opened); EnableItem(menu, mnIDOptionAdvanced, opened); diff --git a/src/ui/simulator/application/main/main.h b/src/ui/simulator/application/main/main.h index 75801064ee..a3526afd60 100644 --- a/src/ui/simulator/application/main/main.h +++ b/src/ui/simulator/application/main/main.h @@ -569,6 +569,8 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent //! MC Playlist void evtOnOptionsMCPlaylist(wxCommandEvent& evt); //! MC Scenario Builder + void evtOnOptionsAdequacyPatch(wxCommandEvent& evt); + //! Adequacy Patch void evtOnOptionsMCScenarioBuilder(wxCommandEvent& evt); //! Optimization preferences void evtOnOptionsOptimizationPrefs(wxCommandEvent& evt); diff --git a/src/ui/simulator/application/main/menu.cpp b/src/ui/simulator/application/main/menu.cpp index 2d7f9b72c1..330fca3756 100644 --- a/src/ui/simulator/application/main/menu.cpp +++ b/src/ui/simulator/application/main/menu.cpp @@ -449,6 +449,11 @@ wxMenu* ApplWnd::createMenuOptions() wxT("MC Scenario playlist"), "images/16x16/orderedlist.png", wxT("Configure MC Scenario playlist")); + Menu::CreateItem(pMenuOptions, + mnIDOptionConfigureAdequacyPatch, + wxT("Adequacy Patch"), + "images/16x16/orderedlist.png", + wxT("Configure Adequacy Patch")); pMenuOptions->AppendSeparator(); diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index c3b3c05ba0..a67783c0b6 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -32,6 +32,7 @@ #include "../../windows/options/select-output/select-output.h" #include "../../windows/options/playlist/playlist.h" #include "../../windows/options/optimization/optimization.h" +#include "../../windows/options/adequacy-patch/adequacyPatch.h" #include "../../windows/options/advanced/advanced.h" #include "../../windows/message.h" @@ -110,6 +111,13 @@ void ApplWnd::evtOnOptionsMCScenarioBuilder(wxCommandEvent&) } } +void ApplWnd::evtOnOptionsAdequacyPatch(wxCommandEvent&) +{ + Forms::Disabler disabler(*this); + if (Data::Study::Current::Valid()) + Dispatcher::GUI::CreateAndShowModal(this); +} + void ApplWnd::evtOnOptionsOptimizationPrefs(wxCommandEvent&) { Forms::Disabler disabler(*this); diff --git a/src/ui/simulator/cmake/windows-options.cmake b/src/ui/simulator/cmake/windows-options.cmake index e8aef3bfc6..34e6152282 100644 --- a/src/ui/simulator/cmake/windows-options.cmake +++ b/src/ui/simulator/cmake/windows-options.cmake @@ -10,6 +10,8 @@ set(SRC_UI_WINDOWS_OPTIONS windows/options/select-output/select-output.cpp windows/options/playlist/playlist.h windows/options/playlist/playlist.cpp + windows/options/adequacy-patch/adequacyPatch.h + windows/options/adequacy-patch/adequacyPatch.cpp windows/options/optimization/optimization.h windows/options/optimization/optimization.cpp windows/options/advanced/advanced.h diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp new file mode 100644 index 0000000000..edc02b84ac --- /dev/null +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp @@ -0,0 +1,444 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "adequacyPatch.h" +#include +#include +#include +#include +#include "../../../toolbox/create.h" +#include "../../../toolbox/resources.h" +#include "../../../application/study.h" +#include "../../../application/menus.h" +#include "../../../windows/message.h" +#include +#include + +using namespace Yuni; + +namespace Antares +{ +namespace Window +{ +namespace Options +{ +static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) +{ + if (margintop) + { + sizer->AddSpacer(25); + sizer->AddSpacer(25); + } + + auto* label = Component::CreateLabel(parent, text, true); + + sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + sizer->AddSpacer(5); + sizer->AddSpacer(5); + sizer->AddSpacer(5); +} + +static void ResetButton(Component::Button* button, bool value) +{ + assert(button != NULL); + if (value) + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + } + else + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("ignore")); + } +} + +static void ResetButtonAdequacyPatch(Component::Button* button, bool value) +{ + assert(button != NULL); + if (value) + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to null")); + } + else + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + } +} + +static void ResetButtonSpecify(Component::Button* button, bool value) +{ + assert(button != NULL); + if (value) + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("true")); + } + else + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("false")); + } +} + +static void ResetButton(Component::Button* button, Data::TransmissionCapacities value) +{ + assert(button != NULL); + switch (value) + { + case Data::tncEnabled: + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + break; + case Data::tncIgnore: + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to null")); + break; + case Data::tncInfinite: + button->image("images/16x16/infinity.png"); + button->caption(wxT("set to infinite")); + break; + } +} + +static void ResetButton(Component::Button* button, Data::LinkType value) +{ + assert(button != NULL); + switch (value) + { + case Data::ltLocal: + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + break; + case Data::ltAC: + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to AC")); + break; + } +} + +AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : + wxDialog(parent, + wxID_ANY, + wxT("Adequacy Patch Options"), + wxDefaultPosition, + wxDefaultSize, + wxCLOSE_BOX | wxCAPTION | wxCLIP_CHILDREN), + pTargetRef(nullptr) +{ + assert(parent); + + // Title of the Form + SetLabel(wxT("Adequacy Patch Options")); + SetTitle(wxT("Adequacy Patch Options")); + + auto& study = *Data::Study::Current::Get(); + + // Background color + wxColour defaultBgColor = GetBackgroundColour(); + wxColour bgColor(255, 255, 255); + SetBackgroundColour(bgColor); + + auto* sizer = new wxBoxSizer(wxVERTICAL); + + auto* hz = new wxBoxSizer(wxHORIZONTAL); + hz->AddSpacer(6); + hz->Add(Resources::StaticBitmapLoadFromFile(this, wxID_ANY, "images/64x64/db.png"), + 0, + wxALL | wxALIGN_TOP | wxALIGN_CENTER); + hz->AddSpacer(35); + + auto* s = new wxFlexGridSizer(0, 2, 1, 10); + s->AddGrowableCol(0, 1); + hz->Add(s, 1, wxALL | wxEXPAND); + sizer->Add(hz, 0, wxALL | wxEXPAND, 20); + + wxStaticText* label; + Component::Button* button; + Yuni::Bind onPopup; + + + SubTitle(this, s, wxT("Adequacy Patch")); + // Adequacy patch + { + label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &AdequacyPatchOptions::onPopupMenuSpecify, + PopupInfo(study.parameters.include.adequacyPatch, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatch = button; + } + // Transmission capacities (NTC) from physical areas outside adequacy patch (area type 1) to + // physical areas inside adequacy patch (area type 2). Used in the first step of adequacy patch + // local matching rule. + { + label = Component::CreateLabel(this, wxT("NTC from physical areas outside to physical areas inside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &AdequacyPatchOptions::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchNTC12 = button; + } + // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). + // Used in the first step of adequacy patch local matching rule. + { + label = Component::CreateLabel(this, wxT("NTC between physical areas outside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &AdequacyPatchOptions::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchNTC11 = button; + } + + { + s->AddSpacer(2); + s->Add(105, 2); + } + + sizer->AddSpacer(10); + + // Buttons + Component::Panel* panel = new Component::Panel(this); + panel->SetBackgroundColour(defaultBgColor); + wxBoxSizer* pnlSizerBtns = new wxBoxSizer(wxHORIZONTAL); + wxBoxSizer* pnlSizerBtnsV = new wxBoxSizer(wxVERTICAL); + panel->SetSizer(pnlSizerBtnsV); + pnlSizerBtnsV->AddSpacer(8); + pnlSizerBtnsV->Add(pnlSizerBtns, 1, wxALL | wxEXPAND); + pnlSizerBtnsV->AddSpacer(8); + + button = new Component::Button(panel, + wxT("Reset to default"), + "images/16x16/param_reset.png", + this, + &AdequacyPatchOptions::onResetToDefault); + pnlSizerBtns->Add(22, 5); + pnlSizerBtns->Add(button, 0, wxALL | wxEXPAND); + + pnlSizerBtns->AddStretchSpacer(); + wxButton* pBtnCancel + = Antares::Component::CreateButton(panel, wxT(" Close "), this, &AdequacyPatchOptions::onClose); + pBtnCancel->SetDefault(); + pnlSizerBtns->Add(pBtnCancel, 0, wxALL | wxEXPAND); + pnlSizerBtns->Add(25, 5); + + sizer->Add(new wxStaticLine(this, wxID_ANY), 0, wxALL | wxEXPAND); + sizer->Add(panel, 0, wxALL | wxEXPAND); + + // refresh + Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(AdequacyPatchOptions::onInternalMotion), NULL, this); + + refresh(); + SetSizer(sizer); + sizer->Layout(); + + // Recentre the window + sizer->Fit(this); + Centre(wxBOTH); +} + +AdequacyPatchOptions::~AdequacyPatchOptions() +{ +} + +void AdequacyPatchOptions::onClose(void*) +{ + Dispatcher::GUI::Close(this); +} + +void AdequacyPatchOptions::onResetToDefault(void*) +{ + auto studyptr = Data::Study::Current::Get(); + if (!(!studyptr)) + { + Window::Message message(this, + wxT("Adequacy Patch Options"), + wxT("Adequacy Patch Options"), + wxT("Do you really want to reset to the default values ?")); + message.add(Window::Message::btnContinue); + message.add(Window::Message::btnCancel, true); + + if (message.showModal() == Window::Message::btnContinue) + { + auto& study = *studyptr; + + study.parameters.include.adequacyPatch = false; + study.parameters.setToZero12LinksForAdequacyPatch = true; + study.parameters.setToZero11LinksForAdequacyPatch = true; + + refresh(); + MarkTheStudyAsModified(); + return; + } + } +} + +void AdequacyPatchOptions::onInternalMotion(wxMouseEvent&) +{ + Component::Panel::OnMouseMoveFromExternalComponent(); +} + +void AdequacyPatchOptions::refresh() +{ + auto studyptr = Data::Study::Current::Get(); + if (!studyptr) + return; + // The current study + auto& study = *studyptr; + + // Adequacy patch + ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); + // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside + // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, + study.parameters.setToZero12LinksForAdequacyPatch); + // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of + // adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, + study.parameters.setToZero11LinksForAdequacyPatch); +} + +void AdequacyPatchOptions::onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info) +{ + pTargetRef = &info.rval; + wxMenuItem* it; + + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("local values (") << info.text << wxT(")"), + "images/16x16/light_green.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectModeInclude), + nullptr, + this); + it = Menu::CreateItem( + &menu, wxID_ANY, wxT("ignore"), "images/16x16/light_orange.png", wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectModeIgnore), + nullptr, + this); +} + +void AdequacyPatchOptions::onPopupMenuAdequacyPatch(Component::Button&, + wxMenu& menu, + void*, + const PopupInfo& info) +{ + pTargetRef = &info.rval; + wxMenuItem* it; + + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("set to null"), + "images/16x16/light_orange.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectModeInclude), + nullptr, + this); + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("local values (") << info.text << wxT(")"), + "images/16x16/light_green.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectModeIgnore), + nullptr, + this); +} + +void AdequacyPatchOptions::onPopupMenuSpecify(Component::Button&, + wxMenu& menu, + void*, + const PopupInfo& info) +{ + pTargetRef = &info.rval; + wxMenuItem* it; + + it = Menu::CreateItem( + &menu, wxID_ANY, wxString() << info.text, "images/16x16/light_green.png", wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectModeInclude), + nullptr, + this); + it = Menu::CreateItem( + &menu, wxID_ANY, wxT("false"), "images/16x16/light_orange.png", wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectModeIgnore), + nullptr, + this); +} + +void AdequacyPatchOptions::onSelectModeInclude(wxCommandEvent&) +{ + if (pTargetRef and !*pTargetRef) + { + *pTargetRef = true; + MarkTheStudyAsModified(); + refresh(); + } + pTargetRef = nullptr; +} + +void AdequacyPatchOptions::onSelectModeIgnore(wxCommandEvent&) +{ + if (pTargetRef and *pTargetRef) + { + *pTargetRef = false; + MarkTheStudyAsModified(); + refresh(); + } + pTargetRef = nullptr; +} + +} // namespace Options +} // namespace Window +} // namespace Antares diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h new file mode 100644 index 0000000000..1d785354de --- /dev/null +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h @@ -0,0 +1,97 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ +#define __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ + +#include +#include "../../../toolbox/components/button.h" +#include + +#include + +namespace Antares +{ +namespace Window +{ +namespace Options +{ +/*! +** \brief Startup Wizard User Interface +*/ +class AdequacyPatchOptions final : public wxDialog +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + ** + ** \param parent The parent window + */ + AdequacyPatchOptions(wxWindow* parent); + //! Destructor + virtual ~AdequacyPatchOptions(); + //@} + +private: + class PopupInfo final + { + public: + PopupInfo(bool& r, const wxChar* const t) : rval(r), text(t) + { + } + bool& rval; + const wxChar* const text; + }; + +private: + void refresh(); + void onClose(void*); + void onResetToDefault(void*); + + void onSelectModeInclude(wxCommandEvent& evt); + void onSelectModeIgnore(wxCommandEvent& evt); + + void onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); + void onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); + void onPopupMenuAdequacyPatch(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); + + void onInternalMotion(wxMouseEvent&); + +private: + Component::Button* pBtnAdequacyPatch; + Component::Button* pBtnAdequacyPatchNTC12; + Component::Button* pBtnAdequacyPatchNTC11; + bool* pTargetRef; + +}; // class AdequacyPatchOptions + +} // namespace Options +} // namespace Window +} // namespace Antares + +#endif // __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ From 2d264e87856ec613273ad5b61d1bec050bc69a86 Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 7 Apr 2022 11:47:20 +0200 Subject: [PATCH 049/490] remove adq options from optimization tab --- .../options/optimization/optimization.cpp | 120 ------------------ .../options/optimization/optimization.h | 6 +- 2 files changed, 1 insertion(+), 125 deletions(-) diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index 41aef96e64..5c9e32c8ec 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -46,21 +46,6 @@ namespace Window { namespace Options { -static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) -{ - if (margintop) - { - sizer->AddSpacer(25); - sizer->AddSpacer(25); - } - - auto* label = Component::CreateLabel(parent, text, true); - - sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - sizer->AddSpacer(5); - sizer->AddSpacer(5); - sizer->AddSpacer(5); -} static void ResetButton(Component::Button* button, bool value) { assert(button != NULL); @@ -76,21 +61,6 @@ static void ResetButton(Component::Button* button, bool value) } } -static void ResetButtonAdequacyPatch(Component::Button* button, bool value) -{ - assert(button != NULL); - if (value) - { - button->image("images/16x16/light_orange.png"); - button->caption(wxT("set to null")); - } - else - { - button->image("images/16x16/light_green.png"); - button->caption(wxT("local values")); - } -} - static void ResetButtonSpecify(Component::Button* button, bool value) { assert(button != NULL); @@ -373,53 +343,6 @@ Optimization::Optimization(wxWindow* parent) : s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->AddSpacer(2); } - SubTitle(this, s, wxT("Adequacy Patch")); - // Adequacy patch - { - label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); - button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &Optimization::onPopupMenuSpecify, - PopupInfo(study.parameters.include.adequacyPatch, wxT("true"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatch = button; - } - // Transmission capacities (NTC) from physical areas outside adequacy patch (area type 1) to - // physical areas inside adequacy patch (area type 2). Used in the first step of adequacy patch - // local matching rule. - { - label = Component::CreateLabel(this, wxT("NTC from physical areas outside to physical areas inside adequacy patch")); - button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &Optimization::onPopupMenuAdequacyPatch, - PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchNTC12 = button; - } - // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). - // Used in the first step of adequacy patch local matching rule. - { - label = Component::CreateLabel(this, wxT("NTC between physical areas outside adequacy patch")); - button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &Optimization::onPopupMenuAdequacyPatch, - PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchNTC11 = button; - } - { s->AddSpacer(2); s->Add(105, 2); @@ -502,9 +425,6 @@ void Optimization::onResetToDefault(void*) study.parameters.include.reserve.primary = true; study.parameters.include.reserve.spinning = true; study.parameters.include.exportMPS = false; - study.parameters.include.adequacyPatch = false; - study.parameters.setToZero12LinksForAdequacyPatch = true; - study.parameters.setToZero11LinksForAdequacyPatch = true; study.parameters.simplexOptimizationRange = Data::sorWeek; study.parameters.include.unfeasibleProblemBehavior @@ -552,16 +472,6 @@ void Optimization::refresh() ResetButton(pBtnSpinningReserve, study.parameters.include.reserve.spinning); // Export mps ResetButtonSpecify(pBtnExportMPS, study.parameters.include.exportMPS); - // Adequacy patch - ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); - // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside - // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, - study.parameters.setToZero12LinksForAdequacyPatch); - // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of - // adequacy patch local matching rule. - ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, - study.parameters.setToZero11LinksForAdequacyPatch); // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( @@ -606,36 +516,6 @@ void Optimization::onPopupMenu(Component::Button&, wxMenu& menu, void*, const Po this); } -void Optimization::onPopupMenuAdequacyPatch(Component::Button&, - wxMenu& menu, - void*, - const PopupInfo& info) -{ - pTargetRef = &info.rval; - wxMenuItem* it; - - it = Menu::CreateItem(&menu, - wxID_ANY, - wxString() << wxT("set to null"), - "images/16x16/light_orange.png", - wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(Optimization::onSelectModeInclude), - nullptr, - this); - it = Menu::CreateItem(&menu, - wxID_ANY, - wxString() << wxT("local values (") << info.text << wxT(")"), - "images/16x16/light_green.png", - wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(Optimization::onSelectModeIgnore), - nullptr, - this); -} - void Optimization::onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index ae27c47c60..4b7d3a1880 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -98,8 +98,7 @@ class Optimization final : public wxDialog void onPopupMenuTransmissionCapacities(Component::Button&, wxMenu& menu, void*); void onPopupMenuLinkType(Component::Button&, wxMenu& menu, void*); void onPopupMenuUnfeasibleBehavior(Component::Button&, wxMenu& menu, void*); - void onPopupMenuAdequacyPatch(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); - + void onInternalMotion(wxMouseEvent&); private: @@ -116,9 +115,6 @@ class Optimization final : public wxDialog Component::Button* pBtnSimplexOptimizationRange; Component::Button* pBtnExportMPS; - Component::Button* pBtnAdequacyPatch; - Component::Button* pBtnAdequacyPatchNTC12; - Component::Button* pBtnAdequacyPatchNTC11; Component::Button* pBtnUnfeasibleProblemBehavior; bool* pTargetRef; From 7e626bf7718d405f14cc2520987bdf773874f3d1 Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 7 Apr 2022 16:46:38 +0200 Subject: [PATCH 050/490] add pto and intermediate result save buttons --- src/libs/antares/study/fwd.h | 12 ++ src/libs/antares/study/parameters.cpp | 82 ++++++++-- src/libs/antares/study/parameters.h | 5 + .../options/adequacy-patch/adequacyPatch.cpp | 150 ++++++++++++++---- .../options/adequacy-patch/adequacyPatch.h | 7 +- 5 files changed, 217 insertions(+), 39 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 5b70500acf..30ed07c11d 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -594,6 +594,18 @@ enum LinkCapacityForAdequacyPatchFirstStep }; // enum NTC +/*! +** \brief Types of Price Taking Order for Adequacy patch +*/ +enum AdequacyPatchPTO +{ + //! PTO is DENS + adqPtoIsDens = 0, + //! PTO is Load + adqPtoIsLoad + +}; // enum AdequacyPatchPTO + } // namespace AdequacyPatch } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index c108bd1ee9..bb3060f840 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -177,6 +177,38 @@ const char* StudyModeToCString(StudyMode mode) } return "Unknown"; } +bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdequacyPatchPTO& out) +{ + CString<24, false> s = text; + s.trim(); + s.toLower(); + if (s == "dens") + { + out = AdequacyPatch::adqPtoIsDens; + return true; + } + if (s == "load") + { + out = AdequacyPatch::adqPtoIsLoad; + return true; + } + + logs.warning() << "parameters: invalid price taking order. Got '" << text << "'"; + + return false; +} + +const char* PriceTakingOrderToString(AdequacyPatch::AdequacyPatchPTO pto) +{ + switch (pto) + { + case AdequacyPatch::adqPtoIsDens: + return "DENS"; + case AdequacyPatch::adqPtoIsLoad: + return "Load"; + } + return ""; +} Parameters::Parameters() : yearsFilter(nullptr), noOutput(false) { @@ -308,6 +340,8 @@ void Parameters::reset() include.adequacyPatch = false; setToZero12LinksForAdequacyPatch = true; setToZero11LinksForAdequacyPatch = true; + adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; + adqPatchSaveIntermediateResults = false; include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -555,12 +589,6 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, return value.to(d.include.reserve.primary); if (key == "include-exportmps") return value.to(d.include.exportMPS); - if (key == "include-adequacypatch") - return value.to(d.include.adequacyPatch); - if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch") - return value.to(d.setToZero12LinksForAdequacyPatch); - if (key == "set-to-null-ntc-between-physical-out-for-first-step-adq-patch") - return value.to(d.setToZero11LinksForAdequacyPatch); if (key == "include-exportstructure") return value.to(d.include.exportStructure); if (key == "include-unfeasible-problem-behavior") @@ -620,6 +648,30 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, } return false; } +static bool SGDIntLoadFamily_AdqPatch(Parameters& d, + const String& key, + const String& value, + const String&, + uint) +{ + if (key == "include-adq-patch") + return value.to(d.include.adequacyPatch); + if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step") + return value.to(d.setToZero12LinksForAdequacyPatch); + if (key == "set-to-null-ntc-between-physical-out-for-first-step") + return value.to(d.setToZero11LinksForAdequacyPatch); + if (key == "save-intermediate-results") + return value.to(d.adqPatchSaveIntermediateResults); + // Price taking order + if (key == "price-taking-order") + { + return StringToPriceTakingOrder(value, d.adqPatchPriceTakingOrder); + return false; + } + + return false; +} + static bool SGDIntLoadFamily_OtherPreferences(Parameters& d, const String& key, const String& value, @@ -1003,6 +1055,7 @@ bool Parameters::loadFromINI(const IniFile& ini, uint version, const StudyLoadOp {"input", &SGDIntLoadFamily_Input}, {"output", &SGDIntLoadFamily_Output}, {"optimization", &SGDIntLoadFamily_Optimization}, + {"adequacy patch", &SGDIntLoadFamily_AdqPatch}, {"other preferences", &SGDIntLoadFamily_OtherPreferences}, {"advanced parameters", &SGDIntLoadFamily_AdvancedParameters}, {"playlist", &SGDIntLoadFamily_Playlist}, @@ -1718,11 +1771,6 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-primaryreserve", include.reserve.primary); section->add("include-exportmps", include.exportMPS); - section->add("include-adequacypatch", include.adequacyPatch); - section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch", - setToZero12LinksForAdequacyPatch); - section->add("set-to-null-ntc-between-physical-out-for-first-step-adq-patch", - setToZero11LinksForAdequacyPatch); section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior @@ -1730,6 +1778,18 @@ void Parameters::saveToINI(IniFile& ini) const Enum::toString(include.unfeasibleProblemBehavior)); } + // Adequacy patch + { + auto* section = ini.addSection("adequacy patch"); + section->add("include-adq-patch", include.adequacyPatch); + section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step", + setToZero12LinksForAdequacyPatch); + section->add("set-to-null-ntc-between-physical-out-for-first-step", + setToZero11LinksForAdequacyPatch); + section->add("save-intermediate-results", adqPatchSaveIntermediateResults); + section->add("price-taking-order", PriceTakingOrderToString(adqPatchPriceTakingOrder)); + } + // Other preferences { auto* section = ini.addSection("other preferences"); diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 86e72cc814..14c8652e26 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -512,6 +512,11 @@ class Parameters final //! 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. bool setToZero11LinksForAdequacyPatch; + // PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. + AdequacyPatch::AdequacyPatchPTO adqPatchPriceTakingOrder; + // Select whether the intermediate result before the application of the curtailment sharing is + // to be kept in the results + bool adqPatchSaveIntermediateResults; //! \name Scenariio Builder - Rules //@{ diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp index edc02b84ac..383c85e460 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp @@ -46,21 +46,21 @@ namespace Window { namespace Options { -static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) -{ - if (margintop) - { - sizer->AddSpacer(25); - sizer->AddSpacer(25); - } - - auto* label = Component::CreateLabel(parent, text, true); - - sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - sizer->AddSpacer(5); - sizer->AddSpacer(5); - sizer->AddSpacer(5); -} +// static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) +// { +// if (margintop) +// { +// sizer->AddSpacer(25); +// sizer->AddSpacer(25); +// } + +// auto* label = Component::CreateLabel(parent, text, true); + +// sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); +// sizer->AddSpacer(5); +// sizer->AddSpacer(5); +// sizer->AddSpacer(5); +// } static void ResetButton(Component::Button* button, bool value) { @@ -77,7 +77,7 @@ static void ResetButton(Component::Button* button, bool value) } } -static void ResetButtonAdequacyPatch(Component::Button* button, bool value) +static void ResetButtonNTC(Component::Button* button, bool value) { assert(button != NULL); if (value) @@ -92,6 +92,21 @@ static void ResetButtonAdequacyPatch(Component::Button* button, bool value) } } +static void ResetButtonPTO(Component::Button* button, Data::AdequacyPatch::AdequacyPatchPTO value) +{ + assert(button != NULL); + if (value == Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsLoad) + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("Load")); + } + else + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("DENS")); + } +} + static void ResetButtonSpecify(Component::Button* button, bool value) { assert(button != NULL); @@ -184,8 +199,8 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : Yuni::Bind onPopup; - SubTitle(this, s, wxT("Adequacy Patch")); - // Adequacy patch + // SubTitle(this, s, wxT("Adequacy Patch")); + // Enable Adequacy Patch { label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); @@ -208,7 +223,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->SetBackgroundColour(bgColor); button->menu(true); onPopup.bind(this, - &AdequacyPatchOptions::onPopupMenuAdequacyPatch, + &AdequacyPatchOptions::onPopupMenuNTC, PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); @@ -223,13 +238,40 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->SetBackgroundColour(bgColor); button->menu(true); onPopup.bind(this, - &AdequacyPatchOptions::onPopupMenuAdequacyPatch, + &AdequacyPatchOptions::onPopupMenuNTC, PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatchNTC11 = button; } + // PTO (Price Taking Order). User can choose between DENS and Load + { + label = Component::CreateLabel(this, wxT("Price taking order")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, &AdequacyPatchOptions::onPopupMenuPTO); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchPTO = button; + } + // Select whether the intermediate result before the application of the curtailment sharing is + // to be kept in the results + { + label = Component::CreateLabel(this, wxT("Save intermediate results")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &AdequacyPatchOptions::onPopupMenuSpecify, + PopupInfo(study.parameters.adqPatchSaveIntermediateResults, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchSaveIntermediateResults = button; + } { s->AddSpacer(2); @@ -302,11 +344,14 @@ void AdequacyPatchOptions::onResetToDefault(void*) if (message.showModal() == Window::Message::btnContinue) { auto& study = *studyptr; - + study.parameters.include.adequacyPatch = false; study.parameters.setToZero12LinksForAdequacyPatch = true; study.parameters.setToZero11LinksForAdequacyPatch = true; - + study.parameters.adqPatchPriceTakingOrder + = Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; + study.parameters.adqPatchSaveIntermediateResults = false; + refresh(); MarkTheStudyAsModified(); return; @@ -331,12 +376,15 @@ void AdequacyPatchOptions::refresh() ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, - study.parameters.setToZero12LinksForAdequacyPatch); + ResetButtonNTC(pBtnAdequacyPatchNTC12, study.parameters.setToZero12LinksForAdequacyPatch); // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of // adequacy patch local matching rule. - ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, - study.parameters.setToZero11LinksForAdequacyPatch); + ResetButtonNTC(pBtnAdequacyPatchNTC11, study.parameters.setToZero11LinksForAdequacyPatch); + // Price taking order (PTO) for adequacy patch + ResetButtonPTO(pBtnAdequacyPatchPTO, study.parameters.adqPatchPriceTakingOrder); + // Save intermediate results for adequacy patch + ResetButtonSpecify(pBtnAdequacyPatchSaveIntermediateResults, + study.parameters.adqPatchSaveIntermediateResults); } void AdequacyPatchOptions::onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info) @@ -363,7 +411,7 @@ void AdequacyPatchOptions::onPopupMenu(Component::Button&, wxMenu& menu, void*, this); } -void AdequacyPatchOptions::onPopupMenuAdequacyPatch(Component::Button&, +void AdequacyPatchOptions::onPopupMenuNTC(Component::Button&, wxMenu& menu, void*, const PopupInfo& info) @@ -393,6 +441,26 @@ void AdequacyPatchOptions::onPopupMenuAdequacyPatch(Component::Button&, this); } +void AdequacyPatchOptions::onPopupMenuPTO(Component::Button&, wxMenu& menu, void*) +{ + wxMenuItem* it; + + it = Menu::CreateItem( + &menu, wxID_ANY, wxString() << wxT("DENS"), "images/16x16/light_green.png", wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectPtoIsDens), + nullptr, + this); + it = Menu::CreateItem( + &menu, wxID_ANY, wxT("Load"), "images/16x16/light_orange.png", wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(AdequacyPatchOptions::onSelectPtoIsLoad), + nullptr, + this); +} + void AdequacyPatchOptions::onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, @@ -439,6 +507,34 @@ void AdequacyPatchOptions::onSelectModeIgnore(wxCommandEvent&) pTargetRef = nullptr; } +void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) +{ + auto study = Data::Study::Current::Get(); + if (!(!study)) + { + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPtoIsDens) + { + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPtoIsDens; + refresh(); + MarkTheStudyAsModified(); + } + } +} + +void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) +{ + auto study = Data::Study::Current::Get(); + if (!(!study)) + { + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPtoIsLoad) + { + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPtoIsLoad; + refresh(); + MarkTheStudyAsModified(); + } + } +} + } // namespace Options } // namespace Window } // namespace Antares diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h index 1d785354de..c516c06063 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h @@ -73,12 +73,15 @@ class AdequacyPatchOptions final : public wxDialog void onClose(void*); void onResetToDefault(void*); + void onSelectPtoIsDens(wxCommandEvent&); + void onSelectPtoIsLoad(wxCommandEvent&); void onSelectModeInclude(wxCommandEvent& evt); void onSelectModeIgnore(wxCommandEvent& evt); void onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); void onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); - void onPopupMenuAdequacyPatch(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); + void onPopupMenuNTC(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); + void onPopupMenuPTO(Component::Button&, wxMenu& menu, void*); void onInternalMotion(wxMouseEvent&); @@ -86,6 +89,8 @@ class AdequacyPatchOptions final : public wxDialog Component::Button* pBtnAdequacyPatch; Component::Button* pBtnAdequacyPatchNTC12; Component::Button* pBtnAdequacyPatchNTC11; + Component::Button* pBtnAdequacyPatchPTO; + Component::Button* pBtnAdequacyPatchSaveIntermediateResults; bool* pTargetRef; }; // class AdequacyPatchOptions From 7df97e58fc821d9085816f6cde1732e66ba0d8f1 Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 7 Apr 2022 20:44:22 +0200 Subject: [PATCH 051/490] shift adq patch tab to botton of configure menu --- src/ui/simulator/application/main/menu.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/ui/simulator/application/main/menu.cpp b/src/ui/simulator/application/main/menu.cpp index 330fca3756..05fa609415 100644 --- a/src/ui/simulator/application/main/menu.cpp +++ b/src/ui/simulator/application/main/menu.cpp @@ -449,11 +449,6 @@ wxMenu* ApplWnd::createMenuOptions() wxT("MC Scenario playlist"), "images/16x16/orderedlist.png", wxT("Configure MC Scenario playlist")); - Menu::CreateItem(pMenuOptions, - mnIDOptionConfigureAdequacyPatch, - wxT("Adequacy Patch"), - "images/16x16/orderedlist.png", - wxT("Configure Adequacy Patch")); pMenuOptions->AppendSeparator(); @@ -468,6 +463,11 @@ wxMenu* ApplWnd::createMenuOptions() "images/16x16/empty.png", wxT("Set advanced parameters")); it->Enable(false); + Menu::CreateItem(pMenuOptions, + mnIDOptionConfigureAdequacyPatch, + wxT("Adequacy Patch"), + "images/16x16/orderedlist.png", + wxT("Configure Adequacy Patch")); return pMenuOptions; } From 1e183351d3180181081d726bd423fa987118c83a Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 7 Apr 2022 22:31:48 +0200 Subject: [PATCH 052/490] group adq parameters together --- src/libs/antares/study/parameters.cpp | 13 ++++++++----- .../options/adequacy-patch/adequacyPatch.cpp | 11 ++++++----- 2 files changed, 14 insertions(+), 10 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index bb3060f840..bc09052977 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -337,11 +337,6 @@ void Parameters::reset() simplexOptimizationRange = sorWeek; include.exportMPS = false; - include.adequacyPatch = false; - setToZero12LinksForAdequacyPatch = true; - setToZero11LinksForAdequacyPatch = true; - adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; - adqPatchSaveIntermediateResults = false; include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -352,6 +347,14 @@ void Parameters::reset() ortoolsUsed = false; ortoolsEnumUsed = OrtoolsSolver::sirius; + + // Adequacy patch + include.adequacyPatch = false; + setToZero12LinksForAdequacyPatch = true; + setToZero11LinksForAdequacyPatch = true; + adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; + adqPatchSaveIntermediateResults = false; + // resetAdqPatchSeeds(); // Initialize all seeds resetSeeds(); diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp index 383c85e460..1ff3ac00cd 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp @@ -97,12 +97,12 @@ static void ResetButtonPTO(Component::Button* button, Data::AdequacyPatch::Adequ assert(button != NULL); if (value == Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsLoad) { - button->image("images/16x16/light_orange.png"); + button->image("images/16x16/tag.png"); button->caption(wxT("Load")); } else { - button->image("images/16x16/light_green.png"); + button->image("images/16x16/tag.png"); button->caption(wxT("DENS")); } } @@ -248,7 +248,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : // PTO (Price Taking Order). User can choose between DENS and Load { label = Component::CreateLabel(this, wxT("Price taking order")); - button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button = new Component::Button(this, wxT("Day"), "images/16x16/tag.png"); button->SetBackgroundColour(bgColor); button->menu(true); onPopup.bind(this, &AdequacyPatchOptions::onPopupMenuPTO); @@ -351,6 +351,7 @@ void AdequacyPatchOptions::onResetToDefault(void*) study.parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; study.parameters.adqPatchSaveIntermediateResults = false; + // study.parameters.resetAdqPatchSeeds(); refresh(); MarkTheStudyAsModified(); @@ -446,14 +447,14 @@ void AdequacyPatchOptions::onPopupMenuPTO(Component::Button&, wxMenu& menu, void wxMenuItem* it; it = Menu::CreateItem( - &menu, wxID_ANY, wxString() << wxT("DENS"), "images/16x16/light_green.png", wxEmptyString); + &menu, wxID_ANY, wxString() << wxT("DENS"), "images/16x16/tag.png", wxEmptyString); menu.Connect(it->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(AdequacyPatchOptions::onSelectPtoIsDens), nullptr, this); it = Menu::CreateItem( - &menu, wxID_ANY, wxT("Load"), "images/16x16/light_orange.png", wxEmptyString); + &menu, wxID_ANY, wxT("Load"), "images/16x16/tag.png", wxEmptyString); menu.Connect(it->GetId(), wxEVT_COMMAND_MENU_SELECTED, wxCommandEventHandler(AdequacyPatchOptions::onSelectPtoIsLoad), From 1d384d8b0ab3bbfa0ca45867369f591632eca367 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 8 Apr 2022 14:04:59 +0200 Subject: [PATCH 053/490] add 2 float threshold options --- src/libs/antares/study/fwd.h | 14 ++ src/libs/antares/study/parameters.cpp | 22 ++- src/libs/antares/study/parameters.h | 12 +- .../options/adequacy-patch/adequacyPatch.cpp | 149 +++++++++++------- .../options/adequacy-patch/adequacyPatch.h | 9 +- 5 files changed, 140 insertions(+), 66 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 30ed07c11d..2e654c4eae 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -606,6 +606,20 @@ enum AdequacyPatchPTO }; // enum AdequacyPatchPTO +enum AdqPatchThresholdSeed +{ + //! The seed for initiate curtailment sharing rule + seedThresholdInitiateCurtailmentSharingRule = 0, + //! The seed for display of Local Matching Rule violations + seedThresholdDisplayLocalMatchingRuleViolations, + seedThresholdMax +}; + +//! A default threshold value for initiate curtailment sharing rule +const float seedDefaultThresholdInitiateCurtailmentSharingRule = 0.5; +//! A default threshold value for display local matching rule violations +const float seedDefaultThresholdDisplayLocalMatchingRuleViolations = 0.5; + } // namespace AdequacyPatch } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index bc09052977..41b12f9a07 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -233,6 +233,14 @@ void Parameters::resetSeeds() for (auto i = (uint)seedTsGenLoad; i != seedMax; ++i) seed[i] = (s += increment); } +void Parameters::resetSeedsAdqPatch() +{ + // Initialize all seeds for adequacy patch + seedAdqPatch[seedThresholdInitiateCurtailmentSharingRule] + = (float)seedDefaultThresholdInitiateCurtailmentSharingRule; + seedAdqPatch[seedThresholdDisplayLocalMatchingRuleViolations] + = (float)seedDefaultThresholdDisplayLocalMatchingRuleViolations; +} void Parameters::reset() { @@ -354,7 +362,7 @@ void Parameters::reset() setToZero11LinksForAdequacyPatch = true; adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; adqPatchSaveIntermediateResults = false; - // resetAdqPatchSeeds(); + resetSeedsAdqPatch(); // Initialize all seeds resetSeeds(); @@ -671,6 +679,13 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, return StringToPriceTakingOrder(value, d.adqPatchPriceTakingOrder); return false; } + // Thresholds + if (key == "threshold-initiate-curtailment-sharing-rule") + return value.to( + d.seedAdqPatch[AdequacyPatch::seedThresholdInitiateCurtailmentSharingRule]); + if (key == "threshold-display-local-matching-rule-violations") + return value.to( + d.seedAdqPatch[AdequacyPatch::seedThresholdDisplayLocalMatchingRuleViolations]); return false; } @@ -1791,6 +1806,11 @@ void Parameters::saveToINI(IniFile& ini) const setToZero11LinksForAdequacyPatch); section->add("save-intermediate-results", adqPatchSaveIntermediateResults); section->add("price-taking-order", PriceTakingOrderToString(adqPatchPriceTakingOrder)); + // Threshholds + section->add("threshold-initiate-curtailment-sharing-rule", + seedAdqPatch[AdequacyPatch::seedThresholdInitiateCurtailmentSharingRule]); + section->add("threshold-display-local-matching-rule-violations", + seedAdqPatch[AdequacyPatch::seedThresholdDisplayLocalMatchingRuleViolations]); } // Other preferences diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 14c8652e26..0c2b51b764 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -138,6 +138,10 @@ class Parameters final ** \brief Reset to default all seeds */ void resetSeeds(); + /*! + ** \brief Reset to default all seeds in adequacy patch + */ + void resetSeedsAdqPatch(); /*! ** \brief Try to detect then fix any bad value @@ -512,11 +516,13 @@ class Parameters final //! 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. bool setToZero11LinksForAdequacyPatch; - // PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. + //! PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. AdequacyPatch::AdequacyPatchPTO adqPatchPriceTakingOrder; - // Select whether the intermediate result before the application of the curtailment sharing is - // to be kept in the results + //! Select whether the intermediate result before the application of the curtailment sharing is + //! to be kept in the results bool adqPatchSaveIntermediateResults; + //! Seeds for adequacy patch threshold values + float seedAdqPatch[AdequacyPatch::seedThresholdMax]; //! \name Scenariio Builder - Rules //@{ diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp index 1ff3ac00cd..f9803132f8 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp @@ -46,35 +46,20 @@ namespace Window { namespace Options { -// static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) -// { -// if (margintop) -// { -// sizer->AddSpacer(25); -// sizer->AddSpacer(25); -// } - -// auto* label = Component::CreateLabel(parent, text, true); - -// sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); -// sizer->AddSpacer(5); -// sizer->AddSpacer(5); -// sizer->AddSpacer(5); -// } - -static void ResetButton(Component::Button* button, bool value) +static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) { - assert(button != NULL); - if (value) + if (margintop) { - button->image("images/16x16/light_green.png"); - button->caption(wxT("local values")); - } - else - { - button->image("images/16x16/light_orange.png"); - button->caption(wxT("ignore")); + sizer->AddSpacer(25); + sizer->AddSpacer(25); } + + auto* label = Component::CreateLabel(parent, text, true); + + sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + sizer->AddSpacer(5); + sizer->AddSpacer(5); + sizer->AddSpacer(5); } static void ResetButtonNTC(Component::Button* button, bool value) @@ -122,41 +107,20 @@ static void ResetButtonSpecify(Component::Button* button, bool value) } } -static void ResetButton(Component::Button* button, Data::TransmissionCapacities value) +const char* AdqPatchSeedToCString(Data::AdequacyPatch::AdqPatchThresholdSeed seed) { - assert(button != NULL); - switch (value) + switch (seed) { - case Data::tncEnabled: - button->image("images/16x16/light_green.png"); - button->caption(wxT("local values")); - break; - case Data::tncIgnore: - button->image("images/16x16/light_orange.png"); - button->caption(wxT("set to null")); - break; - case Data::tncInfinite: - button->image("images/16x16/infinity.png"); - button->caption(wxT("set to infinite")); - break; + case Data::AdequacyPatch::seedThresholdInitiateCurtailmentSharingRule: + return "Initiate curtailment sharing rule"; + case Data::AdequacyPatch::seedThresholdDisplayLocalMatchingRuleViolations: + return "Display local matching rule violations"; + case Data::AdequacyPatch::seedThresholdMax: + return ""; } + return ""; } -static void ResetButton(Component::Button* button, Data::LinkType value) -{ - assert(button != NULL); - switch (value) - { - case Data::ltLocal: - button->image("images/16x16/light_green.png"); - button->caption(wxT("local values")); - break; - case Data::ltAC: - button->image("images/16x16/light_orange.png"); - button->caption(wxT("set to AC")); - break; - } -} AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : wxDialog(parent, @@ -198,9 +162,6 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : Component::Button* button; Yuni::Bind onPopup; - - // SubTitle(this, s, wxT("Adequacy Patch")); - // Enable Adequacy Patch { label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); @@ -272,6 +233,18 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatchSaveIntermediateResults = button; } + SubTitle(this, s, wxT("Thresholds")); + // Seeds + for (uint i = 0; i != (uint)Data::AdequacyPatch::seedThresholdMax; ++i) + pEditSeeds[i] = nullptr; + + for (uint seed = 0; seed != (uint)Data::AdequacyPatch::seedThresholdMax; ++seed) + { + pEditSeeds[seed] = insertEdit(this, + s, + wxStringFromUTF8(AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdSeed)seed)), + wxCommandEventHandler(AdequacyPatchOptions::onEditSeedTSDraws)); + } { s->AddSpacer(2); @@ -351,7 +324,7 @@ void AdequacyPatchOptions::onResetToDefault(void*) study.parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; study.parameters.adqPatchSaveIntermediateResults = false; - // study.parameters.resetAdqPatchSeeds(); + study.parameters.resetSeedsAdqPatch(); refresh(); MarkTheStudyAsModified(); @@ -386,6 +359,12 @@ void AdequacyPatchOptions::refresh() // Save intermediate results for adequacy patch ResetButtonSpecify(pBtnAdequacyPatchSaveIntermediateResults, study.parameters.adqPatchSaveIntermediateResults); + + for (uint seed = 0; seed != (uint)Data::AdequacyPatch::seedThresholdMax; ++seed) + { + if (pEditSeeds[seed]) + pEditSeeds[seed]->SetValue(wxString() << study.parameters.seedAdqPatch[seed]); + } } void AdequacyPatchOptions::onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info) @@ -536,6 +515,56 @@ void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) } } +wxTextCtrl* AdequacyPatchOptions::insertEdit(wxWindow* parent, + wxSizer* sizer, + const wxString& text, + wxObjectEventFunction method) +{ + auto* label = Component::CreateLabel(parent, text); + auto* edit = new wxTextCtrl(parent, wxID_ANY, wxT("2"), wxDefaultPosition, wxSize(180, 20)); + sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + sizer->Add(edit, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + + // Connect event + edit->Connect(edit->GetId(), wxEVT_COMMAND_TEXT_UPDATED, method, nullptr, this); + return edit; +} + +void AdequacyPatchOptions::onEditSeedTSDraws(wxCommandEvent& evt) +{ + if (not Data::Study::Current::Valid()) + return; + auto& study = *Data::Study::Current::Get(); + + int id = evt.GetId(); + + // Looking for the good id + for (uint i = 0; i != (uint)Data::AdequacyPatch::seedThresholdMax; ++i) + { + if (pEditSeeds[i] && id == pEditSeeds[i]->GetId()) + { + String text; + wxStringToString(pEditSeeds[i]->GetValue(), text); + + float newseed; + if (not text.to(newseed)) + { + logs.error() << "impossible to update the seed for '" + << AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdSeed)i) << "'"; + } + else + { + if (newseed != study.parameters.seedAdqPatch[i]) + { + study.parameters.seedAdqPatch[i] = newseed; + MarkTheStudyAsModified(); + } + } + return; + } + } +} + } // namespace Options } // namespace Window } // namespace Antares diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h index c516c06063..278fa2d039 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h @@ -72,6 +72,10 @@ class AdequacyPatchOptions final : public wxDialog void refresh(); void onClose(void*); void onResetToDefault(void*); + wxTextCtrl* insertEdit(wxWindow* parent, + wxSizer* sizer, + const wxString& text, + wxObjectEventFunction); void onSelectPtoIsDens(wxCommandEvent&); void onSelectPtoIsLoad(wxCommandEvent&); @@ -83,14 +87,15 @@ class AdequacyPatchOptions final : public wxDialog void onPopupMenuNTC(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); void onPopupMenuPTO(Component::Button&, wxMenu& menu, void*); - void onInternalMotion(wxMouseEvent&); - + void onInternalMotion(wxMouseEvent&); + void onEditSeedTSDraws(wxCommandEvent&); private: Component::Button* pBtnAdequacyPatch; Component::Button* pBtnAdequacyPatchNTC12; Component::Button* pBtnAdequacyPatchNTC11; Component::Button* pBtnAdequacyPatchPTO; Component::Button* pBtnAdequacyPatchSaveIntermediateResults; + wxTextCtrl* pEditSeeds[Data::AdequacyPatch::seedThresholdMax]; bool* pTargetRef; }; // class AdequacyPatchOptions From 74246b1d82af348c9c1f731be434faf4fb47b7fb Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 8 Apr 2022 15:22:44 +0200 Subject: [PATCH 054/490] make room/tab for the area-data (temporary!?) --- .../simulator/application/main/internal-ids.h | 4 +++- src/ui/simulator/application/main/main.cpp | 7 ++++-- src/ui/simulator/application/main/main.h | 8 +++++-- src/ui/simulator/application/main/menu.cpp | 22 ++++++++++++++----- src/ui/simulator/application/main/options.cpp | 19 +++++++++++----- 5 files changed, 44 insertions(+), 16 deletions(-) diff --git a/src/ui/simulator/application/main/internal-ids.h b/src/ui/simulator/application/main/internal-ids.h index 52bbc4d7b9..f14dfbd44a 100644 --- a/src/ui/simulator/application/main/internal-ids.h +++ b/src/ui/simulator/application/main/internal-ids.h @@ -132,9 +132,11 @@ enum MenusID mnIDOptionConfigureDistricts, mnIDOptionConfigureMCScenarioBuilder, mnIDOptionConfigureMCScenarioPlaylist, - mnIDOptionConfigureAdequacyPatch, mnIDOptionOptimizationPrefs, mnIDOptionAdvanced, + mnIDOptionAdequacyPatchConfigure, + mnIDOptionAdequacyPatchAreas, + //@} //! \name Window diff --git a/src/ui/simulator/application/main/main.cpp b/src/ui/simulator/application/main/main.cpp index ce02d6161e..b25831510d 100644 --- a/src/ui/simulator/application/main/main.cpp +++ b/src/ui/simulator/application/main/main.cpp @@ -157,9 +157,10 @@ EVT_MENU(mnIDOptionConfigureLinksTrimming, ApplWnd::evtOnOptionsSelectLinksTrimm EVT_MENU(mnIDOptionConfigureDistricts, ApplWnd::evtOnOptionsDistricts) EVT_MENU(mnIDOptionConfigureMCScenarioPlaylist, ApplWnd::evtOnOptionsMCPlaylist) EVT_MENU(mnIDOptionConfigureMCScenarioBuilder, ApplWnd::evtOnOptionsMCScenarioBuilder) -EVT_MENU(mnIDOptionConfigureAdequacyPatch, ApplWnd::evtOnOptionsAdequacyPatch) EVT_MENU(mnIDOptionOptimizationPrefs, ApplWnd::evtOnOptionsOptimizationPrefs) EVT_MENU(mnIDOptionAdvanced, ApplWnd::evtOnOptionsAdvanced) +EVT_MENU(mnIDOptionAdequacyPatchConfigure, ApplWnd::evtOnOptionsAdequacyPatchConfigure) +EVT_MENU(mnIDOptionAdequacyPatchAreas, ApplWnd::evtOnOptionsAdequacyPatchAreas) // Window EVT_MENU(mnIDFullscreen, ApplWnd::evtOnFullscreen) @@ -230,6 +231,7 @@ ApplWnd::ApplWnd() : pMenuSimulation(nullptr), pMenuOptions(nullptr), pMenuGeographicTrimming(nullptr), + pMenuAdequacyPatch(nullptr), pMenuWindow(nullptr), pMenuTools(nullptr), pMenuHelp(nullptr), @@ -515,9 +517,10 @@ void ApplWnd::evtOnUpdateGUIAfterStudyIO(bool opened) // Options EnableItem(menu, mnIDOptionConfigureMCScenarioBuilder, opened); EnableItem(menu, mnIDOptionConfigureMCScenarioPlaylist, opened); - EnableItem(menu, mnIDOptionConfigureAdequacyPatch, opened); EnableItem(menu, mnIDOptionOptimizationPrefs, opened); EnableItem(menu, mnIDOptionAdvanced, opened); + EnableItem(menu, mnIDOptionAdequacyPatchConfigure, opened); + EnableItem(menu, mnIDOptionAdequacyPatchAreas, opened); EnableItem(menu, mnIDInspector, opened); diff --git a/src/ui/simulator/application/main/main.h b/src/ui/simulator/application/main/main.h index a3526afd60..c8cda54296 100644 --- a/src/ui/simulator/application/main/main.h +++ b/src/ui/simulator/application/main/main.h @@ -569,13 +569,15 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent //! MC Playlist void evtOnOptionsMCPlaylist(wxCommandEvent& evt); //! MC Scenario Builder - void evtOnOptionsAdequacyPatch(wxCommandEvent& evt); - //! Adequacy Patch void evtOnOptionsMCScenarioBuilder(wxCommandEvent& evt); //! Optimization preferences void evtOnOptionsOptimizationPrefs(wxCommandEvent& evt); //! Advanced parameters void evtOnOptionsAdvanced(wxCommandEvent& evt); + //! Adequacy Patch Configure + void evtOnOptionsAdequacyPatchConfigure(wxCommandEvent& evt); + //! Adequacy Patch Areas + void evtOnOptionsAdequacyPatchAreas(wxCommandEvent& evt); //@} //! \name Event: Menu: Window @@ -691,6 +693,8 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent wxMenu* pMenuOptions; //! SubMenu: Options > Geographic trimming wxMenuItem* pMenuGeographicTrimming; + //! SubMenu: Options > Adequacy Patch + wxMenuItem* pMenuAdequacyPatch; //! Menu: Window wxMenu* pMenuWindow; //! Menu: Tools diff --git a/src/ui/simulator/application/main/menu.cpp b/src/ui/simulator/application/main/menu.cpp index 05fa609415..514d78cdec 100644 --- a/src/ui/simulator/application/main/menu.cpp +++ b/src/ui/simulator/application/main/menu.cpp @@ -462,12 +462,24 @@ wxMenu* ApplWnd::createMenuOptions() wxT("Advanced parameters"), "images/16x16/empty.png", wxT("Set advanced parameters")); + + delete pMenuAdequacyPatch; + pMenuAdequacyPatch + = pMenuOptions->AppendSubMenu(new wxMenu(), wxT("Adequacy Patch...")); + + wxMenu* adqPatchSubMenu = pMenuAdequacyPatch->GetSubMenu(); + Menu::CreateItem(adqPatchSubMenu, + mnIDOptionAdequacyPatchConfigure, + wxT("Options"), + "images/16x16/filter.png", + wxT("Adequacy Patch Options")); + Menu::CreateItem(adqPatchSubMenu, + mnIDOptionAdequacyPatchAreas, + wxT("Areas"), + "images/16x16/filter.png", + wxT("Adequacy Patch Areas")); + it->Enable(false); - Menu::CreateItem(pMenuOptions, - mnIDOptionConfigureAdequacyPatch, - wxT("Adequacy Patch"), - "images/16x16/orderedlist.png", - wxT("Configure Adequacy Patch")); return pMenuOptions; } diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index a67783c0b6..97e224f34c 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -111,25 +111,32 @@ void ApplWnd::evtOnOptionsMCScenarioBuilder(wxCommandEvent&) } } -void ApplWnd::evtOnOptionsAdequacyPatch(wxCommandEvent&) +void ApplWnd::evtOnOptionsOptimizationPrefs(wxCommandEvent&) { Forms::Disabler disabler(*this); if (Data::Study::Current::Valid()) - Dispatcher::GUI::CreateAndShowModal(this); + Dispatcher::GUI::CreateAndShowModal(this); } -void ApplWnd::evtOnOptionsOptimizationPrefs(wxCommandEvent&) +void ApplWnd::evtOnOptionsAdvanced(wxCommandEvent&) { Forms::Disabler disabler(*this); if (Data::Study::Current::Valid()) - Dispatcher::GUI::CreateAndShowModal(this); + Dispatcher::GUI::CreateAndShowModal(this); } -void ApplWnd::evtOnOptionsAdvanced(wxCommandEvent&) +void ApplWnd::evtOnOptionsAdequacyPatchConfigure(wxCommandEvent&) { Forms::Disabler disabler(*this); if (Data::Study::Current::Valid()) - Dispatcher::GUI::CreateAndShowModal(this); + Dispatcher::GUI::CreateAndShowModal(this); +} + +void ApplWnd::evtOnOptionsAdequacyPatchAreas(wxCommandEvent&) +{ + Forms::Disabler disabler(*this); + if (Data::Study::Current::Valid()) + Dispatcher::GUI::CreateAndShowModal(this); } } // namespace Forms From 137cb2df02da2ae7df275029a4736478fd31effe Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 8 Apr 2022 21:11:12 +0200 Subject: [PATCH 055/490] proper naming --- src/libs/antares/study/fwd.h | 22 ++++++------ src/libs/antares/study/parameters.cpp | 28 +++++++-------- src/libs/antares/study/parameters.h | 6 ++-- .../options/adequacy-patch/adequacyPatch.cpp | 36 +++++++++---------- .../options/adequacy-patch/adequacyPatch.h | 2 +- 5 files changed, 47 insertions(+), 47 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 2e654c4eae..2ccb7c8d14 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -595,30 +595,30 @@ enum LinkCapacityForAdequacyPatchFirstStep }; // enum NTC /*! -** \brief Types of Price Taking Order for Adequacy patch +** \brief Types of Price Taking Order (PTO) for Adequacy Patch */ enum AdequacyPatchPTO { //! PTO is DENS - adqPtoIsDens = 0, + adqPatchPTOIsDens = 0, //! PTO is Load - adqPtoIsLoad + adqPatchPTOIsLoad }; // enum AdequacyPatchPTO -enum AdqPatchThresholdSeed +enum AdqPatchThresholdsIndex { - //! The seed for initiate curtailment sharing rule - seedThresholdInitiateCurtailmentSharingRule = 0, - //! The seed for display of Local Matching Rule violations - seedThresholdDisplayLocalMatchingRuleViolations, - seedThresholdMax + //! Threshold to initiate curtailment sharing rule + adqPatchThresholdInitiateCurtailmentSharingRule = 0, + //! Threshold to display Local Matching Rule violations + adqPatchThresholdDisplayLocalMatchingRuleViolations, + adqPatchThresholdsMax }; //! A default threshold value for initiate curtailment sharing rule -const float seedDefaultThresholdInitiateCurtailmentSharingRule = 0.5; +const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 0.5; //! A default threshold value for display local matching rule violations -const float seedDefaultThresholdDisplayLocalMatchingRuleViolations = 0.5; +const float adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations = 0.5; } // namespace AdequacyPatch } // namespace Data diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 41b12f9a07..b2032923fa 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -184,12 +184,12 @@ bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdequacyPatc s.toLower(); if (s == "dens") { - out = AdequacyPatch::adqPtoIsDens; + out = AdequacyPatch::adqPatchPTOIsDens; return true; } if (s == "load") { - out = AdequacyPatch::adqPtoIsLoad; + out = AdequacyPatch::adqPatchPTOIsLoad; return true; } @@ -202,9 +202,9 @@ const char* PriceTakingOrderToString(AdequacyPatch::AdequacyPatchPTO pto) { switch (pto) { - case AdequacyPatch::adqPtoIsDens: + case AdequacyPatch::adqPatchPTOIsDens: return "DENS"; - case AdequacyPatch::adqPtoIsLoad: + case AdequacyPatch::adqPatchPTOIsLoad: return "Load"; } return ""; @@ -235,11 +235,11 @@ void Parameters::resetSeeds() } void Parameters::resetSeedsAdqPatch() { - // Initialize all seeds for adequacy patch - seedAdqPatch[seedThresholdInitiateCurtailmentSharingRule] - = (float)seedDefaultThresholdInitiateCurtailmentSharingRule; - seedAdqPatch[seedThresholdDisplayLocalMatchingRuleViolations] - = (float)seedDefaultThresholdDisplayLocalMatchingRuleViolations; + // Initialize all seeds/threshold values for adequacy patch + seedAdqPatch[adqPatchThresholdInitiateCurtailmentSharingRule] + = (float)adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule; + seedAdqPatch[adqPatchThresholdDisplayLocalMatchingRuleViolations] + = (float)adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; } void Parameters::reset() @@ -360,7 +360,7 @@ void Parameters::reset() include.adequacyPatch = false; setToZero12LinksForAdequacyPatch = true; setToZero11LinksForAdequacyPatch = true; - adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; + adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsDens; adqPatchSaveIntermediateResults = false; resetSeedsAdqPatch(); @@ -682,10 +682,10 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") return value.to( - d.seedAdqPatch[AdequacyPatch::seedThresholdInitiateCurtailmentSharingRule]); + d.seedAdqPatch[AdequacyPatch::adqPatchThresholdInitiateCurtailmentSharingRule]); if (key == "threshold-display-local-matching-rule-violations") return value.to( - d.seedAdqPatch[AdequacyPatch::seedThresholdDisplayLocalMatchingRuleViolations]); + d.seedAdqPatch[AdequacyPatch::adqPatchThresholdDisplayLocalMatchingRuleViolations]); return false; } @@ -1808,9 +1808,9 @@ void Parameters::saveToINI(IniFile& ini) const section->add("price-taking-order", PriceTakingOrderToString(adqPatchPriceTakingOrder)); // Threshholds section->add("threshold-initiate-curtailment-sharing-rule", - seedAdqPatch[AdequacyPatch::seedThresholdInitiateCurtailmentSharingRule]); + seedAdqPatch[AdequacyPatch::adqPatchThresholdInitiateCurtailmentSharingRule]); section->add("threshold-display-local-matching-rule-violations", - seedAdqPatch[AdequacyPatch::seedThresholdDisplayLocalMatchingRuleViolations]); + seedAdqPatch[AdequacyPatch::adqPatchThresholdDisplayLocalMatchingRuleViolations]); } // Other preferences diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 0c2b51b764..9364f98efc 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -139,7 +139,7 @@ class Parameters final */ void resetSeeds(); /*! - ** \brief Reset to default all seeds in adequacy patch + ** \brief Reset to default all seeds/threshold values in adequacy patch */ void resetSeedsAdqPatch(); @@ -521,8 +521,8 @@ class Parameters final //! Select whether the intermediate result before the application of the curtailment sharing is //! to be kept in the results bool adqPatchSaveIntermediateResults; - //! Seeds for adequacy patch threshold values - float seedAdqPatch[AdequacyPatch::seedThresholdMax]; + //! threshold values for adequacy patch + float seedAdqPatch[AdequacyPatch::adqPatchThresholdsMax]; //! \name Scenariio Builder - Rules //@{ diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp index f9803132f8..6c1528a79d 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp @@ -80,7 +80,7 @@ static void ResetButtonNTC(Component::Button* button, bool value) static void ResetButtonPTO(Component::Button* button, Data::AdequacyPatch::AdequacyPatchPTO value) { assert(button != NULL); - if (value == Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsLoad) + if (value == Data::AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsLoad) { button->image("images/16x16/tag.png"); button->caption(wxT("Load")); @@ -107,15 +107,15 @@ static void ResetButtonSpecify(Component::Button* button, bool value) } } -const char* AdqPatchSeedToCString(Data::AdequacyPatch::AdqPatchThresholdSeed seed) +const char* AdqPatchSeedToCString(Data::AdequacyPatch::AdqPatchThresholdsIndex seed) { switch (seed) { - case Data::AdequacyPatch::seedThresholdInitiateCurtailmentSharingRule: + case Data::AdequacyPatch::adqPatchThresholdInitiateCurtailmentSharingRule: return "Initiate curtailment sharing rule"; - case Data::AdequacyPatch::seedThresholdDisplayLocalMatchingRuleViolations: + case Data::AdequacyPatch::adqPatchThresholdDisplayLocalMatchingRuleViolations: return "Display local matching rule violations"; - case Data::AdequacyPatch::seedThresholdMax: + case Data::AdequacyPatch::adqPatchThresholdsMax: return ""; } return ""; @@ -234,15 +234,15 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : pBtnAdequacyPatchSaveIntermediateResults = button; } SubTitle(this, s, wxT("Thresholds")); - // Seeds - for (uint i = 0; i != (uint)Data::AdequacyPatch::seedThresholdMax; ++i) + // Seeds/threshold values + for (uint i = 0; i != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++i) pEditSeeds[i] = nullptr; - for (uint seed = 0; seed != (uint)Data::AdequacyPatch::seedThresholdMax; ++seed) + for (uint seed = 0; seed != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++seed) { pEditSeeds[seed] = insertEdit(this, s, - wxStringFromUTF8(AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdSeed)seed)), + wxStringFromUTF8(AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdsIndex)seed)), wxCommandEventHandler(AdequacyPatchOptions::onEditSeedTSDraws)); } @@ -322,7 +322,7 @@ void AdequacyPatchOptions::onResetToDefault(void*) study.parameters.setToZero12LinksForAdequacyPatch = true; study.parameters.setToZero11LinksForAdequacyPatch = true; study.parameters.adqPatchPriceTakingOrder - = Data::AdequacyPatch::AdequacyPatchPTO::adqPtoIsDens; + = Data::AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsDens; study.parameters.adqPatchSaveIntermediateResults = false; study.parameters.resetSeedsAdqPatch(); @@ -359,8 +359,8 @@ void AdequacyPatchOptions::refresh() // Save intermediate results for adequacy patch ResetButtonSpecify(pBtnAdequacyPatchSaveIntermediateResults, study.parameters.adqPatchSaveIntermediateResults); - - for (uint seed = 0; seed != (uint)Data::AdequacyPatch::seedThresholdMax; ++seed) + //Threshold values + for (uint seed = 0; seed != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++seed) { if (pEditSeeds[seed]) pEditSeeds[seed]->SetValue(wxString() << study.parameters.seedAdqPatch[seed]); @@ -492,9 +492,9 @@ void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPtoIsDens) + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPatchPTOIsDens) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPtoIsDens; + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPatchPTOIsDens; refresh(); MarkTheStudyAsModified(); } @@ -506,9 +506,9 @@ void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPtoIsLoad) + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPatchPTOIsLoad) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPtoIsLoad; + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPatchPTOIsLoad; refresh(); MarkTheStudyAsModified(); } @@ -539,7 +539,7 @@ void AdequacyPatchOptions::onEditSeedTSDraws(wxCommandEvent& evt) int id = evt.GetId(); // Looking for the good id - for (uint i = 0; i != (uint)Data::AdequacyPatch::seedThresholdMax; ++i) + for (uint i = 0; i != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++i) { if (pEditSeeds[i] && id == pEditSeeds[i]->GetId()) { @@ -550,7 +550,7 @@ void AdequacyPatchOptions::onEditSeedTSDraws(wxCommandEvent& evt) if (not text.to(newseed)) { logs.error() << "impossible to update the seed for '" - << AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdSeed)i) << "'"; + << AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdsIndex)i) << "'"; } else { diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h index 278fa2d039..303dcff801 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h @@ -95,7 +95,7 @@ class AdequacyPatchOptions final : public wxDialog Component::Button* pBtnAdequacyPatchNTC11; Component::Button* pBtnAdequacyPatchPTO; Component::Button* pBtnAdequacyPatchSaveIntermediateResults; - wxTextCtrl* pEditSeeds[Data::AdequacyPatch::seedThresholdMax]; + wxTextCtrl* pEditSeeds[Data::AdequacyPatch::adqPatchThresholdsMax]; bool* pTargetRef; }; // class AdequacyPatchOptions From dab6de367349b21df8a722e4add4eab5691b9361 Mon Sep 17 00:00:00 2001 From: milos Date: Mon, 11 Apr 2022 11:14:39 +0200 Subject: [PATCH 056/490] re-name the ui adq patch files --- src/ui/simulator/application/main/options.cpp | 2 +- src/ui/simulator/cmake/windows-options.cmake | 4 ++-- .../{adequacyPatch.cpp => adequacy-patch-options.cpp} | 2 +- .../{adequacyPatch.h => adequacy-patch-options.h} | 0 4 files changed, 4 insertions(+), 4 deletions(-) rename src/ui/simulator/windows/options/adequacy-patch/{adequacyPatch.cpp => adequacy-patch-options.cpp} (99%) rename src/ui/simulator/windows/options/adequacy-patch/{adequacyPatch.h => adequacy-patch-options.h} (100%) diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index 97e224f34c..9fc0221358 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -32,7 +32,7 @@ #include "../../windows/options/select-output/select-output.h" #include "../../windows/options/playlist/playlist.h" #include "../../windows/options/optimization/optimization.h" -#include "../../windows/options/adequacy-patch/adequacyPatch.h" +#include "../../windows/options/adequacy-patch/adequacy-patch-options.h" #include "../../windows/options/advanced/advanced.h" #include "../../windows/message.h" diff --git a/src/ui/simulator/cmake/windows-options.cmake b/src/ui/simulator/cmake/windows-options.cmake index 34e6152282..cbd74b00f2 100644 --- a/src/ui/simulator/cmake/windows-options.cmake +++ b/src/ui/simulator/cmake/windows-options.cmake @@ -10,8 +10,8 @@ set(SRC_UI_WINDOWS_OPTIONS windows/options/select-output/select-output.cpp windows/options/playlist/playlist.h windows/options/playlist/playlist.cpp - windows/options/adequacy-patch/adequacyPatch.h - windows/options/adequacy-patch/adequacyPatch.cpp + windows/options/adequacy-patch/adequacy-patch-options.h + windows/options/adequacy-patch/adequacy-patch-options.cpp windows/options/optimization/optimization.h windows/options/optimization/optimization.cpp windows/options/advanced/advanced.h diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp similarity index 99% rename from src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp rename to src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp index 6c1528a79d..ae0487939d 100644 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.cpp +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp @@ -25,7 +25,7 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#include "adequacyPatch.h" +#include "adequacy-patch-options.h" #include #include #include diff --git a/src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h similarity index 100% rename from src/ui/simulator/windows/options/adequacy-patch/adequacyPatch.h rename to src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h From bbe8b40e1cc54a54c8cbe31dd03918519d876b9a Mon Sep 17 00:00:00 2001 From: milos Date: Mon, 11 Apr 2022 23:28:29 +0200 Subject: [PATCH 057/490] create adq patch area list (bug!) --- src/ui/simulator/application/main/options.cpp | 3 +- src/ui/simulator/cmake/windows-options.cmake | 2 + .../components/datagrid/gridhelper.cpp | 20 +++ .../toolbox/components/datagrid/renderer.h | 4 + .../renderer/adequacy-patch-area-grid.cpp | 136 +++++++++++++++++ .../renderer/adequacy-patch-area-grid.h | 72 +++++++++ .../adequacy-patch/adequacy-patch-areas.cpp | 142 ++++++++++++++++++ .../adequacy-patch/adequacy-patch-areas.h | 49 ++++++ 8 files changed, 427 insertions(+), 1 deletion(-) create mode 100644 src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp create mode 100644 src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h create mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp create mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index 9fc0221358..73812f4cbe 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -33,6 +33,7 @@ #include "../../windows/options/playlist/playlist.h" #include "../../windows/options/optimization/optimization.h" #include "../../windows/options/adequacy-patch/adequacy-patch-options.h" +#include "../../windows/options/adequacy-patch/adequacy-patch-areas.h" #include "../../windows/options/advanced/advanced.h" #include "../../windows/message.h" @@ -136,7 +137,7 @@ void ApplWnd::evtOnOptionsAdequacyPatchAreas(wxCommandEvent&) { Forms::Disabler disabler(*this); if (Data::Study::Current::Valid()) - Dispatcher::GUI::CreateAndShowModal(this); + Dispatcher::GUI::CreateAndShowModal(this); } } // namespace Forms diff --git a/src/ui/simulator/cmake/windows-options.cmake b/src/ui/simulator/cmake/windows-options.cmake index cbd74b00f2..10d4a08441 100644 --- a/src/ui/simulator/cmake/windows-options.cmake +++ b/src/ui/simulator/cmake/windows-options.cmake @@ -12,6 +12,8 @@ set(SRC_UI_WINDOWS_OPTIONS windows/options/playlist/playlist.cpp windows/options/adequacy-patch/adequacy-patch-options.h windows/options/adequacy-patch/adequacy-patch-options.cpp + windows/options/adequacy-patch/adequacy-patch-areas.h + windows/options/adequacy-patch/adequacy-patch-areas.cpp windows/options/optimization/optimization.h windows/options/optimization/optimization.cpp windows/options/advanced/advanced.h diff --git a/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp b/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp index 37c5be2da3..12812a80dc 100644 --- a/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp @@ -200,6 +200,20 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider pStyles[CellStyle::cellStyleFilterUndefined]->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE); } + // Adequacy patch areas + { + pStyles[CellStyle::cellStyleAdqPatchVirtual]->SetAlignment(wxALIGN_CENTRE, + wxALIGN_CENTRE); + pStyles[CellStyle::cellStyleAdqPatchVirtual]->SetTextColour(wxColour(0, 0, 0)); + + pStyles[CellStyle::cellStyleAdqPatchOutside]->SetAlignment(wxALIGN_CENTRE, + wxALIGN_CENTRE); + pStyles[CellStyle::cellStyleAdqPatchOutside]->SetTextColour(wxColour(204, 51, 0)); + + pStyles[CellStyle::cellStyleAdqPatchInside]->SetAlignment(wxALIGN_CENTRE, + wxALIGN_CENTRE); + pStyles[CellStyle::cellStyleAdqPatchInside]->SetTextColour(wxColour(0, 128, 0)); + } } virtual ~GridCellAttrProvider() @@ -303,6 +317,9 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOn); internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOff); internalAppendCSSCode(s, CellStyle::cellStyleFilterUndefined); + internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchVirtual); + internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchOutside); + internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchInside); } void appendCSSForAllCellStyles2(Yuni::String& s) @@ -339,6 +356,9 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOn); internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOff); internalAppendCSSCode(s, CellStyle::cellStyleFilterUndefined); + internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchVirtual); + internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchOutside); + internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchInside); } private: diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer.h index 785237679b..482af89d23 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer.h @@ -88,6 +88,10 @@ class IRenderer : public Yuni::IEventObserver cellStyleFilterSynthesisOn, cellStyleFilterSynthesisOff, cellStyleFilterUndefined, + cellStyleAdqPatchVirtual, + cellStyleAdqPatchOutside, + cellStyleAdqPatchInside, + cellStyleMax /* Max items in the list */ }; 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 new file mode 100644 index 0000000000..e6f92219b6 --- /dev/null +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp @@ -0,0 +1,136 @@ +#include "adequacy-patch-area-grid.h" +#include + +using namespace Yuni; + +namespace Antares +{ +namespace Component +{ +namespace Datagrid +{ +namespace Renderer +{ +AdequacyPatchAreaGrid::AdequacyPatchAreaGrid() : pControl(nullptr) +{ +} + +AdequacyPatchAreaGrid::~AdequacyPatchAreaGrid() +{ +} + +bool AdequacyPatchAreaGrid::valid() const +{ + if (!study) + std::cout << "not valid ! \n"; + return !(!study); +} + +int AdequacyPatchAreaGrid::height() const +{ + return (not study) ? 0 : gridSize(); +} + +wxString AdequacyPatchAreaGrid::columnCaption(int) const +{ + return wxT(" Adequacy Patch Area \n Mode "); +} + +wxString AdequacyPatchAreaGrid::rowCaption(int rowIndx) const +{ + return (!(!study) && (uint)rowIndx < gridSize()) + ? wxStringFromUTF8(study->areas.byIndex[rowIndx]->name) + : wxString(); +} + +bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) +{ + if (!(!study) && (uint)row < gridSize()) + { + String s = value; + s.trim(); + s.toLower(); + + bool vir = s == "0" || s == "virtual" || s == "virtual area"; + bool ins = s == "2" || s == "inside" || s == "physical area inside patch"; + bool out = s == "1" || s == "outside" || s == "physical area outside patch"; + + if (vir) + study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + else if (ins) + study->areas.byIndex[row]->adequacyPatchMode + = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + else + study->areas.byIndex[row]->adequacyPatchMode + = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + + onTriggerUpdate(); + Dispatcher::GUI::Refresh(pControl); + return true; + } + return false; +} + +double AdequacyPatchAreaGrid::cellNumericValue(int, int row) const +{ + if (!(!study) && (uint)row < gridSize()) + { + assert(gridSize() != 0); + // return study->areas.byIndex[row]->adequacyPatchMode; + } + return 0.; +} + +wxString AdequacyPatchAreaGrid::cellValue(int, int row) const +{ + if (!(!study) && (uint)row < gridSize()) + { + switch (study->areas.byIndex[row]->adequacyPatchMode) + { + case Data::AdequacyPatch::adqmVirtualArea: + return wxT("virtual"); + break; + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + return wxT("outside"); + break; + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + return wxT("inside"); + break; + default: + break; + } + } + return wxEmptyString; +} + +uint AdequacyPatchAreaGrid::gridSize() const +{ + return study->areas.size(); +} + +IRenderer::CellStyle AdequacyPatchAreaGrid::cellStyle(int, int row) const +{ + if (!(!study) && (uint)row < gridSize()) + { + switch (study->areas.byIndex[row]->adequacyPatchMode) + { + case Data::AdequacyPatch::adqmVirtualArea: + return IRenderer::cellStyleAdqPatchVirtual; + break; + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + return IRenderer::cellStyleAdqPatchOutside; + break; + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + return IRenderer::cellStyleAdqPatchInside; + break; + default: + break; + } + } + return IRenderer::cellStyleConstraintNoWeight; +} + +} // namespace Renderer +} // namespace Datagrid +} // namespace Component +} // namespace Antares \ No newline at end of file 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 new file mode 100644 index 0000000000..7e3f4413d9 --- /dev/null +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h @@ -0,0 +1,72 @@ +#ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ +#define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ + +#include +#include "../renderer.h" +#include "../../../../application/study.h" + +namespace Antares +{ +namespace Component +{ +namespace Datagrid +{ +namespace Renderer +{ +class AdequacyPatchAreaGrid : public IRenderer +{ +public: + AdequacyPatchAreaGrid(); + virtual ~AdequacyPatchAreaGrid(); + + virtual int width() const + { + return 1; + } + virtual uint gridSize() const; + + virtual int height() const; + + virtual wxString columnCaption(int colIndx) const; + + virtual wxString rowCaption(int rowIndx) const; + + virtual wxString cellValue(int x, int y) const; + + virtual double cellNumericValue(int x, int y) const; + + virtual bool cellValue(int x, int y, const Yuni::String& value); + + virtual void resetColors(int, int, wxColour&, wxColour&) const + { + // Do nothing + } + + virtual bool valid() const; + + virtual uint maxWidthResize() const + { + return 0; + } + virtual IRenderer::CellStyle cellStyle(int col, int row) const; + + void control(wxWindow* control) + { + pControl = control; + } + +public: + //! An item has been updated + Yuni::Bind onTriggerUpdate; + +protected: + wxWindow* pControl; + +}; // class AdequacyPatchAreaGrid + +} // namespace Renderer +} // namespace Datagrid +} // namespace Component +} // namespace Antares + +#endif // __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ \ No newline at end of file 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 new file mode 100644 index 0000000000..2c4b47fe62 --- /dev/null +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp @@ -0,0 +1,142 @@ + +#include "adequacy-patch-areas.h" +#include +#include +#include + +#include +#include "../../../toolbox/resources.h" +#include "../../../application/study.h" +#include "../../../application/main.h" +#include "../../../toolbox/resources.h" +#include "../../../toolbox/create.h" +#include "../../../application/wait.h" +#include "../../../toolbox/components/wizardheader.h" +#include "../../../toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h" +#include "../../message.h" + +using namespace Yuni; + +namespace Antares +{ +namespace Window +{ +namespace Options +{ +BEGIN_EVENT_TABLE(AdequacyPatchAreas, wxDialog) +EVT_MOTION(AdequacyPatchAreas::mouseMoved) +END_EVENT_TABLE() + +AdequacyPatchAreas::AdequacyPatchAreas(wxFrame* parent) : + wxDialog(parent, + wxID_ANY, + wxT("Adequacy Patch Areas"), + wxDefaultPosition, + wxSize(380, 410), + wxCLOSE_BOX | wxCAPTION | wxRESIZE_BORDER) +{ + assert(parent); + + // The current study + auto study = Data::Study::Current::Get(); + + // Title of the Form + SetLabel(wxT("Adequacy Patch Areas")); + SetTitle(GetLabel()); + + auto* sizer = new wxBoxSizer(wxVERTICAL); + + // Header + sizer->Add( + Toolbox::Components::WizardHeader::Create(this, + wxT("Options"), + "images/32x32/orderedlist.png", + wxT("Configure areas mode for adequacy patch")), + 0, + wxALL | wxEXPAND | wxFIXED_MINSIZE); + + sizer->AddSpacer(20); + + // Panel + pPanel = new Component::Panel(this); + sizer->Add(pPanel, 1, wxALL | wxEXPAND | wxRESERVE_SPACE_EVEN_IF_HIDDEN); + + wxSizer* hz = new wxBoxSizer(wxHORIZONTAL); + wxSizer* rightSizer = new wxBoxSizer(wxVERTICAL); + wxButton* btn; + + // Datagrid + auto* renderer + = new Component::Datagrid::Renderer::AdequacyPatchAreaGrid(); + renderer->study = study; + auto* grid + = new Component::Datagrid::Component(pPanel, renderer, wxEmptyString, false, true, true); + grid->SetBackgroundColour(GetBackgroundColour()); + pGrid = grid; + renderer->control(grid); + + hz->AddSpacer(13); + hz->Add(grid, 1, wxALL | wxEXPAND); + + hz->Add(rightSizer, 0, wxALL | wxEXPAND); + hz->AddSpacer(20); + pPanel->SetSizer(hz); + sizer->AddSpacer(5); + + sizer->Add(new wxStaticLine(this, wxID_ANY), 0, wxALL | wxEXPAND, 8); + + hz = new wxBoxSizer(wxHORIZONTAL); + btn = Component::CreateButton(this, wxT(" Close "), this, &AdequacyPatchAreas::onClose); + hz->AddStretchSpacer(); + hz->Add(btn, 0, wxEXPAND | wxALL); + hz->Add(20, 5); + sizer->Add(hz, 0, wxALL | wxEXPAND); + sizer->AddSpacer(8); + + sizer->Layout(); + SetSizer(sizer); + + // Recentre the window + Centre(wxBOTH); + + SetAutoLayout(true); + + onUpdateStatus(); + grid->forceRefresh(); +} + +AdequacyPatchAreas::~AdequacyPatchAreas() +{ +} + +void AdequacyPatchAreas::onClose(void*) +{ + Dispatcher::GUI::Close(this); +} + +void AdequacyPatchAreas::mouseMoved(wxMouseEvent&) +{ + // Notify other components as well + Antares::Component::Panel::OnMouseMoveFromExternalComponent(); +} + +void AdequacyPatchAreas::onUpdateStatus() +{ + auto studyptr = Data::Study::Current::Get(); + if (!studyptr) + return; + + Freeze(); + bool b = true; + + wxSizer& sizer = *GetSizer(); + sizer.Show(pPanel, b); + pPanel->Show(b); + sizer.Layout(); + Thaw(); + Refresh(); +} + +} // namespace Options +} // namespace Window +} // namespace Antares 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 new file mode 100644 index 0000000000..482f465e39 --- /dev/null +++ b/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h @@ -0,0 +1,49 @@ +#ifndef __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ +#define __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ + +#include +#include "../../../toolbox/components/datagrid/component.h" +#include +#include + +namespace Antares +{ +namespace Window +{ +namespace Options +{ + +class AdequacyPatchAreas final : public wxDialog +{ +public: + //! \name Constructor & Destructor + //@{ + /*! + ** \brief Default constructor + ** + ** \param parent The parent window + */ + AdequacyPatchAreas(wxFrame* parent); + //! Destructor + virtual ~AdequacyPatchAreas(); + //@} + +protected: + void mouseMoved(wxMouseEvent& evt); + +protected: + void onClose(void*); + void onUpdateStatus(); + +private: + Component::Datagrid::Component* pGrid; + wxWindow* pPanel; + DECLARE_EVENT_TABLE() + +}; // class AdequacyPatchAreas + +} // namespace Options +} // namespace Window +} // namespace Antares + +#endif // __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ From bb70206c936bd6d3d0aeecfb8350abc1b4ece212 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Tue, 12 Apr 2022 10:40:40 +0800 Subject: [PATCH 058/490] makefile --- src/ui/simulator/cmake/components.cmake | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/ui/simulator/cmake/components.cmake b/src/ui/simulator/cmake/components.cmake index ef11214fa0..dbdcdcb4c7 100644 --- a/src/ui/simulator/cmake/components.cmake +++ b/src/ui/simulator/cmake/components.cmake @@ -49,6 +49,8 @@ SET(SRC_TOOLBOX_COM_DBGRID_RENDERERS toolbox/components/datagrid/renderer.hxx toolbox/components/datagrid/renderer.cpp toolbox/components/datagrid/selectionoperation.h + toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h + toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp toolbox/components/datagrid/renderer/area.h toolbox/components/datagrid/renderer/area.cpp toolbox/components/datagrid/renderer/analyzer/areas.h From 10f0315bc0cdcc5516387c4ac083fcd7e9dafa48 Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 12 Apr 2022 09:52:58 +0200 Subject: [PATCH 059/490] clean --- .../adequacy-patch/adequacy-patch-areas.cpp | 22 +------------------ 1 file changed, 1 insertion(+), 21 deletions(-) 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 2c4b47fe62..3daa060564 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 @@ -66,8 +66,7 @@ AdequacyPatchAreas::AdequacyPatchAreas(wxFrame* parent) : wxButton* btn; // Datagrid - auto* renderer - = new Component::Datagrid::Renderer::AdequacyPatchAreaGrid(); + auto* renderer = new Component::Datagrid::Renderer::AdequacyPatchAreaGrid(); renderer->study = study; auto* grid = new Component::Datagrid::Component(pPanel, renderer, wxEmptyString, false, true, true); @@ -100,8 +99,6 @@ AdequacyPatchAreas::AdequacyPatchAreas(wxFrame* parent) : Centre(wxBOTH); SetAutoLayout(true); - - onUpdateStatus(); grid->forceRefresh(); } @@ -120,23 +117,6 @@ void AdequacyPatchAreas::mouseMoved(wxMouseEvent&) Antares::Component::Panel::OnMouseMoveFromExternalComponent(); } -void AdequacyPatchAreas::onUpdateStatus() -{ - auto studyptr = Data::Study::Current::Get(); - if (!studyptr) - return; - - Freeze(); - bool b = true; - - wxSizer& sizer = *GetSizer(); - sizer.Show(pPanel, b); - pPanel->Show(b); - sizer.Layout(); - Thaw(); - Refresh(); -} - } // namespace Options } // namespace Window } // namespace Antares From de04e2ccf7194b72db440a6f4f297e79566890dc Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 12 Apr 2022 09:53:29 +0200 Subject: [PATCH 060/490] clean --- .../windows/options/adequacy-patch/adequacy-patch-areas.h | 1 - 1 file changed, 1 deletion(-) 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 482f465e39..e6941ef986 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 @@ -33,7 +33,6 @@ class AdequacyPatchAreas final : public wxDialog protected: void onClose(void*); - void onUpdateStatus(); private: Component::Datagrid::Component* pGrid; From d862bb046bc1e214737d84a7d6ddfc8d96cef3bd Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 12 Apr 2022 10:33:06 +0200 Subject: [PATCH 061/490] eneble save to txt file and numeric values entry --- .../renderer/adequacy-patch-area-grid.cpp | 22 +++++++++++++++---- 1 file changed, 18 insertions(+), 4 deletions(-) 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 e6f92219b6..6f754e468b 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 @@ -51,9 +51,9 @@ bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) s.trim(); s.toLower(); - bool vir = s == "0" || s == "virtual" || s == "virtual area"; - bool ins = s == "2" || s == "inside" || s == "physical area inside patch"; - bool out = s == "1" || s == "outside" || s == "physical area outside patch"; + bool vir = s.to() == 0 || s == "virtual" || s == "virtual area"; + bool ins = s.to() == 2 || s == "inside" || s == "physical area inside patch"; + bool out = s.to() == 1 || s == "outside" || s == "physical area outside patch"; if (vir) study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; @@ -76,7 +76,21 @@ double AdequacyPatchAreaGrid::cellNumericValue(int, int row) const if (!(!study) && (uint)row < gridSize()) { assert(gridSize() != 0); - // return study->areas.byIndex[row]->adequacyPatchMode; + // for saving into *.txt file + switch (study->areas.byIndex[row]->adequacyPatchMode) + { + case Data::AdequacyPatch::adqmVirtualArea: + return 0.; + break; + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + return 1.; + break; + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + return 2.; + break; + default: + break; + } } return 0.; } From f1a6e672ae14899f7f825a1242dcfa6e321f5793 Mon Sep 17 00:00:00 2001 From: milos Date: Tue, 12 Apr 2022 10:46:45 +0200 Subject: [PATCH 062/490] disable numeric values entry for zero --- .../components/datagrid/renderer/adequacy-patch-area-grid.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 6f754e468b..8f1d7cc434 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 @@ -51,7 +51,7 @@ bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) s.trim(); s.toLower(); - bool vir = s.to() == 0 || s == "virtual" || s == "virtual area"; + bool vir = s == "0" || s == "virtual" || s == "virtual area"; bool ins = s.to() == 2 || s == "inside" || s == "physical area inside patch"; bool out = s.to() == 1 || s == "outside" || s == "physical area outside patch"; From f6ef6b9c2211fb4eb31f2203763ab24b13f0ac93 Mon Sep 17 00:00:00 2001 From: milos Date: Wed, 13 Apr 2022 09:32:00 +0200 Subject: [PATCH 063/490] correction --- src/libs/antares/study/parameters.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index b2032923fa..a7032b39fe 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -675,10 +675,7 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, return value.to(d.adqPatchSaveIntermediateResults); // Price taking order if (key == "price-taking-order") - { return StringToPriceTakingOrder(value, d.adqPatchPriceTakingOrder); - return false; - } // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") return value.to( From 350de894afdae185654796f4cf14bdea81ddfff5 Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 14 Apr 2022 12:07:09 +0200 Subject: [PATCH 064/490] trigger CSR function --- src/ext/yuni/src/yuni/core/math/math.h | 11 +++++++++ src/ext/yuni/src/yuni/core/math/math.hxx | 7 ++++++ src/solver/simulation/economy.cpp | 24 +++++++++++++++++++ .../simulation/sim_calcul_economique.cpp | 8 ++++++- .../sim_structure_probleme_economique.h | 4 ++++ 5 files changed, 53 insertions(+), 1 deletion(-) diff --git a/src/ext/yuni/src/yuni/core/math/math.h b/src/ext/yuni/src/yuni/core/math/math.h index 9fbbee4b8b..96aa08ee33 100644 --- a/src/ext/yuni/src/yuni/core/math/math.h +++ b/src/ext/yuni/src/yuni/core/math/math.h @@ -387,6 +387,17 @@ YUNI_DECL bool IsInteger(T x); template YUNI_DECL U GCD(U u, V v); +/*! +** ** \brief Sums two arrays of the same size a[i]=a[i]+b[i] +** ** +** ** \param a An array +** ** \param b An array +** ** \param num An integer +** ** \return +** */ +template +void sumTwoArrays(T* a, T* b, int num); + } // namespace Math } // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/math/math.hxx b/src/ext/yuni/src/yuni/core/math/math.hxx index e896abc803..d95c20c9e4 100644 --- a/src/ext/yuni/src/yuni/core/math/math.hxx +++ b/src/ext/yuni/src/yuni/core/math/math.hxx @@ -636,6 +636,13 @@ inline U GCD(U u, V v) return u; } +template +void sumTwoArrays(T* a, T* b, int num) +{ + for (uint i = 0; i < num; ++i) + a[i] += b[i]; +} + } // namespace Math } // namespace Yuni diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index b37f3dd7a9..cb61c9cfaa 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -35,6 +35,7 @@ #include "simulation.h" #include "../optimisation/opt_fonctions.h" #include "common-eco-adq.h" +#include using namespace Yuni; @@ -140,6 +141,29 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); } +std::set InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo) +{ + float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; + double sumENS[nbHoursInAWeek] = {}; + std::set triggerCsrSet; + + for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) + { + if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + Math::sumTwoArrays( + sumENS, + pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, + pProblemeHebdo->NombreDePasDeTemps); + } + for (int i = 0; i < nbHoursInAWeek; ++i) + { + if ((int)sumENS[i] >= threshold) + triggerCsrSet.insert(i); + } + return triggerCsrSet; +} + bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index c8c8d87411..c98ff5040c 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -67,11 +67,17 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, { problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); // AdequacyFirstStep will be initialized during the economy solve - // AdqBehaviorMap will be initialized during the economy solve problem.adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq = parameters.setToZero12LinksForAdequacyPatch; problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq = parameters.setToZero11LinksForAdequacyPatch; + problem.adqPatch->SaveIntermediateResults + = true; // = parameters.adqPatchSaveIntermediateResults; + // problem.adqPatch->PriceTakingOrder = parameters.adqPatchPriceTakingOrder; + problem.adqPatch->ThresholdInitiateCurtailmentSharingRule + = 300; // = parameters.seedAdqPatch[adqPatchThresholdInitiateCurtailmentSharingRule]; + problem.adqPatch->ThresholdDisplayLocalMatchingRuleViolations + = 1; // = parameters.seedAdqPatch[adqPatchThresholdDisplayLocalMatchingRuleViolations]; } if (parameters.include.adequacyPatch){ diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index e915e28171..d45188677b 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -501,6 +501,10 @@ struct AdequacyPatchParameters bool AdequacyFirstStep; bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; + bool SaveIntermediateResults; + // AdequacyPatch::AdequacyPatchPTO PriceTakingOrder; + float ThresholdInitiateCurtailmentSharingRule; + float ThresholdDisplayLocalMatchingRuleViolations; }; struct PROBLEME_HEBDO From 33a9956272ee0b01a5f66ceadcbb0bc7f2d71928 Mon Sep 17 00:00:00 2001 From: milos Date: Thu, 14 Apr 2022 13:10:34 +0200 Subject: [PATCH 065/490] sets are passed by reference! --- src/solver/simulation/economy.cpp | 5 ++--- 1 file changed, 2 insertions(+), 3 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index cb61c9cfaa..5e24002824 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -141,11 +141,11 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); } -std::set InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo) +void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, + std::set& triggerCsrSet) { float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; double sumENS[nbHoursInAWeek] = {}; - std::set triggerCsrSet; for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) { @@ -161,7 +161,6 @@ std::set InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHe if ((int)sumENS[i] >= threshold) triggerCsrSet.insert(i); } - return triggerCsrSet; } bool Economy::year(Progression::Task& progression, From b0b53e1104c4e97cc6c5752dfea8fe43f1d3fc40 Mon Sep 17 00:00:00 2001 From: milos Date: Fri, 15 Apr 2022 13:26:28 +0200 Subject: [PATCH 066/490] update reference-guide.md --- docs/reference-guide/1-reference-guide.md | 16 ++++++++++++---- 1 file changed, 12 insertions(+), 4 deletions(-) diff --git a/docs/reference-guide/1-reference-guide.md b/docs/reference-guide/1-reference-guide.md index 625134b2ba..7d2fce5779 100644 --- a/docs/reference-guide/1-reference-guide.md +++ b/docs/reference-guide/1-reference-guide.md @@ -366,7 +366,18 @@ 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}}}$$ -- **Adequacy Patch** +- **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)_ + - _Save intermediate results (false / true)_ + - _Thresholds + - _Initiate curtailment sharing rule_ + - _Display local maching rule violations_ - **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. @@ -386,9 +397,6 @@ given back their regular capacities (infinite for those being set on "set to inf - _Strategic reserve (include / ignore)_ - _Spinning reserve (include / ignore)_ - _Export mps (false/true)_ - - _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)_ - _Simplex optimization range # 4_ _(day / week)_ - _Unfeasible problems behavior (Error Dry/ Error Verbose/ Warning Dry/ Warning Verbose_ From e2275866d9b6a15d0abd18badf3435556939be53 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 09:13:53 +0800 Subject: [PATCH 067/490] CSR draft 1 --- src/solver/simulation/economy.cpp | 48 ++++++++++++++++++- .../sim_structure_probleme_economique.h | 33 ++++++++++++- 2 files changed, 78 insertions(+), 3 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 5e24002824..c2408a3d41 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -147,6 +147,10 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; double sumENS[nbHoursInAWeek] = {}; + //init sumENS[]. + for (int j = 0; j < nbHoursInAWeek; ++j) + sumENS[j] = 0.0; + for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) { if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] @@ -154,7 +158,8 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, Math::sumTwoArrays( sumENS, pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, - pProblemeHebdo->NombreDePasDeTemps); + // pProblemeHebdo->NombreDePasDeTemps); + nbHoursInAWeek); //use nbHoursInAWeek seems more clear } for (int i = 0; i < nbHoursInAWeek; ++i) { @@ -163,6 +168,29 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, } } +void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hourInWeek = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_HEBDO* pWeeklyProblem = hourlyCsrProblem.pWeeklyProblemBelongedTo; + //CSR todo + + + + return; +} + +void UpdateWeeklyResultAfterCSR(PROBLEME_HEBDO* pProblemeHebdo) +{ + std::vector hourlyCsrProblems = pProblemeHebdo->houlyCsrProblems; + + for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) + { + RESULTATS_HORAIRES* ResultatsHoraires = pProblemeHebdo->ResultatsHoraires[area]; + //CSR todo update ResultatsHoraires for each area using hourlyCsrProblems + } + return; +} + bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, @@ -201,6 +229,22 @@ bool Economy::year(Progression::Task& progression, { OPT_OptimisationHebdomadaireAdqPatch( pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); + + //CSR todo: shall we start the CSR here, or shall we start the CSR after updatingWeeklyFinalHydroLevel? + std::set hoursInWeekTriggerCsrSet; + InitiateCurtailmentSharingRuleIndexSet(pProblemesHebdo[numSpace], hoursInWeekTriggerCsrSet); + if( hoursInWeekTriggerCsrSet.size() > 0) + { + pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems from previous week in case there is any + for(int hourInWeek : hoursInWeekTriggerCsrSet) + { + HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); + pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); + OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); //CSR todo + } + UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); //CSR todo + pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems of current week after CSR + } } else { @@ -222,6 +266,8 @@ bool Economy::year(Progression::Task& progression, updatingWeeklyFinalHydroLevel(study, *pProblemesHebdo[numSpace], nbHoursInAWeek); + //CSR todo: shall we start here, or shall we start the CSR directly after OPT_OptimisationHebdomadaireAdqPatch + variables.weekBegin(state); uint previousHourInTheYear = state.hourInTheYear; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index d45188677b..ced4cb8686 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -506,7 +506,7 @@ struct AdequacyPatchParameters float ThresholdInitiateCurtailmentSharingRule; float ThresholdDisplayLocalMatchingRuleViolations; }; - +class HOURLY_CSR_PROBLEM; struct PROBLEME_HEBDO { /* Business problem */ @@ -613,7 +613,8 @@ struct PROBLEME_HEBDO /* Adequacy Patch */ std::unique_ptr adqPatch = nullptr; AdequacyPatchRuntimeData adequacyPatchRuntimeData; - + std::vector houlyCsrProblems; //CSR: this should be an array for the hours triggered CSR + optimizationStatistics optimizationStatistics_object; /* Hydro management */ double* CoefficientEcretementPMaxHydraulique; @@ -716,4 +717,32 @@ struct PROBLEME_HEBDO double maxPminThermiqueByDay[366]; }; +class HOURLY_CSR_RESULT +{ + //CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside RESULTATS_HORAIRES? +}; + +// hourly CSR problem structure +class HOURLY_CSR_PROBLEM +{ +public: + int hourInWeekTriggeredCsr; + PROBLEME_HEBDO* pWeeklyProblemBelongedTo; + HOURLY_CSR_PROBLEM(int hourInWeek, PROBLEME_HEBDO* pProblemeHebdo) + { + hourInWeekTriggeredCsr = hourInWeek; + pWeeklyProblemBelongedTo = pProblemeHebdo; + }; + + + /* variables */ + std::vector ENS; + /* Results */ + HOURLY_CSR_RESULT hourlyResult; //CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside RESULTATS_HORAIRES? + + //CSR todo: there should be structures for building the optimization problem like: + // CORRESPONDANCES_DES_VARIABLES* + // CORRESPONDANCES_DES_CONTRAINTES* +}; + #endif From 2139174bf811bd9029fe1086b4f709fa755ae889 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 10:14:40 +0800 Subject: [PATCH 068/490] csr draft 2 --- .../optimisation/opt_appel_solveur_quadratique.cpp | 6 ++++++ ...uction_matrice_des_contraintes_cas_quadratique.cpp | 6 ++++++ ..._construction_variables_optimisees_quadratique.cpp | 6 ++++++ src/solver/optimisation/opt_fonctions.h | 6 ++++++ .../opt_gestion_des_bornes_cas_quadratique.cpp | 6 ++++++ .../opt_gestion_des_couts_cas_quadratique.cpp | 6 ++++++ .../opt_gestion_second_membre_cas_quadratique.cpp | 6 ++++++ src/solver/simulation/economy.cpp | 11 ++++++++--- 8 files changed, 50 insertions(+), 3 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 3ce5b777fa..8286bef436 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -183,3 +183,9 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr return false; } } + + +void OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + //CSR todo call solver for quadratic houly CSR +} \ No newline at end of file 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 index 7f6c2f69f8..024d785cc7 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -91,3 +91,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* MemFree(Pi); MemFree(Colonne); } + + +void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + //CSR todo build matrix of constraint of hourly CSR quadratic problem +} \ No newline at end of file diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 46440a51c9..578a8e1fad 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -57,3 +57,9 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H } ProblemeAResoudre->NombreDeVariables = NombreDeVariables; } + +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + //CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. + return; +} \ No newline at end of file diff --git a/src/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/opt_fonctions.h index d25d1c402c..7aeafba1ed 100644 --- a/src/solver/optimisation/opt_fonctions.h +++ b/src/solver/optimisation/opt_fonctions.h @@ -36,8 +36,10 @@ void OPT_NumeroDeJourDuPasDeTemps(PROBLEME_HEBDO*); void OPT_NumeroDIntervalleOptimiseDuPasDeTemps(PROBLEME_HEBDO*); void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBDO*); void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_HEBDO*); +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaire(PROBLEME_HEBDO*, uint); void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO*); +void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_InitialiserLesPminHebdo(PROBLEME_HEBDO*); void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise(PROBLEME_HEBDO*); void OPT_MaxDesPmaxHydrauliques(PROBLEME_HEBDO*); @@ -46,13 +48,17 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO*, const int, const int); void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO*, int); +void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO*, int, int, int); void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO*, int); +void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO*, const int, const int, uint); void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO*, int); +void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); +void OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&); bool OPT_PilotageOptimisationLineaire(PROBLEME_HEBDO*, uint); void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); 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 233720ad33..9077fff5c1 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -94,3 +94,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; } } + +void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + //CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic problem + return; +} \ No newline at end of file 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 5761cf1341..6979abf2f4 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -57,3 +57,9 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH = ValeursDeResistances->ResistanceApparente[Interco]; } } + +void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + //CSR todo initialize the cost for variables in objective function of hourly CSR quadratic problem. + return; +} \ No newline at end of file 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 5a18c70e63..dbac506a5b 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -47,3 +47,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme = ProblemeHebdo->SoldeMoyenHoraire[PdtHebdo]->SoldeMoyenDuPays[Pays]; } } + +void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + //CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. + return; +} \ No newline at end of file diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index c2408a3d41..d1d077ef1f 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -173,9 +173,14 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP int hourInWeek = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_HEBDO* pWeeklyProblem = hourlyCsrProblem.pWeeklyProblemBelongedTo; //CSR todo - - - + OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); + OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); + OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); + OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); + OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblem, hourlyCsrProblem); + OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblem->ProblemeAResoudre, hourlyCsrProblem); + + //example to build an optim problem can be found in OPT_PilotageOptimisationQuadratique return; } From e1b2502609834bb6f1a8905f1d93142e73ca9fc1 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 10:28:17 +0800 Subject: [PATCH 069/490] csr draft 3 --- .../opt_appel_solveur_quadratique.cpp | 127 +++++++++++++++++- src/solver/optimisation/opt_fonctions.h | 2 +- src/solver/simulation/economy.cpp | 2 +- .../sim_structure_probleme_economique.h | 4 +- 4 files changed, 131 insertions(+), 4 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 8286bef436..c7848a7541 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -185,7 +185,132 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr } -void OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { //CSR todo call solver for quadratic houly CSR + //this part should be exactly the same as in OPT_AppelDuSolveurQuadratique, except for some log. todo refactoring + int Var; + double* pt; + double ToleranceSurLAdmissibilite; + int ChoixToleranceParDefautSurLAdmissibilite; + double ToleranceSurLaStationnarite; + int ChoixToleranceParDefautSurLaStationnarite; + double ToleranceSurLaComplementarite; + int ChoixToleranceParDefautSurLaComplementarite; + + PROBLEME_POINT_INTERIEUR Probleme; + + ToleranceSurLAdmissibilite = 1.e-5; + ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; + + ToleranceSurLaStationnarite = 1.e-5; + ChoixToleranceParDefautSurLaStationnarite = OUI_PI; + + ToleranceSurLaComplementarite = 1.e-5; + ChoixToleranceParDefautSurLaComplementarite = OUI_PI; + + Probleme.NombreMaxDIterations = -1; + Probleme.CoutQuadratique = ProblemeAResoudre->CoutQuadratique; + Probleme.CoutLineaire = ProblemeAResoudre->CoutLineaire; + Probleme.X = ProblemeAResoudre->X; + Probleme.Xmin = ProblemeAResoudre->Xmin; + Probleme.Xmax = ProblemeAResoudre->Xmax; + Probleme.NombreDeVariables = ProblemeAResoudre->NombreDeVariables; + Probleme.TypeDeVariable = ProblemeAResoudre->TypeDeVariable; + + Probleme.VariableBinaire = (char*)ProblemeAResoudre->CoutsReduits; + + Probleme.NombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; + Probleme.IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne; + Probleme.NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes; + Probleme.IndicesColonnes = ProblemeAResoudre->IndicesColonnes; + Probleme.CoefficientsDeLaMatriceDesContraintes + = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes; + Probleme.Sens = ProblemeAResoudre->Sens; + Probleme.SecondMembre = ProblemeAResoudre->SecondMembre; + + Probleme.AffichageDesTraces = NON_PI; + + Probleme.UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; + Probleme.ToleranceDAdmissibilite = ToleranceSurLAdmissibilite; + + Probleme.UtiliserLaToleranceDeStationnariteParDefaut + = ChoixToleranceParDefautSurLaStationnarite; + Probleme.ToleranceDeStationnarite = ToleranceSurLaStationnarite; + + Probleme.UtiliserLaToleranceDeComplementariteParDefaut + = ChoixToleranceParDefautSurLaComplementarite; + Probleme.ToleranceDeComplementarite = ToleranceSurLaComplementarite; + + Probleme.CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; + + Probleme.CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; + Probleme.CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; + + PI_Quamin(&Probleme); + + ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; + if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) + { + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + if (pt) + *pt = ProblemeAResoudre->X[Var]; + } + + return true; + } + else + { + logs.warning() << "CSR Quadratic Optimization: No solution, hour in week: " << hourlyCsrProblem.hourInWeekTriggeredCsr; //todo refactoring + + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + if (pt) + *pt = std::numeric_limits::quiet_NaN(); + } + +#ifndef NDEBUG + + { + logs.info(); + + logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; + + logs.info() << "Here is the trace:"; + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", + Var, + ProblemeAResoudre->CoutLineaire[Var], + ProblemeAResoudre->CoutQuadratique[Var]); + } + for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) + { + logs.info().appendFormat("Constraint %ld sens %c B %e", + Cnt, + ProblemeAResoudre->Sens[Cnt], + ProblemeAResoudre->SecondMembre[Cnt]); + + int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; + int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; + for (; il < ilMax; ++il) + { + Var = ProblemeAResoudre->IndicesColonnes[il]; + logs.info().appendFormat( + " coeff %e var %ld xmin %e xmax %e type %ld", + ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], + Var, + ProblemeAResoudre->Xmin[Var], + ProblemeAResoudre->Xmax[Var], + ProblemeAResoudre->TypeDeVariable[Var]); + } + } + } +#endif + + return false; + } } \ No newline at end of file diff --git a/src/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/opt_fonctions.h index 7aeafba1ed..b5545ac9b3 100644 --- a/src/solver/optimisation/opt_fonctions.h +++ b/src/solver/optimisation/opt_fonctions.h @@ -58,7 +58,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); -void OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&); +bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&); bool OPT_PilotageOptimisationLineaire(PROBLEME_HEBDO*, uint); void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index d1d077ef1f..443b81d02f 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -178,7 +178,7 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblem->ProblemeAResoudre, hourlyCsrProblem); + OPT_AppelDuSolveurQuadratique_CSR(hourlyCsrProblem.ProblemeAResoudre, hourlyCsrProblem); //example to build an optim problem can be found in OPT_PilotageOptimisationQuadratique return; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index ced4cb8686..4257a7bb11 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -506,7 +506,9 @@ struct AdequacyPatchParameters float ThresholdInitiateCurtailmentSharingRule; float ThresholdDisplayLocalMatchingRuleViolations; }; + class HOURLY_CSR_PROBLEM; + struct PROBLEME_HEBDO { /* Business problem */ @@ -734,7 +736,7 @@ class HOURLY_CSR_PROBLEM pWeeklyProblemBelongedTo = pProblemeHebdo; }; - + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; /* variables */ std::vector ENS; /* Results */ From 9d23a46bb3f0e0397e04f93874b6551240d891b3 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 10:37:45 +0800 Subject: [PATCH 070/490] tmp --- src/solver/simulation/sim_structure_probleme_economique.h | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 4257a7bb11..4359b7fd9c 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -736,7 +736,6 @@ class HOURLY_CSR_PROBLEM pWeeklyProblemBelongedTo = pProblemeHebdo; }; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; /* variables */ std::vector ENS; /* Results */ From 5536dd535aa8e0b19ffa31a814d587a7dd8f5964 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 10:45:20 +0800 Subject: [PATCH 071/490] tmp --- src/solver/simulation/economy.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 443b81d02f..d194496ab1 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -172,13 +172,15 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP { int hourInWeek = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_HEBDO* pWeeklyProblem = hourlyCsrProblem.pWeeklyProblemBelongedTo; + + OPT_LiberationProblemesSimplexe(pWeeklyProblem); //CSR todo !!! do we do this here ???? or do we create another PROBLEME_ANTARES_A_RESOUDRE inside HOURLY_CSR_PROBLEM ???? //CSR todo OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_AppelDuSolveurQuadratique_CSR(hourlyCsrProblem.ProblemeAResoudre, hourlyCsrProblem); + OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblem->ProblemeAResoudre, hourlyCsrProblem); //example to build an optim problem can be found in OPT_PilotageOptimisationQuadratique return; From af716e09e164a7407e7b6a45401f4a81a6ccadff Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 14:51:00 +0800 Subject: [PATCH 072/490] tmp --- ...atrice_des_contraintes_cas_quadratique.cpp | 13 ++++++++++ ...ction_variables_optimisees_quadratique.cpp | 25 +++++++++++++++++++ ...opt_gestion_des_bornes_cas_quadratique.cpp | 9 ++++++- 3 files changed, 46 insertions(+), 1 deletion(-) 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 index 024d785cc7..671d1c53e5 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -96,4 +96,17 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { //CSR todo build matrix of constraint of hourly CSR quadratic problem + //CSR todo: let us first to create an optim problem like this: + // variables: ENS of each area + // objective function: Sum (2 * (ENS)^2) of all area + // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // constraint: No constraint + //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + ProblemeAResoudre->NombreDeContraintes = 0; + ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; } \ No newline at end of file diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 578a8e1fad..ee2b8c1217 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -61,5 +61,30 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { //CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. + + //CSR todo: let us first to create an optim problem like this: + // variables: ENS of each area + // objective function: Sum (2 * (ENS)^2) of all area + // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // constraint: No constraint + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + int NumberOfVariables = 0; + + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + + //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + assert(ProblemeAResoudre != NULL); + + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; + + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + } + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; return; } \ No newline at end of file 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 9077fff5c1..09fcbfd852 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -97,6 +97,13 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - //CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic problem + //CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic + //CSR todo: let us first to create an optim problem like this: + // variables: ENS of each area + // objective function: Sum (2 * (ENS)^2) of all area + // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // constraint: No constraint + //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + return; } \ No newline at end of file From fc54751609ac65c5889d3412939c538d1ec5cca0 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 20 Apr 2022 15:15:39 +0800 Subject: [PATCH 073/490] tmp --- src/solver/simulation/economy.cpp | 1 + src/solver/simulation/sim_structure_probleme_economique.h | 3 ++- 2 files changed, 3 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index d194496ab1..ef1af55946 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -245,6 +245,7 @@ bool Economy::year(Progression::Task& progression, pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems from previous week in case there is any for(int hourInWeek : hoursInWeekTriggerCsrSet) { + //CSR todo if we reuse pProblemesHebdo, there will be no need to create HOURLY_CSR_PROBLEM HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); //CSR todo diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 4359b7fd9c..ee5d47cea4 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -737,7 +737,8 @@ class HOURLY_CSR_PROBLEM }; /* variables */ - std::vector ENS; + // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM + /* Results */ HOURLY_CSR_RESULT hourlyResult; //CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside RESULTATS_HORAIRES? From 3d3a3f933d8ba2a1ce19e3a7bf8c090aba263a61 Mon Sep 17 00:00:00 2001 From: hugo-antoine-rtei <73881097+hugo-antoine-rtei@users.noreply.github.com> Date: Wed, 20 Apr 2022 16:05:11 +0200 Subject: [PATCH 074/490] Adequacy Patch - Local Matching Rule 15/03 (#597) * adq ini file with default value false * typo * created the option button(false/true) for adequacy patch and updated the ref-guide * typo * ui selector * deleted boolean cast & clang-format on new files * clang format * adq patch mode * clang format * added new header file for DENS * changes to the filles * syntax error * bring back original all.h for adequacy * clang format * assigning dummy values to DENS * minor name change * default value 1 * typo * column name change and typo * change dens dummy value to zero * Adequacy patch: 2 rounds run / boundary update / output (#10) * created AdequacyFirstStep attribute * reference fix * save DENS value from 1st run * add ::SIM_RenseignementProblemeHebdo before 2nd run * save DENS in result and show in UI * refacto minor * solution for upperbound update (#11) * draft solution for upperbound update * refacto * minor refacto * clean * clean * DENS only for type 2 area * review modif Co-authored-by: rtei-pw Co-authored-by: rtei-pw <92968374+rtei-pw@users.noreply.github.com> * NTC constraints management (#8) * set NTC constraints to 0 in a dummy if loop * Small changes to the dummy loops * insert adqPatchMode data in PROBLEME_HEBDO struct * 0<->0 connections allowed * implement specifications logic into NTC constraint * shift SetNTCForAdequacyFirstStep to separate *.cpp * clang format * Hugo's comments implementation * clean * UI NTC selector for adequacy patch (#12) * update reference guide * add options to problem.hebdo * ui options for ntc constraints for adequacy patch * naming and comments improvements * ref.guide description improvement * plug UI into SetNTCForAdequacyFirstStep * Rte comments 1. 2. 11. implementation (#20) * name changes in domesticUnsuppliedEnergy.h * 11. enumeration * review modif 3. 5. 7, 8 (#16) * 5. consider previously set bounds * 7. remove not multiple * 8. add todo arround SIM_ * 3. namespace * 4. change Start&End to Origine&Extremity * 3. bis fix Co-authored-by: milos * 10. make adq struct * 11. additional changes for comment 11 (#22) * 10. make adqPatch pointer * group adq parameters in a sub category * bug fix * small typo * change NTC name and avoid using directives * placed NTC function inside a AdqPatch namespace * rename Ntc11 & Ntc12 to be more expressive * change End and Start in ntc function * use map for SetNTCForAdequacyFirstStep function * use map for SetNTCForAdqFirstStep function update! * make type std::pair * clang format * make setBounds(No)AdqPatch functions * r2 review changes part 1 (#30) * review: These two ifs can be merged into one. * review: Create a new function called OPT_OptimisationHebdomadaireAdqPatch, call it here. * review: domestic unsupplied energy (comment) * adq-patch is only for studyMode == economy * move behaviorMap to AdequacyPatchParameters struct * attempt at making map creation clearer * using just the Antares::Data namespace * adq runtime data (#35) * adq runtime data * conflict * RTE Comment implementation 3 (#34) * typo Economy * add comment to explain type 1 and type 2 for adq * using namespace AdequacyPatch inside adq_patch.cpp * if there is no area in the adq-patch throw error * divide to smaller functions SetNTCForAdqFirstStep * clang * check that adq patch is on in error handling * bug fix Co-authored-by: rtei-pw Co-authored-by: milos Co-authored-by: rtei-pw <92968374+rtei-pw@users.noreply.github.com> Co-authored-by: Milos <97689304+Milos-RTEi@users.noreply.github.com> --- docs/reference-guide/1-reference-guide.md | 3 + src/libs/antares/exception/LoadingError.cpp | 10 + src/libs/antares/exception/LoadingError.hpp | 13 + src/libs/antares/study/area/area.cpp | 3 + src/libs/antares/study/area/area.h | 4 + src/libs/antares/study/area/list.cpp | 67 ++++ .../antares/study/cleaner/cleaner-v20.cpp | 2 + src/libs/antares/study/fwd.h | 41 +++ src/libs/antares/study/parameters.cpp | 16 + src/libs/antares/study/parameters.h | 11 + src/solver/application.cpp | 33 ++ src/solver/cmake/solver.cmake | 2 + src/solver/cmake/variable.cmake | 1 + src/solver/optimisation/adequacy_patch.cpp | 146 +++++++++ src/solver/optimisation/adequacy_patch.h | 107 +++++++ .../opt_gestion_des_bornes_cas_lineaire.cpp | 19 +- src/solver/simulation/economy.cpp | 39 ++- .../simulation/sim_alloc_probleme_hebdo.cpp | 5 +- .../simulation/sim_calcul_economique.cpp | 15 + .../sim_structure_probleme_economique.h | 39 ++- src/solver/variable/economy/all.h | 68 +++-- .../economy/domesticUnsuppliedEnergy.h | 288 ++++++++++++++++++ src/ui/simulator/application/study.cpp | 1 + src/ui/simulator/application/study.h | 5 + .../windows/inspector/accumulator.hxx | 25 ++ src/ui/simulator/windows/inspector/frame.cpp | 8 + src/ui/simulator/windows/inspector/frame.h | 2 + .../windows/inspector/property.update.cpp | 23 ++ .../options/optimization/optimization.cpp | 120 +++++++- .../options/optimization/optimization.h | 4 + 30 files changed, 1079 insertions(+), 41 deletions(-) create mode 100644 src/solver/optimisation/adequacy_patch.cpp create mode 100644 src/solver/optimisation/adequacy_patch.h create mode 100644 src/solver/variable/economy/domesticUnsuppliedEnergy.h diff --git a/docs/reference-guide/1-reference-guide.md b/docs/reference-guide/1-reference-guide.md index b3667d8eb1..36303e7a85 100644 --- a/docs/reference-guide/1-reference-guide.md +++ b/docs/reference-guide/1-reference-guide.md @@ -384,6 +384,9 @@ given back their regular capacities (infinite for those being set on "set to inf - _Strategic reserve (include / ignore)_ - _Spinning reserve (include / ignore)_ - _Export mps (false/true)_ + - _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)_ - _Simplex optimization range # 4_ _(day / week)_ - _Unfeasible problems behavior (Error Dry/ Error Verbose/ Warning Dry/ Warning Verbose_ diff --git a/src/libs/antares/exception/LoadingError.cpp b/src/libs/antares/exception/LoadingError.cpp index 82ba825ca3..8fc9d1fe75 100644 --- a/src/libs/antares/exception/LoadingError.cpp +++ b/src/libs/antares/exception/LoadingError.cpp @@ -123,5 +123,15 @@ CommandLineArguments::CommandLineArguments(uint errors) : { } +IncompatibleStudyModeForAdqPatch::IncompatibleStudyModeForAdqPatch() : + 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") +{ +} + } // namespace Error } // namespace Antares diff --git a/src/libs/antares/exception/LoadingError.hpp b/src/libs/antares/exception/LoadingError.hpp index 2181cef0aa..44d269b029 100644 --- a/src/libs/antares/exception/LoadingError.hpp +++ b/src/libs/antares/exception/LoadingError.hpp @@ -166,5 +166,18 @@ class CommandLineArguments : public LoadingError public: explicit CommandLineArguments(uint errors); }; + +class IncompatibleStudyModeForAdqPatch : public LoadingError +{ +public: + IncompatibleStudyModeForAdqPatch(); +}; + +class NoAreaInsideAdqPatchMode : public LoadingError +{ +public: + NoAreaInsideAdqPatchMode(); +}; + } // namespace Error } // namespace Antares diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index cefa226157..da7d734762 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,6 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), + adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -70,6 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), + adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -89,6 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), + adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 923da23412..31fca1e628 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -225,6 +225,8 @@ class Area final : private Yuni::NonCopyable uint index; //! Enabled bool enabled; + //! Use adequacy patch for this area + Data::AdequacyPatch::AdequacyPatchMode adequacyPatchMode; /*@}*/ //! \name Associate data */ @@ -347,6 +349,8 @@ class Area final : private Yuni::NonCopyable bool saveAreaOptimisationIniFile(const Area& area, const Yuni::Clob& buffer); +bool saveAreaAdequacyPatchIniFile(const Area& area, const Yuni::Clob& buffer); + /*! ** \brief A list of areas ** diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 5eb2eaa8ed..1d4228bf28 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -203,6 +203,11 @@ static bool AreaListSaveToFolderSingleArea(const Area& area, Clob& buffer, const << "optimization.ini"; ret = saveAreaOptimisationIniFile(area, buffer) and ret; + // Adequacy ini + buffer.clear() << folder << SEP << "input" << SEP << "areas" << SEP << area.id << SEP + << "adequacy_patch.ini"; + ret = saveAreaAdequacyPatchIniFile(area, buffer) and ret; + // Reserves: primary, strategic, dsm, d-1... buffer.clear() << folder << SEP << "input" << SEP << "reserves" << SEP << area.id << ".txt"; ret = area.reserves.saveToCSVFile(buffer) and ret; @@ -326,6 +331,30 @@ bool saveAreaOptimisationIniFile(const Area& area, const Clob& buffer) return ini.save(buffer); } +bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) +{ + IniFile ini; + IniFile::Section* section = ini.addSection("adequacy-patch"); + int value; + switch (area.adequacyPatchMode) + { + case Data::AdequacyPatch::adqmVirtualArea: + value = 0; + break; + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + value = 1; + break; + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + value = 2; + break; + default: + value = 1; //default adqmPhysicalAreaOutsideAdqPatch + break; + } + section->add("adequacy-patch-mode", value); + return ini.save(buffer); +} + AreaList::AreaList(Study& study) : byIndex(nullptr), pStudy(study) { } @@ -1040,6 +1069,44 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, area.renewable.list.flush(); } + // Adequacy patch + if (study.header.version >= 820) + { + buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP + << "adequacy_patch.ini"; + IniFile ini; + if (ini.open(buffer)) + { + auto* section = ini.find("adequacy-patch"); + for (auto* p = section->firstProperty; p; p = p->next) + { + CString<30, false> tmp; + tmp = p->key; + tmp.toLower(); + if (tmp == "adequacy-patch-mode") + { + auto value = p->value.to(); + switch (value) + { + case 0: + area.adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + break; + case 1: + area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + break; + case 2: + area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + break; + default: + area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + break; + } + continue; + } + } + } + } + // Nodal Optimization if (study.header.version >= 330) { diff --git a/src/libs/antares/study/cleaner/cleaner-v20.cpp b/src/libs/antares/study/cleaner/cleaner-v20.cpp index 944c4d27e6..c2f1988f84 100644 --- a/src/libs/antares/study/cleaner/cleaner-v20.cpp +++ b/src/libs/antares/study/cleaner/cleaner-v20.cpp @@ -195,6 +195,8 @@ static void PreflightVersion20_area(PathList& e, PathList& p, const Area* area, e.add(buffer); buffer.clear() << "input/areas/" << id << "/optimization.ini"; e.add(buffer); + buffer.clear() << "input/areas/" << id << "/adequacy_patch.ini"; + e.add(buffer); // Interconnections buffer.clear() << "input/links/" << id; diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index c4e9c59262..5b70500acf 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -557,4 +557,45 @@ class Sets; } // namespace Data } // namespace Antares +namespace Antares +{ +namespace Data +{ +namespace AdequacyPatch +{ + +/*! +** \brief Types of Adequacy patch mode +*/ +enum AdequacyPatchMode +{ + //! Virtual area in adq patch + adqmVirtualArea = 0, + //! Physical Area outside the adq-patch + adqmPhysicalAreaOutsideAdqPatch, + //! Physical Area inside the adq-patch + adqmPhysicalAreaInsideAdqPatch + +}; // enum AdequacyPatchMode + +/*! +** \brief Setting Link Capacity (NTC) for Adequacy patch first step +*/ +enum LinkCapacityForAdequacyPatchFirstStep +{ + //! Leave NTC local values + leaveLocalValues = 0, + //! Set NTC to zero + setToZero, + //! set only origine->extremity NTC to zero + setOrigineExtremityToZero, + //! set only extremity->origine NTC to zero + setExtremityOrigineToZero + +}; // enum NTC + +} // namespace AdequacyPatch +} // namespace Data +} // namespace Antares + #endif // __ANTARES_LIBS_STUDY_FWD_H__ diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index e7d55d1536..c108bd1ee9 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -305,6 +305,9 @@ void Parameters::reset() simplexOptimizationRange = sorWeek; include.exportMPS = false; + include.adequacyPatch = false; + setToZero12LinksForAdequacyPatch = true; + setToZero11LinksForAdequacyPatch = true; include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -552,6 +555,12 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, return value.to(d.include.reserve.primary); if (key == "include-exportmps") return value.to(d.include.exportMPS); + if (key == "include-adequacypatch") + return value.to(d.include.adequacyPatch); + if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch") + return value.to(d.setToZero12LinksForAdequacyPatch); + if (key == "set-to-null-ntc-between-physical-out-for-first-step-adq-patch") + return value.to(d.setToZero11LinksForAdequacyPatch); if (key == "include-exportstructure") return value.to(d.include.exportStructure); if (key == "include-unfeasible-problem-behavior") @@ -1546,6 +1555,8 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) logs.info() << " :: ignoring min up/down time for thermal clusters"; if (!include.exportMPS) logs.info() << " :: ignoring export mps"; + if (!include.adequacyPatch) + logs.info() << " :: ignoring adequacy patch"; if (!include.exportStructure) logs.info() << " :: ignoring export structure"; if (!include.hurdleCosts) @@ -1707,6 +1718,11 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-primaryreserve", include.reserve.primary); section->add("include-exportmps", include.exportMPS); + section->add("include-adequacypatch", include.adequacyPatch); + section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch", + setToZero12LinksForAdequacyPatch); + section->add("set-to-null-ntc-between-physical-out-for-first-step-adq-patch", + setToZero11LinksForAdequacyPatch); section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 13eae9876b..86e72cc814 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -416,6 +416,9 @@ class Parameters final //! a flag to export all mps files bool exportMPS; + //! a flag to use Adequacy patch + bool adequacyPatch; + //! a flag to export structure needed for Antares XPansion bool exportStructure; @@ -502,6 +505,14 @@ class Parameters final SimplexOptimization simplexOptimizationRange; //@} + //! 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. + bool setToZero12LinksForAdequacyPatch; + //! 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. + bool setToZero11LinksForAdequacyPatch; + //! \name Scenariio Builder - Rules //@{ //! The current active rules for building scenarios (useful if building mode == custom) diff --git a/src/solver/application.cpp b/src/solver/application.cpp index e3b212fd3d..1218221aa5 100644 --- a/src/solver/application.cpp +++ b/src/solver/application.cpp @@ -84,6 +84,36 @@ void checkSimplexRangeHydroHeuristic(Antares::Data::SimplexOptimization optRange } } +// Adequacy Patch can only be used with Economy Study/Simulation Mode. +void checkAdqPatchStudyModeEconomyOnly(const bool adqPatchOn, + const Antares::Data::StudyMode studyMode) +{ + if ((studyMode != Antares::Data::StudyMode::stdmEconomy) && adqPatchOn) + { + throw Error::IncompatibleStudyModeForAdqPatch(); + } +} +// When Adequacy Patch is on at least one area must be inside Adequacy patch mode. +void checkAdqPatchContainsAdqPatchArea(const bool adqPatchOn, const Antares::Data::AreaList& areas) +{ + if (adqPatchOn) + { + bool containsAdqArea = false; + for (uint i = 0; i < areas.size(); ++i) + { + const auto& area = *(areas.byIndex[i]); + if (area.adequacyPatchMode + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + containsAdqArea = true; + break; + } + } + if (!containsAdqArea) + throw Error::NoAreaInsideAdqPatchMode(); + } +} + void checkMinStablePower(bool tsGenThermal, const Antares::Data::AreaList& areas) { if (tsGenThermal) @@ -239,6 +269,9 @@ void Application::prepare(int argc, char* argv[]) checkSimplexRangeHydroHeuristic(pParameters->simplexOptimizationRange, pStudy->areas); + checkAdqPatchStudyModeEconomyOnly(pParameters->include.adequacyPatch, pParameters->mode); + checkAdqPatchContainsAdqPatchArea(pParameters->include.adequacyPatch, pStudy->areas); + bool tsGenThermal = (0 != (pStudy->parameters.timeSeriesToGenerate & Antares::Data::TimeSeries::timeSeriesThermal)); diff --git a/src/solver/cmake/solver.cmake b/src/solver/cmake/solver.cmake index 5492128ed1..2c5fcdb33c 100644 --- a/src/solver/cmake/solver.cmake +++ b/src/solver/cmake/solver.cmake @@ -51,6 +51,8 @@ set(RTESOLVER_OPT optimisation/opt_nombre_min_groupes_demarres_couts_demarrage.cpp optimisation/opt_export_structure.h optimisation/opt_export_structure.cpp + optimisation/adequacy_patch.h + optimisation/adequacy_patch.cpp utils/ortools_utils.h utils/ortools_utils.cpp diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 953de4178e..84197f5502 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -129,6 +129,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/waterValue.h variable/economy/hydroCost.h variable/economy/unsupliedEnergy.h + variable/economy/domesticUnsuppliedEnergy.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp new file mode 100644 index 0000000000..8aa7914c07 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -0,0 +1,146 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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/simulation.h" +#include "adequacy_patch.h" + +using namespace Antares::Data::AdequacyPatch; + +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) +{ + LinkCapacityForAdequacyPatchFirstStep returnNTC; + + switch (OriginNodeAdequacyPatchType) + { + case adqmPhysicalAreaInsideAdqPatch: + returnNTC = SetNTCForAdequacyFirstStepOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, + SetToZero12LinksForAdequacyPatch); + break; + case adqmPhysicalAreaOutsideAdqPatch: + returnNTC + = SetNTCForAdequacyFirstStepOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, + SetToZero12LinksForAdequacyPatch, + SetToZero11LinksForAdequacyPatch); + break; + default: + returnNTC = leaveLocalValues; + break; + } + return returnNTC; +} + +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch) +{ + LinkCapacityForAdequacyPatchFirstStep returnNTC; + + switch (ExtremityNodeAdequacyPatchType) + { + case adqmPhysicalAreaInsideAdqPatch: + returnNTC = setToZero; + break; + case adqmPhysicalAreaOutsideAdqPatch: + returnNTC = (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero; + break; + default: + returnNTC = leaveLocalValues; + break; + } + return returnNTC; +} + +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) +{ + LinkCapacityForAdequacyPatchFirstStep returnNTC; + + switch (ExtremityNodeAdequacyPatchType) + { + case adqmPhysicalAreaInsideAdqPatch: + returnNTC = (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero; + break; + case adqmPhysicalAreaOutsideAdqPatch: + returnNTC = (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues; + break; + default: + returnNTC = leaveLocalValues; + break; + } + return returnNTC; +} + +void setBoundsAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo) +{ + LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; + + SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( + ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); + + if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setToZero) + { + Xmax = 0.; + Xmin = 0.; + } + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setOrigineExtremityToZero) + { + Xmax = 0.; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + } + else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setExtremityOrigineToZero) + { + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = 0.; + } + else + { + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + } +} + +void setBoundsNoAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco) +{ + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); +} diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h new file mode 100644 index 0000000000..6df2ab802a --- /dev/null +++ b/src/solver/optimisation/adequacy_patch.h @@ -0,0 +1,107 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_ADEQUACY_FUNCTIONS_H__ +#define __SOLVER_ADEQUACY_FUNCTIONS_H__ + +using namespace Antares::Data; + +/*! + * Determines restriction type for transmission links for first step of adequacy patch. + * + * @param OriginNodeAdequacyPatchType uint: The adq type of the node at the start of the link. + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * (type 1). + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); + +/*! + * Determines restriction type for transmission links for first step of adequacy patch, when start + * node is inside adq path (type 2). + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch); + +/*! + * Determines restriction type for transmission links for first step of adequacy patch, when start + * node is outside adq path (type 1). + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * (type 1). + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); + +/*! + * Sets link bounds for first step of adequacy patch. + */ +void setBoundsAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo); +/*! + * Sets link bounds when adequacy patch is not used or when first step of adequacy patch is false. + */ +void setBoundsNoAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco); + +#endif /* __SOLVER_ADEQUACY_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 aa0eb810b4..608b4efef6 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -34,6 +34,7 @@ #include "../simulation/sim_extern_variables_globales.h" #include "opt_fonctions.h" +#include "adequacy_patch.h" #include #include #include @@ -140,7 +141,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; - + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PALIERS_THERMIQUES* PaliersThermiquesDuPays; @@ -177,9 +178,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) + setBoundsAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); + else + setBoundsNoAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco); if (Math::Infinite(Xmax[Var]) == 1) { @@ -401,9 +403,18 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob else Xmax[Var] = 0.; + // adq patch: update ENS <= DENS in 2nd run + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false + && ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Pays] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + Xmax[Var] + = min(Xmax[Var], + ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); + ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo] = 0.0; + AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo]); AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 12d12a2e79..b37f3dd7a9 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -112,6 +112,34 @@ bool Economy::simulationBegin() return true; } +void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, + Variable::State& state, + uint numSpace, + int hourInTheYear) +{ + pProblemeHebdo->adqPatch->AdequacyFirstStep = true; + OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); + pProblemeHebdo->adqPatch->AdequacyFirstStep = false; + + for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) + { + if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + memcpy(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, + pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, + pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); + else + memset(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, + 0, + pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); + } + + // TODO check if we need to cut SIM_RenseignementProblemeHebdo and just pick out the + // part that we need + ::SIM_RenseignementProblemeHebdo(*pProblemeHebdo, state, numSpace, hourInTheYear); + OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); +} + bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, @@ -146,7 +174,16 @@ bool Economy::year(Progression::Task& progression, try { - OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + if (pProblemesHebdo[numSpace]->adqPatch) + { + OPT_OptimisationHebdomadaireAdqPatch( + pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); + } + else + { + OPT_OptimisationHebdomadaire(pProblemesHebdo[numSpace], numSpace); + } + DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index 275036eabe..d08b5f778f 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -59,7 +59,6 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps problem.BruitSurCoutHydraulique[p] = (double*)MemAlloc(8784 * sizeof(double)); problem.NomsDesPays = (const char**)MemAlloc(nbPays * sizeof(char*)); - problem.PaysExtremiteDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); problem.PaysOrigineDeLInterconnexion = (int*)MemAlloc(linkCount * sizeof(int)); problem.CoutDeTransport = (COUTS_DE_TRANSPORT**)MemAlloc(linkCount * sizeof(void*)); @@ -460,6 +459,8 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); + problem.ResultatsHoraires[k]->ValeursHorairesDENS + = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown @@ -588,7 +589,6 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) uint nbPays = study.areas.size(); MemFree(problem.NomsDesPays); - MemFree(problem.PaysExtremiteDeLInterconnexion); MemFree(problem.PaysOrigineDeLInterconnexion); MemFree(problem.IndexDebutIntercoOrigine); @@ -845,6 +845,7 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.PaliersThermiquesDuPays[k]->PuissanceDisponibleEtCout); MemFree(problem.PaliersThermiquesDuPays[k]); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 7efd4c2798..c8c8d87411 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -63,6 +63,21 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.hydroHotStart = (parameters.initialReservoirLevels.iniLevels == Antares::Data::irlHotStart); + if (parameters.include.adequacyPatch) + { + problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); + // AdequacyFirstStep will be initialized during the economy solve + // AdqBehaviorMap will be initialized during the economy solve + problem.adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq + = parameters.setToZero12LinksForAdequacyPatch; + problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq + = parameters.setToZero11LinksForAdequacyPatch; + } + + if (parameters.include.adequacyPatch){ + problem.adequacyPatchRuntimeData.initialize(study); + } + problem.WaterValueAccurate = (study.parameters.hydroPricing.hpMode == Antares::Data::HydroPricingMode::hpMILP) ? OUI_ANTARES diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 87cfa5b4b6..e915e28171 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -31,12 +31,16 @@ #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" #define GROSSES_VARIABLES NON_ANTARES #define COEFF_GROSSES_VARIABLES 100 +#include #include +using namespace Antares::Data::AdequacyPatch; + typedef struct { int* NumeroDeVariableDeLInterconnexion; @@ -317,6 +321,28 @@ typedef struct constraint on final level*/ } ENERGIES_ET_PUISSANCES_HYDRAULIQUES; +class AdequacyPatchRuntimeData +{ +public: + std::vector areaMode; + std::vector originAreaType; + std::vector extremityAreaType; + void initialize(Antares::Data::Study& study) + { + for (uint i = 0; i != study.areas.size(); ++i) + { + auto& area = *(study.areas[i]); + areaMode.push_back(area.adequacyPatchMode); + } + for (uint i = 0; i < study.runtime->interconnectionsCount; ++i) + { + auto& link = *(study.runtime->areaLink[i]); + originAreaType.push_back(link.from->adequacyPatchMode); + extremityAreaType.push_back(link.with->adequacyPatchMode); + } + } +}; + class computeTimeStepLevel { private: @@ -423,6 +449,7 @@ typedef struct typedef struct { double* ValeursHorairesDeDefaillancePositive; + double* ValeursHorairesDENS; // adq patch domestic unsupplied energy double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; @@ -469,6 +496,13 @@ typedef struct double* CoutsMarginauxHorairesDeLaReserveParZone; } COUTS_MARGINAUX_ZONES_DE_RESERVE; +struct AdequacyPatchParameters +{ + bool AdequacyFirstStep; + bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; +}; + struct PROBLEME_HEBDO { /* Business problem */ @@ -572,6 +606,10 @@ struct PROBLEME_HEBDO double* previousYearFinalLevels; ALL_MUST_RUN_GENERATION** AllMustRunGeneration; + /* Adequacy Patch */ + std::unique_ptr adqPatch = nullptr; + AdequacyPatchRuntimeData adequacyPatchRuntimeData; + optimizationStatistics optimizationStatistics_object; /* Hydro management */ double* CoefficientEcretementPMaxHydraulique; @@ -587,7 +625,6 @@ struct PROBLEME_HEBDO double* coutOptimalSolution2; COUTS_MARGINAUX_ZONES_DE_RESERVE** CoutsMarginauxDesContraintesDeReserveParZone; - /* Unused for now, will be used in future revisions */ #if 0 char SecondeOptimisationRelaxee; diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 436a6fb4bf..e3fc2fc401 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -59,6 +59,7 @@ #include "waterValue.h" #include "hydroCost.h" #include "unsupliedEnergy.h" +#include "domesticUnsuppliedEnergy.h" #include "spilledEnergy.h" #include "lold.h" @@ -144,22 +145,23 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -214,30 +216,32 @@ typedef // Prices Common::SpatialAggregate< UnsupliedEnergy, Common::SpatialAggregate< - SpilledEnergy, - // LOLD + DomesticUnsuppliedEnergy, Common::SpatialAggregate< - LOLD, + SpilledEnergy, + // LOLD Common::SpatialAggregate< - LOLP, - + LOLD, Common::SpatialAggregate< - AvailableDispatchGen, + LOLP, + Common::SpatialAggregate< - DispatchableGenMargin, + AvailableDispatchGen, Common::SpatialAggregate< - Marge, - - // Detail Prices + DispatchableGenMargin, Common::SpatialAggregate< - NonProportionalCost, // MBO 13/05/2014 - - // refs: #21 + Marge, - // Number Of Dispatched Units + // Detail Prices Common::SpatialAggregate< - NbOfDispatchedUnits // MBO 25/02/2016 - - // refs: #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>> + NonProportionalCost, // MBO 13/05/2014 - + // refs: #21 + + // Number Of Dispatched Units + Common::SpatialAggregate< + NbOfDispatchedUnits // MBO 25/02/2016 + // - refs: #55 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< diff --git a/src/solver/variable/economy/domesticUnsuppliedEnergy.h b/src/solver/variable/economy/domesticUnsuppliedEnergy.h new file mode 100644 index 0000000000..c25e4eb217 --- /dev/null +++ b/src/solver/variable/economy/domesticUnsuppliedEnergy.h @@ -0,0 +1,288 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 const char* Caption() + { + return "DENS"; + } + //! Unit + static const char* Unit() + { + return "MWh"; + } + //! The short description of the variable + static const char* 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); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + // Next variable + 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(); + 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/ui/simulator/application/study.cpp b/src/ui/simulator/application/study.cpp index 0f014ecc79..9178f3f679 100644 --- a/src/ui/simulator/application/study.cpp +++ b/src/ui/simulator/application/study.cpp @@ -90,6 +90,7 @@ Event OnStudyLinkDelete; Event OnStudySimulationSettingsChanged; Event OnStudyNodalOptimizationChanged; +Event OnStudyAreaUseAdequacyPatchChanged; Event OnStudyThermalClusterCommonSettingsChanged; Event OnStudyThermalClusterRenamed; diff --git a/src/ui/simulator/application/study.h b/src/ui/simulator/application/study.h index 79f0d6f278..a29998c511 100644 --- a/src/ui/simulator/application/study.h +++ b/src/ui/simulator/application/study.h @@ -266,6 +266,11 @@ extern Yuni::Event OnStudyConstraintModified; */ extern Yuni::Event OnStudyNodalOptimizationChanged; +/*! +** \brief Event: The area use adequacy patch settings have been changed +*/ +extern Yuni::Event OnStudyAreaUseAdequacyPatchChanged; + /*! ** \brief Event: The simulation settings have been changed */ diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index d00f46bb66..0fc3bdd5eb 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -322,6 +322,9 @@ static const wxChar* studyMode[] = {wxT("Economy"), #endif nullptr}; +static const wxChar* adequacyPatchMode[] + = {wxT("virtual area"), wxT("physical area outside patch"), wxT("physical area inside patch"), nullptr}; + struct Unique { template @@ -906,6 +909,28 @@ struct PAreaUnsuppliedEnergyCost } }; +struct PAdequacyPatchMode +{ + typedef Data::AdequacyPatch::AdequacyPatchMode Type; + static Type Value(const Data::Area* area) + { + return area->adequacyPatchMode; + } + static wxString ConvertToString(const Type v) + { + switch (v) + { + case Data::AdequacyPatch::adqmVirtualArea: + return wxT("virtual area"); + case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + return wxT("physical area outside patch"); + case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + return wxT("physical area inside patch"); + } + return wxEmptyString; + } +}; + template struct PAreaResortStatus { diff --git a/src/ui/simulator/windows/inspector/frame.cpp b/src/ui/simulator/windows/inspector/frame.cpp index 04fa0bbcb6..1fbfac5b66 100644 --- a/src/ui/simulator/windows/inspector/frame.cpp +++ b/src/ui/simulator/windows/inspector/frame.cpp @@ -397,6 +397,11 @@ Frame::Frame(wxWindow* parent, bool allowAnyObject) : pPGAreaResort, new wxBoolProperty(wxT("other dispatch. power"), wxT("area.other_dispatch_power"), false)); + pPGAreaAdequacyPatchTitle + = Category(pg, wxT("Adequacy Patch"), wxT("area.adequacy_patch_title")); + pPGAreaAdequacyPatchMode = page->Append(new wxEnumProperty( + wxT("adequacy patch mode"), wxT("area.adequacy_patch_mode"), adequacyPatchMode)); + pPGAreaLocalization = Category(pg, wxT("Localization"), wxT("area.localization")); P_INT("x", "area.x"); P_INT("y", "area.y"); @@ -785,6 +790,8 @@ void Frame::apply(const InspectorData::Ptr& data) pPGAreaName->SetValueFromString(wxStringFromUTF8((*(data->areas.begin()))->name)); // Area color Accumulator::Apply(pPGAreaColor, data->areas); + // Adequacy patch + Accumulator::Apply(pPGAreaAdequacyPatchMode, data->areas); // Area position if (!multiple) { @@ -835,6 +842,7 @@ void Frame::apply(const InspectorData::Ptr& data) } pPGAreaOptimization->Hide(hide); pPGAreaResort->Hide(hide); + pPGAreaAdequacyPatchTitle->Hide(hide); pPGAreaLocalization->Hide(hide || multiple); pPGAreaDeps->Hide(hide); diff --git a/src/ui/simulator/windows/inspector/frame.h b/src/ui/simulator/windows/inspector/frame.h index 807dd7c73d..6f2e1b6275 100644 --- a/src/ui/simulator/windows/inspector/frame.h +++ b/src/ui/simulator/windows/inspector/frame.h @@ -184,6 +184,8 @@ class Frame final : public Antares::Component::Panel, public Yuni::IEventObserve wxPGProperty* pPGUnsupplied; wxPGProperty* pPGSpilled; wxPGProperty* pPGAreaName; + wxPGProperty* pPGAreaAdequacyPatchTitle; + wxPGProperty* pPGAreaAdequacyPatchMode; wxPGProperty* pPGAreaColor; wxPGProperty* pPGAreaLinks; wxPGProperty* pPGAreaPlants; diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 15e65a30c8..601770d195 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -172,6 +172,29 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, OnStudyNodalOptimizationChanged(); return true; } + if (name == "area.adequacy_patch_mode") + { + for (; i != end; ++i) + { + auto* area = *i; + if (area) + { + String s; + wxStringToString(value.GetString(), s); + s.toLower(); + s.trim(); + + if (s == "virtual area" || s == "0") + area->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + else if (s == "physical area outside patch" || s == "1") + area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + else if (s == "physical area inside patch" || s == "2") + area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + } + } + OnStudyAreaUseAdequacyPatchChanged(); + return true; + } if (name == "area.links_count") return false; if (name == "area.cluster_count") diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index a3f8b102b9..41aef96e64 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -46,6 +46,21 @@ namespace Window { namespace Options { +static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) +{ + if (margintop) + { + sizer->AddSpacer(25); + sizer->AddSpacer(25); + } + + auto* label = Component::CreateLabel(parent, text, true); + + sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + sizer->AddSpacer(5); + sizer->AddSpacer(5); + sizer->AddSpacer(5); +} static void ResetButton(Component::Button* button, bool value) { assert(button != NULL); @@ -61,6 +76,21 @@ static void ResetButton(Component::Button* button, bool value) } } +static void ResetButtonAdequacyPatch(Component::Button* button, bool value) +{ + assert(button != NULL); + if (value) + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to null")); + } + else + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + } +} + static void ResetButtonSpecify(Component::Button* button, bool value) { assert(button != NULL); @@ -307,7 +337,6 @@ Optimization::Optimization(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnExportMPS = button; } - // Unfeasible problem behavior { label = Component::CreateLabel(this, wxT("Unfeasible problem behavior")); @@ -344,6 +373,52 @@ Optimization::Optimization(wxWindow* parent) : s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->AddSpacer(2); } + SubTitle(this, s, wxT("Adequacy Patch")); + // Adequacy patch + { + label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuSpecify, + PopupInfo(study.parameters.include.adequacyPatch, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatch = button; + } + // Transmission capacities (NTC) from physical areas outside adequacy patch (area type 1) to + // physical areas inside adequacy patch (area type 2). Used in the first step of adequacy patch + // local matching rule. + { + label = Component::CreateLabel(this, wxT("NTC from physical areas outside to physical areas inside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchNTC12 = button; + } + // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). + // Used in the first step of adequacy patch local matching rule. + { + label = Component::CreateLabel(this, wxT("NTC between physical areas outside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchNTC11 = button; + } { s->AddSpacer(2); @@ -427,6 +502,9 @@ void Optimization::onResetToDefault(void*) study.parameters.include.reserve.primary = true; study.parameters.include.reserve.spinning = true; study.parameters.include.exportMPS = false; + study.parameters.include.adequacyPatch = false; + study.parameters.setToZero12LinksForAdequacyPatch = true; + study.parameters.setToZero11LinksForAdequacyPatch = true; study.parameters.simplexOptimizationRange = Data::sorWeek; study.parameters.include.unfeasibleProblemBehavior @@ -474,6 +552,16 @@ void Optimization::refresh() ResetButton(pBtnSpinningReserve, study.parameters.include.reserve.spinning); // Export mps ResetButtonSpecify(pBtnExportMPS, study.parameters.include.exportMPS); + // Adequacy patch + ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); + // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside + // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, + study.parameters.setToZero12LinksForAdequacyPatch); + // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of + // adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, + study.parameters.setToZero11LinksForAdequacyPatch); // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( @@ -518,6 +606,36 @@ void Optimization::onPopupMenu(Component::Button&, wxMenu& menu, void*, const Po this); } +void Optimization::onPopupMenuAdequacyPatch(Component::Button&, + wxMenu& menu, + void*, + const PopupInfo& info) +{ + pTargetRef = &info.rval; + wxMenuItem* it; + + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("set to null"), + "images/16x16/light_orange.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(Optimization::onSelectModeInclude), + nullptr, + this); + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("local values (") << info.text << wxT(")"), + "images/16x16/light_green.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(Optimization::onSelectModeIgnore), + nullptr, + this); +} + void Optimization::onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index 2ec80bc48b..ae27c47c60 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -98,6 +98,7 @@ class Optimization final : public wxDialog void onPopupMenuTransmissionCapacities(Component::Button&, wxMenu& menu, void*); void onPopupMenuLinkType(Component::Button&, wxMenu& menu, void*); void onPopupMenuUnfeasibleBehavior(Component::Button&, wxMenu& menu, void*); + void onPopupMenuAdequacyPatch(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); void onInternalMotion(wxMouseEvent&); @@ -115,6 +116,9 @@ class Optimization final : public wxDialog Component::Button* pBtnSimplexOptimizationRange; Component::Button* pBtnExportMPS; + Component::Button* pBtnAdequacyPatch; + Component::Button* pBtnAdequacyPatchNTC12; + Component::Button* pBtnAdequacyPatchNTC11; Component::Button* pBtnUnfeasibleProblemBehavior; bool* pTargetRef; From c8bb44803565f8ec79a0113dadf27ad5897fe298 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 21 Apr 2022 00:40:37 +0200 Subject: [PATCH 075/490] obj. function + bounds test --- ...opt_gestion_des_bornes_cas_quadratique.cpp | 62 ++++++++++++++++--- .../opt_gestion_des_couts_cas_quadratique.cpp | 28 ++++++++- 2 files changed, 80 insertions(+), 10 deletions(-) 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 09fcbfd852..35c699ce2c 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -95,15 +95,61 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P } } -void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - //CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic - //CSR todo: let us first to create an optim problem like this: - // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area - // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 - // constraint: No constraint - //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + // CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic + // CSR todo: let us first to create an optim problem like this: + // variables: ENS of each area + // objective function: Sum (2 * (ENS)^2) of all area + // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // constraint: No constraint + // CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new + // one created inside HOURLY_CSR_PROBLEM? + + int Var; + double* AdresseDuResultat; + int hour; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + + ProblemeAResoudre->Xmin[Var] = 0; + ProblemeAResoudre->Xmax[Var] = 3000; + + if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) + { + if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + else + { + if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } + + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; + AdresseDuResultat + = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); + + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + } return; } \ No newline at end of file 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 6979abf2f4..87f3fc0824 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -58,8 +58,32 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH } } -void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - //CSR todo initialize the cost for variables in objective function of hourly CSR quadratic problem. + // CSR todo initialize the cost for variables in objective function of hourly CSR quadratic + // problem. + + int Var; + int hour; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + memset((char*)ProblemeAResoudre->CoutLineaire, + 0, + ProblemeAResoudre->NombreDeVariables * sizeof(double)); + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + ProblemeAResoudre->CoutQuadratique[Var] + = 2.0; + } + return; } \ No newline at end of file From bb823dc1542b81df92e080ccc6d3efc57fdefca5 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 21 Apr 2022 09:15:26 +0800 Subject: [PATCH 076/490] csr todo: hour or 0 --- ...construction_matrice_des_contraintes_cas_quadratique.cpp | 4 +++- .../opt_construction_variables_optimisees_quadratique.cpp | 6 +++--- 2 files changed, 6 insertions(+), 4 deletions(-) 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 index 671d1c53e5..3e64c8624e 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -108,5 +108,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; ProblemeAResoudre->NombreDeContraintes = 0; ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; } \ No newline at end of file diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index ee2b8c1217..b912b8cbe9 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -67,17 +67,17 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE // objective function: Sum (2 * (ENS)^2) of all area // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 // constraint: No constraint + //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; - + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; assert(ProblemeAResoudre != NULL); - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { From 240d2b880ee004cec0ec884af82c25b9fca5ce5b Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 21 Apr 2022 09:27:25 +0800 Subject: [PATCH 077/490] CSR todo hour or 0 --- ...nstruction_matrice_des_contraintes_cas_quadratique.cpp | 4 +++- .../opt_construction_variables_optimisees_quadratique.cpp | 8 ++++---- .../opt_gestion_des_bornes_cas_quadratique.cpp | 1 + .../opt_gestion_des_couts_cas_quadratique.cpp | 1 + src/solver/simulation/economy.cpp | 2 +- 5 files changed, 10 insertions(+), 6 deletions(-) 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 index 671d1c53e5..3e64c8624e 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -108,5 +108,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; ProblemeAResoudre->NombreDeContraintes = 0; ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; } \ No newline at end of file diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index ee2b8c1217..6144293f5f 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -67,17 +67,17 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE // objective function: Sum (2 * (ENS)^2) of all area // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 // constraint: No constraint + //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; - + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; assert(ProblemeAResoudre != NULL); - - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { 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 35c699ce2c..fd2478c0be 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -121,6 +121,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo; this should be 0 not hour ??? for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { 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 87f3fc0824..eade87ae18 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -76,6 +76,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, 0, ProblemeAResoudre->NombreDeVariables * sizeof(double)); CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: ??? this should be 0 not hour for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index ef1af55946..fcbd20475b 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -245,7 +245,7 @@ bool Economy::year(Progression::Task& progression, pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems from previous week in case there is any for(int hourInWeek : hoursInWeekTriggerCsrSet) { - //CSR todo if we reuse pProblemesHebdo, there will be no need to create HOURLY_CSR_PROBLEM + //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); //CSR todo From d3c9cb888c845dbc2cfe739bbcb3c7428651ac98 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 21 Apr 2022 09:46:18 +0800 Subject: [PATCH 078/490] 100 < ENS < 3000 --- ...t_construction_matrice_des_contraintes_cas_quadratique.cpp | 2 +- .../opt_construction_variables_optimisees_quadratique.cpp | 2 +- .../optimisation/opt_gestion_des_bornes_cas_quadratique.cpp | 4 ++-- 3 files changed, 4 insertions(+), 4 deletions(-) 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 index 3e64c8624e..5f04a7e6a8 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -99,7 +99,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB //CSR todo: let us first to create an optim problem like this: // variables: ENS of each area // objective function: Sum (2 * (ENS)^2) of all area - // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 // constraint: No constraint //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 82ea0786e3..606f4f8c29 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -65,7 +65,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE //CSR todo: let us first to create an optim problem like this: // variables: ENS of each area // objective function: Sum (2 * (ENS)^2) of all area - // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 // constraint: No constraint //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? 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 fd2478c0be..f0542bcfe9 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -103,7 +103,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // CSR todo: let us first to create an optim problem like this: // variables: ENS of each area // objective function: Sum (2 * (ENS)^2) of all area - // upper bound and lower bound: for each ENS: 0 <= ENS <= 3000 + // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 // constraint: No constraint // CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new // one created inside HOURLY_CSR_PROBLEM? @@ -127,7 +127,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - ProblemeAResoudre->Xmin[Var] = 0; + ProblemeAResoudre->Xmin[Var] = 100; ProblemeAResoudre->Xmax[Var] = 3000; if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) From 81b46b6fb795a35671e30fb9aff4b89940d8fbb0 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 21 Apr 2022 15:13:45 +0800 Subject: [PATCH 079/490] add constraint 2 * ENS < 1000 --- ...atrice_des_contraintes_cas_quadratique.cpp | 40 ++++++++++++++++++- ..._gestion_second_membre_cas_quadratique.cpp | 13 ++++++ .../sim_structure_probleme_economique.h | 2 +- 3 files changed, 52 insertions(+), 3 deletions(-) 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 index 5f04a7e6a8..6c49cbdfba 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -103,12 +103,48 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // constraint: No constraint //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + // CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + // PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + // ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + // ProblemeAResoudre->NombreDeContraintes = 0; + // ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; + // int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + // // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // constraint: 2 * ENS > 1000 + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Area; + int Var; + int NombreDeTermes; + double* Pi; + int* Colonne; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); + Colonne = (int*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(int)); + ProblemeAResoudre->NombreDeContraintes = 0; ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) + { + NombreDeTermes = 0; + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; + Pi[NombreDeTermes] = 2.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + + hourlyCsrProblem.numberOfConstraintCsr.push_back(ProblemeAResoudre->NombreDeContraintes); + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>'); + } + + MemFree(Pi); + MemFree(Colonne); } \ No newline at end of file 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 dbac506a5b..961a958d7e 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -51,5 +51,18 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { //CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. + //constraint for each area: 2 * ENS > 1000 + int Cnt; + int Area; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + Cnt = hourlyCsrProblem.numberOfConstraintCsr[Area]; + ProblemeAResoudre->SecondMembre[Cnt] = 1000; + } + return; } \ No newline at end of file diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index ee5d47cea4..09e29875af 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -735,7 +735,7 @@ class HOURLY_CSR_PROBLEM hourInWeekTriggeredCsr = hourInWeek; pWeeklyProblemBelongedTo = pProblemeHebdo; }; - + std::vector numberOfConstraintCsr; /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From a14e239d9e95de573f84017671ef0190474b6dfa Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 21 Apr 2022 17:25:27 +0200 Subject: [PATCH 080/490] todo commenets Milos --- src/solver/simulation/economy.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index fcbd20475b..279bbd86cd 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -174,7 +174,9 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP PROBLEME_HEBDO* pWeeklyProblem = hourlyCsrProblem.pWeeklyProblemBelongedTo; OPT_LiberationProblemesSimplexe(pWeeklyProblem); //CSR todo !!! do we do this here ???? or do we create another PROBLEME_ANTARES_A_RESOUDRE inside HOURLY_CSR_PROBLEM ???? - //CSR todo + //CSR todo + // todo!! by using OPT_LiberationProblemesSimplexe are we deleting weekly results in pWeeklyProblem->RESULTATS_HORAIRES, calculated after LMR optimization? + // apparently not cause i'm using RESULTATS_HORAIRES to calculate pto value in opt_gestion_des_couts_cas_quadratique and getting good values! OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); @@ -250,7 +252,7 @@ bool Economy::year(Progression::Task& progression, pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); //CSR todo } - UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); //CSR todo + UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); //CSR todo // result change in csr triggered hours are visible on output when i run tests? pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems of current week after CSR } } From 88ab4ff64b920ac5c8d0bef00e37aba2efbb1feb Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 21 Apr 2022 17:27:10 +0200 Subject: [PATCH 081/490] add pto coefficient to cost function --- .../opt_gestion_des_couts_cas_quadratique.cpp | 65 +++++++++++++++++-- 1 file changed, 60 insertions(+), 5 deletions(-) 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 eade87ae18..bdbce9ee54 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -33,6 +33,11 @@ #include "opt_fonctions.h" +#include +//#include + +using namespace Yuni; + void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtHebdo) { int Interco; @@ -64,10 +69,14 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, // CSR todo initialize the cost for variables in objective function of hourly CSR quadratic // problem. + int Interco; int Var; int hour; + double pto; + double coeff; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + COUTS_DE_TRANSPORT* TransportCost; hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; @@ -76,14 +85,60 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, 0, ProblemeAResoudre->NombreDeVariables * sizeof(double)); CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: ??? this should be 0 not hour + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR + // todo: ??? this should be 0 not hour for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - ProblemeAResoudre->CoutQuadratique[Var] - = 2.0; + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + // if (ProblemeHebdo->adqPatch->PriceTakingOrder ==Data::AdequacyPatch::adqPatchPTOIsLoad) + //todo !! I cannot find load values per area in ProblemeHebdo!!!!!!!!!!!!!!!!!! + // else + pto = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; + // todo !!what if pto = 0.0 e.g. dens for one area is zero!? + + coeff = 1 / Math::Power(pto, 2); + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + ProblemeAResoudre->CoutQuadratique[Var] = coeff; + } + } + + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] = 0.0; + } + + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + } + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + } + } + } } return; From 2a5ca131a541eafda40ffd797730d28e7c332d00 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 21 Apr 2022 17:27:44 +0200 Subject: [PATCH 082/490] add links, links constraint and link hurdle cost --- ...ction_variables_optimisees_quadratique.cpp | 88 +++++++++++++------ ...opt_gestion_des_bornes_cas_quadratique.cpp | 80 +++++++++++++++++ 2 files changed, 139 insertions(+), 29 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 606f4f8c29..5409e03ad8 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -58,34 +58,64 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H ProblemeAResoudre->NombreDeVariables = NombreDeVariables; } -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - //CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. - - //CSR todo: let us first to create an optim problem like this: - // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area - // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: No constraint - //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? - - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - int NumberOfVariables = 0; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); - - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? - - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; - return; + // CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. + + // CSR todo: let us first to create an optim problem like this: + // variables: ENS of each area + // objective function: Sum (2 * (ENS)^2) of all area + // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 + // constraint: No constraint + // CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new + // one created inside HOURLY_CSR_PROBLEM? + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + int NumberOfVariables = 0; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + COUTS_DE_TRANSPORT* TransportCost; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + assert(ProblemeAResoudre != NULL); + + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR + // todo: this should be 0 or hour??? + + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + } + + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + } + } + + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; + return; } \ No newline at end of file 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 f0542bcfe9..ac197e6e98 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -111,11 +111,18 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( int Var; double* AdresseDuResultat; int hour; + double* Xmin; + double* Xmax; + int* TypeDeVariable; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; + COUTS_DE_TRANSPORT* TransportCost; hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + Xmin = ProblemeAResoudre->Xmin; + Xmax = ProblemeAResoudre->Xmax; for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; @@ -152,5 +159,78 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; } + ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; // check if it is hour + + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + + if (Math::Infinite(Xmax[Var]) == 1) + { + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + else + { + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } + + AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] + ->VariableDualeParInterconnexion[Interco]); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; + + AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + + if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + else + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + + Xmax[Var] += 0.01; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + Xmin[Var] = 0.0; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + else + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + + Xmax[Var] += 0.01; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + Xmin[Var] = 0.0; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + } + } + return; } \ No newline at end of file From c5c5c99b83eced5db6f23b0f8246f5a57aa21fe1 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 07:46:28 +0800 Subject: [PATCH 083/490] Revert "add links, links constraint and link hurdle cost" This reverts commit 2a5ca131a541eafda40ffd797730d28e7c332d00. --- ...ction_variables_optimisees_quadratique.cpp | 88 ++++++------------- ...opt_gestion_des_bornes_cas_quadratique.cpp | 80 ----------------- 2 files changed, 29 insertions(+), 139 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 5409e03ad8..606f4f8c29 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -58,64 +58,34 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H ProblemeAResoudre->NombreDeVariables = NombreDeVariables; } -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - // CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. - - // CSR todo: let us first to create an optim problem like this: - // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area - // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: No constraint - // CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new - // one created inside HOURLY_CSR_PROBLEM? - - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - int NumberOfVariables = 0; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - COUTS_DE_TRANSPORT* TransportCost; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); - - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR - // todo: this should be 0 or hour??? - - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - } - - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - } - } - - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; - return; + //CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. + + //CSR todo: let us first to create an optim problem like this: + // variables: ENS of each area + // objective function: Sum (2 * (ENS)^2) of all area + // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 + // constraint: No constraint + //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + int NumberOfVariables = 0; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + assert(ProblemeAResoudre != NULL); + + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? + + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + } + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; + return; } \ No newline at end of file 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 ac197e6e98..f0542bcfe9 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -111,18 +111,11 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( int Var; double* AdresseDuResultat; int hour; - double* Xmin; - double* Xmax; - int* TypeDeVariable; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; - COUTS_DE_TRANSPORT* TransportCost; hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - Xmin = ProblemeAResoudre->Xmin; - Xmax = ProblemeAResoudre->Xmax; for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; @@ -159,78 +152,5 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; } - ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; // check if it is hour - - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - - if (Math::Infinite(Xmax[Var]) == 1) - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } - - AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] - ->VariableDualeParInterconnexion[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; - - AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; - - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - - if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] - - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - else - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - Xmax[Var] += 0.01; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - Xmin[Var] = 0.0; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; - - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] - + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - else - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - - Xmax[Var] += 0.01; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - Xmin[Var] = 0.0; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; - } - } - return; } \ No newline at end of file From 3185dbc59e41d5f8bbeaa546f29b93299f2bdb85 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 07:46:42 +0800 Subject: [PATCH 084/490] Revert "add pto coefficient to cost function" This reverts commit 88ab4ff64b920ac5c8d0bef00e37aba2efbb1feb. --- .../opt_gestion_des_couts_cas_quadratique.cpp | 65 ++----------------- 1 file changed, 5 insertions(+), 60 deletions(-) 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 bdbce9ee54..eade87ae18 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -33,11 +33,6 @@ #include "opt_fonctions.h" -#include -//#include - -using namespace Yuni; - void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtHebdo) { int Interco; @@ -69,14 +64,10 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, // CSR todo initialize the cost for variables in objective function of hourly CSR quadratic // problem. - int Interco; int Var; int hour; - double pto; - double coeff; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - COUTS_DE_TRANSPORT* TransportCost; hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; @@ -85,60 +76,14 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, 0, ProblemeAResoudre->NombreDeVariables * sizeof(double)); CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR - // todo: ??? this should be 0 not hour + // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: ??? this should be 0 not hour for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - // if (ProblemeHebdo->adqPatch->PriceTakingOrder ==Data::AdequacyPatch::adqPatchPTOIsLoad) - //todo !! I cannot find load values per area in ProblemeHebdo!!!!!!!!!!!!!!!!!! - // else - pto = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; - // todo !!what if pto = 0.0 e.g. dens for one area is zero!? - - coeff = 1 / Math::Power(pto, 2); - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - ProblemeAResoudre->CoutQuadratique[Var] = coeff; - } - } - - for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] = 0.0; - } - - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - } - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - } - } - } + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + ProblemeAResoudre->CoutQuadratique[Var] + = 2.0; } return; From 83ffe7053254f676693ae45df442884799bb931d Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 07:59:56 +0800 Subject: [PATCH 085/490] clean comments --- ...ruction_matrice_des_contraintes_cas_quadratique.cpp | 1 - ...t_construction_variables_optimisees_quadratique.cpp | 1 - .../opt_gestion_des_bornes_cas_quadratique.cpp | 1 - .../opt_gestion_des_couts_cas_quadratique.cpp | 1 - src/solver/simulation/economy.cpp | 10 +++------- 5 files changed, 3 insertions(+), 11 deletions(-) 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 index 6c49cbdfba..95640a0219 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -109,7 +109,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // ProblemeAResoudre->NombreDeContraintes = 0; // ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; // int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - // // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // constraint: 2 * ENS > 1000 diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 606f4f8c29..6094cf702d 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -78,7 +78,6 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE assert(ProblemeAResoudre != NULL); CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: this should be 0 or hour??? for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { 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 f0542bcfe9..0d7e9ea25b 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -121,7 +121,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo; this should be 0 not hour ??? for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { 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 eade87ae18..87f3fc0824 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -76,7 +76,6 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, 0, ProblemeAResoudre->NombreDeVariables * sizeof(double)); CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[0]; //CSR todo: ??? this should be 0 not hour for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 279bbd86cd..566ada78ca 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -183,8 +183,6 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblem->ProblemeAResoudre, hourlyCsrProblem); - - //example to build an optim problem can be found in OPT_PilotageOptimisationQuadratique return; } @@ -239,21 +237,19 @@ bool Economy::year(Progression::Task& progression, OPT_OptimisationHebdomadaireAdqPatch( pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); - //CSR todo: shall we start the CSR here, or shall we start the CSR after updatingWeeklyFinalHydroLevel? std::set hoursInWeekTriggerCsrSet; InitiateCurtailmentSharingRuleIndexSet(pProblemesHebdo[numSpace], hoursInWeekTriggerCsrSet); if( hoursInWeekTriggerCsrSet.size() > 0) { - pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems from previous week in case there is any + pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); for(int hourInWeek : hoursInWeekTriggerCsrSet) { - //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); - OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); //CSR todo + OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); } UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); //CSR todo // result change in csr triggered hours are visible on output when i run tests? - pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); // we clear houlyCsrProblems of current week after CSR + pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); } } else From 40566a988ada01572a7e24e2ccbbb0ca38b5d136 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 08:27:17 +0800 Subject: [PATCH 086/490] optim variables only for area inside adq patch --- ...atrice_des_contraintes_cas_quadratique.cpp | 24 +++++----- ...ction_variables_optimisees_quadratique.cpp | 9 ++-- ...opt_gestion_des_bornes_cas_quadratique.cpp | 48 +++++++++---------- .../opt_gestion_des_couts_cas_quadratique.cpp | 10 ++-- ..._gestion_second_membre_cas_quadratique.cpp | 11 +++-- 5 files changed, 54 insertions(+), 48 deletions(-) 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 index 95640a0219..23b3f4cb2f 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -98,10 +98,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB //CSR todo build matrix of constraint of hourly CSR quadratic problem //CSR todo: let us first to create an optim problem like this: // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area + // objective function: Sum (2 * (ENS)^2) of areas inside adq patch // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: No constraint - //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + // constraint: 2 * ENS > 1000 // CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; // PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; @@ -111,7 +110,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // constraint: 2 * ENS > 1000 int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Area; int Var; @@ -132,16 +130,18 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { - NombreDeTermes = 0; - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; - Pi[NombreDeTermes] = 2.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + NombreDeTermes = 0; + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; + Pi[NombreDeTermes] = 2.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; - hourlyCsrProblem.numberOfConstraintCsr.push_back(ProblemeAResoudre->NombreDeContraintes); + hourlyCsrProblem.numberOfConstraintCsr.push_back(ProblemeAResoudre->NombreDeContraintes); - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>'); + OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>'); + } } MemFree(Pi); diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 6094cf702d..ed88a1b2a0 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -64,10 +64,9 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE //CSR todo: let us first to create an optim problem like this: // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area + // objective function: Sum (2 * (ENS)^2) of all area for for areas inside adq patch // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: No constraint - //CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new one created inside HOURLY_CSR_PROBLEM? + // constraint: 2 * ENS < 1000 PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; @@ -81,9 +80,13 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { + //!!! Only ENS for areas inside adq patch are considered as variables + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; NumberOfVariables++; + } } ProblemeAResoudre->NombreDeVariables = NumberOfVariables; 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 0d7e9ea25b..f11334f521 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -102,11 +102,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic // CSR todo: let us first to create an optim problem like this: // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area + // objective function: Sum (2 * (ENS)^2) of areas inside adq patch // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: No constraint - // CSR todo, we re-use ProblemeAResoudre from weekly ProblemeHebdo, shall we instead use a new - // one created inside HOURLY_CSR_PROBLEM? + // constraint: 2 * ENS > 1000 int Var; double* AdresseDuResultat; @@ -124,31 +122,33 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - ProblemeAResoudre->Xmin[Var] = 100; - ProblemeAResoudre->Xmax[Var] = 3000; + ProblemeAResoudre->Xmin[Var] = 100; + ProblemeAResoudre->Xmax[Var] = 3000; - if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) - { - if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else - { - if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) + { + if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } + { + if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; - AdresseDuResultat - = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; + AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + } } 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 87f3fc0824..5671faebd2 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -79,10 +79,12 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - ProblemeAResoudre->CoutQuadratique[Var] - = 2.0; + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + ProblemeAResoudre->CoutQuadratique[Var] = 2.0; + } } 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 961a958d7e..fb826299de 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -51,7 +51,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { //CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. - //constraint for each area: 2 * ENS > 1000 + //constraint for each area inside adq patch: 2 * ENS > 1000 int Cnt; int Area; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; @@ -60,9 +60,10 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { - Cnt = hourlyCsrProblem.numberOfConstraintCsr[Area]; - ProblemeAResoudre->SecondMembre[Cnt] = 1000; + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + Cnt = hourlyCsrProblem.numberOfConstraintCsr[Area]; + ProblemeAResoudre->SecondMembre[Cnt] = 1000; + } } - - return; } \ No newline at end of file From 29303e7eadd74f02d40f03818871c7709376c9e4 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 08:57:02 +0800 Subject: [PATCH 087/490] quadratic cost with PTO from DENS --- ...ction_variables_optimisees_quadratique.cpp | 2 +- .../opt_gestion_des_couts_cas_quadratique.cpp | 30 ++++++++++++++++--- 2 files changed, 27 insertions(+), 5 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index ed88a1b2a0..db1890f457 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -66,7 +66,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE // variables: ENS of each area // objective function: Sum (2 * (ENS)^2) of all area for for areas inside adq patch // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: 2 * ENS < 1000 + // constraint: 2 * ENS > 1000 PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; 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 5671faebd2..5542684c4b 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -61,11 +61,10 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - // CSR todo initialize the cost for variables in objective function of hourly CSR quadratic - // problem. - int Var; int hour; + double priceTakingOrders; //PTO + double quadraticCost; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; @@ -83,7 +82,30 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - ProblemeAResoudre->CoutQuadratique[Var] = 2.0; + { + // if (ProblemeHebdo->adqPatch->PriceTakingOrder ==Data::AdequacyPatch::adqPatchPTOIsLoad) + // { + // // todo !! I cannot find load values per area in ProblemeHebdo!!!!!!!!!!!!!!!!!! + // } + // else + // { + priceTakingOrders = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; + // } + + if (priceTakingOrders <= 0.0) + { + //CSR todo a warning that DENS is negative and it is considered for CSR, there was a check for positive threshold + quadraticCost = 0.0; + } + else + { + quadraticCost = 1 / (priceTakingOrders * priceTakingOrders); + } + // quadraticCost = 2.0; //todo to remove. for debug + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; + } } } From 65e0b2ad49bb0e7c1af49b6762afffa9751bdaa2 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 09:15:54 +0800 Subject: [PATCH 088/490] Milos's commit related to links. not tested. --- ...ction_variables_optimisees_quadratique.cpp | 25 ++++++ ...opt_gestion_des_bornes_cas_quadratique.cpp | 83 +++++++++++++++++++ .../opt_gestion_des_couts_cas_quadratique.cpp | 41 +++++++++ 3 files changed, 149 insertions(+) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index db1890f457..54ae063a7a 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -88,6 +88,31 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE NumberOfVariables++; } } + + COUTS_DE_TRANSPORT* TransportCost; + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + NumberOfVariables++; + } + } + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; return; } \ No newline at end of file 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 f11334f521..8eefe3d579 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -151,5 +151,88 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } } + + double* Xmin; + double* Xmax; + int* TypeDeVariable; + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; + COUTS_DE_TRANSPORT* TransportCost; + Xmin = ProblemeAResoudre->Xmin; + Xmax = ProblemeAResoudre->Xmax; + + ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; // check if it is hour + + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + + if (Math::Infinite(Xmax[Var]) == 1) + { + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + else + { + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } + + AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] + ->VariableDualeParInterconnexion[Interco]); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; + + AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + + if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + else + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + + Xmax[Var] += 0.01; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + Xmin[Var] = 0.0; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + else + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + + Xmax[Var] += 0.01; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + Xmin[Var] = 0.0; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + } + } + + return; } \ No newline at end of file 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 5542684c4b..c2126e12b7 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -109,5 +109,46 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } } + + + int Interco; + COUTS_DE_TRANSPORT* TransportCost; + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] = 0.0; + } + + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + } + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + } + } + } + } + + + return; } \ No newline at end of file From d06b4b5f7cb1fb70eceb8fe30e033263fa2f3e4e Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 22 Apr 2022 09:50:59 +0800 Subject: [PATCH 089/490] comments --- ...n_matrice_des_contraintes_cas_quadratique.cpp | 16 +--------------- ...truction_variables_optimisees_quadratique.cpp | 12 +++--------- .../opt_gestion_des_bornes_cas_quadratique.cpp | 13 +++++-------- .../opt_gestion_des_couts_cas_quadratique.cpp | 9 ++++++++- ...opt_gestion_second_membre_cas_quadratique.cpp | 2 +- 5 files changed, 18 insertions(+), 34 deletions(-) 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 index 23b3f4cb2f..91880f1315 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -95,21 +95,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - //CSR todo build matrix of constraint of hourly CSR quadratic problem - //CSR todo: let us first to create an optim problem like this: - // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of areas inside adq patch - // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: 2 * ENS > 1000 - - // CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - // PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - // ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - // ProblemeAResoudre->NombreDeContraintes = 0; - // ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - // int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - // CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Area; int Var; @@ -128,6 +113,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // constraint: 2 * ENS > 1000 for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 54ae063a7a..5e7bda0d3e 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -60,14 +60,6 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - //CSR todo :build list of variable to be optimized in hourly CSR quadratic problem. - - //CSR todo: let us first to create an optim problem like this: - // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of all area for for areas inside adq patch - // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: 2 * ENS > 1000 - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; @@ -78,9 +70,10 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // variables: ENS of each area insie adq patch for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - //!!! Only ENS for areas inside adq patch are considered as variables + // Only ENS for areas inside adq patch are considered as variables if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; @@ -89,6 +82,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE } } + //CSR todo comments COUTS_DE_TRANSPORT* TransportCost; for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { 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 8eefe3d579..17a0d85267 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -99,13 +99,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - // CSR todo initialize uppper bound and lower bound of variables in hourly CSR quadratic - // CSR todo: let us first to create an optim problem like this: - // variables: ENS of each area - // objective function: Sum (2 * (ENS)^2) of areas inside adq patch - // upper bound and lower bound: for each ENS: 100 <= ENS <= 3000 - // constraint: 2 * ENS > 1000 - int Var; double* AdresseDuResultat; int hour; @@ -120,6 +113,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // variables: ENS for each area inside adq patch + // one dummy constraint for testing : 100 <= ENS <= 3000 //todo remove for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) @@ -152,6 +148,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } + //CSR todo comments double* Xmin; double* Xmax; int* TypeDeVariable; @@ -159,7 +156,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( COUTS_DE_TRANSPORT* TransportCost; Xmin = ProblemeAResoudre->Xmin; Xmax = ProblemeAResoudre->Xmax; - + ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; // check if it is hour for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) 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 c2126e12b7..61d77ba999 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -71,6 +71,13 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + // variables: ENS for each area inside adq patch + // obj function term is: 1 / (PTO * PTO) * ENS * ENS + // => quadratic cost: 1 / (PTO * PTO) + // => linear cost: 0 + // PTO can take two different values according to option: + // 1. from DENS + // 2. from load memset((char*)ProblemeAResoudre->CoutLineaire, 0, ProblemeAResoudre->NombreDeVariables * sizeof(double)); @@ -110,7 +117,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } - + //CSR todo comments int Interco; COUTS_DE_TRANSPORT* TransportCost; for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) 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 fb826299de..c73f866bc6 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -51,13 +51,13 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { //CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. - //constraint for each area inside adq patch: 2 * ENS > 1000 int Cnt; int Area; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + //constraint for each area inside adq patch: 2 * ENS > 1000 for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) From c8e0203f766294c681f8c1e21d64d4db66c37fe7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 25 Apr 2022 10:34:59 +0200 Subject: [PATCH 090/490] Milos' comments for links --- ...onstruction_matrice_des_contraintes_cas_quadratique.cpp | 4 ++++ .../opt_construction_variables_optimisees_quadratique.cpp | 2 +- .../opt_gestion_des_bornes_cas_quadratique.cpp | 3 ++- .../optimisation/opt_gestion_des_couts_cas_quadratique.cpp | 7 ++++++- .../opt_gestion_second_membre_cas_quadratique.cpp | 3 +++ 5 files changed, 16 insertions(+), 3 deletions(-) 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 index 91880f1315..249e00a616 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -130,6 +130,10 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } } + // CSR todo. Add I Kirchhoff's law contstraint for all links. + // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows + // and/or power generated from generating units. + MemFree(Pi); MemFree(Colonne); } \ No newline at end of file diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 5e7bda0d3e..28aeedc5f7 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -82,7 +82,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE } } - //CSR todo comments + // variables: NTC (direct and indirect transmissin flow). For ALL links. COUTS_DE_TRANSPORT* TransportCost; for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { 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 17a0d85267..32dbb56bc7 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -148,7 +148,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } - //CSR todo comments + // variables: NTC (direct and indirect transmissin flow). + // Set hourly bounds for ALL links depending on the user input (max direct and indirect flow). double* Xmin; double* Xmax; int* TypeDeVariable; 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 61d77ba999..cd2427deed 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -117,7 +117,12 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } - //CSR todo comments + // variables: transmission cost for links between nodes of type 2 (area inside adequacy patch) + // obj function term is: ∑( hurdle_cost_direct x flow_direct )+ ∑( hurdle_cost_indirect x flow_indirect ) + // => quadratic cost: 0 + // => linear cost: hurdle_cost_direct / hurdle_cost_indirect + // these members of objective functions are considered only if IntercoGereeAvecDesCouts = OUI_ANTARES (use hurdle cost option is true). + // otherwise these members are zero. int Interco; COUTS_DE_TRANSPORT* TransportCost; for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) 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 c73f866bc6..e05b41d8de 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -66,4 +66,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob ProblemeAResoudre->SecondMembre[Cnt] = 1000; } } + + // CSR todo. Add RHS I Kirchhoff's law contstraint for all links. + // CSR todo. Add RHS, only hourly, user defined Binding constraints for all links. } \ No newline at end of file From fad84e2a25431f56a535444a9a3694c0ccc44f73 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 25 Apr 2022 10:40:47 +0200 Subject: [PATCH 091/490] double checking? no need. --- .../optimisation/opt_gestion_des_couts_cas_quadratique.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 cd2427deed..df0095f18c 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -109,8 +109,8 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, quadraticCost = 1 / (priceTakingOrders * priceTakingOrders); } // quadraticCost = 2.0; //todo to remove. for debug - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; // double checking? no need. + // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; } } From e6cd2bc6a58c0593a174eddcf23d7d0559beeae8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Apr 2022 20:54:21 +0200 Subject: [PATCH 092/490] update PTO (choose between load or dens) --- .../optimisation/opt_gestion_des_couts_cas_quadratique.cpp | 6 ++++-- 1 file changed, 4 insertions(+), 2 deletions(-) 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 df0095f18c..241196e097 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -90,9 +90,11 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - // if (ProblemeHebdo->adqPatch->PriceTakingOrder ==Data::AdequacyPatch::adqPatchPTOIsLoad) + // if (ProblemeHebdo->adqPatch->PriceTakingOrder == Data::AdequacyPatch::adqPatchPTOIsLoad) // { - // // todo !! I cannot find load values per area in ProblemeHebdo!!!!!!!!!!!!!!!!!! + priceTakingOrders + = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] + + ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; // } // else // { From 1ef5da3c8750b95efdde142fe907ef00f92027bd Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Apr 2022 21:03:31 +0200 Subject: [PATCH 093/490] set link variables, constraints and bounds (update) --- ...atrice_des_contraintes_cas_quadratique.cpp | 80 ++++++++++++++++++- ...ction_variables_optimisees_quadratique.cpp | 2 +- ...opt_gestion_des_bornes_cas_quadratique.cpp | 23 ++++-- .../opt_gestion_des_couts_cas_quadratique.cpp | 2 - ..._gestion_second_membre_cas_quadratique.cpp | 33 +++++++- .../sim_structure_probleme_economique.h | 2 + 6 files changed, 130 insertions(+), 12 deletions(-) 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 index 249e00a616..57e3cfc1c0 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -130,7 +130,85 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } } - // CSR todo. Add I Kirchhoff's law contstraint for all links. + // I Kirchhoff's law contstraint for all areas. + int Interco; + COUTS_DE_TRANSPORT* TransportCost; + + for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) + { + NombreDeTermes = 0; + + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + if (Var >= 0) + { + Pi[NombreDeTermes] = 1.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + } + Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; + } + Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + while (Interco >= 0) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + if (Var >= 0) + { + Pi[NombreDeTermes] = -1.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + } + Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + } + + hourlyCsrProblem.numberOfConstraintCsrAreaBalance.push_back( + ProblemeAResoudre->NombreDeContraintes); + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); + } + + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + NombreDeTermes = 0; + 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.push_back( + ProblemeAResoudre->NombreDeContraintes); + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); + } + } + // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 28aeedc5f7..983d4a30f2 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -82,7 +82,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE } } - // variables: NTC (direct and indirect transmissin flow). For ALL links. + // variables: transmissin flows (flow, direct_direct and flow_indirect). For ALL links. COUTS_DE_TRANSPORT* TransportCost; for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { 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 32dbb56bc7..8d574945d3 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -148,7 +148,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } - // variables: NTC (direct and indirect transmissin flow). + // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For ALL links. // Set hourly bounds for ALL links depending on the user input (max direct and indirect flow). double* Xmin; double* Xmax; @@ -158,7 +158,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Xmin = ProblemeAResoudre->Xmin; Xmax = ProblemeAResoudre->Xmax; - ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; // check if it is hour + ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) { @@ -184,8 +184,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] - ->VariableDualeParInterconnexion[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; + ->VariableDualeParInterconnexion[Interco]); // dual variable for links + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; // reduced cost AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; @@ -209,7 +209,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } Xmin[Var] = 0.0; ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; @@ -230,7 +230,18 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; } } - + // 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. + // 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 + // if (FLOW.LIN –LOOP FLOW) > 0 + // HURD. COST = (hourly direct hurdle cost) * (FLOW LIN.) + // else HURD.COST = (hourly indirect hurdle cost) * (-1) * (FLOW LIN.) return; } \ No newline at end of file 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 241196e097..bd977c3f34 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -162,7 +162,5 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } } - - return; } \ No newline at end of file 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 e05b41d8de..e876f2cb36 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -67,6 +67,35 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob } } - // CSR todo. Add RHS I Kirchhoff's law contstraint for all links. - // CSR todo. Add RHS, only hourly, user defined Binding constraints for all links. + // I Kirchhoff's law contstraint for all areas. + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + COUTS_DE_TRANSPORT* TransportCost; + double test; + for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) + { + Cnt = hourlyCsrProblem.numberOfConstraintCsrAreaBalance[Area]; + ProblemeAResoudre->SecondMembre[Cnt] + = ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // todo what to use: + + // ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // average hourly balance per area! OR + // -ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[Area]; // = Reduced consumption per area + } + + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco]; + if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] + ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + else + ProblemeAResoudre->SecondMembre[Cnt] = 0.; + } + } + + // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows + // and/or power generated from generating units. } \ No newline at end of file diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 09e29875af..33b641f5a3 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -736,6 +736,8 @@ class HOURLY_CSR_PROBLEM pWeeklyProblemBelongedTo = pProblemeHebdo; }; std::vector numberOfConstraintCsr; + std::vector numberOfConstraintCsrAreaBalance; + std::vector numberOfConstraintCsrFlowDissociation; /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From fecf1d8f7c41ef6df331c0e319beed4a819d9392 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Apr 2022 21:07:21 +0200 Subject: [PATCH 094/490] todo comments --- .../opt_gestion_des_bornes_cas_quadratique.cpp | 7 ++++--- 1 file changed, 4 insertions(+), 3 deletions(-) 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 8d574945d3..36a45e5f19 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -184,8 +184,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] - ->VariableDualeParInterconnexion[Interco]); // dual variable for links - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; // reduced cost + ->VariableDualeParInterconnexion[Interco]); // dual variable for links // todo: remove + ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; // reduced cost // todo: remove AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; @@ -209,7 +209,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } Xmin[Var] = 0.0; ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! // todo: remove Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; @@ -230,6 +230,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; } } + // todo: remove // 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 From 677605e7bd8f53a25f415d645d23d89494a6bca2 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 27 Apr 2022 12:30:26 +0800 Subject: [PATCH 095/490] only flow --- ...atrice_des_contraintes_cas_quadratique.cpp | 171 +++++++++--------- ...ction_variables_optimisees_quadratique.cpp | 48 +++-- ...opt_gestion_des_bornes_cas_quadratique.cpp | 136 ++++++++------ .../opt_gestion_des_couts_cas_quadratique.cpp | 48 ++--- ..._gestion_second_membre_cas_quadratique.cpp | 61 ++++--- src/solver/simulation/economy.cpp | 8 + 6 files changed, 270 insertions(+), 202 deletions(-) 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 index 57e3cfc1c0..874a264e5b 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -95,6 +95,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { + logs.debug() << "[CSR] constraint list:"; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Area; int Var; @@ -103,7 +104,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB int* Colonne; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - + std::string NomDeLaContrainte; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); @@ -113,7 +114,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // constraint: 2 * ENS > 1000 + // constraint: 2 * ENS > 10 for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) @@ -125,89 +126,97 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB NombreDeTermes++; hourlyCsrProblem.numberOfConstraintCsr.push_back(ProblemeAResoudre->NombreDeContraintes); + NomDeLaContrainte = "dummy 2*ENS > 10. area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; + logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>', NomDeLaContrainte); - OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>'); - } - } - - // I Kirchhoff's law contstraint for all areas. - int Interco; - COUTS_DE_TRANSPORT* TransportCost; - - for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) - { - NombreDeTermes = 0; - - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - if (Var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; - } - Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; - } - Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - while (Interco >= 0) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - if (Var >= 0) - { - Pi[NombreDeTermes] = -1.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; - } - Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; } - - hourlyCsrProblem.numberOfConstraintCsrAreaBalance.push_back( - ProblemeAResoudre->NombreDeContraintes); - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); } - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. - for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - NombreDeTermes = 0; - 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.push_back( - ProblemeAResoudre->NombreDeContraintes); - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); - } - } + // // I Kirchhoff's law contstraint for all areas. + // int Interco; + // COUTS_DE_TRANSPORT* TransportCost; + + // // for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) //??? why not all area, but area - 1? + // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + // { + // NombreDeTermes = 0; + + // Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + // while (Interco >= 0) + // { + // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + // if (Var >= 0) + // { + // Pi[NombreDeTermes] = 1.0; + // Colonne[NombreDeTermes] = Var; + // NombreDeTermes++; + // } + // Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; + // } + // Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + // while (Interco >= 0) + // { + // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + // if (Var >= 0) + // { + // Pi[NombreDeTermes] = -1.0; + // Colonne[NombreDeTermes] = Var; + // NombreDeTermes++; + // } + // Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + // } + + // hourlyCsrProblem.numberOfConstraintCsrAreaBalance.push_back( + // ProblemeAResoudre->NombreDeContraintes); + + // NomDeLaContrainte = "NTC=sum(flow), area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; + // logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + + // OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + // ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); + + + // } + + // // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + // for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + // { + // TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + // { + // NombreDeTermes = 0; + // 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.push_back( + // ProblemeAResoudre->NombreDeContraintes); + + // OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + // ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); + // } + // } // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 983d4a30f2..712c3a1e55 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -60,6 +60,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { + logs.debug() << "[CSR] variable list:"; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; @@ -70,7 +71,8 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // variables: ENS of each area insie adq patch + // variables: ENS of each area inside adq patch + logs.debug() << " ENS of each area inside adq patch: "; for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { // Only ENS for areas inside adq patch are considered as variables @@ -78,33 +80,47 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " ENS[" << area <<"]. "; + NumberOfVariables++; } } - // variables: transmissin flows (flow, direct_direct and flow_indirect). For ALL links. + // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 and 2. + logs.debug() << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; COUTS_DE_TRANSPORT* TransportCost; for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { + // only consider link between 2 and 2 + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " flow[" << Interco <<"]. "; NumberOfVariables++; - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - NumberOfVariables++; - } + // TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) //CSR todo ??? how can it be true? a test case ? + // { + // CorrespondanceVarNativesVarOptim + // ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + // = NumberOfVariables; + // ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + // logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; + // NumberOfVariables++; + + // CorrespondanceVarNativesVarOptim + // ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + // = NumberOfVariables; + // ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + // logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; + // NumberOfVariables++; + + // } + } + } ProblemeAResoudre->NombreDeVariables = NumberOfVariables; 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 36a45e5f19..e9838bef67 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -99,6 +99,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { + logs.debug() << "[CSR] bounds"; + int Var; double* AdresseDuResultat; int hour; @@ -115,15 +117,15 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // variables: ENS for each area inside adq patch - // one dummy constraint for testing : 100 <= ENS <= 3000 //todo remove + // one dummy constraint for testing : 0 <= ENS <= 10000 //todo remove for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - ProblemeAResoudre->Xmin[Var] = 100; - ProblemeAResoudre->Xmax[Var] = 3000; + ProblemeAResoudre->Xmin[Var] = 0; + ProblemeAResoudre->Xmax[Var] = 10000; if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) { @@ -144,6 +146,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; } } @@ -162,72 +166,86 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - if (Math::Infinite(Xmax[Var]) == 1) - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else + // only consider link between 2 and 2 + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] - ->VariableDualeParInterconnexion[Interco]); // dual variable for links // todo: remove - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; // reduced cost // todo: remove - - AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; - - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] - - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - else - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - Xmax[Var] += 0.01; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; } - Xmin[Var] = 0.0; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! // todo: remove - - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] - + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; else - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - - Xmax[Var] += 0.01; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; } - Xmin[Var] = 0.0; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + // AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] + // ->VariableDualeParInterconnexion[Interco]); // dual variable for links // todo: remove + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; // reduced cost // todo: remove + + AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + + + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + // { + // Var = CorrespondanceVarNativesVarOptim + // ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + + // Xmax[Var] += 0.01; + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + // if (Math::Infinite(Xmax[Var]) == 1) + // { + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + // } + // Xmin[Var] = 0.0; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! // todo: remove + + // logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + + // Var = CorrespondanceVarNativesVarOptim + // ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + + // Xmax[Var] += 0.01; + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + // if (Math::Infinite(Xmax[Var]) == 1) + // { + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + // } + // Xmin[Var] = 0.0; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + // logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + + // } } } // todo: remove 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 bd977c3f34..058573c444 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -61,6 +61,7 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { + logs.debug() << "[CSR] cost"; int Var; int hour; double priceTakingOrders; //PTO @@ -92,9 +93,9 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, { // if (ProblemeHebdo->adqPatch->PriceTakingOrder == Data::AdequacyPatch::adqPatchPTOIsLoad) // { - priceTakingOrders - = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] - + ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; + // priceTakingOrders + // = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] + // + ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; // } // else // { @@ -114,6 +115,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; // double checking? no need. // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; + logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; } } } @@ -122,7 +124,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, // variables: transmission cost for links between nodes of type 2 (area inside adequacy patch) // obj function term is: ∑( hurdle_cost_direct x flow_direct )+ ∑( hurdle_cost_indirect x flow_indirect ) // => quadratic cost: 0 - // => linear cost: hurdle_cost_direct / hurdle_cost_indirect + // => linear cost: hurdle_cost_direct or hurdle_cost_indirect // these members of objective functions are considered only if IntercoGereeAvecDesCouts = OUI_ANTARES (use hurdle cost option is true). // otherwise these members are zero. int Interco; @@ -140,25 +142,29 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { ProblemeAResoudre->CoutLineaire[Var] = 0.0; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; } - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - } - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - } - } + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + // { + // Var = CorrespondanceVarNativesVarOptim + // ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + // { + // ProblemeAResoudre->CoutLineaire[Var] + // = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + // logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + + // } + // Var = CorrespondanceVarNativesVarOptim + // ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + // { + // ProblemeAResoudre->CoutLineaire[Var] + // = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + // logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + // } + // } } } 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 e876f2cb36..3cb354dbd9 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -50,6 +50,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { + logs.debug() << "[CSR] RHS: "; //CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. int Cnt; int Area; @@ -57,44 +58,54 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - //constraint for each area inside adq patch: 2 * ENS > 1000 + //constraint for each area inside adq patch: 2 * ENS > 10 for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Cnt = hourlyCsrProblem.numberOfConstraintCsr[Area]; - ProblemeAResoudre->SecondMembre[Cnt] = 1000; + ProblemeAResoudre->SecondMembre[Cnt] = 10; + logs.debug() << Cnt << ": dummy 2*ENS > 10: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } } // I Kirchhoff's law contstraint for all areas. int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; COUTS_DE_TRANSPORT* TransportCost; - double test; - for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) - { - Cnt = hourlyCsrProblem.numberOfConstraintCsrAreaBalance[Area]; - ProblemeAResoudre->SecondMembre[Cnt] - = ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // todo what to use: + // double test; + // // for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) //??? why not all area, but area - 1? + // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + // { + // Cnt = hourlyCsrProblem.numberOfConstraintCsrAreaBalance[Area]; - // ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // average hourly balance per area! OR - // -ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[Area]; // = Reduced consumption per area - } + // //CSR Todo: should not use SoldeMoyenDuPays[Area] + // //should create a new function to calculate “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 chapter 2. - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco]; - if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] - ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - else - ProblemeAResoudre->SecondMembre[Cnt] = 0.; - } - } + // ProblemeAResoudre->SecondMembre[Cnt] + // = ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // todo what to use + // // ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // average hourly balance per area! OR + // // -ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[Area]; // = Reduced consumption per area + // logs.debug() << Cnt << ": NTC=sum(flow): RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + + // } + + // // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + // for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + // { + // TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + // { + // Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco]; + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] + // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // ProblemeAResoudre->SecondMembre[Cnt] = 0.; + // } + // } // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 566ada78ca..c68bb2283d 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -161,11 +161,16 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, // pProblemeHebdo->NombreDePasDeTemps); nbHoursInAWeek); //use nbHoursInAWeek seems more clear } + threshold = 500; //todo remove. for debug for (int i = 0; i < nbHoursInAWeek; ++i) { if ((int)sumENS[i] >= threshold) + { + logs.debug() << "hour: [" << i << "], sumENS = [" << (int)sumENS[i] << "], threshold = " << threshold; triggerCsrSet.insert(i); + } } + logs.debug() << "number of triggered hours: " << triggerCsrSet.size(); } void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -244,9 +249,12 @@ bool Economy::year(Progression::Task& progression, pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); for(int hourInWeek : hoursInWeekTriggerCsrSet) { + logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); + logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; + } UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); //CSR todo // result change in csr triggered hours are visible on output when i run tests? pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); From 4724b2dde2a295e836fc2398bec1b1744d5375a9 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 27 Apr 2022 12:50:35 +0800 Subject: [PATCH 096/490] flow direct and indirect --- .../opt_appel_solveur_quadratique.cpp | 1 + ...ction_variables_optimisees_quadratique.cpp | 34 +++---- ...opt_gestion_des_bornes_cas_quadratique.cpp | 93 ++++++++++--------- .../opt_gestion_des_couts_cas_quadratique.cpp | 38 ++++---- 4 files changed, 85 insertions(+), 81 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index c7848a7541..22f39e45df 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -257,6 +257,7 @@ bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeARes pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; if (pt) *pt = ProblemeAResoudre->X[Var]; + logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; } return true; diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 712c3a1e55..66313ad795 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -101,24 +101,24 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE logs.debug() << NumberOfVariables << " flow[" << Interco <<"]. "; NumberOfVariables++; - // TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) //CSR todo ??? how can it be true? a test case ? - // { - // CorrespondanceVarNativesVarOptim - // ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - // = NumberOfVariables; - // ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - // logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; - // NumberOfVariables++; - - // CorrespondanceVarNativesVarOptim - // ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - // = NumberOfVariables; - // ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - // logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; - // NumberOfVariables++; - - // } + { + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; + NumberOfVariables++; + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; + NumberOfVariables++; + + } } } 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 e9838bef67..b0083d6cf7 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -174,8 +174,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + Xmax[Var] = 2000; //ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = 0; //-(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); if (Math::Infinite(Xmax[Var]) == 1) { @@ -203,49 +203,52 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - // { - // Var = CorrespondanceVarNativesVarOptim - // ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] - // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - // Xmax[Var] += 0.01; - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - // if (Math::Infinite(Xmax[Var]) == 1) - // { - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - // } - // Xmin[Var] = 0.0; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! // todo: remove - - // logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; - - // Var = CorrespondanceVarNativesVarOptim - // ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] - // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - - // Xmax[Var] += 0.01; - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - // if (Math::Infinite(Xmax[Var]) == 1) - // { - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - // } - // Xmin[Var] = 0.0; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; - - // logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; - - // } + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + + Xmax[Var] = 3000; + Xmax[Var] += 0.01; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + + Xmin[Var] = 0.0; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! // todo: remove + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + + Xmax[Var] = 4000; + Xmax[Var] += 0.01; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + Xmin[Var] = 0.0; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; + // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + + } } } // todo: remove 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 058573c444..d0b9d9449c 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -146,25 +146,25 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - // { - // Var = CorrespondanceVarNativesVarOptim - // ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - // { - // ProblemeAResoudre->CoutLineaire[Var] - // = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - // logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - - // } - // Var = CorrespondanceVarNativesVarOptim - // ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - // { - // ProblemeAResoudre->CoutLineaire[Var] - // = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - // logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - // } - // } + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + + } + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + } + } } } From 858907a1228f27f254241138b128907ec74e697d Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 27 Apr 2022 13:43:09 +0800 Subject: [PATCH 097/490] constraint interco flow=d-i --- ...atrice_des_contraintes_cas_quadratique.cpp | 85 ++++++++++--------- ..._gestion_second_membre_cas_quadratique.cpp | 34 +++++--- 2 files changed, 67 insertions(+), 52 deletions(-) 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 index 874a264e5b..52e6255829 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -134,8 +134,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } // // I Kirchhoff's law contstraint for all areas. - // int Interco; - // COUTS_DE_TRANSPORT* TransportCost; + int Interco; + COUTS_DE_TRANSPORT* TransportCost; // // for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) //??? why not all area, but area - 1? // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) @@ -179,44 +179,53 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // } - // // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. - // for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - // { - // TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - // { - // NombreDeTermes = 0; - // 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++; - // } + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { - // hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.push_back( - // ProblemeAResoudre->NombreDeContraintes); + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { - // OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - // ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); - // } - // } + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + NombreDeTermes = 0; + 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.push_back( + ProblemeAResoudre->NombreDeContraintes); + + NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); + logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); + } + } + } // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. 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 3cb354dbd9..b2b3585dfd 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -92,20 +92,26 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // } - // // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. - // for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - // { - // TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - // { - // Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco]; - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] - // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // ProblemeAResoudre->SecondMembre[Cnt] = 0.; - // } - // } + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + { + Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco]; + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] + // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + ProblemeAResoudre->SecondMembre[Cnt] = 0.; + logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + } + } + } // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. From 9a002503aba24ab9bbba19fa648eb155b6ed9c72 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 27 Apr 2022 19:50:32 +0200 Subject: [PATCH 098/490] calculate net_position_init & dens_init --- ...opt_gestion_des_bornes_cas_quadratique.cpp | 91 ++++++++++++++++++- .../sim_structure_probleme_economique.h | 1 + 2 files changed, 90 insertions(+), 2 deletions(-) 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 b0083d6cf7..69ca17491f 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -95,6 +95,93 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P } } +void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + double netPositionInit; + double flowsNode1toNodeA; + double densNew; + double ensInit; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Interco; + bool includeFlowsOutsideAdqPatchToDensNew + = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + + logs.debug() << "========= [CSR]: Starting calculateDensNew for hour: "<< hour; + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + logs.debug() << "Area: " << Area; + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit = 0; + flowsNode1toNodeA = 0; + + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + logs.debug() << "First Interco Origine: " << Interco; + while (Interco >= 0) + { + logs.debug() << "Interco: " << Interco; + //logs.debug() << "extremityAreaType: " << ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco]; + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + + netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + + logs.debug() << "netPositionInit: " << netPositionInit; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA -= Math::Min(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + logs.debug() << "flowsNode1toNodeA: " << flowsNode1toNodeA; + } + Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; + } + Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + logs.debug() << "First Interco Extremite: " << Interco; + while (Interco >= 0) + { + logs.debug() << "Interco: " << Interco; + //logs.debug() << "origineAreaType: " << ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco]; + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + + netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + + logs.debug() << "netPositionInit: " << netPositionInit; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA += Math::Max(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + logs.debug() << "flowsNode1toNodeA: " << flowsNode1toNodeA; + } + Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + } + + // calculate densNew per area + ensInit + = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; + logs.debug() << "ensInit: " << ensInit; + if (includeFlowsOutsideAdqPatchToDensNew){ + densNew = Math::Max(0, ensInit + netPositionInit + flowsNode1toNodeA); + logs.debug() << "densNew (with 1): " << densNew; + } + else{ + densNew = Math::Max(0, ensInit + netPositionInit); + logs.debug() << "densNew (without 1): " << densNew; + } + // place densNew in a key(area)-value + hourlyCsrProblem.densNewValues.push_back(densNew); + // todo can we use vector, is it going to be the same order when we pass it to Xmax! + // or it's safer to go with the key(area)-value map? + } + } + return; +} + void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -115,7 +202,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - + calculateDensNew(ProblemeHebdo, hourlyCsrProblem); // variables: ENS for each area inside adq patch // one dummy constraint for testing : 0 <= ENS <= 10000 //todo remove for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) @@ -125,7 +212,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; ProblemeAResoudre->Xmin[Var] = 0; - ProblemeAResoudre->Xmax[Var] = 10000; + ProblemeAResoudre->Xmax[Var] = 10000; // densNew should be bound here! if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) { diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 33b641f5a3..ff9cab7807 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -738,6 +738,7 @@ class HOURLY_CSR_PROBLEM std::vector numberOfConstraintCsr; std::vector numberOfConstraintCsrAreaBalance; std::vector numberOfConstraintCsrFlowDissociation; + std::vector densNewValues; /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From e79b29b4a4ae6f686532c2b1f2c82f58ef492d7e Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 27 Apr 2022 19:57:07 +0200 Subject: [PATCH 099/490] clean logs and clang --- ...opt_gestion_des_bornes_cas_quadratique.cpp | 40 +++++-------------- 1 file changed, 11 insertions(+), 29 deletions(-) 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 69ca17491f..c9752e9195 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -106,76 +106,59 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC bool includeFlowsOutsideAdqPatchToDensNew = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; - logs.debug() << "========= [CSR]: Starting calculateDensNew for hour: "<< hour; for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { - logs.debug() << "Area: " << Area; if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { netPositionInit = 0; flowsNode1toNodeA = 0; - + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - logs.debug() << "First Interco Origine: " << Interco; while (Interco >= 0) { - logs.debug() << "Interco: " << Interco; - //logs.debug() << "extremityAreaType: " << ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco]; if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - - logs.debug() << "netPositionInit: " << netPositionInit; } else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch) { - flowsNode1toNodeA -= Math::Min(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - logs.debug() << "flowsNode1toNodeA: " << flowsNode1toNodeA; + flowsNode1toNodeA + -= Math::Min(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); } Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; } Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - logs.debug() << "First Interco Extremite: " << Interco; while (Interco >= 0) { - logs.debug() << "Interco: " << Interco; - //logs.debug() << "origineAreaType: " << ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco]; if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - - logs.debug() << "netPositionInit: " << netPositionInit; } else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch) { - flowsNode1toNodeA += Math::Max(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - logs.debug() << "flowsNode1toNodeA: " << flowsNode1toNodeA; + flowsNode1toNodeA + += Math::Max(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); } Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; } - // calculate densNew per area ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; - logs.debug() << "ensInit: " << ensInit; - if (includeFlowsOutsideAdqPatchToDensNew){ + if (includeFlowsOutsideAdqPatchToDensNew) + { densNew = Math::Max(0, ensInit + netPositionInit + flowsNode1toNodeA); - logs.debug() << "densNew (with 1): " << densNew; - } - else{ + } + else + { densNew = Math::Max(0, ensInit + netPositionInit); - logs.debug() << "densNew (without 1): " << densNew; } - // place densNew in a key(area)-value hourlyCsrProblem.densNewValues.push_back(densNew); - // todo can we use vector, is it going to be the same order when we pass it to Xmax! + // todo can we use vector, is it going to be the same order when we pass it to Xmax! // or it's safer to go with the key(area)-value map? } } @@ -202,7 +185,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - calculateDensNew(ProblemeHebdo, hourlyCsrProblem); // variables: ENS for each area inside adq patch // one dummy constraint for testing : 0 <= ENS <= 10000 //todo remove for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) From 7a1d88becd358e4b9bb70ba10bcee459b1fc00c6 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 28 Apr 2022 07:45:05 +0800 Subject: [PATCH 100/490] option 2. for cost in obj func. without changing number of variable/constraint --- .../opt_gestion_des_couts_cas_quadratique.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) 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 d0b9d9449c..34cbe413bd 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -153,6 +153,10 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, { ProblemeAResoudre->CoutLineaire[Var] = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + + if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) + ProblemeAResoudre->CoutLineaire[Var] = 0; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; } @@ -162,6 +166,10 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, { ProblemeAResoudre->CoutLineaire[Var] = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + + if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) + ProblemeAResoudre->CoutLineaire[Var] = 0; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; } } From 0506bc4fcfdfda6d99297bbc85de3cb1d0cc1f37 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Apr 2022 10:00:26 +0200 Subject: [PATCH 101/490] comment update --- ...t_construction_matrice_des_contraintes_cas_quadratique.cpp | 2 +- .../optimisation/opt_gestion_des_bornes_cas_quadratique.cpp | 4 ++-- .../opt_gestion_second_membre_cas_quadratique.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) 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 index 52e6255829..6271a8b3a2 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -179,7 +179,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // } - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of type 2. for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { 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 c9752e9195..0190b3ccd8 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -221,8 +221,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } - // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For ALL links. - // Set hourly bounds for ALL links depending on the user input (max direct and indirect flow). + // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links between nodes of type 2. + // Set hourly bounds for links between nodes of type 2, depending on the user input (max direct and indirect flow). double* Xmin; double* Xmax; int* TypeDeVariable; 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 b2b3585dfd..dd2f9bcf9d 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -92,7 +92,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // } - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for all links. + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of type 2. for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch From 610b9596579de1eafc1dd47b8b33ff3dd257777c Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Apr 2022 15:00:34 +0200 Subject: [PATCH 102/490] fix problem with vectors --- ...nstruction_matrice_des_contraintes_cas_quadratique.cpp | 6 +++--- .../opt_gestion_des_bornes_cas_quadratique.cpp | 2 +- .../opt_gestion_second_membre_cas_quadratique.cpp | 4 ++-- src/solver/simulation/sim_structure_probleme_economique.h | 8 ++++---- 4 files changed, 10 insertions(+), 10 deletions(-) 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 index 6271a8b3a2..95a05ec188 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -125,7 +125,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB Colonne[NombreDeTermes] = Var; NombreDeTermes++; - hourlyCsrProblem.numberOfConstraintCsr.push_back(ProblemeAResoudre->NombreDeContraintes); + hourlyCsrProblem.numberOfConstraintCsr.insert(std::pair(Area, ProblemeAResoudre->NombreDeContraintes)); NomDeLaContrainte = "dummy 2*ENS > 10. area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>', NomDeLaContrainte); @@ -215,8 +215,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB NombreDeTermes++; } - hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.push_back( - ProblemeAResoudre->NombreDeContraintes); + hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.insert( + std::pair(Interco, ProblemeAResoudre->NombreDeContraintes)); NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; 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 0190b3ccd8..0263e0d624 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -157,7 +157,7 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC { densNew = Math::Max(0, ensInit + netPositionInit); } - hourlyCsrProblem.densNewValues.push_back(densNew); + hourlyCsrProblem.densNewValues.insert(std::pair(Area, densNew)); // todo can we use vector, is it going to be the same order when we pass it to Xmax! // or it's safer to go with the key(area)-value map? } 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 dd2f9bcf9d..5d2e592531 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -63,7 +63,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - Cnt = hourlyCsrProblem.numberOfConstraintCsr[Area]; + Cnt = hourlyCsrProblem.numberOfConstraintCsr.find(Area)->second; ProblemeAResoudre->SecondMembre[Cnt] = 10; logs.debug() << Cnt << ": dummy 2*ENS > 10: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } @@ -102,7 +102,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) { - Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco]; + Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco)->second;; // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index ff9cab7807..69ed91d55c 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -735,10 +735,10 @@ class HOURLY_CSR_PROBLEM hourInWeekTriggeredCsr = hourInWeek; pWeeklyProblemBelongedTo = pProblemeHebdo; }; - std::vector numberOfConstraintCsr; - std::vector numberOfConstraintCsrAreaBalance; - std::vector numberOfConstraintCsrFlowDissociation; - std::vector densNewValues; + std::map numberOfConstraintCsr; + //std::vector numberOfConstraintCsrAreaBalance; + std::map numberOfConstraintCsrFlowDissociation; + std::map densNewValues; /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From 088da0eadd4200b1d10607c1f363112e17c240eb Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20Omn=C3=A8s?= Date: Thu, 28 Apr 2022 15:20:06 +0200 Subject: [PATCH 103/490] Make absence of areas//adequacy_patch.ini non-fatal (#655) --- src/libs/antares/study/area/list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 1d4228bf28..e1fc4f2b62 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1070,7 +1070,7 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, } // Adequacy patch - if (study.header.version >= 820) + if (study.header.version >= 820 && study.parameters.include.adequacyPatch) { buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; From 65a54eb627e8d2fe94bb76f3b25c5868ede58595 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Apr 2022 17:01:19 +0200 Subject: [PATCH 104/490] spilled energy variable (tested works) --- ...ction_variables_optimisees_quadratique.cpp | 15 +++++++++ ...opt_gestion_des_bornes_cas_quadratique.cpp | 33 +++++++++++++++++++ 2 files changed, 48 insertions(+) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 66313ad795..b301fe2598 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -86,6 +86,21 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE } } + // variables: Spilled Energy of each area inside adq patch // todo after debugging transfer this into same loop as ENS + logs.debug() << " Spilled Energy of each area inside adq patch: "; + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + // Only Spilled Energy for areas inside adq patch are considered as variables + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + logs.debug() << NumberOfVariables << " Spilled Energy[" << area <<"]. "; + + NumberOfVariables++; + } + } + // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 and 2. logs.debug() << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; COUTS_DE_TRANSPORT* TransportCost; 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 0263e0d624..b5db13b3f8 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -220,6 +220,39 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } } + // variables: Spilled Energy for each area inside adq patch // todo after debugging transfer this into same loop as ENS + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; + + ProblemeAResoudre->Xmin[Var] = 0.0; + ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; + + // if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) + // { + // if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + // else + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + // } + // else + // { + // if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + // else + // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + // } // no need for this check here! + + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; + AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); + + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + } + } // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links between nodes of type 2. // Set hourly bounds for links between nodes of type 2, depending on the user input (max direct and indirect flow). From 11440afed2ce0f0733865fa9aadb8c8713ce91fd Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Fri, 29 Apr 2022 08:27:03 +0800 Subject: [PATCH 105/490] map element exist check --- .../opt_gestion_second_membre_cas_quadratique.cpp | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) 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 5d2e592531..de6ab87839 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -63,7 +63,10 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - Cnt = hourlyCsrProblem.numberOfConstraintCsr.find(Area)->second; + // Cnt = hourlyCsrProblem.numberOfConstraintCsr.find(Area)->second; + std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsr.find(Area); + if(it != hourlyCsrProblem.numberOfConstraintCsr.end()) + Cnt = it->second; ProblemeAResoudre->SecondMembre[Cnt] = 10; logs.debug() << Cnt << ": dummy 2*ENS > 10: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } @@ -102,7 +105,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) { - Cnt = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco)->second;; + std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); + if(it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) + Cnt = it->second; // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; From 8f25ec31dc6134be4078ad8364a36e7fd4147062 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Apr 2022 10:09:02 +0200 Subject: [PATCH 106/490] cleaner inserting key-value pairs into maps --- ...construction_matrice_des_contraintes_cas_quadratique.cpp | 6 +++--- .../optimisation/opt_gestion_des_bornes_cas_quadratique.cpp | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) 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 index 95a05ec188..0b684dfc94 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -125,7 +125,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB Colonne[NombreDeTermes] = Var; NombreDeTermes++; - hourlyCsrProblem.numberOfConstraintCsr.insert(std::pair(Area, ProblemeAResoudre->NombreDeContraintes)); + hourlyCsrProblem.numberOfConstraintCsr[Area]= ProblemeAResoudre->NombreDeContraintes; NomDeLaContrainte = "dummy 2*ENS > 10. area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>', NomDeLaContrainte); @@ -215,8 +215,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB NombreDeTermes++; } - hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.insert( - std::pair(Interco, ProblemeAResoudre->NombreDeContraintes)); + hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco] + = ProblemeAResoudre->NombreDeContraintes; NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; 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 b5db13b3f8..b9106df112 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -157,7 +157,7 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC { densNew = Math::Max(0, ensInit + netPositionInit); } - hourlyCsrProblem.densNewValues.insert(std::pair(Area, densNew)); + hourlyCsrProblem.densNewValues[Area] = densNew; // todo can we use vector, is it going to be the same order when we pass it to Xmax! // or it's safer to go with the key(area)-value map? } From a6c04d2ded5bb00f31da1988d295f98b0053f962 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Apr 2022 14:09:34 +0200 Subject: [PATCH 107/490] "Node Balancing Conservation" constraint --- ...atrice_des_contraintes_cas_quadratique.cpp | 128 ++++++++++++------ ...opt_gestion_des_bornes_cas_quadratique.cpp | 15 +- ..._gestion_second_membre_cas_quadratique.cpp | 55 +++++--- .../sim_structure_probleme_economique.h | 3 +- 4 files changed, 132 insertions(+), 69 deletions(-) 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 index 0b684dfc94..5e96667209 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -133,52 +133,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } } - // // I Kirchhoff's law contstraint for all areas. int Interco; COUTS_DE_TRANSPORT* TransportCost; - // // for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) //??? why not all area, but area - 1? - // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - // { - // NombreDeTermes = 0; - - // Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - // while (Interco >= 0) - // { - // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - // if (Var >= 0) - // { - // Pi[NombreDeTermes] = 1.0; - // Colonne[NombreDeTermes] = Var; - // NombreDeTermes++; - // } - // Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; - // } - // Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - // while (Interco >= 0) - // { - // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - // if (Var >= 0) - // { - // Pi[NombreDeTermes] = -1.0; - // Colonne[NombreDeTermes] = Var; - // NombreDeTermes++; - // } - // Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; - // } - - // hourlyCsrProblem.numberOfConstraintCsrAreaBalance.push_back( - // ProblemeAResoudre->NombreDeContraintes); - - // NomDeLaContrainte = "NTC=sum(flow), area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; - // logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; - - // OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - // ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); - - - // } - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of type 2. for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { @@ -227,6 +184,91 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } } + // constraint: + // ENS(node A) + + // [ ∑flow_direct(node 2 upstream -> node A) + ∑flow_indirect(node A <- node 2 downstream) – + // ∑flow_indirect(node 2 upstream <- node A) – ∑flow_direct(node A -> node 2 downstream) ] – + // spillage(node A) = + // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) + // for all areas inside adequacy patch + for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + // + ENS + NombreDeTermes = 0; + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; + if (Var >= 0) + { + Pi[NombreDeTermes] = 1.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + } + + // - export flows + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableDeLInterconnexion[Interco]; + 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]; + } + // + import flows + Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableDeLInterconnexion[Interco]; + 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; + + NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area];; + logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); + } + } + // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. 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 b9106df112..c6f1bfa138 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -157,9 +157,9 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC { densNew = Math::Max(0, ensInit + netPositionInit); } + hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; hourlyCsrProblem.densNewValues[Area] = densNew; - // todo can we use vector, is it going to be the same order when we pass it to Xmax! - // or it's safer to go with the key(area)-value map? + //todo: maybe create two new maps to store Ens and spillage before them being reset to zero. } } return; @@ -179,6 +179,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + calculateDensNew(ProblemeHebdo, hourlyCsrProblem); // todo remove - for debugging only. Place this function in adequacy_patch and call it from economy for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; @@ -211,7 +212,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; } - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; + // ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; + // todo uncomment: if i reset ENS to zero here, like in linear optim, I cannot re-use it any more as ens_init in RHS (for AreaBalance) + // so, do we skip this reset, if it's not mandatory. or save the original ENS results + // in a new map, simillary to net_position_init and dens_new (cause this function can be triggered before ENS reset)! AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; @@ -245,7 +249,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; // } // no need for this check here! - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; + // ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; + // todo uncomment: if i reset spillage to zero here, like in linear optim, I cannot re-use it any more as spillage_init in RHS (for AreaBalance) + // so, do we skip this reset, if it's not mandatory. or save the original spillage results + // in a new map, simillary to net_position_init and dens_new (cause this function can be triggered before spillage reset)! AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; 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 de6ab87839..8437d89fe0 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -72,29 +72,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob } } - // I Kirchhoff's law contstraint for all areas. int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; COUTS_DE_TRANSPORT* TransportCost; - // double test; - // // for (Area = 0; Area < ProblemeHebdo->NombreDePays - 1; Area++) //??? why not all area, but area - 1? - // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - // { - // Cnt = hourlyCsrProblem.numberOfConstraintCsrAreaBalance[Area]; - - // //CSR Todo: should not use SoldeMoyenDuPays[Area] - // //should create a new function to calculate “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 chapter 2. - - // ProblemeAResoudre->SecondMembre[Cnt] - // = ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // todo what to use - // // ProblemeHebdo->SoldeMoyenHoraire[hour]->SoldeMoyenDuPays[Area]; // average hourly balance per area! OR - // // -ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[Area]; // = Reduced consumption per area - // logs.debug() << Cnt << ": NTC=sum(flow): RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - - // } - + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of type 2. for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { @@ -118,6 +98,39 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob } } + // constraint: + // ENS(node A) + + // [ ∑flow_direct(node 2 upstream -> node A) + ∑flow_indirect(node A <- node 2 downstream) – + // ∑flow_indirect(node 2 upstream <- node A) – ∑flow_direct(node A -> node 2 downstream) ] – + // spillage(node A) = + // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) + // for all areas inside adequacy patch + double netPositionInit; + for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + std::map::iterator it + = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); + if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) + Cnt = it->second; + std::map::iterator itt = hourlyCsrProblem.netPositionInitValues.find(Area); + if (itt != hourlyCsrProblem.netPositionInitValues.end()) + netPositionInit = itt->second; + else + netPositionInit = 0.0; + + ProblemeAResoudre->SecondMembre[Cnt] + = netPositionInit + + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour] + - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; + // todo : only can be used like this if we do not reset hourly results for ENS and spillage to zero (in set bounds function)! + + logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + } + } + // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. } \ No newline at end of file diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 69ed91d55c..b68a1a9784 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -736,8 +736,9 @@ class HOURLY_CSR_PROBLEM pWeeklyProblemBelongedTo = pProblemeHebdo; }; std::map numberOfConstraintCsr; - //std::vector numberOfConstraintCsrAreaBalance; + std::map numberOfConstraintCsrAreaBalance; std::map numberOfConstraintCsrFlowDissociation; + std::map netPositionInitValues; std::map densNewValues; /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From 05e535d42812a2473d07595f4c7216b565f9b1dc Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Apr 2022 14:28:59 +0200 Subject: [PATCH 108/490] clean "Node Balancing" solution --- .../opt_gestion_des_bornes_cas_quadratique.cpp | 15 ++++++--------- ...pt_gestion_second_membre_cas_quadratique.cpp | 17 +++++------------ .../sim_structure_probleme_economique.h | 1 + 3 files changed, 12 insertions(+), 21 deletions(-) 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 c6f1bfa138..4cb0abe38d 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -101,6 +101,7 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC double flowsNode1toNodeA; double densNew; double ensInit; + double spillageInit; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Interco; bool includeFlowsOutsideAdqPatchToDensNew @@ -149,6 +150,8 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC // calculate densNew per area ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; + spillageInit + = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; if (includeFlowsOutsideAdqPatchToDensNew) { densNew = Math::Max(0, ensInit + netPositionInit + flowsNode1toNodeA); @@ -159,7 +162,7 @@ void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC } hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; hourlyCsrProblem.densNewValues[Area] = densNew; - //todo: maybe create two new maps to store Ens and spillage before them being reset to zero. + hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; } } return; @@ -212,10 +215,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; } - // ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; - // todo uncomment: if i reset ENS to zero here, like in linear optim, I cannot re-use it any more as ens_init in RHS (for AreaBalance) - // so, do we skip this reset, if it's not mandatory. or save the original ENS results - // in a new map, simillary to net_position_init and dens_new (cause this function can be triggered before ENS reset)! + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; @@ -249,10 +249,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; // } // no need for this check here! - // ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; - // todo uncomment: if i reset spillage to zero here, like in linear optim, I cannot re-use it any more as spillage_init in RHS (for AreaBalance) - // so, do we skip this reset, if it's not mandatory. or save the original spillage results - // in a new map, simillary to net_position_init and dens_new (cause this function can be triggered before spillage reset)! + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; 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 8437d89fe0..4ae4cfe4e4 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -105,7 +105,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // spillage(node A) = // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - double netPositionInit; + double rhsAreaBalance; for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] @@ -115,18 +115,11 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) Cnt = it->second; - std::map::iterator itt = hourlyCsrProblem.netPositionInitValues.find(Area); - if (itt != hourlyCsrProblem.netPositionInitValues.end()) - netPositionInit = itt->second; - else - netPositionInit = 0.0; - - ProblemeAResoudre->SecondMembre[Cnt] - = netPositionInit - + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour] - - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; - // todo : only can be used like this if we do not reset hourly results for ENS and spillage to zero (in set bounds function)! + std::map::iterator itt = hourlyCsrProblem.rhsAreaBalanceValues.find(Area); + if (itt != hourlyCsrProblem.rhsAreaBalanceValues.end()) + rhsAreaBalance = itt->second; + ProblemeAResoudre->SecondMembre[Cnt] = rhsAreaBalance; logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } } diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index b68a1a9784..b22544c96d 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -740,6 +740,7 @@ class HOURLY_CSR_PROBLEM std::map numberOfConstraintCsrFlowDissociation; std::map netPositionInitValues; std::map densNewValues; + std::map rhsAreaBalanceValues; /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From aceaedd30af035f5b5e603d6c4b2cec6b03bd790 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Apr 2022 14:53:27 +0200 Subject: [PATCH 109/490] rename and move function for parameters calc --- src/solver/optimisation/adequacy_patch.cpp | 75 ++++++++++++++++++ src/solver/optimisation/adequacy_patch.h | 5 ++ ...opt_gestion_des_bornes_cas_quadratique.cpp | 76 +------------------ src/solver/simulation/economy.cpp | 2 + 4 files changed, 83 insertions(+), 75 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 8aa7914c07..750b501439 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -27,7 +27,9 @@ #include "../simulation/simulation.h" #include "adequacy_patch.h" +#include +using namespace Yuni; using namespace Antares::Data::AdequacyPatch; LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( @@ -144,3 +146,76 @@ void setBoundsNoAdqPatch(double& Xmax, Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } + +void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + double netPositionInit; + double flowsNode1toNodeA; + double densNew; + double ensInit; + double spillageInit; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Interco; + bool includeFlowsOutsideAdqPatchToDensNew + = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit = 0; + flowsNode1toNodeA = 0; + + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA + -= Math::Min(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + } + Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; + } + Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA + += Math::Max(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + } + Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + } + // calculate densNew per area + ensInit + = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; + spillageInit + = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; + if (includeFlowsOutsideAdqPatchToDensNew) + { + densNew = Math::Max(0, ensInit + netPositionInit + flowsNode1toNodeA); + } + else + { + densNew = Math::Max(0, ensInit + netPositionInit); + } + hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; + hourlyCsrProblem.densNewValues[Area] = densNew; + hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; + } + } + return; +} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 6df2ab802a..ac0414a7bf 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -104,4 +104,9 @@ void setBoundsNoAdqPatch(double& Xmax, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco); +/*! + * Calculate parameters for curtailment sharing rule inside adequacy patch. + */ +void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem); + #endif /* __SOLVER_ADEQUACY_FUNCTIONS_H__ */ 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 4cb0abe38d..7123ed7490 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -95,79 +95,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P } } -void calculateDensNew(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - double netPositionInit; - double flowsNode1toNodeA; - double densNew; - double ensInit; - double spillageInit; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Interco; - bool includeFlowsOutsideAdqPatchToDensNew - = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; - - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit = 0; - flowsNode1toNodeA = 0; - - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA - -= Math::Min(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; - } - Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA - += Math::Max(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; - } - // calculate densNew per area - ensInit - = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; - spillageInit - = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; - if (includeFlowsOutsideAdqPatchToDensNew) - { - densNew = Math::Max(0, ensInit + netPositionInit + flowsNode1toNodeA); - } - else - { - densNew = Math::Max(0, ensInit + netPositionInit); - } - hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; - hourlyCsrProblem.densNewValues[Area] = densNew; - hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; - } - } - return; -} - void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -182,8 +109,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - calculateDensNew(ProblemeHebdo, hourlyCsrProblem); // todo remove - for debugging only. Place this function in adequacy_patch and call it from economy - + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index c68bb2283d..148bf3fd61 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -36,6 +36,7 @@ #include "../optimisation/opt_fonctions.h" #include "common-eco-adq.h" #include +#include "../optimisation/adequacy_patch.h" using namespace Yuni; @@ -182,6 +183,7 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP //CSR todo // todo!! by using OPT_LiberationProblemesSimplexe are we deleting weekly results in pWeeklyProblem->RESULTATS_HORAIRES, calculated after LMR optimization? // apparently not cause i'm using RESULTATS_HORAIRES to calculate pto value in opt_gestion_des_couts_cas_quadratique and getting good values! + calculateCsrParameters(pWeeklyProblem, hourlyCsrProblem); OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); From cc7b98708b6de3506d9a294c539f18ce2b81c843 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Apr 2022 15:37:24 +0200 Subject: [PATCH 110/490] LHS hourly binding constraints - started, not tested --- ...atrice_des_contraintes_cas_quadratique.cpp | 75 +++++++++++++++++++ .../sim_structure_probleme_economique.h | 1 + 2 files changed, 76 insertions(+) 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 index 5e96667209..4c3537b441 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -32,6 +32,8 @@ #include "../simulation/sim_extern_variables_globales.h" #include "opt_fonctions.h" +using namespace Antares::Data; + void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* ProblemeHebdo) { int Interco; @@ -269,6 +271,79 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } } + // int NbInterco; + // double Poids; // Weight ?? + // int Offset; + // int hour1; + // CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + + // Study::Ptr study = Study::Current::Get(); + // uint numSpace = 0; // todo: not in problem hebdo, we need to pass it as function argument if we whant to use timeStepInYear. + // int timeStepInYear = study->runtime->weekInTheYear[numSpace] * 168 + hour; + + // // Special case of the binding constraints + // for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; + // CntCouplante++) + // { + // MatriceDesContraintesCouplantes + // = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + + // if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) + // { + // NbInterco + // = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; + // NombreDeTermes = 0; + // for (int Index = 0; Index < NbInterco; Index++) + // { + // Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; + // Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; + // Offset = MatriceDesContraintesCouplantes->OffsetTemporelSurLInterco[Index]; + + // if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + // == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + // && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + // == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + // { + // if (Offset >= 0) + // { + // hour1 + // = (hour + Offset) % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; + // } + // else + // { + // hour1 = (hour + Offset + ProblemeHebdo->NombreDePasDeTemps) + // % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; + // } + + // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour1] + // ->NumeroDeVariableDeLInterconnexion[Interco]; + + // if (Var >= 0) + // { + // Pi[NombreDeTermes] = Poids; + // Colonne[NombreDeTermes] = Var; + // NombreDeTermes++; + // } + // } + // } + + // hourlyCsrProblem.numberOfConstraintCsrHourlyBinding[CntCouplante] + // = ProblemeAResoudre->NombreDeContraintes; + + // NomDeLaContrainte = "bc::hourly::" + std::to_string(timeStepInYear + 1) // timeStepInYear not properly defined! + // + "::" + // + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; + + // OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + // ProblemeAResoudre, + // Pi, + // Colonne, + // NombreDeTermes, + // MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante, + // NomDeLaContrainte); + // } + // } + // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index b22544c96d..8a3cd6ebb1 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -738,6 +738,7 @@ class HOURLY_CSR_PROBLEM std::map numberOfConstraintCsr; std::map numberOfConstraintCsrAreaBalance; std::map numberOfConstraintCsrFlowDissociation; + std::map numberOfConstraintCsrHourlyBinding; std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; From 9bb3ab4af4659df6cc769d8209077caa584c0657 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 1 May 2022 18:18:50 +0800 Subject: [PATCH 111/490] debug log; fix comments --- src/solver/optimisation/adequacy_patch.cpp | 2 ++ ...atrice_des_contraintes_cas_quadratique.cpp | 23 +++++++++---------- .../opt_gestion_des_couts_cas_quadratique.cpp | 2 +- ..._gestion_second_membre_cas_quadratique.cpp | 6 ++--- 4 files changed, 17 insertions(+), 16 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 750b501439..84be61487f 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -215,6 +215,8 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; hourlyCsrProblem.densNewValues[Area] = densNew; hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; + logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] + << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit << ") - SpillageInit(" << spillageInit <<")"; } } 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 index 4c3537b441..68cb22f7ee 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -188,9 +188,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // constraint: // ENS(node A) + - // [ ∑flow_direct(node 2 upstream -> node A) + ∑flow_indirect(node A <- node 2 downstream) – - // ∑flow_indirect(node 2 upstream <- node A) – ∑flow_direct(node A -> node 2 downstream) ] – - // spillage(node A) = + // - flow (A -> 2) or (+ flow (2 -> A)) there should be only one of them, otherwise double-count + // - spillage(node A) = // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) @@ -216,20 +215,20 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableDeLInterconnexion[Interco]; + ->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]] << "]"; } - logs.debug() << "S-Interco number: [" << std::to_string(Interco) - << "] between: [" << ProblemeHebdo->NomsDesPays[Area] << "]-[" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] << "]"; } Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; } - // + import flows + // or + import flows Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; while (Interco >= 0) { @@ -237,16 +236,16 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableDeLInterconnexion[Interco]; + ->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]] << "]"; } - logs.debug() << "E-Interco number: [" << std::to_string(Interco) - << "] between: [" << ProblemeHebdo->NomsDesPays[Area] << "]-[" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] << "]"; } Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; } 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 34cbe413bd..564789b5f6 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -122,7 +122,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, // variables: transmission cost for links between nodes of type 2 (area inside adequacy patch) - // obj function term is: ∑( hurdle_cost_direct x flow_direct )+ ∑( hurdle_cost_indirect x flow_indirect ) + // obj function term is: Sum ( hurdle_cost_direct x flow_direct )+ Sum ( hurdle_cost_indirect x flow_indirect ) // => quadratic cost: 0 // => linear cost: hurdle_cost_direct or hurdle_cost_indirect // these members of objective functions are considered only if IntercoGereeAvecDesCouts = OUI_ANTARES (use hurdle cost option is true). 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 4ae4cfe4e4..3dc63b0098 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -100,8 +100,8 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // constraint: // ENS(node A) + - // [ ∑flow_direct(node 2 upstream -> node A) + ∑flow_indirect(node A <- node 2 downstream) – - // ∑flow_indirect(node 2 upstream <- node A) – ∑flow_direct(node A -> node 2 downstream) ] – + // [ 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) ] – // spillage(node A) = // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch @@ -120,7 +120,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob rhsAreaBalance = itt->second; ProblemeAResoudre->SecondMembre[Cnt] = rhsAreaBalance; - logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area <<")"; } } From 35c9ce24f4db662a51de8e318e5cce9da26a89b6 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 1 May 2022 21:48:16 +0800 Subject: [PATCH 112/490] binding constraint. draft --- ...atrice_des_contraintes_cas_quadratique.cpp | 147 ++++++++++-------- ..._gestion_second_membre_cas_quadratique.cpp | 77 ++++++++- .../sim_structure_probleme_economique.h | 9 +- 3 files changed, 163 insertions(+), 70 deletions(-) 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 index 68cb22f7ee..f04f4d5792 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -270,81 +270,92 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } } - // int NbInterco; - // double Poids; // Weight ?? + int NbInterco; + double Poids; // Weight // int Offset; // int hour1; - // CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; // Study::Ptr study = Study::Current::Get(); // uint numSpace = 0; // todo: not in problem hebdo, we need to pass it as function argument if we whant to use timeStepInYear. // int timeStepInYear = study->runtime->weekInTheYear[numSpace] * 168 + hour; - // // Special case of the binding constraints - // for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; - // CntCouplante++) - // { - // MatriceDesContraintesCouplantes - // = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - - // if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) - // { - // NbInterco - // = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; - // NombreDeTermes = 0; - // for (int Index = 0; Index < NbInterco; Index++) - // { - // Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; - // Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - // Offset = MatriceDesContraintesCouplantes->OffsetTemporelSurLInterco[Index]; - - // if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - // == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - // && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - // == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - // { - // if (Offset >= 0) - // { - // hour1 - // = (hour + Offset) % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; - // } - // else - // { - // hour1 = (hour + Offset + ProblemeHebdo->NombreDePasDeTemps) - // % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; - // } - - // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour1] - // ->NumeroDeVariableDeLInterconnexion[Interco]; - - // if (Var >= 0) - // { - // Pi[NombreDeTermes] = Poids; - // Colonne[NombreDeTermes] = Var; - // NombreDeTermes++; - // } - // } - // } - - // hourlyCsrProblem.numberOfConstraintCsrHourlyBinding[CntCouplante] - // = ProblemeAResoudre->NombreDeContraintes; - - // NomDeLaContrainte = "bc::hourly::" + std::to_string(timeStepInYear + 1) // timeStepInYear not properly defined! - // + "::" - // + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; - - // OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - // ProblemeAResoudre, - // Pi, - // Colonne, - // NombreDeTermes, - // MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante, - // NomDeLaContrainte); - // } - // } - - // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows - // and/or power generated from generating units. + // Special case of the binding constraints + for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; + CntCouplante++) + { + MatriceDesContraintesCouplantes + = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + + hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = false; //init as false, if there is interco 2-2, then change to true + + if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) + { + NbInterco + = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; + NombreDeTermes = 0; + for (int Index = 0; Index < NbInterco; Index++) + { + Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; + Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; + // Offset = MatriceDesContraintesCouplantes->OffsetTemporelSurLInterco[Index]; + + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + // if (Offset >= 0) + // { + // hour1 + // = (hour + Offset) % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; + // } + // else + // { + // hour1 = (hour + Offset + ProblemeHebdo->NombreDePasDeTemps) + // % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; + // } + + Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour] + ->NumeroDeVariableDeLInterconnexion[Interco]; + + if (Var >= 0) + { + Pi[NombreDeTermes] = Poids; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + } + } + // CSR todo: cluster becomes RHS parameters + } + + if (NombreDeTermes > 0) //current binding constraint contains an interco type 2<->2 + { + hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = true; + + hourlyCsrProblem.numberOfConstraintCsrHourlyBinding[CntCouplante] + = ProblemeAResoudre->NombreDeContraintes; + + // NomDeLaContrainte = "bc::hourly::" + std::to_string(timeStepInYear + 1) // timeStepInYear not properly defined! + // + "::" + // + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; + NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) + + "::" + + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante + ". Interco:" + std::to_string(Interco); + + logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, + Pi, + Colonne, + NombreDeTermes, + MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante, + NomDeLaContrainte); + } + } + } MemFree(Pi); MemFree(Colonne); 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 3dc63b0098..b3e16b48e4 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -126,4 +126,79 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows // and/or power generated from generating units. -} \ No newline at end of file + int CntCouplante; + int Interco; + CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; + double* SecondMembre = ProblemeAResoudre->SecondMembre; + std::map bingdingConstraintNumber = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; + + int NbInterco; + double Poids; + double ValeurDuFlux; + int Index; + + for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; + CntCouplante++) + { + if(bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) + // if(hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] == true) + { + + MatriceDesContraintesCouplantes = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + + Cnt = bingdingConstraintNumber[CntCouplante]; + + //1. this is the original RHS of bingding constraint + SecondMembre[Cnt] = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; + // SecondMembre[Cnt] = MatriceDesContraintesCouplantes + // ->SecondMembreDeLaContrainteCouplante[PdtHebdo]; + // AdresseOuPlacerLaValeurDesCoutsMarginaux[Cnt] = NULL; + + //2. CSR todo: RHS part 2: flow other than 2<->2 + NbInterco = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; + for (Index = 0; Index < NbInterco; Index++) + { + Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; + Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; + + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + //we have an interco other than type 2-2 + // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]->NumeroDeVariableDeLInterconnexion[Interco]; + ValeurDuFlux = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; //todo check do we care about the export/import + SecondMembre[Cnt] -= ValeurDuFlux * Poids; + } + } + + //3. CSR todo: RHS part 3: - cluster + int NbClusters = MatriceDesContraintesCouplantes + ->NombreDePaliersDispatchDansLaContrainteCouplante; + int Pays; + PALIERS_THERMIQUES* PaliersThermiquesDuPays; + int Palier; + int IndexNumeroDuPalierDispatch; + + for (Index = 0; Index < NbClusters; Index++) + { + Pays = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; + PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Pays]; + + IndexNumeroDuPalierDispatch = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; + + Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques + [IndexNumeroDuPalierDispatch]; + Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; + + //CSR todo, value of Var "Cluster Output" check if this is correct? + // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[Pdt1]->NumeroDeVariableDuPalierThermique[Palier]; + double ValueOfVar = ProblemeHebdo->ResultatsHoraires[Pays] + ->ProductionThermique[hour] + ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; + + SecondMembre[Cnt] -= ValueOfVar * Poids; + } + } + } +} diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 8a3cd6ebb1..2cc4695f3d 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -738,10 +738,17 @@ class HOURLY_CSR_PROBLEM std::map numberOfConstraintCsr; std::map numberOfConstraintCsrAreaBalance; std::map numberOfConstraintCsrFlowDissociation; - std::map numberOfConstraintCsrHourlyBinding; + std::map numberOfConstraintCsrHourlyBinding; //length is number of binding constraint contains interco 2-2 + + //to remember if a bc contains an interco type 2<->2 + //this can be merged with numberOfConstraintCsrHourlyBinding, + // with a check in map numberOfConstraintCsrHourlyBinding.find(..) != .end() + std::map bindingConstraintContainsIntercoInsideAdqPatch; //lenght is number of total binding constraint + std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; + /* variables */ // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM From 34471d186477b72695a744529b2ba818350b367a Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 2 May 2022 14:37:56 +0200 Subject: [PATCH 113/490] binding constraints loggs and update --- ...atrice_des_contraintes_cas_quadratique.cpp | 15 ++++++-- ..._gestion_second_membre_cas_quadratique.cpp | 38 ++++++++++++++----- 2 files changed, 40 insertions(+), 13 deletions(-) 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 index f04f4d5792..1140c74362 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -287,8 +287,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB MatriceDesContraintesCouplantes = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = false; //init as false, if there is interco 2-2, then change to true - + // hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = false; //init as false, if there is interco 2-2, then change to true + // not used. if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) { NbInterco @@ -324,6 +324,13 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB Pi[NombreDeTermes] = Poids; Colonne[NombreDeTermes] = Var; NombreDeTermes++; + + logs.debug() + << "Interco:" + std::to_string(Interco) << ". Between:[" + << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + << "]-[" + << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + << "], with Poids(coeff):" + std::to_string(Poids) + " inserted to LHS!"; } } // CSR todo: cluster becomes RHS parameters @@ -331,7 +338,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB if (NombreDeTermes > 0) //current binding constraint contains an interco type 2<->2 { - hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = true; + // hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = true; // not used hourlyCsrProblem.numberOfConstraintCsrHourlyBinding[CntCouplante] = ProblemeAResoudre->NombreDeContraintes; @@ -341,7 +348,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB // + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) + "::" - + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante + ". Interco:" + std::to_string(Interco); + + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante;// + ". Interco:" + std::to_string(Interco); logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte; 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 b3e16b48e4..d4e7accbba 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -135,13 +135,13 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob int NbInterco; double Poids; - double ValeurDuFlux; + double ValueOfFlow; int Index; for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) { - if(bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) + if(bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) //ok // if(hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] == true) { @@ -151,9 +151,12 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob //1. this is the original RHS of bingding constraint SecondMembre[Cnt] = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; + logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt + << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante + << ")"; // SecondMembre[Cnt] = MatriceDesContraintesCouplantes // ->SecondMembreDeLaContrainteCouplante[PdtHebdo]; - // AdresseOuPlacerLaValeurDesCoutsMarginaux[Cnt] = NULL; + // AdresseOuPlacerLaValeurDesCoutsMarginaux[Cnt] = NULL; // ok. costs are not of interest to us here! //2. CSR todo: RHS part 2: flow other than 2<->2 NbInterco = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; @@ -167,23 +170,34 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob { //we have an interco other than type 2-2 // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]->NumeroDeVariableDeLInterconnexion[Interco]; - ValeurDuFlux = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; //todo check do we care about the export/import - SecondMembre[Cnt] -= ValeurDuFlux * Poids; + ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; //todo check do we care about the export/import + SecondMembre[Cnt] -= ValueOfFlow * Poids; + logs.debug() + << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt + << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" + << ". Interco;" + std::to_string(Interco) << ". Between:[" + << ProblemeHebdo + ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + << "]-[" + << ProblemeHebdo + ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + << "]" << ". ValueOfFlow: " <NombreDePaliersDispatchDansLaContrainteCouplante; - int Pays; + int Area; PALIERS_THERMIQUES* PaliersThermiquesDuPays; int Palier; int IndexNumeroDuPalierDispatch; + double ValueOfVar; // to be consistent code as above for (Index = 0; Index < NbClusters; Index++) { - Pays = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; - PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Pays]; + Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; + PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; IndexNumeroDuPalierDispatch = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; @@ -193,11 +207,17 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob //CSR todo, value of Var "Cluster Output" check if this is correct? // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[Pdt1]->NumeroDeVariableDuPalierThermique[Palier]; - double ValueOfVar = ProblemeHebdo->ResultatsHoraires[Pays] + ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] ->ProductionThermique[hour] ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; SecondMembre[Cnt] -= ValueOfVar * Poids; + logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt + << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante + << ")" + << ". Area:" << Area + << ", Palier:" << Palier << ", Poids" << Poids + << ", ValueOfVar:" << ValueOfVar; } } } From e13aaafa99b03980a07b130cc2eccf5bfcd48e71 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Tue, 3 May 2022 13:42:11 +0800 Subject: [PATCH 114/490] remove dummy constraint --- ...atrice_des_contraintes_cas_quadratique.cpp | 36 +++++++++---------- ..._gestion_second_membre_cas_quadratique.cpp | 26 +++++++------- .../sim_structure_probleme_economique.h | 2 +- 3 files changed, 32 insertions(+), 32 deletions(-) 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 index 1140c74362..5ed3a38df0 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -116,24 +116,24 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // constraint: 2 * ENS > 10 - for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - NombreDeTermes = 0; - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; - Pi[NombreDeTermes] = 2.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; - - hourlyCsrProblem.numberOfConstraintCsr[Area]= ProblemeAResoudre->NombreDeContraintes; - NomDeLaContrainte = "dummy 2*ENS > 10. area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; - logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; - OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>', NomDeLaContrainte); - - } - } + // // constraint: 2 * ENS > 10 + // for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) + // { + // if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + // { + // NombreDeTermes = 0; + // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; + // Pi[NombreDeTermes] = 2.0; + // Colonne[NombreDeTermes] = Var; + // NombreDeTermes++; + + // hourlyCsrProblem.numberOfConstraintCsr[Area]= ProblemeAResoudre->NombreDeContraintes; + // NomDeLaContrainte = "dummy 2*ENS > 10. area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; + // logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + // OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>', NomDeLaContrainte); + + // } + // } int Interco; COUTS_DE_TRANSPORT* TransportCost; 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 d4e7accbba..5975b25777 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -58,19 +58,19 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - //constraint for each area inside adq patch: 2 * ENS > 10 - for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - // Cnt = hourlyCsrProblem.numberOfConstraintCsr.find(Area)->second; - std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsr.find(Area); - if(it != hourlyCsrProblem.numberOfConstraintCsr.end()) - Cnt = it->second; - ProblemeAResoudre->SecondMembre[Cnt] = 10; - logs.debug() << Cnt << ": dummy 2*ENS > 10: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - } - } + // //constraint for each area inside adq patch: 2 * ENS > 10 + // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + // { + // if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + // { + // // Cnt = hourlyCsrProblem.numberOfConstraintCsr.find(Area)->second; + // std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsr.find(Area); + // if(it != hourlyCsrProblem.numberOfConstraintCsr.end()) + // Cnt = it->second; + // ProblemeAResoudre->SecondMembre[Cnt] = 10; + // logs.debug() << Cnt << ": dummy 2*ENS > 10: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + // } + // } int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; COUTS_DE_TRANSPORT* TransportCost; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 2cc4695f3d..09a5993442 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -735,7 +735,7 @@ class HOURLY_CSR_PROBLEM hourInWeekTriggeredCsr = hourInWeek; pWeeklyProblemBelongedTo = pProblemeHebdo; }; - std::map numberOfConstraintCsr; + // std::map numberOfConstraintCsr; std::map numberOfConstraintCsrAreaBalance; std::map numberOfConstraintCsrFlowDissociation; std::map numberOfConstraintCsrHourlyBinding; //length is number of binding constraint contains interco 2-2 From 2f76dd4e2f7ac9bcea69b32aa50a6eff673a8fff Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Tue, 3 May 2022 13:46:30 +0800 Subject: [PATCH 115/490] minor clean --- ...ction_variables_optimisees_quadratique.cpp | 32 +++++++-------- .../opt_gestion_des_couts_cas_quadratique.cpp | 40 +++++++++---------- 2 files changed, 34 insertions(+), 38 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index b301fe2598..7762ef3604 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -117,23 +117,21 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE NumberOfVariables++; TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) //CSR todo ??? how can it be true? a test case ? - { - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; - NumberOfVariables++; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; - NumberOfVariables++; - - } + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; + NumberOfVariables++; + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; + NumberOfVariables++; + } } 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 564789b5f6..e777f13fe9 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -145,33 +145,31 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; } - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) - ProblemeAResoudre->CoutLineaire[Var] = 0; + if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) + ProblemeAResoudre->CoutLineaire[Var] = 0; - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + } + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) - ProblemeAResoudre->CoutLineaire[Var] = 0; + if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) + ProblemeAResoudre->CoutLineaire[Var] = 0; - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; } } } From 03cdef2741a1dabf9d3f8f3b3bbf12cdd0566841 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Tue, 3 May 2022 13:47:49 +0800 Subject: [PATCH 116/490] minor clean --- ...atrice_des_contraintes_cas_quadratique.cpp | 63 +++++++++---------- 1 file changed, 31 insertions(+), 32 deletions(-) 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 index 5ed3a38df0..78d3bd65e2 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -147,42 +147,41 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) + + NombreDeTermes = 0; + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + if (Var >= 0) { - NombreDeTermes = 0; - 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++; - } + 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; + hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco] + = ProblemeAResoudre->NombreDeContraintes; - NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); - logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); + logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); - } } } From 01df9d7ba7b4316775ff3084d908b91cf6319451 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 4 May 2022 08:59:25 +0800 Subject: [PATCH 117/490] fix bounds --- ...ction_variables_optimisees_quadratique.cpp | 8 +- ...opt_gestion_des_bornes_cas_quadratique.cpp | 93 ++----------------- 2 files changed, 11 insertions(+), 90 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 7762ef3604..553062e66d 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -52,7 +52,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NombreDeVariables; - ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; NombreDeVariables++; } ProblemeAResoudre->NombreDeVariables = NombreDeVariables; @@ -112,7 +112,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_NON_BORNEE; logs.debug() << NumberOfVariables << " flow[" << Interco <<"]. "; NumberOfVariables++; @@ -121,14 +121,14 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLE CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; NumberOfVariables++; CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; NumberOfVariables++; 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 7123ed7490..69939cc91b 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -116,30 +116,14 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: ENS for each area inside adq patch - // one dummy constraint for testing : 0 <= ENS <= 10000 //todo remove for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - ProblemeAResoudre->Xmin[Var] = 0; - ProblemeAResoudre->Xmax[Var] = 10000; // densNew should be bound here! - - if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) - { - if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else - { - if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } + ProblemeAResoudre->Xmin[Var] = 0.0; + ProblemeAResoudre->Xmax[Var] = 10000; //hourlyCsrProblem.densNewValues[hour];//CSR todo use DENS new; ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); @@ -160,21 +144,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre->Xmin[Var] = 0.0; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; - // if (Math::Infinite(ProblemeAResoudre->Xmax[Var]) == 1) - // { - // if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - // else - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - // } - // else - // { - // if (Math::Infinite(ProblemeAResoudre->Xmin[Var]) == -1) - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - // else - // ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - // } // no need for this check here! - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); @@ -205,28 +174,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - - Xmax[Var] = 2000; //ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = 0; //-(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - - if (Math::Infinite(Xmax[Var]) == 1) - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } - - // AdresseDuResultat = &(ProblemeHebdo->VariablesDualesDesContraintesDeNTC[hour] - // ->VariableDualeParInterconnexion[Interco]); // dual variable for links // todo: remove - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = AdresseDuResultat; // reduced cost // todo: remove + Xmax[Var] = LINFINI_ANTARES; + Xmin[Var] = -LINFINI_ANTARES; AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; @@ -239,44 +188,16 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] - // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - Xmax[Var] = 3000; - Xmax[Var] += 0.01; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - Xmin[Var] = 0.0; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; // not adding AdresseDuResultat! // todo: remove + Xmax[Var] = LINFINI_ANTARES; logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] - // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - - Xmax[Var] = 4000; - Xmax[Var] += 0.01; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } + Xmin[Var] = 0.0; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesCoutsReduits[Var] = NULL; - // ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + Xmax[Var] = LINFINI_ANTARES; logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; From f012abcfaeff3928e8d547d035198bc6d028cab9 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 4 May 2022 09:19:26 +0800 Subject: [PATCH 118/490] bug fix for max double. --- src/solver/optimisation/adequacy_patch.cpp | 9 +++++---- .../opt_gestion_des_bornes_cas_quadratique.cpp | 2 +- 2 files changed, 6 insertions(+), 5 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 84be61487f..be76b2d10e 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -179,7 +179,7 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h == adqmPhysicalAreaOutsideAdqPatch) { flowsNode1toNodeA - -= Math::Min(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + -= Math::Min(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); } Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; } @@ -195,7 +195,7 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h == adqmPhysicalAreaOutsideAdqPatch) { flowsNode1toNodeA - += Math::Max(0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + += Math::Max(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); } Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; } @@ -206,14 +206,15 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; if (includeFlowsOutsideAdqPatchToDensNew) { - densNew = Math::Max(0, ensInit + netPositionInit + flowsNode1toNodeA); + densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); } else { - densNew = Math::Max(0, ensInit + netPositionInit); + densNew = Math::Max(0.0, ensInit + netPositionInit); } hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; hourlyCsrProblem.densNewValues[Area] = densNew; + logs.debug() << "DENS_new[" << Area <<"] = " << hourlyCsrProblem.densNewValues[Area] ; hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit << ") - SpillageInit(" << spillageInit <<")"; 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 69939cc91b..6e99154765 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -123,7 +123,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; ProblemeAResoudre->Xmin[Var] = 0.0; - ProblemeAResoudre->Xmax[Var] = 10000; //hourlyCsrProblem.densNewValues[hour];//CSR todo use DENS new; + ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area]; ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); From 6a74f15ca6fc7d71ca0c5cadedc252f099f081c8 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 4 May 2022 09:27:29 +0800 Subject: [PATCH 119/490] CSR todo for loopflow ? --- ...opt_gestion_des_bornes_cas_quadratique.cpp | 106 +++++++++++------- 1 file changed, 65 insertions(+), 41 deletions(-) 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 6e99154765..49047e2acd 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -109,7 +109,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( hour = hourlyCsrProblem.hourInWeekTriggeredCsr; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; @@ -118,48 +118,59 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // variables: ENS for each area inside adq patch for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; ProblemeAResoudre->Xmin[Var] = 0.0; ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area]; - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; - AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] + = 0.0; + AdresseDuResultat = &( + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] + = AdresseDuResultat; - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; } } - // variables: Spilled Energy for each area inside adq patch // todo after debugging transfer this into same loop as ENS + // variables: Spilled Energy for each area inside adq patch // todo after debugging transfer + // this into same loop as ENS for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; ProblemeAResoudre->Xmin[Var] = 0.0; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] = 0.0; - AdresseDuResultat = &(ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] + = 0.0; + AdresseDuResultat = &( + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] + = AdresseDuResultat; - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; } } - // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links between nodes of type 2. - // Set hourly bounds for links between nodes of type 2, depending on the user input (max direct and indirect flow). + // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links + // between nodes of type 2. Set hourly bounds for links between nodes of type 2, depending on + // the user input (max direct and indirect flow). double* Xmin; double* Xmax; - int* TypeDeVariable; + int* TypeDeVariable; VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; - COUTS_DE_TRANSPORT* TransportCost; Xmin = ProblemeAResoudre->Xmin; Xmax = ProblemeAResoudre->Xmax; @@ -167,44 +178,57 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) { - // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { + // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; Xmax[Var] = LINFINI_ANTARES; Xmin[Var] = -LINFINI_ANTARES; AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; - - - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - - Xmin[Var] = 0.0; - Xmax[Var] = LINFINI_ANTARES; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] + = AdresseDuResultat; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; + + // direct / indirect flow + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + // CSR Todo? + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + + Xmin[Var] = 0.0; + Xmax[Var] = LINFINI_ANTARES; - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; - Xmin[Var] = 0.0; - Xmax[Var] = LINFINI_ANTARES; + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + // CSR Todo? + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; + Xmin[Var] = 0.0; + Xmax[Var] = LINFINI_ANTARES; - } + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; } } - // todo: remove + // todo: remove //CSR Todo? // 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 From 88564d669c4dc858656f7d5f3054dd91c25ec1c1 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 4 May 2022 09:35:05 +0800 Subject: [PATCH 120/490] clean; format --- ...ction_variables_optimisees_quadratique.cpp | 150 +++++++++--------- 1 file changed, 78 insertions(+), 72 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 553062e66d..e6a302c516 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -58,84 +58,90 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H ProblemeAResoudre->NombreDeVariables = NombreDeVariables; } -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - logs.debug() << "[CSR] variable list:"; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - int NumberOfVariables = 0; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); - - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: ENS of each area inside adq patch - logs.debug() << " ENS of each area inside adq patch: "; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - // Only ENS for areas inside adq patch are considered as variables - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " ENS[" << area <<"]. "; + logs.debug() << "[CSR] variable list:"; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + int NumberOfVariables = 0; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - NumberOfVariables++; - } - } - - // variables: Spilled Energy of each area inside adq patch // todo after debugging transfer this into same loop as ENS - logs.debug() << " Spilled Energy of each area inside adq patch: "; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - // Only Spilled Energy for areas inside adq patch are considered as variables - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; - logs.debug() << NumberOfVariables << " Spilled Energy[" << area <<"]. "; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + assert(ProblemeAResoudre != NULL); - NumberOfVariables++; - } - } - - // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 and 2. - logs.debug() << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; - COUTS_DE_TRANSPORT* TransportCost; - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // variables: ENS of each area inside adq patch + logs.debug() << " ENS of each area inside adq patch: "; + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_NON_BORNEE; - logs.debug() << NumberOfVariables << " flow[" << Interco <<"]. "; - NumberOfVariables++; - - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; - logs.debug() << NumberOfVariables << " direct flow[" << Interco <<"]. "; - NumberOfVariables++; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; - logs.debug() << NumberOfVariables << " indirect flow[" << Interco <<"]. "; - NumberOfVariables++; + // Only ENS for areas inside adq patch are considered as variables + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " ENS[" << area << "]. "; + + NumberOfVariables++; + } + } + // variables: Spilled Energy of each area inside adq patch // todo after debugging transfer + // this into same loop as ENS + logs.debug() << " Spilled Energy of each area inside adq patch: "; + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + // Only Spilled Energy for areas inside adq patch are considered as variables + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "]. "; + + NumberOfVariables++; + } } - } + // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 + // and 2. + logs.debug() + << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + // only consider link between 2 and 2 + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_NON_BORNEE; + logs.debug() << NumberOfVariables << " flow[" << Interco << "]. "; + NumberOfVariables++; + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + logs.debug() << NumberOfVariables << " direct flow[" << Interco << "]. "; + NumberOfVariables++; + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + logs.debug() << NumberOfVariables << " indirect flow[" << Interco << "]. "; + NumberOfVariables++; + } + } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; - return; + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; + return; } \ No newline at end of file From ca09e148a506ace1c65c9ed38a1951ad04510aec Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 4 May 2022 09:54:15 +0800 Subject: [PATCH 121/490] clean; format --- ...atrice_des_contraintes_cas_quadratique.cpp | 136 +++++++--------- .../opt_gestion_des_couts_cas_quadratique.cpp | 75 +++++---- ..._gestion_second_membre_cas_quadratique.cpp | 146 +++++++++--------- .../sim_structure_probleme_economique.h | 25 ++- 4 files changed, 171 insertions(+), 211 deletions(-) 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 index 78d3bd65e2..d926652b00 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -94,8 +94,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* MemFree(Colonne); } - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { logs.debug() << "[CSR] constraint list:"; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; @@ -116,36 +117,18 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // // constraint: 2 * ENS > 10 - // for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) - // { - // if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - // { - // NombreDeTermes = 0; - // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; - // Pi[NombreDeTermes] = 2.0; - // Colonne[NombreDeTermes] = Var; - // NombreDeTermes++; - - // hourlyCsrProblem.numberOfConstraintCsr[Area]= ProblemeAResoudre->NombreDeContraintes; - // NomDeLaContrainte = "dummy 2*ENS > 10. area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; - // logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; - // OPT_ChargerLaContrainteDansLaMatriceDesContraintes(ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '>', NomDeLaContrainte); - - // } - // } - int Interco; COUTS_DE_TRANSPORT* TransportCost; - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of type 2. + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of + // type 2. for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { - - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; NombreDeTermes = 0; @@ -174,21 +157,21 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB } hourlyCsrProblem.numberOfConstraintCsrFlowDissociation[Interco] - = ProblemeAResoudre->NombreDeContraintes; + = ProblemeAResoudre->NombreDeContraintes; NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); - logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte ; + logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); - + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); } } - // constraint: - // ENS(node A) + + // constraint: + // ENS(node A) + // - flow (A -> 2) or (+ flow (2 -> A)) there should be only one of them, otherwise double-count - // - spillage(node A) = + // - spillage(node A) = // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) @@ -205,7 +188,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB Colonne[NombreDeTermes] = Var; NombreDeTermes++; } - + // - export flows Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; while (Interco >= 0) @@ -214,15 +197,18 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableDeLInterconnexion[Interco]; //flow (A->2) + ->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]] << "]"; + logs.debug() + << "S-Interco number: [" << std::to_string(Interco) << "] between: [" + << ProblemeHebdo->NomsDesPays[Area] << "]-[" + << ProblemeHebdo + ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + << "]"; } } Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; @@ -241,9 +227,12 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB 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]] << "]"; + logs.debug() + << "E-Interco number: [" << std::to_string(Interco) << "] between: [" + << ProblemeHebdo->NomsDesPays[Area] << "]-[" + << ProblemeHebdo + ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + << "]"; } } Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; @@ -258,9 +247,12 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB NombreDeTermes++; } - hourlyCsrProblem.numberOfConstraintCsrAreaBalance[Area] = ProblemeAResoudre->NombreDeContraintes; + hourlyCsrProblem.numberOfConstraintCsrAreaBalance[Area] + = ProblemeAResoudre->NombreDeContraintes; - NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area];; + NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " + + ProblemeHebdo->NomsDesPays[Area]; + ; logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte; @@ -271,14 +263,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB int NbInterco; double Poids; // Weight - // int Offset; - // int hour1; CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - - // Study::Ptr study = Study::Current::Get(); - // uint numSpace = 0; // todo: not in problem hebdo, we need to pass it as function argument if we whant to use timeStepInYear. - // int timeStepInYear = study->runtime->weekInTheYear[numSpace] * 168 + hour; - // Special case of the binding constraints for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) @@ -286,8 +271,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB MatriceDesContraintesCouplantes = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - // hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = false; //init as false, if there is interco 2-2, then change to true - // not used. if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) { NbInterco @@ -297,24 +280,12 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB { Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - // Offset = MatriceDesContraintesCouplantes->OffsetTemporelSurLInterco[Index]; if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - // if (Offset >= 0) - // { - // hour1 - // = (hour + Offset) % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; - // } - // else - // { - // hour1 = (hour + Offset + ProblemeHebdo->NombreDePasDeTemps) - // % ProblemeHebdo->NombreDePasDeTempsPourUneOptimisation; - // } - Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour] ->NumeroDeVariableDeLInterconnexion[Interco]; @@ -326,39 +297,36 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEB logs.debug() << "Interco:" + std::to_string(Interco) << ". Between:[" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + << ProblemeHebdo + ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] << "]-[" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + << ProblemeHebdo + ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] << "], with Poids(coeff):" + std::to_string(Poids) + " inserted to LHS!"; } } - // CSR todo: cluster becomes RHS parameters } - if (NombreDeTermes > 0) //current binding constraint contains an interco type 2<->2 + if (NombreDeTermes > 0) // current binding constraint contains an interco type 2<->2 { - // hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] = true; // not used - hourlyCsrProblem.numberOfConstraintCsrHourlyBinding[CntCouplante] - = ProblemeAResoudre->NombreDeContraintes; + = ProblemeAResoudre->NombreDeContraintes; - // NomDeLaContrainte = "bc::hourly::" + std::to_string(timeStepInYear + 1) // timeStepInYear not properly defined! - // + "::" - // + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; - NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) - + "::" - + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante;// + ". Interco:" + std::to_string(Interco); + NomDeLaContrainte + = "bc::hourly::" + std::to_string(hour) + "::" + + MatriceDesContraintesCouplantes + ->NomDeLaContrainteCouplante; // + ". Interco:" + std::to_string(Interco); logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; + << NomDeLaContrainte; OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, - Pi, - Colonne, - NombreDeTermes, - MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante, - NomDeLaContrainte); + ProblemeAResoudre, + Pi, + Colonne, + NombreDeTermes, + MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante, + NomDeLaContrainte); } } } 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 e777f13fe9..d514d879be 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -63,14 +63,13 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, { logs.debug() << "[CSR] cost"; int Var; - int hour; - double priceTakingOrders; //PTO + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + double priceTakingOrders; // PTO double quadraticCost; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + int Interco; + COUTS_DE_TRANSPORT* TransportCost; // variables: ENS for each area inside adq patch // obj function term is: 1 / (PTO * PTO) * ENS * ENS @@ -86,49 +85,52 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - // if (ProblemeHebdo->adqPatch->PriceTakingOrder == Data::AdequacyPatch::adqPatchPTOIsLoad) + // CSR Todo options + // if (ProblemeHebdo->adqPatch->PriceTakingOrder == + // Data::AdequacyPatch::adqPatchPTOIsLoad) // { - // priceTakingOrders - // = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] - // + ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; + // priceTakingOrders + // = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] + // + + // ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; // } // else // { - priceTakingOrders = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; + priceTakingOrders + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; // } if (priceTakingOrders <= 0.0) { - //CSR todo a warning that DENS is negative and it is considered for CSR, there was a check for positive threshold + // CSR todo a warning that DENS is negative and it is considered for CSR, there + // was a check for positive threshold quadraticCost = 0.0; } else { quadraticCost = 1 / (priceTakingOrders * priceTakingOrders); } - // quadraticCost = 2.0; //todo to remove. for debug - // Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; // double checking? no need. - // if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; - logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; + + ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; + logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; } } } - // 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 flow_indirect ) + // obj function term is: Sum ( hurdle_cost_direct x flow_direct )+ Sum ( hurdle_cost_indirect x + // flow_indirect ) // => quadratic cost: 0 // => linear cost: hurdle_cost_direct or hurdle_cost_indirect - // these members of objective functions are considered only if IntercoGereeAvecDesCouts = OUI_ANTARES (use hurdle cost option is true). - // otherwise these members are zero. - int Interco; - COUTS_DE_TRANSPORT* TransportCost; + // these members of objective functions are considered only if IntercoGereeAvecDesCouts = + // OUI_ANTARES (use hurdle cost option is true). otherwise these members are zero. + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] @@ -137,42 +139,37 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - + // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; 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]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) ProblemeAResoudre->CoutLineaire[Var] = 0; - + else + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } + Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) ProblemeAResoudre->CoutLineaire[Var] = 0; - - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + else + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; } } } - - return; } \ No newline at end of file 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 5975b25777..01d184b854 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -48,62 +48,51 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme } } -void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { logs.debug() << "[CSR] RHS: "; - //CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. + // CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. int Cnt; int Area; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - // //constraint for each area inside adq patch: 2 * ENS > 10 - // for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - // { - // if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - // { - // // Cnt = hourlyCsrProblem.numberOfConstraintCsr.find(Area)->second; - // std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsr.find(Area); - // if(it != hourlyCsrProblem.numberOfConstraintCsr.end()) - // Cnt = it->second; - // ProblemeAResoudre->SecondMembre[Cnt] = 10; - // logs.debug() << Cnt << ": dummy 2*ENS > 10: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - // } - // } - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; COUTS_DE_TRANSPORT* TransportCost; - - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of type 2. + + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of + // type 2. for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // if (TransportCost->IntercoGereeAvecDesCouts == OUI_ANTARES) - { - std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); - if(it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) - Cnt = it->second; - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] - // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - ProblemeAResoudre->SecondMembre[Cnt] = 0.; - logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - } + + std::map::iterator it + = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); + if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) + Cnt = it->second; + // CSR Todo? loop flow? + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] + // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + ProblemeAResoudre->SecondMembre[Cnt] = 0.; + logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } } - // constraint: - // ENS(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) ] – - // spillage(node A) = - // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) + // constraint: + // ENS(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) + // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch double rhsAreaBalance; for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) @@ -120,7 +109,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob rhsAreaBalance = itt->second; ProblemeAResoudre->SecondMembre[Cnt] = rhsAreaBalance; - logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area <<")"; + logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area + << ")"; } } @@ -131,46 +122,50 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; double* SecondMembre = ProblemeAResoudre->SecondMembre; - std::map bingdingConstraintNumber = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; - + std::map bingdingConstraintNumber + = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; + int NbInterco; double Poids; - double ValueOfFlow; + double ValueOfFlow; int Index; for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; - CntCouplante++) + CntCouplante++) { - if(bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) //ok - // if(hourlyCsrProblem.bindingConstraintContainsIntercoInsideAdqPatch[CntCouplante] == true) + if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) // ok { - - MatriceDesContraintesCouplantes = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + MatriceDesContraintesCouplantes + = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; Cnt = bingdingConstraintNumber[CntCouplante]; - //1. this is the original RHS of bingding constraint - SecondMembre[Cnt] = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; + // 1. this is the original RHS of bingding constraint + SecondMembre[Cnt] + = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")"; - // SecondMembre[Cnt] = MatriceDesContraintesCouplantes - // ->SecondMembreDeLaContrainteCouplante[PdtHebdo]; - // AdresseOuPlacerLaValeurDesCoutsMarginaux[Cnt] = NULL; // ok. costs are not of interest to us here! - //2. CSR todo: RHS part 2: flow other than 2<->2 - NbInterco = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; + // 2. CSR todo: RHS part 2: flow other than 2<->2 + NbInterco + = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; for (Index = 0; Index < NbInterco; Index++) { Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - //we have an interco other than type 2-2 - // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]->NumeroDeVariableDeLInterconnexion[Interco]; - ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; //todo check do we care about the export/import + // we have an interco other than type 2-2 + // Var = + // ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]->NumeroDeVariableDeLInterconnexion[Interco]; + ValueOfFlow + = ProblemeHebdo->ValeursDeNTC[hour] + ->ValeurDuFlux[Interco]; // todo check do we care about the export/import SecondMembre[Cnt] -= ValueOfFlow * Poids; logs.debug() << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt @@ -181,44 +176,45 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob << "]-[" << ProblemeHebdo ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - << "]" << ". ValueOfFlow: " <NombreDePaliersDispatchDansLaContrainteCouplante; + // 3. CSR todo: RHS part 3: - cluster + int NbClusters + = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; int Area; PALIERS_THERMIQUES* PaliersThermiquesDuPays; int Palier; int IndexNumeroDuPalierDispatch; - double ValueOfVar; // to be consistent code as above - + double ValueOfVar; + for (Index = 0; Index < NbClusters; Index++) { Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; - IndexNumeroDuPalierDispatch = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; + IndexNumeroDuPalierDispatch + = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques - [IndexNumeroDuPalierDispatch]; + [IndexNumeroDuPalierDispatch]; Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; - //CSR todo, value of Var "Cluster Output" check if this is correct? - // Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[Pdt1]->NumeroDeVariableDuPalierThermique[Palier]; + // Var = + // ProblemeHebdo->CorrespondanceVarNativesVarOptim[Pdt1]->NumeroDeVariableDuPalierThermique[Palier]; ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] - ->ProductionThermique[hour] - ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; + ->ProductionThermique[hour] + ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; SecondMembre[Cnt] -= ValueOfVar * Poids; logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" - << ". Area:" << Area - << ", Palier:" << Palier << ", Poids" << Poids + << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids << ", ValueOfVar:" << ValueOfVar; } } - } + } } diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 09a5993442..f769110873 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -326,7 +326,7 @@ class AdequacyPatchRuntimeData public: std::vector areaMode; std::vector originAreaType; - std::vector extremityAreaType; + std::vector extremityAreaType; void initialize(Antares::Data::Study& study) { for (uint i = 0; i != study.areas.size(); ++i) @@ -615,7 +615,8 @@ struct PROBLEME_HEBDO /* Adequacy Patch */ std::unique_ptr adqPatch = nullptr; AdequacyPatchRuntimeData adequacyPatchRuntimeData; - std::vector houlyCsrProblems; //CSR: this should be an array for the hours triggered CSR + std::vector + houlyCsrProblems; // CSR: this should be an array for the hours triggered CSR optimizationStatistics optimizationStatistics_object; /* Hydro management */ @@ -721,7 +722,8 @@ struct PROBLEME_HEBDO class HOURLY_CSR_RESULT { - //CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside RESULTATS_HORAIRES? + // CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside + // RESULTATS_HORAIRES? }; // hourly CSR problem structure @@ -735,27 +737,24 @@ class HOURLY_CSR_PROBLEM hourInWeekTriggeredCsr = hourInWeek; pWeeklyProblemBelongedTo = pProblemeHebdo; }; - // std::map numberOfConstraintCsr; std::map numberOfConstraintCsrAreaBalance; std::map numberOfConstraintCsrFlowDissociation; - std::map numberOfConstraintCsrHourlyBinding; //length is number of binding constraint contains interco 2-2 - - //to remember if a bc contains an interco type 2<->2 - //this can be merged with numberOfConstraintCsrHourlyBinding, - // with a check in map numberOfConstraintCsrHourlyBinding.find(..) != .end() - std::map bindingConstraintContainsIntercoInsideAdqPatch; //lenght is number of total binding constraint + std::map numberOfConstraintCsrHourlyBinding; // length is number of binding constraint + // contains interco 2-2 std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; /* variables */ - // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to create variables inside HOURLY_CSR_PROBLEM + // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to + // create variables inside HOURLY_CSR_PROBLEM /* Results */ - HOURLY_CSR_RESULT hourlyResult; //CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside RESULTATS_HORAIRES? + HOURLY_CSR_RESULT hourlyResult; // CSR todo: shall we create a new HOURLY_CSR_RESULT structure, + // or do we update directly inside RESULTATS_HORAIRES? - //CSR todo: there should be structures for building the optimization problem like: + // CSR todo: there should be structures for building the optimization problem like: // CORRESPONDANCES_DES_VARIABLES* // CORRESPONDANCES_DES_CONTRAINTES* }; From f08471e1c28162a73eaba98e5b6f1fdb3095b8f2 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 4 May 2022 10:13:26 +0800 Subject: [PATCH 122/490] debug note --- src/solver/simulation/economy.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 148bf3fd61..2a996909cd 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -146,6 +146,8 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, std::set& triggerCsrSet) { float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; + threshold = 500; //todo remove. for debug + double sumENS[nbHoursInAWeek] = {}; //init sumENS[]. @@ -162,7 +164,6 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, // pProblemeHebdo->NombreDePasDeTemps); nbHoursInAWeek); //use nbHoursInAWeek seems more clear } - threshold = 500; //todo remove. for debug for (int i = 0; i < nbHoursInAWeek; ++i) { if ((int)sumENS[i] >= threshold) From c9bd66f24087619531845feb3cc39c3bab1ba375 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 10:03:56 +0200 Subject: [PATCH 123/490] clean --- .../opt_gestion_second_membre_cas_quadratique.cpp | 2 +- src/solver/simulation/economy.cpp | 9 ++++----- 2 files changed, 5 insertions(+), 6 deletions(-) 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 01d184b854..6aa1af5843 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -133,7 +133,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) { - if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) // ok + if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) { MatriceDesContraintesCouplantes = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 2a996909cd..10bbcc6974 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -154,15 +154,14 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, for (int j = 0; j < nbHoursInAWeek; ++j) sumENS[j] = 0.0; - for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) + for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) { - if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] + if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) Math::sumTwoArrays( sumENS, - pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, - // pProblemeHebdo->NombreDePasDeTemps); - nbHoursInAWeek); //use nbHoursInAWeek seems more clear + pProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive, + nbHoursInAWeek); } for (int i = 0; i < nbHoursInAWeek; ++i) { From 0759dd9fc8f60d9ac591553f1ca8c8100a3f4f5e Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 11:03:08 +0200 Subject: [PATCH 124/490] clean --- src/solver/simulation/economy.cpp | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 10bbcc6974..a7dc10bb3e 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -180,9 +180,6 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP PROBLEME_HEBDO* pWeeklyProblem = hourlyCsrProblem.pWeeklyProblemBelongedTo; OPT_LiberationProblemesSimplexe(pWeeklyProblem); //CSR todo !!! do we do this here ???? or do we create another PROBLEME_ANTARES_A_RESOUDRE inside HOURLY_CSR_PROBLEM ???? - //CSR todo - // todo!! by using OPT_LiberationProblemesSimplexe are we deleting weekly results in pWeeklyProblem->RESULTATS_HORAIRES, calculated after LMR optimization? - // apparently not cause i'm using RESULTATS_HORAIRES to calculate pto value in opt_gestion_des_couts_cas_quadratique and getting good values! calculateCsrParameters(pWeeklyProblem, hourlyCsrProblem); OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); @@ -258,7 +255,7 @@ bool Economy::year(Progression::Task& progression, logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; } - UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); //CSR todo // result change in csr triggered hours are visible on output when i run tests? + UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); } } From 12ad347384150c864bb0e69b7131aea84dd42e40 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 12:18:09 +0200 Subject: [PATCH 125/490] assign NTC values as flow bounds --- ...ction_variables_optimisees_quadratique.cpp | 6 ++-- ...opt_gestion_des_bornes_cas_quadratique.cpp | 33 ++++++++++++++++--- 2 files changed, 32 insertions(+), 7 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index e6a302c516..b8565c815c 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -122,21 +122,21 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_NON_BORNEE; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() << NumberOfVariables << " flow[" << Interco << "]. "; NumberOfVariables++; CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() << NumberOfVariables << " direct flow[" << Interco << "]. "; NumberOfVariables++; CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() << NumberOfVariables << " indirect flow[" << Interco << "]. "; NumberOfVariables++; } 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 49047e2acd..76db779b6f 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -186,8 +186,23 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( { // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[Var] = LINFINI_ANTARES; - Xmin[Var] = -LINFINI_ANTARES; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + + if (Math::Infinite(Xmax[Var]) == 1) + { + if (Math::Infinite(Xmin[Var]) == -1) + TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + else + { + if (Math::Infinite(Xmin[Var]) == -1) + TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] @@ -207,7 +222,12 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin[Var] = 0.0; - Xmax[Var] = LINFINI_ANTARES; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; @@ -222,7 +242,12 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; Xmin[Var] = 0.0; - Xmax[Var] = LINFINI_ANTARES; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; From a0cee81ab307f150c9005b7d3f3b4751ae01cf4d Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 12:31:06 +0200 Subject: [PATCH 126/490] bug fix --- .../opt_gestion_des_bornes_cas_quadratique.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 76db779b6f..93596667df 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -192,16 +192,16 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( if (Math::Infinite(Xmax[Var]) == 1) { if (Math::Infinite(Xmin[Var]) == -1) - TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; else - TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; } else { if (Math::Infinite(Xmin[Var]) == -1) - TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; else - TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; } AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); @@ -223,10 +223,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Xmin[Var] = 0.0; Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { - TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; } logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " @@ -243,10 +243,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Xmin[Var] = 0.0; Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { - TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; } logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " From 22217d42d1985174ce8dec92a189fe47990f0fca Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 15:04:58 +0200 Subject: [PATCH 127/490] convert upper bound (ENS<= Dens-new) to constraint --- ...atrice_des_contraintes_cas_quadratique.cpp | 23 +++++++++++++++++++ ...ction_variables_optimisees_quadratique.cpp | 2 +- ...opt_gestion_des_bornes_cas_quadratique.cpp | 2 +- ..._gestion_second_membre_cas_quadratique.cpp | 15 ++++++++++++ .../sim_structure_probleme_economique.h | 1 + 5 files changed, 41 insertions(+), 2 deletions(-) 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 index d926652b00..8fd71781e9 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -120,6 +120,29 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( int Interco; COUTS_DE_TRANSPORT* TransportCost; + // constraint: ENS < DENS_new + for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + NombreDeTermes = 0; + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; + Pi[NombreDeTermes] = 1.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + + hourlyCsrProblem.numberOfConstraintCsrEns[Area] + = ProblemeAResoudre->NombreDeContraintes; + NomDeLaContrainte = "ENS < DENS_new. Area:" + std::to_string(Area) + "; " + + ProblemeHebdo->NomsDesPays[Area]; + logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '<', NomDeLaContrainte); + } + } + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of // type 2. for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index b8565c815c..4f5b7a0e86 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -83,7 +83,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; logs.debug() << NumberOfVariables << " ENS[" << area << "]. "; NumberOfVariables++; 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 93596667df..6aca10ebc0 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -124,7 +124,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; ProblemeAResoudre->Xmin[Var] = 0.0; - ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area]; + ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; 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 6aa1af5843..7b9454d21e 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -62,6 +62,21 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; COUTS_DE_TRANSPORT* TransportCost; + // constraint for each area inside adq patch: ENS < DENS_new + for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + { + std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); + if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) + Cnt = it->second; + ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.densNewValues[Area]; + logs.debug() << Cnt << ": ENS < DENS_new: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + } + } + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of // type 2. for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index f769110873..48b452be21 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -737,6 +737,7 @@ class HOURLY_CSR_PROBLEM hourInWeekTriggeredCsr = hourInWeek; pWeeklyProblemBelongedTo = pProblemeHebdo; }; + std::map numberOfConstraintCsrEns; std::map numberOfConstraintCsrAreaBalance; std::map numberOfConstraintCsrFlowDissociation; std::map numberOfConstraintCsrHourlyBinding; // length is number of binding constraint From b48ee46bdd41e7bfa6efaf1faebc27dce2cf8a2f Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 15:12:37 +0200 Subject: [PATCH 128/490] small refacto --- .../opt_gestion_second_membre_cas_quadratique.cpp | 6 +----- 1 file changed, 1 insertion(+), 5 deletions(-) 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 7b9454d21e..d4fab65aef 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -109,7 +109,6 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // – Sum flow_indirect(node 2 upstream <- node A) – Sum flow_direct(node A -> node 2 downstream) // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - double rhsAreaBalance; for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] @@ -119,11 +118,8 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) Cnt = it->second; - std::map::iterator itt = hourlyCsrProblem.rhsAreaBalanceValues.find(Area); - if (itt != hourlyCsrProblem.rhsAreaBalanceValues.end()) - rhsAreaBalance = itt->second; - ProblemeAResoudre->SecondMembre[Cnt] = rhsAreaBalance; + ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area << ")"; From 45abf466a60a07f0ecc67e3accc0bb3cc53d9535 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 4 May 2022 15:24:40 +0200 Subject: [PATCH 129/490] small refacto --- src/solver/simulation/economy.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index a7dc10bb3e..3eb818bc5e 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -148,11 +148,11 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; threshold = 500; //todo remove. for debug - double sumENS[nbHoursInAWeek] = {}; + double sumENS[nbHoursInAWeek] = {0}; // this shold be better as init?, i debugged it. Works fine! - //init sumENS[]. - for (int j = 0; j < nbHoursInAWeek; ++j) - sumENS[j] = 0.0; + // // init sumENS[]. + // for (int j = 0; j < nbHoursInAWeek; ++j) + // sumENS[j] = 0.0; for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) { From 7e7c87a28f03d278ea3f7d43754e0c7e3e9256b4 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 5 May 2022 17:57:42 +0200 Subject: [PATCH 130/490] typo --- src/solver/simulation/economy.cpp | 8 ++++---- src/solver/simulation/sim_structure_probleme_economique.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 3eb818bc5e..ca0f7f20c4 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -192,7 +192,7 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP void UpdateWeeklyResultAfterCSR(PROBLEME_HEBDO* pProblemeHebdo) { - std::vector hourlyCsrProblems = pProblemeHebdo->houlyCsrProblems; + std::vector hourlyCsrProblems = pProblemeHebdo->hourlyCsrProblems; for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) { @@ -245,18 +245,18 @@ bool Economy::year(Progression::Task& progression, InitiateCurtailmentSharingRuleIndexSet(pProblemesHebdo[numSpace], hoursInWeekTriggerCsrSet); if( hoursInWeekTriggerCsrSet.size() > 0) { - pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); + pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); for(int hourInWeek : hoursInWeekTriggerCsrSet) { logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->houlyCsrProblems.push_back(hourlyCsrProblem); + pProblemesHebdo[numSpace]->hourlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; } UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->houlyCsrProblems.clear(); + pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); } } else diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 48b452be21..7ab541530b 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -616,7 +616,7 @@ struct PROBLEME_HEBDO std::unique_ptr adqPatch = nullptr; AdequacyPatchRuntimeData adequacyPatchRuntimeData; std::vector - houlyCsrProblems; // CSR: this should be an array for the hours triggered CSR + hourlyCsrProblems; // CSR: this should be an array for the hours triggered CSR optimizationStatistics optimizationStatistics_object; /* Hydro management */ From 9c6612870db01c01c808853b5b74935b2c872564 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 5 May 2022 18:36:25 +0200 Subject: [PATCH 131/490] lmr violations function (issue) --- src/solver/optimisation/adequacy_patch.cpp | 79 +++++++++++++++++++ src/solver/optimisation/adequacy_patch.h | 4 + src/solver/simulation/economy.cpp | 1 + .../sim_structure_probleme_economique.h | 1 + 4 files changed, 85 insertions(+) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index be76b2d10e..d0f2ebc0b5 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -221,4 +221,83 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h } } return; +} + +void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) +{ + // todo. To much code is duplicated. Create sub function and reuse them. or try something else! + float threshold = ProblemeHebdo->adqPatch->ThresholdDisplayLocalMatchingRuleViolations; + double netPositionInit; + double flowsNode1toNodeA; + double densNew; + double ensInit; + const int numOfHoursInWeek = 168; + double spillageInit; + int Interco; + std::vector lmrTmpVector; + std::map> localMatchingRuleViolation; // todo remove, for debugg + bool includeFlowsOutsideAdqPatchToDensNew + = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == adqmPhysicalAreaInsideAdqPatch) + { + lmrTmpVector.clear(); + for (int hour = 0; hour < numOfHoursInWeek; hour++) + { + netPositionInit = 0; + flowsNode1toNodeA = 0; + + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA -= Math::Min( + 0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + } + Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; + } + Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA += Math::Max( + 0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + } + Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + } + + ensInit = ProblemeHebdo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillancePositive[hour]; + if (includeFlowsOutsideAdqPatchToDensNew) + densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); + else + densNew = Math::Max(0.0, ensInit + netPositionInit); + + // check LMR violations + lmrTmpVector.push_back(0); + if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) + lmrTmpVector.at(hour) = 1; + } + localMatchingRuleViolation[Area] = lmrTmpVector; // todo remove, for debugg + //ProblemeHebdo->localMatchingRuleViolation[Area] = lmrTmpVector; + } + } + return; } \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index ac0414a7bf..744c8a1877 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -108,5 +108,9 @@ void setBoundsNoAdqPatch(double& Xmax, * Calculate parameters for curtailment sharing rule inside adequacy patch. */ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem); +/*! + * Check local matching rule violation for each area inside adequacy patch. + */ +void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo); #endif /* __SOLVER_ADEQUACY_FUNCTIONS_H__ */ diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index ca0f7f20c4..33dd61d5a3 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -258,6 +258,7 @@ bool Economy::year(Progression::Task& progression, UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); } + checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace]); } else { diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 7ab541530b..d2c1819f68 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -617,6 +617,7 @@ struct PROBLEME_HEBDO AdequacyPatchRuntimeData adequacyPatchRuntimeData; std::vector hourlyCsrProblems; // CSR: this should be an array for the hours triggered CSR + std::map> localMatchingRuleViolation; optimizationStatistics optimizationStatistics_object; /* Hydro management */ From c5b58f53ea95b41666fe9d340c369c605019cee5 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 6 May 2022 10:10:19 +0200 Subject: [PATCH 132/490] different approach for storing results --- src/solver/optimisation/adequacy_patch.cpp | 17 +++++++++++------ .../simulation/sim_alloc_probleme_hebdo.cpp | 3 +++ .../sim_structure_probleme_economique.h | 3 ++- 3 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index d0f2ebc0b5..102627e7d8 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -234,8 +234,8 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) const int numOfHoursInWeek = 168; double spillageInit; int Interco; - std::vector lmrTmpVector; - std::map> localMatchingRuleViolation; // todo remove, for debugg + //std::vector lmrTmpVector; + //std::map> localMatchingRuleViolation; // todo remove, for debugg bool includeFlowsOutsideAdqPatchToDensNew = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; @@ -244,7 +244,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == adqmPhysicalAreaInsideAdqPatch) { - lmrTmpVector.clear(); + //lmrTmpVector.clear(); for (int hour = 0; hour < numOfHoursInWeek; hour++) { netPositionInit = 0; @@ -291,11 +291,16 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) densNew = Math::Max(0.0, ensInit + netPositionInit); // check LMR violations - lmrTmpVector.push_back(0); + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = hour; + // lmrTmpVector.push_back(0); if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) - lmrTmpVector.at(hour) = 1; + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; + //lmrTmpVector.at(hour) = 1; + logs.debug() + << "LMR violations. Area:" << Area << ". hour:" << hour << ". Value:" + << ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour]; } - localMatchingRuleViolation[Area] = lmrTmpVector; // todo remove, for debugg + // localMatchingRuleViolation[Area] = lmrTmpVector; // todo remove, for debugg //ProblemeHebdo->localMatchingRuleViolation[Area] = lmrTmpVector; } } diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index d08b5f778f..3ee8d1be7d 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -461,6 +461,8 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDENS = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); // adq patch + problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations + = (int*)MemAlloc(NombreDePasDeTemps * sizeof(int)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown @@ -846,6 +848,7 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.PaliersThermiquesDuPays[k]); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index d2c1819f68..49421dce9c 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -450,6 +450,7 @@ typedef struct { double* ValeursHorairesDeDefaillancePositive; double* ValeursHorairesDENS; // adq patch domestic unsupplied energy + int* ValeursHorairesLmrViolations; // adq patch lmr violations double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; @@ -617,7 +618,7 @@ struct PROBLEME_HEBDO AdequacyPatchRuntimeData adequacyPatchRuntimeData; std::vector hourlyCsrProblems; // CSR: this should be an array for the hours triggered CSR - std::map> localMatchingRuleViolation; + //std::map> localMatchingRuleViolation; optimizationStatistics optimizationStatistics_object; /* Hydro management */ From bc9c3d2650e12c8461fdb9df113e4dc00b510f90 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 6 May 2022 10:52:22 +0200 Subject: [PATCH 133/490] making sub function calculateAreaFlowBalance --- src/solver/optimisation/adequacy_patch.cpp | 131 ++++++++------------- src/solver/optimisation/adequacy_patch.h | 6 + src/solver/simulation/economy.cpp | 2 +- 3 files changed, 59 insertions(+), 80 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 102627e7d8..27b1972915 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -155,7 +155,6 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h double ensInit; double spillageInit; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Interco; bool includeFlowsOutsideAdqPatchToDensNew = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; @@ -164,60 +163,25 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == adqmPhysicalAreaInsideAdqPatch) { - netPositionInit = 0; - flowsNode1toNodeA = 0; - - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == adqmPhysicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA - -= Math::Min(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; - } - Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == adqmPhysicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA - += Math::Max(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; - } + std::tie(netPositionInit, flowsNode1toNodeA) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); // calculate densNew per area ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; spillageInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; if (includeFlowsOutsideAdqPatchToDensNew) - { densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); - } else - { densNew = Math::Max(0.0, ensInit + netPositionInit); - } + hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; hourlyCsrProblem.densNewValues[Area] = densNew; - logs.debug() << "DENS_new[" << Area <<"] = " << hourlyCsrProblem.densNewValues[Area] ; hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; + + logs.debug() << "DENS_new[" << Area <<"] = " << hourlyCsrProblem.densNewValues[Area] ; logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit << ") - SpillageInit(" << spillageInit <<")"; + logs.debug() << "flowsNode1toNodeA[" << Area <<"] = " << flowsNode1toNodeA ; } } return; @@ -233,7 +197,6 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) double ensInit; const int numOfHoursInWeek = 168; double spillageInit; - int Interco; //std::vector lmrTmpVector; //std::map> localMatchingRuleViolation; // todo remove, for debugg bool includeFlowsOutsideAdqPatchToDensNew @@ -247,55 +210,22 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) //lmrTmpVector.clear(); for (int hour = 0; hour < numOfHoursInWeek; hour++) { - netPositionInit = 0; - flowsNode1toNodeA = 0; - - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == adqmPhysicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA -= Math::Min( - 0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; - } - Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == adqmPhysicalAreaInsideAdqPatch) - { - netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == adqmPhysicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA += Math::Max( - 0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; - } - + std::tie(netPositionInit, flowsNode1toNodeA) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); ensInit = ProblemeHebdo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillancePositive[hour]; + if (includeFlowsOutsideAdqPatchToDensNew) densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); else densNew = Math::Max(0.0, ensInit + netPositionInit); // check LMR violations - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = hour; + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; // lmrTmpVector.push_back(0); if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; //lmrTmpVector.at(hour) = 1; + logs.debug() << "LMR violations. Area:" << Area << ". hour:" << hour << ". Value:" << ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour]; @@ -305,4 +235,47 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) } } return; +} + +std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, + int Area, + int hour) +{ + double netPositionInit = 0; + double flowsNode1toNodeA = 0; + int Interco; + + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + == adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA + -= Math::Min(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + } + Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; + } + Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == adqmPhysicalAreaInsideAdqPatch) + { + netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + } + else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + == adqmPhysicalAreaOutsideAdqPatch) + { + flowsNode1toNodeA + += Math::Max(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); + } + Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + } + return std::make_pair(netPositionInit, flowsNode1toNodeA); } \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 744c8a1877..e48bbcbc40 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -104,6 +104,12 @@ void setBoundsNoAdqPatch(double& Xmax, VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, const int Interco); +/*! + * Calculates sum of import and export flows per given area per given hour. + */ +std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, + int Area, + int hour); /*! * Calculate parameters for curtailment sharing rule inside adequacy patch. */ diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 33dd61d5a3..7704cbf19e 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -258,7 +258,7 @@ bool Economy::year(Progression::Task& progression, UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); } - checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace]); + //checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace]); } else { From 8ee3835abb7724741f59b1d4cb0193e2003c3d10 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 6 May 2022 12:00:16 +0200 Subject: [PATCH 134/490] create new output column for lmr violations --- src/solver/cmake/variable.cmake | 1 + src/solver/simulation/economy.cpp | 2 +- src/solver/variable/economy/all.h | 8 +- src/solver/variable/economy/lmrViolations.h | 283 ++++++++++++++++++++ 4 files changed, 291 insertions(+), 3 deletions(-) create mode 100644 src/solver/variable/economy/lmrViolations.h diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 84197f5502..2ff2c6e039 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -130,6 +130,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/hydroCost.h variable/economy/unsupliedEnergy.h variable/economy/domesticUnsuppliedEnergy.h + variable/economy/lmrViolations.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 7704cbf19e..33dd61d5a3 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -258,7 +258,7 @@ bool Economy::year(Progression::Task& progression, UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); } - //checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace]); + checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace]); } else { diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index e3fc2fc401..4598b87479 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -60,6 +60,7 @@ #include "hydroCost.h" #include "unsupliedEnergy.h" #include "domesticUnsuppliedEnergy.h" +#include "lmrViolations.h" #include "spilledEnergy.h" #include "lold.h" @@ -146,6 +147,7 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -217,6 +219,8 @@ typedef // Prices UnsupliedEnergy, Common::SpatialAggregate< DomesticUnsuppliedEnergy, + Common::SpatialAggregate< + LMRViolations, Common::SpatialAggregate< SpilledEnergy, // LOLD @@ -241,7 +245,7 @@ typedef // Prices Common::SpatialAggregate< NbOfDispatchedUnits // MBO 25/02/2016 // - refs: #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< diff --git a/src/solver/variable/economy/lmrViolations.h b/src/solver/variable/economy/lmrViolations.h new file mode 100644 index 0000000000..95b34647b3 --- /dev/null +++ b/src/solver/variable/economy/lmrViolations.h @@ -0,0 +1,283 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardLMRViolations +{ + //! Caption + static const char* Caption() + { + return "LMR VIOL."; + } + //! Unit + static const char* Unit() + { + return " "; + } + + //! The short description of the variable + static const char* 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), + }; + }; + +public: + ~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 DomesticUnsuppliedEnergy emissions + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesLmrViolations[state.hourInTheWeek]; + + // 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(); + pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( + results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class LMRViolations + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ From 94e206d41e0dafa78b60cf238a523208df7246b4 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 6 May 2022 15:28:43 +0200 Subject: [PATCH 135/490] add totalLmrViolation --- src/solver/optimisation/adequacy_patch.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 27b1972915..5edfcfd348 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -189,7 +189,6 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) { - // todo. To much code is duplicated. Create sub function and reuse them. or try something else! float threshold = ProblemeHebdo->adqPatch->ThresholdDisplayLocalMatchingRuleViolations; double netPositionInit; double flowsNode1toNodeA; @@ -197,8 +196,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) double ensInit; const int numOfHoursInWeek = 168; double spillageInit; - //std::vector lmrTmpVector; - //std::map> localMatchingRuleViolation; // todo remove, for debugg + double totalLmrViolation = 0; bool includeFlowsOutsideAdqPatchToDensNew = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; @@ -207,7 +205,6 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == adqmPhysicalAreaInsideAdqPatch) { - //lmrTmpVector.clear(); for (int hour = 0; hour < numOfHoursInWeek; hour++) { std::tie(netPositionInit, flowsNode1toNodeA) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); @@ -221,19 +218,19 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) // check LMR violations ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; - // lmrTmpVector.push_back(0); if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) + { ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; - //lmrTmpVector.at(hour) = 1; + totalLmrViolation += (ensInit - densNew); + } logs.debug() << "LMR violations. Area:" << Area << ". hour:" << hour << ". Value:" << ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour]; } - // localMatchingRuleViolation[Area] = lmrTmpVector; // todo remove, for debugg - //ProblemeHebdo->localMatchingRuleViolation[Area] = lmrTmpVector; } } + logs.debug() << "Total LMR violation:" << totalLmrViolation; return; } From e202abb045e9513b6fc7ac2ce720d3db4a434902 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 6 May 2022 15:55:11 +0200 Subject: [PATCH 136/490] refacto --- src/solver/optimisation/adequacy_patch.cpp | 43 ++++++++++------------ src/solver/optimisation/adequacy_patch.h | 4 +- 2 files changed, 21 insertions(+), 26 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 5edfcfd348..a8ee914853 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -150,29 +150,22 @@ void setBoundsNoAdqPatch(double& Xmax, void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { double netPositionInit; - double flowsNode1toNodeA; double densNew; double ensInit; double spillageInit; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - bool includeFlowsOutsideAdqPatchToDensNew - = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; - + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == adqmPhysicalAreaInsideAdqPatch) { - std::tie(netPositionInit, flowsNode1toNodeA) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); - // calculate densNew per area + std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; spillageInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; - if (includeFlowsOutsideAdqPatchToDensNew) - densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); - else - densNew = Math::Max(0.0, ensInit + netPositionInit); hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; hourlyCsrProblem.densNewValues[Area] = densNew; @@ -181,7 +174,6 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h logs.debug() << "DENS_new[" << Area <<"] = " << hourlyCsrProblem.densNewValues[Area] ; logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit << ") - SpillageInit(" << spillageInit <<")"; - logs.debug() << "flowsNode1toNodeA[" << Area <<"] = " << flowsNode1toNodeA ; } } return; @@ -191,15 +183,11 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) { float threshold = ProblemeHebdo->adqPatch->ThresholdDisplayLocalMatchingRuleViolations; double netPositionInit; - double flowsNode1toNodeA; double densNew; double ensInit; const int numOfHoursInWeek = 168; - double spillageInit; double totalLmrViolation = 0; - bool includeFlowsOutsideAdqPatchToDensNew - = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; - + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] @@ -207,15 +195,11 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) { for (int hour = 0; hour < numOfHoursInWeek; hour++) { - std::tie(netPositionInit, flowsNode1toNodeA) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + ensInit = ProblemeHebdo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillancePositive[hour]; - if (includeFlowsOutsideAdqPatchToDensNew) - densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); - else - densNew = Math::Max(0.0, ensInit + netPositionInit); - // check LMR violations ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) @@ -238,9 +222,13 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo int Area, int hour) { + int Interco; double netPositionInit = 0; double flowsNode1toNodeA = 0; - int Interco; + double ensInit; + double densNew; + bool includeFlowsOutsideAdqPatchToDensNew + = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; while (Interco >= 0) @@ -274,5 +262,12 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo } Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; } - return std::make_pair(netPositionInit, flowsNode1toNodeA); + + ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; + if (includeFlowsOutsideAdqPatchToDensNew) + densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); + else + densNew = Math::Max(0.0, ensInit + netPositionInit); + + return std::make_pair(netPositionInit, densNew); } \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index e48bbcbc40..061ebd7187 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -105,13 +105,13 @@ void setBoundsNoAdqPatch(double& Xmax, const int Interco); /*! - * Calculates sum of import and export flows per given area per given hour. + * Calculates curtailment sharing rule parameters netPositionInit and densNew per given area and hour. */ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, int Area, int hour); /*! - * Calculate parameters for curtailment sharing rule inside adequacy patch. + * Calculate parameters for curtailment sharing rule. */ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem); /*! From 03707011f0d23c7aa69437f9e2221458902553e0 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 6 May 2022 19:19:01 +0200 Subject: [PATCH 137/490] better logging for total lmr violations --- src/solver/optimisation/adequacy_patch.cpp | 10 +++++----- src/solver/optimisation/adequacy_patch.h | 2 +- src/solver/simulation/economy.cpp | 2 +- 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index a8ee914853..f96776bbc7 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -179,7 +179,7 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h return; } -void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) +void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) { float threshold = ProblemeHebdo->adqPatch->ThresholdDisplayLocalMatchingRuleViolations; double netPositionInit; @@ -208,13 +208,13 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) totalLmrViolation += (ensInit - densNew); } - logs.debug() - << "LMR violations. Area:" << Area << ". hour:" << hour << ". Value:" - << ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour]; + // logs.debug() + // << "LMR violations. Area:" << Area << ". hour:" << hour << ". Value:" + // << ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour]; } } } - logs.debug() << "Total LMR violation:" << totalLmrViolation; + logs.debug() << "Week:" << weekNb + 1 << ". Total LMR violation:" << totalLmrViolation; return; } diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 061ebd7187..4574a459c4 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -117,6 +117,6 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h /*! * Check local matching rule violation for each area inside adequacy patch. */ -void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo); +void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); #endif /* __SOLVER_ADEQUACY_FUNCTIONS_H__ */ diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 33dd61d5a3..b29f34de32 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -258,7 +258,7 @@ bool Economy::year(Progression::Task& progression, UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); } - checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace]); + checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); } else { From 330fd12de784ffb670df34006d8eb66771d04737 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 9 May 2022 11:48:03 +0200 Subject: [PATCH 138/490] clean & clang --- src/solver/optimisation/adequacy_patch.cpp | 26 +++++------ ...atrice_des_contraintes_cas_quadratique.cpp | 13 +++--- ...ction_variables_optimisees_quadratique.cpp | 2 +- ...opt_gestion_des_bornes_cas_quadratique.cpp | 13 ------ ..._gestion_second_membre_cas_quadratique.cpp | 38 ++++++---------- src/solver/simulation/economy.cpp | 45 ++++++++----------- 6 files changed, 52 insertions(+), 85 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index f96776bbc7..bff7c4ad2b 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -154,13 +154,14 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h double ensInit; double spillageInit; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == adqmPhysicalAreaInsideAdqPatch) { - std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; @@ -171,9 +172,11 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h hourlyCsrProblem.densNewValues[Area] = densNew; hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; - logs.debug() << "DENS_new[" << Area <<"] = " << hourlyCsrProblem.densNewValues[Area] ; - logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] - << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit << ") - SpillageInit(" << spillageInit <<")"; + logs.debug() << "DENS_new[" << Area << "] = " << hourlyCsrProblem.densNewValues[Area]; + logs.debug() << "rhsAreaBalanceValues[" << Area + << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] << " = ENSinit(" + << ensInit << ") + NetPositionInit(" << netPositionInit + << ") - SpillageInit(" << spillageInit << ")"; } } return; @@ -187,7 +190,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb double ensInit; const int numOfHoursInWeek = 168; double totalLmrViolation = 0; - + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] @@ -195,11 +198,12 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb { for (int hour = 0; hour < numOfHoursInWeek; hour++) { - std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); ensInit = ProblemeHebdo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillancePositive[hour]; - + // check LMR violations ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) @@ -207,10 +211,6 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; totalLmrViolation += (ensInit - densNew); } - - // logs.debug() - // << "LMR violations. Area:" << Area << ". hour:" << hour << ". Value:" - // << ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour]; } } } @@ -262,7 +262,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo } Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; } - + ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; if (includeFlowsOutsideAdqPatchToDensNew) densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); 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 index 8fd71781e9..65469dd922 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -105,6 +105,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( int NombreDeTermes; double* Pi; int* Colonne; + int Interco; + COUTS_DE_TRANSPORT* TransportCost; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; std::string NomDeLaContrainte; @@ -117,9 +119,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int Interco; - COUTS_DE_TRANSPORT* TransportCost; - // constraint: ENS < DENS_new for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { @@ -285,7 +284,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( } int NbInterco; - double Poids; // Weight + double Poids; CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; // Special case of the binding constraints for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; @@ -335,10 +334,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( hourlyCsrProblem.numberOfConstraintCsrHourlyBinding[CntCouplante] = ProblemeAResoudre->NombreDeContraintes; - NomDeLaContrainte - = "bc::hourly::" + std::to_string(hour) + "::" - + MatriceDesContraintesCouplantes - ->NomDeLaContrainteCouplante; // + ". Interco:" + std::to_string(Interco); + NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) + "::" + + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte; diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 4f5b7a0e86..229905d69c 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -63,10 +63,10 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( HOURLY_CSR_PROBLEM& hourlyCsrProblem) { logs.debug() << "[CSR] variable list:"; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; int NumberOfVariables = 0; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; assert(ProblemeAResoudre != NULL); 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 6aca10ebc0..91d92e6940 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -253,19 +253,6 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( << ProblemeAResoudre->Xmax[Var]; } } - // todo: remove //CSR Todo? - // 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. - // 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 - // if (FLOW.LIN –LOOP FLOW) > 0 - // HURD. COST = (hourly direct hurdle cost) * (FLOW LIN.) - // else HURD.COST = (hourly indirect hurdle cost) * (-1) * (FLOW LIN.) return; } \ No newline at end of file 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 d4fab65aef..4fb8a37b13 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -52,15 +52,12 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob HOURLY_CSR_PROBLEM& hourlyCsrProblem) { logs.debug() << "[CSR] RHS: "; - // CSR todo initialize RHS right hand side of constraints for hourly CSR quadratic problem. int Cnt; int Area; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; COUTS_DE_TRANSPORT* TransportCost; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; // constraint for each area inside adq patch: ENS < DENS_new for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) @@ -126,20 +123,20 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob } } - // CSR todo. Add, only hourly, user defined Binding constraints between transmission flows + // constraint: + // user defined Binding constraints between transmission flows // and/or power generated from generating units. int CntCouplante; int Interco; - CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; - double* SecondMembre = ProblemeAResoudre->SecondMembre; - std::map bingdingConstraintNumber - = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; - int NbInterco; double Poids; double ValueOfFlow; int Index; + double* SecondMembre = ProblemeAResoudre->SecondMembre; + CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; + std::map bingdingConstraintNumber + = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) @@ -151,14 +148,14 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob Cnt = bingdingConstraintNumber[CntCouplante]; - // 1. this is the original RHS of bingding constraint + // 1. The original RHS of bingding constraint SecondMembre[Cnt] = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")"; - // 2. CSR todo: RHS part 2: flow other than 2<->2 + // 2. RHS part 2: flow other than 2<->2 NbInterco = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; for (Index = 0; Index < NbInterco; Index++) @@ -171,12 +168,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { - // we have an interco other than type 2-2 - // Var = - // ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]->NumeroDeVariableDeLInterconnexion[Interco]; - ValueOfFlow - = ProblemeHebdo->ValeursDeNTC[hour] - ->ValeurDuFlux[Interco]; // todo check do we care about the export/import + ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; SecondMembre[Cnt] -= ValueOfFlow * Poids; logs.debug() << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt @@ -192,14 +184,14 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob } } - // 3. CSR todo: RHS part 3: - cluster + // 3. RHS part 3: - cluster int NbClusters = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; int Area; - PALIERS_THERMIQUES* PaliersThermiquesDuPays; int Palier; int IndexNumeroDuPalierDispatch; double ValueOfVar; + PALIERS_THERMIQUES* PaliersThermiquesDuPays; for (Index = 0; Index < NbClusters; Index++) { @@ -213,8 +205,6 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob [IndexNumeroDuPalierDispatch]; Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; - // Var = - // ProblemeHebdo->CorrespondanceVarNativesVarOptim[Pdt1]->NumeroDeVariableDuPalierThermique[Palier]; ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] ->ProductionThermique[hour] ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index b29f34de32..2c1092c125 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -146,13 +146,7 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, std::set& triggerCsrSet) { float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; - threshold = 500; //todo remove. for debug - - double sumENS[nbHoursInAWeek] = {0}; // this shold be better as init?, i debugged it. Works fine! - - // // init sumENS[]. - // for (int j = 0; j < nbHoursInAWeek; ++j) - // sumENS[j] = 0.0; + double sumENS[nbHoursInAWeek] = {0}; for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) { @@ -167,7 +161,8 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, { if ((int)sumENS[i] >= threshold) { - logs.debug() << "hour: [" << i << "], sumENS = [" << (int)sumENS[i] << "], threshold = " << threshold; + logs.debug() << "hour: [" << i << "], sumENS = [" << (int)sumENS[i] + << "], threshold = " << threshold; triggerCsrSet.insert(i); } } @@ -190,17 +185,17 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP return; } -void UpdateWeeklyResultAfterCSR(PROBLEME_HEBDO* pProblemeHebdo) -{ - std::vector hourlyCsrProblems = pProblemeHebdo->hourlyCsrProblems; +// void UpdateWeeklyResultAfterCSR(PROBLEME_HEBDO* pProblemeHebdo) +// { +// std::vector hourlyCsrProblems = pProblemeHebdo->hourlyCsrProblems; - for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) - { - RESULTATS_HORAIRES* ResultatsHoraires = pProblemeHebdo->ResultatsHoraires[area]; - //CSR todo update ResultatsHoraires for each area using hourlyCsrProblems - } - return; -} +// for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) +// { +// RESULTATS_HORAIRES* ResultatsHoraires = pProblemeHebdo->ResultatsHoraires[area]; +// //CSR todo update ResultatsHoraires for each area using hourlyCsrProblems +// } +// return; +// } bool Economy::year(Progression::Task& progression, Variable::State& state, @@ -240,22 +235,22 @@ bool Economy::year(Progression::Task& progression, { OPT_OptimisationHebdomadaireAdqPatch( pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); - + std::set hoursInWeekTriggerCsrSet; - InitiateCurtailmentSharingRuleIndexSet(pProblemesHebdo[numSpace], hoursInWeekTriggerCsrSet); - if( hoursInWeekTriggerCsrSet.size() > 0) + InitiateCurtailmentSharingRuleIndexSet(pProblemesHebdo[numSpace], + hoursInWeekTriggerCsrSet); + if (hoursInWeekTriggerCsrSet.size() > 0) { pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); - for(int hourInWeek : hoursInWeekTriggerCsrSet) + for (int hourInWeek : hoursInWeekTriggerCsrSet) { logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->hourlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; - } - UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); + // UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); } checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); @@ -280,8 +275,6 @@ bool Economy::year(Progression::Task& progression, updatingWeeklyFinalHydroLevel(study, *pProblemesHebdo[numSpace], nbHoursInAWeek); - //CSR todo: shall we start here, or shall we start the CSR directly after OPT_OptimisationHebdomadaireAdqPatch - variables.weekBegin(state); uint previousHourInTheYear = state.hourInTheYear; From a5f93ea10896cb6268a487a4e31d9743eed1e5c0 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 9 May 2022 11:55:24 +0200 Subject: [PATCH 139/490] update todo-s --- ...t_construction_matrice_des_contraintes_cas_quadratique.cpp | 2 ++ .../opt_construction_variables_optimisees_quadratique.cpp | 4 ++-- .../optimisation/opt_gestion_des_bornes_cas_quadratique.cpp | 4 ++-- .../opt_gestion_second_membre_cas_quadratique.cpp | 2 ++ 4 files changed, 8 insertions(+), 4 deletions(-) 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 index 65469dd922..220afb3059 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -196,6 +196,8 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( // - spillage(node A) = // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch + + // todo after debugging transfer this into same area loop as ENS for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 229905d69c..9877399bdc 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -90,8 +90,8 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( } } - // variables: Spilled Energy of each area inside adq patch // todo after debugging transfer - // this into same loop as ENS + // variables: Spilled Energy of each area inside adq patch + // todo after debugging transfer this into same area loop as ENS logs.debug() << " Spilled Energy of each area inside adq patch: "; for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { 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 91d92e6940..586cccfcfd 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -139,8 +139,8 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( } } - // variables: Spilled Energy for each area inside adq patch // todo after debugging transfer - // this into same loop as ENS + // variables: Spilled Energy for each area inside adq patch + // todo after debugging transfer this into same area loop as ENS for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] 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 4fb8a37b13..a438ac87ef 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -106,6 +106,8 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // – Sum flow_indirect(node 2 upstream <- node A) – Sum flow_direct(node A -> node 2 downstream) // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch + + // todo after debugging transfer this into same area loop as ENS for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] From 47d867785e46074f841a004f42aa944997e0cb58 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 9 May 2022 12:06:34 +0200 Subject: [PATCH 140/490] Florian's comment --- src/libs/antares/study/area/list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 1d4228bf28..e1fc4f2b62 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1070,7 +1070,7 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, } // Adequacy patch - if (study.header.version >= 820) + if (study.header.version >= 820 && study.parameters.include.adequacyPatch) { buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; From b9970fb6471ee43531964ed24f499fabfb47b6f7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 9 May 2022 13:23:25 +0200 Subject: [PATCH 141/490] connect merged branches --- src/libs/antares/study/fwd.h | 4 +-- .../opt_gestion_des_couts_cas_quadratique.cpp | 27 +++++++++---------- .../simulation/sim_calcul_economique.cpp | 8 +++--- .../sim_structure_probleme_economique.h | 2 +- 4 files changed, 20 insertions(+), 21 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 2ccb7c8d14..b30307e880 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -616,9 +616,9 @@ enum AdqPatchThresholdsIndex }; //! A default threshold value for initiate curtailment sharing rule -const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 0.5; +const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 500.0; //! A default threshold value for display local matching rule violations -const float adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations = 0.5; +const float adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations = 500.0; } // namespace AdequacyPatch } // namespace Data 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 d514d879be..e791a69a41 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -91,20 +91,19 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - // CSR Todo options - // if (ProblemeHebdo->adqPatch->PriceTakingOrder == - // Data::AdequacyPatch::adqPatchPTOIsLoad) - // { - // priceTakingOrders - // = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] - // + - // ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; - // } - // else - // { - priceTakingOrders - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; - // } + if (ProblemeHebdo->adqPatch->PriceTakingOrder + == Data::AdequacyPatch::adqPatchPTOIsLoad) + { + priceTakingOrders + = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] + + ProblemeHebdo->AllMustRunGeneration[hour] + ->AllMustRunGenerationOfArea[area]; + } + else + { + priceTakingOrders + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; + } if (priceTakingOrders <= 0.0) { diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index c98ff5040c..e0d733cbc7 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -72,12 +72,12 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq = parameters.setToZero11LinksForAdequacyPatch; problem.adqPatch->SaveIntermediateResults - = true; // = parameters.adqPatchSaveIntermediateResults; - // problem.adqPatch->PriceTakingOrder = parameters.adqPatchPriceTakingOrder; + = parameters.adqPatchSaveIntermediateResults; + problem.adqPatch->PriceTakingOrder = parameters.adqPatchPriceTakingOrder; problem.adqPatch->ThresholdInitiateCurtailmentSharingRule - = 300; // = parameters.seedAdqPatch[adqPatchThresholdInitiateCurtailmentSharingRule]; + = parameters.seedAdqPatch[adqPatchThresholdInitiateCurtailmentSharingRule]; problem.adqPatch->ThresholdDisplayLocalMatchingRuleViolations - = 1; // = parameters.seedAdqPatch[adqPatchThresholdDisplayLocalMatchingRuleViolations]; + = parameters.seedAdqPatch[adqPatchThresholdDisplayLocalMatchingRuleViolations]; } if (parameters.include.adequacyPatch){ diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 49421dce9c..47d069b7cd 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -503,7 +503,7 @@ struct AdequacyPatchParameters bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; bool SaveIntermediateResults; - // AdequacyPatch::AdequacyPatchPTO PriceTakingOrder; + AdequacyPatchPTO PriceTakingOrder; float ThresholdInitiateCurtailmentSharingRule; float ThresholdDisplayLocalMatchingRuleViolations; }; From 2abed35b24abadb579f94f48c0122322810aba15 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 9 May 2022 17:00:16 +0200 Subject: [PATCH 142/490] change 12-11 parameter names --- src/libs/antares/study/parameters.cpp | 12 +++++----- src/libs/antares/study/parameters.h | 4 ++-- src/solver/optimisation/adequacy_patch.cpp | 22 +++++++++---------- src/solver/optimisation/adequacy_patch.h | 20 ++++++++--------- .../simulation/sim_calcul_economique.cpp | 4 ++-- .../options/optimization/optimization.cpp | 12 +++++----- 6 files changed, 37 insertions(+), 37 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index c108bd1ee9..ba88afc1a7 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -306,8 +306,8 @@ void Parameters::reset() include.exportMPS = false; include.adequacyPatch = false; - setToZero12LinksForAdequacyPatch = true; - setToZero11LinksForAdequacyPatch = true; + setToZeroNTCfromOutToIn_AdqPatch = true; + setToZeroNTCfromOutToOut_AdqPatch = true; include.exportStructure = false; include.unfeasibleProblemBehavior = UnfeasibleProblemBehavior::ERROR_MPS; @@ -558,9 +558,9 @@ static bool SGDIntLoadFamily_Optimization(Parameters& d, if (key == "include-adequacypatch") return value.to(d.include.adequacyPatch); if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch") - return value.to(d.setToZero12LinksForAdequacyPatch); + return value.to(d.setToZeroNTCfromOutToIn_AdqPatch); if (key == "set-to-null-ntc-between-physical-out-for-first-step-adq-patch") - return value.to(d.setToZero11LinksForAdequacyPatch); + return value.to(d.setToZeroNTCfromOutToOut_AdqPatch); if (key == "include-exportstructure") return value.to(d.include.exportStructure); if (key == "include-unfeasible-problem-behavior") @@ -1720,9 +1720,9 @@ void Parameters::saveToINI(IniFile& ini) const section->add("include-exportmps", include.exportMPS); section->add("include-adequacypatch", include.adequacyPatch); section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch", - setToZero12LinksForAdequacyPatch); + setToZeroNTCfromOutToIn_AdqPatch); section->add("set-to-null-ntc-between-physical-out-for-first-step-adq-patch", - setToZero11LinksForAdequacyPatch); + setToZeroNTCfromOutToOut_AdqPatch); section->add("include-exportstructure", include.exportStructure); // Unfeasible problem behavior diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 86e72cc814..2007ffd4bf 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -508,10 +508,10 @@ class Parameters final //! 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. - bool setToZero12LinksForAdequacyPatch; + bool setToZeroNTCfromOutToIn_AdqPatch; //! 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. - bool setToZero11LinksForAdequacyPatch; + bool setToZeroNTCfromOutToOut_AdqPatch; //! \name Scenariio Builder - Rules //@{ diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 8aa7914c07..08212f18ff 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -33,8 +33,8 @@ using namespace Antares::Data::AdequacyPatch; LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch) + bool setToZeroNTCfromOutToIn_AdqPatch, + bool setToZeroNTCfromOutToOut_AdqPatch) { LinkCapacityForAdequacyPatchFirstStep returnNTC; @@ -42,13 +42,13 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( { case adqmPhysicalAreaInsideAdqPatch: returnNTC = SetNTCForAdequacyFirstStepOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, - SetToZero12LinksForAdequacyPatch); + setToZeroNTCfromOutToIn_AdqPatch); break; case adqmPhysicalAreaOutsideAdqPatch: returnNTC = SetNTCForAdequacyFirstStepOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, - SetToZero12LinksForAdequacyPatch, - SetToZero11LinksForAdequacyPatch); + setToZeroNTCfromOutToIn_AdqPatch, + setToZeroNTCfromOutToOut_AdqPatch); break; default: returnNTC = leaveLocalValues; @@ -59,7 +59,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch) + bool setToZeroNTCfromOutToIn_AdqPatch) { LinkCapacityForAdequacyPatchFirstStep returnNTC; @@ -69,7 +69,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside returnNTC = setToZero; break; case adqmPhysicalAreaOutsideAdqPatch: - returnNTC = (SetToZero12LinksForAdequacyPatch) ? setToZero : setOrigineExtremityToZero; + returnNTC = (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setOrigineExtremityToZero; break; default: returnNTC = leaveLocalValues; @@ -80,18 +80,18 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch) + bool setToZeroNTCfromOutToIn_AdqPatch, + bool setToZeroNTCfromOutToOut_AdqPatch) { LinkCapacityForAdequacyPatchFirstStep returnNTC; switch (ExtremityNodeAdequacyPatchType) { case adqmPhysicalAreaInsideAdqPatch: - returnNTC = (SetToZero12LinksForAdequacyPatch) ? setToZero : setExtremityOrigineToZero; + returnNTC = (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setExtremityOrigineToZero; break; case adqmPhysicalAreaOutsideAdqPatch: - returnNTC = (SetToZero11LinksForAdequacyPatch) ? setToZero : leaveLocalValues; + returnNTC = (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; break; default: returnNTC = leaveLocalValues; diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 6df2ab802a..a626c6dd6e 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -37,10 +37,10 @@ using namespace Antares::Data; * * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * @param setToZeroNTCfromOutToIn_AdqPatch bool: Switch to cut links from nodes outside adq patch * (type 1) towards nodes inside adq patch (type 2). * - * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * @param setToZeroNTCfromOutToOut_AdqPatch bool: Switch to cut links between nodes outside adq patch * (type 1). * * @return uint from an enumeration that describes the type of restrictions to put on this link for @@ -49,8 +49,8 @@ using namespace Antares::Data; LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( AdequacyPatchMode OriginNodeAdequacyPatchType, AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch); + bool setToZeroNTCfromOutToIn_AdqPatch, + bool setToZeroNTCfromOutToOut_AdqPatch); /*! * Determines restriction type for transmission links for first step of adequacy patch, when start @@ -58,7 +58,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( * * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * @param setToZeroNTCfromOutToIn_AdqPatch bool: Switch to cut links from nodes outside adq patch * (type 1) towards nodes inside adq patch (type 2). * * @return uint from an enumeration that describes the type of restrictions to put on this link for @@ -66,7 +66,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( */ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch); + bool setToZeroNTCfromOutToIn_AdqPatch); /*! * Determines restriction type for transmission links for first step of adequacy patch, when start @@ -74,10 +74,10 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside * * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. * - * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * @param setToZeroNTCfromOutToIn_AdqPatch bool: Switch to cut links from nodes outside adq patch * (type 1) towards nodes inside adq patch (type 2). * - * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * @param setToZeroNTCfromOutToOut_AdqPatch bool: Switch to cut links between nodes outside adq patch * (type 1). * * @return uint from an enumeration that describes the type of restrictions to put on this link for @@ -85,8 +85,8 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside */ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool SetToZero12LinksForAdequacyPatch, - bool SetToZero11LinksForAdequacyPatch); + bool setToZeroNTCfromOutToIn_AdqPatch, + bool setToZeroNTCfromOutToOut_AdqPatch); /*! * Sets link bounds for first step of adequacy patch. diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index c8c8d87411..70d321f071 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -69,9 +69,9 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, // AdequacyFirstStep will be initialized during the economy solve // AdqBehaviorMap will be initialized during the economy solve problem.adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq - = parameters.setToZero12LinksForAdequacyPatch; + = parameters.setToZeroNTCfromOutToIn_AdqPatch; problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq - = parameters.setToZero11LinksForAdequacyPatch; + = parameters.setToZeroNTCfromOutToOut_AdqPatch; } if (parameters.include.adequacyPatch){ diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index 41aef96e64..63ec695886 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -398,7 +398,7 @@ Optimization::Optimization(wxWindow* parent) : button->menu(true); onPopup.bind(this, &Optimization::onPopupMenuAdequacyPatch, - PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); + PopupInfo(study.parameters.setToZeroNTCfromOutToIn_AdqPatch, wxT("NTC"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); @@ -413,7 +413,7 @@ Optimization::Optimization(wxWindow* parent) : button->menu(true); onPopup.bind(this, &Optimization::onPopupMenuAdequacyPatch, - PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); + PopupInfo(study.parameters.setToZeroNTCfromOutToOut_AdqPatch, wxT("NTC"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); @@ -503,8 +503,8 @@ void Optimization::onResetToDefault(void*) study.parameters.include.reserve.spinning = true; study.parameters.include.exportMPS = false; study.parameters.include.adequacyPatch = false; - study.parameters.setToZero12LinksForAdequacyPatch = true; - study.parameters.setToZero11LinksForAdequacyPatch = true; + study.parameters.setToZeroNTCfromOutToIn_AdqPatch = true; + study.parameters.setToZeroNTCfromOutToOut_AdqPatch = true; study.parameters.simplexOptimizationRange = Data::sorWeek; study.parameters.include.unfeasibleProblemBehavior @@ -557,11 +557,11 @@ void Optimization::refresh() // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, - study.parameters.setToZero12LinksForAdequacyPatch); + study.parameters.setToZeroNTCfromOutToIn_AdqPatch); // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of // adequacy patch local matching rule. ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, - study.parameters.setToZero11LinksForAdequacyPatch); + study.parameters.setToZeroNTCfromOutToOut_AdqPatch); // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( From 0fbca48b4b56f134d2dca81ebc47fe3d76be2d4f Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 9 May 2022 17:39:45 +0200 Subject: [PATCH 143/490] setNTCbounds function --- src/solver/optimisation/adequacy_patch.cpp | 74 +++++++++---------- src/solver/optimisation/adequacy_patch.h | 20 ++--- .../opt_gestion_des_bornes_cas_lineaire.cpp | 5 +- 3 files changed, 45 insertions(+), 54 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 08212f18ff..7d171f311c 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -100,47 +100,47 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsid return returnNTC; } -void setBoundsAdqPatch(double& Xmax, - double& Xmin, - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, - const int Interco, - PROBLEME_HEBDO* ProblemeHebdo) +void setNTCbounds(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo) { LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; - SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( - ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], - ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); + // set as default values + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setToZero) - { - Xmax = 0.; - Xmin = 0.; - } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setOrigineExtremityToZero) - { - Xmax = 0.; - Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - } - else if (SetToZeroLinkNTCForAdequacyPatchFirstStep == setExtremityOrigineToZero) - { - Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin = 0.; - } - else + // set for adq patch first step + if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) { - Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - } -} + SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( + ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, + ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); -void setBoundsNoAdqPatch(double& Xmax, - double& Xmin, - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, - const int Interco) -{ - Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + switch (SetToZeroLinkNTCForAdequacyPatchFirstStep) + { + case setToZero: + { + Xmax = 0.; + Xmin = 0.; + break; + } + case setOrigineExtremityToZero: + { + Xmax = 0.; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + break; + } + case setExtremityOrigineToZero: + { + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = 0.; + break; + } + } + } } diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index a626c6dd6e..a30d43584d 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -89,19 +89,13 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsid bool setToZeroNTCfromOutToOut_AdqPatch); /*! - * Sets link bounds for first step of adequacy patch. + * Sets link bounds for first step of adequacy patch or leaves default values if adequacy patch is + * not used. */ -void setBoundsAdqPatch(double& Xmax, - double& Xmin, - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, - const int Interco, - PROBLEME_HEBDO* ProblemeHebdo); -/*! - * Sets link bounds when adequacy patch is not used or when first step of adequacy patch is false. - */ -void setBoundsNoAdqPatch(double& Xmax, - double& Xmin, - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, - const int Interco); +void setNTCbounds(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo); #endif /* __SOLVER_ADEQUACY_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 608b4efef6..80b292ad21 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -178,10 +178,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) - setBoundsAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); - else - setBoundsNoAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco); + setNTCbounds(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); if (Math::Infinite(Xmax[Var]) == 1) { From 890532f7c89f70801f5113682f936feee0de4963 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 11:11:59 +0200 Subject: [PATCH 144/490] OnStudyAreaUseAdequacyPatchChanged remove --- src/ui/simulator/application/study.cpp | 1 - src/ui/simulator/application/study.h | 5 ----- src/ui/simulator/windows/inspector/property.update.cpp | 1 - 3 files changed, 7 deletions(-) diff --git a/src/ui/simulator/application/study.cpp b/src/ui/simulator/application/study.cpp index 9178f3f679..0f014ecc79 100644 --- a/src/ui/simulator/application/study.cpp +++ b/src/ui/simulator/application/study.cpp @@ -90,7 +90,6 @@ Event OnStudyLinkDelete; Event OnStudySimulationSettingsChanged; Event OnStudyNodalOptimizationChanged; -Event OnStudyAreaUseAdequacyPatchChanged; Event OnStudyThermalClusterCommonSettingsChanged; Event OnStudyThermalClusterRenamed; diff --git a/src/ui/simulator/application/study.h b/src/ui/simulator/application/study.h index a29998c511..79f0d6f278 100644 --- a/src/ui/simulator/application/study.h +++ b/src/ui/simulator/application/study.h @@ -266,11 +266,6 @@ extern Yuni::Event OnStudyConstraintModified; */ extern Yuni::Event OnStudyNodalOptimizationChanged; -/*! -** \brief Event: The area use adequacy patch settings have been changed -*/ -extern Yuni::Event OnStudyAreaUseAdequacyPatchChanged; - /*! ** \brief Event: The simulation settings have been changed */ diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index 601770d195..cfda65a463 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -192,7 +192,6 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; } } - OnStudyAreaUseAdequacyPatchChanged(); return true; } if (name == "area.links_count") From 57454f9ebb93d2d73b1489235cdb1a8e9ac80718 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 11:23:03 +0200 Subject: [PATCH 145/490] refacto struct PAdequacyPatchMode --- src/ui/simulator/windows/inspector/accumulator.hxx | 11 +---------- 1 file changed, 1 insertion(+), 10 deletions(-) diff --git a/src/ui/simulator/windows/inspector/accumulator.hxx b/src/ui/simulator/windows/inspector/accumulator.hxx index 0fc3bdd5eb..db8ec1ff48 100644 --- a/src/ui/simulator/windows/inspector/accumulator.hxx +++ b/src/ui/simulator/windows/inspector/accumulator.hxx @@ -918,16 +918,7 @@ struct PAdequacyPatchMode } static wxString ConvertToString(const Type v) { - switch (v) - { - case Data::AdequacyPatch::adqmVirtualArea: - return wxT("virtual area"); - case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: - return wxT("physical area outside patch"); - case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: - return wxT("physical area inside patch"); - } - return wxEmptyString; + return adequacyPatchMode[v]; } }; From 0800a8c9e9b71f1120f0a6e72269c00ddd5a75b9 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 11:34:16 +0200 Subject: [PATCH 146/490] refacto property update --- .../windows/inspector/property.update.cpp | 14 +++++++++++--- 1 file changed, 11 insertions(+), 3 deletions(-) diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index cfda65a463..c8143b2e1f 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -184,12 +184,20 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, s.toLower(); s.trim(); - if (s == "virtual area" || s == "0") + switch (s.to()) + { + case 0: area->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; - else if (s == "physical area outside patch" || s == "1") + break; + case 1: area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; - else if (s == "physical area inside patch" || s == "2") + break; + case 2: area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + break; + default: + break; + } } } return true; From c429f66e7fca182ea9770e7723c551de05176584 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 11:42:00 +0200 Subject: [PATCH 147/490] pBtnAdequacyPatchNTC12-11 name change --- .../windows/options/optimization/optimization.cpp | 8 ++++---- .../simulator/windows/options/optimization/optimization.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index 63ec695886..fb9bdbc523 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -402,7 +402,7 @@ Optimization::Optimization(wxWindow* parent) : button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchNTC12 = button; + pBtnNTCfromOutToInAdqPatch = button; } // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). // Used in the first step of adequacy patch local matching rule. @@ -417,7 +417,7 @@ Optimization::Optimization(wxWindow* parent) : button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchNTC11 = button; + pBtnNTCfromOutToOutAdqPatch = button; } { @@ -556,11 +556,11 @@ void Optimization::refresh() ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC12, + ResetButtonAdequacyPatch(pBtnNTCfromOutToInAdqPatch, study.parameters.setToZeroNTCfromOutToIn_AdqPatch); // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of // adequacy patch local matching rule. - ResetButtonAdequacyPatch(pBtnAdequacyPatchNTC11, + ResetButtonAdequacyPatch(pBtnNTCfromOutToOutAdqPatch, study.parameters.setToZeroNTCfromOutToOut_AdqPatch); // Unfeasible problem behavior diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index ae27c47c60..a37a295300 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -117,8 +117,8 @@ class Optimization final : public wxDialog Component::Button* pBtnExportMPS; Component::Button* pBtnAdequacyPatch; - Component::Button* pBtnAdequacyPatchNTC12; - Component::Button* pBtnAdequacyPatchNTC11; + Component::Button* pBtnNTCfromOutToInAdqPatch; + Component::Button* pBtnNTCfromOutToOutAdqPatch; Component::Button* pBtnUnfeasibleProblemBehavior; bool* pTargetRef; From e77c177cc23863e956e2ddee3c580af268dcd1a8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 11:57:27 +0200 Subject: [PATCH 148/490] refacto static void SubTitle --- .../windows/options/optimization/optimization.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index fb9bdbc523..e492c28c77 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -46,13 +46,10 @@ namespace Window { namespace Options { -static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) +static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* text) { - if (margintop) - { - sizer->AddSpacer(25); - sizer->AddSpacer(25); - } + sizer->AddSpacer(25); + sizer->AddSpacer(25); auto* label = Component::CreateLabel(parent, text, true); @@ -373,7 +370,7 @@ Optimization::Optimization(wxWindow* parent) : s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->AddSpacer(2); } - SubTitle(this, s, wxT("Adequacy Patch")); + addLabelAdqPatch(this, s, wxT("Adequacy Patch")); // Adequacy patch { label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); From 3c9a4696cf1010b65d71f769bb8d486e4527cad0 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 12:06:40 +0200 Subject: [PATCH 149/490] refacto checkAdqPatchContainsAdqPatchArea --- src/solver/application.cpp | 19 ++++++++----------- 1 file changed, 8 insertions(+), 11 deletions(-) diff --git a/src/solver/application.cpp b/src/solver/application.cpp index 1218221aa5..e556ba9551 100644 --- a/src/solver/application.cpp +++ b/src/solver/application.cpp @@ -98,19 +98,16 @@ void checkAdqPatchContainsAdqPatchArea(const bool adqPatchOn, const Antares::Dat { if (adqPatchOn) { - bool containsAdqArea = false; - for (uint i = 0; i < areas.size(); ++i) + if (!std::any_of(areas.cbegin(), + areas.cend(), + [](const std::pair& area) + { + return area.second->adequacyPatchMode + == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + })) { - const auto& area = *(areas.byIndex[i]); - if (area.adequacyPatchMode - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) - { - containsAdqArea = true; - break; - } - } - if (!containsAdqArea) throw Error::NoAreaInsideAdqPatchMode(); + } } } From 712c998d14acab6a97a77557f0e8718b50d84b6c Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 17:18:44 +0200 Subject: [PATCH 150/490] leave adqm in front of enum values --- src/libs/antares/study/area/area.cpp | 6 +++--- src/libs/antares/study/area/list.cpp | 16 ++++++++-------- src/libs/antares/study/fwd.h | 6 +++--- src/solver/application.cpp | 2 +- src/solver/optimisation/adequacy_patch.cpp | 12 ++++++------ .../opt_gestion_des_bornes_cas_lineaire.cpp | 2 +- src/solver/simulation/economy.cpp | 2 +- .../windows/inspector/property.update.cpp | 6 +++--- 8 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index da7d734762..edaf2057a6 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,7 +53,7 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), - adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), + adequacyPatchMode(AdequacyPatch::physicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -71,7 +71,7 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), - adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), + adequacyPatchMode(AdequacyPatch::physicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -91,7 +91,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), - adequacyPatchMode(AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch), + adequacyPatchMode(AdequacyPatch::physicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index e1fc4f2b62..e2f77a4a9c 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -338,17 +338,17 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) int value; switch (area.adequacyPatchMode) { - case Data::AdequacyPatch::adqmVirtualArea: + case Data::AdequacyPatch::virtualArea: value = 0; break; - case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: value = 1; break; - case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + case Data::AdequacyPatch::physicalAreaInsideAdqPatch: value = 2; break; default: - value = 1; //default adqmPhysicalAreaOutsideAdqPatch + value = 1; //default physicalAreaOutsideAdqPatch break; } section->add("adequacy-patch-mode", value); @@ -1089,16 +1089,16 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, switch (value) { case 0: - area.adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + area.adequacyPatchMode = Data::AdequacyPatch::virtualArea; break; case 1: - area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; break; case 2: - area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaInsideAdqPatch; break; default: - area.adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; break; } continue; diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 5b70500acf..57b4b0ed9b 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -570,11 +570,11 @@ namespace AdequacyPatch enum AdequacyPatchMode { //! Virtual area in adq patch - adqmVirtualArea = 0, + virtualArea = 0, //! Physical Area outside the adq-patch - adqmPhysicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, //! Physical Area inside the adq-patch - adqmPhysicalAreaInsideAdqPatch + physicalAreaInsideAdqPatch }; // enum AdequacyPatchMode diff --git a/src/solver/application.cpp b/src/solver/application.cpp index e556ba9551..99ce52eaaf 100644 --- a/src/solver/application.cpp +++ b/src/solver/application.cpp @@ -103,7 +103,7 @@ void checkAdqPatchContainsAdqPatchArea(const bool adqPatchOn, const Antares::Dat [](const std::pair& area) { return area.second->adequacyPatchMode - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch; })) { throw Error::NoAreaInsideAdqPatchMode(); diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 7d171f311c..db44bfed59 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -40,11 +40,11 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( switch (OriginNodeAdequacyPatchType) { - case adqmPhysicalAreaInsideAdqPatch: + case physicalAreaInsideAdqPatch: returnNTC = SetNTCForAdequacyFirstStepOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, setToZeroNTCfromOutToIn_AdqPatch); break; - case adqmPhysicalAreaOutsideAdqPatch: + case physicalAreaOutsideAdqPatch: returnNTC = SetNTCForAdequacyFirstStepOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, setToZeroNTCfromOutToIn_AdqPatch, @@ -65,10 +65,10 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside switch (ExtremityNodeAdequacyPatchType) { - case adqmPhysicalAreaInsideAdqPatch: + case physicalAreaInsideAdqPatch: returnNTC = setToZero; break; - case adqmPhysicalAreaOutsideAdqPatch: + case physicalAreaOutsideAdqPatch: returnNTC = (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setOrigineExtremityToZero; break; default: @@ -87,10 +87,10 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsid switch (ExtremityNodeAdequacyPatchType) { - case adqmPhysicalAreaInsideAdqPatch: + case physicalAreaInsideAdqPatch: returnNTC = (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setExtremityOrigineToZero; break; - case adqmPhysicalAreaOutsideAdqPatch: + case physicalAreaOutsideAdqPatch: returnNTC = (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; break; default: 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 80b292ad21..14f9657d15 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -403,7 +403,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob // adq patch: update ENS <= DENS in 2nd run if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false && ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Pays] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) Xmax[Var] = min(Xmax[Var], ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index b37f3dd7a9..f812af1e31 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -124,7 +124,7 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) { if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) memcpy(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); diff --git a/src/ui/simulator/windows/inspector/property.update.cpp b/src/ui/simulator/windows/inspector/property.update.cpp index c8143b2e1f..94ef67cdc9 100644 --- a/src/ui/simulator/windows/inspector/property.update.cpp +++ b/src/ui/simulator/windows/inspector/property.update.cpp @@ -187,13 +187,13 @@ bool InspectorGrid::onPropertyChanging_A(wxPGProperty*, switch (s.to()) { case 0: - area->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + area->adequacyPatchMode = Data::AdequacyPatch::virtualArea; break; case 1: - area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + area->adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; break; case 2: - area->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + area->adequacyPatchMode = Data::AdequacyPatch::physicalAreaInsideAdqPatch; break; default: break; From e8a88ba400cfbd552e77c94209a3edce6dd5b683 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 17:25:46 +0200 Subject: [PATCH 151/490] refacto update ENS <= DENS in 2nd run --- .../optimisation/opt_gestion_des_bornes_cas_lineaire.cpp | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) 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 14f9657d15..6117452c77 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -403,11 +403,12 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob // adq patch: update ENS <= DENS in 2nd run if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep == false && ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Pays] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + == AdequacyPatch::physicalAreaInsideAdqPatch) + { Xmax[Var] = min(Xmax[Var], ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); - + } ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo] = 0.0; From b22fc0346f702176a0a7e665a7c599087e4dbd05 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 10 May 2022 17:49:56 +0200 Subject: [PATCH 152/490] change origin/extremityAreaType to AreaMode --- src/solver/optimisation/adequacy_patch.cpp | 4 ++-- src/solver/simulation/sim_structure_probleme_economique.h | 8 ++++---- 2 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index db44bfed59..830492cbde 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -116,8 +116,8 @@ void setNTCbounds(double& Xmax, if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) { SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( - ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], - ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco], ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index e915e28171..aaeedc90e2 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -325,8 +325,8 @@ class AdequacyPatchRuntimeData { public: std::vector areaMode; - std::vector originAreaType; - std::vector extremityAreaType; + std::vector originAreaMode; + std::vector extremityAreaMode; void initialize(Antares::Data::Study& study) { for (uint i = 0; i != study.areas.size(); ++i) @@ -337,8 +337,8 @@ class AdequacyPatchRuntimeData for (uint i = 0; i < study.runtime->interconnectionsCount; ++i) { auto& link = *(study.runtime->areaLink[i]); - originAreaType.push_back(link.from->adequacyPatchMode); - extremityAreaType.push_back(link.with->adequacyPatchMode); + originAreaMode.push_back(link.from->adequacyPatchMode); + extremityAreaMode.push_back(link.with->adequacyPatchMode); } } }; From 73ae615a520d25f281ec14b457e0def73c0fcda3 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 11 May 2022 10:08:30 +0200 Subject: [PATCH 153/490] refacto function SetNTCForAdequacyFirstStep --- src/solver/optimisation/adequacy_patch.cpp | 36 +++++++++++----------- src/solver/optimisation/adequacy_patch.h | 21 ++++--------- 2 files changed, 24 insertions(+), 33 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 830492cbde..18e7e3cfa4 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -30,23 +30,27 @@ using namespace Antares::Data::AdequacyPatch; -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( - AdequacyPatchMode OriginNodeAdequacyPatchType, - AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool setToZeroNTCfromOutToIn_AdqPatch, - bool setToZeroNTCfromOutToOut_AdqPatch) +LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco) { + AdequacyPatchMode OriginNodeAdequacyPatchType + = ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco]; + AdequacyPatchMode ExtremityNodeAdequacyPatchType + = ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco]; + bool setToZeroNTCfromOutToIn_AdqPatch + = ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + bool setToZeroNTCfromOutToOut_AdqPatch + = ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; + LinkCapacityForAdequacyPatchFirstStep returnNTC; switch (OriginNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - returnNTC = SetNTCForAdequacyFirstStepOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, - setToZeroNTCfromOutToIn_AdqPatch); + returnNTC = getNTCtoZeroStatusOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, + setToZeroNTCfromOutToIn_AdqPatch); break; case physicalAreaOutsideAdqPatch: - returnNTC - = SetNTCForAdequacyFirstStepOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, + returnNTC = getNTCtoZeroStatusOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, setToZeroNTCfromOutToIn_AdqPatch, setToZeroNTCfromOutToOut_AdqPatch); break; @@ -57,7 +61,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( return returnNTC; } -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( +LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch) { @@ -78,7 +82,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside return returnNTC; } -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( +LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch, bool setToZeroNTCfromOutToOut_AdqPatch) @@ -106,7 +110,7 @@ void setNTCbounds(double& Xmax, const int Interco, PROBLEME_HEBDO* ProblemeHebdo) { - LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; + LinkCapacityForAdequacyPatchFirstStep ntcToZeroStatusForAdqPatch; // set as default values Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; @@ -115,13 +119,9 @@ void setNTCbounds(double& Xmax, // set for adq patch first step if (ProblemeHebdo->adqPatch && ProblemeHebdo->adqPatch->AdequacyFirstStep) { - SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( - ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco], - ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco], - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq, - ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq); + ntcToZeroStatusForAdqPatch = getNTCtoZeroStatus(ProblemeHebdo, Interco); - switch (SetToZeroLinkNTCForAdequacyPatchFirstStep) + switch (ntcToZeroStatusForAdqPatch) { case setToZero: { diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index a30d43584d..7cdc950735 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -33,24 +33,15 @@ using namespace Antares::Data; /*! * Determines restriction type for transmission links for first step of adequacy patch. * - * @param OriginNodeAdequacyPatchType uint: The adq type of the node at the start of the link. + * @param ProblemeHebdo PROBLEME_HEBDO*: Weekly problem structure. * - * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. - * - * @param setToZeroNTCfromOutToIn_AdqPatch bool: Switch to cut links from nodes outside adq patch - * (type 1) towards nodes inside adq patch (type 2). - * - * @param setToZeroNTCfromOutToOut_AdqPatch bool: Switch to cut links between nodes outside adq patch - * (type 1). + * @param Interco int: Index of the link. * * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( - AdequacyPatchMode OriginNodeAdequacyPatchType, - AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool setToZeroNTCfromOutToIn_AdqPatch, - bool setToZeroNTCfromOutToOut_AdqPatch); +LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, + int Interco); /*! * Determines restriction type for transmission links for first step of adequacy patch, when start @@ -64,7 +55,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( +LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch); @@ -83,7 +74,7 @@ LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInside * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( +LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch, bool setToZeroNTCfromOutToOut_AdqPatch); From 9aef317d16fdb0d1f12d4b57269a509f3c19e88e Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 11 May 2022 10:19:03 +0200 Subject: [PATCH 154/490] LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq name change --- src/solver/optimisation/adequacy_patch.cpp | 4 ++-- src/solver/simulation/sim_calcul_economique.cpp | 4 ++-- src/solver/simulation/sim_structure_probleme_economique.h | 4 ++-- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 18e7e3cfa4..3f64239a38 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -37,9 +37,9 @@ LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* Problem AdequacyPatchMode ExtremityNodeAdequacyPatchType = ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco]; bool setToZeroNTCfromOutToIn_AdqPatch - = ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + = ProblemeHebdo->adqPatch->setToZeroNTCfromOutToIn_AdqPatchStep1; bool setToZeroNTCfromOutToOut_AdqPatch - = ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; + = ProblemeHebdo->adqPatch->setToZeroNTCbetweenOutsideAreas_AdqPatchStep1; LinkCapacityForAdequacyPatchFirstStep returnNTC; diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 70d321f071..db789c10dd 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -68,9 +68,9 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.adqPatch = std::unique_ptr(new AdequacyPatchParameters()); // AdequacyFirstStep will be initialized during the economy solve // AdqBehaviorMap will be initialized during the economy solve - problem.adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq + problem.adqPatch->setToZeroNTCfromOutToIn_AdqPatchStep1 = parameters.setToZeroNTCfromOutToIn_AdqPatch; - problem.adqPatch->LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq + problem.adqPatch->setToZeroNTCbetweenOutsideAreas_AdqPatchStep1 = parameters.setToZeroNTCfromOutToOut_AdqPatch; } diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index aaeedc90e2..220ec5010a 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -499,8 +499,8 @@ typedef struct struct AdequacyPatchParameters { bool AdequacyFirstStep; - bool LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; - bool LinkCapacityForAdqPatchFirstStepBetweenAreaOutsideAdq; + bool setToZeroNTCfromOutToIn_AdqPatchStep1; + bool setToZeroNTCbetweenOutsideAreas_AdqPatchStep1; }; struct PROBLEME_HEBDO From e76f47b70d5508f9e7ca363d761a46fabfecd881 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 11 May 2022 10:32:44 +0200 Subject: [PATCH 155/490] name change for LinkCapacityForAdequacyPatchFirstStep --- src/libs/antares/study/fwd.h | 2 +- src/solver/optimisation/adequacy_patch.cpp | 14 +++++++------- src/solver/optimisation/adequacy_patch.h | 11 +++++------ 3 files changed, 13 insertions(+), 14 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 57b4b0ed9b..d051b86a55 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -581,7 +581,7 @@ enum AdequacyPatchMode /*! ** \brief Setting Link Capacity (NTC) for Adequacy patch first step */ -enum LinkCapacityForAdequacyPatchFirstStep +enum ntcSetToZeroStatus_AdqPatchStep1 { //! Leave NTC local values leaveLocalValues = 0, diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 3f64239a38..26b1f611d6 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -30,7 +30,7 @@ using namespace Antares::Data::AdequacyPatch; -LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco) +ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco) { AdequacyPatchMode OriginNodeAdequacyPatchType = ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco]; @@ -41,7 +41,7 @@ LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* Problem bool setToZeroNTCfromOutToOut_AdqPatch = ProblemeHebdo->adqPatch->setToZeroNTCbetweenOutsideAreas_AdqPatchStep1; - LinkCapacityForAdequacyPatchFirstStep returnNTC; + ntcSetToZeroStatus_AdqPatchStep1 returnNTC; switch (OriginNodeAdequacyPatchType) { @@ -61,11 +61,11 @@ LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* Problem return returnNTC; } -LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeInsideAdq( +ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch) { - LinkCapacityForAdequacyPatchFirstStep returnNTC; + ntcSetToZeroStatus_AdqPatchStep1 returnNTC; switch (ExtremityNodeAdequacyPatchType) { @@ -82,12 +82,12 @@ LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeInsideAdq( return returnNTC; } -LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeOutsideAdq( +ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch, bool setToZeroNTCfromOutToOut_AdqPatch) { - LinkCapacityForAdequacyPatchFirstStep returnNTC; + ntcSetToZeroStatus_AdqPatchStep1 returnNTC; switch (ExtremityNodeAdequacyPatchType) { @@ -110,7 +110,7 @@ void setNTCbounds(double& Xmax, const int Interco, PROBLEME_HEBDO* ProblemeHebdo) { - LinkCapacityForAdequacyPatchFirstStep ntcToZeroStatusForAdqPatch; + ntcSetToZeroStatus_AdqPatchStep1 ntcToZeroStatusForAdqPatch; // set as default values Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 7cdc950735..fc25d47a14 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -40,8 +40,7 @@ using namespace Antares::Data; * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, - int Interco); +ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco); /*! * Determines restriction type for transmission links for first step of adequacy patch, when start @@ -55,7 +54,7 @@ LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatus(PROBLEME_HEBDO* Problem * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeInsideAdq( +ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch); @@ -68,13 +67,13 @@ LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeInsideAdq( * @param setToZeroNTCfromOutToIn_AdqPatch bool: Switch to cut links from nodes outside adq patch * (type 1) towards nodes inside adq patch (type 2). * - * @param setToZeroNTCfromOutToOut_AdqPatch bool: Switch to cut links between nodes outside adq patch - * (type 1). + * @param setToZeroNTCfromOutToOut_AdqPatch bool: Switch to cut links between nodes outside adq + * patch (type 1). * * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ -LinkCapacityForAdequacyPatchFirstStep getNTCtoZeroStatusOriginNodeOutsideAdq( +ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch, bool setToZeroNTCfromOutToOut_AdqPatch); From ceee05b7b96b12250a92c0034b4968091e799bfc Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 11 May 2022 11:20:37 +0200 Subject: [PATCH 156/490] remove returnNTC form adq functions. --- src/solver/optimisation/adequacy_patch.cpp | 33 ++++++++-------------- 1 file changed, 12 insertions(+), 21 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 26b1f611d6..fa0e9502b3 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -41,45 +41,39 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebd bool setToZeroNTCfromOutToOut_AdqPatch = ProblemeHebdo->adqPatch->setToZeroNTCbetweenOutsideAreas_AdqPatchStep1; - ntcSetToZeroStatus_AdqPatchStep1 returnNTC; - switch (OriginNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - returnNTC = getNTCtoZeroStatusOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, - setToZeroNTCfromOutToIn_AdqPatch); + return getNTCtoZeroStatusOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, + setToZeroNTCfromOutToIn_AdqPatch); break; case physicalAreaOutsideAdqPatch: - returnNTC = getNTCtoZeroStatusOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, - setToZeroNTCfromOutToIn_AdqPatch, - setToZeroNTCfromOutToOut_AdqPatch); + return getNTCtoZeroStatusOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, + setToZeroNTCfromOutToIn_AdqPatch, + setToZeroNTCfromOutToOut_AdqPatch); break; default: - returnNTC = leaveLocalValues; + return leaveLocalValues; break; } - return returnNTC; } ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, bool setToZeroNTCfromOutToIn_AdqPatch) { - ntcSetToZeroStatus_AdqPatchStep1 returnNTC; - switch (ExtremityNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - returnNTC = setToZero; + return setToZero; break; case physicalAreaOutsideAdqPatch: - returnNTC = (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setOrigineExtremityToZero; + return (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setOrigineExtremityToZero; break; default: - returnNTC = leaveLocalValues; + return leaveLocalValues; break; } - return returnNTC; } ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( @@ -87,21 +81,18 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( bool setToZeroNTCfromOutToIn_AdqPatch, bool setToZeroNTCfromOutToOut_AdqPatch) { - ntcSetToZeroStatus_AdqPatchStep1 returnNTC; - switch (ExtremityNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - returnNTC = (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setExtremityOrigineToZero; + return (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setExtremityOrigineToZero; break; case physicalAreaOutsideAdqPatch: - returnNTC = (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; + return (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; break; default: - returnNTC = leaveLocalValues; + return leaveLocalValues; break; } - return returnNTC; } void setNTCbounds(double& Xmax, From 19cb70d85f06eaefcc42c6df8f9856c46bed8db9 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 12 May 2022 16:16:12 +0200 Subject: [PATCH 157/490] remove unnecessary break --- src/solver/optimisation/adequacy_patch.cpp | 9 --------- 1 file changed, 9 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index fa0e9502b3..870108f86a 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -46,15 +46,12 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebd case physicalAreaInsideAdqPatch: return getNTCtoZeroStatusOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType, setToZeroNTCfromOutToIn_AdqPatch); - break; case physicalAreaOutsideAdqPatch: return getNTCtoZeroStatusOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, setToZeroNTCfromOutToIn_AdqPatch, setToZeroNTCfromOutToOut_AdqPatch); - break; default: return leaveLocalValues; - break; } } @@ -66,13 +63,10 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeInsideAdq( { case physicalAreaInsideAdqPatch: return setToZero; - break; case physicalAreaOutsideAdqPatch: return (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setOrigineExtremityToZero; - break; default: return leaveLocalValues; - break; } } @@ -85,13 +79,10 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( { case physicalAreaInsideAdqPatch: return (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setExtremityOrigineToZero; - break; case physicalAreaOutsideAdqPatch: return (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; - break; default: return leaveLocalValues; - break; } } From 8cba9b7952c329fcf1598531e03e06bcd8bcebb6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 13 May 2022 09:13:41 +0200 Subject: [PATCH 158/490] make readAdqPatchMode function --- src/libs/antares/study/area/list.cpp | 77 +++++++++++++++------------- 1 file changed, 41 insertions(+), 36 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index e2f77a4a9c..ec5bb47675 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -750,6 +750,46 @@ bool AreaList::saveToFolder(const AnyString& folder) const return ret; } +template +static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) +{ + if (study.header.version >= 820 && study.parameters.include.adequacyPatch) + { + buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP + << "adequacy_patch.ini"; + IniFile ini; + if (ini.open(buffer)) + { + auto* section = ini.find("adequacy-patch"); + for (auto* p = section->firstProperty; p; p = p->next) + { + CString<30, false> tmp; + tmp = p->key; + tmp.toLower(); + if (tmp == "adequacy-patch-mode") + { + auto value = p->value.to(); + switch (value) + { + case 0: + area.adequacyPatchMode = Data::AdequacyPatch::virtualArea; + break; + case 1: + area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; + break; + case 2: + area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaInsideAdqPatch; + break; + default: + area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; + break; + } + continue; + } + } + } + } +} template static bool AreaListLoadFromFolderSingleArea(Study& study, AreaList* list, @@ -1070,42 +1110,7 @@ static bool AreaListLoadFromFolderSingleArea(Study& study, } // Adequacy patch - if (study.header.version >= 820 && study.parameters.include.adequacyPatch) - { - buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP - << "adequacy_patch.ini"; - IniFile ini; - if (ini.open(buffer)) - { - auto* section = ini.find("adequacy-patch"); - for (auto* p = section->firstProperty; p; p = p->next) - { - CString<30, false> tmp; - tmp = p->key; - tmp.toLower(); - if (tmp == "adequacy-patch-mode") - { - auto value = p->value.to(); - switch (value) - { - case 0: - area.adequacyPatchMode = Data::AdequacyPatch::virtualArea; - break; - case 1: - area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; - break; - case 2: - area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaInsideAdqPatch; - break; - default: - area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; - break; - } - continue; - } - } - } - } + readAdqPatchMode(study, area, buffer); // Nodal Optimization if (study.header.version >= 330) From 9bb4e01546b49a27839cac5957ecc8407c847e67 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 13 May 2022 10:46:44 +0200 Subject: [PATCH 159/490] make ini file more expressive --- src/libs/antares/study/area/list.cpp | 29 ++++++++++------------------ 1 file changed, 10 insertions(+), 19 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index ec5bb47675..e451bc4bd5 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -335,20 +335,20 @@ bool saveAreaAdequacyPatchIniFile(const Area& area, const Clob& buffer) { IniFile ini; IniFile::Section* section = ini.addSection("adequacy-patch"); - int value; + std::string value; switch (area.adequacyPatchMode) { case Data::AdequacyPatch::virtualArea: - value = 0; + value = "virtual"; break; case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: - value = 1; + value = "outside"; break; case Data::AdequacyPatch::physicalAreaInsideAdqPatch: - value = 2; + value = "inside"; break; default: - value = 1; //default physicalAreaOutsideAdqPatch + value = "outside"; //default physicalAreaOutsideAdqPatch break; } section->add("adequacy-patch-mode", value); @@ -768,23 +768,14 @@ static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) tmp.toLower(); if (tmp == "adequacy-patch-mode") { - auto value = p->value.to(); - switch (value) - { - case 0: + auto value = (p->value).toLower(); + + if (value == "virtual") area.adequacyPatchMode = Data::AdequacyPatch::virtualArea; - break; - case 1: - area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; - break; - case 2: + else if (value == "inside") area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaInsideAdqPatch; - break; - default: + else area.adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; - break; - } - continue; } } } From cfadebc14cd4740e88a3c40f0873cca3fbc675fc Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 13 May 2022 10:50:12 +0200 Subject: [PATCH 160/490] remove additional check for ini file --- src/libs/antares/study/area/list.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index e451bc4bd5..da37c2d630 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -753,7 +753,7 @@ bool AreaList::saveToFolder(const AnyString& folder) const template static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) { - if (study.header.version >= 820 && study.parameters.include.adequacyPatch) + if (study.header.version >= 820) { buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; From 7e6f91d913b6f9d07c23ae46e119c2987666461b Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 13 May 2022 10:57:00 +0200 Subject: [PATCH 161/490] refacto --- src/libs/antares/study/area/list.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index da37c2d630..89d57a7638 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -768,7 +768,9 @@ static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) tmp.toLower(); if (tmp == "adequacy-patch-mode") { - auto value = (p->value).toLower(); + auto value = p->value; + value.trim(); + value.toLower(); if (value == "virtual") area.adequacyPatchMode = Data::AdequacyPatch::virtualArea; From 683c417cd68619e02c8ab50460699a5a3d9638b3 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 13 May 2022 11:15:34 +0200 Subject: [PATCH 162/490] make version 8.3.0 --- src/libs/antares/study/area/list.cpp | 2 +- src/libs/antares/study/version.cpp | 10 ++++++++-- src/libs/antares/study/version.h | 2 ++ vcpkg_manifest/vcpkg.json | 2 +- 4 files changed, 12 insertions(+), 4 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 89d57a7638..44f6ab278c 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -753,7 +753,7 @@ bool AreaList::saveToFolder(const AnyString& folder) const template static void readAdqPatchMode(Study& study, Area& area, StringT& buffer) { - if (study.header.version >= 820) + if (study.header.version >= 830) { buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; diff --git a/src/libs/antares/study/version.cpp b/src/libs/antares/study/version.cpp index 674e74f2e4..eae987a1cf 100644 --- a/src/libs/antares/study/version.cpp +++ b/src/libs/antares/study/version.cpp @@ -97,7 +97,9 @@ const char* VersionToCStr(const Version v) switch (v) { case versionFutur: - return ">8.2"; + return ">8.3"; + case version830: + return "8.3"; case version820: return "8.2"; case version810: @@ -178,7 +180,9 @@ const wchar_t* VersionToWStr(const Version v) switch (v) { case versionFutur: - return L">8.2"; + return L">8.3"; + case version830: + return L"8.3"; case version820: return L"8.2"; case version810: @@ -258,6 +262,8 @@ Version VersionIntToVersion(uint version) // The list should remain ordered in the reverse order for performance reasons switch (version) { + case 830: + return version830; case 820: return version820; case 810: diff --git a/src/libs/antares/study/version.h b/src/libs/antares/study/version.h index 48d04e7f81..d97076d93d 100644 --- a/src/libs/antares/study/version.h +++ b/src/libs/antares/study/version.h @@ -110,6 +110,8 @@ typedef enum // Version version810 = 810, //! Study version 8.2 version820 = 820, + //! Study version 8.3 + version830 = 830, // see versionLatest below diff --git a/vcpkg_manifest/vcpkg.json b/vcpkg_manifest/vcpkg.json index 5d168ccf77..4a24af3295 100644 --- a/vcpkg_manifest/vcpkg.json +++ b/vcpkg_manifest/vcpkg.json @@ -1,6 +1,6 @@ { "name": "antares-simulator", - "version-string": "8.2.0", + "version-string": "8.3.0", "dependencies": [ "wxwidgets", "boost-test" From 7f2af4675fabc5443e2e5b809087debdc9214db1 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 13 May 2022 11:59:28 +0200 Subject: [PATCH 163/490] Revert "make version 8.3.0" --- src/libs/antares/study/area/list.cpp | 2 +- src/libs/antares/study/version.cpp | 10 ++-------- src/libs/antares/study/version.h | 2 -- vcpkg_manifest/vcpkg.json | 2 +- 4 files changed, 4 insertions(+), 12 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 44f6ab278c..89d57a7638 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -753,7 +753,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 >= 820) { buffer.clear() << study.folderInput << SEP << "areas" << SEP << area.id << SEP << "adequacy_patch.ini"; diff --git a/src/libs/antares/study/version.cpp b/src/libs/antares/study/version.cpp index eae987a1cf..674e74f2e4 100644 --- a/src/libs/antares/study/version.cpp +++ b/src/libs/antares/study/version.cpp @@ -97,9 +97,7 @@ const char* VersionToCStr(const Version v) switch (v) { case versionFutur: - return ">8.3"; - case version830: - return "8.3"; + return ">8.2"; case version820: return "8.2"; case version810: @@ -180,9 +178,7 @@ const wchar_t* VersionToWStr(const Version v) switch (v) { case versionFutur: - return L">8.3"; - case version830: - return L"8.3"; + return L">8.2"; case version820: return L"8.2"; case version810: @@ -262,8 +258,6 @@ Version VersionIntToVersion(uint version) // The list should remain ordered in the reverse order for performance reasons switch (version) { - case 830: - return version830; case 820: return version820; case 810: diff --git a/src/libs/antares/study/version.h b/src/libs/antares/study/version.h index d97076d93d..48d04e7f81 100644 --- a/src/libs/antares/study/version.h +++ b/src/libs/antares/study/version.h @@ -110,8 +110,6 @@ typedef enum // Version version810 = 810, //! Study version 8.2 version820 = 820, - //! Study version 8.3 - version830 = 830, // see versionLatest below diff --git a/vcpkg_manifest/vcpkg.json b/vcpkg_manifest/vcpkg.json index 4a24af3295..5d168ccf77 100644 --- a/vcpkg_manifest/vcpkg.json +++ b/vcpkg_manifest/vcpkg.json @@ -1,6 +1,6 @@ { "name": "antares-simulator", - "version-string": "8.3.0", + "version-string": "8.2.0", "dependencies": [ "wxwidgets", "boost-test" From 44eaa33ba6a38ca9570411837fbbf8eba225329c Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 11:26:34 +0200 Subject: [PATCH 164/490] fix --- src/libs/antares/study/parameters.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index f3ca550a03..de0b39ca5d 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -665,7 +665,7 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, const String&, uint) { - if (key == "include-adequacypatch") + if (key == "include-adq-patch") return value.to(d.include.adequacyPatch); if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch") return value.to(d.setToZeroNTCfromOutToIn_AdqPatch); @@ -1796,7 +1796,7 @@ void Parameters::saveToINI(IniFile& ini) const // Adequacy patch { auto* section = ini.addSection("adequacy patch"); - section->add("include-adequacypatch", include.adequacyPatch); + section->add("include-adq-patch", include.adequacyPatch); section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch", setToZeroNTCfromOutToIn_AdqPatch); section->add("set-to-null-ntc-between-physical-out-for-first-step-adq-patch", From 91735f47dc65373269d77e5042868b2ee86e7f44 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 11:31:36 +0200 Subject: [PATCH 165/490] fix --- src/libs/antares/study/parameters.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index de0b39ca5d..624ee52cad 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -667,9 +667,9 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, { if (key == "include-adq-patch") return value.to(d.include.adequacyPatch); - if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch") + if (key == "set-to-null-ntc-from-physical-out-to-physical-in-for-first-step") return value.to(d.setToZeroNTCfromOutToIn_AdqPatch); - if (key == "set-to-null-ntc-between-physical-out-for-first-step-adq-patch") + if (key == "set-to-null-ntc-between-physical-out-for-first-step") return value.to(d.setToZeroNTCfromOutToOut_AdqPatch); if (key == "save-intermediate-results") return value.to(d.adqPatchSaveIntermediateResults); @@ -1797,9 +1797,9 @@ void Parameters::saveToINI(IniFile& ini) const { auto* section = ini.addSection("adequacy patch"); section->add("include-adq-patch", include.adequacyPatch); - section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step-adq-patch", + section->add("set-to-null-ntc-from-physical-out-to-physical-in-for-first-step", setToZeroNTCfromOutToIn_AdqPatch); - section->add("set-to-null-ntc-between-physical-out-for-first-step-adq-patch", + section->add("set-to-null-ntc-between-physical-out-for-first-step", setToZeroNTCfromOutToOut_AdqPatch); section->add("save-intermediate-results", adqPatchSaveIntermediateResults); section->add("price-taking-order", PriceTakingOrderToString(adqPatchPriceTakingOrder)); From 6f4995abb1b906119d9e29d4df92a5ecee75a7b1 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 11:47:29 +0200 Subject: [PATCH 166/490] synchronize names setToZeroNTCfrom.. --- .../adequacy-patch/adequacy-patch-options.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) 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 ae0487939d..c24d5619da 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 @@ -185,7 +185,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->menu(true); onPopup.bind(this, &AdequacyPatchOptions::onPopupMenuNTC, - PopupInfo(study.parameters.setToZero12LinksForAdequacyPatch, wxT("NTC"))); + PopupInfo(study.parameters.setToZeroNTCfromOutToIn_AdqPatch, wxT("NTC"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); @@ -200,7 +200,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->menu(true); onPopup.bind(this, &AdequacyPatchOptions::onPopupMenuNTC, - PopupInfo(study.parameters.setToZero11LinksForAdequacyPatch, wxT("NTC"))); + PopupInfo(study.parameters.setToZeroNTCfromOutToOut_AdqPatch, wxT("NTC"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); @@ -319,8 +319,8 @@ void AdequacyPatchOptions::onResetToDefault(void*) auto& study = *studyptr; study.parameters.include.adequacyPatch = false; - study.parameters.setToZero12LinksForAdequacyPatch = true; - study.parameters.setToZero11LinksForAdequacyPatch = true; + study.parameters.setToZeroNTCfromOutToIn_AdqPatch = true; + study.parameters.setToZeroNTCfromOutToOut_AdqPatch = true; study.parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsDens; study.parameters.adqPatchSaveIntermediateResults = false; @@ -350,10 +350,10 @@ void AdequacyPatchOptions::refresh() ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - ResetButtonNTC(pBtnAdequacyPatchNTC12, study.parameters.setToZero12LinksForAdequacyPatch); + ResetButtonNTC(pBtnAdequacyPatchNTC12, study.parameters.setToZeroNTCfromOutToIn_AdqPatch); // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of // adequacy patch local matching rule. - ResetButtonNTC(pBtnAdequacyPatchNTC11, study.parameters.setToZero11LinksForAdequacyPatch); + ResetButtonNTC(pBtnAdequacyPatchNTC11, study.parameters.setToZeroNTCfromOutToOut_AdqPatch); // Price taking order (PTO) for adequacy patch ResetButtonPTO(pBtnAdequacyPatchPTO, study.parameters.adqPatchPriceTakingOrder); // Save intermediate results for adequacy patch From 4dc134e5b33c3488b15509d9944aab712ff5389b Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 11:50:29 +0200 Subject: [PATCH 167/490] synchronize names pBtn... --- .../options/adequacy-patch/adequacy-patch-options.cpp | 8 ++++---- .../options/adequacy-patch/adequacy-patch-options.h | 4 ++-- 2 files changed, 6 insertions(+), 6 deletions(-) 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 c24d5619da..9e44081f3a 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 @@ -189,7 +189,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchNTC12 = button; + pBtnNTCfromOutToInAdqPatch = button; } // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). // Used in the first step of adequacy patch local matching rule. @@ -204,7 +204,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchNTC11 = button; + pBtnNTCfromOutToOutAdqPatch = button; } // PTO (Price Taking Order). User can choose between DENS and Load { @@ -350,10 +350,10 @@ void AdequacyPatchOptions::refresh() ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - ResetButtonNTC(pBtnAdequacyPatchNTC12, study.parameters.setToZeroNTCfromOutToIn_AdqPatch); + ResetButtonNTC(pBtnNTCfromOutToInAdqPatch, study.parameters.setToZeroNTCfromOutToIn_AdqPatch); // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of // adequacy patch local matching rule. - ResetButtonNTC(pBtnAdequacyPatchNTC11, study.parameters.setToZeroNTCfromOutToOut_AdqPatch); + ResetButtonNTC(pBtnNTCfromOutToOutAdqPatch, study.parameters.setToZeroNTCfromOutToOut_AdqPatch); // Price taking order (PTO) for adequacy patch ResetButtonPTO(pBtnAdequacyPatchPTO, study.parameters.adqPatchPriceTakingOrder); // Save intermediate results for adequacy patch 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 303dcff801..4d498458bb 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 @@ -91,8 +91,8 @@ class AdequacyPatchOptions final : public wxDialog void onEditSeedTSDraws(wxCommandEvent&); private: Component::Button* pBtnAdequacyPatch; - Component::Button* pBtnAdequacyPatchNTC12; - Component::Button* pBtnAdequacyPatchNTC11; + Component::Button* pBtnNTCfromOutToInAdqPatch; + Component::Button* pBtnNTCfromOutToOutAdqPatch; Component::Button* pBtnAdequacyPatchPTO; Component::Button* pBtnAdequacyPatchSaveIntermediateResults; wxTextCtrl* pEditSeeds[Data::AdequacyPatch::adqPatchThresholdsMax]; From f4420d3e38295eec2452d535f43ec4dd99e30115 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 12:02:16 +0200 Subject: [PATCH 168/490] synchronize adequacy-patch-options.cpp --- .../adequacy-patch/adequacy-patch-options.cpp | 23 +++++++++---------- 1 file changed, 11 insertions(+), 12 deletions(-) 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 9e44081f3a..3457eb1ad1 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 @@ -46,13 +46,10 @@ namespace Window { namespace Options { -static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text, bool margintop = true) +static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* text) { - if (margintop) - { - sizer->AddSpacer(25); - sizer->AddSpacer(25); - } + sizer->AddSpacer(25); + sizer->AddSpacer(25); auto* label = Component::CreateLabel(parent, text, true); @@ -233,17 +230,19 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatchSaveIntermediateResults = button; } - SubTitle(this, s, wxT("Thresholds")); + addLabelAdqPatch(this, s, wxT("Thresholds")); // Seeds/threshold values for (uint i = 0; i != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++i) pEditSeeds[i] = nullptr; - + for (uint seed = 0; seed != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++seed) { - pEditSeeds[seed] = insertEdit(this, - s, - wxStringFromUTF8(AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdsIndex)seed)), - wxCommandEventHandler(AdequacyPatchOptions::onEditSeedTSDraws)); + pEditSeeds[seed] + = insertEdit(this, + s, + wxStringFromUTF8( + AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdsIndex)seed)), + wxCommandEventHandler(AdequacyPatchOptions::onEditSeedTSDraws)); } { From 51ade4ad4bdd89d5925bb5d702a686c14118ef9d Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 12:05:36 +0200 Subject: [PATCH 169/490] synchronize names adqm.. --- src/solver/optimisation/adequacy_patch.cpp | 4 ++-- .../renderer/adequacy-patch-area-grid.cpp | 16 ++++++++-------- 2 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index f9cc9c931c..4505f4c907 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -221,7 +221,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; } else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] - == adqmPhysicalAreaOutsideAdqPatch) + == physicalAreaOutsideAdqPatch) { flowsNode1toNodeA -= Math::Min(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); @@ -237,7 +237,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; } else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] - == adqmPhysicalAreaOutsideAdqPatch) + == physicalAreaOutsideAdqPatch) { flowsNode1toNodeA += Math::Max(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); 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 8f1d7cc434..b22b8be32b 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 @@ -56,13 +56,13 @@ bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) bool out = s.to() == 1 || s == "outside" || s == "physical area outside patch"; if (vir) - study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::adqmVirtualArea; + study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::virtualArea; else if (ins) study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; else study->areas.byIndex[row]->adequacyPatchMode - = Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch; + = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; onTriggerUpdate(); Dispatcher::GUI::Refresh(pControl); @@ -79,10 +79,10 @@ double AdequacyPatchAreaGrid::cellNumericValue(int, int row) const // for saving into *.txt file switch (study->areas.byIndex[row]->adequacyPatchMode) { - case Data::AdequacyPatch::adqmVirtualArea: + case Data::AdequacyPatch::virtualArea: return 0.; break; - case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: return 1.; break; case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: @@ -101,10 +101,10 @@ wxString AdequacyPatchAreaGrid::cellValue(int, int row) const { switch (study->areas.byIndex[row]->adequacyPatchMode) { - case Data::AdequacyPatch::adqmVirtualArea: + case Data::AdequacyPatch::virtualArea: return wxT("virtual"); break; - case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: return wxT("outside"); break; case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: @@ -128,10 +128,10 @@ IRenderer::CellStyle AdequacyPatchAreaGrid::cellStyle(int, int row) const { switch (study->areas.byIndex[row]->adequacyPatchMode) { - case Data::AdequacyPatch::adqmVirtualArea: + case Data::AdequacyPatch::virtualArea: return IRenderer::cellStyleAdqPatchVirtual; break; - case Data::AdequacyPatch::adqmPhysicalAreaOutsideAdqPatch: + case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: return IRenderer::cellStyleAdqPatchOutside; break; case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: From c30cfc88d0f61c0d06b5addff84906b8720ba7f7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 12:09:11 +0200 Subject: [PATCH 170/490] synchronize names AreaType to AreaMode --- src/solver/optimisation/adequacy_patch.cpp | 8 ++++---- ...ction_matrice_des_contraintes_cas_quadratique.cpp | 12 ++++++------ ...construction_variables_optimisees_quadratique.cpp | 4 ++-- .../opt_gestion_des_bornes_cas_quadratique.cpp | 4 ++-- .../opt_gestion_des_couts_cas_quadratique.cpp | 4 ++-- .../opt_gestion_second_membre_cas_quadratique.cpp | 8 ++++---- 6 files changed, 20 insertions(+), 20 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 4505f4c907..6949e4aba2 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -215,12 +215,12 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; while (Interco >= 0) { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == adqmPhysicalAreaInsideAdqPatch) { netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; } - else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == physicalAreaOutsideAdqPatch) { flowsNode1toNodeA @@ -231,12 +231,12 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; while (Interco >= 0) { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == adqmPhysicalAreaInsideAdqPatch) { netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; } - else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == physicalAreaOutsideAdqPatch) { flowsNode1toNodeA 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 index 220afb3059..b96f7ba9e0 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -146,9 +146,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( // type 2. for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; @@ -217,7 +217,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; while (Interco >= 0) { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim @@ -241,7 +241,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; while (Interco >= 0) { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim @@ -305,9 +305,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour] diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 9877399bdc..06f0c6a40a 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -115,9 +115,9 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] 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 586cccfcfd..9068deb12d 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -179,9 +179,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) { // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { // flow 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 e791a69a41..eacbfead81 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -132,9 +132,9 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; 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 a438ac87ef..4d2fa0ed31 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -78,9 +78,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // type 2. for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; @@ -165,9 +165,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco] + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch - || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco] + || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) { ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; From 247670393257a3863985b37a2a89db4e7ae1129c Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 12:11:21 +0200 Subject: [PATCH 171/490] synchronize names LinkCapacity.. --- src/solver/optimisation/adequacy_patch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 6949e4aba2..164347695e 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -210,7 +210,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo double ensInit; double densNew; bool includeFlowsOutsideAdqPatchToDensNew - = !ProblemeHebdo->adqPatch->LinkCapacityForAdqPatchFirstStepFromAreaOutsideToAreaInsideAdq; + = !ProblemeHebdo->adqPatch->setToZeroNTCfromOutToIn_AdqPatchStep1; Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; while (Interco >= 0) From 73f4126a183c1c807c1ff517f38edf0b6f28ad63 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 17 May 2022 12:15:21 +0200 Subject: [PATCH 172/490] synchronize name physicalAreaInsideAdqPatch --- src/solver/optimisation/adequacy_patch.cpp | 8 ++++---- ...n_matrice_des_contraintes_cas_quadratique.cpp | 16 ++++++++-------- ...truction_variables_optimisees_quadratique.cpp | 8 ++++---- .../opt_gestion_des_bornes_cas_quadratique.cpp | 8 ++++---- .../opt_gestion_des_couts_cas_quadratique.cpp | 6 +++--- ...opt_gestion_second_membre_cas_quadratique.cpp | 12 ++++++------ src/solver/simulation/economy.cpp | 2 +- .../renderer/adequacy-patch-area-grid.cpp | 8 ++++---- 8 files changed, 34 insertions(+), 34 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 164347695e..e0864dcccc 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -140,7 +140,7 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == adqmPhysicalAreaInsideAdqPatch) + == physicalAreaInsideAdqPatch) { std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); @@ -176,7 +176,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == adqmPhysicalAreaInsideAdqPatch) + == physicalAreaInsideAdqPatch) { for (int hour = 0; hour < numOfHoursInWeek; hour++) { @@ -216,7 +216,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo while (Interco >= 0) { if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == adqmPhysicalAreaInsideAdqPatch) + == physicalAreaInsideAdqPatch) { netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; } @@ -232,7 +232,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo while (Interco >= 0) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == adqmPhysicalAreaInsideAdqPatch) + == physicalAreaInsideAdqPatch) { netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; } 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 index b96f7ba9e0..a622e64ce3 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -123,7 +123,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { NombreDeTermes = 0; Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; @@ -147,9 +147,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; @@ -201,7 +201,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { // + ENS NombreDeTermes = 0; @@ -218,7 +218,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( while (Interco >= 0) { if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableDeLInterconnexion[Interco]; // flow (A->2) @@ -242,7 +242,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( while (Interco >= 0) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableDeLInterconnexion[Interco]; // flow (2 -> A) @@ -306,9 +306,9 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + == Data::AdequacyPatch::physicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { Var = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour] ->NumeroDeVariableDeLInterconnexion[Interco]; diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 06f0c6a40a..96fd352ab8 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -79,7 +79,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( { // Only ENS for areas inside adq patch are considered as variables if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; @@ -97,7 +97,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( { // Only Spilled Energy for areas inside adq patch are considered as variables if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] = NumberOfVariables; @@ -116,9 +116,9 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( { // only consider link between 2 and 2 if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NumberOfVariables; 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 9068deb12d..b9909299d1 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -119,7 +119,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; @@ -144,7 +144,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; @@ -180,9 +180,9 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( { // only consider link between 2 and 2 if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; 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 eacbfead81..27fed05eae 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -86,7 +86,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) @@ -133,9 +133,9 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; // flow 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 4d2fa0ed31..e06a36dcab 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -63,7 +63,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) @@ -79,9 +79,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; @@ -111,7 +111,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) { std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); @@ -166,9 +166,9 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch + != Data::AdequacyPatch::physicalAreaInsideAdqPatch || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - != Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + != Data::AdequacyPatch::physicalAreaInsideAdqPatch) { ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; SecondMembre[Cnt] -= ValueOfFlow * Poids; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index f08055c516..b6531666fc 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -151,7 +151,7 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) { if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch) + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) Math::sumTwoArrays( sumENS, pProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive, 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 b22b8be32b..3d708545e0 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 @@ -59,7 +59,7 @@ bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::virtualArea; else if (ins) study->areas.byIndex[row]->adequacyPatchMode - = Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch; + = Data::AdequacyPatch::physicalAreaInsideAdqPatch; else study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; @@ -85,7 +85,7 @@ double AdequacyPatchAreaGrid::cellNumericValue(int, int row) const case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: return 1.; break; - case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + case Data::AdequacyPatch::physicalAreaInsideAdqPatch: return 2.; break; default: @@ -107,7 +107,7 @@ wxString AdequacyPatchAreaGrid::cellValue(int, int row) const case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: return wxT("outside"); break; - case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + case Data::AdequacyPatch::physicalAreaInsideAdqPatch: return wxT("inside"); break; default: @@ -134,7 +134,7 @@ IRenderer::CellStyle AdequacyPatchAreaGrid::cellStyle(int, int row) const case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: return IRenderer::cellStyleAdqPatchOutside; break; - case Data::AdequacyPatch::adqmPhysicalAreaInsideAdqPatch: + case Data::AdequacyPatch::physicalAreaInsideAdqPatch: return IRenderer::cellStyleAdqPatchInside; break; default: From 9eb3f140cff922ec5da79e74fad2e3bcc969018f Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 11:44:07 +0200 Subject: [PATCH 173/490] 1. do not modify Yuni library --- src/ext/yuni/src/yuni/core/math/math.h | 11 ----------- src/ext/yuni/src/yuni/core/math/math.hxx | 7 ------- src/solver/optimisation/adequacy_patch.cpp | 10 +++++++++- src/solver/optimisation/adequacy_patch.h | 11 +++++++++++ src/solver/simulation/economy.cpp | 2 +- 5 files changed, 21 insertions(+), 20 deletions(-) diff --git a/src/ext/yuni/src/yuni/core/math/math.h b/src/ext/yuni/src/yuni/core/math/math.h index 96aa08ee33..9fbbee4b8b 100644 --- a/src/ext/yuni/src/yuni/core/math/math.h +++ b/src/ext/yuni/src/yuni/core/math/math.h @@ -387,17 +387,6 @@ YUNI_DECL bool IsInteger(T x); template YUNI_DECL U GCD(U u, V v); -/*! -** ** \brief Sums two arrays of the same size a[i]=a[i]+b[i] -** ** -** ** \param a An array -** ** \param b An array -** ** \param num An integer -** ** \return -** */ -template -void sumTwoArrays(T* a, T* b, int num); - } // namespace Math } // namespace Yuni diff --git a/src/ext/yuni/src/yuni/core/math/math.hxx b/src/ext/yuni/src/yuni/core/math/math.hxx index d95c20c9e4..e896abc803 100644 --- a/src/ext/yuni/src/yuni/core/math/math.hxx +++ b/src/ext/yuni/src/yuni/core/math/math.hxx @@ -636,13 +636,6 @@ inline U GCD(U u, V v) return u; } -template -void sumTwoArrays(T* a, T* b, int num) -{ - for (uint i = 0; i < num; ++i) - a[i] += b[i]; -} - } // namespace Math } // namespace Yuni diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index e0864dcccc..d28bd92ac9 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -252,4 +252,12 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo densNew = Math::Max(0.0, ensInit + netPositionInit); return std::make_pair(netPositionInit, densNew); -} \ No newline at end of file +} + +template +void sumTwoArrays(T* a, T* b, int num) +{ + for (uint i = 0; i < num; ++i) + a[i] += b[i]; +} +template void sumTwoArrays(double* a, double* b, int num); \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 93cdea04e7..fd9875e141 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -103,4 +103,15 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h */ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); +/*! +** ** \brief Sums two arrays of the same size a[i]=a[i]+b[i] +** ** +** ** \param a An array +** ** \param b An array +** ** \param num An integer +** ** \return +** */ +template +extern void sumTwoArrays(T* a, T* b, int num); + #endif /* __SOLVER_ADEQUACY_FUNCTIONS_H__ */ diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index b6531666fc..d34855fef0 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -152,7 +152,7 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, { if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - Math::sumTwoArrays( + sumTwoArrays( sumENS, pProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive, nbHoursInAWeek); From 228d7b583b5dee183aab19c40df28a5f2874361a Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 12:13:30 +0200 Subject: [PATCH 174/490] 3. AdequacyPatchPTO name change --- src/libs/antares/study/fwd.h | 8 ++++---- src/libs/antares/study/parameters.cpp | 14 +++++++------- src/libs/antares/study/parameters.h | 2 +- .../opt_gestion_des_couts_cas_quadratique.cpp | 2 +- .../simulation/sim_structure_probleme_economique.h | 2 +- .../adequacy-patch/adequacy-patch-options.cpp | 14 +++++++------- 6 files changed, 21 insertions(+), 21 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 460f4117a8..13dbdf0dca 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -597,14 +597,14 @@ enum ntcSetToZeroStatus_AdqPatchStep1 /*! ** \brief Types of Price Taking Order (PTO) for Adequacy Patch */ -enum AdequacyPatchPTO +enum AdqPatchPTO { //! PTO is DENS - adqPatchPTOIsDens = 0, + isDens = 0, //! PTO is Load - adqPatchPTOIsLoad + isLoad -}; // enum AdequacyPatchPTO +}; // enum AdqPatchPTO enum AdqPatchThresholdsIndex { diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 624ee52cad..6a6847cbdd 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -177,19 +177,19 @@ const char* StudyModeToCString(StudyMode mode) } return "Unknown"; } -bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdequacyPatchPTO& out) +bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdqPatchPTO& out) { CString<24, false> s = text; s.trim(); s.toLower(); if (s == "dens") { - out = AdequacyPatch::adqPatchPTOIsDens; + out = AdequacyPatch::isDens; return true; } if (s == "load") { - out = AdequacyPatch::adqPatchPTOIsLoad; + out = AdequacyPatch::isLoad; return true; } @@ -198,13 +198,13 @@ bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdequacyPatc return false; } -const char* PriceTakingOrderToString(AdequacyPatch::AdequacyPatchPTO pto) +const char* PriceTakingOrderToString(AdequacyPatch::AdqPatchPTO pto) { switch (pto) { - case AdequacyPatch::adqPatchPTOIsDens: + case AdequacyPatch::isDens: return "DENS"; - case AdequacyPatch::adqPatchPTOIsLoad: + case AdequacyPatch::isLoad: return "Load"; } return ""; @@ -360,7 +360,7 @@ void Parameters::reset() include.adequacyPatch = false; setToZeroNTCfromOutToIn_AdqPatch = true; setToZeroNTCfromOutToOut_AdqPatch = true; - adqPatchPriceTakingOrder = AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsDens; + adqPatchPriceTakingOrder = AdequacyPatch::AdqPatchPTO::isDens; adqPatchSaveIntermediateResults = false; resetSeedsAdqPatch(); diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index dcb5b62575..fceb755dbe 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -517,7 +517,7 @@ class Parameters final //! set to null (if true) only in the first step of adequacy patch local matching rule. bool setToZeroNTCfromOutToOut_AdqPatch; //! PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. - AdequacyPatch::AdequacyPatchPTO adqPatchPriceTakingOrder; + AdequacyPatch::AdqPatchPTO adqPatchPriceTakingOrder; //! Select whether the intermediate result before the application of the curtailment sharing is //! to be kept in the results bool adqPatchSaveIntermediateResults; 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 27fed05eae..499e631925 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -92,7 +92,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { if (ProblemeHebdo->adqPatch->PriceTakingOrder - == Data::AdequacyPatch::adqPatchPTOIsLoad) + == Data::AdequacyPatch::isLoad) { priceTakingOrders = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 53737da5b0..0b2a891e4c 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -503,7 +503,7 @@ struct AdequacyPatchParameters bool setToZeroNTCfromOutToIn_AdqPatchStep1; bool setToZeroNTCbetweenOutsideAreas_AdqPatchStep1; bool SaveIntermediateResults; - AdequacyPatchPTO PriceTakingOrder; + AdqPatchPTO PriceTakingOrder; float ThresholdInitiateCurtailmentSharingRule; float ThresholdDisplayLocalMatchingRuleViolations; }; 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 3457eb1ad1..95721139f1 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 @@ -74,10 +74,10 @@ static void ResetButtonNTC(Component::Button* button, bool value) } } -static void ResetButtonPTO(Component::Button* button, Data::AdequacyPatch::AdequacyPatchPTO value) +static void ResetButtonPTO(Component::Button* button, Data::AdequacyPatch::AdqPatchPTO value) { assert(button != NULL); - if (value == Data::AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsLoad) + if (value == Data::AdequacyPatch::AdqPatchPTO::isLoad) { button->image("images/16x16/tag.png"); button->caption(wxT("Load")); @@ -321,7 +321,7 @@ void AdequacyPatchOptions::onResetToDefault(void*) study.parameters.setToZeroNTCfromOutToIn_AdqPatch = true; study.parameters.setToZeroNTCfromOutToOut_AdqPatch = true; study.parameters.adqPatchPriceTakingOrder - = Data::AdequacyPatch::AdequacyPatchPTO::adqPatchPTOIsDens; + = Data::AdequacyPatch::AdqPatchPTO::isDens; study.parameters.adqPatchSaveIntermediateResults = false; study.parameters.resetSeedsAdqPatch(); @@ -491,9 +491,9 @@ void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPatchPTOIsDens) + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::isDens) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPatchPTOIsDens; + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::isDens; refresh(); MarkTheStudyAsModified(); } @@ -505,9 +505,9 @@ void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::adqPatchPTOIsLoad) + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::isLoad) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::adqPatchPTOIsLoad; + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::isLoad; refresh(); MarkTheStudyAsModified(); } From a769d79a49127c22ef79e47ab1737658fceb1b8a Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 12:19:51 +0200 Subject: [PATCH 175/490] 3. update --- src/libs/antares/study/parameters.cpp | 8 ++++---- .../opt_gestion_des_couts_cas_quadratique.cpp | 2 +- .../options/adequacy-patch/adequacy-patch-options.cpp | 8 ++++---- 3 files changed, 9 insertions(+), 9 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 6a6847cbdd..ea769f8355 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -184,12 +184,12 @@ bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdqPatchPTO& s.toLower(); if (s == "dens") { - out = AdequacyPatch::isDens; + out = AdequacyPatch::AdqPatchPTO::isDens; return true; } if (s == "load") { - out = AdequacyPatch::isLoad; + out = AdequacyPatch::AdqPatchPTO::isLoad; return true; } @@ -202,9 +202,9 @@ const char* PriceTakingOrderToString(AdequacyPatch::AdqPatchPTO pto) { switch (pto) { - case AdequacyPatch::isDens: + case AdequacyPatch::AdqPatchPTO::isDens: return "DENS"; - case AdequacyPatch::isLoad: + case AdequacyPatch::AdqPatchPTO::isLoad: return "Load"; } 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 499e631925..67187e1fd8 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -92,7 +92,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { if (ProblemeHebdo->adqPatch->PriceTakingOrder - == Data::AdequacyPatch::isLoad) + == Data::AdequacyPatch::AdqPatchPTO::isLoad) { priceTakingOrders = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] 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 95721139f1..b3e2055887 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 @@ -491,9 +491,9 @@ void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::isDens) + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::AdqPatchPTO::isDens) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::isDens; + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; refresh(); MarkTheStudyAsModified(); } @@ -505,9 +505,9 @@ void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::isLoad) + if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::AdqPatchPTO::isLoad) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::isLoad; + study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isLoad; refresh(); MarkTheStudyAsModified(); } From 204a9b0165d8a7ad784fd1b8f11eff6305d489a6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 14:23:44 +0200 Subject: [PATCH 176/490] 2-8. replace seeds with two thresholds --- src/libs/antares/study/fwd.h | 9 -- src/libs/antares/study/parameters.cpp | 27 ++--- src/libs/antares/study/parameters.h | 8 +- .../simulation/sim_calcul_economique.cpp | 4 +- .../adequacy-patch/adequacy-patch-options.cpp | 105 ++++++++++-------- .../adequacy-patch/adequacy-patch-options.h | 5 +- 6 files changed, 80 insertions(+), 78 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 13dbdf0dca..9dfb3100c3 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -606,15 +606,6 @@ enum AdqPatchPTO }; // enum AdqPatchPTO -enum AdqPatchThresholdsIndex -{ - //! Threshold to initiate curtailment sharing rule - adqPatchThresholdInitiateCurtailmentSharingRule = 0, - //! Threshold to display Local Matching Rule violations - adqPatchThresholdDisplayLocalMatchingRuleViolations, - adqPatchThresholdsMax -}; - //! A default threshold value for initiate curtailment sharing rule const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 500.0; //! A default threshold value for display local matching rule violations diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index ea769f8355..34f7bc6eab 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -233,13 +233,13 @@ void Parameters::resetSeeds() for (auto i = (uint)seedTsGenLoad; i != seedMax; ++i) seed[i] = (s += increment); } -void Parameters::resetSeedsAdqPatch() +void Parameters::resetThresholdsAdqPatch() { - // Initialize all seeds/threshold values for adequacy patch - seedAdqPatch[adqPatchThresholdInitiateCurtailmentSharingRule] - = (float)adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule; - seedAdqPatch[adqPatchThresholdDisplayLocalMatchingRuleViolations] - = (float)adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; + // Initialize all thresholds values for adequacy patch + adqPatchThresholdInitiateCurtailmentSharingRule + = adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule; + adqPatchThresholdDisplayLocalMatchingRuleViolations + = adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; } void Parameters::reset() @@ -362,7 +362,7 @@ void Parameters::reset() setToZeroNTCfromOutToOut_AdqPatch = true; adqPatchPriceTakingOrder = AdequacyPatch::AdqPatchPTO::isDens; adqPatchSaveIntermediateResults = false; - resetSeedsAdqPatch(); + resetThresholdsAdqPatch(); // Initialize all seeds resetSeeds(); @@ -678,11 +678,9 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, return StringToPriceTakingOrder(value, d.adqPatchPriceTakingOrder); // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") - return value.to( - d.seedAdqPatch[AdequacyPatch::adqPatchThresholdInitiateCurtailmentSharingRule]); + return value.to(d.adqPatchThresholdInitiateCurtailmentSharingRule); if (key == "threshold-display-local-matching-rule-violations") - return value.to( - d.seedAdqPatch[AdequacyPatch::adqPatchThresholdDisplayLocalMatchingRuleViolations]); + return value.to(d.adqPatchThresholdDisplayLocalMatchingRuleViolations); return false; } @@ -1805,10 +1803,9 @@ void Parameters::saveToINI(IniFile& ini) const section->add("price-taking-order", PriceTakingOrderToString(adqPatchPriceTakingOrder)); // Threshholds section->add("threshold-initiate-curtailment-sharing-rule", - seedAdqPatch[AdequacyPatch::adqPatchThresholdInitiateCurtailmentSharingRule]); - section->add( - "threshold-display-local-matching-rule-violations", - seedAdqPatch[AdequacyPatch::adqPatchThresholdDisplayLocalMatchingRuleViolations]); + adqPatchThresholdInitiateCurtailmentSharingRule); + section->add("threshold-display-local-matching-rule-violations", + adqPatchThresholdDisplayLocalMatchingRuleViolations); } // Other preferences diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index fceb755dbe..f649466434 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -141,7 +141,7 @@ class Parameters final /*! ** \brief Reset to default all seeds/threshold values in adequacy patch */ - void resetSeedsAdqPatch(); + void resetThresholdsAdqPatch(); /*! ** \brief Try to detect then fix any bad value @@ -521,8 +521,10 @@ class Parameters final //! Select whether the intermediate result before the application of the curtailment sharing is //! to be kept in the results bool adqPatchSaveIntermediateResults; - //! threshold values for adequacy patch - float seedAdqPatch[AdequacyPatch::adqPatchThresholdsMax]; + //! Threshold to initiate curtailment sharing rule + float adqPatchThresholdInitiateCurtailmentSharingRule; + //! Threshold to display Local Matching Rule violations + float adqPatchThresholdDisplayLocalMatchingRuleViolations; //! \name Scenariio Builder - Rules //@{ diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 1a5dec4d89..d4a7ed194c 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -74,9 +74,9 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.adqPatch->SaveIntermediateResults = parameters.adqPatchSaveIntermediateResults; problem.adqPatch->PriceTakingOrder = parameters.adqPatchPriceTakingOrder; problem.adqPatch->ThresholdInitiateCurtailmentSharingRule - = parameters.seedAdqPatch[adqPatchThresholdInitiateCurtailmentSharingRule]; + = parameters.adqPatchThresholdInitiateCurtailmentSharingRule; problem.adqPatch->ThresholdDisplayLocalMatchingRuleViolations - = parameters.seedAdqPatch[adqPatchThresholdDisplayLocalMatchingRuleViolations]; + = parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations; } if (parameters.include.adequacyPatch){ 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 b3e2055887..efc70bacd3 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 @@ -104,21 +104,6 @@ static void ResetButtonSpecify(Component::Button* button, bool value) } } -const char* AdqPatchSeedToCString(Data::AdequacyPatch::AdqPatchThresholdsIndex seed) -{ - switch (seed) - { - case Data::AdequacyPatch::adqPatchThresholdInitiateCurtailmentSharingRule: - return "Initiate curtailment sharing rule"; - case Data::AdequacyPatch::adqPatchThresholdDisplayLocalMatchingRuleViolations: - return "Display local matching rule violations"; - case Data::AdequacyPatch::adqPatchThresholdsMax: - return ""; - } - return ""; -} - - AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : wxDialog(parent, wxID_ANY, @@ -231,18 +216,20 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : pBtnAdequacyPatchSaveIntermediateResults = button; } addLabelAdqPatch(this, s, wxT("Thresholds")); - // Seeds/threshold values - for (uint i = 0; i != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++i) - pEditSeeds[i] = nullptr; - - for (uint seed = 0; seed != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++seed) + // Threshold values { - pEditSeeds[seed] + pThresholdCSRStart = nullptr; + pThresholdLMRviolations = nullptr; + pThresholdCSRStart + = insertEdit(this, + s, + wxStringFromUTF8("Initiate curtailment sharing rule"), + wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); + pThresholdLMRviolations = insertEdit(this, s, - wxStringFromUTF8( - AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdsIndex)seed)), - wxCommandEventHandler(AdequacyPatchOptions::onEditSeedTSDraws)); + wxStringFromUTF8("Display local matching rule violations"), + wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); } { @@ -323,7 +310,7 @@ void AdequacyPatchOptions::onResetToDefault(void*) study.parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; study.parameters.adqPatchSaveIntermediateResults = false; - study.parameters.resetSeedsAdqPatch(); + study.parameters.resetThresholdsAdqPatch(); refresh(); MarkTheStudyAsModified(); @@ -358,11 +345,14 @@ void AdequacyPatchOptions::refresh() // Save intermediate results for adequacy patch ResetButtonSpecify(pBtnAdequacyPatchSaveIntermediateResults, study.parameters.adqPatchSaveIntermediateResults); - //Threshold values - for (uint seed = 0; seed != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++seed) + // Threshold values { - if (pEditSeeds[seed]) - pEditSeeds[seed]->SetValue(wxString() << study.parameters.seedAdqPatch[seed]); + if (pThresholdCSRStart) + pThresholdCSRStart->SetValue( + wxString() << study.parameters.adqPatchThresholdInitiateCurtailmentSharingRule); + if (pThresholdLMRviolations) + pThresholdLMRviolations->SetValue( + wxString() << study.parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations); } } @@ -529,7 +519,7 @@ wxTextCtrl* AdequacyPatchOptions::insertEdit(wxWindow* parent, return edit; } -void AdequacyPatchOptions::onEditSeedTSDraws(wxCommandEvent& evt) +void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) { if (not Data::Study::Current::Valid()) return; @@ -537,30 +527,51 @@ void AdequacyPatchOptions::onEditSeedTSDraws(wxCommandEvent& evt) int id = evt.GetId(); - // Looking for the good id - for (uint i = 0; i != (uint)Data::AdequacyPatch::adqPatchThresholdsMax; ++i) + if (pThresholdCSRStart && id == pThresholdCSRStart->GetId()) { - if (pEditSeeds[i] && id == pEditSeeds[i]->GetId()) - { - String text; - wxStringToString(pEditSeeds[i]->GetValue(), text); + String text; + wxStringToString(pThresholdCSRStart->GetValue(), text); - float newseed; - if (not text.to(newseed)) + float newthreshold; + if (not text.to(newthreshold)) + { + logs.error() << "impossible to update the seed for '" + << "Initiate curtailment sharing rule" + << "'"; + } + else + { + if (newthreshold != study.parameters.adqPatchThresholdInitiateCurtailmentSharingRule) { - logs.error() << "impossible to update the seed for '" - << AdqPatchSeedToCString((Data::AdequacyPatch::AdqPatchThresholdsIndex)i) << "'"; + study.parameters.adqPatchThresholdInitiateCurtailmentSharingRule = newthreshold; + MarkTheStudyAsModified(); } - else + } + return; + } + + if (pThresholdLMRviolations && id == pThresholdLMRviolations->GetId()) + { + String text; + wxStringToString(pThresholdLMRviolations->GetValue(), text); + + float newthreshold; + if (not text.to(newthreshold)) + { + logs.error() << "impossible to update the seed for '" + << "Display local matching rule violations" + << "'"; + } + else + { + if (newthreshold + != study.parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations) { - if (newseed != study.parameters.seedAdqPatch[i]) - { - study.parameters.seedAdqPatch[i] = newseed; - MarkTheStudyAsModified(); - } + study.parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations = newthreshold; + MarkTheStudyAsModified(); } - return; } + return; } } 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 4d498458bb..f828b2fe01 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 @@ -88,14 +88,15 @@ class AdequacyPatchOptions final : public wxDialog void onPopupMenuPTO(Component::Button&, wxMenu& menu, void*); void onInternalMotion(wxMouseEvent&); - void onEditSeedTSDraws(wxCommandEvent&); + void onEditThresholds(wxCommandEvent&); private: Component::Button* pBtnAdequacyPatch; Component::Button* pBtnNTCfromOutToInAdqPatch; Component::Button* pBtnNTCfromOutToOutAdqPatch; Component::Button* pBtnAdequacyPatchPTO; Component::Button* pBtnAdequacyPatchSaveIntermediateResults; - wxTextCtrl* pEditSeeds[Data::AdequacyPatch::adqPatchThresholdsMax]; + wxTextCtrl* pThresholdCSRStart; + wxTextCtrl* pThresholdLMRviolations; bool* pTargetRef; }; // class AdequacyPatchOptions From f11a428b3e001df3a269c779a60337c5fd832989 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 14:48:21 +0200 Subject: [PATCH 177/490] 9. resetAdqPatchParameters --- src/libs/antares/study/parameters.cpp | 17 +++++++++++------ src/libs/antares/study/parameters.h | 6 +++++- 2 files changed, 16 insertions(+), 7 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 34f7bc6eab..5ba5b3ced8 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -242,6 +242,16 @@ void Parameters::resetThresholdsAdqPatch() = adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; } +void Parameters::resetAdqPatchParameters() +{ + include.adequacyPatch = false; + setToZeroNTCfromOutToIn_AdqPatch = true; + setToZeroNTCfromOutToOut_AdqPatch = true; + adqPatchPriceTakingOrder = AdequacyPatch::AdqPatchPTO::isDens; + adqPatchSaveIntermediateResults = false; + resetThresholdsAdqPatch(); +} + void Parameters::reset() { // Mode @@ -357,12 +367,7 @@ void Parameters::reset() ortoolsEnumUsed = OrtoolsSolver::sirius; // Adequacy patch - include.adequacyPatch = false; - setToZeroNTCfromOutToIn_AdqPatch = true; - setToZeroNTCfromOutToOut_AdqPatch = true; - adqPatchPriceTakingOrder = AdequacyPatch::AdqPatchPTO::isDens; - adqPatchSaveIntermediateResults = false; - resetThresholdsAdqPatch(); + resetAdqPatchParameters(); // Initialize all seeds resetSeeds(); diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index f649466434..478c91f60d 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -139,9 +139,13 @@ class Parameters final */ void resetSeeds(); /*! - ** \brief Reset to default all seeds/threshold values in adequacy patch + ** \brief Reset to default all threshold values in adequacy patch */ void resetThresholdsAdqPatch(); + /*! + ** \brief Reset to default all adequacy patch values + */ + void resetAdqPatchParameters(); /*! ** \brief Try to detect then fix any bad value From 318f30b9d71c7f9dc36dfcc268ac10c4aa12b357 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 15:03:49 +0200 Subject: [PATCH 178/490] 10. re-name lmrViolations.h --- src/solver/cmake/variable.cmake | 2 +- src/solver/variable/economy/all.h | 2 +- .../economy/{lmrViolations.h => localMatchingRuleViolations.h} | 0 3 files changed, 2 insertions(+), 2 deletions(-) rename src/solver/variable/economy/{lmrViolations.h => localMatchingRuleViolations.h} (100%) diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 2ff2c6e039..da7f07d395 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -130,7 +130,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/hydroCost.h variable/economy/unsupliedEnergy.h variable/economy/domesticUnsuppliedEnergy.h - variable/economy/lmrViolations.h + variable/economy/localMatchingRuleViolations.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 4598b87479..0ca677f418 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -60,7 +60,7 @@ #include "hydroCost.h" #include "unsupliedEnergy.h" #include "domesticUnsuppliedEnergy.h" -#include "lmrViolations.h" +#include "localMatchingRuleViolations.h" #include "spilledEnergy.h" #include "lold.h" diff --git a/src/solver/variable/economy/lmrViolations.h b/src/solver/variable/economy/localMatchingRuleViolations.h similarity index 100% rename from src/solver/variable/economy/lmrViolations.h rename to src/solver/variable/economy/localMatchingRuleViolations.h From e2749f4fdd7be9798934671ea2613314c9984e09 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 15:15:30 +0200 Subject: [PATCH 179/490] 25-26. re-name AdequacyPatchConfigure to AdequacyPatchOptions --- src/ui/simulator/application/main/internal-ids.h | 2 +- src/ui/simulator/application/main/main.cpp | 4 ++-- src/ui/simulator/application/main/main.h | 2 +- src/ui/simulator/application/main/menu.cpp | 2 +- src/ui/simulator/application/main/options.cpp | 2 +- 5 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/ui/simulator/application/main/internal-ids.h b/src/ui/simulator/application/main/internal-ids.h index f14dfbd44a..d943fc8b88 100644 --- a/src/ui/simulator/application/main/internal-ids.h +++ b/src/ui/simulator/application/main/internal-ids.h @@ -134,7 +134,7 @@ enum MenusID mnIDOptionConfigureMCScenarioPlaylist, mnIDOptionOptimizationPrefs, mnIDOptionAdvanced, - mnIDOptionAdequacyPatchConfigure, + mnIDOptionAdequacyPatchOptions, mnIDOptionAdequacyPatchAreas, //@} diff --git a/src/ui/simulator/application/main/main.cpp b/src/ui/simulator/application/main/main.cpp index b25831510d..e598716caf 100644 --- a/src/ui/simulator/application/main/main.cpp +++ b/src/ui/simulator/application/main/main.cpp @@ -159,7 +159,7 @@ EVT_MENU(mnIDOptionConfigureMCScenarioPlaylist, ApplWnd::evtOnOptionsMCPlaylist) EVT_MENU(mnIDOptionConfigureMCScenarioBuilder, ApplWnd::evtOnOptionsMCScenarioBuilder) EVT_MENU(mnIDOptionOptimizationPrefs, ApplWnd::evtOnOptionsOptimizationPrefs) EVT_MENU(mnIDOptionAdvanced, ApplWnd::evtOnOptionsAdvanced) -EVT_MENU(mnIDOptionAdequacyPatchConfigure, ApplWnd::evtOnOptionsAdequacyPatchConfigure) +EVT_MENU(mnIDOptionAdequacyPatchOptions, ApplWnd::evtOnOptionsAdequacyPatchOptions) EVT_MENU(mnIDOptionAdequacyPatchAreas, ApplWnd::evtOnOptionsAdequacyPatchAreas) // Window @@ -519,7 +519,7 @@ void ApplWnd::evtOnUpdateGUIAfterStudyIO(bool opened) EnableItem(menu, mnIDOptionConfigureMCScenarioPlaylist, opened); EnableItem(menu, mnIDOptionOptimizationPrefs, opened); EnableItem(menu, mnIDOptionAdvanced, opened); - EnableItem(menu, mnIDOptionAdequacyPatchConfigure, opened); + EnableItem(menu, mnIDOptionAdequacyPatchOptions, opened); EnableItem(menu, mnIDOptionAdequacyPatchAreas, opened); EnableItem(menu, mnIDInspector, opened); diff --git a/src/ui/simulator/application/main/main.h b/src/ui/simulator/application/main/main.h index c8cda54296..6376712280 100644 --- a/src/ui/simulator/application/main/main.h +++ b/src/ui/simulator/application/main/main.h @@ -575,7 +575,7 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent //! Advanced parameters void evtOnOptionsAdvanced(wxCommandEvent& evt); //! Adequacy Patch Configure - void evtOnOptionsAdequacyPatchConfigure(wxCommandEvent& evt); + void evtOnOptionsAdequacyPatchOptions(wxCommandEvent& evt); //! Adequacy Patch Areas void evtOnOptionsAdequacyPatchAreas(wxCommandEvent& evt); //@} diff --git a/src/ui/simulator/application/main/menu.cpp b/src/ui/simulator/application/main/menu.cpp index 514d78cdec..2a1fb2e629 100644 --- a/src/ui/simulator/application/main/menu.cpp +++ b/src/ui/simulator/application/main/menu.cpp @@ -469,7 +469,7 @@ wxMenu* ApplWnd::createMenuOptions() wxMenu* adqPatchSubMenu = pMenuAdequacyPatch->GetSubMenu(); Menu::CreateItem(adqPatchSubMenu, - mnIDOptionAdequacyPatchConfigure, + mnIDOptionAdequacyPatchOptions, wxT("Options"), "images/16x16/filter.png", wxT("Adequacy Patch Options")); diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index 73812f4cbe..4f52f51864 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -126,7 +126,7 @@ void ApplWnd::evtOnOptionsAdvanced(wxCommandEvent&) Dispatcher::GUI::CreateAndShowModal(this); } -void ApplWnd::evtOnOptionsAdequacyPatchConfigure(wxCommandEvent&) +void ApplWnd::evtOnOptionsAdequacyPatchOptions(wxCommandEvent&) { Forms::Disabler disabler(*this); if (Data::Study::Current::Valid()) From 5694fb1a9f56331073003fa3ee2d5389193bfb1d Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 15:21:35 +0200 Subject: [PATCH 180/490] 27. cellValue change --- .../datagrid/renderer/adequacy-patch-area-grid.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) 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 3d708545e0..58f23bfebd 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 @@ -51,9 +51,9 @@ bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) s.trim(); s.toLower(); - bool vir = s == "0" || s == "virtual" || s == "virtual area"; - bool ins = s.to() == 2 || s == "inside" || s == "physical area inside patch"; - bool out = s.to() == 1 || s == "outside" || s == "physical area outside patch"; + bool vir = s == "0" || s == "virtual" || s == "v"; + bool ins = s.to() == 2 || s == "inside" || s == "i"; + bool out = s.to() == 1 || s == "outside" || s == "o"; if (vir) study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::virtualArea; From cb37dc6f48071ffcb49d6bc0546fa8174842f98f Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 15:40:09 +0200 Subject: [PATCH 181/490] 28. is already implemented + small refacto --- .../adequacy-patch/adequacy-patch-options.cpp | 19 ++++++------------- 1 file changed, 6 insertions(+), 13 deletions(-) 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 efc70bacd3..9a3f08dce4 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 @@ -39,6 +39,7 @@ #include using namespace Yuni; +using namespace Data::AdequacyPatch; namespace Antares { @@ -303,15 +304,7 @@ void AdequacyPatchOptions::onResetToDefault(void*) if (message.showModal() == Window::Message::btnContinue) { auto& study = *studyptr; - - study.parameters.include.adequacyPatch = false; - study.parameters.setToZeroNTCfromOutToIn_AdqPatch = true; - study.parameters.setToZeroNTCfromOutToOut_AdqPatch = true; - study.parameters.adqPatchPriceTakingOrder - = Data::AdequacyPatch::AdqPatchPTO::isDens; - study.parameters.adqPatchSaveIntermediateResults = false; - study.parameters.resetThresholdsAdqPatch(); - + study.parameters.resetAdqPatchParameters(); refresh(); MarkTheStudyAsModified(); return; @@ -481,9 +474,9 @@ void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::AdqPatchPTO::isDens) + if (study->parameters.adqPatchPriceTakingOrder != AdqPatchPTO::isDens) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; + study->parameters.adqPatchPriceTakingOrder = AdqPatchPTO::isDens; refresh(); MarkTheStudyAsModified(); } @@ -495,9 +488,9 @@ void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != Data::AdequacyPatch::AdqPatchPTO::isLoad) + if (study->parameters.adqPatchPriceTakingOrder != AdqPatchPTO::isLoad) { - study->parameters.adqPatchPriceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isLoad; + study->parameters.adqPatchPriceTakingOrder = AdqPatchPTO::isLoad; refresh(); MarkTheStudyAsModified(); } From 158913f325ab698bca68b5a268bff29899e56d30 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 16:04:26 +0200 Subject: [PATCH 182/490] small refacto --- .../windows/options/adequacy-patch/adequacy-patch-options.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 9a3f08dce4..f66384fb31 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 @@ -75,10 +75,10 @@ static void ResetButtonNTC(Component::Button* button, bool value) } } -static void ResetButtonPTO(Component::Button* button, Data::AdequacyPatch::AdqPatchPTO value) +static void ResetButtonPTO(Component::Button* button, AdqPatchPTO value) { assert(button != NULL); - if (value == Data::AdequacyPatch::AdqPatchPTO::isLoad) + if (value == AdqPatchPTO::isLoad) { button->image("images/16x16/tag.png"); button->caption(wxT("Load")); From 06116bb029e1e8b04483b2c4a590765458a45d0a Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 31 May 2022 16:43:55 +0200 Subject: [PATCH 183/490] 29. updateButton function --- .../adequacy-patch/adequacy-patch-options.cpp | 90 ++++++++++--------- 1 file changed, 49 insertions(+), 41 deletions(-) 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 f66384fb31..3b313e3430 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 @@ -60,48 +60,46 @@ static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* tex sizer->AddSpacer(5); } -static void ResetButtonNTC(Component::Button* button, bool value) +static void updateButton(Component::Button* button, bool value, std::string buttonType) { - assert(button != NULL); - if (value) - { - button->image("images/16x16/light_orange.png"); - button->caption(wxT("set to null")); - } - else - { - button->image("images/16x16/light_green.png"); - button->caption(wxT("local values")); - } -} + char type = (buttonType == "ntc") ? 'N' : ((buttonType == "pto") ? 'P' : 'S'); -static void ResetButtonPTO(Component::Button* button, AdqPatchPTO value) -{ - assert(button != NULL); - if (value == AdqPatchPTO::isLoad) - { - button->image("images/16x16/tag.png"); - button->caption(wxT("Load")); - } - else - { - button->image("images/16x16/tag.png"); - button->caption(wxT("DENS")); - } -} - -static void ResetButtonSpecify(Component::Button* button, bool value) -{ assert(button != NULL); if (value) { - button->image("images/16x16/light_green.png"); - button->caption(wxT("true")); + switch (type) + { + case 'N': + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to null")); + break; + case 'P': + button->image("images/16x16/tag.png"); + button->caption(wxT("Load")); + break; + default: + button->image("images/16x16/light_green.png"); + button->caption(wxT("true")); + break; + } } else { - button->image("images/16x16/light_orange.png"); - button->caption(wxT("false")); + switch (type) + { + case 'N': + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + break; + case 'P': + button->image("images/16x16/tag.png"); + button->caption(wxT("DENS")); + break; + default: + button->image("images/16x16/light_orange.png"); + button->caption(wxT("false")); + break; + } } } @@ -326,18 +324,28 @@ void AdequacyPatchOptions::refresh() auto& study = *studyptr; // Adequacy patch - ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.include.adequacyPatch); + std::string buttonType = "specify"; + // Include adequacy patch + updateButton(pBtnAdequacyPatch, study.parameters.include.adequacyPatch, buttonType); + // Save intermediate results for adequacy patch + updateButton(pBtnAdequacyPatchSaveIntermediateResults, + study.parameters.adqPatchSaveIntermediateResults, + buttonType); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - ResetButtonNTC(pBtnNTCfromOutToInAdqPatch, study.parameters.setToZeroNTCfromOutToIn_AdqPatch); + buttonType = "ntc"; + updateButton( + pBtnNTCfromOutToInAdqPatch, study.parameters.setToZeroNTCfromOutToIn_AdqPatch, buttonType); // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of // adequacy patch local matching rule. - ResetButtonNTC(pBtnNTCfromOutToOutAdqPatch, study.parameters.setToZeroNTCfromOutToOut_AdqPatch); + updateButton( + pBtnNTCfromOutToOutAdqPatch, study.parameters.setToZeroNTCfromOutToOut_AdqPatch, buttonType); // Price taking order (PTO) for adequacy patch - ResetButtonPTO(pBtnAdequacyPatchPTO, study.parameters.adqPatchPriceTakingOrder); - // Save intermediate results for adequacy patch - ResetButtonSpecify(pBtnAdequacyPatchSaveIntermediateResults, - study.parameters.adqPatchSaveIntermediateResults); + buttonType = "pto"; + bool isPTOload + = (study.parameters.adqPatchPriceTakingOrder == AdqPatchPTO::isLoad) ? true : false; + updateButton(pBtnAdequacyPatchPTO, isPTOload, buttonType); + // Threshold values { if (pThresholdCSRStart) From 4049c6b678b219336d9d43b7c9be58b4905d5286 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 1 Jun 2022 02:49:53 +0200 Subject: [PATCH 184/490] 13. renaming --- src/solver/simulation/economy.cpp | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index d34855fef0..8c0e3c023d 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -142,9 +142,9 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); } -void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, - std::set& triggerCsrSet) +std::set getHoursRequiringCurtailmentSharing(PROBLEME_HEBDO* pProblemeHebdo) { + std::set triggerCsrSet; float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; double sumENS[nbHoursInAWeek] = {0}; @@ -167,6 +167,7 @@ void InitiateCurtailmentSharingRuleIndexSet(PROBLEME_HEBDO* pProblemeHebdo, } } logs.debug() << "number of triggered hours: " << triggerCsrSet.size(); + return triggerCsrSet; } void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -236,13 +237,12 @@ bool Economy::year(Progression::Task& progression, OPT_OptimisationHebdomadaireAdqPatch( pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); - std::set hoursInWeekTriggerCsrSet; - InitiateCurtailmentSharingRuleIndexSet(pProblemesHebdo[numSpace], - hoursInWeekTriggerCsrSet); - if (hoursInWeekTriggerCsrSet.size() > 0) + std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(pProblemesHebdo[numSpace]); + + if (hoursRequiringCurtailmentSharing.size() > 0) { pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); - for (int hourInWeek : hoursInWeekTriggerCsrSet) + for (int hourInWeek : hoursRequiringCurtailmentSharing) { logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); From f070f23a530f0d0dec90b6d479660541d01abd02 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 1 Jun 2022 02:51:46 +0200 Subject: [PATCH 185/490] 14. refactoring --- src/solver/simulation/economy.cpp | 22 ++++++++++------------ 1 file changed, 10 insertions(+), 12 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 8c0e3c023d..6336157dba 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -239,20 +239,18 @@ bool Economy::year(Progression::Task& progression, std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(pProblemesHebdo[numSpace]); - if (hoursRequiringCurtailmentSharing.size() > 0) + pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); + for (int hourInWeek : hoursRequiringCurtailmentSharing) { - pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); - for (int hourInWeek : hoursRequiringCurtailmentSharing) - { - logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; - HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->hourlyCsrProblems.push_back(hourlyCsrProblem); - OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); - logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; - } - // UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); + logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; + HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); + pProblemesHebdo[numSpace]->hourlyCsrProblems.push_back(hourlyCsrProblem); + OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); + logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; } + // UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); + pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); + checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); } else From 1e09d198e7c65877a69f2f47c33344e43f4df90e Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 1 Jun 2022 02:53:00 +0200 Subject: [PATCH 186/490] 15. remove redundancy --- src/solver/simulation/economy.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 6336157dba..989b91ee5a 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -248,8 +248,6 @@ bool Economy::year(Progression::Task& progression, OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; } - // UpdateWeeklyResultAfterCSR(pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); } From 2a6569ca3be905c9b8cdb587b75990a1a468405c Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Wed, 1 Jun 2022 03:25:53 +0200 Subject: [PATCH 187/490] 16. refactoring --- src/solver/simulation/economy.cpp | 15 -------------- .../sim_structure_probleme_economique.h | 20 ------------------- 2 files changed, 35 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 989b91ee5a..d3fe4fbdb9 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -186,18 +186,6 @@ void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrP return; } -// void UpdateWeeklyResultAfterCSR(PROBLEME_HEBDO* pProblemeHebdo) -// { -// std::vector hourlyCsrProblems = pProblemeHebdo->hourlyCsrProblems; - -// for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) -// { -// RESULTATS_HORAIRES* ResultatsHoraires = pProblemeHebdo->ResultatsHoraires[area]; -// //CSR todo update ResultatsHoraires for each area using hourlyCsrProblems -// } -// return; -// } - bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, @@ -239,14 +227,11 @@ bool Economy::year(Progression::Task& progression, std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->hourlyCsrProblems.clear(); for (int hourInWeek : hoursRequiringCurtailmentSharing) { logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); - pProblemesHebdo[numSpace]->hourlyCsrProblems.push_back(hourlyCsrProblem); OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); - logs.debug() << "========= [CSR]: End hourly optim for " << hourInWeek; } checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 0b2a891e4c..f5d3bd2b9f 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -616,8 +616,6 @@ struct PROBLEME_HEBDO /* Adequacy Patch */ std::unique_ptr adqPatch = nullptr; AdequacyPatchRuntimeData adequacyPatchRuntimeData; - std::vector - hourlyCsrProblems; // CSR: this should be an array for the hours triggered CSR //std::map> localMatchingRuleViolation; optimizationStatistics optimizationStatistics_object; @@ -722,12 +720,6 @@ struct PROBLEME_HEBDO double maxPminThermiqueByDay[366]; }; -class HOURLY_CSR_RESULT -{ - // CSR todo: shall we create a new HOURLY_CSR_RESULT structure, or do we update directly inside - // RESULTATS_HORAIRES? -}; - // hourly CSR problem structure class HOURLY_CSR_PROBLEM { @@ -748,18 +740,6 @@ class HOURLY_CSR_PROBLEM std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; - - /* variables */ - // std::vector ENS; //CSR todo if we reuse pProblemesHebdo, there will be no need to - // create variables inside HOURLY_CSR_PROBLEM - - /* Results */ - HOURLY_CSR_RESULT hourlyResult; // CSR todo: shall we create a new HOURLY_CSR_RESULT structure, - // or do we update directly inside RESULTATS_HORAIRES? - - // CSR todo: there should be structures for building the optimization problem like: - // CORRESPONDANCES_DES_VARIABLES* - // CORRESPONDANCES_DES_CONTRAINTES* }; #endif From 07434c2be175e7d0f536550e4f87b913cb69c697 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Jun 2022 17:26:34 +0200 Subject: [PATCH 188/490] 20. separate LHS to functions --- ...atrice_des_contraintes_cas_quadratique.cpp | 95 ++++++++++++++++--- 1 file changed, 80 insertions(+), 15 deletions(-) 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 index a622e64ce3..089106ea22 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -94,29 +94,20 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* MemFree(Colonne); } -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setConstraintsOnENS(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) { - logs.debug() << "[CSR] constraint list:"; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Area; int Var; int NombreDeTermes; - double* Pi; - int* Colonne; - int Interco; - COUTS_DE_TRANSPORT* TransportCost; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; std::string NomDeLaContrainte; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); - Colonne = (int*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(int)); - - ProblemeAResoudre->NombreDeContraintes = 0; - ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // constraint: ENS < DENS_new @@ -141,6 +132,24 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '<', NomDeLaContrainte); } } +} + +void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Var; + int NombreDeTermes; + int Interco; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + std::string NomDeLaContrainte; + COUTS_DE_TRANSPORT* TransportCost; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of // type 2. @@ -189,6 +198,24 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); } } +} + +void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Area; + int Var; + int NombreDeTermes; + int Interco; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + std::string NomDeLaContrainte; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // constraint: // ENS(node A) + @@ -197,7 +224,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - // todo after debugging transfer this into same area loop as ENS for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] @@ -284,10 +310,27 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); } } +} +void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Var; + int NombreDeTermes; + int Interco; int NbInterco; double Poids; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + std::string NomDeLaContrainte; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + // Special case of the binding constraints for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) @@ -352,6 +395,28 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( } } } +} + +void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] constraint list:"; + double* Pi; + int* Colonne; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); + Colonne = (int*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(int)); + + ProblemeAResoudre->NombreDeContraintes = 0; + ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; + + setConstraintsOnENS(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + setConstraintsOnFlows(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + setNodeBalanceConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + setBindingConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); MemFree(Pi); MemFree(Colonne); From 864f3343468f10970ac57d802cf33e22c38e524c Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Jun 2022 18:03:32 +0200 Subject: [PATCH 189/490] 20. separate RHS to functions --- ..._gestion_second_membre_cas_quadratique.cpp | 223 +++++++++++++++++- 1 file changed, 214 insertions(+), 9 deletions(-) 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 e06a36dcab..bdd85300a7 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -48,15 +48,11 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme } } -void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setRHSvalueOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - logs.debug() << "[CSR] RHS: "; int Cnt; int Area; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - COUTS_DE_TRANSPORT* TransportCost; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; // constraint for each area inside adq patch: ENS < DENS_new @@ -73,6 +69,14 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } } +} + +void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Cnt; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + COUTS_DE_TRANSPORT* TransportCost; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of // type 2. @@ -99,6 +103,14 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; } } +} + +void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Cnt; + int Area; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; // constraint: // ENS(node A) + @@ -107,7 +119,6 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - // todo after debugging transfer this into same area loop as ENS for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] @@ -124,22 +135,31 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob << ")"; } } +} - // constraint: - // user defined Binding constraints between transmission flows - // and/or power generated from generating units. +void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Cnt; + int Area; int CntCouplante; int Interco; int NbInterco; double Poids; double ValueOfFlow; int Index; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; double* SecondMembre = ProblemeAResoudre->SecondMembre; CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; std::map bingdingConstraintNumber = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; + // constraint: + // user defined Binding constraints between transmission flows + // and/or power generated from generating units. for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) { @@ -221,3 +241,188 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob } } } + +void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] RHS: "; + + setRHSvalueOnENS(ProblemeHebdo, hourlyCsrProblem); + setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); + setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); + setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); +} + +// void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, +// HOURLY_CSR_PROBLEM& hourlyCsrProblem) +// { +// logs.debug() << "[CSR] RHS: "; +// int Cnt; +// int Area; +// int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; +// PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; +// COUTS_DE_TRANSPORT* TransportCost; +// ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + +// // constraint for each area inside adq patch: ENS < DENS_new +// for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) +// { +// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] +// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) +// { +// std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); +// if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) +// Cnt = it->second; +// ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.densNewValues[Area]; +// logs.debug() << Cnt << ": ENS < DENS_new: RHS[" << Cnt +// << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; +// } +// } + +// // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of +// // type 2. +// for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) +// { +// if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] +// == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch +// && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] +// == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) +// { +// TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + +// std::map::iterator it +// = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); +// if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) +// Cnt = it->second; +// // CSR Todo? loop flow? +// // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) +// // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] +// // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; +// // else +// ProblemeAResoudre->SecondMembre[Cnt] = 0.; +// logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt +// << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; +// } +// } + +// // constraint: +// // ENS(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) +// // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) +// // for all areas inside adequacy patch + +// // todo after debugging transfer this into same area loop as ENS +// for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) +// { +// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] +// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) +// { +// std::map::iterator it +// = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); +// if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) +// Cnt = it->second; + +// ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; +// logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt +// << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area +// << ")"; +// } +// } + +// // constraint: +// // user defined Binding constraints between transmission flows +// // and/or power generated from generating units. +// int CntCouplante; +// int Interco; +// int NbInterco; +// double Poids; +// double ValueOfFlow; +// int Index; +// double* SecondMembre = ProblemeAResoudre->SecondMembre; +// CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; +// CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; +// std::map bingdingConstraintNumber +// = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; + +// for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; +// CntCouplante++) +// { +// if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) +// { +// MatriceDesContraintesCouplantes +// = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + +// Cnt = bingdingConstraintNumber[CntCouplante]; + +// // 1. The original RHS of bingding constraint +// SecondMembre[Cnt] +// = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; +// logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt +// << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante +// << ")"; + +// // 2. RHS part 2: flow other than 2<->2 +// NbInterco +// = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; +// for (Index = 0; Index < NbInterco; Index++) +// { +// Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; +// Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; + +// if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] +// != Data::AdequacyPatch::physicalAreaInsideAdqPatch +// || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] +// != Data::AdequacyPatch::physicalAreaInsideAdqPatch) +// { +// ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; +// SecondMembre[Cnt] -= ValueOfFlow * Poids; +// logs.debug() +// << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt +// << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" +// << ". Interco;" + std::to_string(Interco) << ". Between:[" +// << ProblemeHebdo +// ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] +// << "]-[" +// << ProblemeHebdo +// ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] +// << "]" +// << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; +// } +// } + +// // 3. RHS part 3: - cluster +// int NbClusters +// = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; +// int Area; +// int Palier; +// int IndexNumeroDuPalierDispatch; +// double ValueOfVar; +// PALIERS_THERMIQUES* PaliersThermiquesDuPays; + +// for (Index = 0; Index < NbClusters; Index++) +// { +// Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; +// PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; + +// IndexNumeroDuPalierDispatch +// = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; + +// Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques +// [IndexNumeroDuPalierDispatch]; +// Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; + +// ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] +// ->ProductionThermique[hour] +// ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; + +// SecondMembre[Cnt] -= ValueOfVar * Poids; +// logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt +// << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante +// << ")" +// << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids +// << ", ValueOfVar:" << ValueOfVar; +// } +// } +// } +// } From 900d3e8c24aa2134fc5946588167aa5d0b84adc0 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Jun 2022 18:04:34 +0200 Subject: [PATCH 190/490] clean --- ..._gestion_second_membre_cas_quadratique.cpp | 176 +----------------- 1 file changed, 1 insertion(+), 175 deletions(-) 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 bdd85300a7..f8a90bdfa1 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -251,178 +251,4 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); -} - -// void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, -// HOURLY_CSR_PROBLEM& hourlyCsrProblem) -// { -// logs.debug() << "[CSR] RHS: "; -// int Cnt; -// int Area; -// int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; -// PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; -// COUTS_DE_TRANSPORT* TransportCost; -// ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - -// // constraint for each area inside adq patch: ENS < DENS_new -// for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) -// { -// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] -// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// { -// std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); -// if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) -// Cnt = it->second; -// ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.densNewValues[Area]; -// logs.debug() << Cnt << ": ENS < DENS_new: RHS[" << Cnt -// << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; -// } -// } - -// // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of -// // type 2. -// for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) -// { -// if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] -// == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch -// && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] -// == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// { -// TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - -// std::map::iterator it -// = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); -// if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) -// Cnt = it->second; -// // CSR Todo? loop flow? -// // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) -// // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] -// // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; -// // else -// ProblemeAResoudre->SecondMembre[Cnt] = 0.; -// logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt -// << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; -// } -// } - -// // constraint: -// // ENS(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) -// // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) -// // for all areas inside adequacy patch - -// // todo after debugging transfer this into same area loop as ENS -// for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) -// { -// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] -// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// { -// std::map::iterator it -// = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); -// if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) -// Cnt = it->second; - -// ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; -// logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt -// << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area -// << ")"; -// } -// } - -// // constraint: -// // user defined Binding constraints between transmission flows -// // and/or power generated from generating units. -// int CntCouplante; -// int Interco; -// int NbInterco; -// double Poids; -// double ValueOfFlow; -// int Index; -// double* SecondMembre = ProblemeAResoudre->SecondMembre; -// CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; -// CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; -// std::map bingdingConstraintNumber -// = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; - -// for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; -// CntCouplante++) -// { -// if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) -// { -// MatriceDesContraintesCouplantes -// = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - -// Cnt = bingdingConstraintNumber[CntCouplante]; - -// // 1. The original RHS of bingding constraint -// SecondMembre[Cnt] -// = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; -// logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt -// << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante -// << ")"; - -// // 2. RHS part 2: flow other than 2<->2 -// NbInterco -// = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; -// for (Index = 0; Index < NbInterco; Index++) -// { -// Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; -// Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - -// if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] -// != Data::AdequacyPatch::physicalAreaInsideAdqPatch -// || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] -// != Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// { -// ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; -// SecondMembre[Cnt] -= ValueOfFlow * Poids; -// logs.debug() -// << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt -// << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" -// << ". Interco;" + std::to_string(Interco) << ". Between:[" -// << ProblemeHebdo -// ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] -// << "]-[" -// << ProblemeHebdo -// ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] -// << "]" -// << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; -// } -// } - -// // 3. RHS part 3: - cluster -// int NbClusters -// = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; -// int Area; -// int Palier; -// int IndexNumeroDuPalierDispatch; -// double ValueOfVar; -// PALIERS_THERMIQUES* PaliersThermiquesDuPays; - -// for (Index = 0; Index < NbClusters; Index++) -// { -// Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; -// PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; - -// IndexNumeroDuPalierDispatch -// = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; - -// Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques -// [IndexNumeroDuPalierDispatch]; -// Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; - -// ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] -// ->ProductionThermique[hour] -// ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; - -// SecondMembre[Cnt] -= ValueOfVar * Poids; -// logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt -// << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante -// << ")" -// << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids -// << ", ValueOfVar:" << ValueOfVar; -// } -// } -// } -// } +} \ No newline at end of file From 6ddff4b48b1cf73758ce716666e991f72bd8c94b Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Jun 2022 18:23:53 +0200 Subject: [PATCH 191/490] 23. separate Costs into functions --- .../opt_gestion_des_couts_cas_quadratique.cpp | 39 +++++++++++++------ 1 file changed, 28 insertions(+), 11 deletions(-) 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 67187e1fd8..cf02dbf261 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -58,18 +58,15 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH } } -void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - logs.debug() << "[CSR] cost"; int Var; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; double priceTakingOrders; // PTO double quadraticCost; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - int Interco; - COUTS_DE_TRANSPORT* TransportCost; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: ENS for each area inside adq patch // obj function term is: 1 / (PTO * PTO) * ENS * ENS @@ -78,11 +75,6 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, // PTO can take two different values according to option: // 1. from DENS // 2. from load - memset((char*)ProblemeAResoudre->CoutLineaire, - 0, - ProblemeAResoudre->NombreDeVariables * sizeof(double)); - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] @@ -121,6 +113,17 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } } } +} + +void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Interco; + COUTS_DE_TRANSPORT* TransportCost; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // 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 @@ -171,4 +174,18 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, } } } +} + +void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] cost"; + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + memset((char*)ProblemeAResoudre->CoutLineaire, + 0, + ProblemeAResoudre->NombreDeVariables * sizeof(double)); + + setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); + setLinearCost(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file From b1f98a6943545292a9d7c72e480af944342ad853 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Jun 2022 18:43:44 +0200 Subject: [PATCH 192/490] 22. separate Bounds into functions --- ...opt_gestion_des_bornes_cas_quadratique.cpp | 67 +++++++++++++------ 1 file changed, 48 insertions(+), 19 deletions(-) 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 b9909299d1..061f438f54 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -95,24 +95,15 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P } } -void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - logs.debug() << "[CSR] bounds"; - int Var; double* AdresseDuResultat; int hour; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; - + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: ENS for each area inside adq patch @@ -138,6 +129,18 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( << ProblemeAResoudre->Xmax[Var]; } } +} + +void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* AdresseDuResultat; + int hour; + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: Spilled Energy for each area inside adq patch // todo after debugging transfer this into same area loop as ENS @@ -163,19 +166,29 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( << ProblemeAResoudre->Xmax[Var]; } } +} - // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links - // between nodes of type 2. Set hourly bounds for links between nodes of type 2, depending on - // the user input (max direct and indirect flow). +void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* AdresseDuResultat; + int hour; + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + int* TypeDeVariable; double* Xmin; double* Xmax; - int* TypeDeVariable; - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; Xmin = ProblemeAResoudre->Xmin; Xmax = ProblemeAResoudre->Xmax; - + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; + // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links + // between nodes of type 2. Set hourly bounds for links between nodes of type 2, depending on + // the user input (max direct and indirect flow). for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) { // only consider link between 2 and 2 @@ -253,6 +266,22 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( << ProblemeAResoudre->Xmax[Var]; } } +} + +void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] bounds"; + + int Var; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; - return; + setBoundsOnENS(ProblemeHebdo, hourlyCsrProblem); + setBoundsOnSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); + setBoundsOnFlows(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file From cacc87b18e1e54bf5c4639438857b827aeca8447 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Jun 2022 19:15:06 +0200 Subject: [PATCH 193/490] 21. separate Construction of variables into functions --- ...ction_variables_optimisees_quadratique.cpp | 52 +++++++++++++++---- 1 file changed, 42 insertions(+), 10 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 96fd352ab8..b7e619a434 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -58,19 +58,13 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H ProblemeAResoudre->NombreDeVariables = NombreDeVariables; } -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - logs.debug() << "[CSR] variable list:"; int NumberOfVariables = 0; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); - + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: ENS of each area inside adq patch @@ -89,8 +83,20 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( NumberOfVariables++; } } + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; +} - // variables: Spilled Energy of each area inside adq patch +void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + int NumberOfVariables = ProblemeAResoudre->NombreDeVariables; + + // variables: Spilled Energy of each area inside adq patch // todo after debugging transfer this into same area loop as ENS logs.debug() << " Spilled Energy of each area inside adq patch: "; for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) @@ -107,6 +113,17 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( NumberOfVariables++; } } + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; +} + +void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + int NumberOfVariables = ProblemeAResoudre->NombreDeVariables; // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 // and 2. @@ -141,7 +158,22 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( NumberOfVariables++; } } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; +} + +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] variable list:"; + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + assert(ProblemeAResoudre != NULL); + + constructVariableENS(ProblemeHebdo, hourlyCsrProblem); + constructVariableSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); + constructVariableFlows(ProblemeHebdo, hourlyCsrProblem); + return; } \ No newline at end of file From 59791f6e59e2a16d69d38056bd3a03ce42b91099 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 2 Jun 2022 13:02:49 +0200 Subject: [PATCH 194/490] 19. separate quad-solver into sub-functions --- .../opt_appel_solveur_quadratique.cpp | 131 ++++++++++-------- 1 file changed, 72 insertions(+), 59 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 22f39e45df..2ea99b704a 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -184,13 +184,9 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr } } - -bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + PROBLEME_POINT_INTERIEUR& Probleme) { - //CSR todo call solver for quadratic houly CSR - //this part should be exactly the same as in OPT_AppelDuSolveurQuadratique, except for some log. todo refactoring - int Var; - double* pt; double ToleranceSurLAdmissibilite; int ChoixToleranceParDefautSurLAdmissibilite; double ToleranceSurLaStationnarite; @@ -198,8 +194,6 @@ bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeARes double ToleranceSurLaComplementarite; int ChoixToleranceParDefautSurLaComplementarite; - PROBLEME_POINT_INTERIEUR Probleme; - ToleranceSurLAdmissibilite = 1.e-5; ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; @@ -246,72 +240,91 @@ bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeARes Probleme.CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; Probleme.CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; +} - PI_Quamin(&Probleme); - - ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; - if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) +void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) +{ + int Var; + double* pt; + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; - if (pt) - *pt = ProblemeAResoudre->X[Var]; - logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; - } + pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + if (pt) + *pt = ProblemeAResoudre->X[Var]; + logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; + } +} - return true; +void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* pt; + logs.warning() << "CSR Quadratic Optimization: No solution, hour in week: " + << hourlyCsrProblem.hourInWeekTriggeredCsr; // todo refactoring + + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + if (pt) + *pt = std::numeric_limits::quiet_NaN(); } - else + +#ifndef NDEBUG + { - logs.warning() << "CSR Quadratic Optimization: No solution, hour in week: " << hourlyCsrProblem.hourInWeekTriggeredCsr; //todo refactoring + logs.info(); + + logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; + logs.info() << "Here is the trace:"; for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { - pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; - if (pt) - *pt = std::numeric_limits::quiet_NaN(); + logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", + Var, + ProblemeAResoudre->CoutLineaire[Var], + ProblemeAResoudre->CoutQuadratique[Var]); } - -#ifndef NDEBUG - + for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) { - logs.info(); - - logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; - - logs.info() << "Here is the trace:"; - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", - Var, - ProblemeAResoudre->CoutLineaire[Var], - ProblemeAResoudre->CoutQuadratique[Var]); - } - for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) + logs.info().appendFormat("Constraint %ld sens %c B %e", + Cnt, + ProblemeAResoudre->Sens[Cnt], + ProblemeAResoudre->SecondMembre[Cnt]); + + int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; + int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; + for (; il < ilMax; ++il) { - logs.info().appendFormat("Constraint %ld sens %c B %e", - Cnt, - ProblemeAResoudre->Sens[Cnt], - ProblemeAResoudre->SecondMembre[Cnt]); - - int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; - int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; - for (; il < ilMax; ++il) - { - Var = ProblemeAResoudre->IndicesColonnes[il]; - logs.info().appendFormat( - " coeff %e var %ld xmin %e xmax %e type %ld", - ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], - Var, - ProblemeAResoudre->Xmin[Var], - ProblemeAResoudre->Xmax[Var], - ProblemeAResoudre->TypeDeVariable[Var]); - } + Var = ProblemeAResoudre->IndicesColonnes[il]; + logs.info().appendFormat( + " coeff %e var %ld xmin %e xmax %e type %ld", + ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], + Var, + ProblemeAResoudre->Xmin[Var], + ProblemeAResoudre->Xmax[Var], + ProblemeAResoudre->TypeDeVariable[Var]); } } + } #endif +} +bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + PROBLEME_POINT_INTERIEUR Probleme; + setInteriorPointProblem(ProblemeAResoudre, Probleme); + PI_Quamin(&Probleme); // resolution + ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; + if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) + { + storeInteriorPointResults(ProblemeAResoudre); + return true; + } + else + { + handleInteriorPointError(ProblemeAResoudre, hourlyCsrProblem); return false; } } \ No newline at end of file From d82dee36efacf0185e0b750625c76f5c7bafca44 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 2 Jun 2022 16:22:23 +0200 Subject: [PATCH 195/490] 11. separate getHoursRequiringCurtailmentSharing into two sub-functions --- src/solver/simulation/economy.cpp | 36 +++++++++++++++++++++---------- src/solver/simulation/economy.h | 4 ++++ 2 files changed, 29 insertions(+), 11 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index d3fe4fbdb9..78188bebdd 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -142,21 +142,29 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); } -std::set getHoursRequiringCurtailmentSharing(PROBLEME_HEBDO* pProblemeHebdo) +vector Economy::calculateENSoverAllAreasForEachHour(uint numSpace) { - std::set triggerCsrSet; - float threshold = pProblemeHebdo->adqPatch->ThresholdInitiateCurtailmentSharingRule; - double sumENS[nbHoursInAWeek] = {0}; + double temp[nbHoursInAWeek] = {0}; - for (int area = 0; area < pProblemeHebdo->NombreDePays; ++area) + for (int area = 0; area < pProblemesHebdo[numSpace]->NombreDePays; ++area) { - if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + if (pProblemesHebdo[numSpace]->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - sumTwoArrays( - sumENS, - pProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive, - nbHoursInAWeek); + sumTwoArrays(temp, + pProblemesHebdo[numSpace] + ->ResultatsHoraires[area] + ->ValeursHorairesDeDefaillancePositive, + nbHoursInAWeek); } + std::vector sumENS; + sumENS.assign(std::begin(temp), std::end(temp)); + return sumENS; +} + +std::set Economy::identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) +{ + float threshold = pProblemesHebdo[numSpace]->adqPatch->ThresholdInitiateCurtailmentSharingRule; + std::set triggerCsrSet; for (int i = 0; i < nbHoursInAWeek; ++i) { if ((int)sumENS[i] >= threshold) @@ -170,6 +178,12 @@ std::set getHoursRequiringCurtailmentSharing(PROBLEME_HEBDO* pProblemeHebdo return triggerCsrSet; } +std::set Economy::getHoursRequiringCurtailmentSharing(uint numSpace) +{ + vector sumENS = calculateENSoverAllAreasForEachHour(numSpace); + return identifyHoursForCurtailmentSharing(sumENS, numSpace); +} + void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int hourInWeek = hourlyCsrProblem.hourInWeekTriggeredCsr; @@ -225,7 +239,7 @@ bool Economy::year(Progression::Task& progression, OPT_OptimisationHebdomadaireAdqPatch( pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); - std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(pProblemesHebdo[numSpace]); + std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) { diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 3b0cf323c1..27c1d20cd5 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -94,6 +94,10 @@ class Economy void initializeState(Variable::State& state, uint numSpace); + vector calculateENSoverAllAreasForEachHour(uint numSpace); + std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); + std::set getHoursRequiringCurtailmentSharing(uint numSpace); + private: uint pNbWeeks; uint pStartTime; From cdf0fd8915ce3e9a6e482bdbc8c7ffd63d62e9f8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 2 Jun 2022 18:33:34 +0200 Subject: [PATCH 196/490] 17+18+24. make OPT_ functions private methods and make public run method --- src/solver/simulation/economy.cpp | 61 +++++++++++++------ .../sim_structure_probleme_economique.h | 10 +++ 2 files changed, 54 insertions(+), 17 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 78188bebdd..b2c99fd280 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -37,9 +37,52 @@ #include "common-eco-adq.h" #include #include "../optimisation/adequacy_patch.h" +#include "../simulation/sim_structure_probleme_economique.h" using namespace Yuni; +void HOURLY_CSR_PROBLEM::resetProblem() +{ + OPT_LiberationProblemesSimplexe(pWeeklyProblemBelongedTo); +} +void HOURLY_CSR_PROBLEM::buildProblemVariables() +{ + OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, + *this); +} +void HOURLY_CSR_PROBLEM::buildProblemConstraintsLHS() +{ + OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); +} +void HOURLY_CSR_PROBLEM::setVariableBounds() +{ + OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); +} +void HOURLY_CSR_PROBLEM::buildProblemConstraintsRHS() +{ + OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); +} +void HOURLY_CSR_PROBLEM::setProblemCost() +{ + OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblemBelongedTo, *this); +} +void HOURLY_CSR_PROBLEM::solveProblem() +{ + OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this); +} +void HOURLY_CSR_PROBLEM::run() +{ + resetProblem(); + calculateCsrParameters(pWeeklyProblemBelongedTo, *this); + buildProblemVariables(); + buildProblemConstraintsLHS(); + setVariableBounds(); + buildProblemConstraintsRHS(); + setProblemCost(); + solveProblem(); + return; +} + namespace Antares { namespace Solver @@ -184,22 +227,6 @@ std::set Economy::getHoursRequiringCurtailmentSharing(uint numSpace) return identifyHoursForCurtailmentSharing(sumENS, numSpace); } -void OPT_OptimisationHourlyCurtailmentSharingRule(HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hourInWeek = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_HEBDO* pWeeklyProblem = hourlyCsrProblem.pWeeklyProblemBelongedTo; - - OPT_LiberationProblemesSimplexe(pWeeklyProblem); //CSR todo !!! do we do this here ???? or do we create another PROBLEME_ANTARES_A_RESOUDRE inside HOURLY_CSR_PROBLEM ???? - calculateCsrParameters(pWeeklyProblem, hourlyCsrProblem); - OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblem, hourlyCsrProblem); - OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblem->ProblemeAResoudre, hourlyCsrProblem); - return; -} - bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, @@ -245,7 +272,7 @@ bool Economy::year(Progression::Task& progression, { logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); - OPT_OptimisationHourlyCurtailmentSharingRule(hourlyCsrProblem); + hourlyCsrProblem.run(); } checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index f5d3bd2b9f..a4afd4d7ac 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -723,6 +723,14 @@ struct PROBLEME_HEBDO // hourly CSR problem structure class HOURLY_CSR_PROBLEM { +private: + void resetProblem(); + void buildProblemVariables(); + void setVariableBounds(); + void buildProblemConstraintsLHS(); + void buildProblemConstraintsRHS(); + void setProblemCost(); + void solveProblem(); public: int hourInWeekTriggeredCsr; PROBLEME_HEBDO* pWeeklyProblemBelongedTo; @@ -740,6 +748,8 @@ class HOURLY_CSR_PROBLEM std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; + + void run(); }; #endif From 09e35c28f36e3a2246fc7ca107429d918a1a84b6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 2 Jun 2022 18:37:53 +0200 Subject: [PATCH 197/490] clean --- src/solver/simulation/sim_structure_probleme_economique.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index a4afd4d7ac..9f25f51144 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -731,6 +731,8 @@ class HOURLY_CSR_PROBLEM void buildProblemConstraintsRHS(); void setProblemCost(); void solveProblem(); +public: + void run(); public: int hourInWeekTriggeredCsr; PROBLEME_HEBDO* pWeeklyProblemBelongedTo; @@ -748,8 +750,6 @@ class HOURLY_CSR_PROBLEM std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; - - void run(); }; #endif From 21cbdcc57baedf06abb9a26345ac1ddd3a801da4 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Thu, 2 Jun 2022 21:19:49 +0200 Subject: [PATCH 198/490] clean --- src/solver/optimisation/adequacy_patch.cpp | 59 ++++++++++++++++++++-- src/solver/simulation/economy.cpp | 52 +------------------ 2 files changed, 56 insertions(+), 55 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index d28bd92ac9..1bb9c52628 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -26,8 +26,10 @@ */ #include "../simulation/simulation.h" +#include "opt_fonctions.h" #include "adequacy_patch.h" #include +#include "../simulation/sim_structure_probleme_economique.h" using namespace Yuni; using namespace Antares::Data::AdequacyPatch; @@ -139,8 +141,7 @@ void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == physicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) { std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); @@ -175,8 +176,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == physicalAreaInsideAdqPatch) + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) { for (int hour = 0; hour < numOfHoursInWeek; hour++) { @@ -260,4 +260,53 @@ void sumTwoArrays(T* a, T* b, int num) for (uint i = 0; i < num; ++i) a[i] += b[i]; } -template void sumTwoArrays(double* a, double* b, int num); \ No newline at end of file +template void sumTwoArrays(double* a, double* b, int num); + +void HOURLY_CSR_PROBLEM::resetProblem() +{ + OPT_LiberationProblemesSimplexe(pWeeklyProblemBelongedTo); +} + +void HOURLY_CSR_PROBLEM::buildProblemVariables() +{ + OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, + *this); +} + +void HOURLY_CSR_PROBLEM::buildProblemConstraintsLHS() +{ + OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); +} + +void HOURLY_CSR_PROBLEM::setVariableBounds() +{ + OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); +} + +void HOURLY_CSR_PROBLEM::buildProblemConstraintsRHS() +{ + OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); +} + +void HOURLY_CSR_PROBLEM::setProblemCost() +{ + OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblemBelongedTo, *this); +} + +void HOURLY_CSR_PROBLEM::solveProblem() +{ + OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this); +} + +void HOURLY_CSR_PROBLEM::run() +{ + resetProblem(); + calculateCsrParameters(pWeeklyProblemBelongedTo, *this); + buildProblemVariables(); + buildProblemConstraintsLHS(); + setVariableBounds(); + buildProblemConstraintsRHS(); + setProblemCost(); + solveProblem(); + return; +} diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index b2c99fd280..c785e14bfa 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -41,48 +41,6 @@ using namespace Yuni; -void HOURLY_CSR_PROBLEM::resetProblem() -{ - OPT_LiberationProblemesSimplexe(pWeeklyProblemBelongedTo); -} -void HOURLY_CSR_PROBLEM::buildProblemVariables() -{ - OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, - *this); -} -void HOURLY_CSR_PROBLEM::buildProblemConstraintsLHS() -{ - OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); -} -void HOURLY_CSR_PROBLEM::setVariableBounds() -{ - OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); -} -void HOURLY_CSR_PROBLEM::buildProblemConstraintsRHS() -{ - OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); -} -void HOURLY_CSR_PROBLEM::setProblemCost() -{ - OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblemBelongedTo, *this); -} -void HOURLY_CSR_PROBLEM::solveProblem() -{ - OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this); -} -void HOURLY_CSR_PROBLEM::run() -{ - resetProblem(); - calculateCsrParameters(pWeeklyProblemBelongedTo, *this); - buildProblemVariables(); - buildProblemConstraintsLHS(); - setVariableBounds(); - buildProblemConstraintsRHS(); - setProblemCost(); - solveProblem(); - return; -} - namespace Antares { namespace Solver @@ -91,7 +49,6 @@ namespace Simulation { enum { - nbHoursInAWeek = 168, }; @@ -179,8 +136,6 @@ void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); } - // TODO check if we need to cut SIM_RenseignementProblemeHebdo and just pick out the - // part that we need ::SIM_RenseignementProblemeHebdo(*pProblemeHebdo, state, numSpace, hourInTheYear); OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); } @@ -212,12 +167,9 @@ std::set Economy::identifyHoursForCurtailmentSharing(vector sumENS, { if ((int)sumENS[i] >= threshold) { - logs.debug() << "hour: [" << i << "], sumENS = [" << (int)sumENS[i] - << "], threshold = " << threshold; triggerCsrSet.insert(i); } } - logs.debug() << "number of triggered hours: " << triggerCsrSet.size(); return triggerCsrSet; } @@ -266,11 +218,11 @@ bool Economy::year(Progression::Task& progression, OPT_OptimisationHebdomadaireAdqPatch( pProblemesHebdo[numSpace], state, numSpace, hourInTheYear); - std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); + std::set hoursRequiringCurtailmentSharing + = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) { - logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); hourlyCsrProblem.run(); } From 221a40964d6b5ecdf9ffc62f0630f9a45750a093 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 3 Jun 2022 10:00:28 +0200 Subject: [PATCH 199/490] clean --- src/solver/simulation/economy.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index c785e14bfa..7789ccce4b 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -37,7 +37,6 @@ #include "common-eco-adq.h" #include #include "../optimisation/adequacy_patch.h" -#include "../simulation/sim_structure_probleme_economique.h" using namespace Yuni; From 17ef4ea0c1d9d522393ea3cd8881aa92616f847a Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 10:32:00 +0200 Subject: [PATCH 200/490] 0 as a default value, and (value > threshold) --- src/libs/antares/study/fwd.h | 4 ++-- src/solver/optimisation/adequacy_patch.cpp | 2 +- src/solver/simulation/economy.cpp | 2 +- 3 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index b646578445..6a852dbe55 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -605,9 +605,9 @@ enum AdqPatchPTO }; // enum AdqPatchPTO //! A default threshold value for initiate curtailment sharing rule -const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 500.0; +const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 0.0; //! A default threshold value for display local matching rule violations -const float adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations = 500.0; +const float adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; } // namespace AdequacyPatch } // namespace Data diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 90b8700107..59a1c943fa 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -188,7 +188,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb // check LMR violations ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; - if ((densNew < ensInit) && (ensInit - densNew >= Math::Abs(threshold))) + if ((densNew < ensInit) && (ensInit - densNew > Math::Abs(threshold))) { ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; totalLmrViolation += (ensInit - densNew); diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 78221cb730..c41fdf2efe 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -225,7 +225,7 @@ std::set Economy::identifyHoursForCurtailmentSharing(vector sumENS, std::set triggerCsrSet; for (int i = 0; i < nbHoursInAWeek; ++i) { - if ((int)sumENS[i] >= threshold) + if ((int)sumENS[i] > threshold) { triggerCsrSet.insert(i); } From 65fb99c2b188c976c25dba40be86f87e9407d6fc Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 10:38:54 +0200 Subject: [PATCH 201/490] 4. add else if for AdqPatchPTO::isDens --- .../optimisation/opt_gestion_des_couts_cas_quadratique.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) 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 994c097d00..fbfb8573b9 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -91,7 +91,8 @@ void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC + ProblemeHebdo->AllMustRunGeneration[hour] ->AllMustRunGenerationOfArea[area]; } - else + else if (ProblemeHebdo->adqPatchParams->PriceTakingOrder + == Data::AdequacyPatch::AdqPatchPTO::isDens) { priceTakingOrders = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; From 8e3069ed736615c819c5e93c763249ea113118a4 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 12:45:13 +0200 Subject: [PATCH 202/490] bring back some debugg logs for easy result check --- src/solver/simulation/economy.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index c41fdf2efe..dfbf16e857 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -227,9 +227,12 @@ std::set Economy::identifyHoursForCurtailmentSharing(vector sumENS, { if ((int)sumENS[i] > threshold) { + logs.debug() << "hour: [" << i << "], sumENS = [" << (int)sumENS[i] + << "], threshold = " << threshold; triggerCsrSet.insert(i); } } + logs.debug() << "number of triggered hours: " << triggerCsrSet.size(); return triggerCsrSet; } @@ -282,6 +285,7 @@ bool Economy::year(Progression::Task& progression, for (int hourInWeek : hoursRequiringCurtailmentSharing) { + logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); hourlyCsrProblem.run(); } From 5a0b08421f687ae4b45cd865f5af48dccd23ef98 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 13:21:48 +0200 Subject: [PATCH 203/490] 2. make calculateCsrParameters method of HOURLY_CSR_PROBLEM --- src/solver/optimisation/adequacy_patch.cpp | 34 +++++++++---------- src/solver/optimisation/adequacy_patch.h | 8 ++--- .../sim_structure_probleme_economique.h | 1 + 3 files changed, 22 insertions(+), 21 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 59a1c943fa..4cf7e28600 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -131,34 +131,34 @@ void setNTCbounds(double& Xmax, } } -void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void HOURLY_CSR_PROBLEM::calculateCsrParameters() { double netPositionInit; double densNew; double ensInit; double spillageInit; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int hour = hourInWeekTriggeredCsr; - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) + if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] + == physicalAreaInsideAdqPatch) { std::tie(netPositionInit, densNew) - = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + = calculateAreaFlowBalance(pWeeklyProblemBelongedTo, Area, hour); - ensInit - = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; - spillageInit - = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillanceNegative[hour]; + ensInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillancePositive[hour]; + spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillanceNegative[hour]; - hourlyCsrProblem.netPositionInitValues[Area] = netPositionInit; - hourlyCsrProblem.densNewValues[Area] = densNew; - hourlyCsrProblem.rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; + netPositionInitValues[Area] = netPositionInit; + densNewValues[Area] = densNew; + rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; - logs.debug() << "DENS_new[" << Area << "] = " << hourlyCsrProblem.densNewValues[Area]; - logs.debug() << "rhsAreaBalanceValues[" << Area - << "] = " << hourlyCsrProblem.rhsAreaBalanceValues[Area] << " = ENSinit(" - << ensInit << ") + NetPositionInit(" << netPositionInit + logs.debug() << "DENS_new[" << Area << "] = " << densNewValues[Area]; + logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << rhsAreaBalanceValues[Area] + << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit << ") - SpillageInit(" << spillageInit << ")"; } } @@ -301,7 +301,7 @@ void HOURLY_CSR_PROBLEM::solveProblem() void HOURLY_CSR_PROBLEM::run() { resetProblem(); - calculateCsrParameters(pWeeklyProblemBelongedTo, *this); + calculateCsrParameters(); buildProblemVariables(); buildProblemConstraintsLHS(); setVariableBounds(); diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 6664a44e64..3c41ba3f20 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -101,10 +101,10 @@ void setNTCbounds(double& Xmax, std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, int Area, int hour); -/*! - * Calculate parameters for curtailment sharing rule. - */ -void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem); +// /*! +// * Calculate parameters for curtailment sharing rule. +// */ +// void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem); /*! * Check local matching rule violation for each area inside adequacy patch. */ diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index d22aa8489d..5b24d0932f 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -726,6 +726,7 @@ struct PROBLEME_HEBDO class HOURLY_CSR_PROBLEM { private: + void calculateCsrParameters(); void resetProblem(); void buildProblemVariables(); void setVariableBounds(); From af1df5d8a4192b9e97e93247fb25405cf683de73 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 13:22:53 +0200 Subject: [PATCH 204/490] clean --- src/solver/optimisation/adequacy_patch.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 3c41ba3f20..f315a30ab2 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -101,10 +101,7 @@ void setNTCbounds(double& Xmax, std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, int Area, int hour); -// /*! -// * Calculate parameters for curtailment sharing rule. -// */ -// void calculateCsrParameters(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem); + /*! * Check local matching rule violation for each area inside adequacy patch. */ From e207c8a16e2f444b18a3f09c8cd8574d7cc12c9a Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 14:58:26 +0200 Subject: [PATCH 205/490] 1. use std::vector for sumENS --- src/solver/optimisation/adequacy_patch.cpp | 6 ++---- src/solver/optimisation/adequacy_patch.h | 11 +++++------ src/solver/simulation/economy.cpp | 15 ++++++--------- 3 files changed, 13 insertions(+), 19 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 4cf7e28600..4fce27d78d 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -254,13 +254,11 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo return std::make_pair(netPositionInit, densNew); } -template -void sumTwoArrays(T* a, T* b, int num) +void addArray(std::vector& A, double* B, int num) { for (uint i = 0; i < num; ++i) - a[i] += b[i]; + A[i] += B[i]; } -template void sumTwoArrays(double* a, double* b, int num); void HOURLY_CSR_PROBLEM::resetProblem() { diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index f315a30ab2..7bfa84274f 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -108,15 +108,14 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); /*! -** ** \brief Sums two arrays of the same size a[i]=a[i]+b[i] +** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] ** ** -** ** \param a An array -** ** \param b An array +** ** \param A A vector +** ** \param B An array ** ** \param num An integer -** ** \return +** ** \return ** */ -template -extern void sumTwoArrays(T* a, T* b, int num); +void addArray(std::vector& A, double* B, int num); // } // end namespace Antares // } // end namespace Data diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index dfbf16e857..cc0e1392e0 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -202,20 +202,17 @@ bool Economy::simulationBegin() vector Economy::calculateENSoverAllAreasForEachHour(uint numSpace) { - double temp[nbHoursInAWeek] = {0}; - + std::vector sumENS(nbHoursInAWeek, 0.0); for (int area = 0; area < pProblemesHebdo[numSpace]->NombreDePays; ++area) { if (pProblemesHebdo[numSpace]->adequacyPatchRuntimeData.areaMode[area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - sumTwoArrays(temp, - pProblemesHebdo[numSpace] - ->ResultatsHoraires[area] - ->ValeursHorairesDeDefaillancePositive, - nbHoursInAWeek); + addArray(sumENS, + pProblemesHebdo[numSpace] + ->ResultatsHoraires[area] + ->ValeursHorairesDeDefaillancePositive, + nbHoursInAWeek); } - std::vector sumENS; - sumENS.assign(std::begin(temp), std::end(temp)); return sumENS; } From 1e30f917d3d280ec8d860078121f4c8854ea66f7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 15:51:25 +0200 Subject: [PATCH 206/490] 9. repack CSR ui input data in parameters.h --- src/libs/antares/study/parameters.cpp | 25 +++++++++--------- src/libs/antares/study/parameters.h | 25 +++++++++++------- .../simulation/sim_calcul_economique.cpp | 9 ++++--- .../adequacy-patch/adequacy-patch-options.cpp | 26 +++++++++---------- 4 files changed, 46 insertions(+), 39 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 668c6ef660..17ba6e121b 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -236,9 +236,9 @@ void Parameters::resetSeeds() void Parameters::resetThresholdsAdqPatch() { // Initialize all thresholds values for adequacy patch - adqPatchThresholdInitiateCurtailmentSharingRule + adqPatch.curtailmentSharing.thresholdInitiate = adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule; - adqPatchThresholdDisplayLocalMatchingRuleViolations + adqPatch.localMatching.thresholdDisplayViolations = adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; } @@ -247,8 +247,8 @@ void Parameters::resetAdqPatchParameters() include.adequacyPatch = false; adqPatch.localMatching.setToZeroOutsideInsideLinks = true; adqPatch.localMatching.setToZeroOutsideOutsideLinks = true; - adqPatchPriceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; - adqPatchSaveIntermediateResults = false; + adqPatch.curtailmentSharing.priceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; + adqPatch.saveIntermediateResults = false; resetThresholdsAdqPatch(); } @@ -677,15 +677,15 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, if (key == "set-to-null-ntc-between-physical-out-for-first-step") return value.to(d.adqPatch.localMatching.setToZeroOutsideOutsideLinks); if (key == "save-intermediate-results") - return value.to(d.adqPatchSaveIntermediateResults); + return value.to(d.adqPatch.saveIntermediateResults); // Price taking order if (key == "price-taking-order") - return StringToPriceTakingOrder(value, d.adqPatchPriceTakingOrder); + return StringToPriceTakingOrder(value, d.adqPatch.curtailmentSharing.priceTakingOrder); // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") - return value.to(d.adqPatchThresholdInitiateCurtailmentSharingRule); + return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); if (key == "threshold-display-local-matching-rule-violations") - return value.to(d.adqPatchThresholdDisplayLocalMatchingRuleViolations); + return value.to(d.adqPatch.localMatching.thresholdDisplayViolations); return false; } @@ -1806,13 +1806,14 @@ void Parameters::saveToINI(IniFile& ini) const adqPatch.localMatching.setToZeroOutsideInsideLinks); section->add("set-to-null-ntc-between-physical-out-for-first-step", adqPatch.localMatching.setToZeroOutsideOutsideLinks); - section->add("save-intermediate-results", adqPatchSaveIntermediateResults); - section->add("price-taking-order", PriceTakingOrderToString(adqPatchPriceTakingOrder)); + section->add("save-intermediate-results", adqPatch.saveIntermediateResults); + section->add("price-taking-order", + PriceTakingOrderToString(adqPatch.curtailmentSharing.priceTakingOrder)); // Threshholds section->add("threshold-initiate-curtailment-sharing-rule", - adqPatchThresholdInitiateCurtailmentSharingRule); + adqPatch.curtailmentSharing.thresholdInitiate); section->add("threshold-display-local-matching-rule-violations", - adqPatchThresholdDisplayLocalMatchingRuleViolations); + adqPatch.localMatching.thresholdDisplayViolations); } // Other preferences diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 34b7bca702..9a492f18a8 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -525,22 +525,27 @@ class Parameters final //! NTC is set to null (if true) only in the first step of adequacy patch local matching //! rule. bool setToZeroOutsideOutsideLinks = true; + //! Threshold to display Local Matching Rule violations + float thresholdDisplayViolations; }; LocalMatching localMatching; + + struct CurtailmentSharing + { + //! PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. + Data::AdequacyPatch::AdqPatchPTO priceTakingOrder; + //! Threshold to initiate curtailment sharing rule + float thresholdInitiate; + }; + CurtailmentSharing curtailmentSharing; + + //! Select whether the intermediate result before the application of the curtailment + //! sharing is to be kept in the results + bool saveIntermediateResults; }; AdequacyPatch adqPatch; - //! PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. - Data::AdequacyPatch::AdqPatchPTO adqPatchPriceTakingOrder; - //! Select whether the intermediate result before the application of the curtailment sharing is - //! to be kept in the results - bool adqPatchSaveIntermediateResults; - //! Threshold to initiate curtailment sharing rule - float adqPatchThresholdInitiateCurtailmentSharingRule; - //! Threshold to display Local Matching Rule violations - float adqPatchThresholdDisplayLocalMatchingRuleViolations; - //! \name Scenariio Builder - Rules //@{ //! The current active rules for building scenarios (useful if building mode == custom) diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 83f105dd70..5f93a8902a 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -73,12 +73,13 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.adqPatchParams->SetNTCOutsideToOutsideToZero = parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks; problem.adqPatchParams->SaveIntermediateResults - = parameters.adqPatchSaveIntermediateResults; - problem.adqPatchParams->PriceTakingOrder = parameters.adqPatchPriceTakingOrder; + = parameters.adqPatch.saveIntermediateResults; + problem.adqPatchParams->PriceTakingOrder + = parameters.adqPatch.curtailmentSharing.priceTakingOrder; problem.adqPatchParams->ThresholdInitiateCurtailmentSharingRule - = parameters.adqPatchThresholdInitiateCurtailmentSharingRule; + = parameters.adqPatch.curtailmentSharing.thresholdInitiate; problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations - = parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations; + = parameters.adqPatch.localMatching.thresholdDisplayViolations; } if (parameters.include.adequacyPatch) 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 9c2bf78842..e457d4dc0a 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 @@ -211,7 +211,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : button->menu(true); onPopup.bind(this, &AdequacyPatchOptions::onPopupMenuSpecify, - PopupInfo(study.parameters.adqPatchSaveIntermediateResults, wxT("true"))); + PopupInfo(study.parameters.adqPatch.saveIntermediateResults, wxT("true"))); button->onPopupMenu(onPopup); s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); @@ -332,7 +332,7 @@ void AdequacyPatchOptions::refresh() updateButton(pBtnAdequacyPatch, study.parameters.include.adequacyPatch, buttonType); // Save intermediate results for adequacy patch updateButton(pBtnAdequacyPatchSaveIntermediateResults, - study.parameters.adqPatchSaveIntermediateResults, + study.parameters.adqPatch.saveIntermediateResults, buttonType); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. @@ -348,17 +348,17 @@ void AdequacyPatchOptions::refresh() // Price taking order (PTO) for adequacy patch buttonType = "pto"; bool isPTOload - = (study.parameters.adqPatchPriceTakingOrder == AdqPatchPTO::isLoad) ? true : false; + = (study.parameters.adqPatch.curtailmentSharing.priceTakingOrder == AdqPatchPTO::isLoad) ? true : false; updateButton(pBtnAdequacyPatchPTO, isPTOload, buttonType); // Threshold values { if (pThresholdCSRStart) pThresholdCSRStart->SetValue( - wxString() << study.parameters.adqPatchThresholdInitiateCurtailmentSharingRule); + wxString() << study.parameters.adqPatch.curtailmentSharing.thresholdInitiate); if (pThresholdLMRviolations) pThresholdLMRviolations->SetValue( - wxString() << study.parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations); + wxString() << study.parameters.adqPatch.localMatching.thresholdDisplayViolations); } } @@ -487,9 +487,9 @@ void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != AdqPatchPTO::isDens) + if (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isDens) { - study->parameters.adqPatchPriceTakingOrder = AdqPatchPTO::isDens; + study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isDens; refresh(); MarkTheStudyAsModified(); } @@ -501,9 +501,9 @@ void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) auto study = Data::Study::Current::Get(); if (!(!study)) { - if (study->parameters.adqPatchPriceTakingOrder != AdqPatchPTO::isLoad) + if (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isLoad) { - study->parameters.adqPatchPriceTakingOrder = AdqPatchPTO::isLoad; + study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isLoad; refresh(); MarkTheStudyAsModified(); } @@ -547,9 +547,9 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) } else { - if (newthreshold != study.parameters.adqPatchThresholdInitiateCurtailmentSharingRule) + if (newthreshold != study.parameters.adqPatch.curtailmentSharing.thresholdInitiate) { - study.parameters.adqPatchThresholdInitiateCurtailmentSharingRule = newthreshold; + study.parameters.adqPatch.curtailmentSharing.thresholdInitiate = newthreshold; MarkTheStudyAsModified(); } } @@ -571,9 +571,9 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) else { if (newthreshold - != study.parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations) + != study.parameters.adqPatch.localMatching.thresholdDisplayViolations) { - study.parameters.adqPatchThresholdDisplayLocalMatchingRuleViolations = newthreshold; + study.parameters.adqPatch.localMatching.thresholdDisplayViolations = newthreshold; MarkTheStudyAsModified(); } } From f03804fbdfe9522186056306282b7c5904f3f19b Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 16:12:51 +0200 Subject: [PATCH 207/490] 8. placing all functions inside adequacy_patch.h to namespace Adequcy patch --- src/solver/optimisation/adequacy_patch.cpp | 81 ++++++++++--------- src/solver/optimisation/adequacy_patch.h | 18 ++--- .../opt_gestion_des_bornes_cas_lineaire.cpp | 2 +- 3 files changed, 55 insertions(+), 46 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 4fce27d78d..f57a2cb2ec 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -32,8 +32,13 @@ #include "../simulation/sim_structure_probleme_economique.h" using namespace Yuni; -using namespace Antares::Data::AdequacyPatch; +namespace Antares +{ +namespace Data +{ +namespace AdequacyPatch +{ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco) { AdequacyPatchMode OriginNodeAdequacyPatchType @@ -131,40 +136,6 @@ void setNTCbounds(double& Xmax, } } -void HOURLY_CSR_PROBLEM::calculateCsrParameters() -{ - double netPositionInit; - double densNew; - double ensInit; - double spillageInit; - int hour = hourInWeekTriggeredCsr; - - for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) - { - if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] - == physicalAreaInsideAdqPatch) - { - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalance(pWeeklyProblemBelongedTo, Area, hour); - - ensInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillancePositive[hour]; - spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillanceNegative[hour]; - - netPositionInitValues[Area] = netPositionInit; - densNewValues[Area] = densNew; - rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; - - logs.debug() << "DENS_new[" << Area << "] = " << densNewValues[Area]; - logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << rhsAreaBalanceValues[Area] - << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit - << ") - SpillageInit(" << spillageInit << ")"; - } - } - return; -} - void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) { float threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; @@ -260,6 +231,44 @@ void addArray(std::vector& A, double* B, int num) A[i] += B[i]; } +} // end namespace Antares +} // end namespace Data +} // end namespace AdequacyPatch + +void HOURLY_CSR_PROBLEM::calculateCsrParameters() +{ + double netPositionInit; + double densNew; + double ensInit; + double spillageInit; + int hour = hourInWeekTriggeredCsr; + + for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) + { + if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] + == physicalAreaInsideAdqPatch) + { + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalance(pWeeklyProblemBelongedTo, Area, hour); + + ensInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillancePositive[hour]; + spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillanceNegative[hour]; + + netPositionInitValues[Area] = netPositionInit; + densNewValues[Area] = densNew; + rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; + + logs.debug() << "DENS_new[" << Area << "] = " << densNewValues[Area]; + logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << rhsAreaBalanceValues[Area] + << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit + << ") - SpillageInit(" << spillageInit << ")"; + } + } + return; +} + void HOURLY_CSR_PROBLEM::resetProblem() { OPT_LiberationProblemesSimplexe(pWeeklyProblemBelongedTo); @@ -307,4 +316,4 @@ void HOURLY_CSR_PROBLEM::run() setProblemCost(); solveProblem(); return; -} +} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 7bfa84274f..0ce55d56fc 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -31,12 +31,12 @@ #include #include "../simulation/sim_structure_probleme_economique.h" -// namespace Antares -// { -// namespace Data -// { -// namespace AdequacyPatch -// { +namespace Antares +{ +namespace Data +{ +namespace AdequacyPatch +{ /*! * Determines restriction type for transmission links for first step of adequacy patch. * @@ -117,7 +117,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb ** */ void addArray(std::vector& A, double* B, int num); -// } // end namespace Antares -// } // end namespace Data -// } // end namespace AdequacyPatch +} // end namespace Antares +} // end namespace Data +} // end namespace AdequacyPatch #endif /* __SOLVER_ADEQUACY_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 1023c03749..e225c39a6b 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -156,7 +156,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - setNTCbounds(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); + AdequacyPatch::setNTCbounds(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); if (Math::Infinite(Xmax[Var]) == 1) { From e627773d5d79e373b84fbbc7bf698a9fd8bd54ca Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 24 Jun 2022 16:49:22 +0200 Subject: [PATCH 208/490] 7. re-pack CSR run into weeklyOptProblem->solve method --- src/solver/simulation/economy.cpp | 66 +++++++++---------------------- src/solver/simulation/economy.h | 14 +++---- 2 files changed, 25 insertions(+), 55 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index cc0e1392e0..92114d4518 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -70,7 +70,7 @@ EconomyWeeklyOptimization::Ptr EconomyWeeklyOptimization::create(bool adqPatchEn // Adequacy patch AdequacyPatchOptimization::AdequacyPatchOptimization() = default; -void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, uint numSpace) +void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) { auto problemeHebdo = pProblemesHebdo[numSpace]; problemeHebdo->adqPatchParams->AdequacyFirstStep = true; @@ -94,11 +94,20 @@ void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, // part that we need ::SIM_RenseignementProblemeHebdo(*problemeHebdo, state, numSpace, hourInTheYear); OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); + + std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); + for (int hourInWeek : hoursRequiringCurtailmentSharing) + { + logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; + HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); + hourlyCsrProblem.run(); + } + checkLocalMatchingRuleViolations(problemeHebdo, w); } // No adequacy patch NoAdequacyPatchOptimization::NoAdequacyPatchOptimization() = default; -void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace) +void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace, uint w = 0) { auto problemeHebdo = pProblemesHebdo[numSpace]; OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); @@ -174,33 +183,7 @@ bool Economy::simulationBegin() return true; } -// void OPT_OptimisationHebdomadaireAdqPatch(PROBLEME_HEBDO* pProblemeHebdo, -// Variable::State& state, -// uint numSpace, -// int hourInTheYear) -// { -// pProblemeHebdo->adqPatchParams->AdequacyFirstStep = true; -// OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); -// pProblemeHebdo->adqPatchParams->AdequacyFirstStep = false; - -// for (int pays = 0; pays < pProblemeHebdo->NombreDePays; ++pays) -// { -// if (pProblemeHebdo->adequacyPatchRuntimeData.areaMode[pays] -// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// memcpy(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, -// pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDeDefaillancePositive, -// pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); -// else -// memset(pProblemeHebdo->ResultatsHoraires[pays]->ValeursHorairesDENS, -// 0, -// pProblemeHebdo->NombreDePasDeTemps * sizeof(double)); -// } - -// ::SIM_RenseignementProblemeHebdo(*pProblemeHebdo, state, numSpace, hourInTheYear); -// OPT_OptimisationHebdomadaire(pProblemeHebdo, numSpace); -// } - -vector Economy::calculateENSoverAllAreasForEachHour(uint numSpace) +vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(uint numSpace) { std::vector sumENS(nbHoursInAWeek, 0.0); for (int area = 0; area < pProblemesHebdo[numSpace]->NombreDePays; ++area) @@ -216,9 +199,11 @@ vector Economy::calculateENSoverAllAreasForEachHour(uint numSpace) return sumENS; } -std::set Economy::identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) +std::set AdequacyPatchOptimization::identifyHoursForCurtailmentSharing(vector sumENS, + uint numSpace) { - float threshold = pProblemesHebdo[numSpace]->adqPatchParams->ThresholdInitiateCurtailmentSharingRule; + float threshold + = pProblemesHebdo[numSpace]->adqPatchParams->ThresholdInitiateCurtailmentSharingRule; std::set triggerCsrSet; for (int i = 0; i < nbHoursInAWeek; ++i) { @@ -233,7 +218,7 @@ std::set Economy::identifyHoursForCurtailmentSharing(vector sumENS, return triggerCsrSet; } -std::set Economy::getHoursRequiringCurtailmentSharing(uint numSpace) +std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uint numSpace) { vector sumENS = calculateENSoverAllAreasForEachHour(numSpace); return identifyHoursForCurtailmentSharing(sumENS, numSpace); @@ -273,22 +258,7 @@ bool Economy::year(Progression::Task& progression, try { - weeklyOptProblem->solve(state, hourInTheYear, numSpace); - - if (pProblemesHebdo[numSpace]->adqPatchParams) - { - std::set hoursRequiringCurtailmentSharing - = getHoursRequiringCurtailmentSharing(numSpace); - - for (int hourInWeek : hoursRequiringCurtailmentSharing) - { - logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; - HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, pProblemesHebdo[numSpace]); - hourlyCsrProblem.run(); - } - - checkLocalMatchingRuleViolations(pProblemesHebdo[numSpace], w); - } + weeklyOptProblem->solve(state, hourInTheYear, numSpace, w); DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 8460403a95..e7de5a4750 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -46,7 +46,7 @@ class EconomyWeeklyOptimization { public: using Ptr = std::unique_ptr; - virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace) = 0; + virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) = 0; void initializeProblemeHebdo(PROBLEME_HEBDO** pProblemesHebdo); static Ptr create(bool adqPatchEnabled); @@ -58,14 +58,18 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization { public: AdequacyPatchOptimization(); - void solve(Variable::State& state, int hourInTheYear, uint numSpace) override; + void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) override; + + vector calculateENSoverAllAreasForEachHour(uint numSpace); + std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); + std::set getHoursRequiringCurtailmentSharing(uint numSpace); }; class NoAdequacyPatchOptimization : public EconomyWeeklyOptimization { public: NoAdequacyPatchOptimization(); - void solve(Variable::State&, int, uint numSpace) override; + void solve(Variable::State&, int, uint numSpace, uint w) override; }; class Economy @@ -121,10 +125,6 @@ class Economy void initializeState(Variable::State& state, uint numSpace); - vector calculateENSoverAllAreasForEachHour(uint numSpace); - std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); - std::set getHoursRequiringCurtailmentSharing(uint numSpace); - private: uint pNbWeeks; uint pStartTime; From b707e399b12b74b87091152d8e18bf37d7d2013b Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 29 Jun 2022 10:59:36 +0200 Subject: [PATCH 209/490] adopt RTE syntax for switch/case --- src/solver/optimisation/adequacy_patch.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index f57a2cb2ec..c8454d11fe 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -71,7 +71,6 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeInsideAdq( switch (ExtremityNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - return setToZero; case physicalAreaOutsideAdqPatch: return setToZero; default: From 5b3d8322d1d9e59eb38ddd2461cd4713ad81708c Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 29 Jun 2022 11:11:38 +0200 Subject: [PATCH 210/490] remove comments --- src/solver/optimisation/adequacy_patch.cpp | 5 ----- src/solver/simulation/economy.cpp | 3 --- 2 files changed, 8 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index c8454d11fe..c7cab86eb5 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -258,11 +258,6 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() netPositionInitValues[Area] = netPositionInit; densNewValues[Area] = densNew; rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; - - logs.debug() << "DENS_new[" << Area << "] = " << densNewValues[Area]; - logs.debug() << "rhsAreaBalanceValues[" << Area << "] = " << rhsAreaBalanceValues[Area] - << " = ENSinit(" << ensInit << ") + NetPositionInit(" << netPositionInit - << ") - SpillageInit(" << spillageInit << ")"; } } return; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 92114d4518..adb64d73f4 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -98,7 +98,6 @@ void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) { - logs.debug() << "========= [CSR]: Starting hourly optim for " << hourInWeek; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); hourlyCsrProblem.run(); } @@ -209,8 +208,6 @@ std::set AdequacyPatchOptimization::identifyHoursForCurtailmentSharing(vect { if ((int)sumENS[i] > threshold) { - logs.debug() << "hour: [" << i << "], sumENS = [" << (int)sumENS[i] - << "], threshold = " << threshold; triggerCsrSet.insert(i); } } From 0a256507b18082c8fb71b4a6128e35c5e028709b Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 30 Jun 2022 14:39:05 +0200 Subject: [PATCH 211/490] change RC number --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 571f6f11a3..410b845c0a 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -13,7 +13,7 @@ set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release set(ANTARES_BETA 0) -set(ANTARES_RC 1) +set(ANTARES_RC 2) # OR-Tools tag file(READ "../ortools_tag" ORTOOLS_TAG) From 3ded22c5a746c82f880e5bd90360ac35d866f830 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 30 Jun 2022 14:58:44 +0200 Subject: [PATCH 212/490] change beta release number --- src/CMakeLists.txt | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 410b845c0a..f4a4639566 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -12,8 +12,8 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 0) -set(ANTARES_RC 2) +set(ANTARES_BETA 2) +set(ANTARES_RC 0) # OR-Tools tag file(READ "../ortools_tag" ORTOOLS_TAG) From 94abc63b48f46744da6e1ec381bbb1968cb36431 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 1 Jul 2022 08:47:29 +0200 Subject: [PATCH 213/490] unit test for CSR-calculateAreaFlowBalance --- .../solver/optimisation/adequacy_patch.cpp | 250 ++++++++++++++++++ 1 file changed, 250 insertions(+) diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 4ea39c9f0d..dacc223a76 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -49,6 +49,76 @@ std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originTyp return std::make_pair(Xmin, Xmax); } +static double flowArea1toArea2_positive = 10; +static double flowArea1toArea2_negative = -10; +static double flowArea3toArea1_positive = 30; +static double flowArea3toArea1_negative = -30; + +std::pair calculateAreaFlowBalanceForOneTimeStep( + bool includeFlowsOutsideAdqPatchToDensNew, + AdequacyPatchMode Area1Mode, + AdequacyPatchMode Area2Mode, + double flowToArea1, + double flowFromArea2) +{ + PROBLEME_HEBDO problem; + int Area = 0; + uint hour = 0; + + // allocate memory + problem.adequacyPatchRuntimeData.originAreaMode.resize(3); + problem.adequacyPatchRuntimeData.extremityAreaMode.resize(3); + + problem.adqPatchParams + = std::unique_ptr(new AdequacyPatchParameters()); + auto& adqPatchParams = problem.adqPatchParams; + + problem.ResultatsHoraires = (RESULTATS_HORAIRES**)malloc(1 * sizeof(void*)); + problem.ResultatsHoraires[0] = (RESULTATS_HORAIRES*)malloc(sizeof(RESULTATS_HORAIRES)); + problem.ResultatsHoraires[0]->ValeursHorairesDeDefaillancePositive + = (double*)malloc(1 * sizeof(double)); + problem.ValeursDeNTC = (VALEURS_DE_NTC_ET_RESISTANCES**)malloc(1 * sizeof(void*)); + problem.ValeursDeNTC[0] + = (VALEURS_DE_NTC_ET_RESISTANCES*)malloc(sizeof(VALEURS_DE_NTC_ET_RESISTANCES)); + problem.ValeursDeNTC[0]->ValeurDuFlux = (double*)malloc(3 * sizeof(double)); + problem.IndexSuivantIntercoOrigine = (int*)malloc(3 * sizeof(int)); + problem.IndexDebutIntercoOrigine = (int*)malloc(1 * sizeof(int)); + problem.IndexDebutIntercoExtremite = (int*)malloc(1 * sizeof(int)); + + // input values + adqPatchParams->SetNTCOutsideToInsideToZero = !includeFlowsOutsideAdqPatchToDensNew; + problem.ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; + 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, densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(&problem, Area, hour); + + // free memory + free(problem.IndexDebutIntercoExtremite); + free(problem.IndexDebutIntercoOrigine); + free(problem.IndexSuivantIntercoOrigine); + free(problem.ValeursDeNTC[0]->ValeurDuFlux); + free(problem.ValeursDeNTC[0]); + free(problem.ValeursDeNTC); + free(problem.ResultatsHoraires[0]->ValeursHorairesDeDefaillancePositive); + free(problem.ResultatsHoraires[0]); + free(problem.ResultatsHoraires); + + // return + return std::make_pair(netPositionInit, densNew); +} + // Virtual -> Virtual (0 -> 0) // No change in bounds is expected BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_virtual_no_change_expected) @@ -143,3 +213,183 @@ BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_change_expected_o BOOST_TEST(Xmax == origineExtremite); BOOST_TEST(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, densNew; + std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( + false, virtualArea, virtualArea, flowArea1toArea2_positive, flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == 0.0); + BOOST_TEST(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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(false, + physicalAreaInsideAdqPatch, + virtualArea, + flowArea1toArea2_positive, + flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == -flowArea1toArea2_positive); + BOOST_TEST(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 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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(false, + physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea1toArea2_positive, + flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == -flowArea1toArea2_positive); + BOOST_TEST(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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(false, + physicalAreaInsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea1toArea2_positive, + flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == -flowArea1toArea2_positive + flowArea3toArea1_positive); + BOOST_TEST(densNew == -flowArea1toArea2_positive + flowArea3toArea1_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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(true, + physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea1toArea2_positive, + flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == -flowArea1toArea2_positive); + BOOST_TEST(densNew == -flowArea1toArea2_positive + flowArea3toArea1_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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(true, + physicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea1toArea2_positive, + flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == 0.0); + BOOST_TEST(densNew == flowArea3toArea1_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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(true, + physicalAreaOutsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea1toArea2_positive, + flowArea3toArea1_positive); + BOOST_TEST(netPositionInit == +flowArea3toArea1_positive); + BOOST_TEST(densNew == +flowArea3toArea1_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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(true, + physicalAreaInsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea1toArea2_negative, + flowArea3toArea1_negative); + BOOST_TEST(netPositionInit == -flowArea1toArea2_negative); + BOOST_TEST(densNew == -flowArea1toArea2_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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(true, + physicalAreaOutsideAdqPatch, + physicalAreaOutsideAdqPatch, + flowArea1toArea2_negative, + flowArea3toArea1_negative); + BOOST_TEST(netPositionInit == 0.0); + BOOST_TEST(densNew == -flowArea1toArea2_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, densNew; + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalanceForOneTimeStep(true, + physicalAreaOutsideAdqPatch, + physicalAreaInsideAdqPatch, + flowArea1toArea2_negative, + flowArea3toArea1_negative); + BOOST_TEST(netPositionInit == flowArea3toArea1_negative); + BOOST_TEST(densNew == 0.0); +} From 78600240bb1eaad7b125a2b867bcbeb24c454764 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 6 Jul 2022 14:36:52 +0200 Subject: [PATCH 214/490] small refacto --- src/solver/simulation/economy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index adb64d73f4..4495660d08 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -106,7 +106,7 @@ void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, // No adequacy patch NoAdequacyPatchOptimization::NoAdequacyPatchOptimization() = default; -void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace, uint w = 0) +void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace, uint) { auto problemeHebdo = pProblemesHebdo[numSpace]; OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); From 432c2842adc9bd01f2ebf8e45362614f3d986145 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 7 Jul 2022 09:30:35 +0200 Subject: [PATCH 215/490] unit test bug fix --- src/tests/src/solver/optimisation/adequacy_patch.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index dacc223a76..29e26dcf05 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -82,6 +82,7 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( = (VALEURS_DE_NTC_ET_RESISTANCES*)malloc(sizeof(VALEURS_DE_NTC_ET_RESISTANCES)); problem.ValeursDeNTC[0]->ValeurDuFlux = (double*)malloc(3 * sizeof(double)); problem.IndexSuivantIntercoOrigine = (int*)malloc(3 * sizeof(int)); + problem.IndexSuivantIntercoExtremite = (int*)malloc(3 * sizeof(int)); problem.IndexDebutIntercoOrigine = (int*)malloc(1 * sizeof(int)); problem.IndexDebutIntercoExtremite = (int*)malloc(1 * sizeof(int)); @@ -106,6 +107,7 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( // free memory free(problem.IndexDebutIntercoExtremite); + free(problem.IndexSuivantIntercoExtremite); free(problem.IndexDebutIntercoOrigine); free(problem.IndexSuivantIntercoOrigine); free(problem.ValeursDeNTC[0]->ValeurDuFlux); From 067a8eb123a068259521aa51e6c273d7b7ee872b Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 10 Jul 2022 16:13:33 +0200 Subject: [PATCH 216/490] 4. remove unused --- src/solver/optimisation/adequacy_patch.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index c7cab86eb5..7a2c429497 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -255,7 +255,6 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillanceNegative[hour]; - netPositionInitValues[Area] = netPositionInit; densNewValues[Area] = densNew; rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; } From 397263844013371075d21d8312101b0299259b6e Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 10 Jul 2022 16:39:21 +0200 Subject: [PATCH 217/490] 6.1 MemAllocMemset --- src/solver/simulation/sim_alloc_probleme_hebdo.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index 8c0df81d86..7c4a1b8d25 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -454,7 +454,7 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps problem.ResultatsHoraires[k]->ValeursHorairesDENS = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations - = (int*)MemAlloc(NombreDePasDeTemps * sizeof(int)); // adq patch + = (int*)MemAllocMemset(NombreDePasDeTemps * sizeof(int)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown From 5fe37b5ae94829eff1c072cf25cf768f6f21ea3d Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 10 Jul 2022 16:40:09 +0200 Subject: [PATCH 218/490] 5. remove return --- src/solver/optimisation/adequacy_patch.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 7a2c429497..3e0cf63dab 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -308,5 +308,4 @@ void HOURLY_CSR_PROBLEM::run() buildProblemConstraintsRHS(); setProblemCost(); solveProblem(); - return; } \ No newline at end of file From 02688e5f8b21fee74c4e5c7722e4a9426137a0e0 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 10 Jul 2022 16:45:02 +0200 Subject: [PATCH 219/490] 3. remove debug log --- src/solver/optimisation/adequacy_patch.cpp | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 3e0cf63dab..45c514bde5 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -166,8 +166,6 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb } } } - logs.debug() << "Week:" << weekNb + 1 << ". Total LMR violation:" << totalLmrViolation; - return; } std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, From 2e2e42388fabaab99f6506af22a585937e2efb5f Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 10 Jul 2022 18:53:14 +0200 Subject: [PATCH 220/490] 2. move to csr --- src/libs/antares/study/parameters.cpp | 6 +++--- src/libs/antares/study/parameters.h | 4 ++-- src/solver/simulation/sim_calcul_economique.cpp | 2 +- src/solver/simulation/sim_structure_probleme_economique.h | 1 - .../options/adequacy-patch/adequacy-patch-options.cpp | 6 +++--- 5 files changed, 9 insertions(+), 10 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 17ba6e121b..315fb01bf0 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -238,7 +238,7 @@ void Parameters::resetThresholdsAdqPatch() // Initialize all thresholds values for adequacy patch adqPatch.curtailmentSharing.thresholdInitiate = adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule; - adqPatch.localMatching.thresholdDisplayViolations + adqPatch.curtailmentSharing.thresholdDisplayViolations = adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; } @@ -685,7 +685,7 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, if (key == "threshold-initiate-curtailment-sharing-rule") return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); if (key == "threshold-display-local-matching-rule-violations") - return value.to(d.adqPatch.localMatching.thresholdDisplayViolations); + return value.to(d.adqPatch.curtailmentSharing.thresholdDisplayViolations); return false; } @@ -1813,7 +1813,7 @@ void Parameters::saveToINI(IniFile& ini) const section->add("threshold-initiate-curtailment-sharing-rule", adqPatch.curtailmentSharing.thresholdInitiate); section->add("threshold-display-local-matching-rule-violations", - adqPatch.localMatching.thresholdDisplayViolations); + adqPatch.curtailmentSharing.thresholdDisplayViolations); } // Other preferences diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 9a492f18a8..beb967e9b3 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -525,8 +525,6 @@ class Parameters final //! NTC is set to null (if true) only in the first step of adequacy patch local matching //! rule. bool setToZeroOutsideOutsideLinks = true; - //! Threshold to display Local Matching Rule violations - float thresholdDisplayViolations; }; LocalMatching localMatching; @@ -536,6 +534,8 @@ class Parameters final Data::AdequacyPatch::AdqPatchPTO priceTakingOrder; //! Threshold to initiate curtailment sharing rule float thresholdInitiate; + //! Threshold to display Local Matching Rule violations + float thresholdDisplayViolations; }; CurtailmentSharing curtailmentSharing; diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 85f5eaab43..f34f71c074 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -79,7 +79,7 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.adqPatchParams->ThresholdInitiateCurtailmentSharingRule = parameters.adqPatch.curtailmentSharing.thresholdInitiate; problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations - = parameters.adqPatch.localMatching.thresholdDisplayViolations; + = parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations; } if (parameters.include.adequacyPatch) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 0ce897f4ff..0a2d089056 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -743,7 +743,6 @@ class HOURLY_CSR_PROBLEM std::map numberOfConstraintCsrHourlyBinding; // length is number of binding constraint // contains interco 2-2 - std::map netPositionInitValues; std::map densNewValues; std::map rhsAreaBalanceValues; }; 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 e457d4dc0a..0f6db60c1c 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 @@ -358,7 +358,7 @@ void AdequacyPatchOptions::refresh() wxString() << study.parameters.adqPatch.curtailmentSharing.thresholdInitiate); if (pThresholdLMRviolations) pThresholdLMRviolations->SetValue( - wxString() << study.parameters.adqPatch.localMatching.thresholdDisplayViolations); + wxString() << study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations); } } @@ -571,9 +571,9 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) else { if (newthreshold - != study.parameters.adqPatch.localMatching.thresholdDisplayViolations) + != study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations) { - study.parameters.adqPatch.localMatching.thresholdDisplayViolations = newthreshold; + study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations = newthreshold; MarkTheStudyAsModified(); } } From 35f1712ab04961bd4547acaabe420cf602052793 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Sun, 10 Jul 2022 18:57:13 +0200 Subject: [PATCH 221/490] 1. refacto --- src/libs/antares/study/area/area.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index edaf2057a6..cefa226157 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -53,7 +53,6 @@ void Area::internalInitialize() Area::Area() : index((uint)(-1)), enabled(true), - adequacyPatchMode(AdequacyPatch::physicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -71,7 +70,6 @@ Area::Area() : Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), - adequacyPatchMode(AdequacyPatch::physicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), @@ -91,7 +89,6 @@ Area::Area(const AnyString& name, uint nbParallelYears) : Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uint indx) : index(indx), - adequacyPatchMode(AdequacyPatch::physicalAreaOutsideAdqPatch), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), nodalOptimization(anoAll), From 827df8de44f7024a13ec4a903bd95758b03bfb7b Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 11 Jul 2022 18:22:17 +0200 Subject: [PATCH 222/490] 6.2 hide column --- src/libs/antares/study/parameters.cpp | 9 ++++++++- 1 file changed, 8 insertions(+), 1 deletion(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 315fb01bf0..cd85f1d44b 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -1500,7 +1500,14 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) case rgUnknown: logs.error() << "Generation should be either `clusters` or `aggregated`"; } - const std::vector excluded_vars = renewableGeneration.excludedVariables(); + std::vector excluded_vars = renewableGeneration.excludedVariables(); + + //do not display LMRViolations if not adequacyPatch + if (!include.adequacyPatch) + { + excluded_vars.push_back("LMRViolations"); + } + variablesPrintInfo.prepareForSimulation(thematicTrimming, excluded_vars); switch (mode) From 94770f46cf6e2a6e2a834e9b46e016171e00f977 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 11 Jul 2022 18:34:53 +0200 Subject: [PATCH 223/490] 6.2 --- src/libs/antares/study/parameters.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index cd85f1d44b..95849629e2 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -1505,7 +1505,7 @@ void Parameters::prepareForSimulation(const StudyLoadOptions& options) //do not display LMRViolations if not adequacyPatch if (!include.adequacyPatch) { - excluded_vars.push_back("LMRViolations"); + excluded_vars.push_back("LMR VIOL."); //LMRViolations } variablesPrintInfo.prepareForSimulation(thematicTrimming, excluded_vars); From f9dc79c98cbdbb228498708b15fdc013fffa56e0 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 11 Jul 2022 19:30:08 +0200 Subject: [PATCH 224/490] 3. move log --- src/solver/simulation/economy.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 4495660d08..7ea6c94657 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -101,7 +101,8 @@ void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); hourlyCsrProblem.run(); } - checkLocalMatchingRuleViolations(problemeHebdo, w); + double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); + logs.info() << " [adq-patch] Year:" << state.year << " Week:" << w + 1 << ". Total LMR violation:" << totalLmrViolation; } // No adequacy patch From 7a3d313f6f63c4f88a49668aa7b377304c81d6ea Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 11 Jul 2022 19:33:39 +0200 Subject: [PATCH 225/490] 3. move log.. --- src/solver/optimisation/adequacy_patch.cpp | 3 ++- src/solver/optimisation/adequacy_patch.h | 2 +- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 45c514bde5..949ebbd6ce 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -135,7 +135,7 @@ void setNTCbounds(double& Xmax, } } -void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) +double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) { float threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; double netPositionInit; @@ -166,6 +166,7 @@ void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb } } } + return totalLmrViolation; } std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 0ce55d56fc..e1497c1533 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -105,7 +105,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo /*! * Check local matching rule violation for each area inside adequacy patch. */ -void checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); +double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); /*! ** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] From 0529719823451aa4a44e1c1ba16149d111b727c0 Mon Sep 17 00:00:00 2001 From: rtei-pw Date: Mon, 11 Jul 2022 20:07:24 +0200 Subject: [PATCH 226/490] clean --- src/solver/simulation/economy.cpp | 8 ++++++-- 1 file changed, 6 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 7ea6c94657..0d1511e9ec 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -70,7 +70,10 @@ EconomyWeeklyOptimization::Ptr EconomyWeeklyOptimization::create(bool adqPatchEn // Adequacy patch AdequacyPatchOptimization::AdequacyPatchOptimization() = default; -void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) +void AdequacyPatchOptimization::solve(Variable::State& state, + int hourInTheYear, + uint numSpace, + uint w) { auto problemeHebdo = pProblemesHebdo[numSpace]; problemeHebdo->adqPatchParams->AdequacyFirstStep = true; @@ -102,7 +105,8 @@ void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, hourlyCsrProblem.run(); } double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); - logs.info() << " [adq-patch] Year:" << state.year << " Week:" << w + 1 << ". Total LMR violation:" << totalLmrViolation; + logs.info() << "[adq-patch] Year:" << state.year << " Week:" << w + 1 + << ".Total LMR violation:" << totalLmrViolation; } // No adequacy patch From 3f56f8def6bc30e8340c93adc1a54819a33d8600 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 11:22:52 +0200 Subject: [PATCH 227/490] small fix year count --- src/solver/simulation/economy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index b2a6d611e3..60dd99d090 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -105,7 +105,7 @@ void AdequacyPatchOptimization::solve(Variable::State& state, hourlyCsrProblem.run(); } double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); - logs.info() << "[adq-patch] Year:" << state.year << " Week:" << w + 1 + logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 << ".Total LMR violation:" << totalLmrViolation; } From 93f3258b982086ecaf64e8f91f73a2137389b85f Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 11:26:57 +0200 Subject: [PATCH 228/490] hot start --- .../opt_gestion_des_bornes_cas_quadratique.cpp | 11 +++++++---- 1 file changed, 7 insertions(+), 4 deletions(-) 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 061f438f54..3dc6e42014 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -117,8 +117,9 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr ProblemeAResoudre->Xmin[Var] = 0.0; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour] - = 0.0; + ProblemeAResoudre->X[Var] + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; + AdresseDuResultat = &( ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); @@ -154,8 +155,9 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& ProblemeAResoudre->Xmin[Var] = 0.0; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour] - = 0.0; + ProblemeAResoudre->X[Var] + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]; + AdresseDuResultat = &( ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); @@ -201,6 +203,7 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; if (Math::Infinite(Xmax[Var]) == 1) { From fe10ab2a135c5e52a2b63a32fd62b405222d6344 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 11:30:01 +0200 Subject: [PATCH 229/490] relax var bounds --- .../opt_gestion_des_bornes_cas_quadratique.cpp | 16 ++++++++-------- 1 file changed, 8 insertions(+), 8 deletions(-) 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 3dc6e42014..cd86211c43 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -114,7 +114,7 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - ProblemeAResoudre->Xmin[Var] = 0.0; + ProblemeAResoudre->Xmin[Var] = -1e-3; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; ProblemeAResoudre->X[Var] @@ -152,7 +152,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; - ProblemeAResoudre->Xmin[Var] = 0.0; + ProblemeAResoudre->Xmin[Var] = -1e-3; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; ProblemeAResoudre->X[Var] @@ -201,8 +201,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC { // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + 1e-3; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - 1e-3; ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; if (Math::Infinite(Xmax[Var]) == 1) @@ -237,8 +237,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC // else // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = 0.0; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin[Var] = -1e-3; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + 1e-3; ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { @@ -257,8 +257,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC // else // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - Xmin[Var] = 0.0; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + Xmin[Var] = -1e-3; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + 1e-3; ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { From 6b66ff9271e835d6cf8c5e875bfc185afc9045fb Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 11:43:31 +0200 Subject: [PATCH 230/490] remove ENS <= densNew constraint, set as var bound --- ...atrice_des_contraintes_cas_quadratique.cpp | 80 +++++++++---------- ...ction_variables_optimisees_quadratique.cpp | 2 +- ...opt_gestion_des_bornes_cas_quadratique.cpp | 2 +- ..._gestion_second_membre_cas_quadratique.cpp | 46 +++++------ 4 files changed, 65 insertions(+), 65 deletions(-) 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 index 089106ea22..f384541c97 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -94,45 +94,45 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* MemFree(Colonne); } -void setConstraintsOnENS(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Area; - int Var; - int NombreDeTermes; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // constraint: ENS < DENS_new - for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - NombreDeTermes = 0; - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; - - hourlyCsrProblem.numberOfConstraintCsrEns[Area] - = ProblemeAResoudre->NombreDeContraintes; - NomDeLaContrainte = "ENS < DENS_new. Area:" + std::to_string(Area) + "; " - + ProblemeHebdo->NomsDesPays[Area]; - logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '<', NomDeLaContrainte); - } - } -} +// void setConstraintsOnENS(PROBLEME_HEBDO* ProblemeHebdo, +// HOURLY_CSR_PROBLEM& hourlyCsrProblem, +// double* Pi, +// int* Colonne) +// { +// int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; +// int Area; +// int Var; +// int NombreDeTermes; +// CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; +// PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; +// std::string NomDeLaContrainte; + +// ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; +// CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + +// // constraint: ENS < DENS_new +// for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) +// { +// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] +// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) +// { +// NombreDeTermes = 0; +// Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; +// Pi[NombreDeTermes] = 1.0; +// Colonne[NombreDeTermes] = Var; +// NombreDeTermes++; + +// hourlyCsrProblem.numberOfConstraintCsrEns[Area] +// = ProblemeAResoudre->NombreDeContraintes; +// NomDeLaContrainte = "ENS < DENS_new. Area:" + std::to_string(Area) + "; " +// + ProblemeHebdo->NomsDesPays[Area]; +// logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " +// << NomDeLaContrainte; +// OPT_ChargerLaContrainteDansLaMatriceDesContraintes( +// ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '<', NomDeLaContrainte); +// } +// } +// } void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem, @@ -413,7 +413,7 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( ProblemeAResoudre->NombreDeContraintes = 0; ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - setConstraintsOnENS(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + // setConstraintsOnENS(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); setConstraintsOnFlows(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); setNodeBalanceConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); setBindingConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index b7e619a434..695754a1d7 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -77,7 +77,7 @@ void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hou { CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; logs.debug() << NumberOfVariables << " ENS[" << area << "]. "; NumberOfVariables++; 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 cd86211c43..fdb1262d7e 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -115,7 +115,7 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; ProblemeAResoudre->Xmin[Var] = -1e-3; - ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; + ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area] + 1e-3; ProblemeAResoudre->X[Var] = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; 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 f8a90bdfa1..241502e338 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -48,28 +48,28 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme } } -void setRHSvalueOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Cnt; - int Area; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - // constraint for each area inside adq patch: ENS < DENS_new - for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); - if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) - Cnt = it->second; - ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.densNewValues[Area]; - logs.debug() << Cnt << ": ENS < DENS_new: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - } - } -} +// void setRHSvalueOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +// { +// int Cnt; +// int Area; +// PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; +// ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + +// // constraint for each area inside adq patch: ENS < DENS_new +// for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) +// { +// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] +// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) +// { +// std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); +// if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) +// Cnt = it->second; +// ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.densNewValues[Area]; +// logs.debug() << Cnt << ": ENS < DENS_new: RHS[" << Cnt +// << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; +// } +// } +// } void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { @@ -247,7 +247,7 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob { logs.debug() << "[CSR] RHS: "; - setRHSvalueOnENS(ProblemeHebdo, hourlyCsrProblem); + // setRHSvalueOnENS(ProblemeHebdo, hourlyCsrProblem); setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); From 30ca7360b3b9657c78c77017d92847dfcef414d5 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 11:45:15 +0200 Subject: [PATCH 231/490] remove set values to NaN if csr solver fails --- .../optimisation/opt_appel_solveur_quadratique.cpp | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 2ea99b704a..ecf8e08ecd 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -263,12 +263,12 @@ void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, logs.warning() << "CSR Quadratic Optimization: No solution, hour in week: " << hourlyCsrProblem.hourInWeekTriggeredCsr; // todo refactoring - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; - if (pt) - *pt = std::numeric_limits::quiet_NaN(); - } + // for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + // { + // pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + // if (pt) + // *pt = std::numeric_limits::quiet_NaN(); + // } #ifndef NDEBUG From 9a973962b2b97f78021845212639f0871dbee69c Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 11:51:14 +0200 Subject: [PATCH 232/490] relax bining constrains for csr solver --- .../opt_gestion_second_membre_cas_quadratique.cpp | 8 ++++++++ 1 file changed, 8 insertions(+) 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 241502e338..045df0ef4e 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -238,6 +238,14 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids << ", ValueOfVar:" << ValueOfVar; } + if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') + { + SecondMembre[Cnt] += 1e+3; + } + else if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '>') + { + SecondMembre[Cnt] -= 1e-3; + } } } } From 849722cd028b59eda670a630dd97e5600c0904ca Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 12:08:45 +0200 Subject: [PATCH 233/490] make csr crash log more expressive --- src/solver/optimisation/adequacy_patch.cpp | 8 ++++---- .../opt_appel_solveur_quadratique.cpp | 16 +++++++++++----- src/solver/optimisation/opt_fonctions.h | 2 +- src/solver/simulation/economy.cpp | 2 +- .../sim_structure_probleme_economique.h | 4 ++-- 5 files changed, 19 insertions(+), 13 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 949ebbd6ce..ee7f2f79d9 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -292,12 +292,12 @@ void HOURLY_CSR_PROBLEM::setProblemCost() OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblemBelongedTo, *this); } -void HOURLY_CSR_PROBLEM::solveProblem() +void HOURLY_CSR_PROBLEM::solveProblem(uint week, int year) { - OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this); + OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this, week, year); } -void HOURLY_CSR_PROBLEM::run() +void HOURLY_CSR_PROBLEM::run(uint week, int year) { resetProblem(); calculateCsrParameters(); @@ -306,5 +306,5 @@ void HOURLY_CSR_PROBLEM::run() setVariableBounds(); buildProblemConstraintsRHS(); setProblemCost(); - solveProblem(); + solveProblem(week, year); } \ No newline at end of file diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index ecf8e08ecd..878f269bca 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -256,12 +256,16 @@ void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) } void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb) { int Var; double* pt; - logs.warning() << "CSR Quadratic Optimization: No solution, hour in week: " - << hourlyCsrProblem.hourInWeekTriggeredCsr; // todo refactoring + logs.warning() + << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " + << yearNb + 1 << ". week: " << weekNb + 1 + << ". hour: " << hourlyCsrProblem.hourInWeekTriggeredCsr; // for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) // { @@ -311,7 +315,9 @@ void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, } bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb) { PROBLEME_POINT_INTERIEUR Probleme; setInteriorPointProblem(ProblemeAResoudre, Probleme); @@ -324,7 +330,7 @@ bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeARes } else { - handleInteriorPointError(ProblemeAResoudre, hourlyCsrProblem); + handleInteriorPointError(ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb); return false; } } \ No newline at end of file diff --git a/src/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/opt_fonctions.h index 0f0efe1daf..bf6f764d7e 100644 --- a/src/solver/optimisation/opt_fonctions.h +++ b/src/solver/optimisation/opt_fonctions.h @@ -55,7 +55,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); -bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&); +bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&, uint week, int year); bool OPT_PilotageOptimisationLineaire(PROBLEME_HEBDO*, uint); void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 60dd99d090..e9b3451fea 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -102,7 +102,7 @@ void AdequacyPatchOptimization::solve(Variable::State& state, for (int hourInWeek : hoursRequiringCurtailmentSharing) { HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); - hourlyCsrProblem.run(); + hourlyCsrProblem.run(w, state.year); } double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index fc5b74db11..2cde9b18cd 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -727,9 +727,9 @@ class HOURLY_CSR_PROBLEM void buildProblemConstraintsLHS(); void buildProblemConstraintsRHS(); void setProblemCost(); - void solveProblem(); + void solveProblem(uint week, int year); public: - void run(); + void run(uint week, int year); public: int hourInWeekTriggeredCsr; PROBLEME_HEBDO* pWeeklyProblemBelongedTo; From c2995dac5f15affeb4926b66d79884b75572208d Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 13:12:47 +0200 Subject: [PATCH 234/490] clean some logs --- ...atrice_des_contraintes_cas_quadratique.cpp | 16 ++++---- ..._gestion_second_membre_cas_quadratique.cpp | 39 ++++++++++--------- 2 files changed, 28 insertions(+), 27 deletions(-) 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 index f384541c97..85c8f1044e 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -362,14 +362,14 @@ void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, Colonne[NombreDeTermes] = Var; NombreDeTermes++; - logs.debug() - << "Interco:" + std::to_string(Interco) << ". Between:[" - << ProblemeHebdo - ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - << "]-[" - << ProblemeHebdo - ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - << "], with Poids(coeff):" + std::to_string(Poids) + " inserted to LHS!"; + // logs.debug() + // << "Interco:" + std::to_string(Interco) << ". Between:[" + // << ProblemeHebdo + // ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + // << "]-[" + // << ProblemeHebdo + // ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + // << "], with Poids(coeff):" + std::to_string(Poids) + " inserted to LHS!"; } } } 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 045df0ef4e..c043c7ff54 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -173,9 +173,9 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, // 1. The original RHS of bingding constraint SecondMembre[Cnt] = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; - logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt - << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante - << ")"; + // logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt + // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante + // << ")"; // 2. RHS part 2: flow other than 2<->2 NbInterco @@ -192,17 +192,17 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, { ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; SecondMembre[Cnt] -= ValueOfFlow * Poids; - logs.debug() - << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt - << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" - << ". Interco;" + std::to_string(Interco) << ". Between:[" - << ProblemeHebdo - ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - << "]-[" - << ProblemeHebdo - ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - << "]" - << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; + // logs.debug() + // << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt + // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" + // << ". Interco;" + std::to_string(Interco) << ". Between:[" + // << ProblemeHebdo + // ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + // << "]-[" + // << ProblemeHebdo + // ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + // << "]" + // << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; } } @@ -232,11 +232,11 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; SecondMembre[Cnt] -= ValueOfVar * Poids; - logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt - << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante - << ")" - << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids - << ", ValueOfVar:" << ValueOfVar; + // logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt + // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante + // << ")" + // << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids + // << ", ValueOfVar:" << ValueOfVar; } if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') { @@ -246,6 +246,7 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, { SecondMembre[Cnt] -= 1e-3; } + logs.debug() << Cnt << ": Hourly bc: -RHS[" << Cnt << "] = " << SecondMembre[Cnt]; } } } From b1bfeba1fc7ea82c840350204a35137961ff6bd5 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 19 Jul 2022 13:57:59 +0200 Subject: [PATCH 235/490] beta 3 -> beta 4 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 883bb7068e..0fc441712e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -12,7 +12,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 0) +set(ANTARES_BETA 4) set(ANTARES_RC 0) # OR-Tools tag From 73e259bd951affa3865d1999edd5915f589ca99f Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 21 Jul 2022 16:22:23 +0200 Subject: [PATCH 236/490] wrong relaxation of bc - bug fix --- src/CMakeLists.txt | 2 +- .../optimisation/opt_gestion_second_membre_cas_quadratique.cpp | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 0fc441712e..ac17b7b8fd 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -12,7 +12,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 4) +set(ANTARES_BETA 5) set(ANTARES_RC 0) # OR-Tools tag 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 c043c7ff54..b0c55140f1 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -240,7 +240,7 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, } if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') { - SecondMembre[Cnt] += 1e+3; + SecondMembre[Cnt] += 1e-3; } else if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '>') { From 6c95b9693d4a157484cc7eb75295d85ce3d5244b Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Jul 2022 11:55:18 +0200 Subject: [PATCH 237/490] logg out triggered csr hours --- src/solver/simulation/economy.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index e9b3451fea..dbcd62fb84 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -101,6 +101,8 @@ void AdequacyPatchOptimization::solve(Variable::State& state, std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) { + logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 + << " Hour:" << w * 168 + hourInWeek + 1; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); hourlyCsrProblem.run(w, state.year); } From 1b90fbbe2b43e03f81c56220b58c8be9f95a9c5d Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Jul 2022 11:55:44 +0200 Subject: [PATCH 238/490] refacto 1e-3 --- ...opt_gestion_des_bornes_cas_quadratique.cpp | 19 ++++++++++--------- ..._gestion_second_membre_cas_quadratique.cpp | 6 ++++-- 2 files changed, 14 insertions(+), 11 deletions(-) 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 fdb1262d7e..cf52ac9484 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -39,6 +39,7 @@ #include #define ZERO_POUR_LES_VARIABLES_FIXES 1.e-6 +const double csrSolverRelaxation = 1e-3; using namespace Yuni; @@ -114,8 +115,8 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - ProblemeAResoudre->Xmin[Var] = -1e-3; - ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area] + 1e-3; + ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; + ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area] + csrSolverRelaxation; ProblemeAResoudre->X[Var] = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; @@ -152,7 +153,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& { Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; - ProblemeAResoudre->Xmin[Var] = -1e-3; + ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; ProblemeAResoudre->X[Var] @@ -201,8 +202,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC { // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + 1e-3; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - 1e-3; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - csrSolverRelaxation; ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; if (Math::Infinite(Xmax[Var]) == 1) @@ -237,8 +238,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC // else // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin[Var] = -1e-3; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + 1e-3; + Xmin[Var] = -csrSolverRelaxation; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { @@ -257,8 +258,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC // else // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - Xmin[Var] = -1e-3; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + 1e-3; + Xmin[Var] = -csrSolverRelaxation; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { 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 b0c55140f1..afc18db7c4 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -25,6 +25,8 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ +const double csrSolverRelaxationRHS = 1e-3; + #include "opt_structure_probleme_a_resoudre.h" #include "../simulation/simulation.h" @@ -240,11 +242,11 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, } if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') { - SecondMembre[Cnt] += 1e-3; + SecondMembre[Cnt] += csrSolverRelaxationRHS; } else if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '>') { - SecondMembre[Cnt] -= 1e-3; + SecondMembre[Cnt] -= csrSolverRelaxationRHS; } logs.debug() << Cnt << ": Hourly bc: -RHS[" << Cnt << "] = " << SecondMembre[Cnt]; } From 80a813e6ed4e40594edb2959f42884da01801a40 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Jul 2022 11:56:19 +0200 Subject: [PATCH 239/490] logg out csr warnings - refacto --- src/solver/optimisation/opt_appel_solveur_quadratique.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 878f269bca..1300fa670a 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -264,8 +264,7 @@ void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, double* pt; logs.warning() << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " - << yearNb + 1 << ". week: " << weekNb + 1 - << ". hour: " << hourlyCsrProblem.hourInWeekTriggeredCsr; + << yearNb + 1 << ". hour: " << weekNb * 168 + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; // for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) // { From 890cfea9f4d20c8545199304d8f41430825d4dbd Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Jul 2022 18:08:27 +0200 Subject: [PATCH 240/490] update antares output dens value --- .../optimisation/opt_gestion_des_bornes_cas_quadratique.cpp | 4 ++++ 1 file changed, 4 insertions(+) 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 cf52ac9484..992e1bade9 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -127,6 +127,10 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; + // update DENS values with densNew values + // ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] + // = hourlyCsrProblem.densNewValues[area]; + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; } From f7d94b6bb6be9e8d36a671ab6cfcdddc09e417ca Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 26 Jul 2022 19:22:52 +0200 Subject: [PATCH 241/490] more expressive log --- ...onstruction_variables_optimisees_quadratique.cpp | 13 ++++++++++--- 1 file changed, 10 insertions(+), 3 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 695754a1d7..481ba37158 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -78,7 +78,8 @@ void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hou CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " ENS[" << area << "]. "; + logs.debug() << NumberOfVariables << " ENS[" << area << "].-[" + << ProblemeHebdo->NomsDesPays[area] << "]."; NumberOfVariables++; } @@ -108,7 +109,8 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; - logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "]. "; + logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "].-[" + << ProblemeHebdo->NomsDesPays[area] << "]."; NumberOfVariables++; } @@ -140,7 +142,12 @@ void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " flow[" << Interco << "]. "; + logs.debug() + << NumberOfVariables << " flow[" << Interco << "]. [" + << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + << "]-[" + << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + << "]."; NumberOfVariables++; CorrespondanceVarNativesVarOptim From 4a02e5a25990b2024d3a72eed22a382ec18f4e89 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 10:31:55 +0200 Subject: [PATCH 242/490] update dens and use it as pto --- .../optimisation/opt_gestion_des_bornes_cas_quadratique.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 992e1bade9..3834e6870e 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -128,8 +128,8 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr = AdresseDuResultat; // update DENS values with densNew values - // ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] - // = hourlyCsrProblem.densNewValues[area]; + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] + = hourlyCsrProblem.densNewValues[area]; logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; From 2cd3644fb8e2e16793c0be1ac119ee39f6694470 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 10:35:54 +0200 Subject: [PATCH 243/490] dont include linear cost coeff - temporary beta6 only --- .../optimisation/opt_gestion_des_couts_cas_quadratique.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 fbfb8573b9..e80f2a91a4 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -188,5 +188,5 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, ProblemeAResoudre->NombreDeVariables * sizeof(double)); setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); - setLinearCost(ProblemeHebdo, hourlyCsrProblem); + // setLinearCost(ProblemeHebdo, hourlyCsrProblem); // only for Daniel-Elia beta6 version - TEMPORARY!!!! } \ No newline at end of file From a48f02bdc3bc070016d2334e2eeb2e5b304e0e5c Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 10:36:26 +0200 Subject: [PATCH 244/490] beta5->beta6 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ac17b7b8fd..9a3be70c65 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -12,7 +12,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 5) +set(ANTARES_BETA 6) set(ANTARES_RC 0) # OR-Tools tag From ede9966334f02cd03b998e6ceb87f9c2d6b2d025 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:18:51 +0200 Subject: [PATCH 245/490] 10. bring back type of var to origin quad solver - mistake --- .../opt_construction_variables_optimisees_quadratique.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 481ba37158..fc4fbe3749 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -52,7 +52,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H { CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NombreDeVariables; - ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + ProblemeAResoudre->TypeDeVariable[NombreDeVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; NombreDeVariables++; } ProblemeAResoudre->NombreDeVariables = NombreDeVariables; From 305719f2a1b3d7adad5a934d36465337b0bc13dc Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:23:02 +0200 Subject: [PATCH 246/490] 2. remove default values for the solver accuracy --- src/solver/optimisation/opt_appel_solveur_quadratique.cpp | 5 ----- 1 file changed, 5 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 1300fa670a..2d75aaa730 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -194,13 +194,8 @@ void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, double ToleranceSurLaComplementarite; int ChoixToleranceParDefautSurLaComplementarite; - ToleranceSurLAdmissibilite = 1.e-5; ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; - - ToleranceSurLaStationnarite = 1.e-5; ChoixToleranceParDefautSurLaStationnarite = OUI_PI; - - ToleranceSurLaComplementarite = 1.e-5; ChoixToleranceParDefautSurLaComplementarite = OUI_PI; Probleme.NombreMaxDIterations = -1; From c025c08410eb3a8afb36c814c629233401072ef1 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:25:59 +0200 Subject: [PATCH 247/490] change function name to ADQ_PATCH_CSR --- src/solver/optimisation/adequacy_patch.cpp | 2 +- src/solver/optimisation/opt_appel_solveur_quadratique.cpp | 8 ++++---- src/solver/optimisation/opt_fonctions.h | 2 +- 3 files changed, 6 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index ee7f2f79d9..5abf96d2b5 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -294,7 +294,7 @@ void HOURLY_CSR_PROBLEM::setProblemCost() void HOURLY_CSR_PROBLEM::solveProblem(uint week, int year) { - OPT_AppelDuSolveurQuadratique_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this, week, year); + ADQ_PATCH_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this, week, year); } void HOURLY_CSR_PROBLEM::run(uint week, int year) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 2d75aaa730..ccaa653cd4 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -308,10 +308,10 @@ void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, #endif } -bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb) +bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb) { PROBLEME_POINT_INTERIEUR Probleme; setInteriorPointProblem(ProblemeAResoudre, Probleme); diff --git a/src/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/opt_fonctions.h index bf6f764d7e..6fd9bc5bcd 100644 --- a/src/solver/optimisation/opt_fonctions.h +++ b/src/solver/optimisation/opt_fonctions.h @@ -55,7 +55,7 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); -bool OPT_AppelDuSolveurQuadratique_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&, uint week, int year); +bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&, uint week, int year); bool OPT_PilotageOptimisationLineaire(PROBLEME_HEBDO*, uint); void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); From f4fec6a438e2c6a19aee1eedb91577ea1aed284d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:28:40 +0200 Subject: [PATCH 248/490] 6. remove comments --- ...atrice_des_contraintes_cas_quadratique.cpp | 41 ------------------- ..._gestion_second_membre_cas_quadratique.cpp | 24 ----------- 2 files changed, 65 deletions(-) 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 index 85c8f1044e..708f302fb3 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -94,46 +94,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* MemFree(Colonne); } -// void setConstraintsOnENS(PROBLEME_HEBDO* ProblemeHebdo, -// HOURLY_CSR_PROBLEM& hourlyCsrProblem, -// double* Pi, -// int* Colonne) -// { -// int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; -// int Area; -// int Var; -// int NombreDeTermes; -// CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; -// PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; -// std::string NomDeLaContrainte; - -// ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; -// CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - -// // constraint: ENS < DENS_new -// for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) -// { -// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] -// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// { -// NombreDeTermes = 0; -// Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; -// Pi[NombreDeTermes] = 1.0; -// Colonne[NombreDeTermes] = Var; -// NombreDeTermes++; - -// hourlyCsrProblem.numberOfConstraintCsrEns[Area] -// = ProblemeAResoudre->NombreDeContraintes; -// NomDeLaContrainte = "ENS < DENS_new. Area:" + std::to_string(Area) + "; " -// + ProblemeHebdo->NomsDesPays[Area]; -// logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " -// << NomDeLaContrainte; -// OPT_ChargerLaContrainteDansLaMatriceDesContraintes( -// ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '<', NomDeLaContrainte); -// } -// } -// } - void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem, double* Pi, @@ -413,7 +373,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( ProblemeAResoudre->NombreDeContraintes = 0; ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - // setConstraintsOnENS(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); setConstraintsOnFlows(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); setNodeBalanceConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); setBindingConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); 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 afc18db7c4..1892c7124c 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -50,29 +50,6 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme } } -// void setRHSvalueOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -// { -// int Cnt; -// int Area; -// PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; -// ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - -// // constraint for each area inside adq patch: ENS < DENS_new -// for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) -// { -// if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] -// == Data::AdequacyPatch::physicalAreaInsideAdqPatch) -// { -// std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrEns.find(Area); -// if (it != hourlyCsrProblem.numberOfConstraintCsrEns.end()) -// Cnt = it->second; -// ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.densNewValues[Area]; -// logs.debug() << Cnt << ": ENS < DENS_new: RHS[" << Cnt -// << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; -// } -// } -// } - void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Cnt; @@ -258,7 +235,6 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* Prob { logs.debug() << "[CSR] RHS: "; - // setRHSvalueOnENS(ProblemeHebdo, hourlyCsrProblem); setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); From 8ffd5cc386101ed89bda0c94d55947969f6c92a8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:33:27 +0200 Subject: [PATCH 249/490] 7. remove nused transport cost --- ...struction_matrice_des_contraintes_cas_quadratique.cpp | 3 --- .../opt_gestion_second_membre_cas_quadratique.cpp | 9 +-------- 2 files changed, 1 insertion(+), 11 deletions(-) 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 index 708f302fb3..1074326ca7 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -106,7 +106,6 @@ void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; std::string NomDeLaContrainte; - COUTS_DE_TRANSPORT* TransportCost; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; @@ -120,8 +119,6 @@ void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - NombreDeTermes = 0; Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; if (Var >= 0) 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 1892c7124c..5aa38b4508 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -54,7 +54,6 @@ void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourl { int Cnt; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - COUTS_DE_TRANSPORT* TransportCost; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of @@ -66,17 +65,11 @@ void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourl && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) Cnt = it->second; - // CSR Todo? loop flow? - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->ValeursDeNTC[hour] - // ->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else + ProblemeAResoudre->SecondMembre[Cnt] = 0.; logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; From dbb372cc255e1777280852e4d4eb9ac83b450bd4 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:35:39 +0200 Subject: [PATCH 250/490] 9. remove comments --- ...struction_matrice_des_contraintes_cas_quadratique.cpp | 9 --------- 1 file changed, 9 deletions(-) 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 index 1074326ca7..c06c5a0101 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -318,15 +318,6 @@ void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, Pi[NombreDeTermes] = Poids; Colonne[NombreDeTermes] = Var; NombreDeTermes++; - - // logs.debug() - // << "Interco:" + std::to_string(Interco) << ". Between:[" - // << ProblemeHebdo - // ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - // << "]-[" - // << ProblemeHebdo - // ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - // << "], with Poids(coeff):" + std::to_string(Poids) + " inserted to LHS!"; } } } From db43049e194c0ea8df2858456d271f4dec2b1525 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:52:10 +0200 Subject: [PATCH 251/490] 11. refacto - int NumberOfVariables --- .../opt_construction_variables_optimisees_quadratique.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index fc4fbe3749..3f863d9db8 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -95,7 +95,7 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int NumberOfVariables = ProblemeAResoudre->NombreDeVariables; + int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; // variables: Spilled Energy of each area inside adq patch // todo after debugging transfer this into same area loop as ENS @@ -115,7 +115,6 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, NumberOfVariables++; } } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; } void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -125,7 +124,7 @@ void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int NumberOfVariables = ProblemeAResoudre->NombreDeVariables; + int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 // and 2. @@ -165,7 +164,6 @@ void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h NumberOfVariables++; } } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; } void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( From 51d9f016fbab54853c2905f45dc4b97f8a68ccdf Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 16:56:26 +0200 Subject: [PATCH 252/490] 8. remove NomDeLaContrainte --- ...onstruction_matrice_des_contraintes_cas_quadratique.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) 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 index c06c5a0101..bd2ae25bad 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -152,7 +152,7 @@ void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, << NomDeLaContrainte; OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); } } } @@ -264,7 +264,7 @@ void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, << NomDeLaContrainte; OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '=', NomDeLaContrainte); + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); } } } @@ -338,8 +338,7 @@ void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, Pi, Colonne, NombreDeTermes, - MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante, - NomDeLaContrainte); + MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante); } } } From 0125a832be9b96fbc2e1bd83908a82f22f9934ea Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 28 Jul 2022 17:26:17 +0200 Subject: [PATCH 253/490] bring back linear hurdle costs --- .../optimisation/opt_gestion_des_couts_cas_quadratique.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e80f2a91a4..fbfb8573b9 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -188,5 +188,5 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, ProblemeAResoudre->NombreDeVariables * sizeof(double)); setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); - // setLinearCost(ProblemeHebdo, hourlyCsrProblem); // only for Daniel-Elia beta6 version - TEMPORARY!!!! + setLinearCost(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file From 4abef1cc34201eb7ba973cb6986f37c5763e2528 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Jul 2022 09:46:50 +0200 Subject: [PATCH 254/490] set to zero ENS & spillage if below threshold (avoid LOLP=100% dummy values) --- .../opt_appel_solveur_quadratique.cpp | 17 +++++++++++++++-- ...ruction_variables_optimisees_quadratique.cpp | 2 ++ .../sim_structure_probleme_economique.h | 3 +++ 3 files changed, 20 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index ccaa653cd4..932e2d5916 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -237,7 +237,17 @@ void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, Probleme.CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; } -void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) +void setToZeroIfBelowThreshold(double* pt, int Var, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + bool inSet = hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.find(Var) + != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); + bool belowLimit = *pt < hourlyCsrProblem.belowThisThresholdSetToZero; + if (inSet && belowLimit) + *pt = 0.0; +} + +void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; double* pt; @@ -245,7 +255,10 @@ void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; if (pt) + { *pt = ProblemeAResoudre->X[Var]; + setToZeroIfBelowThreshold(pt, Var, hourlyCsrProblem); + } logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; } } @@ -319,7 +332,7 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) { - storeInteriorPointResults(ProblemeAResoudre); + storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); return true; } else diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 3f863d9db8..f257ca74aa 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -78,6 +78,7 @@ void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hou CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); logs.debug() << NumberOfVariables << " ENS[" << area << "].-[" << ProblemeHebdo->NomsDesPays[area] << "]."; @@ -109,6 +110,7 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "].-[" << ProblemeHebdo->NomsDesPays[area] << "]."; diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 2cde9b18cd..47f88fa5d5 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -732,6 +732,7 @@ class HOURLY_CSR_PROBLEM void run(uint week, int year); public: int hourInWeekTriggeredCsr; + const double belowThisThresholdSetToZero = 1e-3; PROBLEME_HEBDO* pWeeklyProblemBelongedTo; HOURLY_CSR_PROBLEM(int hourInWeek, PROBLEME_HEBDO* pProblemeHebdo) { @@ -746,6 +747,8 @@ class HOURLY_CSR_PROBLEM std::map densNewValues; std::map rhsAreaBalanceValues; + + std::set varToBeSetToZeroIfBelowThreshold; // place inside only ENS and Spillage variable }; #endif From 63cc8293aa80a31962bc5a53d8bc83b2a449974b Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Jul 2022 10:09:38 +0200 Subject: [PATCH 255/490] small refacto --- src/solver/simulation/economy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index dbcd62fb84..a7fcd295f9 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -102,7 +102,7 @@ void AdequacyPatchOptimization::solve(Variable::State& state, for (int hourInWeek : hoursRequiringCurtailmentSharing) { logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 - << " Hour:" << w * 168 + hourInWeek + 1; + << " Hour:" << w * nbHoursInAWeek + hourInWeek + 1; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); hourlyCsrProblem.run(w, state.year); } From 3eba8e4fc26c4c91f4a9b90657cbe29fa0df14bc Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Jul 2022 10:13:21 +0200 Subject: [PATCH 256/490] 4. make subfunction CSR_DEBUG_BLAH --- .../opt_appel_solveur_quadratique.cpp | 87 +++++++++---------- 1 file changed, 41 insertions(+), 46 deletions(-) diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 932e2d5916..03d10ef8c0 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -263,61 +263,56 @@ void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, } } -void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb) +void CSR_DEBUG_BLAH(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { int Var; - double* pt; - logs.warning() - << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " - << yearNb + 1 << ". hour: " << weekNb * 168 + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; - // for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - // { - // pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; - // if (pt) - // *pt = std::numeric_limits::quiet_NaN(); - // } - -#ifndef NDEBUG + logs.info(); + logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; + logs.info() << "Here is the trace:"; + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { - logs.info(); - - logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; - - logs.info() << "Here is the trace:"; - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", + Var, + ProblemeAResoudre->CoutLineaire[Var], + ProblemeAResoudre->CoutQuadratique[Var]); + } + for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) + { + logs.info().appendFormat("Constraint %ld sens %c B %e", + Cnt, + ProblemeAResoudre->Sens[Cnt], + ProblemeAResoudre->SecondMembre[Cnt]); + + int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; + int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; + for (; il < ilMax; ++il) { - logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", + Var = ProblemeAResoudre->IndicesColonnes[il]; + logs.info().appendFormat(" coeff %e var %ld xmin %e xmax %e type %ld", + ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], Var, - ProblemeAResoudre->CoutLineaire[Var], - ProblemeAResoudre->CoutQuadratique[Var]); - } - for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) - { - logs.info().appendFormat("Constraint %ld sens %c B %e", - Cnt, - ProblemeAResoudre->Sens[Cnt], - ProblemeAResoudre->SecondMembre[Cnt]); - - int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; - int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; - for (; il < ilMax; ++il) - { - Var = ProblemeAResoudre->IndicesColonnes[il]; - logs.info().appendFormat( - " coeff %e var %ld xmin %e xmax %e type %ld", - ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], - Var, - ProblemeAResoudre->Xmin[Var], - ProblemeAResoudre->Xmax[Var], - ProblemeAResoudre->TypeDeVariable[Var]); - } + ProblemeAResoudre->Xmin[Var], + ProblemeAResoudre->Xmax[Var], + ProblemeAResoudre->TypeDeVariable[Var]); } } +} + +void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb) +{ + const int hoursInWeek = 168; + logs.warning() + << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " + << yearNb + 1 + << ". hour: " << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; + +#ifndef NDEBUG + CSR_DEBUG_BLAH(ProblemeAResoudre); #endif } From bd4164968d500897f36141fc05f63b217ee36d27 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Jul 2022 11:29:45 +0200 Subject: [PATCH 257/490] 1. move csr problem functions to separate directory --- src/solver/cmake/solver.cmake | 6 + .../construct_problem_constraints_LHS.cpp | 309 ++++++++++++++++++ .../construct_problem_constraints_RHS.cpp | 218 ++++++++++++ .../construct_problem_variables.cpp | 163 +++++++++ .../set_problem_cost_function.cpp | 167 ++++++++++ .../set_variable_boundaries.cpp | 240 ++++++++++++++ .../adequacy_patch_csr/solve_problem.cpp | 209 ++++++++++++ .../opt_appel_solveur_quadratique.cpp | 153 --------- ...atrice_des_contraintes_cas_quadratique.cpp | 274 ---------------- ...ction_variables_optimisees_quadratique.cpp | 127 ------- ...opt_gestion_des_bornes_cas_quadratique.cpp | 199 ----------- .../opt_gestion_des_couts_cas_quadratique.cpp | 133 -------- ..._gestion_second_membre_cas_quadratique.cpp | 183 ----------- 13 files changed, 1312 insertions(+), 1069 deletions(-) create mode 100644 src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp create mode 100644 src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp create mode 100644 src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp create mode 100644 src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp create mode 100644 src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp create mode 100644 src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp diff --git a/src/solver/cmake/solver.cmake b/src/solver/cmake/solver.cmake index 76e46d653b..f00087ad7c 100644 --- a/src/solver/cmake/solver.cmake +++ b/src/solver/cmake/solver.cmake @@ -53,6 +53,12 @@ set(RTESOLVER_OPT optimisation/opt_export_structure.cpp optimisation/adequacy_patch.h optimisation/adequacy_patch.cpp + optimisation/adequacy_patch_csr/solve_problem.cpp + optimisation/adequacy_patch_csr/set_variable_boundaries.cpp + optimisation/adequacy_patch_csr/set_problem_cost_function.cpp + optimisation/adequacy_patch_csr/construct_problem_variables.cpp + optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp + optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp utils/ortools_utils.h utils/ortools_utils.cpp diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp new file mode 100644 index 0000000000..2257aa05d2 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp @@ -0,0 +1,309 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "../solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../solver/simulation/simulation.h" +#include "../solver/simulation/sim_structure_donnees.h" +#include "../solver/simulation/sim_extern_variables_globales.h" +#include "../solver/optimisation/opt_fonctions.h" + +using namespace Antares::Data; + +void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Var; + int NombreDeTermes; + int Interco; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + std::string NomDeLaContrainte; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of + // type 2. + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + NombreDeTermes = 0; + 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; + + NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); + logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); + } + } +} + +void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Area; + int Var; + int NombreDeTermes; + int Interco; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + std::string NomDeLaContrainte; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // constraint: + // ENS(node A) + + // - flow (A -> 2) or (+ flow (2 -> A)) there should be only one of them, otherwise double-count + // - spillage(node A) = + // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) + // for all areas inside adequacy patch + + for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + // + ENS + NombreDeTermes = 0; + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; + if (Var >= 0) + { + Pi[NombreDeTermes] = 1.0; + Colonne[NombreDeTermes] = Var; + NombreDeTermes++; + } + + // - export flows + Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; + while (Interco >= 0) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + 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) + { + 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; + + NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " + + ProblemeHebdo->NomsDesPays[Area]; + ; + logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); + } + } +} + +void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + double* Pi, + int* Colonne) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Var; + int NombreDeTermes; + int Interco; + int NbInterco; + double Poids; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + std::string NomDeLaContrainte; + + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // Special case of the binding constraints + for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; + CntCouplante++) + { + MatriceDesContraintesCouplantes + = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + + if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) + { + NbInterco + = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; + NombreDeTermes = 0; + for (int Index = 0; Index < NbInterco; Index++) + { + Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; + Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; + + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + 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; + + NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) + "::" + + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; + + logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " + << NomDeLaContrainte; + + OPT_ChargerLaContrainteDansLaMatriceDesContraintes( + ProblemeAResoudre, + Pi, + Colonne, + NombreDeTermes, + MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante); + } + } + } +} + +void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] constraint list:"; + double* Pi; + int* Colonne; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); + Colonne = (int*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(int)); + + ProblemeAResoudre->NombreDeContraintes = 0; + ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; + + setConstraintsOnFlows(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + setNodeBalanceConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + setBindingConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); + + MemFree(Pi); + MemFree(Colonne); +} \ No newline at end of file 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 new file mode 100644 index 0000000000..14cc4bf5a5 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp @@ -0,0 +1,218 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have received a copy of the GNU General Public License +** along with Antares_Simulator. If not, see . +** +** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions +*/ + +const double csrSolverRelaxationRHS = 1e-3; + +#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../solver/simulation/simulation.h" +#include "../solver/simulation/sim_extern_variables_globales.h" + +#include "../solver/optimisation/opt_fonctions.h" + +void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Cnt; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of + // type 2. + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + std::map::iterator it + = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); + if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) + Cnt = it->second; + + ProblemeAResoudre->SecondMembre[Cnt] = 0.; + logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + } + } +} + +void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Cnt; + int Area; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + // constraint: + // ENS(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) + // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) + // for all areas inside adequacy patch + + for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + std::map::iterator it + = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); + if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) + Cnt = it->second; + + ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; + logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area + << ")"; + } + } +} + +void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Cnt; + int Area; + int CntCouplante; + int Interco; + int NbInterco; + double Poids; + double ValueOfFlow; + int Index; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + double* SecondMembre = ProblemeAResoudre->SecondMembre; + CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; + std::map bingdingConstraintNumber + = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; + + // constraint: + // user defined Binding constraints between transmission flows + // and/or power generated from generating units. + for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; + CntCouplante++) + { + if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) + { + MatriceDesContraintesCouplantes + = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; + + Cnt = bingdingConstraintNumber[CntCouplante]; + + // 1. The original RHS of bingding constraint + SecondMembre[Cnt] + = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; + // logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt + // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante + // << ")"; + + // 2. RHS part 2: flow other than 2<->2 + NbInterco + = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; + for (Index = 0; Index < NbInterco; Index++) + { + Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; + Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; + + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + != Data::AdequacyPatch::physicalAreaInsideAdqPatch + || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + != Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; + SecondMembre[Cnt] -= ValueOfFlow * Poids; + // logs.debug() + // << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt + // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" + // << ". Interco;" + std::to_string(Interco) << ". Between:[" + // << ProblemeHebdo + // ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + // << "]-[" + // << ProblemeHebdo + // ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + // << "]" + // << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; + } + } + + // 3. RHS part 3: - cluster + int NbClusters + = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; + int Area; + int Palier; + int IndexNumeroDuPalierDispatch; + double ValueOfVar; + PALIERS_THERMIQUES* PaliersThermiquesDuPays; + + for (Index = 0; Index < NbClusters; Index++) + { + Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; + PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; + + IndexNumeroDuPalierDispatch + = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; + + Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques + [IndexNumeroDuPalierDispatch]; + Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; + + ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] + ->ProductionThermique[hour] + ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; + + SecondMembre[Cnt] -= ValueOfVar * Poids; + // logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt + // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante + // << ")" + // << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids + // << ", ValueOfVar:" << ValueOfVar; + } + if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') + { + SecondMembre[Cnt] += csrSolverRelaxationRHS; + } + else if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '>') + { + SecondMembre[Cnt] -= csrSolverRelaxationRHS; + } + logs.debug() << Cnt << ": Hourly bc: -RHS[" << Cnt << "] = " << SecondMembre[Cnt]; + } + } +} + +void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] RHS: "; + + setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); + setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); + setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); +} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp new file mode 100644 index 0000000000..d53ba569f5 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -0,0 +1,163 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "../solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../solver/simulation/simulation.h" +#include "../solver/simulation/sim_structure_donnees.h" +#include "../solver/simulation/sim_extern_variables_globales.h" + +#include "../solver/optimisation/opt_fonctions.h" + +#include "pi_constantes_externes.h" + +void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int NumberOfVariables = 0; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // variables: ENS of each area inside adq patch + logs.debug() << " ENS of each area inside adq patch: "; + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + // Only ENS for areas inside adq patch are considered as variables + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); + logs.debug() << NumberOfVariables << " ENS[" << area << "].-[" + << ProblemeHebdo->NomsDesPays[area] << "]."; + + NumberOfVariables++; + } + } + ProblemeAResoudre->NombreDeVariables = NumberOfVariables; +} + +void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; + + // variables: Spilled Energy of each area inside adq patch + // todo after debugging transfer this into same area loop as ENS + logs.debug() << " Spilled Energy of each area inside adq patch: "; + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + // Only Spilled Energy for areas inside adq patch are considered as variables + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; + hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); + logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "].-[" + << ProblemeHebdo->NomsDesPays[area] << "]."; + + NumberOfVariables++; + } + } +} + +void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; + + // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 + // and 2. + logs.debug() + << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + // only consider link between 2 and 2 + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() + << NumberOfVariables << " flow[" << Interco << "]. [" + << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] + << "]-[" + << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] + << "]."; + NumberOfVariables++; + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " direct flow[" << Interco << "]. "; + NumberOfVariables++; + + CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] + = NumberOfVariables; + ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + logs.debug() << NumberOfVariables << " indirect flow[" << Interco << "]. "; + NumberOfVariables++; + } + } +} + +void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] variable list:"; + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + assert(ProblemeAResoudre != NULL); + + constructVariableENS(ProblemeHebdo, hourlyCsrProblem); + constructVariableSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); + constructVariableFlows(ProblemeHebdo, hourlyCsrProblem); + + return; +} \ No newline at end of file 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 new file mode 100644 index 0000000000..871ad68090 --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp @@ -0,0 +1,167 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "../solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../solver/simulation/simulation.h" +#include "../solver/simulation/sim_structure_donnees.h" +#include "../solver/simulation/sim_extern_variables_globales.h" + +#include "../solver/optimisation/opt_fonctions.h" + +void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + double priceTakingOrders; // PTO + double quadraticCost; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // variables: ENS for each area inside adq patch + // obj function term is: 1 / (PTO * PTO) * ENS * ENS + // => quadratic cost: 1 / (PTO * PTO) + // => linear cost: 0 + // PTO can take two different values according to option: + // 1. from DENS + // 2. from load + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + if (ProblemeHebdo->adqPatchParams->PriceTakingOrder + == Data::AdequacyPatch::AdqPatchPTO::isLoad) + { + priceTakingOrders + = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] + + ProblemeHebdo->AllMustRunGeneration[hour] + ->AllMustRunGenerationOfArea[area]; + } + else if (ProblemeHebdo->adqPatchParams->PriceTakingOrder + == Data::AdequacyPatch::AdqPatchPTO::isDens) + { + priceTakingOrders + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; + } + + if (priceTakingOrders <= 0.0) + { + // CSR todo a warning that DENS is negative and it is considered for CSR, there + // was a check for positive threshold + quadraticCost = 0.0; + } + else + { + quadraticCost = 1 / (priceTakingOrders * priceTakingOrders); + } + + ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; + logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; + } + } + } +} + +void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + int Interco; + COUTS_DE_TRANSPORT* TransportCost; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // 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 + // flow_indirect ) + // => quadratic cost: 0 + // => linear cost: hurdle_cost_direct or hurdle_cost_indirect + // these members of objective functions are considered only if IntercoGereeAvecDesCouts = + // OUI_ANTARES (use hurdle cost option is true). otherwise these members are zero. + + for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; + // flow + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + 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]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) + ProblemeAResoudre->CoutLineaire[Var] = 0; + else + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + } + + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) + { + if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) + ProblemeAResoudre->CoutLineaire[Var] = 0; + else + ProblemeAResoudre->CoutLineaire[Var] + = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; + logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; + } + } + } +} + +void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] cost"; + + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + memset((char*)ProblemeAResoudre->CoutLineaire, + 0, + ProblemeAResoudre->NombreDeVariables * sizeof(double)); + + setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); + setLinearCost(ProblemeHebdo, hourlyCsrProblem); +} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp new file mode 100644 index 0000000000..2651940c5e --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -0,0 +1,240 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "../solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../solver/simulation/simulation.h" +#include "../solver/simulation/sim_structure_donnees.h" +#include "../solver/simulation/sim_extern_variables_globales.h" + +#include "../solver/optimisation/opt_fonctions.h" + +#include "pi_constantes_externes.h" + +#include +#include + +const double csrSolverRelaxation = 1e-3; +using namespace Yuni; + +void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* AdresseDuResultat; + int hour; + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // variables: ENS for each area inside adq patch + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; + + ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; + ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area] + csrSolverRelaxation; + + ProblemeAResoudre->X[Var] + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; + + AdresseDuResultat = &( + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); + + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] + = AdresseDuResultat; + + // update DENS values with densNew values + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] + = hourlyCsrProblem.densNewValues[area]; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; + } + } +} + +void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* AdresseDuResultat; + int hour; + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + + // variables: Spilled Energy for each area inside adq patch + // todo after debugging transfer this into same area loop as ENS + for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; + + ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; + ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; + + ProblemeAResoudre->X[Var] + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]; + + AdresseDuResultat = &( + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); + + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] + = AdresseDuResultat; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; + } + } +} + +void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* AdresseDuResultat; + int hour; + hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + int* TypeDeVariable; + double* Xmin; + double* Xmax; + Xmin = ProblemeAResoudre->Xmin; + Xmax = ProblemeAResoudre->Xmax; + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; + ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; + + // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links + // between nodes of type 2. Set hourly bounds for links between nodes of type 2, depending on + // the user input (max direct and indirect flow). + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) + { + // only consider link between 2 and 2 + if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch + && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] + == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) + { + // flow + Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; + Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - csrSolverRelaxation; + ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; + + if (Math::Infinite(Xmax[Var]) == 1) + { + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + else + { + if (Math::Infinite(Xmin[Var]) == -1) + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; + else + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + } + + AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] + = AdresseDuResultat; + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; + + // direct / indirect flow + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; + // CSR Todo? + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + + Xmin[Var] = -csrSolverRelaxation; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; + + Var = CorrespondanceVarNativesVarOptim + ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; + // CSR Todo? + // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; + // else + // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; + + Xmin[Var] = -csrSolverRelaxation; + Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; + if (Math::Infinite(Xmax[Var]) == 1) + { + ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; + } + + logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " + << ProblemeAResoudre->Xmax[Var]; + } + } +} + +void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( + PROBLEME_HEBDO* ProblemeHebdo, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + logs.debug() << "[CSR] bounds"; + + int Var; + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + + setBoundsOnENS(ProblemeHebdo, hourlyCsrProblem); + setBoundsOnSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); + setBoundsOnFlows(ProblemeHebdo, hourlyCsrProblem); +} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp new file mode 100644 index 0000000000..ef19275f0f --- /dev/null +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -0,0 +1,209 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "../solver/optimisation/opt_structure_probleme_a_resoudre.h" + +#include "../solver/simulation/simulation.h" +#include "../solver/simulation/sim_structure_donnees.h" +#include "../solver/simulation/sim_structure_probleme_economique.h" +#include "../solver/simulation/sim_structure_probleme_adequation.h" +#include "../solver/simulation/sim_extern_variables_globales.h" + +#include "../solver/optimisation/opt_fonctions.h" + +/* + pi_define.h doesn't include this header, yet it uses struct jmp_buf. + It would be nice to remove this include, but would require to change pi_define.h, + which isn't part of Antares +*/ +#include + +extern "C" +{ +#include "pi_define.h" +#include "pi_definition_arguments.h" +#include "pi_fonctions.h" +} + +#include + +using namespace Antares; + +void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + PROBLEME_POINT_INTERIEUR& Probleme) +{ + double ToleranceSurLAdmissibilite; + int ChoixToleranceParDefautSurLAdmissibilite; + double ToleranceSurLaStationnarite; + int ChoixToleranceParDefautSurLaStationnarite; + double ToleranceSurLaComplementarite; + int ChoixToleranceParDefautSurLaComplementarite; + + ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; + ChoixToleranceParDefautSurLaStationnarite = OUI_PI; + ChoixToleranceParDefautSurLaComplementarite = OUI_PI; + + Probleme.NombreMaxDIterations = -1; + Probleme.CoutQuadratique = ProblemeAResoudre->CoutQuadratique; + Probleme.CoutLineaire = ProblemeAResoudre->CoutLineaire; + Probleme.X = ProblemeAResoudre->X; + Probleme.Xmin = ProblemeAResoudre->Xmin; + Probleme.Xmax = ProblemeAResoudre->Xmax; + Probleme.NombreDeVariables = ProblemeAResoudre->NombreDeVariables; + Probleme.TypeDeVariable = ProblemeAResoudre->TypeDeVariable; + + Probleme.VariableBinaire = (char*)ProblemeAResoudre->CoutsReduits; + + Probleme.NombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; + Probleme.IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne; + Probleme.NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes; + Probleme.IndicesColonnes = ProblemeAResoudre->IndicesColonnes; + Probleme.CoefficientsDeLaMatriceDesContraintes + = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes; + Probleme.Sens = ProblemeAResoudre->Sens; + Probleme.SecondMembre = ProblemeAResoudre->SecondMembre; + + Probleme.AffichageDesTraces = NON_PI; + + Probleme.UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; + Probleme.ToleranceDAdmissibilite = ToleranceSurLAdmissibilite; + + Probleme.UtiliserLaToleranceDeStationnariteParDefaut + = ChoixToleranceParDefautSurLaStationnarite; + Probleme.ToleranceDeStationnarite = ToleranceSurLaStationnarite; + + Probleme.UtiliserLaToleranceDeComplementariteParDefaut + = ChoixToleranceParDefautSurLaComplementarite; + Probleme.ToleranceDeComplementarite = ToleranceSurLaComplementarite; + + Probleme.CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; + + Probleme.CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; + Probleme.CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; +} + +void setToZeroIfBelowThreshold(double* pt, int Var, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + bool inSet = hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.find(Var) + != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); + bool belowLimit = *pt < hourlyCsrProblem.belowThisThresholdSetToZero; + if (inSet && belowLimit) + *pt = 0.0; +} + +void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + int Var; + double* pt; + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; + if (pt) + { + *pt = ProblemeAResoudre->X[Var]; + setToZeroIfBelowThreshold(pt, Var, hourlyCsrProblem); + } + logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; + } +} + +void CSR_DEBUG_BLAH(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) +{ + int Var; + + logs.info(); + logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; + logs.info() << "Here is the trace:"; + + for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", + Var, + ProblemeAResoudre->CoutLineaire[Var], + ProblemeAResoudre->CoutQuadratique[Var]); + } + for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) + { + logs.info().appendFormat("Constraint %ld sens %c B %e", + Cnt, + ProblemeAResoudre->Sens[Cnt], + ProblemeAResoudre->SecondMembre[Cnt]); + + int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; + int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; + for (; il < ilMax; ++il) + { + Var = ProblemeAResoudre->IndicesColonnes[il]; + logs.info().appendFormat(" coeff %e var %ld xmin %e xmax %e type %ld", + ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], + Var, + ProblemeAResoudre->Xmin[Var], + ProblemeAResoudre->Xmax[Var], + ProblemeAResoudre->TypeDeVariable[Var]); + } + } +} + +void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb) +{ + const int hoursInWeek = 168; + logs.warning() + << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " + << yearNb + 1 + << ". hour: " << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; + +#ifndef NDEBUG + CSR_DEBUG_BLAH(ProblemeAResoudre); +#endif +} + +bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb) +{ + PROBLEME_POINT_INTERIEUR Probleme; + setInteriorPointProblem(ProblemeAResoudre, Probleme); + PI_Quamin(&Probleme); // resolution + ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; + if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) + { + storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); + return true; + } + else + { + handleInteriorPointError(ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb); + return false; + } +} \ No newline at end of file diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index 03d10ef8c0..e374db5bc6 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -180,159 +180,6 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr } #endif - return false; - } -} - -void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - PROBLEME_POINT_INTERIEUR& Probleme) -{ - double ToleranceSurLAdmissibilite; - int ChoixToleranceParDefautSurLAdmissibilite; - double ToleranceSurLaStationnarite; - int ChoixToleranceParDefautSurLaStationnarite; - double ToleranceSurLaComplementarite; - int ChoixToleranceParDefautSurLaComplementarite; - - ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; - ChoixToleranceParDefautSurLaStationnarite = OUI_PI; - ChoixToleranceParDefautSurLaComplementarite = OUI_PI; - - Probleme.NombreMaxDIterations = -1; - Probleme.CoutQuadratique = ProblemeAResoudre->CoutQuadratique; - Probleme.CoutLineaire = ProblemeAResoudre->CoutLineaire; - Probleme.X = ProblemeAResoudre->X; - Probleme.Xmin = ProblemeAResoudre->Xmin; - Probleme.Xmax = ProblemeAResoudre->Xmax; - Probleme.NombreDeVariables = ProblemeAResoudre->NombreDeVariables; - Probleme.TypeDeVariable = ProblemeAResoudre->TypeDeVariable; - - Probleme.VariableBinaire = (char*)ProblemeAResoudre->CoutsReduits; - - Probleme.NombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; - Probleme.IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne; - Probleme.NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes; - Probleme.IndicesColonnes = ProblemeAResoudre->IndicesColonnes; - Probleme.CoefficientsDeLaMatriceDesContraintes - = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes; - Probleme.Sens = ProblemeAResoudre->Sens; - Probleme.SecondMembre = ProblemeAResoudre->SecondMembre; - - Probleme.AffichageDesTraces = NON_PI; - - Probleme.UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; - Probleme.ToleranceDAdmissibilite = ToleranceSurLAdmissibilite; - - Probleme.UtiliserLaToleranceDeStationnariteParDefaut - = ChoixToleranceParDefautSurLaStationnarite; - Probleme.ToleranceDeStationnarite = ToleranceSurLaStationnarite; - - Probleme.UtiliserLaToleranceDeComplementariteParDefaut - = ChoixToleranceParDefautSurLaComplementarite; - Probleme.ToleranceDeComplementarite = ToleranceSurLaComplementarite; - - Probleme.CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; - - Probleme.CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; - Probleme.CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; -} - -void setToZeroIfBelowThreshold(double* pt, int Var, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - bool inSet = hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.find(Var) - != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); - bool belowLimit = *pt < hourlyCsrProblem.belowThisThresholdSetToZero; - if (inSet && belowLimit) - *pt = 0.0; -} - -void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* pt; - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; - if (pt) - { - *pt = ProblemeAResoudre->X[Var]; - setToZeroIfBelowThreshold(pt, Var, hourlyCsrProblem); - } - logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; - } -} - -void CSR_DEBUG_BLAH(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) -{ - int Var; - - logs.info(); - logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; - logs.info() << "Here is the trace:"; - - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", - Var, - ProblemeAResoudre->CoutLineaire[Var], - ProblemeAResoudre->CoutQuadratique[Var]); - } - for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) - { - logs.info().appendFormat("Constraint %ld sens %c B %e", - Cnt, - ProblemeAResoudre->Sens[Cnt], - ProblemeAResoudre->SecondMembre[Cnt]); - - int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; - int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; - for (; il < ilMax; ++il) - { - Var = ProblemeAResoudre->IndicesColonnes[il]; - logs.info().appendFormat(" coeff %e var %ld xmin %e xmax %e type %ld", - ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], - Var, - ProblemeAResoudre->Xmin[Var], - ProblemeAResoudre->Xmax[Var], - ProblemeAResoudre->TypeDeVariable[Var]); - } - } -} - -void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb) -{ - const int hoursInWeek = 168; - logs.warning() - << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " - << yearNb + 1 - << ". hour: " << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; - -#ifndef NDEBUG - CSR_DEBUG_BLAH(ProblemeAResoudre); -#endif -} - -bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb) -{ - PROBLEME_POINT_INTERIEUR Probleme; - setInteriorPointProblem(ProblemeAResoudre, Probleme); - PI_Quamin(&Probleme); // resolution - ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; - if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) - { - storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); - return true; - } - else - { - handleInteriorPointError(ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb); return false; } } \ No newline at end of file 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 index bd2ae25bad..f24c00be56 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -90,280 +90,6 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); } - MemFree(Pi); - MemFree(Colonne); -} - -void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Var; - int NombreDeTermes; - int Interco; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of - // type 2. - for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - NombreDeTermes = 0; - 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; - - NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); - logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); - } - } -} - -void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Area; - int Var; - int NombreDeTermes; - int Interco; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // constraint: - // ENS(node A) + - // - flow (A -> 2) or (+ flow (2 -> A)) there should be only one of them, otherwise double-count - // - spillage(node A) = - // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) - // for all areas inside adequacy patch - - for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - // + ENS - NombreDeTermes = 0; - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; - if (Var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; - } - - // - export flows - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - 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) - { - 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; - - NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " - + ProblemeHebdo->NomsDesPays[Area]; - ; - logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); - } - } -} - -void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Var; - int NombreDeTermes; - int Interco; - int NbInterco; - double Poids; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // Special case of the binding constraints - for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; - CntCouplante++) - { - MatriceDesContraintesCouplantes - = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - - if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) - { - NbInterco - = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; - NombreDeTermes = 0; - for (int Index = 0; Index < NbInterco; Index++) - { - Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; - Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - 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; - - NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) + "::" - + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; - - logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, - Pi, - Colonne, - NombreDeTermes, - MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante); - } - } - } -} - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] constraint list:"; - double* Pi; - int* Colonne; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); - Colonne = (int*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(int)); - - ProblemeAResoudre->NombreDeContraintes = 0; - ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - - setConstraintsOnFlows(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); - setNodeBalanceConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); - setBindingConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); - MemFree(Pi); MemFree(Colonne); } \ No newline at end of file diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index f257ca74aa..9cbea7809c 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -56,131 +56,4 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H NombreDeVariables++; } ProblemeAResoudre->NombreDeVariables = NombreDeVariables; -} - -void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int NumberOfVariables = 0; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: ENS of each area inside adq patch - logs.debug() << " ENS of each area inside adq patch: "; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - // Only ENS for areas inside adq patch are considered as variables - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); - logs.debug() << NumberOfVariables << " ENS[" << area << "].-[" - << ProblemeHebdo->NomsDesPays[area] << "]."; - - NumberOfVariables++; - } - } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; -} - -void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; - - // variables: Spilled Energy of each area inside adq patch - // todo after debugging transfer this into same area loop as ENS - logs.debug() << " Spilled Energy of each area inside adq patch: "; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - // Only Spilled Energy for areas inside adq patch are considered as variables - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; - hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); - logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "].-[" - << ProblemeHebdo->NomsDesPays[area] << "]."; - - NumberOfVariables++; - } - } -} - -void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; - - // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 - // and 2. - logs.debug() - << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() - << NumberOfVariables << " flow[" << Interco << "]. [" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - << "]-[" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - << "]."; - NumberOfVariables++; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " direct flow[" << Interco << "]. "; - NumberOfVariables++; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " indirect flow[" << Interco << "]. "; - NumberOfVariables++; - } - } -} - -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] variable list:"; - - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); - - constructVariableENS(ProblemeHebdo, hourlyCsrProblem); - constructVariableSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); - constructVariableFlows(ProblemeHebdo, hourlyCsrProblem); - - return; } \ No newline at end of file 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 3834e6870e..b556f1ab0f 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -39,7 +39,6 @@ #include #define ZERO_POUR_LES_VARIABLES_FIXES 1.e-6 -const double csrSolverRelaxation = 1e-3; using namespace Yuni; @@ -94,202 +93,4 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; } -} - -void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* AdresseDuResultat; - int hour; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: ENS for each area inside adq patch - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - - ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; - ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area] + csrSolverRelaxation; - - ProblemeAResoudre->X[Var] - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; - - AdresseDuResultat = &( - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); - - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = AdresseDuResultat; - - // update DENS values with densNew values - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] - = hourlyCsrProblem.densNewValues[area]; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - } - } -} - -void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* AdresseDuResultat; - int hour; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: Spilled Energy for each area inside adq patch - // todo after debugging transfer this into same area loop as ENS - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; - - ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; - ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; - - ProblemeAResoudre->X[Var] - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]; - - AdresseDuResultat = &( - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); - - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = AdresseDuResultat; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - } - } -} - -void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* AdresseDuResultat; - int hour; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int* TypeDeVariable; - double* Xmin; - double* Xmax; - Xmin = ProblemeAResoudre->Xmin; - Xmax = ProblemeAResoudre->Xmax; - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; - ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; - - // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links - // between nodes of type 2. Set hourly bounds for links between nodes of type 2, depending on - // the user input (max direct and indirect flow). - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) - { - // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - // flow - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - csrSolverRelaxation; - ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; - - if (Math::Infinite(Xmax[Var]) == 1) - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } - - AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = AdresseDuResultat; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - - // direct / indirect flow - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - // CSR Todo? - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] - // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - - Xmin[Var] = -csrSolverRelaxation; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - // CSR Todo? - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] - // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; - - Xmin[Var] = -csrSolverRelaxation; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - } - } -} - -void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] bounds"; - - int Var; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; - - setBoundsOnENS(ProblemeHebdo, hourlyCsrProblem); - setBoundsOnSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); - setBoundsOnFlows(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file 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 fbfb8573b9..4e843bb965 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -56,137 +56,4 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH ProblemeAResoudre->CoutQuadratique[Var] = ValeursDeResistances->ResistanceApparente[Interco]; } -} - -void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - double priceTakingOrders; // PTO - double quadraticCost; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: ENS for each area inside adq patch - // obj function term is: 1 / (PTO * PTO) * ENS * ENS - // => quadratic cost: 1 / (PTO * PTO) - // => linear cost: 0 - // PTO can take two different values according to option: - // 1. from DENS - // 2. from load - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - if (ProblemeHebdo->adqPatchParams->PriceTakingOrder - == Data::AdequacyPatch::AdqPatchPTO::isLoad) - { - priceTakingOrders - = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] - + ProblemeHebdo->AllMustRunGeneration[hour] - ->AllMustRunGenerationOfArea[area]; - } - else if (ProblemeHebdo->adqPatchParams->PriceTakingOrder - == Data::AdequacyPatch::AdqPatchPTO::isDens) - { - priceTakingOrders - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; - } - - if (priceTakingOrders <= 0.0) - { - // CSR todo a warning that DENS is negative and it is considered for CSR, there - // was a check for positive threshold - quadraticCost = 0.0; - } - else - { - quadraticCost = 1 / (priceTakingOrders * priceTakingOrders); - } - - ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; - logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; - } - } - } -} - -void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Interco; - COUTS_DE_TRANSPORT* TransportCost; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // 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 - // flow_indirect ) - // => quadratic cost: 0 - // => linear cost: hurdle_cost_direct or hurdle_cost_indirect - // these members of objective functions are considered only if IntercoGereeAvecDesCouts = - // OUI_ANTARES (use hurdle cost option is true). otherwise these members are zero. - - for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // flow - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - 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]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) - ProblemeAResoudre->CoutLineaire[Var] = 0; - else - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } - - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) - ProblemeAResoudre->CoutLineaire[Var] = 0; - else - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } - } - } -} - -void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] cost"; - - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - memset((char*)ProblemeAResoudre->CoutLineaire, - 0, - ProblemeAResoudre->NombreDeVariables * sizeof(double)); - - setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); - setLinearCost(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file 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 5aa38b4508..17e9596c20 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -48,187 +48,4 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->SoldeMoyenHoraire[PdtHebdo]->SoldeMoyenDuPays[Pays]; } -} - -void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Cnt; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of - // type 2. - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - std::map::iterator it - = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); - if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) - Cnt = it->second; - - ProblemeAResoudre->SecondMembre[Cnt] = 0.; - logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - } - } -} - -void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Cnt; - int Area; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - // constraint: - // ENS(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) - // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) - // for all areas inside adequacy patch - - for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - std::map::iterator it - = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); - if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) - Cnt = it->second; - - ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; - logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area - << ")"; - } - } -} - -void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Cnt; - int Area; - int CntCouplante; - int Interco; - int NbInterco; - double Poids; - double ValueOfFlow; - int Index; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - double* SecondMembre = ProblemeAResoudre->SecondMembre; - CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; - std::map bingdingConstraintNumber - = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; - - // constraint: - // user defined Binding constraints between transmission flows - // and/or power generated from generating units. - for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; - CntCouplante++) - { - if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) - { - MatriceDesContraintesCouplantes - = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - - Cnt = bingdingConstraintNumber[CntCouplante]; - - // 1. The original RHS of bingding constraint - SecondMembre[Cnt] - = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; - // logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt - // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante - // << ")"; - - // 2. RHS part 2: flow other than 2<->2 - NbInterco - = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; - for (Index = 0; Index < NbInterco; Index++) - { - Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; - Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch - || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - SecondMembre[Cnt] -= ValueOfFlow * Poids; - // logs.debug() - // << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt - // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" - // << ". Interco;" + std::to_string(Interco) << ". Between:[" - // << ProblemeHebdo - // ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - // << "]-[" - // << ProblemeHebdo - // ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - // << "]" - // << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; - } - } - - // 3. RHS part 3: - cluster - int NbClusters - = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; - int Area; - int Palier; - int IndexNumeroDuPalierDispatch; - double ValueOfVar; - PALIERS_THERMIQUES* PaliersThermiquesDuPays; - - for (Index = 0; Index < NbClusters; Index++) - { - Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; - PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; - - IndexNumeroDuPalierDispatch - = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; - - Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques - [IndexNumeroDuPalierDispatch]; - Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; - - ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] - ->ProductionThermique[hour] - ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; - - SecondMembre[Cnt] -= ValueOfVar * Poids; - // logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt - // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante - // << ")" - // << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids - // << ", ValueOfVar:" << ValueOfVar; - } - if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') - { - SecondMembre[Cnt] += csrSolverRelaxationRHS; - } - else if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '>') - { - SecondMembre[Cnt] -= csrSolverRelaxationRHS; - } - logs.debug() << Cnt << ": Hourly bc: -RHS[" << Cnt << "] = " << SecondMembre[Cnt]; - } - } -} - -void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] RHS: "; - - setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); - setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); - setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file From a84b5321c0141ec4b0ab71fc68d6958506bd9792 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 29 Jul 2022 13:00:00 +0200 Subject: [PATCH 258/490] 12. Add "Include hurdle cost" false/true button --- docs/reference-guide/03-commands.md | 1 + src/libs/antares/study/parameters.cpp | 5 +++++ src/libs/antares/study/parameters.h | 2 ++ .../set_problem_cost_function.cpp | 3 ++- .../simulation/sim_calcul_economique.cpp | 2 ++ .../sim_structure_probleme_economique.h | 1 + .../adequacy-patch/adequacy-patch-options.cpp | 19 +++++++++++++++++++ .../adequacy-patch/adequacy-patch-options.h | 1 + 8 files changed, 33 insertions(+), 1 deletion(-) diff --git a/docs/reference-guide/03-commands.md b/docs/reference-guide/03-commands.md index 0441bc943f..3598b9ed9d 100644 --- a/docs/reference-guide/03-commands.md +++ b/docs/reference-guide/03-commands.md @@ -221,6 +221,7 @@ Auxiliary window [Areas] Opens a window in which a choice can be made regarding - _NTC between physical areas outside adequacy patch (set to null / local values)_ - _Price taking order (DENS / Load)_ - _Save intermediate results (false / true)_ +- _Include hurdle cost in CSR optimization (false / true)_ - _Thresholds:_ - _Initiate curtailment sharing rule_ - _Display local maching rule violations_ diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 1efee4a2dd..20bb3013f0 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -249,6 +249,7 @@ void Parameters::resetAdqPatchParameters() adqPatch.localMatching.setToZeroOutsideOutsideLinks = true; adqPatch.curtailmentSharing.priceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; adqPatch.saveIntermediateResults = false; + adqPatch.curtailmentSharing.includeHurdleCost = false; resetThresholdsAdqPatch(); } @@ -684,6 +685,9 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, // Price taking order if (key == "price-taking-order") return StringToPriceTakingOrder(value, d.adqPatch.curtailmentSharing.priceTakingOrder); + // Include Hurdle Cost + if (key == "include-hurdle-cost-csr") + return value.to(d.adqPatch.curtailmentSharing.includeHurdleCost); // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); @@ -1818,6 +1822,7 @@ void Parameters::saveToINI(IniFile& ini) const section->add("save-intermediate-results", adqPatch.saveIntermediateResults); section->add("price-taking-order", PriceTakingOrderToString(adqPatch.curtailmentSharing.priceTakingOrder)); + section->add("include-hurdle-cost-csr", adqPatch.curtailmentSharing.includeHurdleCost); // Threshholds section->add("threshold-initiate-curtailment-sharing-rule", adqPatch.curtailmentSharing.thresholdInitiate); diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 3e676cebe2..2178107319 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -537,6 +537,8 @@ class Parameters final float thresholdInitiate; //! Threshold to display Local Matching Rule violations float thresholdDisplayViolations; + //! Include hurdle cost in CSR cost function + bool includeHurdleCost; }; CurtailmentSharing curtailmentSharing; 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 871ad68090..2db8d2ccc2 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 @@ -163,5 +163,6 @@ void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, ProblemeAResoudre->NombreDeVariables * sizeof(double)); setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); - setLinearCost(ProblemeHebdo, hourlyCsrProblem); + if (ProblemeHebdo->adqPatchParams->IncludeHurdleCostCsr) + setLinearCost(ProblemeHebdo, hourlyCsrProblem); } \ No newline at end of file diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 28d1e8782c..600e80698e 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -76,6 +76,8 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, = parameters.adqPatch.saveIntermediateResults; problem.adqPatchParams->PriceTakingOrder = parameters.adqPatch.curtailmentSharing.priceTakingOrder; + problem.adqPatchParams->IncludeHurdleCostCsr + = parameters.adqPatch.curtailmentSharing.includeHurdleCost; problem.adqPatchParams->ThresholdInitiateCurtailmentSharingRule = parameters.adqPatch.curtailmentSharing.thresholdInitiate; problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 47f88fa5d5..14782edf7b 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -499,6 +499,7 @@ struct AdequacyPatchParameters bool SetNTCOutsideToInsideToZero; bool SetNTCOutsideToOutsideToZero; bool SaveIntermediateResults; + bool IncludeHurdleCostCsr; AdqPatchPTO PriceTakingOrder; float ThresholdInitiateCurtailmentSharingRule; float ThresholdDisplayLocalMatchingRuleViolations; 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 a8fa0a0595..c6b453f47f 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 @@ -202,6 +202,21 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatchPTO = button; } + // Select whether the hurdle cost will be included into curtailment sharing rule cost function + { + label = Component::CreateLabel(this, wxT("Include hurdle cost in CSR optimization")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind( + this, + &AdequacyPatchOptions::onPopupMenuSpecify, + PopupInfo(study.parameters.adqPatch.curtailmentSharing.includeHurdleCost, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchIncludeHurdleCostCsr = button; + } // Select whether the intermediate result before the application of the curtailment sharing is // to be kept in the results { @@ -334,6 +349,10 @@ void AdequacyPatchOptions::refresh() updateButton(pBtnAdequacyPatchSaveIntermediateResults, study.parameters.adqPatch.saveIntermediateResults, buttonType); + // Include hurdle cost for CSR + updateButton(pBtnAdequacyPatchIncludeHurdleCostCsr, + study.parameters.adqPatch.curtailmentSharing.includeHurdleCost, + buttonType); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. buttonType = "ntc"; 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 f828b2fe01..888fb4a0d4 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 @@ -95,6 +95,7 @@ class AdequacyPatchOptions final : public wxDialog Component::Button* pBtnNTCfromOutToOutAdqPatch; Component::Button* pBtnAdequacyPatchPTO; Component::Button* pBtnAdequacyPatchSaveIntermediateResults; + Component::Button* pBtnAdequacyPatchIncludeHurdleCostCsr; wxTextCtrl* pThresholdCSRStart; wxTextCtrl* pThresholdLMRviolations; bool* pTargetRef; From e1188d02141cb454cd042fd489062769ee2baf49 Mon Sep 17 00:00:00 2001 From: Milos A Date: Sat, 6 Aug 2022 22:57:29 +0200 Subject: [PATCH 259/490] refacto avoid bugs --- .../construct_problem_constraints_RHS.cpp | 20 ++++++++++--------- 1 file changed, 11 insertions(+), 9 deletions(-) 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 14cc4bf5a5..79917212c5 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 @@ -52,11 +52,12 @@ void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourl std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) + { Cnt = it->second; - - ProblemeAResoudre->SecondMembre[Cnt] = 0.; - logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + ProblemeAResoudre->SecondMembre[Cnt] = 0.; + logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; + } } } } @@ -83,12 +84,13 @@ void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h std::map::iterator it = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) + { Cnt = it->second; - - ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; - logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt] << " (Area = " << Area - << ")"; + ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; + logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt + << "] = " << ProblemeAResoudre->SecondMembre[Cnt] + << " (Area = " << Area << ")"; + } } } } From 668dcb8ba0ffad143abd6f10e55500a613b8593d Mon Sep 17 00:00:00 2001 From: Milos A Date: Sat, 6 Aug 2022 22:57:49 +0200 Subject: [PATCH 260/490] refacto avoid bugs --- .../adequacy_patch_csr/set_problem_cost_function.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 2db8d2ccc2..ba91f1ebba 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 @@ -37,7 +37,7 @@ void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC { int Var; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - double priceTakingOrders; // PTO + double priceTakingOrders = 0.0; // PTO double quadraticCost; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; From 3452de9425d6654a2c781baa62cc8321d5fa9f3c Mon Sep 17 00:00:00 2001 From: Milos A Date: Sat, 6 Aug 2022 22:58:04 +0200 Subject: [PATCH 261/490] refacto bugs --- .../optimisation/adequacy_patch_csr/solve_problem.cpp | 6 ------ 1 file changed, 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index ef19275f0f..0224d8b8cb 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -58,11 +58,8 @@ using namespace Antares; void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, PROBLEME_POINT_INTERIEUR& Probleme) { - double ToleranceSurLAdmissibilite; int ChoixToleranceParDefautSurLAdmissibilite; - double ToleranceSurLaStationnarite; int ChoixToleranceParDefautSurLaStationnarite; - double ToleranceSurLaComplementarite; int ChoixToleranceParDefautSurLaComplementarite; ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; @@ -92,15 +89,12 @@ void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, Probleme.AffichageDesTraces = NON_PI; Probleme.UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; - Probleme.ToleranceDAdmissibilite = ToleranceSurLAdmissibilite; Probleme.UtiliserLaToleranceDeStationnariteParDefaut = ChoixToleranceParDefautSurLaStationnarite; - Probleme.ToleranceDeStationnarite = ToleranceSurLaStationnarite; Probleme.UtiliserLaToleranceDeComplementariteParDefaut = ChoixToleranceParDefautSurLaComplementarite; - Probleme.ToleranceDeComplementarite = ToleranceSurLaComplementarite; Probleme.CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; From 443a41f01aafc914a7080fe24bd73eb5693fb9ca Mon Sep 17 00:00:00 2001 From: Florian OMNES Date: Thu, 18 Aug 2022 15:27:32 +0200 Subject: [PATCH 262/490] Fix build Rename LinkCapacityForAdequacyPatchFirstStep -> ntcSetToZeroStatus_AdqPatchStep1 --- src/solver/optimisation/adequacy_patch.cpp | 2 +- src/solver/optimisation/adequacy_patch.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index b8eec3c93e..3d86c7870a 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -64,7 +64,7 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebd } } -LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( +ntcSetToZeroStatus_AdqPatchStep1 SetNTCForAdequacyFirstStepOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType) { switch (ExtremityNodeAdequacyPatchType) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 83d77ac1f9..f8a1d78972 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -58,7 +58,7 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebd * @return uint from an enumeration that describes the type of restrictions to put on this link for * adq purposes. */ - LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq(AdequacyPatchMode ExtremityNodeAdequacyPatchType); +ntcSetToZeroStatus_AdqPatchStep1 SetNTCForAdequacyFirstStepOriginNodeInsideAdq(AdequacyPatchMode ExtremityNodeAdequacyPatchType); /*! * Determines restriction type for transmission links for first step of adequacy patch, when start From 919fc6a28ca9b00ba1d5ae632f140868e12187fd Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 14:15:33 +0200 Subject: [PATCH 263/490] 1. Make NumberOfVariables a reference var --- .../adequacy_patch_csr/construct_problem_variables.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 d53ba569f5..d7d24fe6e2 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -37,10 +37,11 @@ void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - int NumberOfVariables = 0; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; + int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; + NumberOfVariables = 0; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; @@ -62,7 +63,6 @@ void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hou NumberOfVariables++; } } - ProblemeAResoudre->NombreDeVariables = NumberOfVariables; } void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, From 653af41845716f5abb2247b39a972d3fac43f469 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 14:19:48 +0200 Subject: [PATCH 264/490] change function name CSR_DEBUG_ --- src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 0224d8b8cb..c7c512f913 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -128,7 +128,7 @@ void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, } } -void CSR_DEBUG_BLAH(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) +void CSR_DEBUG_HANDLE(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { int Var; @@ -177,7 +177,7 @@ void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, << ". hour: " << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; #ifndef NDEBUG - CSR_DEBUG_BLAH(ProblemeAResoudre); + CSR_DEBUG_HANDLE(ProblemeAResoudre); #endif } From d593fb24a3d35b4ab211b43ead5603d6ee76da3b Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 14:33:04 +0200 Subject: [PATCH 265/490] 3. test Probleme.ExistenceDUneSolution directly --- src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index c7c512f913..83c4cb6cfe 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -189,8 +189,7 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, PROBLEME_POINT_INTERIEUR Probleme; setInteriorPointProblem(ProblemeAResoudre, Probleme); PI_Quamin(&Probleme); // resolution - ProblemeAResoudre->ExistenceDUneSolution = Probleme.ExistenceDUneSolution; - if (ProblemeAResoudre->ExistenceDUneSolution == OUI_PI) + if (Probleme.ExistenceDUneSolution == OUI_PI) { storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); return true; From eda86bdfc31dca2f9d5c6f63c863fb4b2a86b313 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 15:11:52 +0200 Subject: [PATCH 266/490] 2. Slightly clearer version --- .../adequacy_patch_csr/solve_problem.cpp | 65 ++++++++++--------- 1 file changed, 34 insertions(+), 31 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 83c4cb6cfe..68a6604d60 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -55,9 +55,10 @@ extern "C" using namespace Antares; -void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - PROBLEME_POINT_INTERIEUR& Probleme) +std::unique_ptr buildInteriorPointProblem( + PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { + std::unique_ptr Probleme(new PROBLEME_POINT_INTERIEUR()); int ChoixToleranceParDefautSurLAdmissibilite; int ChoixToleranceParDefautSurLaStationnarite; int ChoixToleranceParDefautSurLaComplementarite; @@ -66,40 +67,42 @@ void setInteriorPointProblem(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, ChoixToleranceParDefautSurLaStationnarite = OUI_PI; ChoixToleranceParDefautSurLaComplementarite = OUI_PI; - Probleme.NombreMaxDIterations = -1; - Probleme.CoutQuadratique = ProblemeAResoudre->CoutQuadratique; - Probleme.CoutLineaire = ProblemeAResoudre->CoutLineaire; - Probleme.X = ProblemeAResoudre->X; - Probleme.Xmin = ProblemeAResoudre->Xmin; - Probleme.Xmax = ProblemeAResoudre->Xmax; - Probleme.NombreDeVariables = ProblemeAResoudre->NombreDeVariables; - Probleme.TypeDeVariable = ProblemeAResoudre->TypeDeVariable; - - Probleme.VariableBinaire = (char*)ProblemeAResoudre->CoutsReduits; - - Probleme.NombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; - Probleme.IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne; - Probleme.NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes; - Probleme.IndicesColonnes = ProblemeAResoudre->IndicesColonnes; - Probleme.CoefficientsDeLaMatriceDesContraintes + Probleme->NombreMaxDIterations = -1; + Probleme->CoutQuadratique = ProblemeAResoudre->CoutQuadratique; + Probleme->CoutLineaire = ProblemeAResoudre->CoutLineaire; + Probleme->X = ProblemeAResoudre->X; + Probleme->Xmin = ProblemeAResoudre->Xmin; + Probleme->Xmax = ProblemeAResoudre->Xmax; + Probleme->NombreDeVariables = ProblemeAResoudre->NombreDeVariables; + Probleme->TypeDeVariable = ProblemeAResoudre->TypeDeVariable; + + Probleme->VariableBinaire = (char*)ProblemeAResoudre->CoutsReduits; + + Probleme->NombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; + Probleme->IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne; + Probleme->NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes; + Probleme->IndicesColonnes = ProblemeAResoudre->IndicesColonnes; + Probleme->CoefficientsDeLaMatriceDesContraintes = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes; - Probleme.Sens = ProblemeAResoudre->Sens; - Probleme.SecondMembre = ProblemeAResoudre->SecondMembre; + Probleme->Sens = ProblemeAResoudre->Sens; + Probleme->SecondMembre = ProblemeAResoudre->SecondMembre; - Probleme.AffichageDesTraces = NON_PI; + Probleme->AffichageDesTraces = NON_PI; - Probleme.UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; + Probleme->UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; - Probleme.UtiliserLaToleranceDeStationnariteParDefaut + Probleme->UtiliserLaToleranceDeStationnariteParDefaut = ChoixToleranceParDefautSurLaStationnarite; - Probleme.UtiliserLaToleranceDeComplementariteParDefaut + Probleme->UtiliserLaToleranceDeComplementariteParDefaut = ChoixToleranceParDefautSurLaComplementarite; - Probleme.CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; + Probleme->CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; - Probleme.CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; - Probleme.CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; + Probleme->CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; + Probleme->CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; + + return Probleme; } void setToZeroIfBelowThreshold(double* pt, int Var, HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -186,10 +189,10 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, uint weekNb, int yearNb) { - PROBLEME_POINT_INTERIEUR Probleme; - setInteriorPointProblem(ProblemeAResoudre, Probleme); - PI_Quamin(&Probleme); // resolution - if (Probleme.ExistenceDUneSolution == OUI_PI) + std::unique_ptr Probleme + = buildInteriorPointProblem(ProblemeAResoudre); + PI_Quamin(Probleme.get()); // resolution + if (Probleme->ExistenceDUneSolution == OUI_PI) { storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); return true; From 3525d4474aa07fef5404c2c9c4f5768509bd1604 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 15:17:16 +0200 Subject: [PATCH 267/490] 4. make hoursRequiringCurtailmentSharing const var --- src/solver/simulation/economy.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 771e07d11c..ebcc1cf6b8 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -98,7 +98,8 @@ void AdequacyPatchOptimization::solve(Variable::State& state, ::SIM_RenseignementProblemeHebdo(*problemeHebdo, state, numSpace, hourInTheYear); OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); - std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); + const std::set hoursRequiringCurtailmentSharing + = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) { logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 From 15e10dd88a1d91a4f2ad4c87b46565ea1e5b993f Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 15:30:59 +0200 Subject: [PATCH 268/490] 5. avoid cast sumENS[i] to int! --- src/solver/optimisation/adequacy_patch.cpp | 2 +- src/solver/simulation/economy.cpp | 4 ++-- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 3d86c7870a..9940cc45de 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -136,7 +136,7 @@ void setNTCbounds(double& Xmax, double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) { - float threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; + double threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; double netPositionInit; double densNew; double ensInit; diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index ebcc1cf6b8..faf088a640 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -221,12 +221,12 @@ vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(ui std::set AdequacyPatchOptimization::identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) { - float threshold + double threshold = pProblemesHebdo[numSpace]->adqPatchParams->ThresholdInitiateCurtailmentSharingRule; std::set triggerCsrSet; for (int i = 0; i < nbHoursInAWeek; ++i) { - if ((int)sumENS[i] > threshold) + if (sumENS[i] > threshold) { triggerCsrSet.insert(i); } From 65caf6e12a8b36cc6cf4bd033c09f98a9bebdf2b Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:08:09 +0200 Subject: [PATCH 269/490] 17. move default thresholds to adequacy_patch.h --- src/libs/antares/study/fwd.h | 5 ----- src/libs/antares/study/parameters.cpp | 5 +++-- src/solver/optimisation/adequacy_patch.h | 4 ++++ 3 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 6a852dbe55..1a879e82e3 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -604,11 +604,6 @@ enum AdqPatchPTO }; // enum AdqPatchPTO -//! A default threshold value for initiate curtailment sharing rule -const float adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule = 0.0; -//! A default threshold value for display local matching rule violations -const float adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; - } // namespace AdequacyPatch } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 20bb3013f0..b401a88ee0 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -43,6 +43,7 @@ #include #include #include "../solver/variable/economy/all.h" +#include "../solver/optimisation/adequacy_patch.h" #include #include @@ -237,9 +238,9 @@ void Parameters::resetThresholdsAdqPatch() { // Initialize all thresholds values for adequacy patch adqPatch.curtailmentSharing.thresholdInitiate - = adqPatchDefaultValueThresholdInitiateCurtailmentSharingRule; + = defaultValueThresholdInitiateCurtailmentSharingRule; adqPatch.curtailmentSharing.thresholdDisplayViolations - = adqPatchDefaultValueThresholdDisplayLocalMatchingRuleViolations; + = defaultValueThresholdDisplayLocalMatchingRuleViolations; } void Parameters::resetAdqPatchParameters() diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index f8a1d78972..86c161832d 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -37,6 +37,10 @@ namespace Data { namespace AdequacyPatch { +//! A default threshold value for initiate curtailment sharing rule +const double defaultValueThresholdInitiateCurtailmentSharingRule = 0.0; +//! A default threshold value for display local matching rule violations +const double defaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; /*! * Determines restriction type for transmission links for first step of adequacy patch. * From 6df6a4ef18915b732fbae614d46c0a7e11b781b9 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:14:46 +0200 Subject: [PATCH 270/490] 20. use A.size() in addArray function --- src/solver/optimisation/adequacy_patch.cpp | 4 ++-- src/solver/optimisation/adequacy_patch.h | 3 +-- src/solver/simulation/economy.cpp | 3 +-- 3 files changed, 4 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 9940cc45de..9092b5702a 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -222,9 +222,9 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo return std::make_pair(netPositionInit, densNew); } -void addArray(std::vector& A, double* B, int num) +void addArray(std::vector& A, double* B) { - for (uint i = 0; i < num; ++i) + for (uint i = 0; i < A.size(); ++i) A[i] += B[i]; } diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 86c161832d..c253778140 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -111,10 +111,9 @@ double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint week ** ** ** ** \param A A vector ** ** \param B An array -** ** \param num An integer ** ** \return ** */ -void addArray(std::vector& A, double* B, int num); +void addArray(std::vector& A, double* B); } // end namespace Antares } // end namespace Data diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index faf088a640..f5d06884cf 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -212,8 +212,7 @@ vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(ui addArray(sumENS, pProblemesHebdo[numSpace] ->ResultatsHoraires[area] - ->ValeursHorairesDeDefaillancePositive, - nbHoursInAWeek); + ->ValeursHorairesDeDefaillancePositive); } return sumENS; } From 90c6f0be5a1fdfbcf34c953156091862b7686db8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:31:41 +0200 Subject: [PATCH 271/490] 19. create dedicated method solveCSR --- src/solver/simulation/economy.cpp | 30 ++++++++++++++++++------------ src/solver/simulation/economy.h | 1 + 2 files changed, 19 insertions(+), 12 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index f5d06884cf..e770f426d3 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -98,18 +98,7 @@ void AdequacyPatchOptimization::solve(Variable::State& state, ::SIM_RenseignementProblemeHebdo(*problemeHebdo, state, numSpace, hourInTheYear); OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); - const std::set hoursRequiringCurtailmentSharing - = getHoursRequiringCurtailmentSharing(numSpace); - for (int hourInWeek : hoursRequiringCurtailmentSharing) - { - logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 - << " Hour:" << w * nbHoursInAWeek + hourInWeek + 1; - HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); - hourlyCsrProblem.run(w, state.year); - } - double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); - logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 - << ".Total LMR violation:" << totalLmrViolation; + solveCSR(state, numSpace, w); } // No adequacy patch @@ -240,6 +229,23 @@ std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uin return identifyHoursForCurtailmentSharing(sumENS, numSpace); } +void AdequacyPatchOptimization::solveCSR(Variable::State& state, uint numSpace, uint w) +{ + auto problemeHebdo = pProblemesHebdo[numSpace]; + const std::set hoursRequiringCurtailmentSharing + = getHoursRequiringCurtailmentSharing(numSpace); + for (int hourInWeek : hoursRequiringCurtailmentSharing) + { + logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 + << " Hour:" << w * nbHoursInAWeek + hourInWeek + 1; + HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); + hourlyCsrProblem.run(w, state.year); + } + double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); + logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 + << ".Total LMR violation:" << totalLmrViolation; +} + bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index aa675073cf..fe78eb3ea5 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -60,6 +60,7 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization public: AdequacyPatchOptimization(); void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) override; + void solveCSR(Variable::State& state, uint numSpace, uint w); vector calculateENSoverAllAreasForEachHour(uint numSpace); std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); From 53528706d55f31dd288048e3079964c9ef31e2c6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:40:59 +0200 Subject: [PATCH 272/490] 7. name change --- src/solver/simulation/economy.h | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index fe78eb3ea5..039f73c129 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -47,7 +47,7 @@ class EconomyWeeklyOptimization { public: using Ptr = std::unique_ptr; - virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) = 0; + virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) = 0; void initializeProblemeHebdo(PROBLEME_HEBDO** pProblemesHebdo); static Ptr create(bool adqPatchEnabled); @@ -59,8 +59,8 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization { public: AdequacyPatchOptimization(); - void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint w) override; - void solveCSR(Variable::State& state, uint numSpace, uint w); + void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; + void solveCSR(Variable::State& state, uint numSpace, uint week); vector calculateENSoverAllAreasForEachHour(uint numSpace); std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); @@ -71,7 +71,7 @@ class NoAdequacyPatchOptimization : public EconomyWeeklyOptimization { public: NoAdequacyPatchOptimization(); - void solve(Variable::State&, int, uint numSpace, uint w) override; + void solve(Variable::State&, int, uint numSpace, uint week) override; }; class Economy From 7086560344a870fc1541e7655fa7a9009a2b0405 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:46:50 +0200 Subject: [PATCH 273/490] 8. make methods of AdequacyPatchOptimization private --- src/solver/simulation/economy.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 039f73c129..e7cb1ee0a0 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -61,7 +61,7 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization AdequacyPatchOptimization(); void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; void solveCSR(Variable::State& state, uint numSpace, uint week); - +private: vector calculateENSoverAllAreasForEachHour(uint numSpace); std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); std::set getHoursRequiringCurtailmentSharing(uint numSpace); From 5bdbd3546eb928700d87bab4ce25d1ab0fd5c2e8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:54:53 +0200 Subject: [PATCH 274/490] 11. 14. 16 delete unused logs --- .../construct_problem_constraints_RHS.cpp | 19 ------------------- 1 file changed, 19 deletions(-) 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 79917212c5..bbcda3a88e 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 @@ -131,9 +131,6 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, // 1. The original RHS of bingding constraint SecondMembre[Cnt] = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; - // logs.debug() << Cnt << ": Hourly bc: Existing-RHS[" << Cnt - // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante - // << ")"; // 2. RHS part 2: flow other than 2<->2 NbInterco @@ -150,17 +147,6 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, { ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; SecondMembre[Cnt] -= ValueOfFlow * Poids; - // logs.debug() - // << Cnt << ": Hourly bc: IntercoFlow-RHS[" << Cnt - // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante << ")" - // << ". Interco;" + std::to_string(Interco) << ". Between:[" - // << ProblemeHebdo - // ->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - // << "]-[" - // << ProblemeHebdo - // ->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - // << "]" - // << ". ValueOfFlow: " << ValueOfFlow << ". Poids: " << Poids; } } @@ -190,11 +176,6 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; SecondMembre[Cnt] -= ValueOfVar * Poids; - // logs.debug() << Cnt << ": Hourly bc: ThermalCluster-RHS[" << Cnt - // << "] = " << SecondMembre[Cnt] << " (CntCouplante = " << CntCouplante - // << ")" - // << ". Area:" << Area << ", Palier:" << Palier << ", Poids" << Poids - // << ", ValueOfVar:" << ValueOfVar; } if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') { From cca06c7cb4aa29183fcf21b5c1dd0788cf3a4c61 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:56:25 +0200 Subject: [PATCH 275/490] 9. delete forward declaration of HOURLY_CSR_PROBLEM --- src/solver/simulation/sim_structure_probleme_economique.h | 2 -- 1 file changed, 2 deletions(-) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 14782edf7b..260e7f1f13 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -505,8 +505,6 @@ struct AdequacyPatchParameters float ThresholdDisplayLocalMatchingRuleViolations; }; -class HOURLY_CSR_PROBLEM; - struct PROBLEME_HEBDO { /* Business problem */ From ab253addb5358e00750e5288465f6294889fb304 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 16:59:20 +0200 Subject: [PATCH 276/490] 15. remove Double definition. --- .../optimisation/opt_gestion_second_membre_cas_quadratique.cpp | 2 -- 1 file changed, 2 deletions(-) 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 17e9596c20..0d5188d13d 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -25,8 +25,6 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -const double csrSolverRelaxationRHS = 1e-3; - #include "opt_structure_probleme_a_resoudre.h" #include "../simulation/simulation.h" From 363208cfa09ca58ab48f9d1aee485bc4f4bcabcb Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 22 Aug 2022 17:04:17 +0200 Subject: [PATCH 277/490] 12. 13 update copyright & Authors for adq-patch files --- src/solver/optimisation/adequacy_patch.cpp | 4 ++-- src/solver/optimisation/adequacy_patch.h | 4 ++-- .../adequacy_patch_csr/construct_problem_constraints_LHS.cpp | 4 ++-- .../adequacy_patch_csr/construct_problem_constraints_RHS.cpp | 4 ++-- .../adequacy_patch_csr/construct_problem_variables.cpp | 4 ++-- .../adequacy_patch_csr/set_problem_cost_function.cpp | 4 ++-- .../adequacy_patch_csr/set_variable_boundaries.cpp | 4 ++-- src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp | 4 ++-- 8 files changed, 16 insertions(+), 16 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 9092b5702a..ad4141353e 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index c253778140..9e4514e77f 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp index 2257aa05d2..3acf492761 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** 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 bbcda3a88e..43cab01f5d 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,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** 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 d7d24fe6e2..8421fcfd60 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** 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 ba91f1ebba..ea05066a3f 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,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** 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 2651940c5e..2ca69fd898 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 68a6604d60..690cba4dea 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2022 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** From b4ad70333fa1ee34d60c341887badbebb30bb071 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 24 Aug 2022 11:11:54 +0200 Subject: [PATCH 278/490] make solveCSR private method --- src/solver/simulation/economy.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index e7cb1ee0a0..73dd53b999 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -60,8 +60,8 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization public: AdequacyPatchOptimization(); void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; - void solveCSR(Variable::State& state, uint numSpace, uint week); private: + void solveCSR(Variable::State& state, uint numSpace, uint week); vector calculateENSoverAllAreasForEachHour(uint numSpace); std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); std::set getHoursRequiringCurtailmentSharing(uint numSpace); From c865631bd3cc92e4a06556d6fa7abaa26a990079 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 24 Aug 2022 11:14:15 +0200 Subject: [PATCH 279/490] use auto instead of std::unique_ptr --- src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 690cba4dea..1b9bfcb141 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -58,7 +58,7 @@ using namespace Antares; std::unique_ptr buildInteriorPointProblem( PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { - std::unique_ptr Probleme(new PROBLEME_POINT_INTERIEUR()); + auto Probleme = std::make_unique(); int ChoixToleranceParDefautSurLAdmissibilite; int ChoixToleranceParDefautSurLaStationnarite; int ChoixToleranceParDefautSurLaComplementarite; @@ -189,7 +189,7 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, uint weekNb, int yearNb) { - std::unique_ptr Probleme + auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) From 20d0bd33005031d514f6592b33a41fcaa2e03ed4 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 24 Aug 2022 11:15:16 +0200 Subject: [PATCH 280/490] float->double --- src/solver/simulation/sim_structure_probleme_economique.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 260e7f1f13..8950899df0 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -501,8 +501,8 @@ struct AdequacyPatchParameters bool SaveIntermediateResults; bool IncludeHurdleCostCsr; AdqPatchPTO PriceTakingOrder; - float ThresholdInitiateCurtailmentSharingRule; - float ThresholdDisplayLocalMatchingRuleViolations; + double ThresholdInitiateCurtailmentSharingRule; + double ThresholdDisplayLocalMatchingRuleViolations; }; struct PROBLEME_HEBDO From 016444135505a02d00470b5086069adc77025439 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 24 Aug 2022 11:47:59 +0200 Subject: [PATCH 281/490] remove saveIntermediateResults --- docs/reference-guide/03-commands.md | 1 - src/libs/antares/study/parameters.cpp | 4 ---- src/libs/antares/study/parameters.h | 3 --- .../simulation/sim_calcul_economique.cpp | 2 -- .../sim_structure_probleme_economique.h | 1 - .../adequacy-patch/adequacy-patch-options.cpp | 19 ------------------- .../adequacy-patch/adequacy-patch-options.h | 1 - 7 files changed, 31 deletions(-) diff --git a/docs/reference-guide/03-commands.md b/docs/reference-guide/03-commands.md index 3598b9ed9d..96c95dcea0 100644 --- a/docs/reference-guide/03-commands.md +++ b/docs/reference-guide/03-commands.md @@ -220,7 +220,6 @@ Auxiliary window [Areas] Opens a window in which a choice can be made regarding - _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)_ -- _Save intermediate results (false / true)_ - _Include hurdle cost in CSR optimization (false / true)_ - _Thresholds:_ - _Initiate curtailment sharing rule_ diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index b401a88ee0..21543155a3 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -249,7 +249,6 @@ void Parameters::resetAdqPatchParameters() adqPatch.localMatching.setToZeroOutsideInsideLinks = true; adqPatch.localMatching.setToZeroOutsideOutsideLinks = true; adqPatch.curtailmentSharing.priceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; - adqPatch.saveIntermediateResults = false; adqPatch.curtailmentSharing.includeHurdleCost = false; resetThresholdsAdqPatch(); } @@ -681,8 +680,6 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, return value.to(d.adqPatch.localMatching.setToZeroOutsideInsideLinks); if (key == "set-to-null-ntc-between-physical-out-for-first-step") return value.to(d.adqPatch.localMatching.setToZeroOutsideOutsideLinks); - if (key == "save-intermediate-results") - return value.to(d.adqPatch.saveIntermediateResults); // Price taking order if (key == "price-taking-order") return StringToPriceTakingOrder(value, d.adqPatch.curtailmentSharing.priceTakingOrder); @@ -1820,7 +1817,6 @@ void Parameters::saveToINI(IniFile& ini) const adqPatch.localMatching.setToZeroOutsideInsideLinks); section->add("set-to-null-ntc-between-physical-out-for-first-step", adqPatch.localMatching.setToZeroOutsideOutsideLinks); - section->add("save-intermediate-results", adqPatch.saveIntermediateResults); section->add("price-taking-order", PriceTakingOrderToString(adqPatch.curtailmentSharing.priceTakingOrder)); section->add("include-hurdle-cost-csr", adqPatch.curtailmentSharing.includeHurdleCost); diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 2178107319..f3678ff4c5 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -542,9 +542,6 @@ class Parameters final }; CurtailmentSharing curtailmentSharing; - //! Select whether the intermediate result before the application of the curtailment - //! sharing is to be kept in the results - bool saveIntermediateResults; void addExcludedVariables(std::vector&) const; }; diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 600e80698e..274ba00496 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -72,8 +72,6 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, = parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks; problem.adqPatchParams->SetNTCOutsideToOutsideToZero = parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks; - problem.adqPatchParams->SaveIntermediateResults - = parameters.adqPatch.saveIntermediateResults; problem.adqPatchParams->PriceTakingOrder = parameters.adqPatch.curtailmentSharing.priceTakingOrder; problem.adqPatchParams->IncludeHurdleCostCsr diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 8950899df0..419ca359ef 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -498,7 +498,6 @@ struct AdequacyPatchParameters bool AdequacyFirstStep; bool SetNTCOutsideToInsideToZero; bool SetNTCOutsideToOutsideToZero; - bool SaveIntermediateResults; bool IncludeHurdleCostCsr; AdqPatchPTO PriceTakingOrder; double ThresholdInitiateCurtailmentSharingRule; 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 c6b453f47f..2fcf7b0f3f 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 @@ -217,21 +217,6 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatchIncludeHurdleCostCsr = button; } - // Select whether the intermediate result before the application of the curtailment sharing is - // to be kept in the results - { - label = Component::CreateLabel(this, wxT("Save intermediate results")); - button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &AdequacyPatchOptions::onPopupMenuSpecify, - PopupInfo(study.parameters.adqPatch.saveIntermediateResults, wxT("true"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchSaveIntermediateResults = button; - } addLabelAdqPatch(this, s, wxT("Thresholds")); // Threshold values { @@ -345,10 +330,6 @@ void AdequacyPatchOptions::refresh() std::string buttonType = "specify"; // Include adequacy patch updateButton(pBtnAdequacyPatch, study.parameters.adqPatch.enabled, buttonType); - // Save intermediate results for adequacy patch - updateButton(pBtnAdequacyPatchSaveIntermediateResults, - study.parameters.adqPatch.saveIntermediateResults, - buttonType); // Include hurdle cost for CSR updateButton(pBtnAdequacyPatchIncludeHurdleCostCsr, study.parameters.adqPatch.curtailmentSharing.includeHurdleCost, 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 888fb4a0d4..0b46bdb1a7 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 @@ -94,7 +94,6 @@ class AdequacyPatchOptions final : public wxDialog Component::Button* pBtnNTCfromOutToInAdqPatch; Component::Button* pBtnNTCfromOutToOutAdqPatch; Component::Button* pBtnAdequacyPatchPTO; - Component::Button* pBtnAdequacyPatchSaveIntermediateResults; Component::Button* pBtnAdequacyPatchIncludeHurdleCostCsr; wxTextCtrl* pThresholdCSRStart; wxTextCtrl* pThresholdLMRviolations; From 13dfa7438e8c4aa709680d3204c20a085115c784 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 14:03:57 +0200 Subject: [PATCH 282/490] code smells parameters.cpp --- src/libs/antares/study/parameters.cpp | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 21543155a3..fcad3a8cb8 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -207,8 +207,9 @@ const char* PriceTakingOrderToString(AdequacyPatch::AdqPatchPTO pto) return "DENS"; case AdequacyPatch::AdqPatchPTO::isLoad: return "Load"; + default: + return ""; } - return ""; } Parameters::Parameters() : yearsFilter(nullptr), noOutput(false) From e90b8a057317666be0c66d0500f285f3527c0849 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 14:42:45 +0200 Subject: [PATCH 283/490] critical-CodeSmell-adequacy_patch.cpp --- src/solver/optimisation/adequacy_patch.cpp | 50 ++++++++++++---------- src/solver/optimisation/adequacy_patch.h | 5 +++ 2 files changed, 33 insertions(+), 22 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index ad4141353e..ba68604f06 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -136,38 +136,44 @@ void setNTCbounds(double& Xmax, double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) { - double threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; - double netPositionInit; - double densNew; - double ensInit; - const int numOfHoursInWeek = 168; double totalLmrViolation = 0; - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) { - for (int hour = 0; hour < numOfHoursInWeek; hour++) - { - std::tie(netPositionInit, densNew) - = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); - - ensInit = ProblemeHebdo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillancePositive[hour]; - - // check LMR violations - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; - if ((densNew < ensInit) && (ensInit - densNew > Math::Abs(threshold))) - { - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; - totalLmrViolation += (ensInit - densNew); - } - } + totalLmrViolation += LmrViolationArea(ProblemeHebdo,Area); } } return totalLmrViolation; } +double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area) +{ + const int numOfHoursInWeek = 168; + double totalLmrViolationArea = 0; + double netPositionInit; + double densNew; + double ensInit; + double threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; + + for (int hour = 0; hour < numOfHoursInWeek; hour++) + { + std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + + ensInit + = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; + + // check LMR violations + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; + if ((densNew < ensInit) && (ensInit - densNew > Math::Abs(threshold))) + { + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; + totalLmrViolationArea += (ensInit - densNew); + } + } + return totalLmrViolationArea; +} + std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, int Area, int hour) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 9e4514e77f..0dd62d4e0e 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -106,6 +106,11 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo */ double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); +/*! + * Calculate total local matching rule violation per one area. + */ +double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area); + /*! ** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] ** ** From 3bfd49069e2810c7255b0dca708f48d46b5064aa Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 14:54:37 +0200 Subject: [PATCH 284/490] critical-codeSmells- set_problem_cost.cpp --- .../set_problem_cost_function.cpp | 58 +++++++++---------- 1 file changed, 29 insertions(+), 29 deletions(-) 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 ea05066a3f..732ea1b8ed 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 @@ -33,12 +33,37 @@ #include "../solver/optimisation/opt_fonctions.h" +double calculateQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, int hour, int area) +{ + double priceTakingOrders = 0.0; // PTO + if (ProblemeHebdo->adqPatchParams->PriceTakingOrder == Data::AdequacyPatch::AdqPatchPTO::isLoad) + { + priceTakingOrders + = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] + + ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; + } + else if (ProblemeHebdo->adqPatchParams->PriceTakingOrder + == Data::AdequacyPatch::AdqPatchPTO::isDens) + { + priceTakingOrders = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; + } + + if (priceTakingOrders <= 0.0) + { + // CSR todo a warning that DENS is negative and it is considered for CSR, there + // was a check for positive threshold + return 0.0; + } + else + { + return (1 / (priceTakingOrders * priceTakingOrders)); + } +} + void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - double priceTakingOrders = 0.0; // PTO - double quadraticCost; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; @@ -58,33 +83,8 @@ void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) { - if (ProblemeHebdo->adqPatchParams->PriceTakingOrder - == Data::AdequacyPatch::AdqPatchPTO::isLoad) - { - priceTakingOrders - = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] - + ProblemeHebdo->AllMustRunGeneration[hour] - ->AllMustRunGenerationOfArea[area]; - } - else if (ProblemeHebdo->adqPatchParams->PriceTakingOrder - == Data::AdequacyPatch::AdqPatchPTO::isDens) - { - priceTakingOrders - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; - } - - if (priceTakingOrders <= 0.0) - { - // CSR todo a warning that DENS is negative and it is considered for CSR, there - // was a check for positive threshold - quadraticCost = 0.0; - } - else - { - quadraticCost = 1 / (priceTakingOrders * priceTakingOrders); - } - - ProblemeAResoudre->CoutQuadratique[Var] = quadraticCost; + ProblemeAResoudre->CoutQuadratique[Var] + = calculateQuadraticCost(ProblemeHebdo, hour, area); logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; } } From 98363bc31f15fc6b8c37b86c7200c3b2cd4982f6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 16:21:01 +0200 Subject: [PATCH 285/490] info-CodeSmell - remove todo-s --- .../construct_problem_variables.cpp | 1 - .../set_problem_cost_function.cpp | 6 ------ .../set_variable_boundaries.cpp | 15 +-------------- 3 files changed, 1 insertion(+), 21 deletions(-) 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 8421fcfd60..e37a7adb0e 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -76,7 +76,6 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; // variables: Spilled Energy of each area inside adq patch - // todo after debugging transfer this into same area loop as ENS logs.debug() << " Spilled Energy of each area inside adq patch: "; for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { 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 732ea1b8ed..e49a44c92d 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 @@ -49,15 +49,9 @@ double calculateQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, int hour, int area) } if (priceTakingOrders <= 0.0) - { - // CSR todo a warning that DENS is negative and it is considered for CSR, there - // was a check for positive threshold return 0.0; - } else - { return (1 / (priceTakingOrders * priceTakingOrders)); - } } void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) 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 2ca69fd898..58fdf62c8f 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -93,8 +93,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - // variables: Spilled Energy for each area inside adq patch - // todo after debugging transfer this into same area loop as ENS + // variables: Spilled Energy for each area inside adq patch for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] @@ -180,12 +179,6 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC // direct / indirect flow Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - // CSR Todo? - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] - // - ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; Xmin[Var] = -csrSolverRelaxation; Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; @@ -200,12 +193,6 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC Var = CorrespondanceVarNativesVarOptim ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - // CSR Todo? - // if (TransportCost->IntercoGereeAvecLoopFlow == OUI_ANTARES) - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] - // + ValeursDeNTC->ValeurDeLoopFlowOrigineVersExtremite[Interco]; - // else - // Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]; Xmin[Var] = -csrSolverRelaxation; Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; From 96017884ce939710aad7c46a8615d06c741ed0b8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 16:51:40 +0200 Subject: [PATCH 286/490] CodeSmells - global var should be const --- src/tests/src/solver/optimisation/adequacy_patch.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 29e26dcf05..15adc7246f 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -49,10 +49,10 @@ std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originTyp return std::make_pair(Xmin, Xmax); } -static double flowArea1toArea2_positive = 10; -static double flowArea1toArea2_negative = -10; -static double flowArea3toArea1_positive = 30; -static double flowArea3toArea1_negative = -30; +static const double flowArea1toArea2_positive = 10; +static const double flowArea1toArea2_negative = -10; +static const double flowArea3toArea1_positive = 30; +static const double flowArea3toArea1_negative = -30; std::pair calculateAreaFlowBalanceForOneTimeStep( bool includeFlowsOutsideAdqPatchToDensNew, From f9d0d2c258267b5dd95846f5e137dedca39e8af7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 16:51:59 +0200 Subject: [PATCH 287/490] NULL->nullptr --- .../optimisation/adequacy_patch_csr/set_variable_boundaries.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 58fdf62c8f..f102ef0172 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -219,7 +219,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = NULL; + ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = nullptr; setBoundsOnENS(ProblemeHebdo, hourlyCsrProblem); setBoundsOnSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); From 9516295183f42db229b0a26e8e097a60f50e1e6c Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 16:59:39 +0200 Subject: [PATCH 288/490] use default destructor --- .../components/datagrid/renderer/adequacy-patch-area-grid.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 58f23bfebd..cb43ff0614 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 @@ -15,9 +15,7 @@ AdequacyPatchAreaGrid::AdequacyPatchAreaGrid() : pControl(nullptr) { } -AdequacyPatchAreaGrid::~AdequacyPatchAreaGrid() -{ -} +AdequacyPatchAreaGrid::~AdequacyPatchAreaGrid() = default; bool AdequacyPatchAreaGrid::valid() const { From 0a39ad366972bf193454573e5d155a8fb4d3e2e8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:01:37 +0200 Subject: [PATCH 289/490] protected->private in adq-patch-area-grid.h --- .../components/datagrid/renderer/adequacy-patch-area-grid.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 7e3f4413d9..77503c61ab 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 @@ -59,7 +59,7 @@ class AdequacyPatchAreaGrid : public IRenderer //! An item has been updated Yuni::Bind onTriggerUpdate; -protected: +private: wxWindow* pControl; }; // class AdequacyPatchAreaGrid From f21aa5494be010c6886cf937c817a1863f16e595 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:05:22 +0200 Subject: [PATCH 290/490] use default constructor in adequacy-patch-areas --- .../windows/options/adequacy-patch/adequacy-patch-areas.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 3daa060564..22fdd8ac58 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 @@ -102,9 +102,7 @@ AdequacyPatchAreas::AdequacyPatchAreas(wxFrame* parent) : grid->forceRefresh(); } -AdequacyPatchAreas::~AdequacyPatchAreas() -{ -} +AdequacyPatchAreas::~AdequacyPatchAreas() = default; void AdequacyPatchAreas::onClose(void*) { From f10f14543db6bcddc515300f565e71d7cfc87b8a Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:11:12 +0200 Subject: [PATCH 291/490] Add the "explicit" keyword to AdequacyPatchAreas constructor --- .../windows/options/adequacy-patch/adequacy-patch-areas.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e6941ef986..334add8827 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 @@ -23,7 +23,7 @@ class AdequacyPatchAreas final : public wxDialog ** ** \param parent The parent window */ - AdequacyPatchAreas(wxFrame* parent); + explicit AdequacyPatchAreas(wxFrame* parent); //! Destructor virtual ~AdequacyPatchAreas(); //@} From a6f798011e57e8f68ba2e8323a43d2e59f036276 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:13:03 +0200 Subject: [PATCH 292/490] NULL->nullptr in adequacy-patch-options.cpp --- .../windows/options/adequacy-patch/adequacy-patch-options.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 2fcf7b0f3f..d698c66084 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 @@ -270,7 +270,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : sizer->Add(panel, 0, wxALL | wxEXPAND); // refresh - Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(AdequacyPatchOptions::onInternalMotion), NULL, this); + Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(AdequacyPatchOptions::onInternalMotion), nullptr, this); refresh(); SetSizer(sizer); From 76bf59986f302852ce30aef6d23680b32d3f7ede Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:14:57 +0200 Subject: [PATCH 293/490] = default, AdequacyPatchOptions --- .../windows/options/adequacy-patch/adequacy-patch-options.cpp | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) 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 d698c66084..aefe157d89 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 @@ -281,9 +281,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : Centre(wxBOTH); } -AdequacyPatchOptions::~AdequacyPatchOptions() -{ -} +AdequacyPatchOptions::~AdequacyPatchOptions() = default; void AdequacyPatchOptions::onClose(void*) { From f56b69aa8d04fc22c7538adac9642eae2c21d750 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:16:14 +0200 Subject: [PATCH 294/490] Add the "explicit" keyword to AdequacyPatchOptions constructor --- .../windows/options/adequacy-patch/adequacy-patch-options.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 0b46bdb1a7..aaf9a1d792 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 @@ -52,7 +52,7 @@ class AdequacyPatchOptions final : public wxDialog ** ** \param parent The parent window */ - AdequacyPatchOptions(wxWindow* parent); + explicit AdequacyPatchOptions(wxWindow* parent); //! Destructor virtual ~AdequacyPatchOptions(); //@} From 276065716a3ac49add64f60076fe5c361bf1a97f Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:25:12 +0200 Subject: [PATCH 295/490] Remove these useless parentheses --- src/solver/optimisation/adequacy_patch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index ba68604f06..6084412727 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -85,7 +85,7 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( switch (ExtremityNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - return (setToZeroNTCfromOutToIn_AdqPatch) ? setToZero : setExtremityOrigineToZero; + return setToZeroNTCfromOutToIn_AdqPatch ? setToZero : setExtremityOrigineToZero; case physicalAreaOutsideAdqPatch: return (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; default: From f560f72b360a52e5de1bb13e1a2f69eb19a5bed6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:25:44 +0200 Subject: [PATCH 296/490] Remove these useless parentheses --- src/solver/optimisation/adequacy_patch.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 6084412727..f2da043d76 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -87,7 +87,7 @@ ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( case physicalAreaInsideAdqPatch: return setToZeroNTCfromOutToIn_AdqPatch ? setToZero : setExtremityOrigineToZero; case physicalAreaOutsideAdqPatch: - return (setToZeroNTCfromOutToOut_AdqPatch) ? setToZero : leaveLocalValues; + return setToZeroNTCfromOutToOut_AdqPatch ? setToZero : leaveLocalValues; default: return leaveLocalValues; } From aecaa1f8a79b360e8f850e505b9fc8bdc32d723c Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:30:20 +0200 Subject: [PATCH 297/490] Remove the unused parameter "weekNb", --- src/solver/optimisation/adequacy_patch.cpp | 2 +- src/solver/optimisation/adequacy_patch.h | 2 +- src/solver/simulation/economy.cpp | 2 +- 3 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index f2da043d76..eff2db36c3 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -134,7 +134,7 @@ void setNTCbounds(double& Xmax, } } -double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb) +double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) { double totalLmrViolation = 0; for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 0dd62d4e0e..d899af9a1d 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -104,7 +104,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo /*! * Check local matching rule violation for each area inside adequacy patch. */ -double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo, uint weekNb); +double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo); /*! * Calculate total local matching rule violation per one area. diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index e770f426d3..4c782def95 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -241,7 +241,7 @@ void AdequacyPatchOptimization::solveCSR(Variable::State& state, uint numSpace, HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); hourlyCsrProblem.run(w, state.year); } - double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo, w); + double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo); logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 << ".Total LMR violation:" << totalLmrViolation; } From 122e0053637d5f36d1d7762e128ab822f37fa42d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:38:09 +0200 Subject: [PATCH 298/490] Move these 4 #include directives to the top of the file --- .../construct_problem_constraints_RHS.cpp | 6 ++---- 1 file changed, 2 insertions(+), 4 deletions(-) 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 43cab01f5d..814612a748 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 @@ -25,15 +25,13 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -const double csrSolverRelaxationRHS = 1e-3; - #include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - #include "../solver/simulation/simulation.h" #include "../solver/simulation/sim_extern_variables_globales.h" - #include "../solver/optimisation/opt_fonctions.h" +const double csrSolverRelaxationRHS = 1e-3; + void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Cnt; From 606a77b3b2f9771f4a3d3e02923aea303159875d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:51:05 +0200 Subject: [PATCH 299/490] declaration shadows a local variable --- .../adequacy_patch_csr/construct_problem_constraints_RHS.cpp | 1 - 1 file changed, 1 deletion(-) 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 814612a748..a95ca8bc86 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 @@ -98,7 +98,6 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, { int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Cnt; - int Area; int CntCouplante; int Interco; int NbInterco; From d7865c293f2dd3bb0cc98e5e4b177c53507fd960 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 17:54:33 +0200 Subject: [PATCH 300/490] Value stored to 'ProblemeAResoudre' is never read --- .../adequacy_patch_csr/construct_problem_variables.cpp | 1 - 1 file changed, 1 deletion(-) 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 e37a7adb0e..e8e7f01eed 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -151,7 +151,6 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( logs.debug() << "[CSR] variable list:"; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; assert(ProblemeAResoudre != NULL); constructVariableENS(ProblemeHebdo, hourlyCsrProblem); From f334819619b06159e7831764e337246c11e7fcf7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 18:14:00 +0200 Subject: [PATCH 301/490] function should be declared "const" --- src/solver/simulation/economy.cpp | 4 ++-- src/solver/simulation/economy.h | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 4c782def95..5a520d01cf 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -191,7 +191,7 @@ bool Economy::simulationBegin() return true; } -vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(uint numSpace) +vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(uint numSpace) const { std::vector sumENS(nbHoursInAWeek, 0.0); for (int area = 0; area < pProblemesHebdo[numSpace]->NombreDePays; ++area) @@ -207,7 +207,7 @@ vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(ui } std::set AdequacyPatchOptimization::identifyHoursForCurtailmentSharing(vector sumENS, - uint numSpace) + uint numSpace) const { double threshold = pProblemesHebdo[numSpace]->adqPatchParams->ThresholdInitiateCurtailmentSharingRule; diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 73dd53b999..37cc4b87ef 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -62,8 +62,8 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; private: void solveCSR(Variable::State& state, uint numSpace, uint week); - vector calculateENSoverAllAreasForEachHour(uint numSpace); - std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace); + vector calculateENSoverAllAreasForEachHour(uint numSpace) const; + std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) const; std::set getHoursRequiringCurtailmentSharing(uint numSpace); }; From f4ac2b958b1e6d47e779ec9438ccd587d122148e Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 18:20:38 +0200 Subject: [PATCH 302/490] Use "std::make_unique" to construct "std::unique_ptr --- src/tests/src/solver/optimisation/adequacy_patch.cpp | 3 +-- 1 file changed, 1 insertion(+), 2 deletions(-) diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 15adc7246f..43c3d7b90f 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -69,8 +69,7 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( problem.adequacyPatchRuntimeData.originAreaMode.resize(3); problem.adequacyPatchRuntimeData.extremityAreaMode.resize(3); - problem.adqPatchParams - = std::unique_ptr(new AdequacyPatchParameters()); + problem.adqPatchParams = std::make_unique(); auto& adqPatchParams = problem.adqPatchParams; problem.ResultatsHoraires = (RESULTATS_HORAIRES**)malloc(1 * sizeof(void*)); From 82b419c9235ee94c4e246fe39d67819221c9423d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 18:24:41 +0200 Subject: [PATCH 303/490] Value stored to 'out' during its initialization is never read --- .../components/datagrid/renderer/adequacy-patch-area-grid.cpp | 1 - 1 file changed, 1 deletion(-) 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 cb43ff0614..097f0d372c 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 @@ -51,7 +51,6 @@ bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) bool vir = s == "0" || s == "virtual" || s == "v"; bool ins = s.to() == 2 || s == "inside" || s == "i"; - bool out = s.to() == 1 || s == "outside" || s == "o"; if (vir) study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::virtualArea; From 49a68ec0e3402c32f7d00d188a24e307fb6032b3 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 18:58:45 +0200 Subject: [PATCH 304/490] major-CodeSmells-adequacy-patch-options.cpp --- .../adequacy-patch/adequacy-patch-options.cpp | 42 ++++++++++--------- 1 file changed, 23 insertions(+), 19 deletions(-) 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 aefe157d89..b62af9c013 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 @@ -60,9 +60,17 @@ static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* tex sizer->AddSpacer(5); } -static void updateButton(Component::Button* button, bool value, std::string buttonType) +static void updateButton(Component::Button* button, bool value, std::string& buttonType) { - char type = (buttonType == "ntc") ? 'N' : ((buttonType == "pto") ? 'P' : 'S'); + char type; + if (buttonType == "ntc") + { + type = 'N'; + } + else + { + type = (buttonType == "pto") ? 'P' : 'S'; + } assert(button != NULL); if (value) @@ -242,10 +250,10 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : sizer->AddSpacer(10); // Buttons - Component::Panel* panel = new Component::Panel(this); + auto panel = new Component::Panel(this); panel->SetBackgroundColour(defaultBgColor); - wxBoxSizer* pnlSizerBtns = new wxBoxSizer(wxHORIZONTAL); - wxBoxSizer* pnlSizerBtnsV = new wxBoxSizer(wxVERTICAL); + auto pnlSizerBtns = new wxBoxSizer(wxHORIZONTAL); + auto pnlSizerBtnsV = new wxBoxSizer(wxVERTICAL); panel->SetSizer(pnlSizerBtnsV); pnlSizerBtnsV->AddSpacer(8); pnlSizerBtnsV->Add(pnlSizerBtns, 1, wxALL | wxEXPAND); @@ -483,28 +491,24 @@ void AdequacyPatchOptions::onSelectModeIgnore(wxCommandEvent&) void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) { auto study = Data::Study::Current::Get(); - if (!(!study)) + if ((!(!study)) + && (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isDens)) { - if (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isDens) - { - study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isDens; - refresh(); - MarkTheStudyAsModified(); - } + study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isDens; + refresh(); + MarkTheStudyAsModified(); } } void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) { auto study = Data::Study::Current::Get(); - if (!(!study)) + if ((!(!study)) + && (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isLoad)) { - if (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isLoad) - { - study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isLoad; - refresh(); - MarkTheStudyAsModified(); - } + study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isLoad; + refresh(); + MarkTheStudyAsModified(); } } From 6dc2b06aab9453790652c23469ad88fe183009dd Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 21:31:00 +0200 Subject: [PATCH 305/490] remove "never read" variables --- .../adequacy_patch_csr/construct_problem_constraints_LHS.cpp | 1 - .../adequacy_patch_csr/construct_problem_constraints_RHS.cpp | 2 -- 2 files changed, 3 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp index 3acf492761..bc73d04267 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp @@ -226,7 +226,6 @@ void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, std::string NomDeLaContrainte; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // Special case of the binding constraints for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; 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 a95ca8bc86..d51b774911 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 @@ -164,8 +164,6 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, IndexNumeroDuPalierDispatch = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; - Palier = PaliersThermiquesDuPays->NumeroDuPalierDansLEnsembleDesPaliersThermiques - [IndexNumeroDuPalierDispatch]; Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] From 8f9f97f5d07b88b812e193aa559774f648c4b0fd Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 21:34:29 +0200 Subject: [PATCH 306/490] const& buttonType in updateButton --- .../windows/options/adequacy-patch/adequacy-patch-options.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 b62af9c013..8db553550d 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 @@ -60,7 +60,7 @@ static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* tex sizer->AddSpacer(5); } -static void updateButton(Component::Button* button, bool value, std::string& buttonType) +static void updateButton(Component::Button* button, bool value, std::string const& buttonType) { char type; if (buttonType == "ntc") From df3311643834c660b5ba7f7777cc8e8aa45a7acd Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 21:57:53 +0200 Subject: [PATCH 307/490] Replace this "enum" with "enum class" AdqPatchPTO --- src/libs/antares/study/fwd.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 1a879e82e3..a495f1a994 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -595,7 +595,7 @@ enum ntcSetToZeroStatus_AdqPatchStep1 /*! ** \brief Types of Price Taking Order (PTO) for Adequacy Patch */ -enum AdqPatchPTO +enum class AdqPatchPTO { //! PTO is DENS isDens = 0, From d7a14c70a072cf832fab08fa606c991bfa2f355d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 21:58:46 +0200 Subject: [PATCH 308/490] double*->const double* in addArray --- src/solver/optimisation/adequacy_patch.cpp | 2 +- src/solver/optimisation/adequacy_patch.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index eff2db36c3..44fda45cfb 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -228,7 +228,7 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo return std::make_pair(netPositionInit, densNew); } -void addArray(std::vector& A, double* B) +void addArray(std::vector& A, const double* B) { for (uint i = 0; i < A.size(); ++i) A[i] += B[i]; diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index d899af9a1d..237d706bd6 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -118,7 +118,7 @@ double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area); ** ** \param B An array ** ** \return ** */ -void addArray(std::vector& A, double* B); +void addArray(std::vector& A, const double* B); } // end namespace Antares } // end namespace Data From 3b2294c968e908665c5fbe1de43ec20296a07a5e Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:01:23 +0200 Subject: [PATCH 309/490] MinorCodeSmell-s construct_LHS --- .../construct_problem_constraints_LHS.cpp | 16 +++++++--------- 1 file changed, 7 insertions(+), 9 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp index bc73d04267..cb1460f82f 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp @@ -42,8 +42,7 @@ void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Var; int NombreDeTermes; - int Interco; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; std::string NomDeLaContrainte; @@ -52,7 +51,7 @@ void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of // type 2. - for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch @@ -103,11 +102,10 @@ void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, int* Colonne) { int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Area; int Var; int NombreDeTermes; int Interco; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; std::string NomDeLaContrainte; @@ -121,7 +119,7 @@ void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - for (Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) @@ -199,7 +197,7 @@ void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " + ProblemeHebdo->NomsDesPays[Area]; - ; + logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " << NomDeLaContrainte; @@ -220,9 +218,9 @@ void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, int Interco; int NbInterco; double Poids; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; + const CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; std::string NomDeLaContrainte; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; From a1ded064be49fd3d3a66056e9b50461594960f55 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:09:56 +0200 Subject: [PATCH 310/490] MinorCodeSmell-s construct_RHS --- .../construct_problem_constraints_RHS.cpp | 13 +++++-------- 1 file changed, 5 insertions(+), 8 deletions(-) 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 d51b774911..c155a28dc4 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 @@ -63,7 +63,6 @@ void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourl void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Cnt; - int Area; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; @@ -74,7 +73,7 @@ void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) // for all areas inside adequacy patch - for (Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) { if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == Data::AdequacyPatch::physicalAreaInsideAdqPatch) @@ -94,11 +93,10 @@ void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& h } void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) + const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; int Cnt; - int CntCouplante; int Interco; int NbInterco; double Poids; @@ -107,15 +105,14 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; double* SecondMembre = ProblemeAResoudre->SecondMembre; - CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - CORRESPONDANCES_DES_CONTRAINTES* CorrespondanceCntNativesCntOptim; + const CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; std::map bingdingConstraintNumber = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; // constraint: // user defined Binding constraints between transmission flows // and/or power generated from generating units. - for (CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; + for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; CntCouplante++) { if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) @@ -154,7 +151,7 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, int Palier; int IndexNumeroDuPalierDispatch; double ValueOfVar; - PALIERS_THERMIQUES* PaliersThermiquesDuPays; + const PALIERS_THERMIQUES* PaliersThermiquesDuPays; for (Index = 0; Index < NbClusters; Index++) { From 7f76dfb6721244705ef9616824ba04aad0aeedd6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:13:27 +0200 Subject: [PATCH 311/490] MinorCodeSmell-s construct_variables --- .../adequacy_patch_csr/construct_problem_variables.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) 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 e8e7f01eed..00f8695220 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -95,7 +95,7 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, } } -void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; @@ -150,7 +150,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( { logs.debug() << "[CSR] variable list:"; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; assert(ProblemeAResoudre != NULL); constructVariableENS(ProblemeHebdo, hourlyCsrProblem); From 4a4bd4d63f1aba33a5886202bde58785311ab06d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:18:29 +0200 Subject: [PATCH 312/490] MinorCodeSmell-s cost_function --- .../set_problem_cost_function.cpp | 13 ++++++------- 1 file changed, 6 insertions(+), 7 deletions(-) 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 e49a44c92d..e86d899dc3 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 @@ -54,12 +54,12 @@ double calculateQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, int hour, int area) return (1 / (priceTakingOrders * priceTakingOrders)); } -void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: ENS for each area inside adq patch @@ -85,14 +85,13 @@ void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC } } -void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Interco; - COUTS_DE_TRANSPORT* TransportCost; + const COUTS_DE_TRANSPORT* TransportCost; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: transmission cost for links between nodes of type 2 (area inside adequacy patch) @@ -103,7 +102,7 @@ void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrP // these members of objective functions are considered only if IntercoGereeAvecDesCouts = // OUI_ANTARES (use hurdle cost option is true). otherwise these members are zero. - for (Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) + for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) { if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch From 3c47ac1390f5c90ebb2fa9b52dffa9545e3bdcda Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:22:35 +0200 Subject: [PATCH 313/490] MinorCodeSmell-s set_var_bounds --- .../adequacy_patch_csr/set_variable_boundaries.cpp | 14 ++++++-------- 1 file changed, 6 insertions(+), 8 deletions(-) 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 f102ef0172..8de38a699c 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -49,7 +49,7 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: ENS for each area inside adq patch @@ -82,7 +82,7 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr } } -void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; double* AdresseDuResultat; @@ -90,7 +90,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; // variables: Spilled Energy for each area inside adq patch @@ -119,7 +119,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& } } -void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; double* AdresseDuResultat; @@ -127,9 +127,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyC hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; + const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int* TypeDeVariable; double* Xmin; double* Xmax; Xmin = ProblemeAResoudre->Xmin; @@ -214,11 +213,10 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( { logs.debug() << "[CSR] bounds"; - int Var; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = nullptr; setBoundsOnENS(ProblemeHebdo, hourlyCsrProblem); From 9b386d5874f328b7705ce73b1fc51ba95d15dccb Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:27:06 +0200 Subject: [PATCH 314/490] MinorCodeSmell-s solve_problem --- .../optimisation/adequacy_patch_csr/solve_problem.cpp | 11 +++++------ 1 file changed, 5 insertions(+), 6 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 1b9bfcb141..5e3bece2b6 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -114,12 +114,11 @@ void setToZeroIfBelowThreshold(double* pt, int Var, HOURLY_CSR_PROBLEM& hourlyCs *pt = 0.0; } -void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, +void storeInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - int Var; double* pt; - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; if (pt) @@ -131,7 +130,7 @@ void storeInteriorPointResults(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, } } -void CSR_DEBUG_HANDLE(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) +void CSR_DEBUG_HANDLE(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { int Var; @@ -168,8 +167,8 @@ void CSR_DEBUG_HANDLE(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) } } -void handleInteriorPointError(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, +void handleInteriorPointError(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + const HOURLY_CSR_PROBLEM& hourlyCsrProblem, uint weekNb, int yearNb) { From 4ea6acdd4fd74463b8d63c4f1dd8ae65acc9b8f7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:33:08 +0200 Subject: [PATCH 315/490] MinorCodeSmell-s economy.cpp --- src/solver/simulation/economy.cpp | 2 +- src/solver/simulation/economy.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 5a520d01cf..717ea54099 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -229,7 +229,7 @@ std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uin return identifyHoursForCurtailmentSharing(sumENS, numSpace); } -void AdequacyPatchOptimization::solveCSR(Variable::State& state, uint numSpace, uint w) +void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint w) { auto problemeHebdo = pProblemesHebdo[numSpace]; const std::set hoursRequiringCurtailmentSharing diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 37cc4b87ef..59f20e23f6 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -61,7 +61,7 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization AdequacyPatchOptimization(); void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; private: - void solveCSR(Variable::State& state, uint numSpace, uint week); + void solveCSR(const Variable::State& state, uint numSpace, uint week); vector calculateENSoverAllAreasForEachHour(uint numSpace) const; std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) const; std::set getHoursRequiringCurtailmentSharing(uint numSpace); From 53bc663d3a07a841777a638b1e8ce31bdcbd2715 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:34:41 +0200 Subject: [PATCH 316/490] Remove redundant public access specifier --- src/solver/simulation/sim_structure_probleme_economique.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 419ca359ef..791cabb025 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -728,7 +728,7 @@ class HOURLY_CSR_PROBLEM void solveProblem(uint week, int year); public: void run(uint week, int year); -public: + int hourInWeekTriggeredCsr; const double belowThisThresholdSetToZero = 1e-3; PROBLEME_HEBDO* pWeeklyProblemBelongedTo; From 2d8945fa67d91a514794b9b9f00a98ca1b99a8b6 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:41:40 +0200 Subject: [PATCH 317/490] Remove this redundant access specifier --- src/solver/variable/economy/localMatchingRuleViolations.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/variable/economy/localMatchingRuleViolations.h b/src/solver/variable/economy/localMatchingRuleViolations.h index 95b34647b3..36453977c6 100644 --- a/src/solver/variable/economy/localMatchingRuleViolations.h +++ b/src/solver/variable/economy/localMatchingRuleViolations.h @@ -134,7 +134,7 @@ class LMRViolations : public Variable::IVariable, NextT, VC }; }; -public: + ~LMRViolations() { delete[] pValuesForTheCurrentYear; From 91761dace90cf0fd97ca56f01f1dac70a6461356 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 22:57:38 +0200 Subject: [PATCH 318/490] MinorCodeSmell-s adq-patch-unit-tests --- .../solver/optimisation/adequacy_patch.cpp | 35 ++++++++++++------- 1 file changed, 23 insertions(+), 12 deletions(-) diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 43c3d7b90f..131957284f 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -70,7 +70,7 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( problem.adequacyPatchRuntimeData.extremityAreaMode.resize(3); problem.adqPatchParams = std::make_unique(); - auto& adqPatchParams = problem.adqPatchParams; + const auto& adqPatchParams = problem.adqPatchParams; problem.ResultatsHoraires = (RESULTATS_HORAIRES**)malloc(1 * sizeof(void*)); problem.ResultatsHoraires[0] = (RESULTATS_HORAIRES*)malloc(sizeof(RESULTATS_HORAIRES)); @@ -101,7 +101,8 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( problem.IndexSuivantIntercoExtremite[Interco] = -1; // get results - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(&problem, Area, hour); // free memory @@ -223,7 +224,8 @@ BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_change_expected_o BOOST_AUTO_TEST_CASE( calculateAreaFlowBalanceForOneTimeStep_virtual_virtual_NotIncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( false, virtualArea, virtualArea, flowArea1toArea2_positive, flowArea3toArea1_positive); BOOST_TEST(netPositionInit == 0.0); @@ -238,7 +240,8 @@ BOOST_AUTO_TEST_CASE( BOOST_AUTO_TEST_CASE( calculateAreaFlowBalanceForOneTimeStep_inside_virtual_NotIncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(false, physicalAreaInsideAdqPatch, @@ -257,7 +260,8 @@ BOOST_AUTO_TEST_CASE( BOOST_AUTO_TEST_CASE( calculateAreaFlowBalanceForOneTimeStep_inside_outside_NotIncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(false, physicalAreaInsideAdqPatch, @@ -276,7 +280,8 @@ BOOST_AUTO_TEST_CASE( BOOST_AUTO_TEST_CASE( calculateAreaFlowBalanceForOneTimeStep_inside_inside_NotIncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(false, physicalAreaInsideAdqPatch, @@ -294,7 +299,8 @@ BOOST_AUTO_TEST_CASE( // DensNew parameter SHOULD include flows from areas outside adq patch BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_IncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(true, physicalAreaInsideAdqPatch, @@ -312,7 +318,8 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_Inclu // DensNew parameter SHOULD include flows from areas outside adq patch BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_IncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(true, physicalAreaOutsideAdqPatch, @@ -330,7 +337,8 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_Incl // DensNew parameter SHOULD include flows from areas outside adq patch BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_positiveFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(true, physicalAreaOutsideAdqPatch, @@ -348,7 +356,8 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_Inclu // DensNew parameter SHOULD include flows from areas outside adq patch BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_IncludeOut_negativeFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(true, physicalAreaInsideAdqPatch, @@ -366,7 +375,8 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_Inclu // DensNew parameter SHOULD include flows from areas outside adq patch BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_IncludeOut_negativeFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(true, physicalAreaOutsideAdqPatch, @@ -384,7 +394,8 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_Incl // DensNew parameter SHOULD include flows from areas outside adq patch BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_IncludeOut_negativeFlow) { - double netPositionInit, densNew; + double netPositionInit; + double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep(true, physicalAreaOutsideAdqPatch, From a250900b07cb336096fa4071ccf2d7f00c57cbec Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 23:15:50 +0200 Subject: [PATCH 319/490] Concatenate namespace with the nested ones. --- .../economy/localMatchingRuleViolations.h | 13 ++----------- .../renderer/adequacy-patch-area-grid.cpp | 15 +++------------ .../datagrid/renderer/adequacy-patch-area-grid.h | 13 ++----------- 3 files changed, 7 insertions(+), 34 deletions(-) diff --git a/src/solver/variable/economy/localMatchingRuleViolations.h b/src/solver/variable/economy/localMatchingRuleViolations.h index 36453977c6..43b72f2306 100644 --- a/src/solver/variable/economy/localMatchingRuleViolations.h +++ b/src/solver/variable/economy/localMatchingRuleViolations.h @@ -29,13 +29,7 @@ #include "../variable.h" -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy +namespace Antares::Solver::Variable::Economy { struct VCardLMRViolations { @@ -275,9 +269,6 @@ class LMRViolations : public Variable::IVariable, NextT, VC }; // class LMRViolations -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares +} #endif // __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ 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 097f0d372c..e5b7cfd7f1 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 @@ -3,13 +3,7 @@ using namespace Yuni; -namespace Antares -{ -namespace Component -{ -namespace Datagrid -{ -namespace Renderer +namespace Antares::Component::Datagrid::Renderer { AdequacyPatchAreaGrid::AdequacyPatchAreaGrid() : pControl(nullptr) { @@ -26,7 +20,7 @@ bool AdequacyPatchAreaGrid::valid() const int AdequacyPatchAreaGrid::height() const { - return (not study) ? 0 : gridSize(); + return (!study) ? 0 : gridSize(); } wxString AdequacyPatchAreaGrid::columnCaption(int) const @@ -141,7 +135,4 @@ IRenderer::CellStyle AdequacyPatchAreaGrid::cellStyle(int, int row) const return IRenderer::cellStyleConstraintNoWeight; } -} // namespace Renderer -} // namespace Datagrid -} // namespace Component -} // namespace Antares \ No newline at end of file +} \ No newline at end of file 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 77503c61ab..45f8e7fc5e 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 @@ -5,13 +5,7 @@ #include "../renderer.h" #include "../../../../application/study.h" -namespace Antares -{ -namespace Component -{ -namespace Datagrid -{ -namespace Renderer +namespace Antares::Component::Datagrid::Renderer { class AdequacyPatchAreaGrid : public IRenderer { @@ -64,9 +58,6 @@ class AdequacyPatchAreaGrid : public IRenderer }; // class AdequacyPatchAreaGrid -} // namespace Renderer -} // namespace Datagrid -} // namespace Component -} // namespace Antares +} #endif // __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ \ No newline at end of file From 25e193d2e8cfa5c22fb503b5421892a62b9c3ed9 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 23:39:44 +0200 Subject: [PATCH 320/490] Use "override" or "final" instead of "virtual". --- .../datagrid/renderer/adequacy-patch-area-grid.h | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 45f8e7fc5e..3cf9c67d5b 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 @@ -11,9 +11,9 @@ class AdequacyPatchAreaGrid : public IRenderer { public: AdequacyPatchAreaGrid(); - virtual ~AdequacyPatchAreaGrid(); + ~AdequacyPatchAreaGrid() override; - virtual int width() const + int width() const override { return 1; } @@ -31,18 +31,18 @@ class AdequacyPatchAreaGrid : public IRenderer virtual bool cellValue(int x, int y, const Yuni::String& value); - virtual void resetColors(int, int, wxColour&, wxColour&) const + void resetColors(int, int, wxColour&, wxColour&) const override { // Do nothing } virtual bool valid() const; - virtual uint maxWidthResize() const + uint maxWidthResize() const override { return 0; } - virtual IRenderer::CellStyle cellStyle(int col, int row) const; + IRenderer::CellStyle cellStyle(int col, int row) const override; void control(wxWindow* control) { From 368f562b448d34dcaf4058d2424a5ea3886247df Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 23:40:53 +0200 Subject: [PATCH 321/490] Remove public redundant access specifier; --- .../components/datagrid/renderer/adequacy-patch-area-grid.h | 1 - 1 file changed, 1 deletion(-) 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 3cf9c67d5b..9d9ebe6d35 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 @@ -49,7 +49,6 @@ class AdequacyPatchAreaGrid : public IRenderer pControl = control; } -public: //! An item has been updated Yuni::Bind onTriggerUpdate; From 24857815303a522df3514f3d8c0e29379114eea1 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 23:53:11 +0200 Subject: [PATCH 322/490] MinorCodeSmell-s adequacy-patch-areas.h --- .../adequacy-patch/adequacy-patch-areas.cpp | 12 +++-------- .../adequacy-patch/adequacy-patch-areas.h | 20 +++++-------------- 2 files changed, 8 insertions(+), 24 deletions(-) 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 22fdd8ac58..b03975ebe4 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 @@ -17,11 +17,7 @@ using namespace Yuni; -namespace Antares -{ -namespace Window -{ -namespace Options +namespace Antares::Window::Options { BEGIN_EVENT_TABLE(AdequacyPatchAreas, wxDialog) EVT_MOTION(AdequacyPatchAreas::mouseMoved) @@ -104,7 +100,7 @@ AdequacyPatchAreas::AdequacyPatchAreas(wxFrame* parent) : AdequacyPatchAreas::~AdequacyPatchAreas() = default; -void AdequacyPatchAreas::onClose(void*) +void AdequacyPatchAreas::onClose(const void*) { Dispatcher::GUI::Close(this); } @@ -115,6 +111,4 @@ void AdequacyPatchAreas::mouseMoved(wxMouseEvent&) Antares::Component::Panel::OnMouseMoveFromExternalComponent(); } -} // namespace Options -} // namespace Window -} // namespace Antares +} 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 334add8827..3186736a6b 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 @@ -6,13 +6,8 @@ #include #include -namespace Antares +namespace Antares::Window::Options { -namespace Window -{ -namespace Options -{ - class AdequacyPatchAreas final : public wxDialog { public: @@ -25,24 +20,19 @@ class AdequacyPatchAreas final : public wxDialog */ explicit AdequacyPatchAreas(wxFrame* parent); //! Destructor - virtual ~AdequacyPatchAreas(); + ~AdequacyPatchAreas() override; //@} -protected: +private: void mouseMoved(wxMouseEvent& evt); + void onClose(const void*); -protected: - void onClose(void*); - -private: Component::Datagrid::Component* pGrid; wxWindow* pPanel; DECLARE_EVENT_TABLE() }; // class AdequacyPatchAreas -} // namespace Options -} // namespace Window -} // namespace Antares +} #endif // __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ From 32de16067f725783893dbc76aff5219ca2acf17f Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 25 Aug 2022 23:56:39 +0200 Subject: [PATCH 323/490] Concatenate namespace with the nested ones. --- .../options/adequacy-patch/adequacy-patch-options.cpp | 10 ++-------- 1 file changed, 2 insertions(+), 8 deletions(-) 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 8db553550d..05d26b6ccb 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 @@ -41,11 +41,7 @@ using namespace Yuni; using namespace Data::AdequacyPatch; -namespace Antares -{ -namespace Window -{ -namespace Options +namespace Antares::Window::Options { static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* text) { @@ -583,6 +579,4 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) } } -} // namespace Options -} // namespace Window -} // namespace Antares +} From c57dc15a70e98b099fd575ff8a33682703d9e99c Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 26 Aug 2022 00:09:49 +0200 Subject: [PATCH 324/490] Make the type of auto& study ; a reference-to-const --- .../windows/options/adequacy-patch/adequacy-patch-options.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 05d26b6ccb..b0e9ebe599 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 @@ -326,7 +326,7 @@ void AdequacyPatchOptions::refresh() if (!studyptr) return; // The current study - auto& study = *studyptr; + const auto& study = *studyptr; // Adequacy patch std::string buttonType = "specify"; From c2c2e0e99f83dfe7fec944f793a62a034018283b Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 26 Aug 2022 00:16:45 +0200 Subject: [PATCH 325/490] MinorCodeSmell-s AdequacyPatchOptions --- .../adequacy-patch/adequacy-patch-options.cpp | 2 +- .../adequacy-patch/adequacy-patch-options.h | 17 +++++------------ 2 files changed, 6 insertions(+), 13 deletions(-) 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 b0e9ebe599..6b3cc7cb8e 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 @@ -287,7 +287,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : AdequacyPatchOptions::~AdequacyPatchOptions() = default; -void AdequacyPatchOptions::onClose(void*) +void AdequacyPatchOptions::onClose(const void*) { Dispatcher::GUI::Close(this); } 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 aaf9a1d792..7e2c6a96bd 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 @@ -33,11 +33,7 @@ #include -namespace Antares -{ -namespace Window -{ -namespace Options +namespace Antares::Window::Options { /*! ** \brief Startup Wizard User Interface @@ -54,7 +50,7 @@ class AdequacyPatchOptions final : public wxDialog */ explicit AdequacyPatchOptions(wxWindow* parent); //! Destructor - virtual ~AdequacyPatchOptions(); + ~AdequacyPatchOptions() override; //@} private: @@ -68,9 +64,8 @@ class AdequacyPatchOptions final : public wxDialog const wxChar* const text; }; -private: void refresh(); - void onClose(void*); + void onClose(const void*); void onResetToDefault(void*); wxTextCtrl* insertEdit(wxWindow* parent, wxSizer* sizer, @@ -89,7 +84,7 @@ class AdequacyPatchOptions final : public wxDialog void onInternalMotion(wxMouseEvent&); void onEditThresholds(wxCommandEvent&); -private: + Component::Button* pBtnAdequacyPatch; Component::Button* pBtnNTCfromOutToInAdqPatch; Component::Button* pBtnNTCfromOutToOutAdqPatch; @@ -101,8 +96,6 @@ class AdequacyPatchOptions final : public wxDialog }; // class AdequacyPatchOptions -} // namespace Options -} // namespace Window -} // namespace Antares +} #endif // __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ From 3a59b5dece441f1057851c23294f321287cd5f9a Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 26 Aug 2022 00:33:36 +0200 Subject: [PATCH 326/490] "not"-> "!" , "and"-> "&&" --- .../options/adequacy-patch/adequacy-patch-options.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) 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 6b3cc7cb8e..9a46ab58c7 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 @@ -464,7 +464,7 @@ void AdequacyPatchOptions::onPopupMenuSpecify(Component::Button&, void AdequacyPatchOptions::onSelectModeInclude(wxCommandEvent&) { - if (pTargetRef and !*pTargetRef) + if (pTargetRef && !*pTargetRef) { *pTargetRef = true; MarkTheStudyAsModified(); @@ -475,7 +475,7 @@ void AdequacyPatchOptions::onSelectModeInclude(wxCommandEvent&) void AdequacyPatchOptions::onSelectModeIgnore(wxCommandEvent&) { - if (pTargetRef and *pTargetRef) + if (pTargetRef && *pTargetRef) { *pTargetRef = false; MarkTheStudyAsModified(); @@ -525,7 +525,7 @@ wxTextCtrl* AdequacyPatchOptions::insertEdit(wxWindow* parent, void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) { - if (not Data::Study::Current::Valid()) + if (!Data::Study::Current::Valid()) return; auto& study = *Data::Study::Current::Get(); @@ -537,7 +537,7 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) wxStringToString(pThresholdCSRStart->GetValue(), text); float newthreshold; - if (not text.to(newthreshold)) + if (!text.to(newthreshold)) { logs.error() << "impossible to update the seed for '" << "Initiate curtailment sharing rule" @@ -560,7 +560,7 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) wxStringToString(pThresholdLMRviolations->GetValue(), text); float newthreshold; - if (not text.to(newthreshold)) + if (!text.to(newthreshold)) { logs.error() << "impossible to update the seed for '" << "Display local matching rule violations" From 77391552c8790236eb656493c3a623bcffb7908a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20Omn=C3=A8s?= Date: Fri, 26 Aug 2022 16:28:29 +0200 Subject: [PATCH 327/490] Add adequacy-patch CSR study format changes (#817) --- docs/reference-guide/13-file-format.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md index 3c93e25991..91f11785b8 100644 --- a/docs/reference-guide/13-file-format.md +++ b/docs/reference-guide/13-file-format.md @@ -1,6 +1,19 @@ # 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.4.0 +### Input +In file **settings/generaldata.ini**, in existing section `adequacy patch`, add properties +* `price-taking-order` [str] that can take values "DENS" (default) or "Load" +* `include-hurdle-cost-csr` [bool], default value = `false` +* `threshold-initiate-curtailment-sharing-rule` [float], default value = 0 +* `threshold-display-local-matching-rule-violations` [float], default value = 0 + +Add variable `LMR VIOL.` for each area. Thematic trimming allows to enable/disable this output variable, see section `variables selection` in file **settings/generaldata.ini**. + +### Output +A variable `LMR VIOL.` is added for each area if `include-adq-patch` is set to `true`. + ## 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. From a2249929e51ea8e524169b04b93abc610265e4fd Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 29 Aug 2022 11:14:45 +0200 Subject: [PATCH 328/490] beta 7 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index ef3c406700..3d4a4419dd 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,7 +14,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 0) +set(ANTARES_BETA 7) set(ANTARES_RC 0) # OR-Tools tag From 81770f956dd0d975221ccf47a32c54cdb6510f13 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 29 Aug 2022 12:56:53 +0200 Subject: [PATCH 329/490] create GUI for csr var relax button --- src/libs/antares/study/parameters.cpp | 10 ++++- src/libs/antares/study/parameters.h | 6 ++- src/solver/optimisation/adequacy_patch.h | 2 + .../simulation/sim_calcul_economique.cpp | 2 + .../sim_structure_probleme_economique.h | 5 ++- .../adequacy-patch/adequacy-patch-options.cpp | 39 ++++++++++++++++++- .../adequacy-patch/adequacy-patch-options.h | 1 + 7 files changed, 58 insertions(+), 7 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index fcad3a8cb8..a1d60a3611 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -242,6 +242,8 @@ void Parameters::resetThresholdsAdqPatch() = defaultValueThresholdInitiateCurtailmentSharingRule; adqPatch.curtailmentSharing.thresholdDisplayViolations = defaultValueThresholdDisplayLocalMatchingRuleViolations; + adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation + = defaultValueThresholdVarBoundsRelaxation; } void Parameters::resetAdqPatchParameters() @@ -689,9 +691,11 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, return value.to(d.adqPatch.curtailmentSharing.includeHurdleCost); // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") - return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); + return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); if (key == "threshold-display-local-matching-rule-violations") - return value.to(d.adqPatch.curtailmentSharing.thresholdDisplayViolations); + return value.to(d.adqPatch.curtailmentSharing.thresholdDisplayViolations); + if (key == "threshold-csr-variable-bounds-relaxation") + return value.to(d.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); return false; } @@ -1826,6 +1830,8 @@ void Parameters::saveToINI(IniFile& ini) const adqPatch.curtailmentSharing.thresholdInitiate); section->add("threshold-display-local-matching-rule-violations", adqPatch.curtailmentSharing.thresholdDisplayViolations); + section->add("threshold-csr-variable-bounds-relaxation", + adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); } // Other preferences diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index f3678ff4c5..ad154bbc5f 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -534,9 +534,11 @@ class Parameters final //! PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. Data::AdequacyPatch::AdqPatchPTO priceTakingOrder; //! Threshold to initiate curtailment sharing rule - float thresholdInitiate; + double thresholdInitiate; //! Threshold to display Local Matching Rule violations - float thresholdDisplayViolations; + double thresholdDisplayViolations; + //! CSR Variables relaxation threshold + double thresholdVarBoundsRelaxation; //! Include hurdle cost in CSR cost function bool includeHurdleCost; }; diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 237d706bd6..9c3f9148a1 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -41,6 +41,8 @@ namespace AdequacyPatch const double defaultValueThresholdInitiateCurtailmentSharingRule = 0.0; //! A default threshold value for display local matching rule violations const double defaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; +//! CSR Variables relaxation threshold +const double defaultValueThresholdVarBoundsRelaxation = 1e-5; /*! * Determines restriction type for transmission links for first step of adequacy patch. * diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 274ba00496..301e3d8342 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -80,6 +80,8 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, = parameters.adqPatch.curtailmentSharing.thresholdInitiate; problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations = parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations; + problem.adqPatchParams->ThresholdCSRVarBoundsRelaxation + = parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation; problem.adequacyPatchRuntimeData.initialize(study); } diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 791cabb025..871533bf55 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -502,6 +502,7 @@ struct AdequacyPatchParameters AdqPatchPTO PriceTakingOrder; double ThresholdInitiateCurtailmentSharingRule; double ThresholdDisplayLocalMatchingRuleViolations; + double ThresholdCSRVarBoundsRelaxation; }; struct PROBLEME_HEBDO @@ -730,12 +731,14 @@ class HOURLY_CSR_PROBLEM void run(uint week, int year); int hourInWeekTriggeredCsr; - const double belowThisThresholdSetToZero = 1e-3; + double belowThisThresholdSetToZero; PROBLEME_HEBDO* pWeeklyProblemBelongedTo; HOURLY_CSR_PROBLEM(int hourInWeek, PROBLEME_HEBDO* pProblemeHebdo) { hourInWeekTriggeredCsr = hourInWeek; pWeeklyProblemBelongedTo = pProblemeHebdo; + belowThisThresholdSetToZero + = pProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; }; std::map numberOfConstraintCsrEns; std::map numberOfConstraintCsrAreaBalance; 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 9a46ab58c7..c867e35778 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 @@ -226,6 +226,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : { pThresholdCSRStart = nullptr; pThresholdLMRviolations = nullptr; + pThresholdCSRVarBoundsRelaxation = nullptr; pThresholdCSRStart = insertEdit(this, s, @@ -236,6 +237,11 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : s, wxStringFromUTF8("Display local matching rule violations"), wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); + pThresholdCSRVarBoundsRelaxation + = insertEdit(this, + s, + wxStringFromUTF8("Relax CSR variable boundaries"), + wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); } { @@ -360,7 +366,12 @@ void AdequacyPatchOptions::refresh() wxString() << study.parameters.adqPatch.curtailmentSharing.thresholdInitiate); if (pThresholdLMRviolations) pThresholdLMRviolations->SetValue( - wxString() << study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations); + wxString() + << study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations); + if (pThresholdCSRVarBoundsRelaxation) + pThresholdCSRVarBoundsRelaxation->SetValue( + wxString() + << study.parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); } } @@ -577,6 +588,30 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) } return; } -} + if (pThresholdCSRVarBoundsRelaxation && id == pThresholdCSRVarBoundsRelaxation->GetId()) + { + String text; + wxStringToString(pThresholdCSRVarBoundsRelaxation->GetValue(), text); + + float newthreshold; + if (!text.to(newthreshold)) + { + logs.error() << "impossible to update the seed for '" + << "Relax CSR variable boundaries" + << "'"; + } + else + { + if (newthreshold + != study.parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation) + { + study.parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation + = newthreshold; + MarkTheStudyAsModified(); + } + } + return; + } } +} // namespace Antares::Window::Options 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 7e2c6a96bd..b1c741ae0c 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 @@ -92,6 +92,7 @@ class AdequacyPatchOptions final : public wxDialog Component::Button* pBtnAdequacyPatchIncludeHurdleCostCsr; wxTextCtrl* pThresholdCSRStart; wxTextCtrl* pThresholdLMRviolations; + wxTextCtrl* pThresholdCSRVarBoundsRelaxation; bool* pTargetRef; }; // class AdequacyPatchOptions From 3dc576ec97fe6d81f51aed80059f31632d041c73 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 29 Aug 2022 13:23:54 +0200 Subject: [PATCH 330/490] connect GUI to logic --- .../construct_problem_constraints_RHS.cpp | 3 +-- .../set_variable_boundaries.cpp | 22 +++++++++++++------ 2 files changed, 16 insertions(+), 9 deletions(-) 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 c155a28dc4..51739ef15a 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 @@ -30,8 +30,6 @@ #include "../solver/simulation/sim_extern_variables_globales.h" #include "../solver/optimisation/opt_fonctions.h" -const double csrSolverRelaxationRHS = 1e-3; - void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Cnt; @@ -96,6 +94,7 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + double csrSolverRelaxationRHS = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; int Cnt; int Interco; int NbInterco; 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 8de38a699c..29080a58d3 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -38,7 +38,6 @@ #include #include -const double csrSolverRelaxation = 1e-3; using namespace Yuni; void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) @@ -51,6 +50,7 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + double csrSolverRelaxation = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; // variables: ENS for each area inside adq patch for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) @@ -61,7 +61,8 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; - ProblemeAResoudre->Xmax[Var] = hourlyCsrProblem.densNewValues[area] + csrSolverRelaxation; + ProblemeAResoudre->Xmax[Var] + = hourlyCsrProblem.densNewValues[area] + csrSolverRelaxation; ProblemeAResoudre->X[Var] = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; @@ -82,7 +83,8 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr } } -void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, + const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int Var; double* AdresseDuResultat; @@ -92,6 +94,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PR ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; + double csrSolverRelaxation = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; // variables: Spilled Energy for each area inside adq patch for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) @@ -125,6 +128,7 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& h double* AdresseDuResultat; int hour; hour = hourlyCsrProblem.hourInWeekTriggeredCsr; + double csrSolverRelaxation = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; @@ -149,8 +153,10 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& h { // flow Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; - Xmin[Var] = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - csrSolverRelaxation; + Xmax[Var] + = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; + Xmin[Var] + = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - csrSolverRelaxation; ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; if (Math::Infinite(Xmax[Var]) == 1) @@ -180,7 +186,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& h ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; Xmin[Var] = -csrSolverRelaxation; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; + Xmax[Var] + = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { @@ -194,7 +201,8 @@ void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& h ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; Xmin[Var] = -csrSolverRelaxation; - Xmax[Var] = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; + Xmax[Var] + = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; if (Math::Infinite(Xmax[Var]) == 1) { From 10190fe627079857b76ac5a2c1a285122e05cfd8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 29 Aug 2022 13:28:58 +0200 Subject: [PATCH 331/490] threshold e-3 >e-5 --- src/solver/optimisation/adequacy_patch.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 9c3f9148a1..dec7f72e93 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -42,7 +42,7 @@ const double defaultValueThresholdInitiateCurtailmentSharingRule = 0.0; //! A default threshold value for display local matching rule violations const double defaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; //! CSR Variables relaxation threshold -const double defaultValueThresholdVarBoundsRelaxation = 1e-5; +const double defaultValueThresholdVarBoundsRelaxation = 1e-3; /*! * Determines restriction type for transmission links for first step of adequacy patch. * From 95086f0bcd3c3192b79dc6cdd9d94761911aac1f Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 30 Aug 2022 11:58:23 +0200 Subject: [PATCH 332/490] fix (GUI wont pass smaller than 10^-6) --- src/libs/antares/study/parameters.cpp | 2 +- src/libs/antares/study/parameters.h | 2 +- src/solver/optimisation/adequacy_patch.h | 2 +- src/solver/simulation/sim_calcul_economique.cpp | 4 ++-- .../options/adequacy-patch/adequacy-patch-options.cpp | 6 +++--- 5 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index a1d60a3611..9c9b5fe80b 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -695,7 +695,7 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, if (key == "threshold-display-local-matching-rule-violations") return value.to(d.adqPatch.curtailmentSharing.thresholdDisplayViolations); if (key == "threshold-csr-variable-bounds-relaxation") - return value.to(d.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); + return value.to(d.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); return false; } diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index ad154bbc5f..ce4d2152f9 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -538,7 +538,7 @@ class Parameters final //! Threshold to display Local Matching Rule violations double thresholdDisplayViolations; //! CSR Variables relaxation threshold - double thresholdVarBoundsRelaxation; + int thresholdVarBoundsRelaxation; //! Include hurdle cost in CSR cost function bool includeHurdleCost; }; diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index dec7f72e93..fa65540979 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -42,7 +42,7 @@ const double defaultValueThresholdInitiateCurtailmentSharingRule = 0.0; //! A default threshold value for display local matching rule violations const double defaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; //! CSR Variables relaxation threshold -const double defaultValueThresholdVarBoundsRelaxation = 1e-3; +const int defaultValueThresholdVarBoundsRelaxation = 3; /*! * Determines restriction type for transmission links for first step of adequacy patch. * diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 301e3d8342..76ad5d7fa9 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -80,8 +80,8 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, = parameters.adqPatch.curtailmentSharing.thresholdInitiate; problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations = parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations; - problem.adqPatchParams->ThresholdCSRVarBoundsRelaxation - = parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation; + double temp = pow(10, -parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); + problem.adqPatchParams->ThresholdCSRVarBoundsRelaxation = temp < 0.1 ? temp : 0.1; problem.adequacyPatchRuntimeData.initialize(study); } 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 c867e35778..2defa28197 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 @@ -240,7 +240,7 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : pThresholdCSRVarBoundsRelaxation = insertEdit(this, s, - wxStringFromUTF8("Relax CSR variable boundaries"), + wxStringFromUTF8("Relax CSR variable boundaries (10^-)"), wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); } @@ -594,11 +594,11 @@ void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) String text; wxStringToString(pThresholdCSRVarBoundsRelaxation->GetValue(), text); - float newthreshold; + int newthreshold; if (!text.to(newthreshold)) { logs.error() << "impossible to update the seed for '" - << "Relax CSR variable boundaries" + << "Relax CSR variable boundaries (10^-)" << "'"; } else From a2ca7057f96b46ee1d7f85ce8c38176ffbe5a4f9 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 30 Aug 2022 15:48:07 +0200 Subject: [PATCH 333/490] Value stored to 'PaliersThermiquesDuPays' is never read --- .../adequacy_patch_csr/construct_problem_constraints_RHS.cpp | 3 --- 1 file changed, 3 deletions(-) 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 c155a28dc4..5bc230fb6c 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 @@ -148,15 +148,12 @@ void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, int NbClusters = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; int Area; - int Palier; int IndexNumeroDuPalierDispatch; double ValueOfVar; - const PALIERS_THERMIQUES* PaliersThermiquesDuPays; for (Index = 0; Index < NbClusters; Index++) { Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; - PaliersThermiquesDuPays = ProblemeHebdo->PaliersThermiquesDuPays[Area]; IndexNumeroDuPalierDispatch = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; From 74cd7ebc96c05ad4fc75257b5aadc6c58762aa33 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 30 Aug 2022 15:48:45 +0200 Subject: [PATCH 334/490] "std::string" -> "std::string_view" --- .../windows/options/adequacy-patch/adequacy-patch-options.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 9a46ab58c7..7a25ed21b6 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 @@ -56,7 +56,7 @@ static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* tex sizer->AddSpacer(5); } -static void updateButton(Component::Button* button, bool value, std::string const& buttonType) +static void updateButton(Component::Button* button, bool value, std::string_view buttonType) { char type; if (buttonType == "ntc") From f55e7ba327c0c3392e8e07d0f15e6ef3ba62d9be Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 30 Aug 2022 15:50:46 +0200 Subject: [PATCH 335/490] make getHoursRequiringCurtailmentSharing const method --- src/solver/simulation/economy.cpp | 2 +- src/solver/simulation/economy.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 717ea54099..90384ed1dc 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -223,7 +223,7 @@ std::set AdequacyPatchOptimization::identifyHoursForCurtailmentSharing(vect return triggerCsrSet; } -std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uint numSpace) +std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uint numSpace) const { vector sumENS = calculateENSoverAllAreasForEachHour(numSpace); return identifyHoursForCurtailmentSharing(sumENS, numSpace); diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 59f20e23f6..3d3f8b6df3 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -64,7 +64,7 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization void solveCSR(const Variable::State& state, uint numSpace, uint week); vector calculateENSoverAllAreasForEachHour(uint numSpace) const; std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) const; - std::set getHoursRequiringCurtailmentSharing(uint numSpace); + std::set getHoursRequiringCurtailmentSharing(uint numSpace) const; }; class NoAdequacyPatchOptimization : public EconomyWeeklyOptimization From 9e264f6d200b5d32f84593c1c35b18aa7e9f4eff Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 30 Aug 2022 15:51:16 +0200 Subject: [PATCH 336/490] remove unused var --- .../adequacy_patch_csr/construct_problem_constraints_LHS.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp index cb1460f82f..84917d814a 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp @@ -218,7 +218,6 @@ void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, int Interco; int NbInterco; double Poids; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; const CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; std::string NomDeLaContrainte; From c1cbcb7cc4d878f656be20511fe04d902ec4d38a Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 30 Aug 2022 15:51:45 +0200 Subject: [PATCH 337/490] assign ProblemeAResoudre properly --- .../adequacy_patch_csr/construct_problem_variables.cpp | 1 + 1 file changed, 1 insertion(+) 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 00f8695220..134dc90519 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -151,6 +151,7 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( logs.debug() << "[CSR] variable list:"; const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; + ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; assert(ProblemeAResoudre != NULL); constructVariableENS(ProblemeHebdo, hourlyCsrProblem); From 60013ea8ebf45202f0f8a4ab71e7aac2ea0f8749 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 19 Oct 2022 12:57:14 +0200 Subject: [PATCH 338/490] Reporting of DENS_new in GUI result for all hours --- src/solver/optimisation/adequacy_patch.cpp | 20 +++++++++++++++++++ src/solver/optimisation/adequacy_patch.h | 6 ++++++ .../set_variable_boundaries.cpp | 4 ++-- src/solver/simulation/economy.cpp | 1 + 4 files changed, 29 insertions(+), 2 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 44fda45cfb..8bf1bf8bad 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -173,6 +173,26 @@ double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area) } return totalLmrViolationArea; } +void calculateDensNewForAllHours(PROBLEME_HEBDO* ProblemeHebdo) +{ + double netPositionInit; + double densNew; + const int numOfHoursInWeek = 168; + + for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + { + if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) + { + for (int hour = 0; hour < numOfHoursInWeek; hour++) + { + std::tie(netPositionInit, densNew) + = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDENS[hour] = densNew; + } + } + } + return; +} std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, int Area, diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index fa65540979..ab8e66796f 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -113,6 +113,12 @@ double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo); */ double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area); +/*! + * 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. + */ +void calculateDensNewForAllHours(PROBLEME_HEBDO* ProblemeHebdo); + /*! ** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] ** ** 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 29080a58d3..4a5bb433bb 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -72,7 +72,7 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; - + // ovde se stavljaju rezultati u kolonu dens new, ovo treba izbaciti i staviti petlju van CSR da upise u sve redove // update DENS values with densNew values ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] = hourlyCsrProblem.densNewValues[area]; @@ -110,7 +110,7 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, ProblemeAResoudre->X[Var] = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]; - AdresseDuResultat = &( + AdresseDuResultat = &(// ovde treba da se promeni gde se stavljaju rezultati da budu u spillage after CSR ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 90384ed1dc..762002ebe4 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -232,6 +232,7 @@ std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uin void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint w) { auto problemeHebdo = pProblemesHebdo[numSpace]; + calculateDensNewForAllHours(problemeHebdo); const std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) From ec95e913e94b0028c13906cd52d7487527584fab Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 19 Oct 2022 14:00:04 +0200 Subject: [PATCH 339/490] Check CSR cost-fun-value prior&after CSR-opt - GUI --- docs/reference-guide/03-commands.md | 2 ++ src/libs/antares/study/parameters.cpp | 5 +++++ src/libs/antares/study/parameters.h | 2 ++ .../simulation/sim_calcul_economique.cpp | 2 ++ .../sim_structure_probleme_economique.h | 1 + .../adequacy-patch/adequacy-patch-options.cpp | 20 +++++++++++++++++++ .../adequacy-patch/adequacy-patch-options.h | 1 + 7 files changed, 33 insertions(+) diff --git a/docs/reference-guide/03-commands.md b/docs/reference-guide/03-commands.md index 96c95dcea0..06fb21eb2a 100644 --- a/docs/reference-guide/03-commands.md +++ b/docs/reference-guide/03-commands.md @@ -221,9 +221,11 @@ Auxiliary window [Areas] Opens a window in which a choice can be made regarding - _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 SCR 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. diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 9c9b5fe80b..1894b7096b 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -253,6 +253,7 @@ void Parameters::resetAdqPatchParameters() adqPatch.localMatching.setToZeroOutsideOutsideLinks = true; adqPatch.curtailmentSharing.priceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; adqPatch.curtailmentSharing.includeHurdleCost = false; + adqPatch.curtailmentSharing.checkCsrCostFunction = false; resetThresholdsAdqPatch(); } @@ -689,6 +690,9 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, // Include Hurdle Cost if (key == "include-hurdle-cost-csr") return value.to(d.adqPatch.curtailmentSharing.includeHurdleCost); + // Check CSR cost function prior and after CSR + if (key == "check-csr-cost-function") + return value.to(d.adqPatch.curtailmentSharing.checkCsrCostFunction); // Thresholds if (key == "threshold-initiate-curtailment-sharing-rule") return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); @@ -1825,6 +1829,7 @@ void Parameters::saveToINI(IniFile& ini) const section->add("price-taking-order", PriceTakingOrderToString(adqPatch.curtailmentSharing.priceTakingOrder)); section->add("include-hurdle-cost-csr", adqPatch.curtailmentSharing.includeHurdleCost); + section->add("check-csr-cost-function", adqPatch.curtailmentSharing.checkCsrCostFunction); // Threshholds section->add("threshold-initiate-curtailment-sharing-rule", adqPatch.curtailmentSharing.thresholdInitiate); diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index ce4d2152f9..3860b8c788 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -541,6 +541,8 @@ class Parameters final int thresholdVarBoundsRelaxation; //! Include hurdle cost in CSR cost function bool includeHurdleCost; + //! Check CSR cost function prior & after CSR optimization + bool checkCsrCostFunction; }; CurtailmentSharing curtailmentSharing; diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 76ad5d7fa9..05a8c7f265 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -76,6 +76,8 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, = parameters.adqPatch.curtailmentSharing.priceTakingOrder; problem.adqPatchParams->IncludeHurdleCostCsr = parameters.adqPatch.curtailmentSharing.includeHurdleCost; + problem.adqPatchParams->CheckCsrCostFunctionValue + = parameters.adqPatch.curtailmentSharing.checkCsrCostFunction; problem.adqPatchParams->ThresholdInitiateCurtailmentSharingRule = parameters.adqPatch.curtailmentSharing.thresholdInitiate; problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 871533bf55..c151c6a47e 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -499,6 +499,7 @@ struct AdequacyPatchParameters bool SetNTCOutsideToInsideToZero; bool SetNTCOutsideToOutsideToZero; bool IncludeHurdleCostCsr; + bool CheckCsrCostFunctionValue; AdqPatchPTO PriceTakingOrder; double ThresholdInitiateCurtailmentSharingRule; double ThresholdDisplayLocalMatchingRuleViolations; 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 93f9a33795..ddcdf0bf7e 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 @@ -221,6 +221,22 @@ AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); pBtnAdequacyPatchIncludeHurdleCostCsr = button; } + // Select whether the CSR cost function will be compared prior and after CSR optimization and + // results provided accordingly + { + label = Component::CreateLabel(this, wxT("Check CSR cost function value prior and after CSR")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind( + this, + &AdequacyPatchOptions::onPopupMenuSpecify, + PopupInfo(study.parameters.adqPatch.curtailmentSharing.checkCsrCostFunction, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatchCheckCsrCostFunctionValue = button; + } addLabelAdqPatch(this, s, wxT("Thresholds")); // Threshold values { @@ -342,6 +358,10 @@ void AdequacyPatchOptions::refresh() updateButton(pBtnAdequacyPatchIncludeHurdleCostCsr, study.parameters.adqPatch.curtailmentSharing.includeHurdleCost, buttonType); + // Check CSR cost function value prior and after CSR optimization + updateButton(pBtnAdequacyPatchCheckCsrCostFunctionValue, + study.parameters.adqPatch.curtailmentSharing.checkCsrCostFunction, + buttonType); // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. buttonType = "ntc"; 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 b1c741ae0c..1a7a311750 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 @@ -90,6 +90,7 @@ class AdequacyPatchOptions final : public wxDialog Component::Button* pBtnNTCfromOutToOutAdqPatch; Component::Button* pBtnAdequacyPatchPTO; Component::Button* pBtnAdequacyPatchIncludeHurdleCostCsr; + Component::Button* pBtnAdequacyPatchCheckCsrCostFunctionValue; wxTextCtrl* pThresholdCSRStart; wxTextCtrl* pThresholdLMRviolations; wxTextCtrl* pThresholdCSRVarBoundsRelaxation; From 20796858335b7f4a92aaea88cee19b1d0e2e087d Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 19 Oct 2022 18:24:24 +0200 Subject: [PATCH 340/490] refacto due to pre-calculating dens_new for all hours prior to csr optim --- .../adequacy_patch_csr/set_variable_boundaries.cpp | 7 ++----- 1 file changed, 2 insertions(+), 5 deletions(-) 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 4a5bb433bb..20278722ca 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -62,7 +62,8 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; ProblemeAResoudre->Xmax[Var] - = hourlyCsrProblem.densNewValues[area] + csrSolverRelaxation; + = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] + + csrSolverRelaxation; ProblemeAResoudre->X[Var] = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; @@ -72,10 +73,6 @@ void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsr ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; - // ovde se stavljaju rezultati u kolonu dens new, ovo treba izbaciti i staviti petlju van CSR da upise u sve redove - // update DENS values with densNew values - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] - = hourlyCsrProblem.densNewValues[area]; logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " << ProblemeAResoudre->Xmax[Var]; From 6a52615c8c76329bdde3562470d25e7afb960e53 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 20 Oct 2022 10:10:45 +0200 Subject: [PATCH 341/490] add "SpilledenergyAfterCSR" column --- src/libs/antares/study/parameters.cpp | 1 + src/solver/cmake/variable.cmake | 1 + .../set_variable_boundaries.cpp | 4 +- .../simulation/sim_alloc_probleme_hebdo.cpp | 3 + .../sim_structure_probleme_economique.h | 1 + src/solver/variable/economy/all.h | 69 +++-- .../economy/localMatchingRuleViolations.h | 2 +- .../variable/economy/spilledEnergyAfterCSR.h | 289 ++++++++++++++++++ 8 files changed, 337 insertions(+), 33 deletions(-) create mode 100644 src/solver/variable/economy/spilledEnergyAfterCSR.h diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 1894b7096b..f15e76cf9d 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -2021,6 +2021,7 @@ void Parameters::AdequacyPatch::addExcludedVariables(std::vector& o { out.emplace_back("DENS"); out.emplace_back("LMR VIOL."); + out.emplace_back("SPIL. ENRG. CSR"); } } diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 99ee31a335..218dcf3298 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -131,6 +131,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/unsupliedEnergy.h variable/economy/domesticUnsuppliedEnergy.h variable/economy/localMatchingRuleViolations.h + variable/economy/spilledEnergyAfterCSR.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h 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 20278722ca..9a29e2564e 100644 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp @@ -107,8 +107,8 @@ void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, ProblemeAResoudre->X[Var] = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]; - AdresseDuResultat = &(// ovde treba da se promeni gde se stavljaju rezultati da budu u spillage after CSR - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]); + AdresseDuResultat = &( + ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesSpilledEnergyAfterCSR[hour]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index 7c4a1b8d25..a536426ae7 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -455,6 +455,8 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations = (int*)MemAllocMemset(NombreDePasDeTemps * sizeof(int)); // adq patch + problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR + = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown @@ -834,6 +836,7 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index c151c6a47e..aa2466fccf 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -447,6 +447,7 @@ typedef struct double* ValeursHorairesDeDefaillancePositive; double* ValeursHorairesDENS; // adq patch domestic unsupplied energy int* ValeursHorairesLmrViolations; // adq patch lmr violations + double* ValeursHorairesSpilledEnergyAfterCSR; // adq patch spillage after CSR double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index d402ed4ffb..2a9f00c70e 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -61,6 +61,7 @@ #include "unsupliedEnergy.h" #include "domesticUnsuppliedEnergy.h" #include "localMatchingRuleViolations.h" +#include "spilledEnergyAfterCSR.h" #include "spilledEnergy.h" #include "lold.h" @@ -148,19 +149,23 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -222,31 +227,35 @@ typedef // Prices LMRViolations, Common::SpatialAggregate< SpilledEnergy, - // LOLD Common::SpatialAggregate< - LOLD, + SpilledEnergyAfterCSR, + // LOLD Common::SpatialAggregate< - LOLP, - + LOLD, Common::SpatialAggregate< - AvailableDispatchGen, + LOLP, + Common::SpatialAggregate< - DispatchableGenMargin, + AvailableDispatchGen, Common::SpatialAggregate< - Marge, - - // Detail Prices + DispatchableGenMargin, Common::SpatialAggregate< - NonProportionalCost, // MBO - // 13/05/2014 - // - refs: #21 + Marge, - // Number Of Dispatched Units + // Detail Prices Common::SpatialAggregate< - NbOfDispatchedUnits // MBO - // 25/02/2016 - // - refs: #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + NonProportionalCost, // MBO + // 13/05/2014 + // - refs: + // #21 + + // Number Of Dispatched Units + Common::SpatialAggregate< + NbOfDispatchedUnits // MBO + // 25/02/2016 + // - refs: + // #55 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< diff --git a/src/solver/variable/economy/localMatchingRuleViolations.h b/src/solver/variable/economy/localMatchingRuleViolations.h index 43b72f2306..19d5b96769 100644 --- a/src/solver/variable/economy/localMatchingRuleViolations.h +++ b/src/solver/variable/economy/localMatchingRuleViolations.h @@ -225,7 +225,7 @@ class LMRViolations : public Variable::IVariable, NextT, VC void hourForEachArea(State& state, unsigned int numSpace) { - // Total DomesticUnsuppliedEnergy emissions + // Total LocalMatchingRule Violations pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = state.hourlyResults->ValeursHorairesLmrViolations[state.hourInTheWeek]; diff --git a/src/solver/variable/economy/spilledEnergyAfterCSR.h b/src/solver/variable/economy/spilledEnergyAfterCSR.h new file mode 100644 index 0000000000..eeb9192cb0 --- /dev/null +++ b/src/solver/variable/economy/spilledEnergyAfterCSR.h @@ -0,0 +1,289 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardSpilledEnergyAfterCSR +{ + //! Caption + static const char* Caption() + { + return "SPIL. ENRG. CSR"; + } + //! Unit + static const char* Unit() + { + return "MWh"; + } + //! The short description of the variable + static const char* 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), + }; + }; + +public: + ~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); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + // Next variable + 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(); + pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( + results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class SpilledEnergyAfterCSR + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ From 308111472c37d60adc7050c5e8a98f0c217c09a8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 20 Oct 2022 10:11:21 +0200 Subject: [PATCH 342/490] TODO: densNewValues --- src/solver/optimisation/adequacy_patch.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 8bf1bf8bad..18d8848ec1 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -279,6 +279,8 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillanceNegative[hour]; + // TODO: figure out why this map when removed crashes one csr hour in test example. + // even if it not used ay all, if value is set to 10.0 it will still work and provide same results.. densNewValues[Area] = densNew; rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; } From f6715ac3b93f2ceea2a0c82dbf8b6396d0cbd415 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 20 Oct 2022 13:43:39 +0200 Subject: [PATCH 343/490] Correction of MRG.PRICE Price Cap in hours LOLE>0.5 after CSR --- src/solver/optimisation/adequacy_patch.cpp | 22 +++++++++++++++++-- src/solver/simulation/economy.cpp | 2 +- .../sim_structure_probleme_economique.h | 4 +++- 3 files changed, 24 insertions(+), 4 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 18d8848ec1..8bb8fcd3c9 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -287,6 +287,23 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() } return; } +void HOURLY_CSR_PROBLEM::adjustMrgPrices(const Antares::Solver::Variable::State& state) +{ + int hour = hourInWeekTriggeredCsr; + for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) + { + if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] + == physicalAreaInsideAdqPatch + && pWeeklyProblemBelongedTo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillancePositive[hour] + > 0.5) + { + pWeeklyProblemBelongedTo->ResultatsHoraires[Area]->CoutsMarginauxHoraires[hour] + = -state.study.areas[Area]->thermal.unsuppliedEnergyCost; + } + } + return; +} void HOURLY_CSR_PROBLEM::resetProblem() { @@ -324,7 +341,7 @@ void HOURLY_CSR_PROBLEM::solveProblem(uint week, int year) ADQ_PATCH_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this, week, year); } -void HOURLY_CSR_PROBLEM::run(uint week, int year) +void HOURLY_CSR_PROBLEM::run(uint week, const Antares::Solver::Variable::State& state) { resetProblem(); calculateCsrParameters(); @@ -333,5 +350,6 @@ void HOURLY_CSR_PROBLEM::run(uint week, int year) setVariableBounds(); buildProblemConstraintsRHS(); setProblemCost(); - solveProblem(week, year); + solveProblem(week, state.year); + adjustMrgPrices(state); } diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 762002ebe4..77463e6ea1 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -240,7 +240,7 @@ void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numS logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 << " Hour:" << w * nbHoursInAWeek + hourInWeek + 1; HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); - hourlyCsrProblem.run(w, state.year); + hourlyCsrProblem.run(w, state); } double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo); logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index aa2466fccf..f98a86adf4 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -717,6 +717,7 @@ struct PROBLEME_HEBDO double maxPminThermiqueByDay[366]; }; +namespace Antares::Solver::Variable { class State; } // foward declaration // hourly CSR problem structure class HOURLY_CSR_PROBLEM { @@ -729,8 +730,9 @@ class HOURLY_CSR_PROBLEM void buildProblemConstraintsRHS(); void setProblemCost(); void solveProblem(uint week, int year); + void adjustMrgPrices(const Antares::Solver::Variable::State& state); public: - void run(uint week, int year); + void run(uint week, const Antares::Solver::Variable::State& state); int hourInWeekTriggeredCsr; double belowThisThresholdSetToZero; From ab1f291bb5d8017c04dfa11c2a6fcb7accef76dd Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 20 Oct 2022 17:06:02 +0200 Subject: [PATCH 344/490] refacto "DENS_new" parameter calc, same thing at the end!? --- src/solver/optimisation/adequacy_patch.cpp | 12 +- src/solver/optimisation/adequacy_patch.h | 12 +- .../solver/optimisation/adequacy_patch.cpp | 167 +++++++++++++----- 3 files changed, 142 insertions(+), 49 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 8bb8fcd3c9..1c576b83e6 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -241,13 +241,21 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; if (includeFlowsOutsideAdqPatchToDensNew) - densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); + densNew = calculateDensNew(ensInit, netPositionInit + flowsNode1toNodeA); else - densNew = Math::Max(0.0, ensInit + netPositionInit); + densNew = calculateDensNew(ensInit, netPositionInit); return std::make_pair(netPositionInit, densNew); } +double calculateDensNew(double ensInit, double totalNetPositionInit) +{ + if ((totalNetPositionInit >= 0) || (ensInit > Math::Abs(totalNetPositionInit))) + return Math::Max(0.0, ensInit + totalNetPositionInit); + else + return 0.0; +} + void addArray(std::vector& A, const double* B) { for (uint i = 0; i < A.size(); ++i) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index ab8e66796f..d82044817c 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -97,12 +97,22 @@ void setNTCbounds(double& Xmax, PROBLEME_HEBDO* ProblemeHebdo); /*! - * Calculates curtailment sharing rule parameters netPositionInit and densNew per given area and hour. + * Calculates curtailment sharing rule parameters netPositionInit and densNew per given area and + * hour. */ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, int Area, int hour); +/*! + * Calculates dens new parameter depending on the values and ratio of ensInit and + * totalNetPositionInit + ** ** \param ensInit initial value of ENS (before CSR optimization) of the area + ** ** \param totalNetPositionInit total initial import/export of the area + ** ** \return double densNew value + */ +double calculateDensNew(double ensInit, double totalNetPositionInit); + /*! * Check local matching rule violation for each area inside adequacy patch. */ diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 131957284f..8f957e657a 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -49,12 +49,14 @@ std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originTyp return std::make_pair(Xmin, Xmax); } -static const double flowArea1toArea2_positive = 10; -static const double flowArea1toArea2_negative = -10; -static const double flowArea3toArea1_positive = 30; -static const double flowArea3toArea1_negative = -30; +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, @@ -87,7 +89,7 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( // input values adqPatchParams->SetNTCOutsideToInsideToZero = !includeFlowsOutsideAdqPatchToDensNew; - problem.ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour] = 0.0; + problem.ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour] = ensInit; int Interco = 1; problem.IndexDebutIntercoOrigine[Area] = Interco; problem.adequacyPatchRuntimeData.extremityAreaMode[Interco] = Area1Mode; @@ -227,7 +229,7 @@ BOOST_AUTO_TEST_CASE( double netPositionInit; double densNew; std::tie(netPositionInit, densNew) = calculateAreaFlowBalanceForOneTimeStep( - false, virtualArea, virtualArea, flowArea1toArea2_positive, flowArea3toArea1_positive); + 0.0, false, virtualArea, virtualArea, flowArea0toArea1_positive, flowArea2toArea0_positive); BOOST_TEST(netPositionInit == 0.0); BOOST_TEST(densNew == 0.0); } @@ -243,15 +245,38 @@ BOOST_AUTO_TEST_CASE( double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(false, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + false, physicalAreaInsideAdqPatch, virtualArea, - flowArea1toArea2_positive, - flowArea3toArea1_positive); - BOOST_TEST(netPositionInit == -flowArea1toArea2_positive); + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_TEST(netPositionInit == -flowArea0toArea1_positive); BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive); + BOOST_TEST(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 @@ -263,12 +288,13 @@ BOOST_AUTO_TEST_CASE( double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(false, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + false, physicalAreaInsideAdqPatch, physicalAreaOutsideAdqPatch, - flowArea1toArea2_positive, - flowArea3toArea1_positive); - BOOST_TEST(netPositionInit == -flowArea1toArea2_positive); + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_TEST(netPositionInit == -flowArea0toArea1_positive); BOOST_TEST(densNew == 0.0); } @@ -283,13 +309,14 @@ BOOST_AUTO_TEST_CASE( double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(false, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + false, physicalAreaInsideAdqPatch, physicalAreaInsideAdqPatch, - flowArea1toArea2_positive, - flowArea3toArea1_positive); - BOOST_TEST(netPositionInit == -flowArea1toArea2_positive + flowArea3toArea1_positive); - BOOST_TEST(densNew == -flowArea1toArea2_positive + flowArea3toArea1_positive); + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_TEST(netPositionInit == -flowArea0toArea1_positive + flowArea2toArea0_positive); + BOOST_TEST(densNew == -flowArea0toArea1_positive + flowArea2toArea0_positive); } // Area 0 is physical area inside adq-patch connected to two areas: @@ -302,13 +329,14 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_Inclu double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(true, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + true, physicalAreaInsideAdqPatch, physicalAreaOutsideAdqPatch, - flowArea1toArea2_positive, - flowArea3toArea1_positive); - BOOST_TEST(netPositionInit == -flowArea1toArea2_positive); - BOOST_TEST(densNew == -flowArea1toArea2_positive + flowArea3toArea1_positive); + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_TEST(netPositionInit == -flowArea0toArea1_positive); + BOOST_TEST(densNew == -flowArea0toArea1_positive + flowArea2toArea0_positive); } // Area 0 is physical area inside adq-patch connected to two areas: @@ -321,13 +349,14 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_Incl double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(true, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + true, physicalAreaOutsideAdqPatch, physicalAreaOutsideAdqPatch, - flowArea1toArea2_positive, - flowArea3toArea1_positive); + flowArea0toArea1_positive, + flowArea2toArea0_positive); BOOST_TEST(netPositionInit == 0.0); - BOOST_TEST(densNew == flowArea3toArea1_positive); + BOOST_TEST(densNew == flowArea2toArea0_positive); } // Area 0 is physical area inside adq-patch connected to two areas: @@ -340,13 +369,14 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_Inclu double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(true, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + true, physicalAreaOutsideAdqPatch, physicalAreaInsideAdqPatch, - flowArea1toArea2_positive, - flowArea3toArea1_positive); - BOOST_TEST(netPositionInit == +flowArea3toArea1_positive); - BOOST_TEST(densNew == +flowArea3toArea1_positive); + flowArea0toArea1_positive, + flowArea2toArea0_positive); + BOOST_TEST(netPositionInit == +flowArea2toArea0_positive); + BOOST_TEST(densNew == +flowArea2toArea0_positive); } // Area 0 is physical area inside adq-patch connected to two areas: @@ -359,13 +389,14 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_inside_outside_Inclu double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(true, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + true, physicalAreaInsideAdqPatch, physicalAreaOutsideAdqPatch, - flowArea1toArea2_negative, - flowArea3toArea1_negative); - BOOST_TEST(netPositionInit == -flowArea1toArea2_negative); - BOOST_TEST(densNew == -flowArea1toArea2_negative); + flowArea0toArea1_negative, + flowArea2toArea0_negative); + BOOST_TEST(netPositionInit == -flowArea0toArea1_negative); + BOOST_TEST(densNew == -flowArea0toArea1_negative); } // Area 0 is physical area inside adq-patch connected to two areas: @@ -378,13 +409,14 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_outside_Incl double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(true, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + true, physicalAreaOutsideAdqPatch, physicalAreaOutsideAdqPatch, - flowArea1toArea2_negative, - flowArea3toArea1_negative); + flowArea0toArea1_negative, + flowArea2toArea0_negative); BOOST_TEST(netPositionInit == 0.0); - BOOST_TEST(densNew == -flowArea1toArea2_negative); + BOOST_TEST(densNew == -flowArea0toArea1_negative); } // Area 0 is physical area inside adq-patch connected to two areas: @@ -397,11 +429,54 @@ BOOST_AUTO_TEST_CASE(calculateAreaFlowBalanceForOneTimeStep_outside_inside_Inclu double netPositionInit; double densNew; std::tie(netPositionInit, densNew) - = calculateAreaFlowBalanceForOneTimeStep(true, + = calculateAreaFlowBalanceForOneTimeStep(0.0, + true, physicalAreaOutsideAdqPatch, physicalAreaInsideAdqPatch, - flowArea1toArea2_negative, - flowArea3toArea1_negative); - BOOST_TEST(netPositionInit == flowArea3toArea1_negative); + flowArea0toArea1_negative, + flowArea2toArea0_negative); + BOOST_TEST(netPositionInit == flowArea2toArea0_negative); + BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive+flowArea2toArea0_negative); + BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive+flowArea2toArea0_negative); BOOST_TEST(densNew == 0.0); } From c82dac3455924d36844bb00a52776334c649be20 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 21 Oct 2022 11:31:01 +0200 Subject: [PATCH 345/490] add DTG. MRG INT/FIN columns to GUI --- src/libs/antares/study/parameters.cpp | 2 + src/solver/cmake/variable.cmake | 2 + .../simulation/sim_alloc_probleme_hebdo.cpp | 6 + .../sim_structure_probleme_economique.h | 2 + src/solver/variable/economy/all.h | 78 ++--- src/solver/variable/economy/dtgMarginFinal.h | 289 ++++++++++++++++++ src/solver/variable/economy/dtgMarginInit.h | 289 ++++++++++++++++++ 7 files changed, 634 insertions(+), 34 deletions(-) create mode 100644 src/solver/variable/economy/dtgMarginFinal.h create mode 100644 src/solver/variable/economy/dtgMarginInit.h diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index f15e76cf9d..7d36b28784 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -2022,6 +2022,8 @@ void Parameters::AdequacyPatch::addExcludedVariables(std::vector& o out.emplace_back("DENS"); out.emplace_back("LMR VIOL."); out.emplace_back("SPIL. ENRG. CSR"); + out.emplace_back("DTG. MRG. INT"); + out.emplace_back("DTG. MRG. FIN"); } } diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 218dcf3298..802aea96db 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -132,6 +132,8 @@ set(SRC_VARIABLE_ECONOMY variable/economy/domesticUnsuppliedEnergy.h variable/economy/localMatchingRuleViolations.h variable/economy/spilledEnergyAfterCSR.h + variable/economy/dtgMarginInit.h + variable/economy/dtgMarginFinal.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index a536426ae7..b2ff2daf64 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -457,6 +457,10 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (int*)MemAllocMemset(NombreDePasDeTemps * sizeof(int)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch + problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgInit + = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch + problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgFinal + = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown @@ -837,6 +841,8 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgInit); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgFinal); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index f98a86adf4..76a16323b4 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -448,6 +448,8 @@ typedef struct double* ValeursHorairesDENS; // adq patch domestic unsupplied energy int* ValeursHorairesLmrViolations; // adq patch lmr violations double* ValeursHorairesSpilledEnergyAfterCSR; // adq patch spillage after CSR + double* ValeursHorairesDtgMrgInit; // adq patch initial DTG MRG + double* ValeursHorairesDtgMrgFinal; // adq patch final DTG MRG double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 2a9f00c70e..9a5247ff61 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -62,6 +62,8 @@ #include "domesticUnsuppliedEnergy.h" #include "localMatchingRuleViolations.h" #include "spilledEnergyAfterCSR.h" +#include "dtgMarginInit.h" +#include "dtgMarginFinal.h" #include "spilledEnergy.h" #include "lold.h" @@ -152,20 +154,22 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -229,33 +233,39 @@ typedef // Prices SpilledEnergy, Common::SpatialAggregate< SpilledEnergyAfterCSR, - // LOLD Common::SpatialAggregate< - LOLD, + DtgMarginInit, Common::SpatialAggregate< - LOLP, - + DtgMarginFinal, + // LOLD Common::SpatialAggregate< - AvailableDispatchGen, + LOLD, Common::SpatialAggregate< - DispatchableGenMargin, - Common::SpatialAggregate< - Marge, + LOLP, - // Detail Prices + Common::SpatialAggregate< + AvailableDispatchGen, Common::SpatialAggregate< - NonProportionalCost, // MBO - // 13/05/2014 - // - refs: - // #21 - - // Number Of Dispatched Units + DispatchableGenMargin, Common::SpatialAggregate< - NbOfDispatchedUnits // MBO - // 25/02/2016 - // - refs: - // #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + 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 Variable::Join< diff --git a/src/solver/variable/economy/dtgMarginFinal.h b/src/solver/variable/economy/dtgMarginFinal.h new file mode 100644 index 0000000000..798808630e --- /dev/null +++ b/src/solver/variable/economy/dtgMarginFinal.h @@ -0,0 +1,289 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_DtgMarginFinal_H__ +#define __SOLVER_VARIABLE_ECONOMY_DtgMarginFinal_H__ + +#include "../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardDtgMarginFinal +{ + //! Caption + static const char* Caption() + { + return "DTG. MRG. FIN"; + } + //! Unit + static const char* Unit() + { + return "MWh"; + } + //! The short description of the variable + static const char* 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 VCardDtgMarginFinal 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 DtgMarginFinal emissions expected from all +** the thermal dispatchable clusters +*/ +template +class DtgMarginFinal + : public Variable::IVariable, NextT, VCardDtgMarginFinal> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardDtgMarginFinal 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: + ~DtgMarginFinal() + { + 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 DtgMarginFinal + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesDtgMrgFinal[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + // Next variable + 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(); + pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( + results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class DtgMarginFinal + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginFinal_H__ diff --git a/src/solver/variable/economy/dtgMarginInit.h b/src/solver/variable/economy/dtgMarginInit.h new file mode 100644 index 0000000000..e6d38dd9d6 --- /dev/null +++ b/src/solver/variable/economy/dtgMarginInit.h @@ -0,0 +1,289 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_DtgMarginInit_H__ +#define __SOLVER_VARIABLE_ECONOMY_DtgMarginInit_H__ + +#include "../variable.h" + +namespace Antares +{ +namespace Solver +{ +namespace Variable +{ +namespace Economy +{ +struct VCardDtgMarginInit +{ + //! Caption + static const char* Caption() + { + return "DTG. MRG. INT"; + } + //! Unit + static const char* Unit() + { + return "MWh"; + } + //! The short description of the variable + static const char* 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 VCardDtgMarginInit 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 DtgMarginInit emissions expected from all +** the thermal dispatchable clusters +*/ +template +class DtgMarginInit + : public Variable::IVariable, NextT, VCardDtgMarginInit> +{ +public: + //! Type of the next static variable + typedef NextT NextType; + //! VCard + typedef VCardDtgMarginInit 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: + ~DtgMarginInit() + { + 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 DtgMarginInit + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesDtgMrgInit[state.hourInTheWeek]; + + // Next variable + NextType::hourForEachArea(state, numSpace); + } + + void hourEnd(State& state, unsigned int hourInTheYear) + { + // Next variable + 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(); + pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( + results, fileLevel, precision); + } + } + +private: + //! Intermediate values for each year + typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; + unsigned int pNbYearsParallel; + +}; // class DtgMarginInit + +} // namespace Economy +} // namespace Variable +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginInit_H__ From 806710c00b853443643309125842ba84f8bc0337 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 21 Oct 2022 15:35:56 +0200 Subject: [PATCH 346/490] copy-paste spilled Energy values into spilled Energy values after CSR prior to CSR --- src/solver/optimisation/adequacy_patch.cpp | 4 ++++ 1 file changed, 4 insertions(+) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 1c576b83e6..c1da34fc02 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -188,6 +188,10 @@ void calculateDensNewForAllHours(PROBLEME_HEBDO* ProblemeHebdo) std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDENS[hour] = densNew; + // copy spilled Energy values into spilled Energy values after CSR + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesSpilledEnergyAfterCSR[hour] + = ProblemeHebdo->ResultatsHoraires[Area] + ->ValeursHorairesDeDefaillanceNegative[hour]; } } } From 161e8c6643dd3ab8384a0b4ed7428f35843c4cb4 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 25 Oct 2022 16:54:23 +0200 Subject: [PATCH 347/490] Check CSR cost value prior to and after - UNTESTED --- .../construct_problem_variables.cpp | 4 +- .../adequacy_patch_csr/solve_problem.cpp | 52 +++++++++++++++++-- .../sim_structure_probleme_economique.h | 2 + 3 files changed, 54 insertions(+), 4 deletions(-) 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 134dc90519..00bf616e5f 100644 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp @@ -57,6 +57,7 @@ void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hou = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); + hourlyCsrProblem.ensSet.insert(NumberOfVariables); logs.debug() << NumberOfVariables << " ENS[" << area << "].-[" << ProblemeHebdo->NomsDesPays[area] << "]."; @@ -95,7 +96,7 @@ void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, } } -void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) { int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; @@ -119,6 +120,7 @@ void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROB CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] = NumberOfVariables; ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; + hourlyCsrProblem.linkSet.insert(NumberOfVariables); logs.debug() << NumberOfVariables << " flow[" << Interco << "]. [" << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 5e3bece2b6..bb44995153 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -130,6 +130,50 @@ void storeInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResou } } +void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem, + uint weekNb, + int yearNb, + double deltaCost) +{ + const int hoursInWeek = 168; + if (deltaCost <= 0.0) + storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); + else + logs.warning() << "CSR optimization is providing solution with greater costs, optimum " + "solution is set as LMR . year: " + << yearNb + 1 << ". hour: " + << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; +} + +double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + const HOURLY_CSR_PROBLEM& hourlyCsrProblem) +{ + double cost = 0.0; + if (!hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->CheckCsrCostFunctionValue) + return cost; + + for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + bool inEnsSet = hourlyCsrProblem.ensSet.find(Var) != hourlyCsrProblem.ensSet.end(); + if (inEnsSet) + { + cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->X[Var] + * ProblemeAResoudre->CoutQuadratique[Var]; + } + bool inLinkSet = hourlyCsrProblem.linkSet.find(Var) != hourlyCsrProblem.linkSet.end(); + if (inLinkSet + && hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->IncludeHurdleCostCsr) + { + if (ProblemeAResoudre->X[Var] >= 0) + cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 1]; + else + cost -= ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 2]; + } + } + return cost; +} + void CSR_DEBUG_HANDLE(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) { int Var; @@ -188,12 +232,14 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, uint weekNb, int yearNb) { - auto Probleme - = buildInteriorPointProblem(ProblemeAResoudre); + double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); + auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { - storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); + double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); + storeOrDisregardInteriorPointResults( + ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); return true; } else diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 76a16323b4..a2f0e97bb5 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -756,6 +756,8 @@ class HOURLY_CSR_PROBLEM std::map rhsAreaBalanceValues; std::set varToBeSetToZeroIfBelowThreshold; // place inside only ENS and Spillage variable + std::set ensSet; // place inside only ENS inside adq-patch + std::set linkSet; // place inside only links between to zones inside adq-patch }; #endif From 7b6f348a996a79925602ff8c3ec2e1750c535d05 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 26 Oct 2022 13:27:26 +0200 Subject: [PATCH 348/490] refacto on DTG MRG CSR columns GUI --- src/libs/antares/study/parameters.cpp | 3 +- src/solver/cmake/variable.cmake | 3 +- .../simulation/sim_alloc_probleme_hebdo.cpp | 7 +- .../sim_structure_probleme_economique.h | 3 +- src/solver/variable/economy/all.h | 79 +++-- .../{dtgMarginInit.h => dtgMarginAfterCsr.h} | 30 +- src/solver/variable/economy/dtgMarginFinal.h | 289 ------------------ 7 files changed, 57 insertions(+), 357 deletions(-) rename src/solver/variable/economy/{dtgMarginInit.h => dtgMarginAfterCsr.h} (91%) delete mode 100644 src/solver/variable/economy/dtgMarginFinal.h diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 7d36b28784..12e706dbb0 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -2022,8 +2022,7 @@ void Parameters::AdequacyPatch::addExcludedVariables(std::vector& o out.emplace_back("DENS"); out.emplace_back("LMR VIOL."); out.emplace_back("SPIL. ENRG. CSR"); - out.emplace_back("DTG. MRG. INT"); - out.emplace_back("DTG. MRG. FIN"); + out.emplace_back("DTG MRG CSR"); } } diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 802aea96db..1b0ebd7ee8 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -132,8 +132,7 @@ set(SRC_VARIABLE_ECONOMY variable/economy/domesticUnsuppliedEnergy.h variable/economy/localMatchingRuleViolations.h variable/economy/spilledEnergyAfterCSR.h - variable/economy/dtgMarginInit.h - variable/economy/dtgMarginFinal.h + variable/economy/dtgMarginAfterCsr.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index b2ff2daf64..eb9cf5388d 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -457,9 +457,7 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (int*)MemAllocMemset(NombreDePasDeTemps * sizeof(int)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch - problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgInit - = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch - problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgFinal + problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgCsr = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); @@ -841,8 +839,7 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR); - MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgInit); - MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgFinal); + MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgCsr); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index a2f0e97bb5..9205818ed4 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -448,8 +448,7 @@ typedef struct double* ValeursHorairesDENS; // adq patch domestic unsupplied energy int* ValeursHorairesLmrViolations; // adq patch lmr violations double* ValeursHorairesSpilledEnergyAfterCSR; // adq patch spillage after CSR - double* ValeursHorairesDtgMrgInit; // adq patch initial DTG MRG - double* ValeursHorairesDtgMrgFinal; // adq patch final DTG MRG + double* ValeursHorairesDtgMrgCsr; // adq patch DTG MRG after CSR double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index 9a5247ff61..6dff2c066a 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -62,8 +62,7 @@ #include "domesticUnsuppliedEnergy.h" #include "localMatchingRuleViolations.h" #include "spilledEnergyAfterCSR.h" -#include "dtgMarginInit.h" -#include "dtgMarginFinal.h" +#include "dtgMarginAfterCsr.h" #include "spilledEnergy.h" #include "lold.h" @@ -154,22 +153,21 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -233,39 +231,36 @@ typedef // Prices SpilledEnergy, Common::SpatialAggregate< SpilledEnergyAfterCSR, + // LOLD Common::SpatialAggregate< - DtgMarginInit, + LOLD, Common::SpatialAggregate< - DtgMarginFinal, - // LOLD + LOLP, Common::SpatialAggregate< - LOLD, + AvailableDispatchGen, Common::SpatialAggregate< - LOLP, - + DispatchableGenMargin, Common::SpatialAggregate< - AvailableDispatchGen, + DtgMarginCsr, Common::SpatialAggregate< - DispatchableGenMargin, + Marge, + + // Detail Prices Common::SpatialAggregate< - Marge, + NonProportionalCost, // MBO + // 13/05/2014 + // - + // refs: + // #21 - // Detail Prices + // Number Of Dispatched Units Common::SpatialAggregate< - NonProportionalCost, // MBO - // 13/05/2014 - // - - // refs: - // #21 - - // Number Of Dispatched Units - Common::SpatialAggregate< - NbOfDispatchedUnits // MBO - // 25/02/2016 - // - - // refs: - // #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + NbOfDispatchedUnits // MBO + // 25/02/2016 + // - + // refs: + // #55 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; typedef Variable::Join< diff --git a/src/solver/variable/economy/dtgMarginInit.h b/src/solver/variable/economy/dtgMarginAfterCsr.h similarity index 91% rename from src/solver/variable/economy/dtgMarginInit.h rename to src/solver/variable/economy/dtgMarginAfterCsr.h index e6d38dd9d6..6021c13170 100644 --- a/src/solver/variable/economy/dtgMarginInit.h +++ b/src/solver/variable/economy/dtgMarginAfterCsr.h @@ -24,8 +24,8 @@ ** ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#ifndef __SOLVER_VARIABLE_ECONOMY_DtgMarginInit_H__ -#define __SOLVER_VARIABLE_ECONOMY_DtgMarginInit_H__ +#ifndef __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ +#define __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ #include "../variable.h" @@ -37,12 +37,12 @@ namespace Variable { namespace Economy { -struct VCardDtgMarginInit +struct VCardDtgMarginCsr { //! Caption static const char* Caption() { - return "DTG. MRG. INT"; + return "DTG MRG CSR"; } //! Unit static const char* Unit() @@ -65,7 +65,7 @@ struct VCardDtgMarginInit ResultsType; //! The VCard to look for for calculating spatial aggregates - typedef VCardDtgMarginInit VCardForSpatialAggregate; + typedef VCardDtgMarginCsr VCardForSpatialAggregate; enum { @@ -99,20 +99,20 @@ struct VCardDtgMarginInit }; // class VCard /*! -** \brief C02 Average value of the overrall DtgMarginInit emissions expected from all +** \brief C02 Average value of the overrall DtgMarginCsr emissions expected from all ** the thermal dispatchable clusters */ template -class DtgMarginInit - : public Variable::IVariable, NextT, VCardDtgMarginInit> +class DtgMarginCsr + : public Variable::IVariable, NextT, VCardDtgMarginCsr> { public: //! Type of the next static variable typedef NextT NextType; //! VCard - typedef VCardDtgMarginInit VCardType; + typedef VCardDtgMarginCsr VCardType; //! Ancestor - typedef Variable::IVariable, NextT, VCardType> AncestorType; + typedef Variable::IVariable, NextT, VCardType> AncestorType; //! List of expected results typedef typename VCardType::ResultsType ResultsType; @@ -139,7 +139,7 @@ class DtgMarginInit }; public: - ~DtgMarginInit() + ~DtgMarginCsr() { delete[] pValuesForTheCurrentYear; } @@ -236,9 +236,9 @@ class DtgMarginInit void hourForEachArea(State& state, unsigned int numSpace) { - // Total DtgMarginInit + // Total DtgMarginCsr pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDtgMrgInit[state.hourInTheWeek]; + = state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek]; // Next variable NextType::hourForEachArea(state, numSpace); @@ -279,11 +279,11 @@ class DtgMarginInit typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; unsigned int pNbYearsParallel; -}; // class DtgMarginInit +}; // class DtgMarginCsr } // namespace Economy } // namespace Variable } // namespace Solver } // namespace Antares -#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginInit_H__ +#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ diff --git a/src/solver/variable/economy/dtgMarginFinal.h b/src/solver/variable/economy/dtgMarginFinal.h deleted file mode 100644 index 798808630e..0000000000 --- a/src/solver/variable/economy/dtgMarginFinal.h +++ /dev/null @@ -1,289 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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_DtgMarginFinal_H__ -#define __SOLVER_VARIABLE_ECONOMY_DtgMarginFinal_H__ - -#include "../variable.h" - -namespace Antares -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardDtgMarginFinal -{ - //! Caption - static const char* Caption() - { - return "DTG. MRG. FIN"; - } - //! Unit - static const char* Unit() - { - return "MWh"; - } - //! The short description of the variable - static const char* 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 VCardDtgMarginFinal 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 DtgMarginFinal emissions expected from all -** the thermal dispatchable clusters -*/ -template -class DtgMarginFinal - : public Variable::IVariable, NextT, VCardDtgMarginFinal> -{ -public: - //! Type of the next static variable - typedef NextT NextType; - //! VCard - typedef VCardDtgMarginFinal 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: - ~DtgMarginFinal() - { - 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 DtgMarginFinal - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDtgMrgFinal[state.hourInTheWeek]; - - // Next variable - NextType::hourForEachArea(state, numSpace); - } - - void hourEnd(State& state, unsigned int hourInTheYear) - { - // Next variable - 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(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class DtgMarginFinal - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginFinal_H__ From ca5824ff69c15e3140d88307b41ee39cc4ce6390 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 26 Oct 2022 13:36:23 +0200 Subject: [PATCH 349/490] change log to info in "Check CSR cost value" --- .../optimisation/adequacy_patch_csr/solve_problem.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index bb44995153..1ea1006e43 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -140,10 +140,10 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* Pro if (deltaCost <= 0.0) storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); else - logs.warning() << "CSR optimization is providing solution with greater costs, optimum " - "solution is set as LMR . year: " - << yearNb + 1 << ". hour: " - << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; + logs.info() << "CSR optimization is providing solution with greater costs, optimum " + "solution is set as LMR . year: " + << yearNb + 1 << ". hour: " + << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; } double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, From d26f9870205944f96c8ab072922692999175cc43 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 26 Oct 2022 16:21:13 +0200 Subject: [PATCH 350/490] test implementation csr fun cost prior/after --- .../adequacy_patch_csr/solve_problem.cpp | 21 +++++++++++++++++++ 1 file changed, 21 insertions(+) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 1ea1006e43..5a773af22e 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -149,26 +149,44 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* Pro double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { + logs.info() << "calculateCsrCostFunctionValue! "; double cost = 0.0; if (!hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->CheckCsrCostFunctionValue) + { + logs.info() << "CheckCsrCostFunctionValue = FALSE"; return cost; + } for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { + logs.info() << "Var: " << Var; bool inEnsSet = hourlyCsrProblem.ensSet.find(Var) != hourlyCsrProblem.ensSet.end(); if (inEnsSet) { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutQuadratique[Var]; + logs.info() << "X-Q: " << ProblemeAResoudre->X[Var]; + logs.info() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]; + logs.info() << "TotalCost: " << cost; } bool inLinkSet = hourlyCsrProblem.linkSet.find(Var) != hourlyCsrProblem.linkSet.end(); if (inLinkSet && hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->IncludeHurdleCostCsr) { if (ProblemeAResoudre->X[Var] >= 0) + { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 1]; + logs.info() << "X+: " << ProblemeAResoudre->X[Var]; + logs.info() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]; + logs.info() << "TotalCost: " << cost; + } else + { cost -= ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 2]; + logs.info() << "X-: " << ProblemeAResoudre->X[Var]; + logs.info() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]; + logs.info() << "TotalCost: " << cost; + } } } return cost; @@ -233,11 +251,14 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, int yearNb) { double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); + logs.debug() << "costPriorToCsr: " << costPriorToCsr; auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); + logs.debug() << "costAfterCsr: " << costAfterCsr; + logs.debug() << "deltaCost: " << costAfterCsr - costPriorToCsr; storeOrDisregardInteriorPointResults( ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); return true; From e76202c16d7e9acff33323b0f0efc419c27e458f Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 27 Oct 2022 13:46:04 +0200 Subject: [PATCH 351/490] refacto LMR violations according to the agreement with Daniel + clean --- src/solver/optimisation/adequacy_patch.cpp | 90 +++++++------------ src/solver/optimisation/adequacy_patch.h | 38 ++++---- .../adequacy_patch_csr/solve_problem.cpp | 24 ++--- src/solver/simulation/economy.cpp | 7 +- .../sim_structure_probleme_economique.h | 2 - .../solver/optimisation/adequacy_patch.cpp | 2 +- 6 files changed, 65 insertions(+), 98 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index c1da34fc02..1f7e968157 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -134,49 +134,32 @@ void setNTCbounds(double& Xmax, } } -double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo) +double LmrViolationAreaHour(PROBLEME_HEBDO* ProblemeHebdo, + double totalNodeBalance, + int Area, + int hour) { - double totalLmrViolation = 0; - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) - { - totalLmrViolation += LmrViolationArea(ProblemeHebdo,Area); - } - } - return totalLmrViolation; -} - -double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area) -{ - const int numOfHoursInWeek = 168; - double totalLmrViolationArea = 0; - double netPositionInit; - double densNew; - double ensInit; + double ensInit + = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; double threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; - for (int hour = 0; hour < numOfHoursInWeek; hour++) + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; + // check LMR violations + if ((ensInit > 0.0) && (totalNodeBalance < 0.0) + && (Math::Abs(totalNodeBalance) > ensInit + Math::Abs(threshold))) { - std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); - - ensInit - = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; - - // check LMR violations - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; - if ((densNew < ensInit) && (ensInit - densNew > Math::Abs(threshold))) - { - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; - totalLmrViolationArea += (ensInit - densNew); - } + ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; + return Math::Abs(totalNodeBalance); } - return totalLmrViolationArea; + return 0.0; } -void calculateDensNewForAllHours(PROBLEME_HEBDO* ProblemeHebdo) + +double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo) { double netPositionInit; double densNew; + double totalNodeBalance; + double totalLmrViolation = 0.0; const int numOfHoursInWeek = 168; for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) @@ -185,22 +168,25 @@ void calculateDensNewForAllHours(PROBLEME_HEBDO* ProblemeHebdo) { for (int hour = 0; hour < numOfHoursInWeek; hour++) { - std::tie(netPositionInit, densNew) + std::tie(netPositionInit, densNew, totalNodeBalance) = calculateAreaFlowBalance(ProblemeHebdo, Area, hour); ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDENS[hour] = densNew; // copy spilled Energy values into spilled Energy values after CSR ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesSpilledEnergyAfterCSR[hour] = ProblemeHebdo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillanceNegative[hour]; + // check LMR violations + totalLmrViolation += LmrViolationAreaHour( + ProblemeHebdo, totalNodeBalance, Area, hour); } } } - return; + return totalLmrViolation; } -std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, - int Area, - int hour) +std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, + int Area, + int hour) { int Interco; double netPositionInit = 0; @@ -245,19 +231,15 @@ std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; if (includeFlowsOutsideAdqPatchToDensNew) - densNew = calculateDensNew(ensInit, netPositionInit + flowsNode1toNodeA); - else - densNew = calculateDensNew(ensInit, netPositionInit); - - return std::make_pair(netPositionInit, densNew); -} - -double calculateDensNew(double ensInit, double totalNetPositionInit) -{ - if ((totalNetPositionInit >= 0) || (ensInit > Math::Abs(totalNetPositionInit))) - return Math::Max(0.0, ensInit + totalNetPositionInit); + { + densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); + return std::make_tuple(netPositionInit, densNew, netPositionInit + flowsNode1toNodeA); + } else - return 0.0; + { + densNew = Math::Max(0.0, ensInit + netPositionInit); + return std::make_tuple(netPositionInit, densNew, netPositionInit); + } } void addArray(std::vector& A, const double* B) @@ -273,7 +255,6 @@ void addArray(std::vector& A, const double* B) void HOURLY_CSR_PROBLEM::calculateCsrParameters() { double netPositionInit; - double densNew; double ensInit; double spillageInit; int hour = hourInWeekTriggeredCsr; @@ -283,7 +264,7 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) { - std::tie(netPositionInit, densNew) + std::tie(netPositionInit, ignore, ignore) = calculateAreaFlowBalance(pWeeklyProblemBelongedTo, Area, hour); ensInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] @@ -291,9 +272,6 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillanceNegative[hour]; - // TODO: figure out why this map when removed crashes one csr hour in test example. - // even if it not used ay all, if value is set to 10.0 it will still work and provide same results.. - densNewValues[Area] = densNew; rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; } } diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index d82044817c..767e283b56 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -97,37 +97,29 @@ void setNTCbounds(double& Xmax, PROBLEME_HEBDO* ProblemeHebdo); /*! - * Calculates curtailment sharing rule parameters netPositionInit and densNew per given area and - * hour. + * Calculates curtailment sharing rule parameters netPositionInit, densNew and totalNodeBalance per + * given area and hour. */ -std::pair calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, - int Area, - int hour); +std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, + int Area, + int hour); /*! - * Calculates dens new parameter depending on the values and ratio of ensInit and - * totalNetPositionInit - ** ** \param ensInit initial value of ENS (before CSR optimization) of the area - ** ** \param totalNetPositionInit total initial import/export of the area - ** ** \return double densNew value + * Calculate total local matching rule violation per one area, per one hour. */ -double calculateDensNew(double ensInit, double totalNetPositionInit); +double LmrViolationAreaHour(PROBLEME_HEBDO* ProblemeHebdo, + double totalNodeBalance, + int Area, + int hour); /*! - * Check local matching rule violation for each area inside adequacy patch. - */ -double checkLocalMatchingRuleViolations(PROBLEME_HEBDO* ProblemeHebdo); - -/*! - * Calculate total local matching rule violation per one area. - */ -double LmrViolationArea(PROBLEME_HEBDO* ProblemeHebdo, int Area); - -/*! - * Calculate densNew values for all hours and areas inside adequacy patch and places them into + * 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] */ -void calculateDensNewForAllHours(PROBLEME_HEBDO* ProblemeHebdo); +double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo); /*! ** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 5a773af22e..7150958d28 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -149,25 +149,25 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* Pro double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - logs.info() << "calculateCsrCostFunctionValue! "; + logs.debug() << "calculateCsrCostFunctionValue! "; double cost = 0.0; if (!hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->CheckCsrCostFunctionValue) { - logs.info() << "CheckCsrCostFunctionValue = FALSE"; + logs.debug() << "CheckCsrCostFunctionValue = FALSE"; return cost; } for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) { - logs.info() << "Var: " << Var; + logs.debug() << "Var: " << Var; bool inEnsSet = hourlyCsrProblem.ensSet.find(Var) != hourlyCsrProblem.ensSet.end(); if (inEnsSet) { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutQuadratique[Var]; - logs.info() << "X-Q: " << ProblemeAResoudre->X[Var]; - logs.info() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]; - logs.info() << "TotalCost: " << cost; + logs.debug() << "X-Q: " << ProblemeAResoudre->X[Var]; + logs.debug() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]; + logs.debug() << "TotalCost: " << cost; } bool inLinkSet = hourlyCsrProblem.linkSet.find(Var) != hourlyCsrProblem.linkSet.end(); if (inLinkSet @@ -176,16 +176,16 @@ double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* Probleme if (ProblemeAResoudre->X[Var] >= 0) { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 1]; - logs.info() << "X+: " << ProblemeAResoudre->X[Var]; - logs.info() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]; - logs.info() << "TotalCost: " << cost; + logs.debug() << "X+: " << ProblemeAResoudre->X[Var]; + logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]; + logs.debug() << "TotalCost: " << cost; } else { cost -= ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 2]; - logs.info() << "X-: " << ProblemeAResoudre->X[Var]; - logs.info() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]; - logs.info() << "TotalCost: " << cost; + logs.debug() << "X-: " << ProblemeAResoudre->X[Var]; + logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]; + logs.debug() << "TotalCost: " << cost; } } } diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 77463e6ea1..c3f8ec6fb1 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -232,7 +232,9 @@ std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uin void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint w) { auto problemeHebdo = pProblemesHebdo[numSpace]; - calculateDensNewForAllHours(problemeHebdo); + double totalLmrViolation = calculateDensNewAndTotalLmrViolation(problemeHebdo); + logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 + << ".Total LMR violation:" << totalLmrViolation; const std::set hoursRequiringCurtailmentSharing = getHoursRequiringCurtailmentSharing(numSpace); for (int hourInWeek : hoursRequiringCurtailmentSharing) @@ -242,9 +244,6 @@ void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numS HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); hourlyCsrProblem.run(w, state); } - double totalLmrViolation = checkLocalMatchingRuleViolations(problemeHebdo); - logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 - << ".Total LMR violation:" << totalLmrViolation; } bool Economy::year(Progression::Task& progression, diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 9205818ed4..9744ea27ed 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -751,9 +751,7 @@ class HOURLY_CSR_PROBLEM std::map numberOfConstraintCsrHourlyBinding; // length is number of binding constraint // contains interco 2-2 - std::map densNewValues; std::map rhsAreaBalanceValues; - std::set varToBeSetToZeroIfBelowThreshold; // place inside only ENS and Spillage variable std::set ensSet; // place inside only ENS inside adq-patch std::set linkSet; // place inside only links between to zones inside adq-patch diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 8f957e657a..8d36a21327 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -105,7 +105,7 @@ std::pair calculateAreaFlowBalanceForOneTimeStep( // get results double netPositionInit; double densNew; - std::tie(netPositionInit, densNew) = calculateAreaFlowBalance(&problem, Area, hour); + std::tie(netPositionInit, densNew, ignore) = calculateAreaFlowBalance(&problem, Area, hour); // free memory free(problem.IndexDebutIntercoExtremite); From 94bfe5a7df787f18ba7a40f155f6b2920cba8ecb Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 31 Oct 2022 14:29:00 +0100 Subject: [PATCH 352/490] csr-postProcess - adjust ENS value and calc dtgMrgCsr --- src/solver/optimisation/adequacy_patch.cpp | 21 +++++++++++++++++++ src/solver/optimisation/adequacy_patch.h | 9 ++++++++ .../simulation/common-dispatchable-margin.cpp | 2 ++ .../variable/economy/dtgMarginAfterCsr.h | 14 ++++++++----- 4 files changed, 41 insertions(+), 5 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 1f7e968157..467263b103 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -248,6 +248,22 @@ void addArray(std::vector& A, const double* B) A[i] += B[i]; } +void postProcess(const double* dtgmrg, RESULTATS_HORAIRES& hourlyResults) +{ + for (uint y = 0; y != 168; ++y) + { + double& dtgMrgCsr = hourlyResults.ValeursHorairesDtgMrgCsr[y]; + double& ens = hourlyResults.ValeursHorairesDeDefaillancePositive[y]; + if (dtgMrgCsr == -1.0) // area is inside adq-patch and it is CSR triggered hour + { + dtgMrgCsr = Math::Max(0.0, dtgmrg[y] - ens); + ens = Math::Max(0.0, ens - dtgmrg[y]); + } + else + dtgMrgCsr = dtgmrg[y]; + } +} + } // end namespace Antares } // end namespace Data } // end namespace AdequacyPatch @@ -264,6 +280,10 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) { + // set DTG MRG CSR in all areas inside adq-path for all CSR triggered hours to -1.0 + pWeeklyProblemBelongedTo->ResultatsHoraires[Area]->ValeursHorairesDtgMrgCsr[hour] + = -1.0; + // calculate netPositionInit and the RHS of the AreaBalance constraints std::tie(netPositionInit, ignore, ignore) = calculateAreaFlowBalance(pWeeklyProblemBelongedTo, Area, hour); @@ -282,6 +302,7 @@ void HOURLY_CSR_PROBLEM::adjustMrgPrices(const Antares::Solver::Variable::State& int hour = hourInWeekTriggeredCsr; for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) { + // set MRG PRICE to value of unsupplied energy cost, if LOLD=1.0 (ENS>0.5) if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch && pWeeklyProblemBelongedTo->ResultatsHoraires[Area] diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 767e283b56..af5da00050 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -130,6 +130,15 @@ double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo); ** */ void addArray(std::vector& A, const double* B); +/*! +** ** \brief calculate dtgMrgCsr and adjust ENS values if neccessary +** ** +** ** \param dtgmrg pointer to array of DTG MRG +** ** \param hourlyResults hourly results +** ** \return +** */ +void postProcess(const double* dtgmrg, RESULTATS_HORAIRES& hourlyResults); + } // end namespace Antares } // end namespace Data } // end namespace AdequacyPatch diff --git a/src/solver/simulation/common-dispatchable-margin.cpp b/src/solver/simulation/common-dispatchable-margin.cpp index 5ae5a75d16..a9b7a5c593 100644 --- a/src/solver/simulation/common-dispatchable-margin.cpp +++ b/src/solver/simulation/common-dispatchable-margin.cpp @@ -32,6 +32,7 @@ #include "common-eco-adq.h" #include "sim_structure_donnees.h" #include "sim_structure_probleme_economique.h" +#include "../optimisation/adequacy_patch.h" namespace Antares { @@ -77,6 +78,7 @@ void DispatchableMarginForAllAreas(const Data::Study& study, } matrix.flush(); } + Data::AdequacyPatch::postProcess(dtgmrg, hourlyResults); } }); } diff --git a/src/solver/variable/economy/dtgMarginAfterCsr.h b/src/solver/variable/economy/dtgMarginAfterCsr.h index 6021c13170..6d3f36f39a 100644 --- a/src/solver/variable/economy/dtgMarginAfterCsr.h +++ b/src/solver/variable/economy/dtgMarginAfterCsr.h @@ -52,8 +52,7 @@ struct VCardDtgMarginCsr //! The short description of the variable static const char* Description() { - return "Spilled Energy After CSR Optimization (generation that cannot be satisfied) " - "after CSR optimization"; + return "Dispatchable Generation Margin (after CSR optimization)"; } //! The expecte results @@ -236,9 +235,14 @@ class DtgMarginCsr void hourForEachArea(State& state, unsigned int numSpace) { - // Total DtgMarginCsr - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek]; + // Total DtgMarginCsr + // if area is inside adq-patch but has no thermal clusters, value of -1.0 is left over, + // and needs to be set to zero here + if (state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek] < 0.0) + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 0.0; + else + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek]; // Next variable NextType::hourForEachArea(state, numSpace); From c1a4d05522e020fe52648316274a36cccb0be98b Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 31 Oct 2022 14:56:32 +0100 Subject: [PATCH 353/490] small refacto --- src/solver/optimisation/adequacy_patch.h | 7 ++++--- src/solver/simulation/common-dispatchable-margin.cpp | 3 ++- src/solver/variable/economy/dtgMarginAfterCsr.h | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index af5da00050..8f97979127 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -131,10 +131,11 @@ double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo); void addArray(std::vector& A, const double* B); /*! -** ** \brief calculate dtgMrgCsr and adjust ENS values if neccessary +** ** \brief Calculate Dispatchable margin for all areas after CSR optimization and adjust ENS +** ** values if neccessary ** ** -** ** \param dtgmrg pointer to array of DTG MRG -** ** \param hourlyResults hourly results +** ** \param dtgmrg pointer to the array of DTG MRG (Dispatchable margin - already calculated) +** ** \param hourlyResults hourly results structure ** ** \return ** */ void postProcess(const double* dtgmrg, RESULTATS_HORAIRES& hourlyResults); diff --git a/src/solver/simulation/common-dispatchable-margin.cpp b/src/solver/simulation/common-dispatchable-margin.cpp index a9b7a5c593..2f7bd66cd3 100644 --- a/src/solver/simulation/common-dispatchable-margin.cpp +++ b/src/solver/simulation/common-dispatchable-margin.cpp @@ -78,7 +78,8 @@ void DispatchableMarginForAllAreas(const Data::Study& study, } matrix.flush(); } - Data::AdequacyPatch::postProcess(dtgmrg, hourlyResults); + if (study.parameters.adqPatch.enabled) + Data::AdequacyPatch::postProcess(dtgmrg, hourlyResults); } }); } diff --git a/src/solver/variable/economy/dtgMarginAfterCsr.h b/src/solver/variable/economy/dtgMarginAfterCsr.h index 6d3f36f39a..7d96fd8c42 100644 --- a/src/solver/variable/economy/dtgMarginAfterCsr.h +++ b/src/solver/variable/economy/dtgMarginAfterCsr.h @@ -236,7 +236,7 @@ class DtgMarginCsr void hourForEachArea(State& state, unsigned int numSpace) { // Total DtgMarginCsr - // if area is inside adq-patch but has no thermal clusters, value of -1.0 is left over, + // if area is inside adq-patch but has no thermal clusters, value of -1.0 can be left over, // and needs to be set to zero here if (state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek] < 0.0) pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 0.0; From 4ec4939f1f9ffd327c954c3dad006f85ad069c53 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 1 Nov 2022 13:47:20 +0100 Subject: [PATCH 354/490] refacto - adjust mrgPrice after caclulating dtgMrgCsr and new Ens --- src/solver/optimisation/adequacy_patch.cpp | 58 ++++++++++--------- src/solver/optimisation/adequacy_patch.h | 8 +-- .../simulation/common-dispatchable-margin.cpp | 3 - src/solver/simulation/economy.cpp | 2 + .../sim_structure_probleme_economique.h | 1 - .../variable/economy/dtgMarginAfterCsr.h | 9 +-- 6 files changed, 38 insertions(+), 43 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 467263b103..8e295374e6 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -30,6 +30,7 @@ #include "adequacy_patch.h" #include #include "../simulation/sim_structure_probleme_economique.h" +#include "../study/area/scratchpad.h" using namespace Yuni; @@ -248,19 +249,39 @@ void addArray(std::vector& A, const double* B) A[i] += B[i]; } -void postProcess(const double* dtgmrg, RESULTATS_HORAIRES& hourlyResults) +void adqPatchPostProcess(const Data::Study& study, PROBLEME_HEBDO& problem, int numSpace) { - for (uint y = 0; y != 168; ++y) + if (!study.parameters.adqPatch.enabled) + return; + + const int numOfHoursInWeek = 168; + for (int Area = 0; Area < problem.NombreDePays; Area++) { - double& dtgMrgCsr = hourlyResults.ValeursHorairesDtgMrgCsr[y]; - double& ens = hourlyResults.ValeursHorairesDeDefaillancePositive[y]; - if (dtgMrgCsr == -1.0) // area is inside adq-patch and it is CSR triggered hour + if (problem.adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) { - dtgMrgCsr = Math::Max(0.0, dtgmrg[y] - ens); - ens = Math::Max(0.0, ens - dtgmrg[y]); + for (int hour = 0; hour < numOfHoursInWeek; hour++) + { + // define access to the required variables + auto& scratchpad = *(study.areas[Area]->scratchpad[numSpace]); + double dtgMrg = scratchpad.dispatchableGenerationMargin[hour]; + + auto& hourlyResults = *(problem.ResultatsHoraires[Area]); + double& dtgMrgCsr = hourlyResults.ValeursHorairesDtgMrgCsr[hour]; + double& ens = hourlyResults.ValeursHorairesDeDefaillancePositive[hour]; + double& mrgCost = hourlyResults.CoutsMarginauxHoraires[hour]; + // calculate DTG MRG CSR and adjust ENS if neccessary + if (dtgMrgCsr == -1.0) // area is inside adq-patch and it is CSR triggered hour + { + dtgMrgCsr = Math::Max(0.0, dtgMrg - ens); + ens = Math::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 = -study.areas[Area]->thermal.unsuppliedEnergyCost; + } + else + dtgMrgCsr = dtgMrg; + } } - else - dtgMrgCsr = dtgmrg[y]; } } @@ -297,24 +318,6 @@ void HOURLY_CSR_PROBLEM::calculateCsrParameters() } return; } -void HOURLY_CSR_PROBLEM::adjustMrgPrices(const Antares::Solver::Variable::State& state) -{ - int hour = hourInWeekTriggeredCsr; - for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) - { - // set MRG PRICE to value of unsupplied energy cost, if LOLD=1.0 (ENS>0.5) - if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] - == physicalAreaInsideAdqPatch - && pWeeklyProblemBelongedTo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillancePositive[hour] - > 0.5) - { - pWeeklyProblemBelongedTo->ResultatsHoraires[Area]->CoutsMarginauxHoraires[hour] - = -state.study.areas[Area]->thermal.unsuppliedEnergyCost; - } - } - return; -} void HOURLY_CSR_PROBLEM::resetProblem() { @@ -362,5 +365,4 @@ void HOURLY_CSR_PROBLEM::run(uint week, const Antares::Solver::Variable::State& buildProblemConstraintsRHS(); setProblemCost(); solveProblem(week, state.year); - adjustMrgPrices(state); } diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 8f97979127..364bdcfc41 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -132,13 +132,13 @@ void addArray(std::vector& A, const double* B); /*! ** ** \brief Calculate Dispatchable margin for all areas after CSR optimization and adjust ENS -** ** values if neccessary +** ** values if neccessary. If LOLD=1, Sets MRG COST for to the max value (unsupplied energy cost) ** ** -** ** \param dtgmrg pointer to the array of DTG MRG (Dispatchable margin - already calculated) -** ** \param hourlyResults hourly results structure +** ** \param study The Antares study +** ** \param problem The weekly problem, from the solver ** ** \return ** */ -void postProcess(const double* dtgmrg, RESULTATS_HORAIRES& hourlyResults); +void adqPatchPostProcess(const Data::Study& study, PROBLEME_HEBDO& problem, int numSpace); } // end namespace Antares } // end namespace Data diff --git a/src/solver/simulation/common-dispatchable-margin.cpp b/src/solver/simulation/common-dispatchable-margin.cpp index 2f7bd66cd3..5ae5a75d16 100644 --- a/src/solver/simulation/common-dispatchable-margin.cpp +++ b/src/solver/simulation/common-dispatchable-margin.cpp @@ -32,7 +32,6 @@ #include "common-eco-adq.h" #include "sim_structure_donnees.h" #include "sim_structure_probleme_economique.h" -#include "../optimisation/adequacy_patch.h" namespace Antares { @@ -78,8 +77,6 @@ void DispatchableMarginForAllAreas(const Data::Study& study, } matrix.flush(); } - if (study.parameters.adqPatch.enabled) - Data::AdequacyPatch::postProcess(dtgmrg, hourlyResults); } }); } diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index c3f8ec6fb1..2c8098f2f0 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -285,6 +285,8 @@ bool Economy::year(Progression::Task& progression, DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); + adqPatchPostProcess(study, *pProblemesHebdo[numSpace], numSpace); + computingHydroLevels(study, *pProblemesHebdo[numSpace], nbHoursInAWeek, false); RemixHydroForAllAreas( diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 9744ea27ed..fc956c5f25 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -731,7 +731,6 @@ class HOURLY_CSR_PROBLEM void buildProblemConstraintsRHS(); void setProblemCost(); void solveProblem(uint week, int year); - void adjustMrgPrices(const Antares::Solver::Variable::State& state); public: void run(uint week, const Antares::Solver::Variable::State& state); diff --git a/src/solver/variable/economy/dtgMarginAfterCsr.h b/src/solver/variable/economy/dtgMarginAfterCsr.h index 7d96fd8c42..3c2dbdf80b 100644 --- a/src/solver/variable/economy/dtgMarginAfterCsr.h +++ b/src/solver/variable/economy/dtgMarginAfterCsr.h @@ -236,13 +236,8 @@ class DtgMarginCsr void hourForEachArea(State& state, unsigned int numSpace) { // Total DtgMarginCsr - // if area is inside adq-patch but has no thermal clusters, value of -1.0 can be left over, - // and needs to be set to zero here - if (state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek] < 0.0) - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] = 0.0; - else - pValuesForTheCurrentYear[numSpace][state.hourInTheYear] - = state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek]; + pValuesForTheCurrentYear[numSpace][state.hourInTheYear] + = state.hourlyResults->ValeursHorairesDtgMrgCsr[state.hourInTheWeek]; // Next variable NextType::hourForEachArea(state, numSpace); From 4f992f55121a3547662ca0b7c4ead874926289b8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 1 Nov 2022 15:31:36 +0100 Subject: [PATCH 355/490] log update --- .../optimisation/adequacy_patch_csr/solve_problem.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 7150958d28..dcecdb4460 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -251,14 +251,14 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, int yearNb) { double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.debug() << "costPriorToCsr: " << costPriorToCsr; + logs.info() << "costPriorToCsr: " << costPriorToCsr; auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.debug() << "costAfterCsr: " << costAfterCsr; - logs.debug() << "deltaCost: " << costAfterCsr - costPriorToCsr; + logs.info() << "costAfterCsr: " << costAfterCsr; + logs.info() << "deltaCost: " << costAfterCsr - costPriorToCsr; storeOrDisregardInteriorPointResults( ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); return true; From 48e188846b34f32ca0993248bfa101918a280ac7 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 1 Nov 2022 17:36:20 +0100 Subject: [PATCH 356/490] refacto setToZeroIfBelowThreshold --- .../adequacy_patch_csr/solve_problem.cpp | 18 +++++++++++------- 1 file changed, 11 insertions(+), 7 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index dcecdb4460..81c412b404 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -105,13 +105,17 @@ std::unique_ptr buildInteriorPointProblem( return Probleme; } -void setToZeroIfBelowThreshold(double* pt, int Var, HOURLY_CSR_PROBLEM& hourlyCsrProblem) +void setToZeroIfBelowThreshold(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, + HOURLY_CSR_PROBLEM& hourlyCsrProblem) { - bool inSet = hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.find(Var) - != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); - bool belowLimit = *pt < hourlyCsrProblem.belowThisThresholdSetToZero; - if (inSet && belowLimit) - *pt = 0.0; + for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) + { + bool inSet = hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.find(Var) + != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); + bool belowLimit = ProblemeAResoudre->X[Var] < hourlyCsrProblem.belowThisThresholdSetToZero; + if (inSet && belowLimit) + ProblemeAResoudre->X[Var] = 0.0; + } } void storeInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, @@ -124,7 +128,6 @@ void storeInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResou if (pt) { *pt = ProblemeAResoudre->X[Var]; - setToZeroIfBelowThreshold(pt, Var, hourlyCsrProblem); } logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; } @@ -256,6 +259,7 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { + setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); logs.info() << "costAfterCsr: " << costAfterCsr; logs.info() << "deltaCost: " << costAfterCsr - costPriorToCsr; From aab53fbe903a6051b4b933e6ccd0aa8f15e5ff7e Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 1 Nov 2022 18:11:35 +0100 Subject: [PATCH 357/490] update/refacto log csr-solver --- .../adequacy_patch_csr/solve_problem.cpp | 32 +++++++++---------- 1 file changed, 16 insertions(+), 16 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 81c412b404..56be899de0 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -143,10 +143,10 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* Pro if (deltaCost <= 0.0) storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); else - logs.info() << "CSR optimization is providing solution with greater costs, optimum " - "solution is set as LMR . year: " - << yearNb + 1 << ". hour: " - << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; + logs.warning() << "CSR optimization is providing solution with greater costs, optimum " + "solution is set as LMR . year: " + << yearNb + 1 << ". hour: " + << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; } double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, @@ -168,9 +168,9 @@ double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* Probleme { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutQuadratique[Var]; - logs.debug() << "X-Q: " << ProblemeAResoudre->X[Var]; - logs.debug() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]; - logs.debug() << "TotalCost: " << cost; + logs.debug() << "X-Q: " << ProblemeAResoudre->X[Var]*1000000; + logs.debug() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]*1000000; + logs.debug() << "TotalCost: " << cost*1000000; } bool inLinkSet = hourlyCsrProblem.linkSet.find(Var) != hourlyCsrProblem.linkSet.end(); if (inLinkSet @@ -179,16 +179,16 @@ double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* Probleme if (ProblemeAResoudre->X[Var] >= 0) { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 1]; - logs.debug() << "X+: " << ProblemeAResoudre->X[Var]; - logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]; - logs.debug() << "TotalCost: " << cost; + logs.debug() << "X+: " << ProblemeAResoudre->X[Var]*1000000; + logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]*1000000; + logs.debug() << "TotalCost: " << cost*1000000; } else { cost -= ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 2]; - logs.debug() << "X-: " << ProblemeAResoudre->X[Var]; - logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]; - logs.debug() << "TotalCost: " << cost; + logs.debug() << "X-: " << ProblemeAResoudre->X[Var]*1000000; + logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]*1000000; + logs.debug() << "TotalCost: " << cost*1000000; } } } @@ -254,15 +254,15 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, int yearNb) { double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "costPriorToCsr: " << costPriorToCsr; + logs.info() << "costPriorToCsr[*10^6]: " << costPriorToCsr*1e6; auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "costAfterCsr: " << costAfterCsr; - logs.info() << "deltaCost: " << costAfterCsr - costPriorToCsr; + logs.info() << "costAfterCsr[*10^6]: " << costAfterCsr*1e6; + logs.info() << "deltaCost[*10^6]: " << (costAfterCsr - costPriorToCsr)*1e6; storeOrDisregardInteriorPointResults( ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); return true; From 593de28a37818c43296ebbe134a90ffef8a64c37 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 2 Nov 2022 09:16:51 +0100 Subject: [PATCH 358/490] refacto logs @ solve_problem.cpp --- .../adequacy_patch_csr/solve_problem.cpp | 24 +++++++++---------- 1 file changed, 12 insertions(+), 12 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 56be899de0..0e8ed6b227 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -168,9 +168,9 @@ double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* Probleme { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutQuadratique[Var]; - logs.debug() << "X-Q: " << ProblemeAResoudre->X[Var]*1000000; - logs.debug() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]*1000000; - logs.debug() << "TotalCost: " << cost*1000000; + logs.debug() << "X-Q: " << ProblemeAResoudre->X[Var]*1e3; + logs.debug() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]*1e3; + logs.debug() << "TotalCost: " << cost*1e3; } bool inLinkSet = hourlyCsrProblem.linkSet.find(Var) != hourlyCsrProblem.linkSet.end(); if (inLinkSet @@ -179,16 +179,16 @@ double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* Probleme if (ProblemeAResoudre->X[Var] >= 0) { cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 1]; - logs.debug() << "X+: " << ProblemeAResoudre->X[Var]*1000000; - logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]*1000000; - logs.debug() << "TotalCost: " << cost*1000000; + logs.debug() << "X+: " << ProblemeAResoudre->X[Var]*1e3; + logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]*1e3; + logs.debug() << "TotalCost: " << cost*1e3; } else { cost -= ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 2]; - logs.debug() << "X-: " << ProblemeAResoudre->X[Var]*1000000; - logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]*1000000; - logs.debug() << "TotalCost: " << cost*1000000; + logs.debug() << "X-: " << ProblemeAResoudre->X[Var]*1e3; + logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]*1e3; + logs.debug() << "TotalCost: " << cost*1e3; } } } @@ -254,15 +254,15 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, int yearNb) { double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "costPriorToCsr[*10^6]: " << costPriorToCsr*1e6; + logs.info() << "costPriorToCsr: " << costPriorToCsr; auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "costAfterCsr[*10^6]: " << costAfterCsr*1e6; - logs.info() << "deltaCost[*10^6]: " << (costAfterCsr - costPriorToCsr)*1e6; + logs.info() << "costAfterCsr: " << costAfterCsr; + logs.info() << "deltaCost: " << costAfterCsr - costPriorToCsr; storeOrDisregardInteriorPointResults( ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); return true; From 283b7a6f1550f526530dbd57bf3586b7b7fc1c86 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 2 Nov 2022 09:17:40 +0100 Subject: [PATCH 359/490] typo --- src/solver/optimisation/adequacy_patch.h | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 364bdcfc41..9e81ce9af7 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -132,7 +132,7 @@ void addArray(std::vector& A, const double* B); /*! ** ** \brief Calculate Dispatchable margin for all areas after CSR optimization and adjust ENS -** ** values if neccessary. If LOLD=1, Sets MRG COST for to the max value (unsupplied energy cost) +** ** values if neccessary. If LOLD=1, Sets MRG COST to the max value (unsupplied energy cost) ** ** ** ** \param study The Antares study ** ** \param problem The weekly problem, from the solver From 1ce0a65c1d127f5aaa22a3d139df47151c49c33f Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 3 Nov 2022 09:11:50 +0100 Subject: [PATCH 360/490] beta7 -> beta8 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 3d4a4419dd..8a9bf54597 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,7 +14,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 7) +set(ANTARES_BETA 8) set(ANTARES_RC 0) # OR-Tools tag From 45baf97afd1db676b3134b5818f68d6f452f129f Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 3 Nov 2022 11:23:32 +0100 Subject: [PATCH 361/490] add prefix [adq-patch] to info logs --- .../adequacy_patch_csr/solve_problem.cpp | 15 ++++++++------- 1 file changed, 8 insertions(+), 7 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 0e8ed6b227..69cdbcdc1a 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -143,10 +143,11 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* Pro if (deltaCost <= 0.0) storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); else - logs.warning() << "CSR optimization is providing solution with greater costs, optimum " - "solution is set as LMR . year: " - << yearNb + 1 << ". hour: " - << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; + 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.hourInWeekTriggeredCsr + 1; } double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, @@ -254,15 +255,15 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, int yearNb) { double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "costPriorToCsr: " << costPriorToCsr; + logs.info() << "[adq-patch] costPriorToCsr: " << costPriorToCsr; auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "costAfterCsr: " << costAfterCsr; - logs.info() << "deltaCost: " << costAfterCsr - costPriorToCsr; + logs.info() << "[adq-patch] costAfterCsr: " << costAfterCsr; + logs.info() << "[adq-patch] deltaCost: " << costAfterCsr - costPriorToCsr; storeOrDisregardInteriorPointResults( ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); return true; From 8369d658df6fa9c7b85ef7f8d0048e912d1458c5 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 9 Nov 2022 13:10:42 +0100 Subject: [PATCH 362/490] move adqPatchPostProcess after HydroRemix --- src/solver/simulation/economy.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 2c8098f2f0..df60486ec5 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -285,12 +285,12 @@ bool Economy::year(Progression::Task& progression, DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); - adqPatchPostProcess(study, *pProblemesHebdo[numSpace], numSpace); - computingHydroLevels(study, *pProblemesHebdo[numSpace], nbHoursInAWeek, false); RemixHydroForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); + + adqPatchPostProcess(study, *pProblemesHebdo[numSpace], numSpace); computingHydroLevels(study, *pProblemesHebdo[numSpace], nbHoursInAWeek, true); From 4edb924900ad400b99315d315505f57dc01118e2 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 16 Nov 2022 15:14:05 +0100 Subject: [PATCH 363/490] refactor + change - storeOrDisregardInteriorPointResults --- .../adequacy_patch_csr/solve_problem.cpp | 23 +++++++++++++------ 1 file changed, 16 insertions(+), 7 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp index 69cdbcdc1a..c22324b09e 100644 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp @@ -137,12 +137,24 @@ void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* Pro HOURLY_CSR_PROBLEM& hourlyCsrProblem, uint weekNb, int yearNb, - double deltaCost) + double costPriorToCsr, + double costAfterCsr) { const int hoursInWeek = 168; - if (deltaCost <= 0.0) + const bool checkCost + = hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->CheckCsrCostFunctionValue; + double deltaCost = costAfterCsr - costPriorToCsr; + + if (checkCost) + { + logs.info() << "[adq-patch] costPriorToCsr: " << costPriorToCsr + << ", costAfterCsr: " << costAfterCsr + << ", deltaCost: " << costAfterCsr - costPriorToCsr; + } + + if (!checkCost || (checkCost && deltaCost < 0.0)) storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); - else + 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: " @@ -255,17 +267,14 @@ bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, int yearNb) { double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "[adq-patch] costPriorToCsr: " << costPriorToCsr; auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); PI_Quamin(Probleme.get()); // resolution if (Probleme->ExistenceDUneSolution == OUI_PI) { setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - logs.info() << "[adq-patch] costAfterCsr: " << costAfterCsr; - logs.info() << "[adq-patch] deltaCost: " << costAfterCsr - costPriorToCsr; storeOrDisregardInteriorPointResults( - ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costAfterCsr - costPriorToCsr); + ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costPriorToCsr, costAfterCsr); return true; } else From 424b882025d0e2fef655a6df615164dd997cd80c Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 16 Nov 2022 15:14:16 +0100 Subject: [PATCH 364/490] beta 9.1 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 8a9bf54597..5fb05142bd 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,7 +14,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 8) +set(ANTARES_BETA 9.1) set(ANTARES_RC 0) # OR-Tools tag From b386013fa7b24423d47035af9476496812fc40b1 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 17 Nov 2022 11:01:16 +0100 Subject: [PATCH 365/490] refactor solveCSR --- src/solver/simulation/economy.cpp | 8 ++++++-- src/solver/simulation/economy.h | 4 +++- 2 files changed, 9 insertions(+), 3 deletions(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index df60486ec5..d3f98a5780 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -97,8 +97,6 @@ void AdequacyPatchOptimization::solve(Variable::State& state, // part that we need ::SIM_RenseignementProblemeHebdo(*problemeHebdo, state, numSpace, hourInTheYear); OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); - - solveCSR(state, numSpace, w); } // No adequacy patch @@ -108,6 +106,10 @@ void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace, ui auto problemeHebdo = pProblemesHebdo[numSpace]; OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); } +void NoAdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint week) +{ + return; +} Economy::Economy(Data::Study& study) : study(study), preproOnly(false), pProblemesHebdo(nullptr) { @@ -285,6 +287,8 @@ bool Economy::year(Progression::Task& progression, DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); + weeklyOptProblem->solveCSR(state, numSpace, w); + computingHydroLevels(study, *pProblemesHebdo[numSpace], nbHoursInAWeek, false); RemixHydroForAllAreas( diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index 3d3f8b6df3..54557f9b23 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -48,6 +48,7 @@ class EconomyWeeklyOptimization public: using Ptr = std::unique_ptr; virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) = 0; + virtual void solveCSR(const Variable::State& state, uint numSpace, uint week) = 0; void initializeProblemeHebdo(PROBLEME_HEBDO** pProblemesHebdo); static Ptr create(bool adqPatchEnabled); @@ -60,8 +61,8 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization public: AdequacyPatchOptimization(); void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; -private: void solveCSR(const Variable::State& state, uint numSpace, uint week); +private: vector calculateENSoverAllAreasForEachHour(uint numSpace) const; std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) const; std::set getHoursRequiringCurtailmentSharing(uint numSpace) const; @@ -72,6 +73,7 @@ class NoAdequacyPatchOptimization : public EconomyWeeklyOptimization public: NoAdequacyPatchOptimization(); void solve(Variable::State&, int, uint numSpace, uint week) override; + void solveCSR(const Variable::State& state, uint numSpace, uint week); }; class Economy From 87a4e5b798a8862e7a6f8911bde210d0f5779b61 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 17 Nov 2022 16:28:02 +0100 Subject: [PATCH 366/490] add "- dtgMrg" to densNew formula --- src/solver/optimisation/adequacy_patch.cpp | 15 ++++++++++++--- src/solver/optimisation/adequacy_patch.h | 4 +++- src/solver/simulation/economy.cpp | 3 ++- 3 files changed, 17 insertions(+), 5 deletions(-) diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index 8e295374e6..baac7f7aac 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -155,7 +155,9 @@ double LmrViolationAreaHour(PROBLEME_HEBDO* ProblemeHebdo, return 0.0; } -double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo) +double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo, + const Study& study, + uint numSpace) { double netPositionInit; double densNew; @@ -171,14 +173,21 @@ double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo) { std::tie(netPositionInit, densNew, totalNodeBalance) = calculateAreaFlowBalance(ProblemeHebdo, 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)] */ + auto& scratchpad = *(study.areas[Area]->scratchpad[numSpace]); + double dtgMrg = scratchpad.dispatchableGenerationMargin[hour]; + densNew = Math::Max(0.0, densNew - dtgMrg); + // write down densNew values for all the hours ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDENS[hour] = densNew; // copy spilled Energy values into spilled Energy values after CSR ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesSpilledEnergyAfterCSR[hour] = ProblemeHebdo->ResultatsHoraires[Area] ->ValeursHorairesDeDefaillanceNegative[hour]; // check LMR violations - totalLmrViolation += LmrViolationAreaHour( - ProblemeHebdo, totalNodeBalance, Area, hour); + totalLmrViolation + += LmrViolationAreaHour(ProblemeHebdo, totalNodeBalance, Area, hour); } } } diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 9e81ce9af7..45b3b0557c 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -119,7 +119,9 @@ double LmrViolationAreaHour(PROBLEME_HEBDO* ProblemeHebdo, * calculates total LMR violations and LMR violations per area per hour inside * ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] */ -double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo); +double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo, + const Study& study, + uint numSpace); /*! ** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index d3f98a5780..0f929fad7e 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -234,7 +234,8 @@ std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uin void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint w) { auto problemeHebdo = pProblemesHebdo[numSpace]; - double totalLmrViolation = calculateDensNewAndTotalLmrViolation(problemeHebdo); + double totalLmrViolation + = calculateDensNewAndTotalLmrViolation(problemeHebdo, state.study, numSpace); logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 << ".Total LMR violation:" << totalLmrViolation; const std::set hoursRequiringCurtailmentSharing From 8a8ab743ee9c2e325e935df08d9f1d78f0a890f3 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 17 Nov 2022 16:28:08 +0100 Subject: [PATCH 367/490] beta 10 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 5fb05142bd..78aed23c07 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,7 +14,7 @@ set(ANTARES_WEBSITE "https://antares.rte-france.com") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 9.1) +set(ANTARES_BETA 10) set(ANTARES_RC 0) # OR-Tools tag From 2ea5968ab8e66fc2634019e306ca0c30c4b40e20 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 21 Nov 2022 15:27:36 +0100 Subject: [PATCH 368/490] fix error --- src/solver/simulation/economy.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index f3ac3fe1a9..74e14fcc69 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -67,7 +67,7 @@ EconomyWeeklyOptimization::Ptr EconomyWeeklyOptimization::create(bool adqPatchEn return nullptr; } -/ Adequacy patch +// Adequacy patch AdequacyPatchOptimization::AdequacyPatchOptimization(PROBLEME_HEBDO** problemesHebdo) : EconomyWeeklyOptimization(problemesHebdo) { From 1b7fc2f4b3c055096cb7ab0af7ef9d9c57fa6453 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 22 Nov 2022 12:31:40 +0100 Subject: [PATCH 369/490] update 13-file-format.md for adq-patch CSR --- docs/reference-guide/13-file-format.md | 13 +++++++++++++ 1 file changed, 13 insertions(+) diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md index 68f96e6673..4ace7765b6 100644 --- a/docs/reference-guide/13-file-format.md +++ b/docs/reference-guide/13-file-format.md @@ -20,10 +20,23 @@ In existing section `optimization`, remove property `include-split-exported-mps` #### 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. +In file **settings/generaldata.ini**, in section `adequacy patch`, add properties + +* `price-taking-order` [Enum[isDens = 0, isLoad = 1]]. Default value = `isDens` +* `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 #### 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. +* 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.3.2 ### Writing MPS files MPS files of first optimization used to be overwritten by MPS files of second optimization. Not anymore. From 728163e469b7e58c38c285a08f2086b8dcaa3013 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 22 Nov 2022 15:53:38 +0100 Subject: [PATCH 370/490] update 14-adequacy-patch.md for adq-patch CSR --- docs/reference-guide/14-adequacy-patch.md | 183 +++++++++++++++++++++- 1 file changed, 180 insertions(+), 3 deletions(-) diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md index 35f587e823..2731500e3e 100644 --- a/docs/reference-guide/14-adequacy-patch.md +++ b/docs/reference-guide/14-adequacy-patch.md @@ -9,7 +9,7 @@ It should be noted that, in the current implementation of the patch within Antar 1. Local matching constraint. -2. The implemented solution does not yet consider secondary problem of sharing of curtailment by the quadratic term. +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. @@ -53,8 +53,185 @@ Once the first iteration is completed, we have access to the DENS value, which r 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 <= DENS +- ENS ≤ DENS (for all physical areas inside the adequacy patch). ## Curtailment sharing rule -The curtailment sharing rule will be implemented in Antares Simulator 8.4. It will include an hourly post-processing phase. + +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 or Draft 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) = ∑ 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) = ∑ flow_direct (node 2 upstream -> node A) + ∑ flow_indirect (node A <- node 2 downstream) - ∑ flow_indirect (node 2 upstream <- node A) - ∑ 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) + ∑ 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”: + + - ∑ flows (node 1 -> node A) = ∑ flow_direct (node 1 upstream -> node A) + ∑ 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) ≤ DENS_new(node A) + +- **Positivity constraints:** + + - ENS (node A) ≥ 0 + - spillage (node A) ≥ 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 ∑(ENS/PTO)$^2$ 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$ ≤ ENS (node A) ≤ DENS_new (node A) + 10$^-$$^m$ + - -10$^-$$^m$ ≤ spillage (node A) ≤ + infinity + Where _m_ is an integer defined by the user. + +### Objective function + +- Minimize [∑(ENS/PTO)$^2$ + ∑(hurdle_cost_direct x flow_direct) + ∑(hurdle_cost_indirect x flow_indirect)] + +The 2 latest terms are introduced to minimize loop flows in the considering domain. +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$ = [∑(ENS_init/PTO)$^2$ + ∑(hurdle_cost_direct x flow_direct_init) + ∑(hurdle_cost_indirect x flow_indirect_init)] +- QUAD$_1$ = [∑(ENS_final/PTO)$^2$ + ∑(hurdle_cost_direct x flow_direct_final) + ∑(hurdle_cost_indirect x flow_indirect_final)] + +If: + +- QUAD$_0$ ≤ 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) + ∑ flows (node 1 -> node A) < 0;_ + - _Abs[net_position_init (node A) + ∑ 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 (∑ flows (node 1 -> node A)) is optional._ + + From 2b14a8e92a526174396c25bbbfb8dfb129207f8d Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 1 Dec 2022 11:05:01 +0100 Subject: [PATCH 371/490] change CSR objective function (Elia) --- .../adequacy_patch_csr/set_problem_cost_function.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 e86d899dc3..80b930d3c2 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 @@ -51,7 +51,7 @@ double calculateQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, int hour, int area) if (priceTakingOrders <= 0.0) return 0.0; else - return (1 / (priceTakingOrders * priceTakingOrders)); + return (1 / priceTakingOrders); } void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) From 95aefb14bca59142d8cc37e1dcb74045ee5418dc Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 1 Dec 2022 11:05:21 +0100 Subject: [PATCH 372/490] change CSR objective function (Elia) - doc update --- docs/reference-guide/14-adequacy-patch.md | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md index 2731500e3e..04098c62ba 100644 --- a/docs/reference-guide/14-adequacy-patch.md +++ b/docs/reference-guide/14-adequacy-patch.md @@ -189,13 +189,13 @@ _**Notes**_ ### Objective function -- Minimize [∑(ENS/PTO)$^2$ + ∑(hurdle_cost_direct x flow_direct) + ∑(hurdle_cost_indirect x flow_indirect)] +- Minimize [∑(ENS$^2$/PTO) + ∑(hurdle_cost_direct x flow_direct) + ∑(hurdle_cost_indirect x flow_indirect)] The 2 latest terms are introduced to minimize loop flows in the considering domain. 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$ = [∑(ENS_init/PTO)$^2$ + ∑(hurdle_cost_direct x flow_direct_init) + ∑(hurdle_cost_indirect x flow_indirect_init)] -- QUAD$_1$ = [∑(ENS_final/PTO)$^2$ + ∑(hurdle_cost_direct x flow_direct_final) + ∑(hurdle_cost_indirect x flow_indirect_final)] +- QUAD$_0$ = [∑(ENS_init$^2$/PTO) + ∑(hurdle_cost_direct x flow_direct_init) + ∑(hurdle_cost_indirect x flow_indirect_init)] +- QUAD$_1$ = [∑(ENS_final$^2$/PTO) + ∑(hurdle_cost_direct x flow_direct_final) + ∑(hurdle_cost_indirect x flow_indirect_final)] If: From 12323a838facc46d34d401441fe53d7d4dd63511 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 1 Dec 2022 16:13:52 +0100 Subject: [PATCH 373/490] beta11 --- src/CMakeLists.txt | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index e5c2dd5106..3ca3fdb047 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,7 +14,7 @@ set(ANTARES_WEBSITE "https://antares-simulator.org/") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 10) +set(ANTARES_BETA 11) set(ANTARES_RC 0) # OR-Tools tag From ca162fad534a029dc70bc0c281aa5b8051095ebb Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 1 Dec 2022 16:19:23 +0100 Subject: [PATCH 374/490] change CSR objective function (Elia) - doc update --- docs/reference-guide/14-adequacy-patch.md | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md index 04098c62ba..3bc4954470 100644 --- a/docs/reference-guide/14-adequacy-patch.md +++ b/docs/reference-guide/14-adequacy-patch.md @@ -172,7 +172,7 @@ _**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 ∑(ENS/PTO)$^2$ and such objective is not exactly equivalent than minimizing Total ENS._ + - _The curtailment sharing rule target is to minimize ∑(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:_ From 39300231dbeec427af2005bf9973130abc8e1b68 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 5 Dec 2022 17:09:55 +0100 Subject: [PATCH 375/490] 14-adq-patch-doc-bug fix (unrecognized characters) --- docs/reference-guide/14-adequacy-patch.md | 14 +++++++------- 1 file changed, 7 insertions(+), 7 deletions(-) diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md index 3bc4954470..330318272f 100644 --- a/docs/reference-guide/14-adequacy-patch.md +++ b/docs/reference-guide/14-adequacy-patch.md @@ -53,7 +53,7 @@ Once the first iteration is completed, we have access to the DENS value, which r 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 ≤ DENS +- ENS <= DENS (for all physical areas inside the adequacy patch). ## Curtailment sharing rule @@ -160,12 +160,12 @@ The value of “net_position (node A)” is deduced from “flow” variable as - **Constraint induced by Local matching rule:** - - ENS (node A) ≤ DENS_new(node A) + - ENS (node A) <= DENS_new(node A) - **Positivity constraints:** - - ENS (node A) ≥ 0 - - spillage (node A) ≥ 0 + - ENS (node A) >= 0 + - spillage (node A) >= 0 _**Notes**_ @@ -183,8 +183,8 @@ _**Notes**_ - _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$ ≤ ENS (node A) ≤ DENS_new (node A) + 10$^-$$^m$ - - -10$^-$$^m$ ≤ spillage (node A) ≤ + infinity + - -10$^-$$^m$ <= ENS (node A) <= DENS_new (node A) + 10$^-$$^m$ + - -10$^-$$^m$ <= spillage (node A) <= + infinity Where _m_ is an integer defined by the user. ### Objective function @@ -199,7 +199,7 @@ In order to assess the quality of the CSR solution additional verification can b If: -- QUAD$_0$ ≤ QUAD$_1$ +- QUAD$_0$ <= 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. From ec1ab89a3a322948dde9d62802afc2984108ee80 Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 6 Dec 2022 10:49:12 +0100 Subject: [PATCH 376/490] 14-adq-patch-doc-bug fix (unrecognized characters)-2 --- docs/reference-guide/14-adequacy-patch.md | 36 +++++++++++------------ 1 file changed, 18 insertions(+), 18 deletions(-) diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md index 330318272f..22ae1e15b5 100644 --- a/docs/reference-guide/14-adequacy-patch.md +++ b/docs/reference-guide/14-adequacy-patch.md @@ -53,7 +53,7 @@ Once the first iteration is completed, we have access to the DENS value, which r 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 <= DENS +- ENS $\le$ DENS (for all physical areas inside the adequacy patch). ## Curtailment sharing rule @@ -122,14 +122,14 @@ These variables should have exactly the same constraints than the ones considere - **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) = ∑ algebraic “Flows” over links involving node A + - 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) = ∑ flow_direct (node 2 upstream -> node A) + ∑ flow_indirect (node A <- node 2 downstream) - ∑ flow_indirect (node 2 upstream <- node A) - ∑ flow_direct (node A -> node 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: @@ -141,11 +141,11 @@ The value of “net_position (node A)” is deduced from “flow” variable as 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) + ∑ flows (node 1 -> node A) - DTG.MRG (node A)] + - 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”: - - ∑ flows (node 1 -> node A) = ∑ flow_direct (node 1 upstream -> node A) + ∑ flow_indirect (node A <- node 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 @@ -160,19 +160,19 @@ The value of “net_position (node A)” is deduced from “flow” variable as - **Constraint induced by Local matching rule:** - - ENS (node A) <= DENS_new(node A) + - ENS (node A) $\le$ DENS_new(node A) - **Positivity constraints:** - - ENS (node A) >= 0 - - spillage (node A) >= 0 + - 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 ∑(ENS$^2$/PTO) and such objective is not exactly equivalent than minimizing Total ENS._ + - _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:_ @@ -183,23 +183,23 @@ _**Notes**_ - _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$ <= ENS (node A) <= DENS_new (node A) + 10$^-$$^m$ - - -10$^-$$^m$ <= spillage (node A) <= + infinity + - -10$^-$$^m$ $\le$ ENS (node A) $\le$ DENS_new (node A) + 10$^-$$^m$ + - -10$^-$$^m$ $\le$ spillage (node A) $\le$ + infinity Where _m_ is an integer defined by the user. ### Objective function -- Minimize [∑(ENS$^2$/PTO) + ∑(hurdle_cost_direct x flow_direct) + ∑(hurdle_cost_indirect x flow_indirect)] +- Minimize [$\sum$(ENS$^2$/PTO) + $\sum$(hurdle_cost_direct x flow_direct) + $\sum$(hurdle_cost_indirect x flow_indirect)] The 2 latest terms are introduced to minimize loop flows in the considering domain. 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$ = [∑(ENS_init$^2$/PTO) + ∑(hurdle_cost_direct x flow_direct_init) + ∑(hurdle_cost_indirect x flow_indirect_init)] -- QUAD$_1$ = [∑(ENS_final$^2$/PTO) + ∑(hurdle_cost_direct x flow_direct_final) + ∑(hurdle_cost_indirect x flow_indirect_final)] +- QUAD$_0$ = [$\sum$(ENS_init$^2$/PTO) + $\sum$(hurdle_cost_direct x flow_direct_init) + $\sum$(hurdle_cost_indirect x flow_indirect_init)] +- QUAD$_1$ = [$\sum$(ENS_final$^2$/PTO) + $\sum$(hurdle_cost_direct x flow_direct_final) + $\sum$(hurdle_cost_indirect x flow_indirect_final)] If: -- QUAD$_0$ <= QUAD$_1$ +- 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. @@ -229,9 +229,9 @@ _**Notes**_ 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) + ∑ flows (node 1 -> node A) < 0;_ - - _Abs[net_position_init (node A) + ∑ flows (node 1 -> node A)] > ENS_init (node A) + GUI_defined_threshold._ + - _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 (∑ flows (node 1 -> node A)) is optional._ + _Second equation is satisfied if the area is exporting power. Depending on the GUI option member ($\sum$ flows (node 1 -> node A)) is optional._ From 3b927bd8e058b117580fe8843ea52ac2f4a47c91 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 7 Dec 2022 18:17:53 +0100 Subject: [PATCH 377/490] Revert "Merge branch 'feature/adq-patch-sequel' into develop" This reverts commit 84984f5587897501eea6aa504bc96aaaef427442, reversing changes made to 88e213865b55fc0bd231c8424d4b1dff7b602e62. --- docs/reference-guide/03-commands.md | 18 +- docs/reference-guide/13-file-format.md | 13 - docs/reference-guide/14-adequacy-patch.md | 183 +---- src/CMakeLists.txt | 4 +- src/libs/antares/study/fwd.h | 15 +- src/libs/antares/study/parameters.cpp | 83 +-- src/libs/antares/study/parameters.h | 22 - src/solver/cmake/solver.cmake | 6 - src/solver/cmake/variable.cmake | 3 - src/solver/optimisation/adequacy_patch.cpp | 341 ++-------- src/solver/optimisation/adequacy_patch.h | 172 ++--- .../construct_problem_constraints_LHS.cpp | 305 --------- .../construct_problem_constraints_RHS.cpp | 189 ------ .../construct_problem_variables.cpp | 164 ----- .../set_problem_cost_function.cpp | 161 ----- .../set_variable_boundaries.cpp | 230 ------- .../adequacy_patch_csr/solve_problem.cpp | 285 -------- .../opt_appel_solveur_quadratique.cpp | 2 +- ...atrice_des_contraintes_cas_quadratique.cpp | 4 +- ...ction_variables_optimisees_quadratique.cpp | 2 +- src/solver/optimisation/opt_fonctions.h | 6 - .../opt_gestion_des_bornes_cas_lineaire.cpp | 16 +- ...opt_gestion_des_bornes_cas_quadratique.cpp | 2 +- .../opt_gestion_des_couts_cas_quadratique.cpp | 2 +- ..._gestion_second_membre_cas_quadratique.cpp | 2 +- src/solver/simulation/economy.cpp | 77 +-- src/solver/simulation/economy.h | 14 +- .../simulation/sim_alloc_probleme_hebdo.cpp | 9 - .../simulation/sim_calcul_economique.cpp | 13 +- .../sim_structure_probleme_economique.h | 57 +- src/solver/variable/economy/all.h | 79 +-- .../variable/economy/dtgMarginAfterCsr.h | 288 -------- .../economy/localMatchingRuleViolations.h | 274 -------- .../variable/economy/spilledEnergyAfterCSR.h | 289 -------- .../solver/optimisation/adequacy_patch.cpp | 347 +--------- .../simulator/application/main/internal-ids.h | 3 - src/ui/simulator/application/main/main.cpp | 5 - src/ui/simulator/application/main/main.h | 6 - src/ui/simulator/application/main/menu.cpp | 17 - src/ui/simulator/application/main/options.cpp | 16 - src/ui/simulator/cmake/components.cmake | 2 - src/ui/simulator/cmake/windows-options.cmake | 4 - .../components/datagrid/gridhelper.cpp | 20 - .../toolbox/components/datagrid/renderer.h | 4 - .../renderer/adequacy-patch-area-grid.cpp | 138 ---- .../renderer/adequacy-patch-area-grid.h | 62 -- .../adequacy-patch/adequacy-patch-areas.cpp | 114 ---- .../adequacy-patch/adequacy-patch-areas.h | 38 -- .../adequacy-patch/adequacy-patch-options.cpp | 637 ------------------ .../adequacy-patch/adequacy-patch-options.h | 103 --- .../options/optimization/optimization.cpp | 124 +++- .../options/optimization/optimization.h | 6 +- 52 files changed, 320 insertions(+), 4656 deletions(-) delete mode 100644 src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp delete mode 100644 src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp delete mode 100644 src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp delete mode 100644 src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp delete mode 100644 src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp delete mode 100644 src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp delete mode 100644 src/solver/variable/economy/dtgMarginAfterCsr.h delete mode 100644 src/solver/variable/economy/localMatchingRuleViolations.h delete mode 100644 src/solver/variable/economy/spilledEnergyAfterCSR.h delete mode 100644 src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp delete mode 100644 src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h delete mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp delete mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h delete mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp delete mode 100644 src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h diff --git a/docs/reference-guide/03-commands.md b/docs/reference-guide/03-commands.md index 3993289ab8..fcff4f2915 100644 --- a/docs/reference-guide/03-commands.md +++ b/docs/reference-guide/03-commands.md @@ -211,21 +211,9 @@ given back their regular capacities (infinite for those being set on "set to inf - _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 SCR cost function value prior and after CSR (false / true)_ -- _Thresholds:_ -- _Initiate curtailment sharing rule_ -- _Display local maching rule violations_ -- _Relax CSR variable boundaries_ + - _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)_ - **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. diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md index 4ace7765b6..68f96e6673 100644 --- a/docs/reference-guide/13-file-format.md +++ b/docs/reference-guide/13-file-format.md @@ -20,23 +20,10 @@ In existing section `optimization`, remove property `include-split-exported-mps` #### 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. -In file **settings/generaldata.ini**, in section `adequacy patch`, add properties - -* `price-taking-order` [Enum[isDens = 0, isLoad = 1]]. Default value = `isDens` -* `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 #### 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. -* 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.3.2 ### Writing MPS files MPS files of first optimization used to be overwritten by MPS files of second optimization. Not anymore. diff --git a/docs/reference-guide/14-adequacy-patch.md b/docs/reference-guide/14-adequacy-patch.md index 22ae1e15b5..35f587e823 100644 --- a/docs/reference-guide/14-adequacy-patch.md +++ b/docs/reference-guide/14-adequacy-patch.md @@ -9,7 +9,7 @@ It should be noted that, in the current implementation of the patch within Antar 1. Local matching constraint. -2. Secondary problem of sharing of curtailment by the quadratic term. +2. The implemented solution does not yet consider 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. @@ -53,185 +53,8 @@ Once the first iteration is completed, we have access to the DENS value, which r 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 +- ENS <= DENS (for all physical areas inside the adequacy patch). ## Curtailment sharing rule - -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 or Draft 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$ + infinity - Where _m_ is an integer defined by the user. - -### Objective function - -- Minimize [$\sum$(ENS$^2$/PTO) + $\sum$(hurdle_cost_direct x flow_direct) + $\sum$(hurdle_cost_indirect x flow_indirect)] - -The 2 latest terms are introduced to minimize loop flows in the considering domain. -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$ = [$\sum$(ENS_init$^2$/PTO) + $\sum$(hurdle_cost_direct x flow_direct_init) + $\sum$(hurdle_cost_indirect x flow_indirect_init)] -- QUAD$_1$ = [$\sum$(ENS_final$^2$/PTO) + $\sum$(hurdle_cost_direct x flow_direct_final) + $\sum$(hurdle_cost_indirect x flow_indirect_final)] - -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._ - - +The curtailment sharing rule will be implemented in Antares Simulator 8.4. It will include an hourly post-processing phase. diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 94bdf773ab..a26042cb7c 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -14,8 +14,8 @@ set(ANTARES_WEBSITE "https://antares-simulator.org/") set(ANTARES_ONLINE_DOC "https://antares-simulator.readthedocs.io/") # Beta release -set(ANTARES_BETA 11) -set(ANTARES_RC 0) +set(ANTARES_BETA 0) +set(ANTARES_RC 3) # OR-Tools tag file(READ "../ortools_tag" ORTOOLS_TAG) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 3872acfc64..13393c5bf7 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -614,7 +614,7 @@ enum AdequacyPatchMode /*! ** \brief Setting Link Capacity (NTC) for Adequacy patch first step */ -enum ntcSetToZeroStatus_AdqPatchStep1 +enum LinkCapacityForAdequacyPatchFirstStep { //! Leave NTC local values leaveLocalValues = 0, @@ -626,19 +626,6 @@ enum ntcSetToZeroStatus_AdqPatchStep1 setExtremityOrigineToZero }; // enum NTC - -/*! -** \brief Types of Price Taking Order (PTO) for Adequacy Patch -*/ -enum class AdqPatchPTO -{ - //! PTO is DENS - isDens = 0, - //! PTO is Load - isLoad - -}; // enum AdqPatchPTO - } // namespace AdequacyPatch } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/parameters.cpp b/src/libs/antares/study/parameters.cpp index 25acd4f5f0..0e144935d3 100644 --- a/src/libs/antares/study/parameters.cpp +++ b/src/libs/antares/study/parameters.cpp @@ -39,7 +39,6 @@ #include #include #include "../solver/variable/economy/all.h" -#include "../solver/optimisation/adequacy_patch.h" #include #include @@ -209,39 +208,6 @@ const char* StudyModeToCString(StudyMode mode) } return "Unknown"; } -bool StringToPriceTakingOrder(const AnyString& text, AdequacyPatch::AdqPatchPTO& out) -{ - CString<24, false> s = text; - s.trim(); - s.toLower(); - if (s == "dens") - { - out = AdequacyPatch::AdqPatchPTO::isDens; - return true; - } - if (s == "load") - { - out = AdequacyPatch::AdqPatchPTO::isLoad; - return true; - } - - logs.warning() << "parameters: invalid price taking order. Got '" << text << "'"; - - return false; -} - -const char* PriceTakingOrderToString(AdequacyPatch::AdqPatchPTO pto) -{ - switch (pto) - { - case AdequacyPatch::AdqPatchPTO::isDens: - return "DENS"; - case AdequacyPatch::AdqPatchPTO::isLoad: - return "Load"; - default: - return ""; - } -} Parameters::Parameters() : yearsFilter(nullptr), noOutput(false) { @@ -266,26 +232,12 @@ void Parameters::resetSeeds() for (auto i = (uint)seedTsGenLoad; i != seedMax; ++i) seed[i] = (s += increment); } -void Parameters::resetThresholdsAdqPatch() -{ - // Initialize all thresholds values for adequacy patch - adqPatch.curtailmentSharing.thresholdInitiate - = defaultValueThresholdInitiateCurtailmentSharingRule; - adqPatch.curtailmentSharing.thresholdDisplayViolations - = defaultValueThresholdDisplayLocalMatchingRuleViolations; - adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation - = defaultValueThresholdVarBoundsRelaxation; -} void Parameters::resetAdqPatchParameters() { adqPatch.enabled = false; adqPatch.localMatching.setToZeroOutsideInsideLinks = true; adqPatch.localMatching.setToZeroOutsideOutsideLinks = true; - adqPatch.curtailmentSharing.priceTakingOrder = Data::AdequacyPatch::AdqPatchPTO::isDens; - adqPatch.curtailmentSharing.includeHurdleCost = false; - adqPatch.curtailmentSharing.checkCsrCostFunction = false; - resetThresholdsAdqPatch(); } void Parameters::reset() @@ -720,22 +672,6 @@ static bool SGDIntLoadFamily_AdqPatch(Parameters& d, return value.to(d.adqPatch.localMatching.setToZeroOutsideInsideLinks); if (key == "set-to-null-ntc-between-physical-out-for-first-step") return value.to(d.adqPatch.localMatching.setToZeroOutsideOutsideLinks); - // Price taking order - if (key == "price-taking-order") - return StringToPriceTakingOrder(value, d.adqPatch.curtailmentSharing.priceTakingOrder); - // Include Hurdle Cost - if (key == "include-hurdle-cost-csr") - return value.to(d.adqPatch.curtailmentSharing.includeHurdleCost); - // Check CSR cost function prior and after CSR - if (key == "check-csr-cost-function") - return value.to(d.adqPatch.curtailmentSharing.checkCsrCostFunction); - // Thresholds - if (key == "threshold-initiate-curtailment-sharing-rule") - return value.to(d.adqPatch.curtailmentSharing.thresholdInitiate); - if (key == "threshold-display-local-matching-rule-violations") - return value.to(d.adqPatch.curtailmentSharing.thresholdDisplayViolations); - if (key == "threshold-csr-variable-bounds-relaxation") - return value.to(d.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); return false; } @@ -1825,19 +1761,7 @@ void Parameters::saveToINI(IniFile& ini) const adqPatch.localMatching.setToZeroOutsideInsideLinks); section->add("set-to-null-ntc-between-physical-out-for-first-step", adqPatch.localMatching.setToZeroOutsideOutsideLinks); - section->add("price-taking-order", - PriceTakingOrderToString(adqPatch.curtailmentSharing.priceTakingOrder)); - section->add("include-hurdle-cost-csr", adqPatch.curtailmentSharing.includeHurdleCost); - section->add("check-csr-cost-function", adqPatch.curtailmentSharing.checkCsrCostFunction); - // Threshholds - section->add("threshold-initiate-curtailment-sharing-rule", - adqPatch.curtailmentSharing.thresholdInitiate); - section->add("threshold-display-local-matching-rule-violations", - adqPatch.curtailmentSharing.thresholdDisplayViolations); - section->add("threshold-csr-variable-bounds-relaxation", - adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); } - // Other preferences { auto* section = ini.addSection("other preferences"); @@ -2016,12 +1940,7 @@ void Parameters::RenewableGeneration::addExcludedVariables(std::vector& out) const { if (!enabled) - { - out.emplace_back("DENS"); - out.emplace_back("LMR VIOL."); - out.emplace_back("SPIL. ENRG. CSR"); - out.emplace_back("DTG MRG CSR"); - } + out.emplace_back("dens"); } bool Parameters::haveToImport(int tsKind) const diff --git a/src/libs/antares/study/parameters.h b/src/libs/antares/study/parameters.h index 89cc491664..e731bc362e 100644 --- a/src/libs/antares/study/parameters.h +++ b/src/libs/antares/study/parameters.h @@ -137,10 +137,6 @@ class Parameters final */ void resetSeeds(); /*! - ** \brief Reset to default all threshold values in adequacy patch - */ - void resetThresholdsAdqPatch(); - /*! ** \brief Reset to default all adequacy patch values */ void resetAdqPatchParameters(); @@ -515,24 +511,6 @@ class Parameters final }; bool enabled; LocalMatching localMatching; - - struct CurtailmentSharing - { - //! PTO (Price Taking Order) for adequacy patch. User can choose between DENS and Load. - Data::AdequacyPatch::AdqPatchPTO priceTakingOrder; - //! Threshold to initiate curtailment sharing rule - double thresholdInitiate; - //! Threshold to display Local Matching Rule violations - double thresholdDisplayViolations; - //! CSR Variables relaxation threshold - int thresholdVarBoundsRelaxation; - //! Include hurdle cost in CSR cost function - bool includeHurdleCost; - //! Check CSR cost function prior & after CSR optimization - bool checkCsrCostFunction; - }; - CurtailmentSharing curtailmentSharing; - void addExcludedVariables(std::vector&) const; }; diff --git a/src/solver/cmake/solver.cmake b/src/solver/cmake/solver.cmake index a07183c053..8df68d57d1 100644 --- a/src/solver/cmake/solver.cmake +++ b/src/solver/cmake/solver.cmake @@ -53,12 +53,6 @@ set(RTESOLVER_OPT optimisation/opt_export_structure.cpp optimisation/adequacy_patch.h optimisation/adequacy_patch.cpp - optimisation/adequacy_patch_csr/solve_problem.cpp - optimisation/adequacy_patch_csr/set_variable_boundaries.cpp - optimisation/adequacy_patch_csr/set_problem_cost_function.cpp - optimisation/adequacy_patch_csr/construct_problem_variables.cpp - optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp - optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp utils/ortools_utils.h utils/ortools_utils.cpp diff --git a/src/solver/cmake/variable.cmake b/src/solver/cmake/variable.cmake index 189782ae3c..b4cf1e5d89 100644 --- a/src/solver/cmake/variable.cmake +++ b/src/solver/cmake/variable.cmake @@ -134,9 +134,6 @@ set(SRC_VARIABLE_ECONOMY variable/economy/hydroCost.h variable/economy/unsupliedEnergy.h variable/economy/domesticUnsuppliedEnergy.h - variable/economy/localMatchingRuleViolations.h - variable/economy/spilledEnergyAfterCSR.h - variable/economy/dtgMarginAfterCsr.h variable/economy/spilledEnergy.h variable/economy/dispatchableGeneration.h variable/economy/productionByDispatchablePlant.h diff --git a/src/solver/optimisation/adequacy_patch.cpp b/src/solver/optimisation/adequacy_patch.cpp index baac7f7aac..30cbeff5da 100644 --- a/src/solver/optimisation/adequacy_patch.cpp +++ b/src/solver/optimisation/adequacy_patch.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** @@ -26,13 +26,7 @@ */ #include "../simulation/simulation.h" -#include "opt_fonctions.h" #include "adequacy_patch.h" -#include -#include "../simulation/sim_structure_probleme_economique.h" -#include "../study/area/scratchpad.h" - -using namespace Yuni; namespace Antares { @@ -40,32 +34,27 @@ namespace Data { namespace AdequacyPatch { -ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco) +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) { - AdequacyPatchMode OriginNodeAdequacyPatchType - = ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco]; - AdequacyPatchMode ExtremityNodeAdequacyPatchType - = ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco]; - bool setToZeroNTCfromOutToIn_AdqPatch - = ProblemeHebdo->adqPatchParams->SetNTCOutsideToInsideToZero; - bool setToZeroNTCfromOutToOut_AdqPatch - = ProblemeHebdo->adqPatchParams->SetNTCOutsideToOutsideToZero; - switch (OriginNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: return SetNTCForAdequacyFirstStepOriginNodeInsideAdq(ExtremityNodeAdequacyPatchType); case physicalAreaOutsideAdqPatch: - return getNTCtoZeroStatusOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, - setToZeroNTCfromOutToIn_AdqPatch, - setToZeroNTCfromOutToOut_AdqPatch); + return SetNTCForAdequacyFirstStepOriginNodeOutsideAdq(ExtremityNodeAdequacyPatchType, + SetToZero12LinksForAdequacyPatch, + SetToZero11LinksForAdequacyPatch); default: return leaveLocalValues; } } -ntcSetToZeroStatus_AdqPatchStep1 SetNTCForAdequacyFirstStepOriginNodeInsideAdq( +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType) { switch (ExtremityNodeAdequacyPatchType) @@ -78,300 +67,72 @@ ntcSetToZeroStatus_AdqPatchStep1 SetNTCForAdequacyFirstStepOriginNodeInsideAdq( } } -ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( +LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool setToZeroNTCfromOutToIn_AdqPatch, - bool setToZeroNTCfromOutToOut_AdqPatch) + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch) { switch (ExtremityNodeAdequacyPatchType) { case physicalAreaInsideAdqPatch: - return setToZeroNTCfromOutToIn_AdqPatch ? setToZero : setExtremityOrigineToZero; + return SetToZero12LinksForAdequacyPatch ? setToZero : setExtremityOrigineToZero; case physicalAreaOutsideAdqPatch: - return setToZeroNTCfromOutToOut_AdqPatch ? setToZero : leaveLocalValues; + return SetToZero11LinksForAdequacyPatch ? setToZero : leaveLocalValues; default: return leaveLocalValues; } } -void setNTCbounds(double& Xmax, - double& Xmin, - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, - const int Interco, - PROBLEME_HEBDO* ProblemeHebdo) +void setBoundsAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo) { - ntcSetToZeroStatus_AdqPatchStep1 ntcToZeroStatusForAdqPatch; + LinkCapacityForAdequacyPatchFirstStep SetToZeroLinkNTCForAdequacyPatchFirstStep; - // set as default values - Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + SetToZeroLinkNTCForAdequacyPatchFirstStep = SetNTCForAdequacyFirstStep( + ProblemeHebdo->adequacyPatchRuntimeData.originAreaType[Interco], + ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaType[Interco], + ProblemeHebdo->adqPatchParams->SetNTCOutsideToInsideToZero, + ProblemeHebdo->adqPatchParams->SetNTCOutsideToOutsideToZero); - // set for adq patch first step - if (ProblemeHebdo->adqPatchParams && ProblemeHebdo->adqPatchParams->AdequacyFirstStep) + switch (SetToZeroLinkNTCForAdequacyPatchFirstStep) { - ntcToZeroStatusForAdqPatch = getNTCtoZeroStatus(ProblemeHebdo, Interco); - - switch (ntcToZeroStatusForAdqPatch) - { - case setToZero: - { - Xmax = 0.; - Xmin = 0.; - break; - } - case setOrigineExtremityToZero: - { - Xmax = 0.; - Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); - break; - } - case setExtremityOrigineToZero: - { - Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; - Xmin = 0.; - break; - } - } - } -} - -double LmrViolationAreaHour(PROBLEME_HEBDO* ProblemeHebdo, - double totalNodeBalance, - int Area, - int hour) -{ - double ensInit - = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; - double threshold = ProblemeHebdo->adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations; - - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 0; - // check LMR violations - if ((ensInit > 0.0) && (totalNodeBalance < 0.0) - && (Math::Abs(totalNodeBalance) > ensInit + Math::Abs(threshold))) + case setToZero: { - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesLmrViolations[hour] = 1; - return Math::Abs(totalNodeBalance); + Xmax = 0.; + Xmin = 0.; + break; } - return 0.0; -} - -double calculateDensNewAndTotalLmrViolation(PROBLEME_HEBDO* ProblemeHebdo, - const Study& study, - uint numSpace) -{ - double netPositionInit; - double densNew; - double totalNodeBalance; - double totalLmrViolation = 0.0; - const int numOfHoursInWeek = 168; - - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) + case setOrigineExtremityToZero: { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) - { - for (int hour = 0; hour < numOfHoursInWeek; hour++) - { - std::tie(netPositionInit, densNew, totalNodeBalance) - = calculateAreaFlowBalance(ProblemeHebdo, 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)] */ - auto& scratchpad = *(study.areas[Area]->scratchpad[numSpace]); - double dtgMrg = scratchpad.dispatchableGenerationMargin[hour]; - densNew = Math::Max(0.0, densNew - dtgMrg); - // write down densNew values for all the hours - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDENS[hour] = densNew; - // copy spilled Energy values into spilled Energy values after CSR - ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesSpilledEnergyAfterCSR[hour] - = ProblemeHebdo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillanceNegative[hour]; - // check LMR violations - totalLmrViolation - += LmrViolationAreaHour(ProblemeHebdo, totalNodeBalance, Area, hour); - } - } + Xmax = 0.; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); + break; } - return totalLmrViolation; -} - -std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, - int Area, - int hour) -{ - int Interco; - double netPositionInit = 0; - double flowsNode1toNodeA = 0; - double ensInit; - double densNew; - bool includeFlowsOutsideAdqPatchToDensNew - = !ProblemeHebdo->adqPatchParams->SetNTCOutsideToInsideToZero; - - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == physicalAreaInsideAdqPatch) - { - netPositionInit -= ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == physicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA - -= Math::Min(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoOrigine[Interco]; - } - Interco = ProblemeHebdo->IndexDebutIntercoExtremite[Area]; - while (Interco >= 0) + case setExtremityOrigineToZero: { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == physicalAreaInsideAdqPatch) - { - netPositionInit += ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - } - else if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == physicalAreaOutsideAdqPatch) - { - flowsNode1toNodeA - += Math::Max(0.0, ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]); - } - Interco = ProblemeHebdo->IndexSuivantIntercoExtremite[Interco]; + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = 0.; + break; } - - ensInit = ProblemeHebdo->ResultatsHoraires[Area]->ValeursHorairesDeDefaillancePositive[hour]; - if (includeFlowsOutsideAdqPatchToDensNew) + default: { - densNew = Math::Max(0.0, ensInit + netPositionInit + flowsNode1toNodeA); - return std::make_tuple(netPositionInit, densNew, netPositionInit + flowsNode1toNodeA); + setBoundsNoAdqPatch(Xmax, Xmin, ValeursDeNTC, Interco); + break; } - else - { - densNew = Math::Max(0.0, ensInit + netPositionInit); - return std::make_tuple(netPositionInit, densNew, netPositionInit); } } -void addArray(std::vector& A, const double* B) -{ - for (uint i = 0; i < A.size(); ++i) - A[i] += B[i]; -} - -void adqPatchPostProcess(const Data::Study& study, PROBLEME_HEBDO& problem, int numSpace) +void setBoundsNoAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco) { - if (!study.parameters.adqPatch.enabled) - return; - - const int numOfHoursInWeek = 168; - for (int Area = 0; Area < problem.NombreDePays; Area++) - { - if (problem.adequacyPatchRuntimeData.areaMode[Area] == physicalAreaInsideAdqPatch) - { - for (int hour = 0; hour < numOfHoursInWeek; hour++) - { - // define access to the required variables - auto& scratchpad = *(study.areas[Area]->scratchpad[numSpace]); - double dtgMrg = scratchpad.dispatchableGenerationMargin[hour]; - - auto& hourlyResults = *(problem.ResultatsHoraires[Area]); - double& dtgMrgCsr = hourlyResults.ValeursHorairesDtgMrgCsr[hour]; - double& ens = hourlyResults.ValeursHorairesDeDefaillancePositive[hour]; - double& mrgCost = hourlyResults.CoutsMarginauxHoraires[hour]; - // calculate DTG MRG CSR and adjust ENS if neccessary - if (dtgMrgCsr == -1.0) // area is inside adq-patch and it is CSR triggered hour - { - dtgMrgCsr = Math::Max(0.0, dtgMrg - ens); - ens = Math::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 = -study.areas[Area]->thermal.unsuppliedEnergyCost; - } - else - dtgMrgCsr = dtgMrg; - } - } - } + Xmax = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco]; + Xmin = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]); } - -} // end namespace Antares +} // namespace AdequacyPatch } // end namespace Data -} // end namespace AdequacyPatch - -void HOURLY_CSR_PROBLEM::calculateCsrParameters() -{ - double netPositionInit; - double ensInit; - double spillageInit; - int hour = hourInWeekTriggeredCsr; - - for (int Area = 0; Area < pWeeklyProblemBelongedTo->NombreDePays; Area++) - { - if (pWeeklyProblemBelongedTo->adequacyPatchRuntimeData.areaMode[Area] - == physicalAreaInsideAdqPatch) - { - // set DTG MRG CSR in all areas inside adq-path for all CSR triggered hours to -1.0 - pWeeklyProblemBelongedTo->ResultatsHoraires[Area]->ValeursHorairesDtgMrgCsr[hour] - = -1.0; - // calculate netPositionInit and the RHS of the AreaBalance constraints - std::tie(netPositionInit, ignore, ignore) - = calculateAreaFlowBalance(pWeeklyProblemBelongedTo, Area, hour); - - ensInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillancePositive[hour]; - spillageInit = pWeeklyProblemBelongedTo->ResultatsHoraires[Area] - ->ValeursHorairesDeDefaillanceNegative[hour]; - - rhsAreaBalanceValues[Area] = ensInit + netPositionInit - spillageInit; - } - } - return; -} - -void HOURLY_CSR_PROBLEM::resetProblem() -{ - OPT_LiberationProblemesSimplexe(pWeeklyProblemBelongedTo); -} - -void HOURLY_CSR_PROBLEM::buildProblemVariables() -{ - OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, - *this); -} - -void HOURLY_CSR_PROBLEM::buildProblemConstraintsLHS() -{ - OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); -} - -void HOURLY_CSR_PROBLEM::setVariableBounds() -{ - OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); -} - -void HOURLY_CSR_PROBLEM::buildProblemConstraintsRHS() -{ - OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(pWeeklyProblemBelongedTo, *this); -} - -void HOURLY_CSR_PROBLEM::setProblemCost() -{ - OPT_InitialiserLesCoutsQuadratiques_CSR(pWeeklyProblemBelongedTo, *this); -} - -void HOURLY_CSR_PROBLEM::solveProblem(uint week, int year) -{ - ADQ_PATCH_CSR(pWeeklyProblemBelongedTo->ProblemeAResoudre, *this, week, year); -} - -void HOURLY_CSR_PROBLEM::run(uint week, const Antares::Solver::Variable::State& state) -{ - resetProblem(); - calculateCsrParameters(); - buildProblemVariables(); - buildProblemConstraintsLHS(); - setVariableBounds(); - buildProblemConstraintsRHS(); - setProblemCost(); - solveProblem(week, state.year); -} +} // namespace Antares diff --git a/src/solver/optimisation/adequacy_patch.h b/src/solver/optimisation/adequacy_patch.h index 45b3b0557c..5a7cfd2700 100644 --- a/src/solver/optimisation/adequacy_patch.h +++ b/src/solver/optimisation/adequacy_patch.h @@ -1,6 +1,6 @@ /* -** Copyright 2007-2022 RTE -** Authors: RTE-international / Redstork / Antares_Simulator Team +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** @@ -37,111 +37,75 @@ namespace Data { namespace AdequacyPatch { -//! A default threshold value for initiate curtailment sharing rule -const double defaultValueThresholdInitiateCurtailmentSharingRule = 0.0; -//! A default threshold value for display local matching rule violations -const double defaultValueThresholdDisplayLocalMatchingRuleViolations = 0.0; -//! CSR Variables relaxation threshold -const int defaultValueThresholdVarBoundsRelaxation = 3; -/*! - * Determines restriction type for transmission links for first step of adequacy patch. - * - * @param ProblemeHebdo PROBLEME_HEBDO*: Weekly problem structure. - * - * @param Interco int: Index of the link. - * - * @return uint from an enumeration that describes the type of restrictions to put on this link for - * adq purposes. - */ -ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatus(PROBLEME_HEBDO* ProblemeHebdo, int Interco); + /*! + * Determines restriction type for transmission links for first step of adequacy patch. + * + * @param OriginNodeAdequacyPatchType uint: The adq type of the node at the start of the link. + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * (type 1). + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ + LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStep( + AdequacyPatchMode OriginNodeAdequacyPatchType, + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); -/*! - * Determines restriction type for transmission links for first step of adequacy patch, when start - * node is inside adq path (type 2). - * - * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. - * - * @return uint from an enumeration that describes the type of restrictions to put on this link for - * adq purposes. - */ -ntcSetToZeroStatus_AdqPatchStep1 SetNTCForAdequacyFirstStepOriginNodeInsideAdq(AdequacyPatchMode ExtremityNodeAdequacyPatchType); + /*! + * Determines restriction type for transmission links for first step of adequacy patch, when start + * node is inside adq path (type 2). + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ + LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeInsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType); -/*! - * Determines restriction type for transmission links for first step of adequacy patch, when start - * node is outside adq path (type 1). - * - * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. - * - * @param setToZeroNTCfromOutToIn_AdqPatch bool: Switch to cut links from nodes outside adq patch - * (type 1) towards nodes inside adq patch (type 2). - * - * @param setToZeroNTCfromOutToOut_AdqPatch bool: Switch to cut links between nodes outside adq - * patch (type 1). - * - * @return uint from an enumeration that describes the type of restrictions to put on this link for - * adq purposes. - */ -ntcSetToZeroStatus_AdqPatchStep1 getNTCtoZeroStatusOriginNodeOutsideAdq( - AdequacyPatchMode ExtremityNodeAdequacyPatchType, - bool setToZeroNTCfromOutToIn_AdqPatch, - bool setToZeroNTCfromOutToOut_AdqPatch); - -/*! - * 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, - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, - const int Interco, - PROBLEME_HEBDO* ProblemeHebdo); - -/*! - * Calculates curtailment sharing rule parameters netPositionInit, densNew and totalNodeBalance per - * given area and hour. - */ -std::tuple calculateAreaFlowBalance(PROBLEME_HEBDO* ProblemeHebdo, - int Area, - int hour); - -/*! - * Calculate total local matching rule violation per one area, per one hour. - */ -double LmrViolationAreaHour(PROBLEME_HEBDO* ProblemeHebdo, - double totalNodeBalance, - 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, - const Study& study, - uint numSpace); - -/*! -** ** \brief add values of a array B to vector A, A[i]=A[i]+B[i] -** ** -** ** \param A A vector -** ** \param B An array -** ** \return -** */ -void addArray(std::vector& A, const double* B); - -/*! -** ** \brief Calculate Dispatchable margin for all areas after CSR optimization and adjust ENS -** ** values if neccessary. If LOLD=1, Sets MRG COST to the max value (unsupplied energy cost) -** ** -** ** \param study The Antares study -** ** \param problem The weekly problem, from the solver -** ** \return -** */ -void adqPatchPostProcess(const Data::Study& study, PROBLEME_HEBDO& problem, int numSpace); + /*! + * Determines restriction type for transmission links for first step of adequacy patch, when start + * node is outside adq path (type 1). + * + * @param ExtremityNodeAdequacyPatchType uint: The adq type of the node at the end of the link. + * + * @param SetToZero12LinksForAdequacyPatch bool: Switch to cut links from nodes outside adq patch + * (type 1) towards nodes inside adq patch (type 2). + * + * @param SetToZero11LinksForAdequacyPatch bool: Switch to cut links between nodes outside adq patch + * (type 1). + * + * @return uint from an enumeration that describes the type of restrictions to put on this link for + * adq purposes. + */ + LinkCapacityForAdequacyPatchFirstStep SetNTCForAdequacyFirstStepOriginNodeOutsideAdq( + AdequacyPatchMode ExtremityNodeAdequacyPatchType, + bool SetToZero12LinksForAdequacyPatch, + bool SetToZero11LinksForAdequacyPatch); + /*! + * Sets link bounds for first step of adequacy patch. + */ + void setBoundsAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco, + PROBLEME_HEBDO* ProblemeHebdo); + /*! + * Sets link bounds when adequacy patch is not used or when first step of adequacy patch is false. + */ + void setBoundsNoAdqPatch(double& Xmax, + double& Xmin, + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC, + const int Interco); } // end namespace Antares } // end namespace Data } // end namespace AdequacyPatch diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp deleted file mode 100644 index 84917d814a..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_LHS.cpp +++ /dev/null @@ -1,305 +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 -*/ - -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_structure_donnees.h" -#include "../solver/simulation/sim_extern_variables_globales.h" -#include "../solver/optimisation/opt_fonctions.h" - -using namespace Antares::Data; - -void setConstraintsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Var; - int NombreDeTermes; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of - // type 2. - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - NombreDeTermes = 0; - 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; - - NomDeLaContrainte = "flow=d-i, Interco:" + std::to_string(Interco); - logs.debug() << "C Interco: " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); - } - } -} - -void setNodeBalanceConstraints(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Var; - int NombreDeTermes; - int Interco; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // constraint: - // ENS(node A) + - // - flow (A -> 2) or (+ flow (2 -> A)) there should be only one of them, otherwise double-count - // - spillage(node A) = - // ENS_init(node A) + net_position_init(node A) – spillage_init(node A) - // for all areas inside adequacy patch - - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; ++Area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - // + ENS - NombreDeTermes = 0; - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[Area]; - if (Var >= 0) - { - Pi[NombreDeTermes] = 1.0; - Colonne[NombreDeTermes] = Var; - NombreDeTermes++; - } - - // - export flows - Interco = ProblemeHebdo->IndexDebutIntercoOrigine[Area]; - while (Interco >= 0) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - 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) - { - 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; - - NomDeLaContrainte = "Area Balance, Area:" + std::to_string(Area) + "; " - + ProblemeHebdo->NomsDesPays[Area]; - - logs.debug() << "C: " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, Pi, Colonne, NombreDeTermes, '='); - } - } -} - -void setBindingConstraints(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - double* Pi, - int* Colonne) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - int Var; - int NombreDeTermes; - int Interco; - int NbInterco; - double Poids; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - const CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - std::string NomDeLaContrainte; - - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - // Special case of the binding constraints - for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; - CntCouplante++) - { - MatriceDesContraintesCouplantes - = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - - if (MatriceDesContraintesCouplantes->TypeDeContrainteCouplante == CONTRAINTE_HORAIRE) - { - NbInterco - = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; - NombreDeTermes = 0; - for (int Index = 0; Index < NbInterco; Index++) - { - Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; - Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - 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; - - NomDeLaContrainte = "bc::hourly::" + std::to_string(hour) + "::" - + MatriceDesContraintesCouplantes->NomDeLaContrainteCouplante; - - logs.debug() << "C (bc): " << ProblemeAResoudre->NombreDeContraintes << ": " - << NomDeLaContrainte; - - OPT_ChargerLaContrainteDansLaMatriceDesContraintes( - ProblemeAResoudre, - Pi, - Colonne, - NombreDeTermes, - MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante); - } - } - } -} - -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] constraint list:"; - double* Pi; - int* Colonne; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - Pi = (double*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(double)); - Colonne = (int*)MemAlloc(ProblemeAResoudre->NombreDeVariables * sizeof(int)); - - ProblemeAResoudre->NombreDeContraintes = 0; - ProblemeAResoudre->NombreDeTermesDansLaMatriceDesContraintes = 0; - - setConstraintsOnFlows(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); - setNodeBalanceConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); - setBindingConstraints(ProblemeHebdo, hourlyCsrProblem, Pi, Colonne); - - MemFree(Pi); - MemFree(Colonne); -} \ No newline at end of file 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 deleted file mode 100644 index 66c4c2dee5..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_constraints_RHS.cpp +++ /dev/null @@ -1,189 +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 -*/ - -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_extern_variables_globales.h" -#include "../solver/optimisation/opt_fonctions.h" - -void setRHSvalueOnFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Cnt; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - // constraint: Flow = Flow_direct - Flow_indirect (+ loop flow) for links between nodes of - // type 2. - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - std::map::iterator it - = hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.find(Interco); - if (it != hourlyCsrProblem.numberOfConstraintCsrFlowDissociation.end()) - { - Cnt = it->second; - ProblemeAResoudre->SecondMembre[Cnt] = 0.; - logs.debug() << Cnt << "Flow=D-I: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt]; - } - } - } -} - -void setRHSnodeBalanceValue(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Cnt; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - // constraint: - // ENS(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) - // ] – spillage(node A) = ENS_init(node A) + net_position_init(node A) – spillage_init(node A) - // for all areas inside adequacy patch - - for (int Area = 0; Area < ProblemeHebdo->NombreDePays; Area++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - std::map::iterator it - = hourlyCsrProblem.numberOfConstraintCsrAreaBalance.find(Area); - if (it != hourlyCsrProblem.numberOfConstraintCsrAreaBalance.end()) - { - Cnt = it->second; - ProblemeAResoudre->SecondMembre[Cnt] = hourlyCsrProblem.rhsAreaBalanceValues[Area]; - logs.debug() << Cnt << ": Area Balance: RHS[" << Cnt - << "] = " << ProblemeAResoudre->SecondMembre[Cnt] - << " (Area = " << Area << ")"; - } - } - } -} - -void setRHSbindingConstraintsValue(PROBLEME_HEBDO* ProblemeHebdo, - const HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - double csrSolverRelaxationRHS = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; - int Cnt; - int Interco; - int NbInterco; - double Poids; - double ValueOfFlow; - int Index; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - double* SecondMembre = ProblemeAResoudre->SecondMembre; - const CONTRAINTES_COUPLANTES* MatriceDesContraintesCouplantes; - std::map bingdingConstraintNumber - = hourlyCsrProblem.numberOfConstraintCsrHourlyBinding; - - // constraint: - // user defined Binding constraints between transmission flows - // and/or power generated from generating units. - for (int CntCouplante = 0; CntCouplante < ProblemeHebdo->NombreDeContraintesCouplantes; - CntCouplante++) - { - if (bingdingConstraintNumber.find(CntCouplante) != bingdingConstraintNumber.end()) - { - MatriceDesContraintesCouplantes - = ProblemeHebdo->MatriceDesContraintesCouplantes[CntCouplante]; - - Cnt = bingdingConstraintNumber[CntCouplante]; - - // 1. The original RHS of bingding constraint - SecondMembre[Cnt] - = MatriceDesContraintesCouplantes->SecondMembreDeLaContrainteCouplante[hour]; - - // 2. RHS part 2: flow other than 2<->2 - NbInterco - = MatriceDesContraintesCouplantes->NombreDInterconnexionsDansLaContrainteCouplante; - for (Index = 0; Index < NbInterco; Index++) - { - Interco = MatriceDesContraintesCouplantes->NumeroDeLInterconnexion[Index]; - Poids = MatriceDesContraintesCouplantes->PoidsDeLInterconnexion[Index]; - - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch - || ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - != Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - ValueOfFlow = ProblemeHebdo->ValeursDeNTC[hour]->ValeurDuFlux[Interco]; - SecondMembre[Cnt] -= ValueOfFlow * Poids; - } - } - - // 3. RHS part 3: - cluster - int NbClusters - = MatriceDesContraintesCouplantes->NombreDePaliersDispatchDansLaContrainteCouplante; - int Area; - int IndexNumeroDuPalierDispatch; - double ValueOfVar; - - for (Index = 0; Index < NbClusters; Index++) - { - Area = MatriceDesContraintesCouplantes->PaysDuPalierDispatch[Index]; - - IndexNumeroDuPalierDispatch - = MatriceDesContraintesCouplantes->NumeroDuPalierDispatch[Index]; - - Poids = MatriceDesContraintesCouplantes->PoidsDuPalierDispatch[Index]; - - ValueOfVar = ProblemeHebdo->ResultatsHoraires[Area] - ->ProductionThermique[hour] - ->ProductionThermiqueDuPalier[IndexNumeroDuPalierDispatch]; - - SecondMembre[Cnt] -= ValueOfVar * Poids; - } - if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '<') - { - SecondMembre[Cnt] += csrSolverRelaxationRHS; - } - else if (MatriceDesContraintesCouplantes->SensDeLaContrainteCouplante == '>') - { - SecondMembre[Cnt] -= csrSolverRelaxationRHS; - } - logs.debug() << Cnt << ": Hourly bc: -RHS[" << Cnt << "] = " << SecondMembre[Cnt]; - } - } -} - -void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] RHS: "; - - setRHSvalueOnFlows(ProblemeHebdo, hourlyCsrProblem); - setRHSnodeBalanceValue(ProblemeHebdo, hourlyCsrProblem); - setRHSbindingConstraintsValue(ProblemeHebdo, hourlyCsrProblem); -} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp b/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp deleted file mode 100644 index 00bf616e5f..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/construct_problem_variables.cpp +++ /dev/null @@ -1,164 +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 -*/ - -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_structure_donnees.h" -#include "../solver/simulation/sim_extern_variables_globales.h" - -#include "../solver/optimisation/opt_fonctions.h" - -#include "pi_constantes_externes.h" - -void constructVariableENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; - NumberOfVariables = 0; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: ENS of each area inside adq patch - logs.debug() << " ENS of each area inside adq patch: "; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - // Only ENS for areas inside adq patch are considered as variables - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); - hourlyCsrProblem.ensSet.insert(NumberOfVariables); - logs.debug() << NumberOfVariables << " ENS[" << area << "].-[" - << ProblemeHebdo->NomsDesPays[area] << "]."; - - NumberOfVariables++; - } - } -} - -void constructVariableSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; - - // variables: Spilled Energy of each area inside adq patch - logs.debug() << " Spilled Energy of each area inside adq patch: "; - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - // Only Spilled Energy for areas inside adq patch are considered as variables - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_INFERIEUREMENT; - hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.insert(NumberOfVariables); - logs.debug() << NumberOfVariables << " Spilled Energy[" << area << "].-[" - << ProblemeHebdo->NomsDesPays[area] << "]."; - - NumberOfVariables++; - } - } -} - -void constructVariableFlows(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - int& NumberOfVariables = ProblemeAResoudre->NombreDeVariables; - - // variables: transmissin flows (flow, direct_direct and flow_indirect). For links between 2 - // and 2. - logs.debug() - << " transmissin flows (flow, flow_direct and flow_indirect). For links between 2 and 2:"; - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - hourlyCsrProblem.linkSet.insert(NumberOfVariables); - logs.debug() - << NumberOfVariables << " flow[" << Interco << "]. [" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysExtremiteDeLInterconnexion[Interco]] - << "]-[" - << ProblemeHebdo->NomsDesPays[ProblemeHebdo->PaysOrigineDeLInterconnexion[Interco]] - << "]."; - NumberOfVariables++; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " direct flow[" << Interco << "]. "; - NumberOfVariables++; - - CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco] - = NumberOfVariables; - ProblemeAResoudre->TypeDeVariable[NumberOfVariables] = VARIABLE_BORNEE_DES_DEUX_COTES; - logs.debug() << NumberOfVariables << " indirect flow[" << Interco << "]. "; - NumberOfVariables++; - } - } -} - -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] variable list:"; - - const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - assert(ProblemeAResoudre != NULL); - - constructVariableENS(ProblemeHebdo, hourlyCsrProblem); - constructVariableSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); - constructVariableFlows(ProblemeHebdo, hourlyCsrProblem); - - return; -} \ No newline at end of file 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 deleted file mode 100644 index 80b930d3c2..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/set_problem_cost_function.cpp +++ /dev/null @@ -1,161 +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 -*/ - -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_structure_donnees.h" -#include "../solver/simulation/sim_extern_variables_globales.h" - -#include "../solver/optimisation/opt_fonctions.h" - -double calculateQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, int hour, int area) -{ - double priceTakingOrders = 0.0; // PTO - if (ProblemeHebdo->adqPatchParams->PriceTakingOrder == Data::AdequacyPatch::AdqPatchPTO::isLoad) - { - priceTakingOrders - = ProblemeHebdo->ConsommationsAbattues[hour]->ConsommationAbattueDuPays[area] - + ProblemeHebdo->AllMustRunGeneration[hour]->AllMustRunGenerationOfArea[area]; - } - else if (ProblemeHebdo->adqPatchParams->PriceTakingOrder - == Data::AdequacyPatch::AdqPatchPTO::isDens) - { - priceTakingOrders = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour]; - } - - if (priceTakingOrders <= 0.0) - return 0.0; - else - return (1 / priceTakingOrders); -} - -void setQuadraticCost(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // variables: ENS for each area inside adq patch - // obj function term is: 1 / (PTO * PTO) * ENS * ENS - // => quadratic cost: 1 / (PTO * PTO) - // => linear cost: 0 - // PTO can take two different values according to option: - // 1. from DENS - // 2. from load - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - ProblemeAResoudre->CoutQuadratique[Var] - = calculateQuadraticCost(ProblemeHebdo, hour, area); - logs.debug() << Var << ". Quad C = " << ProblemeAResoudre->CoutQuadratique[Var]; - } - } - } -} - -void setLinearCost(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - int hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - const COUTS_DE_TRANSPORT* TransportCost; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - - // 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 - // flow_indirect ) - // => quadratic cost: 0 - // => linear cost: hurdle_cost_direct or hurdle_cost_indirect - // these members of objective functions are considered only if IntercoGereeAvecDesCouts = - // OUI_ANTARES (use hurdle cost option is true). otherwise these members are zero. - - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; Interco++) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - TransportCost = ProblemeHebdo->CoutDeTransport[Interco]; - // flow - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - 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]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) - ProblemeAResoudre->CoutLineaire[Var] = 0; - else - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportOrigineVersExtremite[hour]; - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } - - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - if (Var >= 0 && Var < ProblemeAResoudre->NombreDeVariables) - { - if (TransportCost->IntercoGereeAvecDesCouts == NON_ANTARES) - ProblemeAResoudre->CoutLineaire[Var] = 0; - else - ProblemeAResoudre->CoutLineaire[Var] - = TransportCost->CoutDeTransportExtremiteVersOrigine[hour]; - logs.debug() << Var << ". Linear C = " << ProblemeAResoudre->CoutLineaire[Var]; - } - } - } -} - -void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] cost"; - - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - memset((char*)ProblemeAResoudre->CoutLineaire, - 0, - ProblemeAResoudre->NombreDeVariables * sizeof(double)); - - setQuadraticCost(ProblemeHebdo, hourlyCsrProblem); - if (ProblemeHebdo->adqPatchParams->IncludeHurdleCostCsr) - setLinearCost(ProblemeHebdo, hourlyCsrProblem); -} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp b/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp deleted file mode 100644 index 9a29e2564e..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/set_variable_boundaries.cpp +++ /dev/null @@ -1,230 +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 -*/ - -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_structure_donnees.h" -#include "../solver/simulation/sim_extern_variables_globales.h" - -#include "../solver/optimisation/opt_fonctions.h" - -#include "pi_constantes_externes.h" - -#include -#include - -using namespace Yuni; - -void setBoundsOnENS(PROBLEME_HEBDO* ProblemeHebdo, HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* AdresseDuResultat; - int hour; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - double csrSolverRelaxation = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; - - // variables: ENS for each area inside adq patch - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillancePositive[area]; - - ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; - ProblemeAResoudre->Xmax[Var] - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDENS[hour] - + csrSolverRelaxation; - - ProblemeAResoudre->X[Var] - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]; - - AdresseDuResultat = &( - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillancePositive[hour]); - - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = AdresseDuResultat; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - } - } -} - -void setBoundsOnSpilledEnergy(PROBLEME_HEBDO* ProblemeHebdo, - const HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* AdresseDuResultat; - int hour; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - double csrSolverRelaxation = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; - - // variables: Spilled Energy for each area inside adq patch - for (int area = 0; area < ProblemeHebdo->NombreDePays; ++area) - { - if (ProblemeHebdo->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDefaillanceNegative[area]; - - ProblemeAResoudre->Xmin[Var] = -csrSolverRelaxation; - ProblemeAResoudre->Xmax[Var] = LINFINI_ANTARES; - - ProblemeAResoudre->X[Var] - = ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesDeDefaillanceNegative[hour]; - - AdresseDuResultat = &( - ProblemeHebdo->ResultatsHoraires[area]->ValeursHorairesSpilledEnergyAfterCSR[hour]); - - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = AdresseDuResultat; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - } - } -} - -void setBoundsOnFlows(PROBLEME_HEBDO* ProblemeHebdo, const HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - int Var; - double* AdresseDuResultat; - int hour; - hour = hourlyCsrProblem.hourInWeekTriggeredCsr; - double csrSolverRelaxation = ProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - const CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; - CorrespondanceVarNativesVarOptim = ProblemeHebdo->CorrespondanceVarNativesVarOptim[hour]; - double* Xmin; - double* Xmax; - Xmin = ProblemeAResoudre->Xmin; - Xmax = ProblemeAResoudre->Xmax; - VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; - ValeursDeNTC = ProblemeHebdo->ValeursDeNTC[hour]; - - // variables bounds: transmissin flows (flow, direct_direct and flow_indirect). For links - // between nodes of type 2. Set hourly bounds for links between nodes of type 2, depending on - // the user input (max direct and indirect flow). - for (int Interco = 0; Interco < ProblemeHebdo->NombreDInterconnexions; ++Interco) - { - // only consider link between 2 and 2 - if (ProblemeHebdo->adequacyPatchRuntimeData.originAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch - && ProblemeHebdo->adequacyPatchRuntimeData.extremityAreaMode[Interco] - == Antares::Data::AdequacyPatch::physicalAreaInsideAdqPatch) - { - // flow - Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; - Xmax[Var] - = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; - Xmin[Var] - = -(ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco]) - csrSolverRelaxation; - ProblemeAResoudre->X[Var] = ValeursDeNTC->ValeurDuFlux[Interco]; - - if (Math::Infinite(Xmax[Var]) == 1) - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_NON_BORNEE; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - else - { - if (Math::Infinite(Xmin[Var]) == -1) - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_SUPERIEUREMENT; - else - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - } - - AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] - = AdresseDuResultat; - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - - // direct / indirect flow - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutOrigineVersExtremiteDeLInterconnexion[Interco]; - - Xmin[Var] = -csrSolverRelaxation; - Xmax[Var] - = ValeursDeNTC->ValeurDeNTCOrigineVersExtremite[Interco] + csrSolverRelaxation; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - - Var = CorrespondanceVarNativesVarOptim - ->NumeroDeVariableCoutExtremiteVersOrigineDeLInterconnexion[Interco]; - - Xmin[Var] = -csrSolverRelaxation; - Xmax[Var] - = ValeursDeNTC->ValeurDeNTCExtremiteVersOrigine[Interco] + csrSolverRelaxation; - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_DES_DEUX_COTES; - if (Math::Infinite(Xmax[Var]) == 1) - { - ProblemeAResoudre->TypeDeVariable[Var] = VARIABLE_BORNEE_INFERIEUREMENT; - } - - logs.debug() << Var << ": " << ProblemeAResoudre->Xmin[Var] << ", " - << ProblemeAResoudre->Xmax[Var]; - } - } -} - -void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR( - PROBLEME_HEBDO* ProblemeHebdo, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "[CSR] bounds"; - - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre; - ProblemeAResoudre = ProblemeHebdo->ProblemeAResoudre; - - for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = nullptr; - - setBoundsOnENS(ProblemeHebdo, hourlyCsrProblem); - setBoundsOnSpilledEnergy(ProblemeHebdo, hourlyCsrProblem); - setBoundsOnFlows(ProblemeHebdo, hourlyCsrProblem); -} \ No newline at end of file diff --git a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp b/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp deleted file mode 100644 index c22324b09e..0000000000 --- a/src/solver/optimisation/adequacy_patch_csr/solve_problem.cpp +++ /dev/null @@ -1,285 +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 -*/ - -#include - -#include "../solver/optimisation/opt_structure_probleme_a_resoudre.h" - -#include "../solver/simulation/simulation.h" -#include "../solver/simulation/sim_structure_donnees.h" -#include "../solver/simulation/sim_structure_probleme_economique.h" -#include "../solver/simulation/sim_structure_probleme_adequation.h" -#include "../solver/simulation/sim_extern_variables_globales.h" - -#include "../solver/optimisation/opt_fonctions.h" - -/* - pi_define.h doesn't include this header, yet it uses struct jmp_buf. - It would be nice to remove this include, but would require to change pi_define.h, - which isn't part of Antares -*/ -#include - -extern "C" -{ -#include "pi_define.h" -#include "pi_definition_arguments.h" -#include "pi_fonctions.h" -} - -#include - -using namespace Antares; - -std::unique_ptr buildInteriorPointProblem( - PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) -{ - auto Probleme = std::make_unique(); - int ChoixToleranceParDefautSurLAdmissibilite; - int ChoixToleranceParDefautSurLaStationnarite; - int ChoixToleranceParDefautSurLaComplementarite; - - ChoixToleranceParDefautSurLAdmissibilite = OUI_PI; - ChoixToleranceParDefautSurLaStationnarite = OUI_PI; - ChoixToleranceParDefautSurLaComplementarite = OUI_PI; - - Probleme->NombreMaxDIterations = -1; - Probleme->CoutQuadratique = ProblemeAResoudre->CoutQuadratique; - Probleme->CoutLineaire = ProblemeAResoudre->CoutLineaire; - Probleme->X = ProblemeAResoudre->X; - Probleme->Xmin = ProblemeAResoudre->Xmin; - Probleme->Xmax = ProblemeAResoudre->Xmax; - Probleme->NombreDeVariables = ProblemeAResoudre->NombreDeVariables; - Probleme->TypeDeVariable = ProblemeAResoudre->TypeDeVariable; - - Probleme->VariableBinaire = (char*)ProblemeAResoudre->CoutsReduits; - - Probleme->NombreDeContraintes = ProblemeAResoudre->NombreDeContraintes; - Probleme->IndicesDebutDeLigne = ProblemeAResoudre->IndicesDebutDeLigne; - Probleme->NombreDeTermesDesLignes = ProblemeAResoudre->NombreDeTermesDesLignes; - Probleme->IndicesColonnes = ProblemeAResoudre->IndicesColonnes; - Probleme->CoefficientsDeLaMatriceDesContraintes - = ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes; - Probleme->Sens = ProblemeAResoudre->Sens; - Probleme->SecondMembre = ProblemeAResoudre->SecondMembre; - - Probleme->AffichageDesTraces = NON_PI; - - Probleme->UtiliserLaToleranceDAdmissibiliteParDefaut = ChoixToleranceParDefautSurLAdmissibilite; - - Probleme->UtiliserLaToleranceDeStationnariteParDefaut - = ChoixToleranceParDefautSurLaStationnarite; - - Probleme->UtiliserLaToleranceDeComplementariteParDefaut - = ChoixToleranceParDefautSurLaComplementarite; - - Probleme->CoutsMarginauxDesContraintes = ProblemeAResoudre->CoutsMarginauxDesContraintes; - - Probleme->CoutsMarginauxDesContraintesDeBorneInf = ProblemeAResoudre->CoutsReduits; - Probleme->CoutsMarginauxDesContraintesDeBorneSup = ProblemeAResoudre->CoutsReduits; - - return Probleme; -} - -void setToZeroIfBelowThreshold(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - bool inSet = hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.find(Var) - != hourlyCsrProblem.varToBeSetToZeroIfBelowThreshold.end(); - bool belowLimit = ProblemeAResoudre->X[Var] < hourlyCsrProblem.belowThisThresholdSetToZero; - if (inSet && belowLimit) - ProblemeAResoudre->X[Var] = 0.0; - } -} - -void storeInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - double* pt; - for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - pt = ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var]; - if (pt) - { - *pt = ProblemeAResoudre->X[Var]; - } - logs.debug() << "[CSR]" << Var << " = " << ProblemeAResoudre->X[Var]; - } -} - -void storeOrDisregardInteriorPointResults(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb, - double costPriorToCsr, - double costAfterCsr) -{ - const int hoursInWeek = 168; - const bool checkCost - = hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->CheckCsrCostFunctionValue; - double deltaCost = costAfterCsr - costPriorToCsr; - - if (checkCost) - { - logs.info() << "[adq-patch] costPriorToCsr: " << costPriorToCsr - << ", costAfterCsr: " << costAfterCsr - << ", deltaCost: " << costAfterCsr - costPriorToCsr; - } - - if (!checkCost || (checkCost && deltaCost < 0.0)) - storeInteriorPointResults(ProblemeAResoudre, hourlyCsrProblem); - 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.hourInWeekTriggeredCsr + 1; -} - -double calculateCsrCostFunctionValue(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - const HOURLY_CSR_PROBLEM& hourlyCsrProblem) -{ - logs.debug() << "calculateCsrCostFunctionValue! "; - double cost = 0.0; - if (!hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->CheckCsrCostFunctionValue) - { - logs.debug() << "CheckCsrCostFunctionValue = FALSE"; - return cost; - } - - for (int Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - logs.debug() << "Var: " << Var; - bool inEnsSet = hourlyCsrProblem.ensSet.find(Var) != hourlyCsrProblem.ensSet.end(); - if (inEnsSet) - { - cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->X[Var] - * ProblemeAResoudre->CoutQuadratique[Var]; - logs.debug() << "X-Q: " << ProblemeAResoudre->X[Var]*1e3; - logs.debug() << "CoutQ: " << ProblemeAResoudre->CoutQuadratique[Var]*1e3; - logs.debug() << "TotalCost: " << cost*1e3; - } - bool inLinkSet = hourlyCsrProblem.linkSet.find(Var) != hourlyCsrProblem.linkSet.end(); - if (inLinkSet - && hourlyCsrProblem.pWeeklyProblemBelongedTo->adqPatchParams->IncludeHurdleCostCsr) - { - if (ProblemeAResoudre->X[Var] >= 0) - { - cost += ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 1]; - logs.debug() << "X+: " << ProblemeAResoudre->X[Var]*1e3; - logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 1]*1e3; - logs.debug() << "TotalCost: " << cost*1e3; - } - else - { - cost -= ProblemeAResoudre->X[Var] * ProblemeAResoudre->CoutLineaire[Var + 2]; - logs.debug() << "X-: " << ProblemeAResoudre->X[Var]*1e3; - logs.debug() << "CoutL: " << ProblemeAResoudre->CoutLineaire[Var + 2]*1e3; - logs.debug() << "TotalCost: " << cost*1e3; - } - } - } - return cost; -} - -void CSR_DEBUG_HANDLE(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre) -{ - int Var; - - logs.info(); - logs.info() << LOG_UI_DISPLAY_MESSAGES_OFF; - logs.info() << "Here is the trace:"; - - for (Var = 0; Var < ProblemeAResoudre->NombreDeVariables; Var++) - { - logs.info().appendFormat("Variable %ld cout lineaire %e cout quadratique %e", - Var, - ProblemeAResoudre->CoutLineaire[Var], - ProblemeAResoudre->CoutQuadratique[Var]); - } - for (int Cnt = 0; Cnt < ProblemeAResoudre->NombreDeContraintes; Cnt++) - { - logs.info().appendFormat("Constraint %ld sens %c B %e", - Cnt, - ProblemeAResoudre->Sens[Cnt], - ProblemeAResoudre->SecondMembre[Cnt]); - - int il = ProblemeAResoudre->IndicesDebutDeLigne[Cnt]; - int ilMax = il + ProblemeAResoudre->NombreDeTermesDesLignes[Cnt]; - for (; il < ilMax; ++il) - { - Var = ProblemeAResoudre->IndicesColonnes[il]; - logs.info().appendFormat(" coeff %e var %ld xmin %e xmax %e type %ld", - ProblemeAResoudre->CoefficientsDeLaMatriceDesContraintes[il], - Var, - ProblemeAResoudre->Xmin[Var], - ProblemeAResoudre->Xmax[Var], - ProblemeAResoudre->TypeDeVariable[Var]); - } - } -} - -void handleInteriorPointError(const PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - const HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb) -{ - const int hoursInWeek = 168; - logs.warning() - << "No further optimization for CSR is possible, optimum solution is set as LMR . year: " - << yearNb + 1 - << ". hour: " << weekNb * hoursInWeek + hourlyCsrProblem.hourInWeekTriggeredCsr + 1; - -#ifndef NDEBUG - CSR_DEBUG_HANDLE(ProblemeAResoudre); -#endif -} - -bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudre, - HOURLY_CSR_PROBLEM& hourlyCsrProblem, - uint weekNb, - int yearNb) -{ - double costPriorToCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - auto Probleme = buildInteriorPointProblem(ProblemeAResoudre); - PI_Quamin(Probleme.get()); // resolution - if (Probleme->ExistenceDUneSolution == OUI_PI) - { - setToZeroIfBelowThreshold(ProblemeAResoudre, hourlyCsrProblem); - double costAfterCsr = calculateCsrCostFunctionValue(ProblemeAResoudre, hourlyCsrProblem); - storeOrDisregardInteriorPointResults( - ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb, costPriorToCsr, costAfterCsr); - return true; - } - else - { - handleInteriorPointError(ProblemeAResoudre, hourlyCsrProblem, weekNb, yearNb); - return false; - } -} \ No newline at end of file diff --git a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp index e374db5bc6..3ce5b777fa 100644 --- a/src/solver/optimisation/opt_appel_solveur_quadratique.cpp +++ b/src/solver/optimisation/opt_appel_solveur_quadratique.cpp @@ -182,4 +182,4 @@ bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE* ProblemeAResoudr return false; } -} \ No newline at end of file +} 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 index f24c00be56..7f6c2f69f8 100644 --- a/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_matrice_des_contraintes_cas_quadratique.cpp @@ -32,8 +32,6 @@ #include "../simulation/sim_extern_variables_globales.h" #include "opt_fonctions.h" -using namespace Antares::Data; - void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* ProblemeHebdo) { int Interco; @@ -92,4 +90,4 @@ void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO* MemFree(Pi); MemFree(Colonne); -} \ No newline at end of file +} diff --git a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp index 9cbea7809c..46440a51c9 100644 --- a/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp +++ b/src/solver/optimisation/opt_construction_variables_optimisees_quadratique.cpp @@ -56,4 +56,4 @@ void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_H NombreDeVariables++; } ProblemeAResoudre->NombreDeVariables = NombreDeVariables; -} \ No newline at end of file +} diff --git a/src/solver/optimisation/opt_fonctions.h b/src/solver/optimisation/opt_fonctions.h index 6fd9bc5bcd..31e5ff4ac7 100644 --- a/src/solver/optimisation/opt_fonctions.h +++ b/src/solver/optimisation/opt_fonctions.h @@ -36,26 +36,20 @@ void OPT_NumeroDeJourDuPasDeTemps(PROBLEME_HEBDO*); void OPT_NumeroDIntervalleOptimiseDuPasDeTemps(PROBLEME_HEBDO*); void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeLineaire(PROBLEME_HEBDO*); void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique(PROBLEME_HEBDO*); -void OPT_ConstruireLaListeDesVariablesOptimiseesDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_ConstruireLaMatriceDesContraintesDuProblemeLineaire(PROBLEME_HEBDO*, uint); void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique(PROBLEME_HEBDO*); -void OPT_ConstruireLaMatriceDesContraintesDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_InitialiserLesPminHebdo(PROBLEME_HEBDO*); void OPT_InitialiserLesContrainteDEnergieHydrauliqueParIntervalleOptimise(PROBLEME_HEBDO*); void OPT_MaxDesPmaxHydrauliques(PROBLEME_HEBDO*); void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO*, const int, const int); void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO*, int); -void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_InitialiserLeSecondMembreDuProblemeLineaire(PROBLEME_HEBDO*, int, int, int); void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO*, int); -void OPT_InitialiserLeSecondMembreDuProblemeQuadratique_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_InitialiserLesCoutsLineaire(PROBLEME_HEBDO*, const int, const int, uint); void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO*, int); -void OPT_InitialiserLesCoutsQuadratiques_CSR(PROBLEME_HEBDO*, HOURLY_CSR_PROBLEM&); void OPT_ControleDesPminPmaxThermiques(PROBLEME_HEBDO*); bool OPT_AppelDuSolveurQuadratique(PROBLEME_ANTARES_A_RESOUDRE*, const int); -bool ADQ_PATCH_CSR(PROBLEME_ANTARES_A_RESOUDRE*, HOURLY_CSR_PROBLEM&, uint week, int year); bool OPT_PilotageOptimisationLineaire(PROBLEME_HEBDO*, uint); void OPT_VerifierPresenceReserveJmoins1(PROBLEME_HEBDO*); 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 d93771d564..4011e43772 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_lineaire.cpp @@ -119,7 +119,7 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob double* Xmin; double* Xmax; int* TypeDeVariable; - + VALEURS_DE_NTC_ET_RESISTANCES* ValeursDeNTC; CORRESPONDANCES_DES_VARIABLES* CorrespondanceVarNativesVarOptim; PALIERS_THERMIQUES* PaliersThermiquesDuPays; @@ -156,7 +156,11 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Var = CorrespondanceVarNativesVarOptim->NumeroDeVariableDeLInterconnexion[Interco]; CoutDeTransport = ProblemeHebdo->CoutDeTransport[Interco]; - AdequacyPatch::setNTCbounds(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); + if (ProblemeHebdo->adqPatchParams && ProblemeHebdo->adqPatchParams->AdequacyFirstStep) + AdequacyPatch::setBoundsAdqPatch( + Xmax[Var], Xmin[Var], ValeursDeNTC, Interco, ProblemeHebdo); + else + AdequacyPatch::setBoundsNoAdqPatch(Xmax[Var], Xmin[Var], ValeursDeNTC, Interco); if (Math::Infinite(Xmax[Var]) == 1) { @@ -377,14 +381,14 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeLineaire(PROBLEME_HEBDO* Prob Xmax[Var] = 0.; // adq patch: update ENS <= DENS in 2nd run - if (ProblemeHebdo->adqPatchParams && ProblemeHebdo->adqPatchParams->AdequacyFirstStep == false + if (ProblemeHebdo->adqPatchParams + && ProblemeHebdo->adqPatchParams->AdequacyFirstStep == false && ProblemeHebdo->adequacyPatchRuntimeData.areaMode[Pays] - == AdequacyPatch::physicalAreaInsideAdqPatch) - { + == Data::AdequacyPatch::physicalAreaInsideAdqPatch) Xmax[Var] = std::min(Xmax[Var], ProblemeHebdo->ResultatsHoraires[Pays]->ValeursHorairesDENS[PdtHebdo]); - } + ProblemeHebdo->ResultatsHoraires[Pays] ->ValeursHorairesDeDefaillancePositive[PdtHebdo] = 0.0; 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 b556f1ab0f..233720ad33 100644 --- a/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_bornes_cas_quadratique.cpp @@ -93,4 +93,4 @@ void OPT_InitialiserLesBornesDesVariablesDuProblemeQuadratique(PROBLEME_HEBDO* P AdresseDuResultat = &(ValeursDeNTC->ValeurDuFlux[Interco]); ProblemeAResoudre->AdresseOuPlacerLaValeurDesVariablesOptimisees[Var] = AdresseDuResultat; } -} \ No newline at end of file +} 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 4e843bb965..5761cf1341 100644 --- a/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_des_couts_cas_quadratique.cpp @@ -56,4 +56,4 @@ void OPT_InitialiserLesCoutsQuadratiques(PROBLEME_HEBDO* ProblemeHebdo, int PdtH ProblemeAResoudre->CoutQuadratique[Var] = ValeursDeResistances->ResistanceApparente[Interco]; } -} \ No newline at end of file +} 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 0d5188d13d..5a18c70e63 100644 --- a/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp +++ b/src/solver/optimisation/opt_gestion_second_membre_cas_quadratique.cpp @@ -46,4 +46,4 @@ void OPT_InitialiserLeSecondMembreDuProblemeQuadratique(PROBLEME_HEBDO* Probleme ProblemeAResoudre->SecondMembre[Cnt] = ProblemeHebdo->SoldeMoyenHoraire[PdtHebdo]->SoldeMoyenDuPays[Pays]; } -} \ No newline at end of file +} diff --git a/src/solver/simulation/economy.cpp b/src/solver/simulation/economy.cpp index 45bdc08bfc..03e158878b 100644 --- a/src/solver/simulation/economy.cpp +++ b/src/solver/simulation/economy.cpp @@ -36,9 +36,6 @@ #include "../optimisation/opt_fonctions.h" #include "common-eco-adq.h" #include "opt_time_writer.h" -#include -#include "../optimisation/adequacy_patch.h" - using namespace Yuni; @@ -50,6 +47,7 @@ namespace Simulation { enum { + nbHoursInAWeek = 168, }; @@ -74,10 +72,7 @@ AdequacyPatchOptimization::AdequacyPatchOptimization(PROBLEME_HEBDO** problemesH EconomyWeeklyOptimization(problemesHebdo) { } -void AdequacyPatchOptimization::solve(Variable::State& state, - int hourInTheYear, - uint numSpace, - uint w) +void AdequacyPatchOptimization::solve(Variable::State& state, int hourInTheYear, uint numSpace) { auto problemeHebdo = pProblemesHebdo[numSpace]; problemeHebdo->adqPatchParams->AdequacyFirstStep = true; @@ -108,15 +103,11 @@ NoAdequacyPatchOptimization::NoAdequacyPatchOptimization(PROBLEME_HEBDO** proble EconomyWeeklyOptimization(problemesHebdo) { } -void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace, uint) +void NoAdequacyPatchOptimization::solve(Variable::State&, int, uint numSpace) { auto problemeHebdo = pProblemesHebdo[numSpace]; OPT_OptimisationHebdomadaire(problemeHebdo, numSpace); } -void NoAdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint week) -{ - return; -} Economy::Economy(Data::Study& study) : study(study), preproOnly(false), pProblemesHebdo(nullptr) { @@ -193,62 +184,6 @@ bool Economy::simulationBegin() return true; } -vector AdequacyPatchOptimization::calculateENSoverAllAreasForEachHour(uint numSpace) const -{ - std::vector sumENS(nbHoursInAWeek, 0.0); - for (int area = 0; area < pProblemesHebdo[numSpace]->NombreDePays; ++area) - { - if (pProblemesHebdo[numSpace]->adequacyPatchRuntimeData.areaMode[area] - == Data::AdequacyPatch::physicalAreaInsideAdqPatch) - addArray(sumENS, - pProblemesHebdo[numSpace] - ->ResultatsHoraires[area] - ->ValeursHorairesDeDefaillancePositive); - } - return sumENS; -} - -std::set AdequacyPatchOptimization::identifyHoursForCurtailmentSharing(vector sumENS, - uint numSpace) const -{ - double threshold - = pProblemesHebdo[numSpace]->adqPatchParams->ThresholdInitiateCurtailmentSharingRule; - std::set triggerCsrSet; - for (int i = 0; i < nbHoursInAWeek; ++i) - { - if (sumENS[i] > threshold) - { - triggerCsrSet.insert(i); - } - } - logs.debug() << "number of triggered hours: " << triggerCsrSet.size(); - return triggerCsrSet; -} - -std::set AdequacyPatchOptimization::getHoursRequiringCurtailmentSharing(uint numSpace) const -{ - vector sumENS = calculateENSoverAllAreasForEachHour(numSpace); - return identifyHoursForCurtailmentSharing(sumENS, numSpace); -} - -void AdequacyPatchOptimization::solveCSR(const Variable::State& state, uint numSpace, uint w) -{ - auto problemeHebdo = pProblemesHebdo[numSpace]; - double totalLmrViolation - = calculateDensNewAndTotalLmrViolation(problemeHebdo, state.study, numSpace); - logs.info() << "[adq-patch] Year:" << state.year + 1 << " Week:" << w + 1 - << ".Total LMR violation:" << totalLmrViolation; - const std::set hoursRequiringCurtailmentSharing - = getHoursRequiringCurtailmentSharing(numSpace); - for (int hourInWeek : hoursRequiringCurtailmentSharing) - { - logs.info() << "[adq-patch] CSR triggered for Year:" << state.year + 1 - << " Hour:" << w * nbHoursInAWeek + hourInWeek + 1; - HOURLY_CSR_PROBLEM hourlyCsrProblem(hourInWeek, problemeHebdo); - hourlyCsrProblem.run(w, state); - } -} - bool Economy::year(Progression::Task& progression, Variable::State& state, uint numSpace, @@ -285,19 +220,15 @@ bool Economy::year(Progression::Task& progression, try { - weeklyOptProblem->solve(state, hourInTheYear, numSpace, w); + weeklyOptProblem->solve(state, hourInTheYear, numSpace); DispatchableMarginForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear); - weeklyOptProblem->solveCSR(state, numSpace, w); - computingHydroLevels(study, *pProblemesHebdo[numSpace], nbHoursInAWeek, false); RemixHydroForAllAreas( study, *pProblemesHebdo[numSpace], numSpace, hourInTheYear, nbHoursInAWeek); - - adqPatchPostProcess(study, *pProblemesHebdo[numSpace], numSpace); computingHydroLevels(study, *pProblemesHebdo[numSpace], nbHoursInAWeek, true); diff --git a/src/solver/simulation/economy.h b/src/solver/simulation/economy.h index cf8c5d79a4..d28f9deb25 100644 --- a/src/solver/simulation/economy.h +++ b/src/solver/simulation/economy.h @@ -47,8 +47,7 @@ class EconomyWeeklyOptimization { public: using Ptr = std::unique_ptr; - virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) = 0; - virtual void solveCSR(const Variable::State& state, uint numSpace, uint week) = 0; + virtual void solve(Variable::State& state, int hourInTheYear, uint numSpace) = 0; static Ptr create(bool adqPatchEnabled, PROBLEME_HEBDO** pProblemesHebdo); protected: @@ -60,21 +59,14 @@ class AdequacyPatchOptimization : public EconomyWeeklyOptimization { public: explicit AdequacyPatchOptimization(PROBLEME_HEBDO** problemesHebdo); - void solve(Variable::State& state, int hourInTheYear, uint numSpace, uint week) override; - void solveCSR(const Variable::State& state, uint numSpace, uint week) override; - -private: - vector calculateENSoverAllAreasForEachHour(uint numSpace) const; - std::set identifyHoursForCurtailmentSharing(vector sumENS, uint numSpace) const; - std::set getHoursRequiringCurtailmentSharing(uint numSpace) const; + void solve(Variable::State& state, int hourInTheYear, uint numSpace) override; }; class NoAdequacyPatchOptimization : public EconomyWeeklyOptimization { public: explicit NoAdequacyPatchOptimization(PROBLEME_HEBDO** problemesHebdo); - void solve(Variable::State&, int, uint numSpace, uint week) override; - void solveCSR(const Variable::State& state, uint numSpace, uint week) override; + void solve(Variable::State&, int, uint numSpace) override; }; class Economy diff --git a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp index fa60f1cd77..e3dc9916cc 100644 --- a/src/solver/simulation/sim_alloc_probleme_hebdo.cpp +++ b/src/solver/simulation/sim_alloc_probleme_hebdo.cpp @@ -457,12 +457,6 @@ void SIM_AllocationProblemeHebdo(PROBLEME_HEBDO& problem, int NombreDePasDeTemps = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDENS = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); // adq patch - problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations - = (int*)MemAllocMemset(NombreDePasDeTemps * sizeof(int)); // adq patch - problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR - = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch - problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgCsr - = (double*)MemAllocMemset(NombreDePasDeTemps * sizeof(double)); // adq patch problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp = (double*)MemAlloc(NombreDePasDeTemps * sizeof(double)); problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown @@ -826,9 +820,6 @@ void SIM_DesallocationProblemeHebdo(PROBLEME_HEBDO& problem) MemFree(problem.PaliersThermiquesDuPays[k]); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositive); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDENS); - MemFree(problem.ResultatsHoraires[k]->ValeursHorairesLmrViolations); - MemFree(problem.ResultatsHoraires[k]->ValeursHorairesSpilledEnergyAfterCSR); - MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDtgMrgCsr); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveUp); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveDown); MemFree(problem.ResultatsHoraires[k]->ValeursHorairesDeDefaillancePositiveAny); diff --git a/src/solver/simulation/sim_calcul_economique.cpp b/src/solver/simulation/sim_calcul_economique.cpp index 053b523a0e..d28d0ff9ee 100644 --- a/src/solver/simulation/sim_calcul_economique.cpp +++ b/src/solver/simulation/sim_calcul_economique.cpp @@ -68,22 +68,11 @@ void SIM_InitialisationProblemeHebdo(Data::Study& study, problem.adqPatchParams = std::unique_ptr(new AdequacyPatchParameters()); // AdequacyFirstStep will be initialized during the economy solve + // AdqBehaviorMap will be initialized during the economy solve problem.adqPatchParams->SetNTCOutsideToInsideToZero = parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks; problem.adqPatchParams->SetNTCOutsideToOutsideToZero = parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks; - problem.adqPatchParams->PriceTakingOrder - = parameters.adqPatch.curtailmentSharing.priceTakingOrder; - problem.adqPatchParams->IncludeHurdleCostCsr - = parameters.adqPatch.curtailmentSharing.includeHurdleCost; - problem.adqPatchParams->CheckCsrCostFunctionValue - = parameters.adqPatch.curtailmentSharing.checkCsrCostFunction; - problem.adqPatchParams->ThresholdInitiateCurtailmentSharingRule - = parameters.adqPatch.curtailmentSharing.thresholdInitiate; - problem.adqPatchParams->ThresholdDisplayLocalMatchingRuleViolations - = parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations; - double temp = pow(10, -parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); - problem.adqPatchParams->ThresholdCSRVarBoundsRelaxation = temp < 0.1 ? temp : 0.1; problem.adequacyPatchRuntimeData.initialize(study); } diff --git a/src/solver/simulation/sim_structure_probleme_economique.h b/src/solver/simulation/sim_structure_probleme_economique.h index 4745ae2b2d..2eecf41427 100644 --- a/src/solver/simulation/sim_structure_probleme_economique.h +++ b/src/solver/simulation/sim_structure_probleme_economique.h @@ -36,8 +36,6 @@ #include #include -using namespace Antares::Data::AdequacyPatch; - typedef struct { int* NumeroDeVariableDeLInterconnexion; @@ -312,8 +310,8 @@ class AdequacyPatchRuntimeData public: std::vector areaMode; - std::vector originAreaMode; - std::vector extremityAreaMode; + std::vector originAreaType; + std::vector extremityAreaType; void initialize(Antares::Data::Study& study) { for (uint i = 0; i != study.areas.size(); ++i) @@ -324,8 +322,8 @@ class AdequacyPatchRuntimeData for (uint i = 0; i < study.runtime->interconnectionsCount; ++i) { auto& link = *(study.runtime->areaLink[i]); - originAreaMode.push_back(link.from->adequacyPatchMode); - extremityAreaMode.push_back(link.with->adequacyPatchMode); + originAreaType.push_back(link.from->adequacyPatchMode); + extremityAreaType.push_back(link.with->adequacyPatchMode); } } }; @@ -437,9 +435,6 @@ typedef struct { double* ValeursHorairesDeDefaillancePositive; double* ValeursHorairesDENS; // adq patch domestic unsupplied energy - int* ValeursHorairesLmrViolations; // adq patch lmr violations - double* ValeursHorairesSpilledEnergyAfterCSR; // adq patch spillage after CSR - double* ValeursHorairesDtgMrgCsr; // adq patch DTG MRG after CSR double* ValeursHorairesDeDefaillancePositiveUp; double* ValeursHorairesDeDefaillancePositiveDown; double* ValeursHorairesDeDefaillancePositiveAny; @@ -491,12 +486,6 @@ struct AdequacyPatchParameters bool AdequacyFirstStep; bool SetNTCOutsideToInsideToZero; bool SetNTCOutsideToOutsideToZero; - bool IncludeHurdleCostCsr; - bool CheckCsrCostFunctionValue; - AdqPatchPTO PriceTakingOrder; - double ThresholdInitiateCurtailmentSharingRule; - double ThresholdDisplayLocalMatchingRuleViolations; - double ThresholdCSRVarBoundsRelaxation; }; struct PROBLEME_HEBDO @@ -716,42 +705,4 @@ struct PROBLEME_HEBDO char debugFolder[1024]; }; -namespace Antares::Solver::Variable { class State; } // foward declaration -// hourly CSR problem structure -class HOURLY_CSR_PROBLEM -{ -private: - void calculateCsrParameters(); - void resetProblem(); - void buildProblemVariables(); - void setVariableBounds(); - void buildProblemConstraintsLHS(); - void buildProblemConstraintsRHS(); - void setProblemCost(); - void solveProblem(uint week, int year); -public: - void run(uint week, const Antares::Solver::Variable::State& state); - - int hourInWeekTriggeredCsr; - double belowThisThresholdSetToZero; - PROBLEME_HEBDO* pWeeklyProblemBelongedTo; - HOURLY_CSR_PROBLEM(int hourInWeek, PROBLEME_HEBDO* pProblemeHebdo) - { - hourInWeekTriggeredCsr = hourInWeek; - pWeeklyProblemBelongedTo = pProblemeHebdo; - belowThisThresholdSetToZero - = pProblemeHebdo->adqPatchParams->ThresholdCSRVarBoundsRelaxation; - }; - 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 ensSet; // place inside only ENS inside adq-patch - std::set linkSet; // place inside only links between to zones inside adq-patch -}; - #endif diff --git a/src/solver/variable/economy/all.h b/src/solver/variable/economy/all.h index a7c527fcc1..e691f7f376 100644 --- a/src/solver/variable/economy/all.h +++ b/src/solver/variable/economy/all.h @@ -61,9 +61,6 @@ #include "hydroCost.h" #include "unsupliedEnergy.h" #include "domesticUnsuppliedEnergy.h" -#include "localMatchingRuleViolations.h" -#include "spilledEnergyAfterCSR.h" -#include "dtgMarginAfterCsr.h" #include "spilledEnergy.h" #include "lold.h" @@ -155,24 +152,18 @@ typedef // Prices >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerArea; /*! @@ -231,41 +222,31 @@ typedef // Prices Common::SpatialAggregate< DomesticUnsuppliedEnergy, Common::SpatialAggregate< - LMRViolations, + SpilledEnergy, + // LOLD Common::SpatialAggregate< - SpilledEnergy, + LOLD, Common::SpatialAggregate< - SpilledEnergyAfterCSR, - // LOLD + LOLP, + Common::SpatialAggregate< - LOLD, + AvailableDispatchGen, Common::SpatialAggregate< - LOLP, + DispatchableGenMargin, Common::SpatialAggregate< - AvailableDispatchGen, - Common::SpatialAggregate< - DispatchableGenMargin, - Common::SpatialAggregate< - DtgMarginCsr, - Common::SpatialAggregate< - Marge, + Marge, - // Detail Prices - Common::SpatialAggregate< - NonProportionalCost, // MBO - // 13/05/2014 - // - - // refs: - // #21 + // Detail Prices + Common::SpatialAggregate< + NonProportionalCost, // MBO 13/05/2014 + // - refs: #21 - // Number Of Dispatched Units - Common::SpatialAggregate< - NbOfDispatchedUnits // MBO - // 25/02/2016 - // - - // refs: - // #55 - >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> + // Number Of Dispatched Units + Common::SpatialAggregate< + NbOfDispatchedUnits // MBO + // 25/02/2016 + // - refs: #55 + >>>>>>>>>>>>>>>>>>>>>>>>>>>>>>> VariablesPerSetOfAreas; diff --git a/src/solver/variable/economy/dtgMarginAfterCsr.h b/src/solver/variable/economy/dtgMarginAfterCsr.h deleted file mode 100644 index 3c2dbdf80b..0000000000 --- a/src/solver/variable/economy/dtgMarginAfterCsr.h +++ /dev/null @@ -1,288 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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 -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardDtgMarginCsr -{ - //! Caption - static const char* Caption() - { - return "DTG MRG CSR"; - } - //! Unit - static const char* Unit() - { - return "MWh"; - } - //! The short description of the variable - static const char* 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), - }; - }; - -public: - ~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); - } - - void hourEnd(State& state, unsigned int hourInTheYear) - { - // Next variable - 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(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class DtgMarginCsr - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_DtgMarginCsr_H__ diff --git a/src/solver/variable/economy/localMatchingRuleViolations.h b/src/solver/variable/economy/localMatchingRuleViolations.h deleted file mode 100644 index 19d5b96769..0000000000 --- a/src/solver/variable/economy/localMatchingRuleViolations.h +++ /dev/null @@ -1,274 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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 const char* Caption() - { - return "LMR VIOL."; - } - //! Unit - static const char* Unit() - { - return " "; - } - - //! The short description of the variable - static const char* 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); - } - - 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(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class LMRViolations - -} - -#endif // __SOLVER_VARIABLE_ECONOMY_LMR_VIOLATIONS_H__ diff --git a/src/solver/variable/economy/spilledEnergyAfterCSR.h b/src/solver/variable/economy/spilledEnergyAfterCSR.h deleted file mode 100644 index eeb9192cb0..0000000000 --- a/src/solver/variable/economy/spilledEnergyAfterCSR.h +++ /dev/null @@ -1,289 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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 -{ -namespace Solver -{ -namespace Variable -{ -namespace Economy -{ -struct VCardSpilledEnergyAfterCSR -{ - //! Caption - static const char* Caption() - { - return "SPIL. ENRG. CSR"; - } - //! Unit - static const char* Unit() - { - return "MWh"; - } - //! The short description of the variable - static const char* 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), - }; - }; - -public: - ~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); - } - - void hourEnd(State& state, unsigned int hourInTheYear) - { - // Next variable - 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(); - pValuesForTheCurrentYear[numSpace].template buildAnnualSurveyReport( - results, fileLevel, precision); - } - } - -private: - //! Intermediate values for each year - typename VCardType::IntermediateValuesType pValuesForTheCurrentYear; - unsigned int pNbYearsParallel; - -}; // class SpilledEnergyAfterCSR - -} // namespace Economy -} // namespace Variable -} // namespace Solver -} // namespace Antares - -#endif // __SOLVER_VARIABLE_ECONOMY_SpilledEnergyAfterCSR_H__ diff --git a/src/tests/src/solver/optimisation/adequacy_patch.cpp b/src/tests/src/solver/optimisation/adequacy_patch.cpp index 8d36a21327..0b8bf48a50 100644 --- a/src/tests/src/solver/optimisation/adequacy_patch.cpp +++ b/src/tests/src/solver/optimisation/adequacy_patch.cpp @@ -24,11 +24,11 @@ std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originTyp bool SetNTCOutsideToInsideToZero) { PROBLEME_HEBDO problem; - problem.adequacyPatchRuntimeData.originAreaMode.resize(1); - problem.adequacyPatchRuntimeData.extremityAreaMode.resize(1); + problem.adequacyPatchRuntimeData.originAreaType.resize(1); + problem.adequacyPatchRuntimeData.extremityAreaType.resize(1); - problem.adequacyPatchRuntimeData.originAreaMode[0] = originType; - problem.adequacyPatchRuntimeData.extremityAreaMode[0] = extremityType; + problem.adequacyPatchRuntimeData.originAreaType[0] = originType; + problem.adequacyPatchRuntimeData.extremityAreaType[0] = extremityType; problem.adqPatchParams = std::unique_ptr(new AdequacyPatchParameters()); auto& adqPatchParams = problem.adqPatchParams; @@ -44,85 +44,11 @@ std::pair setNTCboundsForOneTimeStep(AdequacyPatchMode originTyp double Xmin; double Xmax; - setNTCbounds(Xmax, Xmin, &ValeursDeNTC, 0, &problem); + setBoundsAdqPatch(Xmax, Xmin, &ValeursDeNTC, 0, &problem); 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.originAreaMode.resize(3); - problem.adequacyPatchRuntimeData.extremityAreaMode.resize(3); - - problem.adqPatchParams = std::make_unique(); - const auto& adqPatchParams = problem.adqPatchParams; - - problem.ResultatsHoraires = (RESULTATS_HORAIRES**)malloc(1 * sizeof(void*)); - problem.ResultatsHoraires[0] = (RESULTATS_HORAIRES*)malloc(sizeof(RESULTATS_HORAIRES)); - problem.ResultatsHoraires[0]->ValeursHorairesDeDefaillancePositive - = (double*)malloc(1 * sizeof(double)); - problem.ValeursDeNTC = (VALEURS_DE_NTC_ET_RESISTANCES**)malloc(1 * sizeof(void*)); - problem.ValeursDeNTC[0] - = (VALEURS_DE_NTC_ET_RESISTANCES*)malloc(sizeof(VALEURS_DE_NTC_ET_RESISTANCES)); - problem.ValeursDeNTC[0]->ValeurDuFlux = (double*)malloc(3 * sizeof(double)); - problem.IndexSuivantIntercoOrigine = (int*)malloc(3 * sizeof(int)); - problem.IndexSuivantIntercoExtremite = (int*)malloc(3 * sizeof(int)); - problem.IndexDebutIntercoOrigine = (int*)malloc(1 * sizeof(int)); - problem.IndexDebutIntercoExtremite = (int*)malloc(1 * sizeof(int)); - - // input values - adqPatchParams->SetNTCOutsideToInsideToZero = !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, ignore) = calculateAreaFlowBalance(&problem, Area, hour); - - // free memory - free(problem.IndexDebutIntercoExtremite); - free(problem.IndexSuivantIntercoExtremite); - free(problem.IndexDebutIntercoOrigine); - free(problem.IndexSuivantIntercoOrigine); - free(problem.ValeursDeNTC[0]->ValeurDuFlux); - free(problem.ValeursDeNTC[0]); - free(problem.ValeursDeNTC); - free(problem.ResultatsHoraires[0]->ValeursHorairesDeDefaillancePositive); - free(problem.ResultatsHoraires[0]); - free(problem.ResultatsHoraires); - - // return - return std::make_pair(netPositionInit, densNew); -} - // Virtual -> Virtual (0 -> 0) // No change in bounds is expected BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_virtual_virtual_no_change_expected) @@ -217,266 +143,3 @@ BOOST_AUTO_TEST_CASE(setNTCboundsForOneTimeStep_outside_inside_change_expected_o BOOST_TEST(Xmax == origineExtremite); BOOST_TEST(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_TEST(netPositionInit == 0.0); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive + flowArea2toArea0_positive); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive); - BOOST_TEST(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_TEST(netPositionInit == 0.0); - BOOST_TEST(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_TEST(netPositionInit == +flowArea2toArea0_positive); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_negative); - BOOST_TEST(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_TEST(netPositionInit == 0.0); - BOOST_TEST(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_TEST(netPositionInit == flowArea2toArea0_negative); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive+flowArea2toArea0_negative); - BOOST_TEST(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_TEST(netPositionInit == -flowArea0toArea1_positive+flowArea2toArea0_negative); - BOOST_TEST(densNew == 0.0); -} diff --git a/src/ui/simulator/application/main/internal-ids.h b/src/ui/simulator/application/main/internal-ids.h index 46fb6cb16a..a725240a40 100644 --- a/src/ui/simulator/application/main/internal-ids.h +++ b/src/ui/simulator/application/main/internal-ids.h @@ -134,9 +134,6 @@ enum MenusID mnIDOptionConfigureMCScenarioPlaylist, mnIDOptionOptimizationPrefs, mnIDOptionAdvanced, - mnIDOptionAdequacyPatchOptions, - mnIDOptionAdequacyPatchAreas, - //@} //! \name Window diff --git a/src/ui/simulator/application/main/main.cpp b/src/ui/simulator/application/main/main.cpp index 4d583e08bc..5cbe0fc8d6 100644 --- a/src/ui/simulator/application/main/main.cpp +++ b/src/ui/simulator/application/main/main.cpp @@ -159,8 +159,6 @@ EVT_MENU(mnIDOptionConfigureMCScenarioPlaylist, ApplWnd::evtOnOptionsMCPlaylist) EVT_MENU(mnIDOptionConfigureMCScenarioBuilder, ApplWnd::evtOnOptionsMCScenarioBuilder) EVT_MENU(mnIDOptionOptimizationPrefs, ApplWnd::evtOnOptionsOptimizationPrefs) EVT_MENU(mnIDOptionAdvanced, ApplWnd::evtOnOptionsAdvanced) -EVT_MENU(mnIDOptionAdequacyPatchOptions, ApplWnd::evtOnOptionsAdequacyPatchOptions) -EVT_MENU(mnIDOptionAdequacyPatchAreas, ApplWnd::evtOnOptionsAdequacyPatchAreas) // Window EVT_MENU(mnIDFullscreen, ApplWnd::evtOnFullscreen) @@ -229,7 +227,6 @@ ApplWnd::ApplWnd() : pMenuSimulation(nullptr), pMenuOptions(nullptr), pMenuGeographicTrimming(nullptr), - pMenuAdequacyPatch(nullptr), pMenuWindow(nullptr), pMenuTools(nullptr), pMenuHelp(nullptr), @@ -511,8 +508,6 @@ void ApplWnd::evtOnUpdateGUIAfterStudyIO(bool opened) EnableItem(menu, mnIDOptionConfigureMCScenarioPlaylist, opened); EnableItem(menu, mnIDOptionOptimizationPrefs, opened); EnableItem(menu, mnIDOptionAdvanced, opened); - EnableItem(menu, mnIDOptionAdequacyPatchOptions, opened); - EnableItem(menu, mnIDOptionAdequacyPatchAreas, opened); EnableItem(menu, mnIDInspector, opened); diff --git a/src/ui/simulator/application/main/main.h b/src/ui/simulator/application/main/main.h index 1c27984f14..8a2b9dd4dc 100644 --- a/src/ui/simulator/application/main/main.h +++ b/src/ui/simulator/application/main/main.h @@ -562,10 +562,6 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent void evtOnOptionsOptimizationPrefs(wxCommandEvent& evt); //! Advanced parameters void evtOnOptionsAdvanced(wxCommandEvent& evt); - //! Adequacy Patch Configure - void evtOnOptionsAdequacyPatchOptions(wxCommandEvent& evt); - //! Adequacy Patch Areas - void evtOnOptionsAdequacyPatchAreas(wxCommandEvent& evt); //@} //! \name Event: Menu: Window @@ -679,8 +675,6 @@ class ApplWnd final : public Component::Frame::WxLocalFrame, public Yuni::IEvent wxMenu* pMenuOptions; //! SubMenu: Options > Geographic trimming wxMenuItem* pMenuGeographicTrimming; - //! SubMenu: Options > Adequacy Patch - wxMenuItem* pMenuAdequacyPatch; //! Menu: Window wxMenu* pMenuWindow; //! Menu: Tools diff --git a/src/ui/simulator/application/main/menu.cpp b/src/ui/simulator/application/main/menu.cpp index 4144ce6ace..a2dc034dee 100644 --- a/src/ui/simulator/application/main/menu.cpp +++ b/src/ui/simulator/application/main/menu.cpp @@ -462,23 +462,6 @@ wxMenu* ApplWnd::createMenuOptions() wxT("Advanced parameters"), "images/16x16/empty.png", wxT("Set advanced parameters")); - - delete pMenuAdequacyPatch; - pMenuAdequacyPatch - = pMenuOptions->AppendSubMenu(new wxMenu(), wxT("Adequacy Patch...")); - - wxMenu* adqPatchSubMenu = pMenuAdequacyPatch->GetSubMenu(); - Menu::CreateItem(adqPatchSubMenu, - mnIDOptionAdequacyPatchOptions, - wxT("Options"), - "images/16x16/filter.png", - wxT("Adequacy Patch Options")); - Menu::CreateItem(adqPatchSubMenu, - mnIDOptionAdequacyPatchAreas, - wxT("Areas"), - "images/16x16/filter.png", - wxT("Adequacy Patch Areas")); - it->Enable(false); return pMenuOptions; diff --git a/src/ui/simulator/application/main/options.cpp b/src/ui/simulator/application/main/options.cpp index 4f52f51864..c3b3c05ba0 100644 --- a/src/ui/simulator/application/main/options.cpp +++ b/src/ui/simulator/application/main/options.cpp @@ -32,8 +32,6 @@ #include "../../windows/options/select-output/select-output.h" #include "../../windows/options/playlist/playlist.h" #include "../../windows/options/optimization/optimization.h" -#include "../../windows/options/adequacy-patch/adequacy-patch-options.h" -#include "../../windows/options/adequacy-patch/adequacy-patch-areas.h" #include "../../windows/options/advanced/advanced.h" #include "../../windows/message.h" @@ -126,19 +124,5 @@ void ApplWnd::evtOnOptionsAdvanced(wxCommandEvent&) Dispatcher::GUI::CreateAndShowModal(this); } -void ApplWnd::evtOnOptionsAdequacyPatchOptions(wxCommandEvent&) -{ - Forms::Disabler disabler(*this); - if (Data::Study::Current::Valid()) - Dispatcher::GUI::CreateAndShowModal(this); -} - -void ApplWnd::evtOnOptionsAdequacyPatchAreas(wxCommandEvent&) -{ - Forms::Disabler disabler(*this); - if (Data::Study::Current::Valid()) - Dispatcher::GUI::CreateAndShowModal(this); -} - } // namespace Forms } // namespace Antares diff --git a/src/ui/simulator/cmake/components.cmake b/src/ui/simulator/cmake/components.cmake index dbdcdcb4c7..ef11214fa0 100644 --- a/src/ui/simulator/cmake/components.cmake +++ b/src/ui/simulator/cmake/components.cmake @@ -49,8 +49,6 @@ SET(SRC_TOOLBOX_COM_DBGRID_RENDERERS toolbox/components/datagrid/renderer.hxx toolbox/components/datagrid/renderer.cpp toolbox/components/datagrid/selectionoperation.h - toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h - toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp toolbox/components/datagrid/renderer/area.h toolbox/components/datagrid/renderer/area.cpp toolbox/components/datagrid/renderer/analyzer/areas.h diff --git a/src/ui/simulator/cmake/windows-options.cmake b/src/ui/simulator/cmake/windows-options.cmake index 10d4a08441..e8aef3bfc6 100644 --- a/src/ui/simulator/cmake/windows-options.cmake +++ b/src/ui/simulator/cmake/windows-options.cmake @@ -10,10 +10,6 @@ set(SRC_UI_WINDOWS_OPTIONS windows/options/select-output/select-output.cpp windows/options/playlist/playlist.h windows/options/playlist/playlist.cpp - windows/options/adequacy-patch/adequacy-patch-options.h - windows/options/adequacy-patch/adequacy-patch-options.cpp - windows/options/adequacy-patch/adequacy-patch-areas.h - windows/options/adequacy-patch/adequacy-patch-areas.cpp windows/options/optimization/optimization.h windows/options/optimization/optimization.cpp windows/options/advanced/advanced.h diff --git a/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp b/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp index 0fc11ab286..0bcc59c9f8 100644 --- a/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp +++ b/src/ui/simulator/toolbox/components/datagrid/gridhelper.cpp @@ -199,20 +199,6 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider pStyles[CellStyle::cellStyleFilterUndefined]->SetAlignment(wxALIGN_CENTRE, wxALIGN_CENTRE); } - // Adequacy patch areas - { - pStyles[CellStyle::cellStyleAdqPatchVirtual]->SetAlignment(wxALIGN_CENTRE, - wxALIGN_CENTRE); - pStyles[CellStyle::cellStyleAdqPatchVirtual]->SetTextColour(wxColour(0, 0, 0)); - - pStyles[CellStyle::cellStyleAdqPatchOutside]->SetAlignment(wxALIGN_CENTRE, - wxALIGN_CENTRE); - pStyles[CellStyle::cellStyleAdqPatchOutside]->SetTextColour(wxColour(204, 51, 0)); - - pStyles[CellStyle::cellStyleAdqPatchInside]->SetAlignment(wxALIGN_CENTRE, - wxALIGN_CENTRE); - pStyles[CellStyle::cellStyleAdqPatchInside]->SetTextColour(wxColour(0, 128, 0)); - } } virtual ~GridCellAttrProvider() @@ -316,9 +302,6 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOn); internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOff); internalAppendCSSCode(s, CellStyle::cellStyleFilterUndefined); - internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchVirtual); - internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchOutside); - internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchInside); } void appendCSSForAllCellStyles2(Yuni::String& s) @@ -355,9 +338,6 @@ class GridCellAttrProvider final : public wxGridCellAttrProvider internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOn); internalAppendCSSCode(s, CellStyle::cellStyleFilterSynthesisOff); internalAppendCSSCode(s, CellStyle::cellStyleFilterUndefined); - internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchVirtual); - internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchOutside); - internalAppendCSSCode(s, CellStyle::cellStyleAdqPatchInside); } private: diff --git a/src/ui/simulator/toolbox/components/datagrid/renderer.h b/src/ui/simulator/toolbox/components/datagrid/renderer.h index 482af89d23..785237679b 100644 --- a/src/ui/simulator/toolbox/components/datagrid/renderer.h +++ b/src/ui/simulator/toolbox/components/datagrid/renderer.h @@ -88,10 +88,6 @@ class IRenderer : public Yuni::IEventObserver cellStyleFilterSynthesisOn, cellStyleFilterSynthesisOff, cellStyleFilterUndefined, - cellStyleAdqPatchVirtual, - cellStyleAdqPatchOutside, - cellStyleAdqPatchInside, - cellStyleMax /* Max items in the list */ }; 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 deleted file mode 100644 index e5b7cfd7f1..0000000000 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.cpp +++ /dev/null @@ -1,138 +0,0 @@ -#include "adequacy-patch-area-grid.h" -#include - -using namespace Yuni; - -namespace Antares::Component::Datagrid::Renderer -{ -AdequacyPatchAreaGrid::AdequacyPatchAreaGrid() : pControl(nullptr) -{ -} - -AdequacyPatchAreaGrid::~AdequacyPatchAreaGrid() = default; - -bool AdequacyPatchAreaGrid::valid() const -{ - if (!study) - std::cout << "not valid ! \n"; - return !(!study); -} - -int AdequacyPatchAreaGrid::height() const -{ - return (!study) ? 0 : gridSize(); -} - -wxString AdequacyPatchAreaGrid::columnCaption(int) const -{ - return wxT(" Adequacy Patch Area \n Mode "); -} - -wxString AdequacyPatchAreaGrid::rowCaption(int rowIndx) const -{ - return (!(!study) && (uint)rowIndx < gridSize()) - ? wxStringFromUTF8(study->areas.byIndex[rowIndx]->name) - : wxString(); -} - -bool AdequacyPatchAreaGrid::cellValue(int, int row, const Yuni::String& value) -{ - if (!(!study) && (uint)row < gridSize()) - { - String s = value; - s.trim(); - s.toLower(); - - bool vir = s == "0" || s == "virtual" || s == "v"; - bool ins = s.to() == 2 || s == "inside" || s == "i"; - - if (vir) - study->areas.byIndex[row]->adequacyPatchMode = Data::AdequacyPatch::virtualArea; - else if (ins) - study->areas.byIndex[row]->adequacyPatchMode - = Data::AdequacyPatch::physicalAreaInsideAdqPatch; - else - study->areas.byIndex[row]->adequacyPatchMode - = Data::AdequacyPatch::physicalAreaOutsideAdqPatch; - - onTriggerUpdate(); - Dispatcher::GUI::Refresh(pControl); - return true; - } - return false; -} - -double AdequacyPatchAreaGrid::cellNumericValue(int, int row) const -{ - if (!(!study) && (uint)row < gridSize()) - { - assert(gridSize() != 0); - // for saving into *.txt file - switch (study->areas.byIndex[row]->adequacyPatchMode) - { - case Data::AdequacyPatch::virtualArea: - return 0.; - break; - case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: - return 1.; - break; - case Data::AdequacyPatch::physicalAreaInsideAdqPatch: - return 2.; - break; - default: - break; - } - } - return 0.; -} - -wxString AdequacyPatchAreaGrid::cellValue(int, int row) const -{ - if (!(!study) && (uint)row < gridSize()) - { - switch (study->areas.byIndex[row]->adequacyPatchMode) - { - case Data::AdequacyPatch::virtualArea: - return wxT("virtual"); - break; - case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: - return wxT("outside"); - break; - case Data::AdequacyPatch::physicalAreaInsideAdqPatch: - return wxT("inside"); - break; - default: - break; - } - } - return wxEmptyString; -} - -uint AdequacyPatchAreaGrid::gridSize() const -{ - return study->areas.size(); -} - -IRenderer::CellStyle AdequacyPatchAreaGrid::cellStyle(int, int row) const -{ - if (!(!study) && (uint)row < gridSize()) - { - switch (study->areas.byIndex[row]->adequacyPatchMode) - { - case Data::AdequacyPatch::virtualArea: - return IRenderer::cellStyleAdqPatchVirtual; - break; - case Data::AdequacyPatch::physicalAreaOutsideAdqPatch: - return IRenderer::cellStyleAdqPatchOutside; - break; - case Data::AdequacyPatch::physicalAreaInsideAdqPatch: - return IRenderer::cellStyleAdqPatchInside; - break; - default: - break; - } - } - return IRenderer::cellStyleConstraintNoWeight; -} - -} \ No newline at end of file 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 deleted file mode 100644 index 9d9ebe6d35..0000000000 --- a/src/ui/simulator/toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h +++ /dev/null @@ -1,62 +0,0 @@ -#ifndef __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ -#define __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ - -#include -#include "../renderer.h" -#include "../../../../application/study.h" - -namespace Antares::Component::Datagrid::Renderer -{ -class AdequacyPatchAreaGrid : public IRenderer -{ -public: - AdequacyPatchAreaGrid(); - ~AdequacyPatchAreaGrid() override; - - int width() const override - { - return 1; - } - virtual uint gridSize() const; - - virtual int height() const; - - virtual wxString columnCaption(int colIndx) const; - - virtual wxString rowCaption(int rowIndx) const; - - virtual wxString cellValue(int x, int y) const; - - virtual double cellNumericValue(int x, int y) const; - - virtual bool cellValue(int x, int y, const Yuni::String& value); - - void resetColors(int, int, wxColour&, wxColour&) const override - { - // Do nothing - } - - virtual bool valid() const; - - uint maxWidthResize() const override - { - return 0; - } - IRenderer::CellStyle cellStyle(int col, int row) const override; - - void control(wxWindow* control) - { - pControl = control; - } - - //! An item has been updated - Yuni::Bind onTriggerUpdate; - -private: - wxWindow* pControl; - -}; // class AdequacyPatchAreaGrid - -} - -#endif // __ANTARES_TOOLBOX_COMPONENT_DATAGRID_RENDERER_ADEQUACY_PATCH_AREAS_GRID_H__ \ No newline at end of file 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 deleted file mode 100644 index b03975ebe4..0000000000 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.cpp +++ /dev/null @@ -1,114 +0,0 @@ - -#include "adequacy-patch-areas.h" -#include -#include -#include - -#include -#include "../../../toolbox/resources.h" -#include "../../../application/study.h" -#include "../../../application/main.h" -#include "../../../toolbox/resources.h" -#include "../../../toolbox/create.h" -#include "../../../application/wait.h" -#include "../../../toolbox/components/wizardheader.h" -#include "../../../toolbox/components/datagrid/renderer/adequacy-patch-area-grid.h" -#include "../../message.h" - -using namespace Yuni; - -namespace Antares::Window::Options -{ -BEGIN_EVENT_TABLE(AdequacyPatchAreas, wxDialog) -EVT_MOTION(AdequacyPatchAreas::mouseMoved) -END_EVENT_TABLE() - -AdequacyPatchAreas::AdequacyPatchAreas(wxFrame* parent) : - wxDialog(parent, - wxID_ANY, - wxT("Adequacy Patch Areas"), - wxDefaultPosition, - wxSize(380, 410), - wxCLOSE_BOX | wxCAPTION | wxRESIZE_BORDER) -{ - assert(parent); - - // The current study - auto study = Data::Study::Current::Get(); - - // Title of the Form - SetLabel(wxT("Adequacy Patch Areas")); - SetTitle(GetLabel()); - - auto* sizer = new wxBoxSizer(wxVERTICAL); - - // Header - sizer->Add( - Toolbox::Components::WizardHeader::Create(this, - wxT("Options"), - "images/32x32/orderedlist.png", - wxT("Configure areas mode for adequacy patch")), - 0, - wxALL | wxEXPAND | wxFIXED_MINSIZE); - - sizer->AddSpacer(20); - - // Panel - pPanel = new Component::Panel(this); - sizer->Add(pPanel, 1, wxALL | wxEXPAND | wxRESERVE_SPACE_EVEN_IF_HIDDEN); - - wxSizer* hz = new wxBoxSizer(wxHORIZONTAL); - wxSizer* rightSizer = new wxBoxSizer(wxVERTICAL); - wxButton* btn; - - // Datagrid - auto* renderer = new Component::Datagrid::Renderer::AdequacyPatchAreaGrid(); - renderer->study = study; - auto* grid - = new Component::Datagrid::Component(pPanel, renderer, wxEmptyString, false, true, true); - grid->SetBackgroundColour(GetBackgroundColour()); - pGrid = grid; - renderer->control(grid); - - hz->AddSpacer(13); - hz->Add(grid, 1, wxALL | wxEXPAND); - - hz->Add(rightSizer, 0, wxALL | wxEXPAND); - hz->AddSpacer(20); - pPanel->SetSizer(hz); - sizer->AddSpacer(5); - - sizer->Add(new wxStaticLine(this, wxID_ANY), 0, wxALL | wxEXPAND, 8); - - hz = new wxBoxSizer(wxHORIZONTAL); - btn = Component::CreateButton(this, wxT(" Close "), this, &AdequacyPatchAreas::onClose); - hz->AddStretchSpacer(); - hz->Add(btn, 0, wxEXPAND | wxALL); - hz->Add(20, 5); - sizer->Add(hz, 0, wxALL | wxEXPAND); - sizer->AddSpacer(8); - - sizer->Layout(); - SetSizer(sizer); - - // Recentre the window - Centre(wxBOTH); - - SetAutoLayout(true); - grid->forceRefresh(); -} - -AdequacyPatchAreas::~AdequacyPatchAreas() = default; - -void AdequacyPatchAreas::onClose(const void*) -{ - Dispatcher::GUI::Close(this); -} - -void AdequacyPatchAreas::mouseMoved(wxMouseEvent&) -{ - // Notify other components as well - Antares::Component::Panel::OnMouseMoveFromExternalComponent(); -} - -} 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 deleted file mode 100644 index 3186736a6b..0000000000 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-areas.h +++ /dev/null @@ -1,38 +0,0 @@ -#ifndef __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ -#define __ANTARES_APPLICATION_WINDOWS_ADEQUACY_PATCH_AREAS_H__ - -#include -#include "../../../toolbox/components/datagrid/component.h" -#include -#include - -namespace Antares::Window::Options -{ -class AdequacyPatchAreas final : public wxDialog -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - ** - ** \param parent The parent window - */ - explicit AdequacyPatchAreas(wxFrame* parent); - //! Destructor - ~AdequacyPatchAreas() override; - //@} - -private: - void mouseMoved(wxMouseEvent& evt); - void onClose(const void*); - - Component::Datagrid::Component* pGrid; - wxWindow* pPanel; - DECLARE_EVENT_TABLE() - -}; // class AdequacyPatchAreas - -} - -#endif // __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 deleted file mode 100644 index ddcdf0bf7e..0000000000 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.cpp +++ /dev/null @@ -1,637 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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-patch-options.h" -#include -#include -#include -#include -#include "../../../toolbox/create.h" -#include "../../../toolbox/resources.h" -#include "../../../application/study.h" -#include "../../../application/menus.h" -#include "../../../windows/message.h" -#include -#include - -using namespace Yuni; -using namespace Data::AdequacyPatch; - -namespace Antares::Window::Options -{ -static void addLabelAdqPatch(wxWindow* parent, wxSizer* sizer, const wxChar* text) -{ - sizer->AddSpacer(25); - sizer->AddSpacer(25); - - auto* label = Component::CreateLabel(parent, text, true); - - sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - sizer->AddSpacer(5); - sizer->AddSpacer(5); - sizer->AddSpacer(5); -} - -static void updateButton(Component::Button* button, bool value, std::string_view buttonType) -{ - char type; - if (buttonType == "ntc") - { - type = 'N'; - } - else - { - type = (buttonType == "pto") ? 'P' : 'S'; - } - - assert(button != NULL); - if (value) - { - switch (type) - { - case 'N': - button->image("images/16x16/light_orange.png"); - button->caption(wxT("set to null")); - break; - case 'P': - button->image("images/16x16/tag.png"); - button->caption(wxT("Load")); - break; - default: - button->image("images/16x16/light_green.png"); - button->caption(wxT("true")); - break; - } - } - else - { - switch (type) - { - case 'N': - button->image("images/16x16/light_green.png"); - button->caption(wxT("local values")); - break; - case 'P': - button->image("images/16x16/tag.png"); - button->caption(wxT("DENS")); - break; - default: - button->image("images/16x16/light_orange.png"); - button->caption(wxT("false")); - break; - } - } -} - -AdequacyPatchOptions::AdequacyPatchOptions(wxWindow* parent) : - wxDialog(parent, - wxID_ANY, - wxT("Adequacy Patch Options"), - wxDefaultPosition, - wxDefaultSize, - wxCLOSE_BOX | wxCAPTION | wxCLIP_CHILDREN), - pTargetRef(nullptr) -{ - assert(parent); - - // Title of the Form - SetLabel(wxT("Adequacy Patch Options")); - SetTitle(wxT("Adequacy Patch Options")); - - auto& study = *Data::Study::Current::Get(); - - // Background color - wxColour defaultBgColor = GetBackgroundColour(); - wxColour bgColor(255, 255, 255); - SetBackgroundColour(bgColor); - - auto* sizer = new wxBoxSizer(wxVERTICAL); - - auto* hz = new wxBoxSizer(wxHORIZONTAL); - hz->AddSpacer(6); - hz->Add(Resources::StaticBitmapLoadFromFile(this, wxID_ANY, "images/64x64/db.png"), - 0, - wxALL | wxALIGN_TOP | wxALIGN_CENTER); - hz->AddSpacer(35); - - auto* s = new wxFlexGridSizer(0, 2, 1, 10); - s->AddGrowableCol(0, 1); - hz->Add(s, 1, wxALL | wxEXPAND); - sizer->Add(hz, 0, wxALL | wxEXPAND, 20); - - wxStaticText* label; - Component::Button* button; - Yuni::Bind onPopup; - - { - label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); - button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &AdequacyPatchOptions::onPopupMenuSpecify, - PopupInfo(study.parameters.adqPatch.enabled, wxT("true"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatch = button; - } - // Transmission capacities (NTC) from physical areas outside adequacy patch (area type 1) to - // physical areas inside adequacy patch (area type 2). Used in the first step of adequacy patch - // local matching rule. - { - label = Component::CreateLabel( - this, wxT("NTC from physical areas outside to physical areas inside adequacy patch")); - button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &AdequacyPatchOptions::onPopupMenuNTC, - PopupInfo(study.parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks, - wxT("NTC"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnNTCfromOutToInAdqPatch = button; - } - // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). - // Used in the first step of adequacy patch local matching rule. - { - label = Component::CreateLabel(this, wxT("NTC between physical areas outside adequacy patch")); - button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, - &AdequacyPatchOptions::onPopupMenuNTC, - PopupInfo(study.parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks, - wxT("NTC"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnNTCfromOutToOutAdqPatch = button; - } - // PTO (Price Taking Order). User can choose between DENS and Load - { - label = Component::CreateLabel(this, wxT("Price taking order")); - button = new Component::Button(this, wxT("Day"), "images/16x16/tag.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind(this, &AdequacyPatchOptions::onPopupMenuPTO); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchPTO = button; - } - // Select whether the hurdle cost will be included into curtailment sharing rule cost function - { - label = Component::CreateLabel(this, wxT("Include hurdle cost in CSR optimization")); - button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind( - this, - &AdequacyPatchOptions::onPopupMenuSpecify, - PopupInfo(study.parameters.adqPatch.curtailmentSharing.includeHurdleCost, wxT("true"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchIncludeHurdleCostCsr = button; - } - // Select whether the CSR cost function will be compared prior and after CSR optimization and - // results provided accordingly - { - label = Component::CreateLabel(this, wxT("Check CSR cost function value prior and after CSR")); - button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); - button->SetBackgroundColour(bgColor); - button->menu(true); - onPopup.bind( - this, - &AdequacyPatchOptions::onPopupMenuSpecify, - PopupInfo(study.parameters.adqPatch.curtailmentSharing.checkCsrCostFunction, wxT("true"))); - button->onPopupMenu(onPopup); - s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - pBtnAdequacyPatchCheckCsrCostFunctionValue = button; - } - addLabelAdqPatch(this, s, wxT("Thresholds")); - // Threshold values - { - pThresholdCSRStart = nullptr; - pThresholdLMRviolations = nullptr; - pThresholdCSRVarBoundsRelaxation = nullptr; - pThresholdCSRStart - = insertEdit(this, - s, - wxStringFromUTF8("Initiate curtailment sharing rule"), - wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); - pThresholdLMRviolations - = insertEdit(this, - s, - wxStringFromUTF8("Display local matching rule violations"), - wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); - pThresholdCSRVarBoundsRelaxation - = insertEdit(this, - s, - wxStringFromUTF8("Relax CSR variable boundaries (10^-)"), - wxCommandEventHandler(AdequacyPatchOptions::onEditThresholds)); - } - - { - s->AddSpacer(2); - s->Add(105, 2); - } - - sizer->AddSpacer(10); - - // Buttons - auto panel = new Component::Panel(this); - panel->SetBackgroundColour(defaultBgColor); - auto pnlSizerBtns = new wxBoxSizer(wxHORIZONTAL); - auto pnlSizerBtnsV = new wxBoxSizer(wxVERTICAL); - panel->SetSizer(pnlSizerBtnsV); - pnlSizerBtnsV->AddSpacer(8); - pnlSizerBtnsV->Add(pnlSizerBtns, 1, wxALL | wxEXPAND); - pnlSizerBtnsV->AddSpacer(8); - - button = new Component::Button(panel, - wxT("Reset to default"), - "images/16x16/param_reset.png", - this, - &AdequacyPatchOptions::onResetToDefault); - pnlSizerBtns->Add(22, 5); - pnlSizerBtns->Add(button, 0, wxALL | wxEXPAND); - - pnlSizerBtns->AddStretchSpacer(); - wxButton* pBtnCancel - = Antares::Component::CreateButton(panel, wxT(" Close "), this, &AdequacyPatchOptions::onClose); - pBtnCancel->SetDefault(); - pnlSizerBtns->Add(pBtnCancel, 0, wxALL | wxEXPAND); - pnlSizerBtns->Add(25, 5); - - sizer->Add(new wxStaticLine(this, wxID_ANY), 0, wxALL | wxEXPAND); - sizer->Add(panel, 0, wxALL | wxEXPAND); - - // refresh - Connect(GetId(), wxEVT_MOTION, wxMouseEventHandler(AdequacyPatchOptions::onInternalMotion), nullptr, this); - - refresh(); - SetSizer(sizer); - sizer->Layout(); - - // Recentre the window - sizer->Fit(this); - Centre(wxBOTH); -} - -AdequacyPatchOptions::~AdequacyPatchOptions() = default; - -void AdequacyPatchOptions::onClose(const void*) -{ - Dispatcher::GUI::Close(this); -} - -void AdequacyPatchOptions::onResetToDefault(void*) -{ - auto studyptr = Data::Study::Current::Get(); - if (!(!studyptr)) - { - Window::Message message(this, - wxT("Adequacy Patch Options"), - wxT("Adequacy Patch Options"), - wxT("Do you really want to reset to the default values ?")); - message.add(Window::Message::btnContinue); - message.add(Window::Message::btnCancel, true); - - if (message.showModal() == Window::Message::btnContinue) - { - auto& study = *studyptr; - study.parameters.resetAdqPatchParameters(); - refresh(); - MarkTheStudyAsModified(); - return; - } - } -} - -void AdequacyPatchOptions::onInternalMotion(wxMouseEvent&) -{ - Component::Panel::OnMouseMoveFromExternalComponent(); -} - -void AdequacyPatchOptions::refresh() -{ - auto studyptr = Data::Study::Current::Get(); - if (!studyptr) - return; - // The current study - const auto& study = *studyptr; - - // Adequacy patch - std::string buttonType = "specify"; - // Include adequacy patch - updateButton(pBtnAdequacyPatch, study.parameters.adqPatch.enabled, buttonType); - // Include hurdle cost for CSR - updateButton(pBtnAdequacyPatchIncludeHurdleCostCsr, - study.parameters.adqPatch.curtailmentSharing.includeHurdleCost, - buttonType); - // Check CSR cost function value prior and after CSR optimization - updateButton(pBtnAdequacyPatchCheckCsrCostFunctionValue, - study.parameters.adqPatch.curtailmentSharing.checkCsrCostFunction, - buttonType); - // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside - // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. - buttonType = "ntc"; - updateButton(pBtnNTCfromOutToInAdqPatch, - study.parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks, - buttonType); - // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of - // adequacy patch local matching rule. - updateButton(pBtnNTCfromOutToOutAdqPatch, - study.parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks, - buttonType); - // Price taking order (PTO) for adequacy patch - buttonType = "pto"; - bool isPTOload - = (study.parameters.adqPatch.curtailmentSharing.priceTakingOrder == AdqPatchPTO::isLoad) ? true : false; - updateButton(pBtnAdequacyPatchPTO, isPTOload, buttonType); - - // Threshold values - { - if (pThresholdCSRStart) - pThresholdCSRStart->SetValue( - wxString() << study.parameters.adqPatch.curtailmentSharing.thresholdInitiate); - if (pThresholdLMRviolations) - pThresholdLMRviolations->SetValue( - wxString() - << study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations); - if (pThresholdCSRVarBoundsRelaxation) - pThresholdCSRVarBoundsRelaxation->SetValue( - wxString() - << study.parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation); - } -} - -void AdequacyPatchOptions::onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info) -{ - pTargetRef = &info.rval; - wxMenuItem* it; - - it = Menu::CreateItem(&menu, - wxID_ANY, - wxString() << wxT("local values (") << info.text << wxT(")"), - "images/16x16/light_green.png", - wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectModeInclude), - nullptr, - this); - it = Menu::CreateItem( - &menu, wxID_ANY, wxT("ignore"), "images/16x16/light_orange.png", wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectModeIgnore), - nullptr, - this); -} - -void AdequacyPatchOptions::onPopupMenuNTC(Component::Button&, - wxMenu& menu, - void*, - const PopupInfo& info) -{ - pTargetRef = &info.rval; - wxMenuItem* it; - - it = Menu::CreateItem(&menu, - wxID_ANY, - wxString() << wxT("set to null"), - "images/16x16/light_orange.png", - wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectModeInclude), - nullptr, - this); - it = Menu::CreateItem(&menu, - wxID_ANY, - wxString() << wxT("local values (") << info.text << wxT(")"), - "images/16x16/light_green.png", - wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectModeIgnore), - nullptr, - this); -} - -void AdequacyPatchOptions::onPopupMenuPTO(Component::Button&, wxMenu& menu, void*) -{ - wxMenuItem* it; - - it = Menu::CreateItem( - &menu, wxID_ANY, wxString() << wxT("DENS"), "images/16x16/tag.png", wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectPtoIsDens), - nullptr, - this); - it = Menu::CreateItem( - &menu, wxID_ANY, wxT("Load"), "images/16x16/tag.png", wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectPtoIsLoad), - nullptr, - this); -} - -void AdequacyPatchOptions::onPopupMenuSpecify(Component::Button&, - wxMenu& menu, - void*, - const PopupInfo& info) -{ - pTargetRef = &info.rval; - wxMenuItem* it; - - it = Menu::CreateItem( - &menu, wxID_ANY, wxString() << info.text, "images/16x16/light_green.png", wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectModeInclude), - nullptr, - this); - it = Menu::CreateItem( - &menu, wxID_ANY, wxT("false"), "images/16x16/light_orange.png", wxEmptyString); - menu.Connect(it->GetId(), - wxEVT_COMMAND_MENU_SELECTED, - wxCommandEventHandler(AdequacyPatchOptions::onSelectModeIgnore), - nullptr, - this); -} - -void AdequacyPatchOptions::onSelectModeInclude(wxCommandEvent&) -{ - if (pTargetRef && !*pTargetRef) - { - *pTargetRef = true; - MarkTheStudyAsModified(); - refresh(); - } - pTargetRef = nullptr; -} - -void AdequacyPatchOptions::onSelectModeIgnore(wxCommandEvent&) -{ - if (pTargetRef && *pTargetRef) - { - *pTargetRef = false; - MarkTheStudyAsModified(); - refresh(); - } - pTargetRef = nullptr; -} - -void AdequacyPatchOptions::onSelectPtoIsDens(wxCommandEvent&) -{ - auto study = Data::Study::Current::Get(); - if ((!(!study)) - && (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isDens)) - { - study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isDens; - refresh(); - MarkTheStudyAsModified(); - } -} - -void AdequacyPatchOptions::onSelectPtoIsLoad(wxCommandEvent&) -{ - auto study = Data::Study::Current::Get(); - if ((!(!study)) - && (study->parameters.adqPatch.curtailmentSharing.priceTakingOrder != AdqPatchPTO::isLoad)) - { - study->parameters.adqPatch.curtailmentSharing.priceTakingOrder = AdqPatchPTO::isLoad; - refresh(); - MarkTheStudyAsModified(); - } -} - -wxTextCtrl* AdequacyPatchOptions::insertEdit(wxWindow* parent, - wxSizer* sizer, - const wxString& text, - wxObjectEventFunction method) -{ - auto* label = Component::CreateLabel(parent, text); - auto* edit = new wxTextCtrl(parent, wxID_ANY, wxT("2"), wxDefaultPosition, wxSize(180, 20)); - sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); - sizer->Add(edit, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); - - // Connect event - edit->Connect(edit->GetId(), wxEVT_COMMAND_TEXT_UPDATED, method, nullptr, this); - return edit; -} - -void AdequacyPatchOptions::onEditThresholds(wxCommandEvent& evt) -{ - if (!Data::Study::Current::Valid()) - return; - auto& study = *Data::Study::Current::Get(); - - int id = evt.GetId(); - - if (pThresholdCSRStart && id == pThresholdCSRStart->GetId()) - { - String text; - wxStringToString(pThresholdCSRStart->GetValue(), text); - - float newthreshold; - if (!text.to(newthreshold)) - { - logs.error() << "impossible to update the seed for '" - << "Initiate curtailment sharing rule" - << "'"; - } - else - { - if (newthreshold != study.parameters.adqPatch.curtailmentSharing.thresholdInitiate) - { - study.parameters.adqPatch.curtailmentSharing.thresholdInitiate = newthreshold; - MarkTheStudyAsModified(); - } - } - return; - } - - if (pThresholdLMRviolations && id == pThresholdLMRviolations->GetId()) - { - String text; - wxStringToString(pThresholdLMRviolations->GetValue(), text); - - float newthreshold; - if (!text.to(newthreshold)) - { - logs.error() << "impossible to update the seed for '" - << "Display local matching rule violations" - << "'"; - } - else - { - if (newthreshold - != study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations) - { - study.parameters.adqPatch.curtailmentSharing.thresholdDisplayViolations = newthreshold; - MarkTheStudyAsModified(); - } - } - return; - } - - if (pThresholdCSRVarBoundsRelaxation && id == pThresholdCSRVarBoundsRelaxation->GetId()) - { - String text; - wxStringToString(pThresholdCSRVarBoundsRelaxation->GetValue(), text); - - int newthreshold; - if (!text.to(newthreshold)) - { - logs.error() << "impossible to update the seed for '" - << "Relax CSR variable boundaries (10^-)" - << "'"; - } - else - { - if (newthreshold - != study.parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation) - { - study.parameters.adqPatch.curtailmentSharing.thresholdVarBoundsRelaxation - = newthreshold; - MarkTheStudyAsModified(); - } - } - return; - } -} -} // namespace Antares::Window::Options 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 deleted file mode 100644 index 1a7a311750..0000000000 --- a/src/ui/simulator/windows/options/adequacy-patch/adequacy-patch-options.h +++ /dev/null @@ -1,103 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ -#define __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ - -#include -#include "../../../toolbox/components/button.h" -#include - -#include - -namespace Antares::Window::Options -{ -/*! -** \brief Startup Wizard User Interface -*/ -class AdequacyPatchOptions final : public wxDialog -{ -public: - //! \name Constructor & Destructor - //@{ - /*! - ** \brief Default constructor - ** - ** \param parent The parent window - */ - explicit AdequacyPatchOptions(wxWindow* parent); - //! Destructor - ~AdequacyPatchOptions() override; - //@} - -private: - class PopupInfo final - { - public: - PopupInfo(bool& r, const wxChar* const t) : rval(r), text(t) - { - } - bool& rval; - const wxChar* const text; - }; - - void refresh(); - void onClose(const void*); - void onResetToDefault(void*); - wxTextCtrl* insertEdit(wxWindow* parent, - wxSizer* sizer, - const wxString& text, - wxObjectEventFunction); - - void onSelectPtoIsDens(wxCommandEvent&); - void onSelectPtoIsLoad(wxCommandEvent&); - void onSelectModeInclude(wxCommandEvent& evt); - void onSelectModeIgnore(wxCommandEvent& evt); - - void onPopupMenu(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); - void onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); - void onPopupMenuNTC(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); - void onPopupMenuPTO(Component::Button&, wxMenu& menu, void*); - - void onInternalMotion(wxMouseEvent&); - void onEditThresholds(wxCommandEvent&); - - Component::Button* pBtnAdequacyPatch; - Component::Button* pBtnNTCfromOutToInAdqPatch; - Component::Button* pBtnNTCfromOutToOutAdqPatch; - Component::Button* pBtnAdequacyPatchPTO; - Component::Button* pBtnAdequacyPatchIncludeHurdleCostCsr; - Component::Button* pBtnAdequacyPatchCheckCsrCostFunctionValue; - wxTextCtrl* pThresholdCSRStart; - wxTextCtrl* pThresholdLMRviolations; - wxTextCtrl* pThresholdCSRVarBoundsRelaxation; - bool* pTargetRef; - -}; // class AdequacyPatchOptions - -} - -#endif // __ANTARES_APPLICATION_WINDOWS_OPTIONS_ADEQUACY_PATCH_H__ diff --git a/src/ui/simulator/windows/options/optimization/optimization.cpp b/src/ui/simulator/windows/options/optimization/optimization.cpp index ee8cea6df5..663b3c6db7 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.cpp +++ b/src/ui/simulator/windows/options/optimization/optimization.cpp @@ -45,6 +45,18 @@ namespace Window { namespace Options { +static void SubTitle(wxWindow* parent, wxSizer* sizer, const wxChar* text) +{ + sizer->AddSpacer(25); + sizer->AddSpacer(25); + + auto* label = Component::CreateLabel(parent, text, true); + + sizer->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + sizer->AddSpacer(5); + sizer->AddSpacer(5); + sizer->AddSpacer(5); +} static void ResetButton(Component::Button* button, bool value) { assert(button != NULL); @@ -60,6 +72,21 @@ static void ResetButton(Component::Button* button, bool value) } } +static void ResetButtonAdequacyPatch(Component::Button* button, bool value) +{ + assert(button != NULL); + if (value) + { + button->image("images/16x16/light_orange.png"); + button->caption(wxT("set to null")); + } + else + { + button->image("images/16x16/light_green.png"); + button->caption(wxT("local values")); + } +} + static void ResetButtonSpecify(Component::Button* button, bool value) { assert(button != NULL); @@ -362,6 +389,57 @@ Optimization::Optimization(wxWindow* parent) : s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); s->AddSpacer(2); } + SubTitle(this, s, wxT("Adequacy Patch")); + // Adequacy patch + { + label = Component::CreateLabel(this, wxT("Enable Adequacy patch")); + button = new Component::Button(this, wxT("true"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuSpecify, + PopupInfo(study.parameters.adqPatch.enabled, wxT("true"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdequacyPatch = button; + } + // Transmission capacities (NTC) from physical areas outside adequacy patch (area type 1) to + // physical areas inside adequacy patch (area type 2). Used in the first step of adequacy patch + // local matching rule. + { + label = Component::CreateLabel( + this, wxT("NTC from physical areas outside to physical areas inside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks, + wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdqPatchOutsideInside = button; + } + // Transmission capacities (NTC) between physical areas outside adequacy patch (area type 1). + // Used in the first step of adequacy patch local matching rule. + { + label + = Component::CreateLabel(this, wxT("NTC between physical areas outside adequacy patch")); + button = new Component::Button(this, wxT("Day"), "images/16x16/light_green.png"); + button->SetBackgroundColour(bgColor); + button->menu(true); + onPopup.bind(this, + &Optimization::onPopupMenuAdequacyPatch, + PopupInfo(study.parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks, + wxT("NTC"))); + button->onPopupMenu(onPopup); + s->Add(label, 0, wxRIGHT | wxALIGN_RIGHT | wxALIGN_CENTER_VERTICAL); + s->Add(button, 0, wxLEFT | wxALIGN_LEFT | wxALIGN_CENTER_VERTICAL); + pBtnAdqPatchOutsideOutside = button; + } + { s->AddSpacer(2); s->Add(105, 2); @@ -445,7 +523,11 @@ void Optimization::onResetToDefault(void*) study.parameters.include.reserve.primary = true; study.parameters.include.reserve.spinning = true; study.parameters.include.exportMPS = Data::mpsExportStatus::NO_EXPORT; + study.parameters.adqPatch.enabled = false; + study.parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks = true; + study.parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks = true; study.parameters.simplexOptimizationRange = Data::sorWeek; + study.parameters.include.unfeasibleProblemBehavior = Data::UnfeasibleProblemBehavior::ERROR_MPS; @@ -492,7 +574,17 @@ void Optimization::refresh() // Export mps pBtnExportMPS->image(mpsExportIcon(study.parameters.include.exportMPS)); pBtnExportMPS->caption(Data::mpsExportStatusToString(study.parameters.include.exportMPS)); - + // Adequacy patch + ResetButtonSpecify(pBtnAdequacyPatch, study.parameters.adqPatch.enabled); + // NTC from physical areas outside adequacy patch (area type 1) to physical areas inside + // adequacy patch (area type 2). Used in the first step of adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdqPatchOutsideInside, + study.parameters.adqPatch.localMatching.setToZeroOutsideInsideLinks); + // NTC between physical areas outside adequacy patch (area type 1). Used in the first step of + // adequacy patch local matching rule. + ResetButtonAdequacyPatch(pBtnAdqPatchOutsideOutside, + study.parameters.adqPatch.localMatching.setToZeroOutsideOutsideLinks); + // Unfeasible problem behavior pBtnUnfeasibleProblemBehavior->image( Data::getIcon(study.parameters.include.unfeasibleProblemBehavior)); @@ -536,6 +628,36 @@ void Optimization::onPopupMenu(Component::Button&, wxMenu& menu, void*, const Po this); } +void Optimization::onPopupMenuAdequacyPatch(Component::Button&, + wxMenu& menu, + void*, + const PopupInfo& info) +{ + pTargetRef = &info.rval; + wxMenuItem* it; + + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("set to null"), + "images/16x16/light_orange.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(Optimization::onSelectModeInclude), + nullptr, + this); + it = Menu::CreateItem(&menu, + wxID_ANY, + wxString() << wxT("local values (") << info.text << wxT(")"), + "images/16x16/light_green.png", + wxEmptyString); + menu.Connect(it->GetId(), + wxEVT_COMMAND_MENU_SELECTED, + wxCommandEventHandler(Optimization::onSelectModeIgnore), + nullptr, + this); +} + void Optimization::onPopupMenuSpecify(Component::Button&, wxMenu& menu, void*, diff --git a/src/ui/simulator/windows/options/optimization/optimization.h b/src/ui/simulator/windows/options/optimization/optimization.h index f70049f7ad..c29ec70aa2 100644 --- a/src/ui/simulator/windows/options/optimization/optimization.h +++ b/src/ui/simulator/windows/options/optimization/optimization.h @@ -113,7 +113,8 @@ class Optimization final : public wxDialog void onPopupMenuLinkType(Component::Button&, wxMenu& menu, void*); void onPopupMenuExportMPSstatus(Component::Button&, wxMenu& menu, void*); void onPopupMenuUnfeasibleBehavior(Component::Button&, wxMenu& menu, void*); - + void onPopupMenuAdequacyPatch(Component::Button&, wxMenu& menu, void*, const PopupInfo& info); + void onInternalMotion(wxMouseEvent&); private: @@ -130,6 +131,9 @@ class Optimization final : public wxDialog Component::Button* pBtnSimplexOptimizationRange; Component::Button* pBtnExportMPS; + Component::Button* pBtnAdequacyPatch; + Component::Button* pBtnAdqPatchOutsideInside; + Component::Button* pBtnAdqPatchOutsideOutside; Component::Button* pBtnUnfeasibleProblemBehavior; bool* pTargetRef; From 5e3105941d008f5c26a17e0f01cf5a353978ed83 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 13 Feb 2023 16:08:55 +0100 Subject: [PATCH 378/490] UI "Hydro Levels" -> "Hydro Initial Levels" --- src/ui/simulator/application/main/build/scenario-builder.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/ui/simulator/application/main/build/scenario-builder.cpp b/src/ui/simulator/application/main/build/scenario-builder.cpp index 645792f9ca..1873dd59ad 100644 --- a/src/ui/simulator/application/main/build/scenario-builder.cpp +++ b/src/ui/simulator/application/main/build/scenario-builder.cpp @@ -205,7 +205,7 @@ class solarScBuilderPageMaker final : public simpleScBuilderPageMaker } }; -// Hydro levels ... +// Hydro Initial levels ... class hydroLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker { using simpleScBuilderPageMaker::simpleScBuilderPageMaker; @@ -216,7 +216,7 @@ 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")); } }; From c2a1424ea2e762d8c95f038aaf502272f3cf1e4b Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 13 Feb 2023 17:44:36 +0100 Subject: [PATCH 379/490] UI Hydro Final Levels --- .../main/build/scenario-builder.cpp | 24 ++++++++++++++++--- src/ui/simulator/application/main/main.h | 3 ++- 2 files changed, 23 insertions(+), 4 deletions(-) diff --git a/src/ui/simulator/application/main/build/scenario-builder.cpp b/src/ui/simulator/application/main/build/scenario-builder.cpp index 1873dd59ad..2ae285a5f4 100644 --- a/src/ui/simulator/application/main/build/scenario-builder.cpp +++ b/src/ui/simulator/application/main/build/scenario-builder.cpp @@ -206,7 +206,7 @@ class solarScBuilderPageMaker final : public simpleScBuilderPageMaker }; // Hydro Initial levels ... -class hydroLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker +class hydroInitialLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker { using simpleScBuilderPageMaker::simpleScBuilderPageMaker; @@ -220,6 +220,21 @@ class hydroLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker } }; +// 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")); + } +}; + // Links NTC ... class ntcScBuilderPageMaker final : public simpleScBuilderPageMaker { @@ -372,9 +387,12 @@ 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/main.h b/src/ui/simulator/application/main/main.h index 6df0aba8da..a806d1f7d9 100644 --- a/src/ui/simulator/application/main/main.h +++ b/src/ui/simulator/application/main/main.h @@ -703,7 +703,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; From b8cb4b741d3c02497dc6e852758d93e794f10ecb Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 13 Feb 2023 18:42:43 +0100 Subject: [PATCH 380/490] UI Hydro Final Levels - Structures --- src/libs/antares/CMakeLists.txt | 2 + .../scenario-builder/hydroFinalLevelsData.cpp | 94 ++++++++++++++ .../scenario-builder/hydroFinalLevelsData.h | 117 ++++++++++++++++++ .../antares/study/scenario-builder/rules.cpp | 19 +++ .../antares/study/scenario-builder/rules.h | 6 +- .../main/build/scenario-builder.cpp | 4 +- src/ui/simulator/cmake/components.cmake | 2 + ...io-builder-hydro-final-levels-renderer.cpp | 86 +++++++++++++ ...ario-builder-hydro-final-levels-renderer.h | 56 +++++++++ 9 files changed, 384 insertions(+), 2 deletions(-) create mode 100644 src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp create mode 100644 src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h create mode 100644 src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.cpp create mode 100644 src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h diff --git a/src/libs/antares/CMakeLists.txt b/src/libs/antares/CMakeLists.txt index 3421188970..5e59f6c8f0 100644 --- a/src/libs/antares/CMakeLists.txt +++ b/src/libs/antares/CMakeLists.txt @@ -37,6 +37,8 @@ set(SRC_STUDY_SCENARIO_BUILDER study/scenario-builder/TSnumberData.cpp study/scenario-builder/hydroLevelsData.h study/scenario-builder/hydroLevelsData.cpp + study/scenario-builder/hydroFinalLevelsData.h + study/scenario-builder/hydroFinalLevelsData.cpp study/scenario-builder/rules.h study/scenario-builder/rules.hxx study/scenario-builder/rules.cpp diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp new file mode 100644 index 0000000000..e04f26a9a3 --- /dev/null +++ b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp @@ -0,0 +1,94 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "hydroFinalLevelsData.h" +#include "scBuilderUtils.h" + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +bool hydroFinalLevelsData::reset(const Study& study) +{ + const uint nbYears = study.parameters.nbYears; + + pHydroFinalLevelsRules.reset(study.areas.size(), nbYears); + pHydroFinalLevelsRules.fill(std::nan("")); + + return true; +} + +void hydroFinalLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const +{ + // Prefix + CString<512, false> prefix; + prefix += "hfl,"; + + // Turning values into strings (precision 4) + std::ostringstream value_into_string; + value_into_string << std::setprecision(4); + + // Foreach year + assert(pHydroFinalLevelsRules.width == study.areas.size()); + for (uint index = 0; index != pHydroFinalLevelsRules.width; ++index) + { + // alias to the current column + const MatrixType::ColumnType& col = pHydroFinalLevelsRules[index]; + // Foreach area... + for (uint y = 0; y != pHydroFinalLevelsRules.height; ++y) + { + 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 << " = " + << value_into_string.str() << '\n'; + value_into_string.str(string()); // Clearing converter + } + } +} + +void hydroFinalLevelsData::set_value(uint x, uint y, double value) +{ + pHydroFinalLevelsRules.entry[y][x] = value; +} + +bool hydroFinalLevelsData::apply(Study& study) +{ + study.scenarioHydroLevels.copyFrom(pHydroFinalLevelsRules); + return true; +} + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h new file mode 100644 index 0000000000..1655b0d308 --- /dev/null +++ b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h @@ -0,0 +1,117 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_FINAL_LEVELS_H__ +#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_FINAL_LEVELS_H__ + +#include "scBuilderDataInterface.h" + +namespace Antares +{ +namespace Data +{ +namespace ScenarioBuilder +{ +/*! +** \brief Rules for hydro final levels, for all years and areas +*/ +class hydroFinalLevelsData final : public dataInterface +// TODO CR25: can i inherit methods from hydroLevelsData (must delete final in its declaration?!) +{ +public: + //! Matrix + using MatrixType = Matrix; + +public: + // We use default constructor and destructor + + //! \name Data manipulation + //@{ + /*! + ** \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 set(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 final levels overlay (0 if auto) + MatrixType pHydroFinalLevelsRules; + +}; // class hydroLevelsData + +// class hydroLevelsData : inline functions + +inline void hydroFinalLevelsData::set(uint areaindex, uint year, double value) +{ + assert(areaindex < pHydroFinalLevelsRules.width); + if (year < pHydroFinalLevelsRules.height) + pHydroFinalLevelsRules[areaindex][year] = value; +} + +inline uint hydroFinalLevelsData::width() const +{ + return pHydroFinalLevelsRules.width; +} + +inline uint hydroFinalLevelsData::height() const +{ + return pHydroFinalLevelsRules.height; +} + +inline double hydroFinalLevelsData::get_value(uint x, uint y) const +{ + return pHydroFinalLevelsRules.entry[y][x]; +} + +} // namespace ScenarioBuilder +} // namespace Data +} // namespace Antares + +#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_FINAL_LEVELS_H__ diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index 5cb053c4fd..5abbc6ce17 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -65,6 +65,7 @@ void Rules::saveToINIFile(Yuni::IO::File::Stream& file) const } // hydro levels hydroLevels.saveToINIFile(study_, file); + hydroFinalLevels.saveToINIFile(study_, file); } file << '\n'; } @@ -100,6 +101,7 @@ bool Rules::reset() } hydroLevels.reset(study_); + hydroFinalLevels.reset(study_); // links NTC linksNTC.clear(); @@ -268,6 +270,20 @@ bool Rules::readHydroLevels(const AreaName::Vector& splitKey, String value, bool 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 val = fromStringToHydroLevel(value, 1.); + hydroFinalLevels.set(area->index, year, val); + return true; +} + Data::AreaLink* Rules::getLink(const AreaName& fromAreaName, const AreaName& toAreaName, bool updaterMode) @@ -329,6 +345,8 @@ bool Rules::readLine(const AreaName::Vector& splitKey, String value, bool update return readSolar(splitKey, value, updaterMode); else if (kind_of_scenario == "hl") return readHydroLevels(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); return false; @@ -350,6 +368,7 @@ bool Rules::apply() returned_status = linksNTC[i].apply(study_) && returned_status; } returned_status = hydroLevels.apply(study_) && returned_status; + returned_status = hydroFinalLevels.apply(study_) && returned_status; } else returned_status = false; diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index 8e7bb778f7..ce07abae10 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -32,6 +32,7 @@ #include "../fwd.h" #include "TSnumberData.h" #include "hydroLevelsData.h" +#include "hydroFinalLevelsData.h" #include #include @@ -117,8 +118,10 @@ class Rules final : private Yuni::NonCopyable //! Renewable (array [0..pAreaCount - 1]) std::vector renewable; - //! hydro levels + //! hydro initial levels hydroLevelsData hydroLevels; + //! hydro final levels + hydroFinalLevelsData hydroFinalLevels; // Links NTC std::vector linksNTC; @@ -132,6 +135,7 @@ class Rules final : private Yuni::NonCopyable 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 readFinalHydroLevels(const AreaName::Vector& instrs, String value, bool updaterMode); bool readLink(const AreaName::Vector& instrs, String value, bool updaterMode); Data::Area* getArea(const AreaName& areaname, bool updaterMode); diff --git a/src/ui/simulator/application/main/build/scenario-builder.cpp b/src/ui/simulator/application/main/build/scenario-builder.cpp index 2ae285a5f4..12d68b935d 100644 --- a/src/ui/simulator/application/main/build/scenario-builder.cpp +++ b/src/ui/simulator/application/main/build/scenario-builder.cpp @@ -41,6 +41,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; @@ -227,7 +228,7 @@ class hydroFinalLevelsScBuilderPageMaker final : public simpleScBuilderPageMaker Renderer::ScBuilderRendererBase* getRenderer() override { - return new_check_allocation(); + return new_check_allocation(); } Notebook::Page* addPageToNotebook() override { @@ -390,6 +391,7 @@ void ApplWnd::createNBScenarioBuilder() hydroInitialLevelsScBuilderPageMaker hydroInitialLevelsSBpageMaker(scenarioBuilderPanel, pScenarioBuilderNotebook); pageScBuilderHydroInitialLevels = hydroInitialLevelsSBpageMaker.createPage(); + hydroFinalLevelsScBuilderPageMaker hydroFinalLevelsSBpageMaker(scenarioBuilderPanel, pScenarioBuilderNotebook); pageScBuilderHydroFinalLevels = hydroFinalLevelsSBpageMaker.createPage(); diff --git a/src/ui/simulator/cmake/components.cmake b/src/ui/simulator/cmake/components.cmake index 2b7c0119dd..8e1915b039 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 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..f8fffbfea3 --- /dev/null +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.cpp @@ -0,0 +1,86 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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) + { + if ((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) + { + if ((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..ddbdd39eef --- /dev/null +++ b/src/ui/simulator/toolbox/components/datagrid/renderer/scenario-builder-hydro-final-levels-renderer.h @@ -0,0 +1,56 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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__ From 4e71a8d2922a62c1c476f91afb142e3ae3af27bd Mon Sep 17 00:00:00 2001 From: Milos A Date: Tue, 14 Feb 2023 16:38:05 +0100 Subject: [PATCH 381/490] UI Hydro Final Levels - Structures - fix --- .../antares/study/scenario-builder/hydroFinalLevelsData.cpp | 2 +- src/libs/antares/study/study.h | 3 ++- 2 files changed, 3 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp index e04f26a9a3..891db13737 100644 --- a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp @@ -85,7 +85,7 @@ void hydroFinalLevelsData::set_value(uint x, uint y, double value) bool hydroFinalLevelsData::apply(Study& study) { - study.scenarioHydroLevels.copyFrom(pHydroFinalLevelsRules); + study.scenarioFinalHydroLevels.copyFrom(pHydroFinalLevelsRules); return true; } diff --git a/src/libs/antares/study/study.h b/src/libs/antares/study/study.h index dba3d07f0d..ba9e7cb3ec 100644 --- a/src/libs/antares/study/study.h +++ b/src/libs/antares/study/study.h @@ -676,7 +676,8 @@ class Study final : public Yuni::NonCopyable, public IObject, public Laye //@} Matrix scenarioHydroLevels; - + // Hydro Final Levels + Matrix scenarioFinalHydroLevels; /*! ** \brief Runtime informations ** From 2145eff3e06210eb1f4e86100cdc1097939e3a65 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 16 Feb 2023 23:25:53 +0100 Subject: [PATCH 382/490] pre-checks moved to solver.hxx --- src/solver/cmake/simulation.cmake | 2 + ...hydro-final-reservoir-level-pre-checks.cpp | 107 ++++++++++++++++++ .../hydro-final-reservoir-level-pre-checks.h | 40 +++++++ src/solver/simulation/solver.hxx | 6 + 4 files changed, 155 insertions(+) create mode 100644 src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp create mode 100644 src/solver/simulation/hydro-final-reservoir-level-pre-checks.h diff --git a/src/solver/cmake/simulation.cmake b/src/solver/cmake/simulation.cmake index b59daa6058..4f882f2c89 100644 --- a/src/solver/cmake/simulation.cmake +++ b/src/solver/cmake/simulation.cmake @@ -23,6 +23,8 @@ set(SRC_SIMULATION simulation/timeseries-numbers.cpp simulation/apply-scenario.h simulation/apply-scenario.cpp + simulation/hydro-final-reservoir-level-pre-checks.h + simulation/hydro-final-reservoir-level-pre-checks.cpp # Solver diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp new file mode 100644 index 0000000000..5d2d51ca67 --- /dev/null +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -0,0 +1,107 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "hydro-final-reservoir-level-pre-checks.h" +#include +// #include "../solver/simulation/sim_extern_variables_globales.h" + +namespace Antares +{ +namespace Solver +{ +void FinalReservoirLevelPreChecks(Data::Study& study) +{ + bool preChecksPasses = true; + for (uint tsIndex = 0; tsIndex != study.scenarioFinalHydroLevels.height; ++tsIndex) + { + study.areas.each( + [&](Data::Area& area) + { + // TODO CR25: + /*at this point the pre-checks are done for all MC before running the simulation + and the simulation is ended immediately not waisting user time! + However, at this point "tsIndex = (uint)ptchro.Hydraulique" is not assigned yet + so the pre-checks are done for all MC years (whether they are used or not in hydro + scenario-builder) this can lead to error reporting for MC years that are not used (not + the case when pre-checks done im management.cpp) + */ + // auto& ptchro = *NumeroChroniquesTireesParPays[numSpace][area.index]; + auto& inflowsmatrix = area.hydro.series->storage; + // auto tsIndex = (uint)ptchro.Hydraulique; + auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; + double initialReservoirLevel = study.scenarioHydroLevels[area.index][tsIndex]; + double finalReservoirLevel = study.scenarioFinalHydroLevels[area.index][tsIndex]; + + if (area.hydro.reservoirManagement && !area.hydro.useWaterValue + && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) + { + // collect data for pre-checks + double reservoirCapacity = area.hydro.reservoirCapacity; + double lowLevelLastDay + = area.hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + double highLevelLastDay + = area.hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + double totalYearInflows = 0.0; + // calculate yearly inflows + for (uint day = 0; day < DAYS_PER_YEAR; ++day) + { + totalYearInflows += srcinflows[day]; + } + // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ + // yearly_inflows + if ((finalReservoirLevel - initialReservoirLevel) * reservoirCapacity + > totalYearInflows * 24) + { + logs.error() << "Year: " << tsIndex + 1 << ". Area: " << area.name + << ". Incompatible total inflows: " << totalYearInflows + << " with initial: " << initialReservoirLevel + << " and final: " << finalReservoirLevel << " reservoir levels."; + preChecksPasses = false; + } + // pre-check 2 -> final reservoir level set by the user is within the + // rule curves for the final day + if (finalReservoirLevel < lowLevelLastDay + || finalReservoirLevel > highLevelLastDay) + { + logs.error() << "Year: " << tsIndex + 1 << ". Area: " << area.name + << ". Specifed final reservoir level: " << finalReservoirLevel + << " is incompatible with reservoir level rule curve [" + << lowLevelLastDay << " , " << highLevelLastDay << "]"; + preChecksPasses = false; + } + } + }); + } + if (!preChecksPasses) + { + logs.fatal() << "At least one year has failed final reservoir level pre-checks."; + AntaresSolverEmergencyShutdown(); + } +} + +} // namespace Solver +} // namespace Antares \ No newline at end of file diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.h b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.h new file mode 100644 index 0000000000..35cb06989d --- /dev/null +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.h @@ -0,0 +1,40 @@ +/* +** Copyright 2007-2018 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 + +namespace Antares +{ +namespace Solver +{ +void FinalReservoirLevelPreChecks(Data::Study& study); +} // namespace Solver +} // namespace Antares + +#endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index 28c35669eb..119ad24dfa 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -37,6 +37,7 @@ #include "../aleatoire/alea_fonctions.h" #include "timeseries-numbers.h" #include "apply-scenario.h" +#include "hydro-final-reservoir-level-pre-checks.h" #include #include "../ts-generator/generator.h" @@ -344,7 +345,10 @@ void ISimulation::run() } if (parameters.useCustomScenario) + { ApplyCustomScenario(study); + FinalReservoirLevelPreChecks(study); + } // Launching the simulation for all years logs.info() << "MC-Years : [" << (study.runtime->rangeLimits.year[Data::rangeBegin] + 1) @@ -1290,6 +1294,8 @@ void ISimulation::computeRandomNumbers(randomNumbers& randomForYears, double randomLevel = pHydroManagement.randomReservoirLevel( min[firstDayOfMonth], avg[firstDayOfMonth], max[firstDayOfMonth]); + // here in solver the random resevoair level is calulated! + // to late for CR25 pre-checks!? // Possibly update the intial level from scenario builder if (study.parameters.useCustomScenario) From c77e31807ddfa8157a152261951d2d73fcc27de5 Mon Sep 17 00:00:00 2001 From: Milos A Date: Sat, 18 Feb 2023 13:43:16 +0100 Subject: [PATCH 383/490] fix - SP TimeSeries are in MWh (energy) not MW (power) --- .../simulation/hydro-final-reservoir-level-pre-checks.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp index 5d2d51ca67..7ffef78c95 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -74,7 +74,7 @@ void FinalReservoirLevelPreChecks(Data::Study& study) // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows if ((finalReservoirLevel - initialReservoirLevel) * reservoirCapacity - > totalYearInflows * 24) + > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh (energy) { logs.error() << "Year: " << tsIndex + 1 << ". Area: " << area.name << ". Incompatible total inflows: " << totalYearInflows From a0de74d4f13dc9497b05f05709d87668e79a2fba Mon Sep 17 00:00:00 2001 From: Milos A Date: Sun, 19 Feb 2023 02:58:19 +0100 Subject: [PATCH 384/490] prepare deltaReservoirLevel --- src/libs/antares/study/parts/hydro/container.h | 2 ++ .../simulation/hydro-final-reservoir-level-pre-checks.cpp | 4 ++++ 2 files changed, 6 insertions(+) diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 7916c02803..44805d500b 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -171,6 +171,8 @@ class PartHydro PreproHydro* prepro; //! Data for time-series DataSeriesHydro* series; + //! difference between initial and final reservoir levels for all scenario-builder years + std::vector finalReservoirLevelCorrection; }; // class PartHydro diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp index 7ffef78c95..929818e214 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -41,6 +41,7 @@ void FinalReservoirLevelPreChecks(Data::Study& study) study.areas.each( [&](Data::Area& area) { + double deltaReservoirLevel = 0.0; // TODO CR25: /*at this point the pre-checks are done for all MC before running the simulation and the simulation is ended immediately not waisting user time! @@ -59,6 +60,8 @@ void FinalReservoirLevelPreChecks(Data::Study& study) if (area.hydro.reservoirManagement && !area.hydro.useWaterValue && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) { + // deltaReservoirLevel + deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; // collect data for pre-checks double reservoirCapacity = area.hydro.reservoirCapacity; double lowLevelLastDay @@ -94,6 +97,7 @@ void FinalReservoirLevelPreChecks(Data::Study& study) preChecksPasses = false; } } + area.hydro.finalReservoirLevelCorrection.push_back(deltaReservoirLevel); }); } if (!preChecksPasses) From 45593383acf59177c0f2afc40769ba213e381120 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 20 Feb 2023 00:02:25 +0100 Subject: [PATCH 385/490] pre-check fix --- .../simulation/hydro-final-reservoir-level-pre-checks.cpp | 6 +++++- 1 file changed, 5 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp index 929818e214..f956455a74 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -63,6 +63,10 @@ void FinalReservoirLevelPreChecks(Data::Study& study) // deltaReservoirLevel deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; // collect data for pre-checks + uint initReservoirLvlMonth + = area.hydro.initializeReservoirLevelDate; // month [0-11] + uint initReservoirLvlDay + = study.calendar.months[initReservoirLvlMonth].daysYear.first; double reservoirCapacity = area.hydro.reservoirCapacity; double lowLevelLastDay = area.hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; @@ -70,7 +74,7 @@ void FinalReservoirLevelPreChecks(Data::Study& study) = area.hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; double totalYearInflows = 0.0; // calculate yearly inflows - for (uint day = 0; day < DAYS_PER_YEAR; ++day) + for (uint day = initReservoirLvlDay; day < DAYS_PER_YEAR; ++day) { totalYearInflows += srcinflows[day]; } From ed543af164334013fa8a055f267469a0bac030bd Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 20 Feb 2023 11:56:45 +0100 Subject: [PATCH 386/490] fix-error-std:: --- .../antares/study/scenario-builder/hydroFinalLevelsData.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp index 891db13737..f359e751d1 100644 --- a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp @@ -73,7 +73,7 @@ void hydroFinalLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Str value_into_string << value; file << prefix << study.areas.byIndex[index]->id << ',' << y << " = " << value_into_string.str() << '\n'; - value_into_string.str(string()); // Clearing converter + value_into_string.str(std::string()); // Clearing converter } } } From 0e279c086b97d4a44682c1ae18889562c80de988 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 27 Feb 2023 22:00:59 +0100 Subject: [PATCH 387/490] enum FinalReservoirLevelMode --- src/libs/antares/study/fwd.h | 10 ++++++++++ 1 file changed, 10 insertions(+) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index 84e5ed4a82..e99257f5fd 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -242,6 +242,16 @@ enum TimeSeries }; // enum TimeSeries +enum FinalReservoirLevelMode +{ + //! Case-1: Day-1 -> Day-365 (complete year) + completeYear = 1, + //! Case-2A: Day-? -> Day-365 (reservoir level not initialized at 1.Jan, Last Simulation Day = 365) + //! Case-2B: Day-1 -> Day-? (reservoir level initialized at 1.Jan, Last Simulation Day != 365) + //! Case-2C: Day-? -> Day-? (reservoir level not initialized at 1.Jan, Last Simulation Day != 365) + incompleteYear = 2, +}; // enum Final Reservoir Level Mode + template struct TimeSeriesBitPatternIntoIndex; From 1dc81410bf0a11a23326401b6463da0dc854efb3 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 27 Feb 2023 22:01:13 +0100 Subject: [PATCH 388/490] FinalReservoirLevelRuntimeData --- .../antares/study/parts/hydro/container.h | 21 +++++++++++++++++-- 1 file changed, 19 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 44805d500b..1d9a44166f 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -34,6 +34,22 @@ namespace Antares::Data { +/*! + ** \brief Final Reservoir Level data for a single area + */ +class FinalReservoirLevelRuntimeData +{ +private: + using finalResLevelMode = Antares::Data::FinalReservoirLevelMode; + +public: + std::vector includeFinalReservoirLevel; + std::vector finResLevelMode; + std::vector endLevel; + std::vector deltaLevel; + std::vector endMonthIndex; +}; + /*! ** \brief Hydro for a single area */ @@ -171,8 +187,9 @@ class PartHydro PreproHydro* prepro; //! Data for time-series DataSeriesHydro* series; - //! difference between initial and final reservoir levels for all scenario-builder years - std::vector finalReservoirLevelCorrection; + + //! Data for final reservoir level + FinalReservoirLevelRuntimeData finalReservoirLevelRuntimeData; }; // class PartHydro From 883a8a8f8552e7a34b18d0892c11dee430d961e3 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 27 Feb 2023 22:01:38 +0100 Subject: [PATCH 389/490] pre-check update --- ...hydro-final-reservoir-level-pre-checks.cpp | 154 +++++++++++++++--- 1 file changed, 127 insertions(+), 27 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp index f956455a74..1c246ce045 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -27,7 +27,6 @@ #include "hydro-final-reservoir-level-pre-checks.h" #include -// #include "../solver/simulation/sim_extern_variables_globales.h" namespace Antares { @@ -36,54 +35,156 @@ namespace Solver void FinalReservoirLevelPreChecks(Data::Study& study) { bool preChecksPasses = true; - for (uint tsIndex = 0; tsIndex != study.scenarioFinalHydroLevels.height; ++tsIndex) + // Last Day of the simulation + uint simEndDay = study.parameters.simulationDays.end; + for (uint yearIndex = 0; yearIndex != study.scenarioFinalHydroLevels.height; ++yearIndex) { study.areas.each( [&](Data::Area& area) { - double deltaReservoirLevel = 0.0; - // TODO CR25: - /*at this point the pre-checks are done for all MC before running the simulation - and the simulation is ended immediately not waisting user time! - However, at this point "tsIndex = (uint)ptchro.Hydraulique" is not assigned yet - so the pre-checks are done for all MC years (whether they are used or not in hydro - scenario-builder) this can lead to error reporting for MC years that are not used (not - the case when pre-checks done im management.cpp) - */ - // auto& ptchro = *NumeroChroniquesTireesParPays[numSpace][area.index]; + // general data + const Data::DataSeriesHydro& data = *area.hydro.series; + int tsIndex = data.timeseriesNumbers[0][yearIndex]; auto& inflowsmatrix = area.hydro.series->storage; - // auto tsIndex = (uint)ptchro.Hydraulique; auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; - double initialReservoirLevel = study.scenarioHydroLevels[area.index][tsIndex]; - double finalReservoirLevel = study.scenarioFinalHydroLevels[area.index][tsIndex]; + double initialReservoirLevel = study.scenarioHydroLevels[area.index][yearIndex]; + double finalReservoirLevel = study.scenarioFinalHydroLevels[area.index][yearIndex]; + double deltaReservoirLevel = 0.0; + int simEndRealMonth = 0; + // FinalReservoirLevelRuntimeData + auto& finLevData = area.hydro.finalReservoirLevelRuntimeData; + finLevData.includeFinalReservoirLevel.push_back(false); + finLevData.finResLevelMode.push_back( + Antares::Data::FinalReservoirLevelMode::completeYear); + finLevData.deltaLevel.push_back(deltaReservoirLevel); + finLevData.endLevel.push_back(deltaReservoirLevel); + finLevData.endMonthIndex.push_back(simEndRealMonth); if (area.hydro.reservoirManagement && !area.hydro.useWaterValue && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) { + // simEndDayReal + uint simEndDayReal = simEndDay; // deltaReservoirLevel deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; // collect data for pre-checks - uint initReservoirLvlMonth + int initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; // month [0-11] - uint initReservoirLvlDay + int initReservoirLvlDay = study.calendar.months[initReservoirLvlMonth].daysYear.first; double reservoirCapacity = area.hydro.reservoirCapacity; + double totalYearInflows = 0.0; + // FinalReservoirLevelRuntimeData + finLevData.includeFinalReservoirLevel.at(yearIndex) = true; + finLevData.endLevel.at(yearIndex) = finalReservoirLevel; + finLevData.deltaLevel.at(yearIndex) = deltaReservoirLevel; + // select finResLevelMode + // Mode-1 + if (initReservoirLvlDay == 0 && simEndDay == DAYS_PER_YEAR) + { + finLevData.finResLevelMode.at(yearIndex) + = Antares::Data::FinalReservoirLevelMode::completeYear; + } + // Mode-2 + else if (initReservoirLvlDay != 0 && simEndDay == DAYS_PER_YEAR) + { + simEndRealMonth = 0; + finLevData.finResLevelMode.at(yearIndex) + = Antares::Data::FinalReservoirLevelMode::incompleteYear; + } + // Mode-3/4 + else + { + uint simEndMonth = study.calendar.days[simEndDay].month; + uint simEnd_MonthFirstDay = study.calendar.months[simEndMonth].daysYear.first; + uint simEnd_MonthLastDay = study.calendar.months[simEndMonth].daysYear.end; + // select month in which to reach final reservoir level (1st day of the selected month) + simEndRealMonth + = (simEndDay - simEnd_MonthFirstDay) <= (simEnd_MonthLastDay - simEndDay) + ? simEndMonth + : simEndMonth + 1; + finLevData.finResLevelMode.at(yearIndex) + = Antares::Data::FinalReservoirLevelMode::incompleteYear; + + if (simEndRealMonth == 12 && initReservoirLvlDay == 0) + { + simEndRealMonth = 0; + finLevData.finResLevelMode.at(yearIndex) + = Antares::Data::FinalReservoirLevelMode::completeYear; + } + // E.g. End Date = 21.Dec && InitReservoirLevelDate = 1.Jan -> + // - > go back to first case + else if (simEndRealMonth == 12 && initReservoirLvlDay != 0) + simEndRealMonth = 0; + // End Date = 21.Dec && InitReservoirLevelDate = 1.Mar + // Reach FinalReservoirLevel at 1.Jan + else if (simEndRealMonth == initReservoirLvlMonth + && simEndDay >= initReservoirLvlDay) + simEndRealMonth = (simEndRealMonth + 1) % 12; + // E.g. End Date = 10.Jan && InitReservoirLevelDate = 1.Jan -> + // we need to move FinalReservoirLevel to 1.Feb. + // Cannot do both init and final on the same day + else if (simEndRealMonth == initReservoirLvlMonth + && simEndDay < initReservoirLvlDay) + simEndRealMonth = (simEndRealMonth - 1) % 12; + // E.g. End Date = 25.Nov && InitReservoirLevelDate = 1.Dec -> + // we need to move FinalReservoirLevel to 1.Nov. + // Cannot do both init and final on the same day + + // log out that the final reservoir level will be reached on some other day + if (simEndDay != study.calendar.months[simEndRealMonth].daysYear.first) + { + simEndDayReal = study.calendar.months[simEndRealMonth].daysYear.first; + logs.info() + << "Year: " << yearIndex + 1 << ". Area: " << area.name + << ". Final reservoir level will be reached on day: " << simEndDayReal; + } + } + // Now convert to month if initialization is not done in January + int h20_solver_sim_end_month = (simEndRealMonth - initReservoirLvlMonth) >= 0 + ? simEndRealMonth - initReservoirLvlMonth + : simEndRealMonth - initReservoirLvlMonth + 12; + finLevData.endMonthIndex.at(yearIndex) = h20_solver_sim_end_month; + + // logs for debugging + logs.debug() << "yearIndex: " << yearIndex; + logs.debug() << "includeFinalReservoirLevel: " + << std::to_string(finLevData.includeFinalReservoirLevel.at(yearIndex)); + logs.debug() << "finResLevelMode: " + << std::to_string(finLevData.finResLevelMode.at(yearIndex)); + logs.debug() << "deltaLevel: " << finLevData.deltaLevel.at(yearIndex); + logs.debug() << "endLevel: " << finLevData.endLevel.at(yearIndex); + logs.debug() << "realMonth-SimEnd: " << simEndRealMonth; + logs.debug() << "endMonthIndex_h20_solver: " << finLevData.endMonthIndex.at(yearIndex); + logs.debug() << "simEndDayReal: " << simEndDayReal; + logs.debug() << "initReservoirLvlDay: " << initReservoirLvlDay; + // end of logs for debugging + + // rule curve values for simEndDayReal double lowLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + = area.hydro.reservoirLevel[Data::PartHydro::minimum][simEndDayReal - 1]; double highLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; - double totalYearInflows = 0.0; - // calculate yearly inflows - for (uint day = initReservoirLvlDay; day < DAYS_PER_YEAR; ++day) + = area.hydro.reservoirLevel[Data::PartHydro::maximum][simEndDayReal - 1]; + // calculate (partial)yearly inflows + if (initReservoirLvlDay <= simEndDayReal) + { + for (uint day = initReservoirLvlDay; day < simEndDayReal; ++day) + totalYearInflows += srcinflows[day]; + } + else { - totalYearInflows += srcinflows[day]; + for (uint day = initReservoirLvlDay; day < DAYS_PER_YEAR; ++day) + totalYearInflows += srcinflows[day]; + for (uint day = 0; day < simEndDayReal; ++day) + totalYearInflows += srcinflows[day]; } // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows if ((finalReservoirLevel - initialReservoirLevel) * reservoirCapacity - > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh (energy) + > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh + // (energy) { - logs.error() << "Year: " << tsIndex + 1 << ". Area: " << area.name + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << area.name << ". Incompatible total inflows: " << totalYearInflows << " with initial: " << initialReservoirLevel << " and final: " << finalReservoirLevel << " reservoir levels."; @@ -94,14 +195,13 @@ void FinalReservoirLevelPreChecks(Data::Study& study) if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) { - logs.error() << "Year: " << tsIndex + 1 << ". Area: " << area.name + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << area.name << ". Specifed final reservoir level: " << finalReservoirLevel << " is incompatible with reservoir level rule curve [" << lowLevelLastDay << " , " << highLevelLastDay << "]"; preChecksPasses = false; } } - area.hydro.finalReservoirLevelCorrection.push_back(deltaReservoirLevel); }); } if (!preChecksPasses) From 819b57f2481d71ff97db9c539a50053ed9b76ce8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 27 Feb 2023 22:01:50 +0100 Subject: [PATCH 390/490] management --- src/solver/hydro/management/management.cpp | 35 ++++++++++++++++++++++ src/solver/hydro/management/management.h | 7 +++++ 2 files changed, 42 insertions(+) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 7e2304b66c..bf4f595861 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -139,6 +139,39 @@ void HydroManagement::prepareInflowsScaling(uint numSpace) }); } +void HydroManagement::prepareFinalReservoirLevelData(uint numSpace, uint year) +{ + study.areas.each( + [&](Data::Area& area) + { + auto& data = pAreas[numSpace][area.index]; + data.finalReservoirLevel = -1.0; + if (area.hydro.finalReservoirLevelRuntimeData.deltaLevel.empty()) + return; + + if (!area.hydro.finalReservoirLevelRuntimeData.includeFinalReservoirLevel[year]) + return; + + if (area.hydro.finalReservoirLevelRuntimeData.finResLevelMode[year] + == Data::FinalReservoirLevelMode::completeYear) + { + double delta = area.hydro.finalReservoirLevelRuntimeData.deltaLevel[year]; + // must be done before prepareMonthlyTargetGenerations + if (delta > 0) + data.inflows[0] += delta; + else if (delta < 0) + data.inflows[11] += delta; + } + else if (area.hydro.finalReservoirLevelRuntimeData.finResLevelMode[year] + == Data::FinalReservoirLevelMode::incompleteYear) + { + data.finalReservoirLevel = area.hydro.finalReservoirLevelRuntimeData.endLevel[year]; + data.finalReservoirLevelMonth + = area.hydro.finalReservoirLevelRuntimeData.endMonthIndex[year]; + } + }); +} + template void HydroManagement::prepareNetDemand(uint numSpace) { @@ -290,6 +323,8 @@ void HydroManagement::operator()(double* randomReservoirLevel, prepareInflowsScaling(numSpace); + prepareFinalReservoirLevelData(numSpace, y); + if (parameters.adequacy()) prepareNetDemand(numSpace); else diff --git a/src/solver/hydro/management/management.h b/src/solver/hydro/management/management.h index cf560f0c5c..38bac99b7a 100644 --- a/src/solver/hydro/management/management.h +++ b/src/solver/hydro/management/management.h @@ -75,6 +75,8 @@ class HydroManagement final //@{ //! Prepare inflows scaling for each area void prepareInflowsScaling(uint numSpace); + //! prepare data for Final reservoir level + void prepareFinalReservoirLevelData(uint numSpace, uint yearIndex); //! Prepare the net demand for each area template void prepareNetDemand(uint numSpace); @@ -136,6 +138,11 @@ class HydroManagement final //! Daily optimized Generation double DOG[dayYearCount]; + //! Final reservoir level + double finalReservoirLevel; + //! Month to reach final reservoir level (h20_solver month, not real month); + uint finalReservoirLevelMonth; + }; // struct PerArea //! Temporary data per area From c6819f559f88418a06226a49a5c5e4e65fd9a345 Mon Sep 17 00:00:00 2001 From: Milos A Date: Mon, 27 Feb 2023 22:01:59 +0100 Subject: [PATCH 391/490] monthly.cpp --- src/solver/hydro/management/monthly.cpp | 5 +++++ 1 file changed, 5 insertions(+) diff --git a/src/solver/hydro/management/monthly.cpp b/src/solver/hydro/management/monthly.cpp index e03b06aaff..27356c4a7a 100644 --- a/src/solver/hydro/management/monthly.cpp +++ b/src/solver/hydro/management/monthly.cpp @@ -189,6 +189,11 @@ void HydroManagement::prepareMonthlyOptimalGenerations(double* random_reservoir_ problem.VolumeMin[month] = minLvl[firstDay]; problem.VolumeMax[month] = maxLvl[firstDay]; } + + // fix reservoir level for specified month if final reservoir level is used + if (data.finalReservoirLevel != -1.0) + problem.VolumeMin[data.finalReservoirLevelMonth] + = problem.VolumeMax[data.finalReservoirLevelMonth] = data.finalReservoirLevel; H2O_M_OptimiserUneAnnee(&problem, 0); switch (problem.ResultatsValides) From b33e72fc3d997e30231bc5bd17d90ffc805d5756 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 20:21:19 +0100 Subject: [PATCH 392/490] scenarioHydroLevels -> scenarioInitialHydroLevels --- src/libs/antares/study/scenario-builder/hydroLevelsData.cpp | 2 +- src/libs/antares/study/study.h | 2 +- .../simulation/hydro-final-reservoir-level-pre-checks.cpp | 2 +- src/solver/simulation/solver.hxx | 2 +- .../scenario-builder/test-sc-builder-file-read-line.cpp | 6 +++--- 5 files changed, 7 insertions(+), 7 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index 654e9600d6..cc32cd907d 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -85,7 +85,7 @@ void hydroLevelsData::set_value(uint x, uint y, double value) bool hydroLevelsData::apply(Study& study) { - study.scenarioHydroLevels.copyFrom(pHydroLevelsRules); + study.scenarioInitialHydroLevels.copyFrom(pHydroLevelsRules); return true; } diff --git a/src/libs/antares/study/study.h b/src/libs/antares/study/study.h index ba9e7cb3ec..f0afc02025 100644 --- a/src/libs/antares/study/study.h +++ b/src/libs/antares/study/study.h @@ -675,7 +675,7 @@ class Study final : public Yuni::NonCopyable, public IObject, public Laye ScenarioBuilder::Sets* scenarioRules; //@} - Matrix scenarioHydroLevels; + Matrix scenarioInitialHydroLevels; // Hydro Final Levels Matrix scenarioFinalHydroLevels; /*! diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp index 1c246ce045..0a855d5d16 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -47,7 +47,7 @@ void FinalReservoirLevelPreChecks(Data::Study& study) int tsIndex = data.timeseriesNumbers[0][yearIndex]; auto& inflowsmatrix = area.hydro.series->storage; auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; - double initialReservoirLevel = study.scenarioHydroLevels[area.index][yearIndex]; + double initialReservoirLevel = study.scenarioInitialHydroLevels[area.index][yearIndex]; double finalReservoirLevel = study.scenarioFinalHydroLevels[area.index][yearIndex]; double deltaReservoirLevel = 0.0; int simEndRealMonth = 0; diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index 119ad24dfa..be60577d1f 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -1300,7 +1300,7 @@ void ISimulation::computeRandomNumbers(randomNumbers& randomForYears, // Possibly update the intial level from scenario builder if (study.parameters.useCustomScenario) { - double levelFromScenarioBuilder = study.scenarioHydroLevels[areaIndex][y]; + double levelFromScenarioBuilder = study.scenarioInitialHydroLevels[areaIndex][y]; if (levelFromScenarioBuilder >= 0.) randomLevel = levelFromScenarioBuilder; } 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 ba6aa03360..d80b579ad4 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 @@ -315,7 +315,7 @@ BOOST_AUTO_TEST_CASE(on_area1_and_on_year_17__hydro_level_0_123_is_chosen__readi BOOST_CHECK_EQUAL(my_rule.hydroLevels.get_value(yearNumber.to(), area_1->index), level.to()); BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(study->scenarioHydroLevels[area_1->index][yearNumber.to()], level.to()); + BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_1->index][yearNumber.to()], level.to()); } BOOST_AUTO_TEST_CASE(on_area2_and_on_year_9__hydro_level_1_5_is_chosen_level_lowered_to_1__reading_OK) @@ -328,7 +328,7 @@ BOOST_AUTO_TEST_CASE(on_area2_and_on_year_9__hydro_level_1_5_is_chosen_level_low BOOST_CHECK_EQUAL(my_rule.hydroLevels.get_value(yearNumber.to(), area_2->index), 1.); BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(study->scenarioHydroLevels[area_2->index][yearNumber.to()], 1.); + BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_2->index][yearNumber.to()], 1.); } BOOST_AUTO_TEST_CASE(on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__level_raised_to_0__reading_OK) @@ -341,7 +341,7 @@ BOOST_AUTO_TEST_CASE(on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__leve BOOST_CHECK_EQUAL(my_rule.hydroLevels.get_value(yearNumber.to(), area_3->index), 0.); BOOST_CHECK(my_rule.apply()); - BOOST_CHECK_EQUAL(study->scenarioHydroLevels[area_3->index][yearNumber.to()], 0.); + BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_3->index][yearNumber.to()], 0.); } // ====================== From 483626057d27dd2332327c504d8e00f98fbd5f5f Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 20:36:29 +0100 Subject: [PATCH 393/490] finalResLevel - initialResLevel = -deltaResLevel --- .../simulation/hydro-final-reservoir-level-pre-checks.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp index 0a855d5d16..008c102306 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp @@ -180,7 +180,7 @@ void FinalReservoirLevelPreChecks(Data::Study& study) } // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if ((finalReservoirLevel - initialReservoirLevel) * reservoirCapacity + if ((-deltaReservoirLevel) * reservoirCapacity > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh // (energy) { From efa1bcea9026fb52e18c06d74cbd813fbd7637f1 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 20:43:52 +0100 Subject: [PATCH 394/490] readHydroLevels -> readInitialHydroLevels --- src/libs/antares/study/scenario-builder/rules.cpp | 4 ++-- src/libs/antares/study/scenario-builder/rules.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index 5abbc6ce17..c2d3dcffec 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -256,7 +256,7 @@ bool Rules::readSolar(const AreaName::Vector& splitKey, String value, bool updat 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]; @@ -344,7 +344,7 @@ bool Rules::readLine(const AreaName::Vector& splitKey, String value, bool update 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") diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index ce07abae10..2a91bac0e5 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -134,7 +134,7 @@ 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); From ffb206405b39cee0fc196dda19e42bac949ddd6b Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 20:59:24 +0100 Subject: [PATCH 395/490] hydroLevels -> hydroInitialLevels --- src/libs/antares/study/scenario-builder/rules.cpp | 8 ++++---- src/libs/antares/study/scenario-builder/rules.h | 2 +- .../test-sc-builder-file-read-line.cpp | 6 +++--- .../scenario-builder/test-sc-builder-file-save.cpp | 8 ++++---- .../scenario-builder-hydro-levels-renderer.cpp | 12 ++++++------ 5 files changed, 18 insertions(+), 18 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index c2d3dcffec..b17154479f 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -64,7 +64,7 @@ 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); } file << '\n'; @@ -100,7 +100,7 @@ bool Rules::reset() renewable[i].reset(study_); } - hydroLevels.reset(study_); + hydroInitialLevels.reset(study_); hydroFinalLevels.reset(study_); // links NTC @@ -266,7 +266,7 @@ bool Rules::readInitialHydroLevels(const AreaName::Vector& splitKey, String valu return false; double val = fromStringToHydroLevel(value, 1.); - hydroLevels.set(area->index, year, val); + hydroInitialLevels.set(area->index, year, val); return true; } @@ -367,7 +367,7 @@ 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; } else diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index 2a91bac0e5..d82b7f0e03 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -119,7 +119,7 @@ class Rules final : private Yuni::NonCopyable std::vector renewable; //! hydro initial levels - hydroLevelsData hydroLevels; + hydroLevelsData hydroInitialLevels; //! hydro final levels hydroFinalLevelsData hydroFinalLevels; 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 d80b579ad4..05a54194e7 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 @@ -312,7 +312,7 @@ BOOST_AUTO_TEST_CASE(on_area1_and_on_year_17__hydro_level_0_123_is_chosen__readi AreaName::Vector splitKey = { "hl", "area 1", yearNumber }; my_rule.readLine(splitKey, level, false); - 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_1->index), level.to()); BOOST_CHECK(my_rule.apply()); BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_1->index][yearNumber.to()], level.to()); @@ -325,7 +325,7 @@ BOOST_AUTO_TEST_CASE(on_area2_and_on_year_9__hydro_level_1_5_is_chosen_level_low AreaName::Vector splitKey = { "hl", "area 2", yearNumber }; BOOST_CHECK(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.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.); @@ -338,7 +338,7 @@ BOOST_AUTO_TEST_CASE(on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__leve AreaName::Vector splitKey = { "hl", "area 3", 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.hydroInitialLevels.get_value(yearNumber.to(), area_3->index), 0.); BOOST_CHECK(my_rule.apply()); BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_3->index][yearNumber.to()], 0.); 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 e96a98608a..56943d2237 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 @@ -394,9 +394,9 @@ BOOST_AUTO_TEST_CASE( BOOST_AUTO_TEST_CASE( HYDRO_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical) { - my_rule->hydroLevels.set(area_1->index, 9, 9); - my_rule->hydroLevels.set(area_3->index, 18, 7); - my_rule->hydroLevels.set(area_1->index, 5, 8); + my_rule->hydroInitialLevels.set(area_1->index, 9, 9); + my_rule->hydroInitialLevels.set(area_3->index, 18, 7); + my_rule->hydroInitialLevels.set(area_1->index, 5, 8); saveScenarioBuilder(); @@ -450,7 +450,7 @@ BOOST_AUTO_TEST_CASE( my_rule->renewable[area_3->index].set(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.set(area_1->index, 5, 8); + my_rule->hydroInitialLevels.set(area_1->index, 5, 8); saveScenarioBuilder(); 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..6d4f2dcffc 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 @@ -50,10 +50,10 @@ bool hydroLevelsScBuilderRenderer::cellValue(int x, int y, const Yuni::String& v { if ((uint)y < study->areas.size()) { - assert((uint)y < pRules->hydroLevels.width()); - assert((uint)x < pRules->hydroLevels.height()); + assert((uint)y < pRules->hydroInitialLevels.width()); + assert((uint)x < pRules->hydroInitialLevels.height()); double val = fromStringToHydroLevel(value, 100.) / 100.; - pRules->hydroLevels.set_value(x, y, val); + pRules->hydroInitialLevels.set_value(x, y, val); return true; } } @@ -66,9 +66,9 @@ double hydroLevelsScBuilderRenderer::cellNumericValue(int x, int y) const { 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.; From d96ee5937adc252cc96076ce4c6a7fd8358b9514 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 21:09:06 +0100 Subject: [PATCH 396/490] val -> finalLevel in Rules::readFinalHydroLevels --- src/libs/antares/study/scenario-builder/rules.cpp | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index b17154479f..48b7105e8e 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -279,8 +279,8 @@ bool Rules::readFinalHydroLevels(const AreaName::Vector& splitKey, String value, if (!area) return false; - double val = fromStringToHydroLevel(value, 1.); - hydroFinalLevels.set(area->index, year, val); + double finalLevel = fromStringToHydroLevel(value, 1.); + hydroFinalLevels.set(area->index, year, finalLevel); return true; } From 2026dbdd3784e4122c58b5ef80c32630e06e53b2 Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 21:36:04 +0100 Subject: [PATCH 397/490] change file names for hydro-final-reservoir-level --- src/solver/cmake/simulation.cmake | 4 ++-- ...e-checks.cpp => hydro-final-reservoir-level-functions.cpp} | 2 +- ...l-pre-checks.h => hydro-final-reservoir-level-functions.h} | 0 src/solver/simulation/solver.hxx | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) rename src/solver/simulation/{hydro-final-reservoir-level-pre-checks.cpp => hydro-final-reservoir-level-functions.cpp} (99%) rename src/solver/simulation/{hydro-final-reservoir-level-pre-checks.h => hydro-final-reservoir-level-functions.h} (100%) diff --git a/src/solver/cmake/simulation.cmake b/src/solver/cmake/simulation.cmake index 4f882f2c89..1568facb07 100644 --- a/src/solver/cmake/simulation.cmake +++ b/src/solver/cmake/simulation.cmake @@ -23,8 +23,8 @@ set(SRC_SIMULATION simulation/timeseries-numbers.cpp simulation/apply-scenario.h simulation/apply-scenario.cpp - simulation/hydro-final-reservoir-level-pre-checks.h - simulation/hydro-final-reservoir-level-pre-checks.cpp + simulation/hydro-final-reservoir-level-functions.h + simulation/hydro-final-reservoir-level-functions.cpp # Solver diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp similarity index 99% rename from src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp rename to src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 008c102306..c7d3a15188 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -25,7 +25,7 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#include "hydro-final-reservoir-level-pre-checks.h" +#include "hydro-final-reservoir-level-functions.h" #include namespace Antares diff --git a/src/solver/simulation/hydro-final-reservoir-level-pre-checks.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h similarity index 100% rename from src/solver/simulation/hydro-final-reservoir-level-pre-checks.h rename to src/solver/simulation/hydro-final-reservoir-level-functions.h diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index be60577d1f..898000ed45 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -37,7 +37,7 @@ #include "../aleatoire/alea_fonctions.h" #include "timeseries-numbers.h" #include "apply-scenario.h" -#include "hydro-final-reservoir-level-pre-checks.h" +#include "hydro-final-reservoir-level-functions.h" #include #include "../ts-generator/generator.h" From 35061b34a954e1a6f0e7482867822cb4215b87bb Mon Sep 17 00:00:00 2001 From: Milos A Date: Wed, 1 Mar 2023 21:44:01 +0100 Subject: [PATCH 398/490] Include Guards -> Pragma Once --- .../antares/study/scenario-builder/hydroFinalLevelsData.h | 5 +---- 1 file changed, 1 insertion(+), 4 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h index 1655b0d308..8140ef6e9a 100644 --- a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h @@ -24,8 +24,7 @@ ** ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#ifndef __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_FINAL_LEVELS_H__ -#define __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_FINAL_LEVELS_H__ +#pragma once #include "scBuilderDataInterface.h" @@ -113,5 +112,3 @@ inline double hydroFinalLevelsData::get_value(uint x, uint y) const } // namespace ScenarioBuilder } // namespace Data } // namespace Antares - -#endif // __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_FINAL_LEVELS_H__ From 807ed15b831f0cb23efa9a667ea316f3efc986f8 Mon Sep 17 00:00:00 2001 From: Milos A Date: Thu, 2 Mar 2023 12:26:49 +0100 Subject: [PATCH 399/490] FRL functions refactor --- .../antares/study/parts/hydro/container.h | 153 ++++++++++++ src/solver/simulation/apply-scenario.cpp | 4 + .../hydro-final-reservoir-level-functions.cpp | 218 ++++++------------ .../hydro-final-reservoir-level-functions.h | 2 +- src/solver/simulation/solver.hxx | 4 - 5 files changed, 230 insertions(+), 151 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 1d9a44166f..dfed46fbf8 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -43,11 +43,164 @@ class FinalReservoirLevelRuntimeData using finalResLevelMode = Antares::Data::FinalReservoirLevelMode; public: + // FInal reservoir level runtime data std::vector includeFinalReservoirLevel; std::vector finResLevelMode; std::vector endLevel; std::vector deltaLevel; std::vector endMonthIndex; + + // Simulation Data + uint simEndDay; + uint simEndMonth; + uint simEndMonth_FirstDay; + uint simEndMonth_LastDay; + + // simulation year + uint yearIndex; + + // data per area + double initialReservoirLevel; + double finalReservoirLevel; + double deltaReservoirLevel; + double reservoirCapacity; + int initReservoirLvlMonth; + int initReservoirLvlDay; + double lowLevelLastDay; + double highLevelLastDay; + + // methods: + + void fillEmpty() + { + includeFinalReservoirLevel.push_back(false); + finResLevelMode.push_back(completeYear); + deltaLevel.push_back(0.); + endLevel.push_back(0.); + endMonthIndex.push_back(0); + } + + void assignEndLevelAndDelta() + { + includeFinalReservoirLevel.at(yearIndex) = true; + endLevel.at(yearIndex) = finalReservoirLevel; + deltaLevel.at(yearIndex) = deltaReservoirLevel; + } + + int selectMode() + { + int simEndRealMonth = 0; + // Mode-1 + if (initReservoirLvlDay == 0 && simEndDay == DAYS_PER_YEAR) + { + finResLevelMode.at(yearIndex) = completeYear; + return simEndRealMonth; + } + // Mode-2 + else if (initReservoirLvlDay != 0 && simEndDay == DAYS_PER_YEAR) + { + finResLevelMode.at(yearIndex) = incompleteYear; + return simEndRealMonth; + } + // Mode-3/4 + else + { + // select month in which to reach final reservoir level (1st day of the selected month) + simEndRealMonth + = (simEndDay - simEndMonth_FirstDay) <= (simEndMonth_LastDay - simEndDay) + ? simEndMonth + : simEndMonth + 1; + finResLevelMode.at(yearIndex) = incompleteYear; + + if (simEndRealMonth == 12 && initReservoirLvlDay == 0) + { + simEndRealMonth = 0; + finResLevelMode.at(yearIndex) = completeYear; + } + // E.g. End Date = 21.Dec && InitReservoirLevelDate = 1.Jan -> + // - > go back to first case + else if (simEndRealMonth == 12 && initReservoirLvlDay != 0) + simEndRealMonth = 0; + // End Date = 21.Dec && InitReservoirLevelDate = 1.Mar + // Reach FinalReservoirLevel at 1.Jan + else if (simEndRealMonth == initReservoirLvlMonth && simEndDay >= initReservoirLvlDay) + simEndRealMonth = (simEndRealMonth + 1) % 12; + // E.g. End Date = 10.Jan && InitReservoirLevelDate = 1.Jan -> + // we need to move FinalReservoirLevel to 1.Feb. + // Cannot do both init and final on the same day + else if (simEndRealMonth == initReservoirLvlMonth && simEndDay < initReservoirLvlDay) + simEndRealMonth = (simEndRealMonth - 1) % 12; + // E.g. End Date = 25.Nov && InitReservoirLevelDate = 1.Dec -> + // we need to move FinalReservoirLevel to 1.Nov. + // Cannot do both init and final on the same day + + return simEndRealMonth; + } + } + + void logSimEndDayChange(int simEndDayReal, AreaName name) + { + if (simEndDay != simEndDayReal) + { + logs.info() << "Year: " << yearIndex + 1 << ". Area: " << name + << ". Final reservoir level will be reached on day: " << simEndDayReal; + } + } + + void shiftMonths(int simEndRealMonth) + { + int h20_solver_sim_end_month = (simEndRealMonth - initReservoirLvlMonth) >= 0 + ? simEndRealMonth - initReservoirLvlMonth + : simEndRealMonth - initReservoirLvlMonth + 12; + endMonthIndex.at(yearIndex) = h20_solver_sim_end_month; + } + + double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows, + uint simEndDayReal) + { + double totalYearInflows = 0.0; + if (initReservoirLvlDay <= simEndDayReal) + { + for (uint day = initReservoirLvlDay; day < simEndDayReal; ++day) + totalYearInflows += srcinflows[day]; + } + else + { + for (uint day = initReservoirLvlDay; day < DAYS_PER_YEAR; ++day) + totalYearInflows += srcinflows[day]; + for (uint day = 0; day < simEndDayReal; ++day) + totalYearInflows += srcinflows[day]; + } + return totalYearInflows; + } + + bool preCheckOne(double totalYearInflows, AreaName name) + { + if ((-deltaReservoirLevel) * reservoirCapacity + > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh + // (energy) + { + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name + << ". Incompatible total inflows: " << totalYearInflows + << " with initial: " << initialReservoirLevel + << " and final: " << finalReservoirLevel << " reservoir levels."; + return false; + } + return true; + } + + bool preCheckTwo(AreaName name) + { + if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) + { + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name + << ". Specifed final reservoir level: " << finalReservoirLevel + << " is incompatible with reservoir level rule curve [" << lowLevelLastDay + << " , " << highLevelLastDay << "]"; + return false; + } + return true; + } }; /*! diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 0b544bb1cd..2d50c959ba 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -27,6 +27,7 @@ #include "apply-scenario.h" #include +#include "hydro-final-reservoir-level-functions.h" namespace Antares::Solver { @@ -55,6 +56,9 @@ void ApplyCustomScenario(Data::Study& study) study.scenarioRulesDestroy(); logs.info(); + + // final reservoir level functions and pre-checks + FinalReservoirLevel(study); } } // namespace Antares::Solver diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index c7d3a15188..a19bf42941 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -32,175 +32,101 @@ namespace Antares { namespace Solver { -void FinalReservoirLevelPreChecks(Data::Study& study) +void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, + Data::Study& study, + uint year) +{ + finLevData.simEndDay = study.parameters.simulationDays.end; + finLevData.simEndMonth = study.calendar.days[finLevData.simEndDay].month; + finLevData.simEndMonth_FirstDay = study.calendar.months[finLevData.simEndMonth].daysYear.first; + finLevData.simEndMonth_LastDay = study.calendar.months[finLevData.simEndMonth].daysYear.end; + finLevData.yearIndex = year; +} + +void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, + Data::Study& study, + Data::Area& area) +{ + finLevData.initialReservoirLevel + = study.scenarioInitialHydroLevels[area.index][finLevData.yearIndex]; + finLevData.finalReservoirLevel + = study.scenarioFinalHydroLevels[area.index][finLevData.yearIndex]; + finLevData.deltaReservoirLevel + = finLevData.initialReservoirLevel - finLevData.finalReservoirLevel; +} + +void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, + Data::Study& study, + Data::Area& area) +{ + finLevData.initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; // month [0-11] + finLevData.initReservoirLvlDay + = study.calendar.months[finLevData.initReservoirLvlMonth].daysYear.first; + finLevData.reservoirCapacity = area.hydro.reservoirCapacity; +} + +void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, + uint simEndDayReal, + Data::Area& area) +{ + finLevData.lowLevelLastDay + = area.hydro.reservoirLevel[Data::PartHydro::minimum][simEndDayReal - 1]; + finLevData.highLevelLastDay + = area.hydro.reservoirLevel[Data::PartHydro::maximum][simEndDayReal - 1]; +} + +void FinalReservoirLevel(Data::Study& study) { bool preChecksPasses = true; - // Last Day of the simulation - uint simEndDay = study.parameters.simulationDays.end; for (uint yearIndex = 0; yearIndex != study.scenarioFinalHydroLevels.height; ++yearIndex) { study.areas.each( [&](Data::Area& area) { - // general data - const Data::DataSeriesHydro& data = *area.hydro.series; - int tsIndex = data.timeseriesNumbers[0][yearIndex]; - auto& inflowsmatrix = area.hydro.series->storage; - auto const& srcinflows = inflowsmatrix[tsIndex < inflowsmatrix.width ? tsIndex : 0]; - double initialReservoirLevel = study.scenarioInitialHydroLevels[area.index][yearIndex]; - double finalReservoirLevel = study.scenarioFinalHydroLevels[area.index][yearIndex]; - double deltaReservoirLevel = 0.0; - int simEndRealMonth = 0; - // FinalReservoirLevelRuntimeData auto& finLevData = area.hydro.finalReservoirLevelRuntimeData; - finLevData.includeFinalReservoirLevel.push_back(false); - finLevData.finResLevelMode.push_back( - Antares::Data::FinalReservoirLevelMode::completeYear); - finLevData.deltaLevel.push_back(deltaReservoirLevel); - finLevData.endLevel.push_back(deltaReservoirLevel); - finLevData.endMonthIndex.push_back(simEndRealMonth); + finLevData.fillEmpty(); + initializeGeneralData(finLevData, study, yearIndex); + initializePerAreaData(finLevData, study, area); if (area.hydro.reservoirManagement && !area.hydro.useWaterValue - && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) + && !isnan(finLevData.finalReservoirLevel) + && !isnan(finLevData.initialReservoirLevel)) { - // simEndDayReal - uint simEndDayReal = simEndDay; - // deltaReservoirLevel - deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; - // collect data for pre-checks - int initReservoirLvlMonth - = area.hydro.initializeReservoirLevelDate; // month [0-11] - int initReservoirLvlDay - = study.calendar.months[initReservoirLvlMonth].daysYear.first; - double reservoirCapacity = area.hydro.reservoirCapacity; - double totalYearInflows = 0.0; - // FinalReservoirLevelRuntimeData - finLevData.includeFinalReservoirLevel.at(yearIndex) = true; - finLevData.endLevel.at(yearIndex) = finalReservoirLevel; - finLevData.deltaLevel.at(yearIndex) = deltaReservoirLevel; - // select finResLevelMode - // Mode-1 - if (initReservoirLvlDay == 0 && simEndDay == DAYS_PER_YEAR) - { - finLevData.finResLevelMode.at(yearIndex) - = Antares::Data::FinalReservoirLevelMode::completeYear; - } - // Mode-2 - else if (initReservoirLvlDay != 0 && simEndDay == DAYS_PER_YEAR) - { - simEndRealMonth = 0; - finLevData.finResLevelMode.at(yearIndex) - = Antares::Data::FinalReservoirLevelMode::incompleteYear; - } - // Mode-3/4 - else - { - uint simEndMonth = study.calendar.days[simEndDay].month; - uint simEnd_MonthFirstDay = study.calendar.months[simEndMonth].daysYear.first; - uint simEnd_MonthLastDay = study.calendar.months[simEndMonth].daysYear.end; - // select month in which to reach final reservoir level (1st day of the selected month) - simEndRealMonth - = (simEndDay - simEnd_MonthFirstDay) <= (simEnd_MonthLastDay - simEndDay) - ? simEndMonth - : simEndMonth + 1; - finLevData.finResLevelMode.at(yearIndex) - = Antares::Data::FinalReservoirLevelMode::incompleteYear; + initializePreCheckData(finLevData, study, area); + finLevData.assignEndLevelAndDelta(); - if (simEndRealMonth == 12 && initReservoirLvlDay == 0) - { - simEndRealMonth = 0; - finLevData.finResLevelMode.at(yearIndex) - = Antares::Data::FinalReservoirLevelMode::completeYear; - } - // E.g. End Date = 21.Dec && InitReservoirLevelDate = 1.Jan -> - // - > go back to first case - else if (simEndRealMonth == 12 && initReservoirLvlDay != 0) - simEndRealMonth = 0; - // End Date = 21.Dec && InitReservoirLevelDate = 1.Mar - // Reach FinalReservoirLevel at 1.Jan - else if (simEndRealMonth == initReservoirLvlMonth - && simEndDay >= initReservoirLvlDay) - simEndRealMonth = (simEndRealMonth + 1) % 12; - // E.g. End Date = 10.Jan && InitReservoirLevelDate = 1.Jan -> - // we need to move FinalReservoirLevel to 1.Feb. - // Cannot do both init and final on the same day - else if (simEndRealMonth == initReservoirLvlMonth - && simEndDay < initReservoirLvlDay) - simEndRealMonth = (simEndRealMonth - 1) % 12; - // E.g. End Date = 25.Nov && InitReservoirLevelDate = 1.Dec -> - // we need to move FinalReservoirLevel to 1.Nov. - // Cannot do both init and final on the same day + // determine simEnd month and FinalReservoirLevelMode + int simEndRealMonth = finLevData.selectMode(); - // log out that the final reservoir level will be reached on some other day - if (simEndDay != study.calendar.months[simEndRealMonth].daysYear.first) - { - simEndDayReal = study.calendar.months[simEndRealMonth].daysYear.first; - logs.info() - << "Year: " << yearIndex + 1 << ". Area: " << area.name - << ". Final reservoir level will be reached on day: " << simEndDayReal; - } - } - // Now convert to month if initialization is not done in January - int h20_solver_sim_end_month = (simEndRealMonth - initReservoirLvlMonth) >= 0 - ? simEndRealMonth - initReservoirLvlMonth - : simEndRealMonth - initReservoirLvlMonth + 12; - finLevData.endMonthIndex.at(yearIndex) = h20_solver_sim_end_month; + // log if the final reservoir level will be reached on some other day + uint simEndDayReal = study.calendar.months[simEndRealMonth].daysYear.first; + if (simEndDayReal == 0) + simEndDayReal = DAYS_PER_YEAR; + finLevData.logSimEndDayChange(simEndDayReal, area.name); - // logs for debugging - logs.debug() << "yearIndex: " << yearIndex; - logs.debug() << "includeFinalReservoirLevel: " - << std::to_string(finLevData.includeFinalReservoirLevel.at(yearIndex)); - logs.debug() << "finResLevelMode: " - << std::to_string(finLevData.finResLevelMode.at(yearIndex)); - logs.debug() << "deltaLevel: " << finLevData.deltaLevel.at(yearIndex); - logs.debug() << "endLevel: " << finLevData.endLevel.at(yearIndex); - logs.debug() << "realMonth-SimEnd: " << simEndRealMonth; - logs.debug() << "endMonthIndex_h20_solver: " << finLevData.endMonthIndex.at(yearIndex); - logs.debug() << "simEndDayReal: " << simEndDayReal; - logs.debug() << "initReservoirLvlDay: " << initReservoirLvlDay; - // end of logs for debugging + // Now convert to h20-solver-month if initialization is not done in January + finLevData.shiftMonths(simEndRealMonth); // rule curve values for simEndDayReal - double lowLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::minimum][simEndDayReal - 1]; - double highLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::maximum][simEndDayReal - 1]; + ruleCurveForSimEndReal(finLevData, simEndDayReal, area); + // calculate (partial)yearly inflows - if (initReservoirLvlDay <= simEndDayReal) - { - for (uint day = initReservoirLvlDay; day < simEndDayReal; ++day) - totalYearInflows += srcinflows[day]; - } - else - { - for (uint day = initReservoirLvlDay; day < DAYS_PER_YEAR; ++day) - totalYearInflows += srcinflows[day]; - for (uint day = 0; day < simEndDayReal; ++day) - totalYearInflows += srcinflows[day]; - } + const Data::DataSeriesHydro& data = *area.hydro.series; + int tsHydroIndex = data.timeseriesNumbers[0][finLevData.yearIndex]; + auto& inflowsmatrix = area.hydro.series->storage; + auto& srcinflows + = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; + double totalInflows = finLevData.calculateTotalInflows(srcinflows, simEndDayReal); + // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if ((-deltaReservoirLevel) * reservoirCapacity - > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh - // (energy) - { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << area.name - << ". Incompatible total inflows: " << totalYearInflows - << " with initial: " << initialReservoirLevel - << " and final: " << finalReservoirLevel << " reservoir levels."; + if (!finLevData.preCheckOne(totalInflows, area.name)) preChecksPasses = false; - } + // pre-check 2 -> final reservoir level set by the user is within the // rule curves for the final day - if (finalReservoirLevel < lowLevelLastDay - || finalReservoirLevel > highLevelLastDay) - { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << area.name - << ". Specifed final reservoir level: " << finalReservoirLevel - << " is incompatible with reservoir level rule curve [" - << lowLevelLastDay << " , " << highLevelLastDay << "]"; + if (!finLevData.preCheckTwo(area.name)) preChecksPasses = false; - } } }); } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 35cb06989d..ddf9bbd7a1 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -33,7 +33,7 @@ namespace Antares { namespace Solver { -void FinalReservoirLevelPreChecks(Data::Study& study); +void FinalReservoirLevel(Data::Study& study); } // namespace Solver } // namespace Antares diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index 898000ed45..d86c78daa9 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -37,7 +37,6 @@ #include "../aleatoire/alea_fonctions.h" #include "timeseries-numbers.h" #include "apply-scenario.h" -#include "hydro-final-reservoir-level-functions.h" #include #include "../ts-generator/generator.h" @@ -345,10 +344,7 @@ void ISimulation::run() } if (parameters.useCustomScenario) - { ApplyCustomScenario(study); - FinalReservoirLevelPreChecks(study); - } // Launching the simulation for all years logs.info() << "MC-Years : [" << (study.runtime->rangeLimits.year[Data::rangeBegin] + 1) From b680d8dc0d7ffe104565147412ddce531112be57 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 3 Mar 2023 11:24:02 +0100 Subject: [PATCH 400/490] refactor hydroLevelsData --- src/libs/antares/CMakeLists.txt | 2 - .../scenario-builder/hydroFinalLevelsData.cpp | 94 --------------- .../scenario-builder/hydroFinalLevelsData.h | 114 ------------------ .../scenario-builder/hydroLevelsData.cpp | 14 ++- .../study/scenario-builder/hydroLevelsData.h | 4 + .../antares/study/scenario-builder/rules.cpp | 8 +- .../antares/study/scenario-builder/rules.h | 3 +- 7 files changed, 22 insertions(+), 217 deletions(-) delete mode 100644 src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp delete mode 100644 src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h diff --git a/src/libs/antares/CMakeLists.txt b/src/libs/antares/CMakeLists.txt index 5e59f6c8f0..3421188970 100644 --- a/src/libs/antares/CMakeLists.txt +++ b/src/libs/antares/CMakeLists.txt @@ -37,8 +37,6 @@ set(SRC_STUDY_SCENARIO_BUILDER study/scenario-builder/TSnumberData.cpp study/scenario-builder/hydroLevelsData.h study/scenario-builder/hydroLevelsData.cpp - study/scenario-builder/hydroFinalLevelsData.h - study/scenario-builder/hydroFinalLevelsData.cpp study/scenario-builder/rules.h study/scenario-builder/rules.hxx study/scenario-builder/rules.cpp diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp deleted file mode 100644 index f359e751d1..0000000000 --- a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.cpp +++ /dev/null @@ -1,94 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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 "hydroFinalLevelsData.h" -#include "scBuilderUtils.h" - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -bool hydroFinalLevelsData::reset(const Study& study) -{ - const uint nbYears = study.parameters.nbYears; - - pHydroFinalLevelsRules.reset(study.areas.size(), nbYears); - pHydroFinalLevelsRules.fill(std::nan("")); - - return true; -} - -void hydroFinalLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const -{ - // Prefix - CString<512, false> prefix; - prefix += "hfl,"; - - // Turning values into strings (precision 4) - std::ostringstream value_into_string; - value_into_string << std::setprecision(4); - - // Foreach year - assert(pHydroFinalLevelsRules.width == study.areas.size()); - for (uint index = 0; index != pHydroFinalLevelsRules.width; ++index) - { - // alias to the current column - const MatrixType::ColumnType& col = pHydroFinalLevelsRules[index]; - // Foreach area... - for (uint y = 0; y != pHydroFinalLevelsRules.height; ++y) - { - 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 << " = " - << value_into_string.str() << '\n'; - value_into_string.str(std::string()); // Clearing converter - } - } -} - -void hydroFinalLevelsData::set_value(uint x, uint y, double value) -{ - pHydroFinalLevelsRules.entry[y][x] = value; -} - -bool hydroFinalLevelsData::apply(Study& study) -{ - study.scenarioFinalHydroLevels.copyFrom(pHydroFinalLevelsRules); - return true; -} - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h b/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h deleted file mode 100644 index 8140ef6e9a..0000000000 --- a/src/libs/antares/study/scenario-builder/hydroFinalLevelsData.h +++ /dev/null @@ -1,114 +0,0 @@ -/* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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 "scBuilderDataInterface.h" - -namespace Antares -{ -namespace Data -{ -namespace ScenarioBuilder -{ -/*! -** \brief Rules for hydro final levels, for all years and areas -*/ -class hydroFinalLevelsData final : public dataInterface -// TODO CR25: can i inherit methods from hydroLevelsData (must delete final in its declaration?!) -{ -public: - //! Matrix - using MatrixType = Matrix; - -public: - // We use default constructor and destructor - - //! \name Data manipulation - //@{ - /*! - ** \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 set(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 final levels overlay (0 if auto) - MatrixType pHydroFinalLevelsRules; - -}; // class hydroLevelsData - -// class hydroLevelsData : inline functions - -inline void hydroFinalLevelsData::set(uint areaindex, uint year, double value) -{ - assert(areaindex < pHydroFinalLevelsRules.width); - if (year < pHydroFinalLevelsRules.height) - pHydroFinalLevelsRules[areaindex][year] = value; -} - -inline uint hydroFinalLevelsData::width() const -{ - return pHydroFinalLevelsRules.width; -} - -inline uint hydroFinalLevelsData::height() const -{ - return pHydroFinalLevelsRules.height; -} - -inline double hydroFinalLevelsData::get_value(uint x, uint y) const -{ - return pHydroFinalLevelsRules.entry[y][x]; -} - -} // namespace ScenarioBuilder -} // namespace Data -} // namespace Antares diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index cc32cd907d..ea739f06dd 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -47,10 +47,16 @@ bool hydroLevelsData::reset(const Study& study) } void hydroLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const +{ +} + +void hydroLevelsData::saveToINIFileHydroLevel(const Study& study, + Yuni::IO::File::Stream& file, + std::string addToPrefix) const { // Prefix CString<512, false> prefix; - prefix += "hl,"; + prefix += addToPrefix; // Turning values into strings (precision 4) std::ostringstream value_into_string; @@ -89,6 +95,12 @@ bool hydroLevelsData::apply(Study& study) return true; } +bool hydroLevelsData::applyHydroLevels(Matrix& scenarioHydroLevels) +{ + scenarioHydroLevels.copyFrom(pHydroLevelsRules); + return true; +} + } // namespace ScenarioBuilder } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h index b5da18307d..07eb802839 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.h @@ -58,6 +58,9 @@ class hydroLevelsData final : public dataInterface ** \brief Export the data into a mere INI file */ void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const; + void saveToINIFileHydroLevel(const Study& study, + Yuni::IO::File::Stream& file, + std::string addToPrefix) const; /*! ** \brief Assign a single value @@ -78,6 +81,7 @@ class hydroLevelsData final : public dataInterface void set_value(uint x, uint y, double value); bool apply(Study& study); + bool applyHydroLevels(Matrix& scenarioHydroLevels); private: //! Hydro levels overlay (0 if auto) diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index 48b7105e8e..ee93c62efc 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -64,8 +64,8 @@ void Rules::saveToINIFile(Yuni::IO::File::Stream& file) const linksNTC[i].saveToINIFile(study_, file); } // hydro levels - hydroInitialLevels.saveToINIFile(study_, file); - hydroFinalLevels.saveToINIFile(study_, file); + hydroInitialLevels.saveToINIFileHydroLevel(study_, file, "hl,"); + hydroFinalLevels.saveToINIFileHydroLevel(study_, file, "hfl,"); } file << '\n'; } @@ -367,8 +367,8 @@ bool Rules::apply() returned_status = renewable[i].apply(study_) && returned_status; returned_status = linksNTC[i].apply(study_) && returned_status; } - returned_status = hydroInitialLevels.apply(study_) && returned_status; - returned_status = hydroFinalLevels.apply(study_) && returned_status; + returned_status = hydroInitialLevels.applyHydroLevels(study_.scenarioInitialHydroLevels) && returned_status; + returned_status = hydroFinalLevels.applyHydroLevels(study_.scenarioFinalHydroLevels) && returned_status; } else returned_status = false; diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index d82b7f0e03..4b0cc9726e 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -32,7 +32,6 @@ #include "../fwd.h" #include "TSnumberData.h" #include "hydroLevelsData.h" -#include "hydroFinalLevelsData.h" #include #include @@ -121,7 +120,7 @@ class Rules final : private Yuni::NonCopyable //! hydro initial levels hydroLevelsData hydroInitialLevels; //! hydro final levels - hydroFinalLevelsData hydroFinalLevels; + hydroLevelsData hydroFinalLevels; // Links NTC std::vector linksNTC; From 90404191ec54fc4403bb69e039c96bac3836a695 Mon Sep 17 00:00:00 2001 From: Milos A Date: Fri, 3 Mar 2023 13:21:30 +0100 Subject: [PATCH 401/490] refactor FinalReservoirLevel function (++parameters) --- src/solver/simulation/apply-scenario.cpp | 8 +++- .../hydro-final-reservoir-level-functions.cpp | 43 +++++++++++-------- .../hydro-final-reservoir-level-functions.h | 6 ++- 3 files changed, 35 insertions(+), 22 deletions(-) diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 2d50c959ba..c5f9c70a1e 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -56,9 +56,13 @@ void ApplyCustomScenario(Data::Study& study) study.scenarioRulesDestroy(); logs.info(); - + // final reservoir level functions and pre-checks - FinalReservoirLevel(study); + FinalReservoirLevel(study.scenarioInitialHydroLevels, + study.scenarioFinalHydroLevels, + study.calendar, + study.parameters, + study.areas); } } // namespace Antares::Solver diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index a19bf42941..3712985835 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -33,35 +33,35 @@ namespace Antares namespace Solver { void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, - Data::Study& study, + const Date::Calendar& calendar, + const Data::Parameters& parameters, uint year) { - finLevData.simEndDay = study.parameters.simulationDays.end; - finLevData.simEndMonth = study.calendar.days[finLevData.simEndDay].month; - finLevData.simEndMonth_FirstDay = study.calendar.months[finLevData.simEndMonth].daysYear.first; - finLevData.simEndMonth_LastDay = study.calendar.months[finLevData.simEndMonth].daysYear.end; + finLevData.simEndDay = parameters.simulationDays.end; + finLevData.simEndMonth = calendar.days[finLevData.simEndDay].month; + finLevData.simEndMonth_FirstDay = calendar.months[finLevData.simEndMonth].daysYear.first; + finLevData.simEndMonth_LastDay = calendar.months[finLevData.simEndMonth].daysYear.end; finLevData.yearIndex = year; } void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, - Data::Study& study, + const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, Data::Area& area) { - finLevData.initialReservoirLevel - = study.scenarioInitialHydroLevels[area.index][finLevData.yearIndex]; - finLevData.finalReservoirLevel - = study.scenarioFinalHydroLevels[area.index][finLevData.yearIndex]; + finLevData.initialReservoirLevel = scenarioInitialHydroLevels[area.index][finLevData.yearIndex]; + finLevData.finalReservoirLevel = scenarioFinalHydroLevels[area.index][finLevData.yearIndex]; finLevData.deltaReservoirLevel = finLevData.initialReservoirLevel - finLevData.finalReservoirLevel; } void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, - Data::Study& study, + const Date::Calendar& calendar, Data::Area& area) { finLevData.initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; // month [0-11] finLevData.initReservoirLvlDay - = study.calendar.months[finLevData.initReservoirLvlMonth].daysYear.first; + = calendar.months[finLevData.initReservoirLvlMonth].daysYear.first; finLevData.reservoirCapacity = area.hydro.reservoirCapacity; } @@ -75,31 +75,36 @@ void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, = area.hydro.reservoirLevel[Data::PartHydro::maximum][simEndDayReal - 1]; } -void FinalReservoirLevel(Data::Study& study) +void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const Date::Calendar& calendar, + const Data::Parameters& parameters, + const Data::AreaList& areas) { bool preChecksPasses = true; - for (uint yearIndex = 0; yearIndex != study.scenarioFinalHydroLevels.height; ++yearIndex) + for (uint yearIndex = 0; yearIndex != scenarioFinalHydroLevels.height; ++yearIndex) { - study.areas.each( + areas.each( [&](Data::Area& area) { auto& finLevData = area.hydro.finalReservoirLevelRuntimeData; finLevData.fillEmpty(); - initializeGeneralData(finLevData, study, yearIndex); - initializePerAreaData(finLevData, study, area); + initializeGeneralData(finLevData, calendar, parameters, yearIndex); + initializePerAreaData( + finLevData, scenarioInitialHydroLevels, scenarioFinalHydroLevels, area); if (area.hydro.reservoirManagement && !area.hydro.useWaterValue && !isnan(finLevData.finalReservoirLevel) && !isnan(finLevData.initialReservoirLevel)) { - initializePreCheckData(finLevData, study, area); + initializePreCheckData(finLevData, calendar, area); finLevData.assignEndLevelAndDelta(); // determine simEnd month and FinalReservoirLevelMode int simEndRealMonth = finLevData.selectMode(); // log if the final reservoir level will be reached on some other day - uint simEndDayReal = study.calendar.months[simEndRealMonth].daysYear.first; + uint simEndDayReal = calendar.months[simEndRealMonth].daysYear.first; if (simEndDayReal == 0) simEndDayReal = DAYS_PER_YEAR; finLevData.logSimEndDayChange(simEndDayReal, area.name); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index ddf9bbd7a1..20b4451fc3 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -33,7 +33,11 @@ namespace Antares { namespace Solver { -void FinalReservoirLevel(Data::Study& study); +void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const Date::Calendar& calendar, + const Data::Parameters& parameters, + const Data::AreaList& areas); } // namespace Solver } // namespace Antares From e0bf2d6b4599eeda814775d3abaa9767d92d777c Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 17 Mar 2023 11:23:58 +0100 Subject: [PATCH 402/490] rename pre-check methods --- src/libs/antares/study/parts/hydro/container.h | 4 ++-- .../simulation/hydro-final-reservoir-level-functions.cpp | 4 ++-- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index dfed46fbf8..77fc08eeb8 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -174,7 +174,7 @@ class FinalReservoirLevelRuntimeData return totalYearInflows; } - bool preCheckOne(double totalYearInflows, AreaName name) + bool preCheckYearlyInflow(double totalYearInflows, AreaName name) { if ((-deltaReservoirLevel) * reservoirCapacity > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh @@ -189,7 +189,7 @@ class FinalReservoirLevelRuntimeData return true; } - bool preCheckTwo(AreaName name) + bool preCheckRuleCurves(AreaName name) { if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) { diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 3712985835..6c353bf60b 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -125,12 +125,12 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if (!finLevData.preCheckOne(totalInflows, area.name)) + if (!finLevData.preCheckYearlyInflow(totalInflows, area.name)) preChecksPasses = false; // pre-check 2 -> final reservoir level set by the user is within the // rule curves for the final day - if (!finLevData.preCheckTwo(area.name)) + if (!finLevData.preCheckRuleCurves(area.name)) preChecksPasses = false; } }); From 0f7ce46c0259fa7c88195d5a01852b64ec0fda5f Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 17 Mar 2023 12:21:55 +0100 Subject: [PATCH 403/490] update 13-file-format.md --- docs/reference-guide/13-file-format.md | 7 +++++++ 1 file changed, 7 insertions(+) diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md index c60592fe27..5644a908e8 100644 --- a/docs/reference-guide/13-file-format.md +++ b/docs/reference-guide/13-file-format.md @@ -1,5 +1,12 @@ # 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.6.0 +### Input +Under `Configure/MC Scenario Builder` existing section `Hydro Levels` changed name to `Hydro Initial Levels`\ +Under `Configure/MC Scenario Builder` new section added `Hydro Final Levels` + +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>** ## v8.5.0 ### Input From 38c5c939fca385b4357bfdc29bbd5c5a42122911 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 30 Mar 2023 15:07:44 +0200 Subject: [PATCH 404/490] remove UI changes from 13-file-format.md --- docs/reference-guide/13-file-format.md | 3 --- 1 file changed, 3 deletions(-) diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md index 5644a908e8..981b30737c 100644 --- a/docs/reference-guide/13-file-format.md +++ b/docs/reference-guide/13-file-format.md @@ -2,9 +2,6 @@ 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.6.0 ### Input -Under `Configure/MC Scenario Builder` existing section `Hydro Levels` changed name to `Hydro Initial Levels`\ -Under `Configure/MC Scenario Builder` new section added `Hydro Final Levels` - 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>** From 7c9b700988de55a65750f1fa98474f09817278d4 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 30 Mar 2023 18:41:21 +0200 Subject: [PATCH 405/490] remove partial year FRL implementation --- src/libs/antares/study/fwd.h | 10 -- .../antares/study/parts/hydro/container.h | 106 +++--------------- src/solver/hydro/management/management.cpp | 24 +--- src/solver/hydro/management/management.h | 5 - src/solver/hydro/management/monthly.cpp | 5 - .../hydro-final-reservoir-level-functions.cpp | 32 ++---- 6 files changed, 29 insertions(+), 153 deletions(-) diff --git a/src/libs/antares/study/fwd.h b/src/libs/antares/study/fwd.h index e99257f5fd..84e5ed4a82 100644 --- a/src/libs/antares/study/fwd.h +++ b/src/libs/antares/study/fwd.h @@ -242,16 +242,6 @@ enum TimeSeries }; // enum TimeSeries -enum FinalReservoirLevelMode -{ - //! Case-1: Day-1 -> Day-365 (complete year) - completeYear = 1, - //! Case-2A: Day-? -> Day-365 (reservoir level not initialized at 1.Jan, Last Simulation Day = 365) - //! Case-2B: Day-1 -> Day-? (reservoir level initialized at 1.Jan, Last Simulation Day != 365) - //! Case-2C: Day-? -> Day-? (reservoir level not initialized at 1.Jan, Last Simulation Day != 365) - incompleteYear = 2, -}; // enum Final Reservoir Level Mode - template struct TimeSeriesBitPatternIntoIndex; diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 77fc08eeb8..9c80bb295d 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -39,22 +39,14 @@ namespace Antares::Data */ class FinalReservoirLevelRuntimeData { -private: - using finalResLevelMode = Antares::Data::FinalReservoirLevelMode; - public: // FInal reservoir level runtime data std::vector includeFinalReservoirLevel; - std::vector finResLevelMode; std::vector endLevel; std::vector deltaLevel; - std::vector endMonthIndex; // Simulation Data uint simEndDay; - uint simEndMonth; - uint simEndMonth_FirstDay; - uint simEndMonth_LastDay; // simulation year uint yearIndex; @@ -64,20 +56,17 @@ class FinalReservoirLevelRuntimeData double finalReservoirLevel; double deltaReservoirLevel; double reservoirCapacity; - int initReservoirLvlMonth; - int initReservoirLvlDay; double lowLevelLastDay; double highLevelLastDay; + int initReservoirLvlMonth; // methods: void fillEmpty() { includeFinalReservoirLevel.push_back(false); - finResLevelMode.push_back(completeYear); - deltaLevel.push_back(0.); endLevel.push_back(0.); - endMonthIndex.push_back(0); + deltaLevel.push_back(0.); } void assignEndLevelAndDelta() @@ -87,91 +76,24 @@ class FinalReservoirLevelRuntimeData deltaLevel.at(yearIndex) = deltaReservoirLevel; } - int selectMode() - { - int simEndRealMonth = 0; - // Mode-1 - if (initReservoirLvlDay == 0 && simEndDay == DAYS_PER_YEAR) - { - finResLevelMode.at(yearIndex) = completeYear; - return simEndRealMonth; - } - // Mode-2 - else if (initReservoirLvlDay != 0 && simEndDay == DAYS_PER_YEAR) - { - finResLevelMode.at(yearIndex) = incompleteYear; - return simEndRealMonth; - } - // Mode-3/4 - else - { - // select month in which to reach final reservoir level (1st day of the selected month) - simEndRealMonth - = (simEndDay - simEndMonth_FirstDay) <= (simEndMonth_LastDay - simEndDay) - ? simEndMonth - : simEndMonth + 1; - finResLevelMode.at(yearIndex) = incompleteYear; - - if (simEndRealMonth == 12 && initReservoirLvlDay == 0) - { - simEndRealMonth = 0; - finResLevelMode.at(yearIndex) = completeYear; - } - // E.g. End Date = 21.Dec && InitReservoirLevelDate = 1.Jan -> - // - > go back to first case - else if (simEndRealMonth == 12 && initReservoirLvlDay != 0) - simEndRealMonth = 0; - // End Date = 21.Dec && InitReservoirLevelDate = 1.Mar - // Reach FinalReservoirLevel at 1.Jan - else if (simEndRealMonth == initReservoirLvlMonth && simEndDay >= initReservoirLvlDay) - simEndRealMonth = (simEndRealMonth + 1) % 12; - // E.g. End Date = 10.Jan && InitReservoirLevelDate = 1.Jan -> - // we need to move FinalReservoirLevel to 1.Feb. - // Cannot do both init and final on the same day - else if (simEndRealMonth == initReservoirLvlMonth && simEndDay < initReservoirLvlDay) - simEndRealMonth = (simEndRealMonth - 1) % 12; - // E.g. End Date = 25.Nov && InitReservoirLevelDate = 1.Dec -> - // we need to move FinalReservoirLevel to 1.Nov. - // Cannot do both init and final on the same day - - return simEndRealMonth; - } - } - - void logSimEndDayChange(int simEndDayReal, AreaName name) + double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows) { - if (simEndDay != simEndDayReal) - { - logs.info() << "Year: " << yearIndex + 1 << ". Area: " << name - << ". Final reservoir level will be reached on day: " << simEndDayReal; - } - } - - void shiftMonths(int simEndRealMonth) - { - int h20_solver_sim_end_month = (simEndRealMonth - initReservoirLvlMonth) >= 0 - ? simEndRealMonth - initReservoirLvlMonth - : simEndRealMonth - initReservoirLvlMonth + 12; - endMonthIndex.at(yearIndex) = h20_solver_sim_end_month; + double totalYearInflows = 0.0; + for (uint day = 0; day < DAYS_PER_YEAR; ++day) + totalYearInflows += srcinflows[day]; + return totalYearInflows; } - double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows, - uint simEndDayReal) + bool preCheckStartAndEndSim(AreaName name) { - double totalYearInflows = 0.0; - if (initReservoirLvlDay <= simEndDayReal) - { - for (uint day = initReservoirLvlDay; day < simEndDayReal; ++day) - totalYearInflows += srcinflows[day]; - } - else + if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) + return true; { - for (uint day = initReservoirLvlDay; day < DAYS_PER_YEAR; ++day) - totalYearInflows += srcinflows[day]; - for (uint day = 0; day < simEndDayReal; ++day) - totalYearInflows += srcinflows[day]; + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name + << ". Simulation must end on day 365 and reservoir level must be " + "initiated in January"; + return false; } - return totalYearInflows; } bool preCheckYearlyInflow(double totalYearInflows, AreaName name) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index bf4f595861..4e5918500a 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -145,30 +145,18 @@ void HydroManagement::prepareFinalReservoirLevelData(uint numSpace, uint year) [&](Data::Area& area) { auto& data = pAreas[numSpace][area.index]; - data.finalReservoirLevel = -1.0; if (area.hydro.finalReservoirLevelRuntimeData.deltaLevel.empty()) return; if (!area.hydro.finalReservoirLevelRuntimeData.includeFinalReservoirLevel[year]) return; - if (area.hydro.finalReservoirLevelRuntimeData.finResLevelMode[year] - == Data::FinalReservoirLevelMode::completeYear) - { - double delta = area.hydro.finalReservoirLevelRuntimeData.deltaLevel[year]; - // must be done before prepareMonthlyTargetGenerations - if (delta > 0) - data.inflows[0] += delta; - else if (delta < 0) - data.inflows[11] += delta; - } - else if (area.hydro.finalReservoirLevelRuntimeData.finResLevelMode[year] - == Data::FinalReservoirLevelMode::incompleteYear) - { - data.finalReservoirLevel = area.hydro.finalReservoirLevelRuntimeData.endLevel[year]; - data.finalReservoirLevelMonth - = area.hydro.finalReservoirLevelRuntimeData.endMonthIndex[year]; - } + double delta = area.hydro.finalReservoirLevelRuntimeData.deltaLevel[year]; + // must be done before prepareMonthlyTargetGenerations + if (delta > 0) + data.inflows[0] += delta; + else if (delta < 0) + data.inflows[11] += delta; }); } diff --git a/src/solver/hydro/management/management.h b/src/solver/hydro/management/management.h index 38bac99b7a..e57c817ee3 100644 --- a/src/solver/hydro/management/management.h +++ b/src/solver/hydro/management/management.h @@ -138,11 +138,6 @@ class HydroManagement final //! Daily optimized Generation double DOG[dayYearCount]; - //! Final reservoir level - double finalReservoirLevel; - //! Month to reach final reservoir level (h20_solver month, not real month); - uint finalReservoirLevelMonth; - }; // struct PerArea //! Temporary data per area diff --git a/src/solver/hydro/management/monthly.cpp b/src/solver/hydro/management/monthly.cpp index 27356c4a7a..e03b06aaff 100644 --- a/src/solver/hydro/management/monthly.cpp +++ b/src/solver/hydro/management/monthly.cpp @@ -189,11 +189,6 @@ void HydroManagement::prepareMonthlyOptimalGenerations(double* random_reservoir_ problem.VolumeMin[month] = minLvl[firstDay]; problem.VolumeMax[month] = maxLvl[firstDay]; } - - // fix reservoir level for specified month if final reservoir level is used - if (data.finalReservoirLevel != -1.0) - problem.VolumeMin[data.finalReservoirLevelMonth] - = problem.VolumeMax[data.finalReservoirLevelMonth] = data.finalReservoirLevel; H2O_M_OptimiserUneAnnee(&problem, 0); switch (problem.ResultatsValides) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 6c353bf60b..24246a9a03 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -38,9 +38,6 @@ void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, uint year) { finLevData.simEndDay = parameters.simulationDays.end; - finLevData.simEndMonth = calendar.days[finLevData.simEndDay].month; - finLevData.simEndMonth_FirstDay = calendar.months[finLevData.simEndMonth].daysYear.first; - finLevData.simEndMonth_LastDay = calendar.months[finLevData.simEndMonth].daysYear.end; finLevData.yearIndex = year; } @@ -60,19 +57,15 @@ void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, Data::Area& area) { finLevData.initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; // month [0-11] - finLevData.initReservoirLvlDay - = calendar.months[finLevData.initReservoirLvlMonth].daysYear.first; finLevData.reservoirCapacity = area.hydro.reservoirCapacity; } -void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, - uint simEndDayReal, - Data::Area& area) +void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, Data::Area& area) { finLevData.lowLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::minimum][simEndDayReal - 1]; + = area.hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; finLevData.highLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::maximum][simEndDayReal - 1]; + = area.hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; } void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, @@ -100,20 +93,13 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, initializePreCheckData(finLevData, calendar, area); finLevData.assignEndLevelAndDelta(); - // determine simEnd month and FinalReservoirLevelMode - int simEndRealMonth = finLevData.selectMode(); - - // log if the final reservoir level will be reached on some other day - uint simEndDayReal = calendar.months[simEndRealMonth].daysYear.first; - if (simEndDayReal == 0) - simEndDayReal = DAYS_PER_YEAR; - finLevData.logSimEndDayChange(simEndDayReal, area.name); - - // Now convert to h20-solver-month if initialization is not done in January - finLevData.shiftMonths(simEndRealMonth); + // pre-check 0 -> simulation must end on day 365 and reservoir level must be + // initiated in January + if (!finLevData.preCheckStartAndEndSim(area.name)) + preChecksPasses = false; // rule curve values for simEndDayReal - ruleCurveForSimEndReal(finLevData, simEndDayReal, area); + ruleCurveForSimEndReal(finLevData, area); // calculate (partial)yearly inflows const Data::DataSeriesHydro& data = *area.hydro.series; @@ -121,7 +107,7 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, auto& inflowsmatrix = area.hydro.series->storage; auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; - double totalInflows = finLevData.calculateTotalInflows(srcinflows, simEndDayReal); + double totalInflows = finLevData.calculateTotalInflows(srcinflows); // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows From 844f55334e555c392b930befde04013989ac9f4c Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 16 Jun 2023 16:49:25 +0200 Subject: [PATCH 406/490] fix bug - add new files to CMakeList --- src/solver/simulation/CMakeLists.txt | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/solver/simulation/CMakeLists.txt b/src/solver/simulation/CMakeLists.txt index 56352488ae..75849ea75a 100644 --- a/src/solver/simulation/CMakeLists.txt +++ b/src/solver/simulation/CMakeLists.txt @@ -40,6 +40,8 @@ set(SRC_SIMULATION opt_time_writer.cpp adequacy_patch_runtime_data.h adequacy_patch_runtime_data.cpp + hydro-final-reservoir-level-functions.h + hydro-final-reservoir-level-functions.cpp ) source_group("simulation" FILES ${SRC_SIMULATION}) From 4e20ac2cfa50216fa4fb1906f68efe034819eed3 Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Wed, 21 Jun 2023 09:20:47 +0200 Subject: [PATCH 407/490] Final reservoir level cr25 rtei dev - sonar cloud smells (#1373) * Minor code smells resloved * Major code smells * Critical code smells --------- Co-authored-by: NikolaIlic --- docs/reference-guide/13-file-format.md | 2 +- .../antares/study/parts/hydro/container.h | 9 ++--- .../scenario-builder/hydroLevelsData.cpp | 9 +++-- .../study/scenario-builder/hydroLevelsData.h | 6 ++-- src/solver/hydro/management/management.cpp | 2 +- src/solver/simulation/apply-scenario.cpp | 1 - .../hydro-final-reservoir-level-functions.cpp | 35 +++++++++---------- .../hydro-final-reservoir-level-functions.h | 8 ++--- ...scenario-builder-hydro-levels-renderer.cpp | 30 +++++++--------- 9 files changed, 49 insertions(+), 53 deletions(-) diff --git a/docs/reference-guide/13-file-format.md b/docs/reference-guide/13-file-format.md index 92900e3b55..40401cf5ab 100644 --- a/docs/reference-guide/13-file-format.md +++ b/docs/reference-guide/13-file-format.md @@ -30,7 +30,7 @@ For each thermal cluster, in existing file **input/thermal/clusters/<area> For each thermal cluster, new files added **input/thermal/prepro/<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) -#### Final Reservoir Level +#### 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>** diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 9c80bb295d..0b0194fac2 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -76,7 +76,7 @@ class FinalReservoirLevelRuntimeData deltaLevel.at(yearIndex) = deltaReservoirLevel; } - double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows) + double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows) const { double totalYearInflows = 0.0; for (uint day = 0; day < DAYS_PER_YEAR; ++day) @@ -84,10 +84,11 @@ class FinalReservoirLevelRuntimeData return totalYearInflows; } - bool preCheckStartAndEndSim(AreaName name) + bool preCheckStartAndEndSim(const AreaName& name) const { if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) return true; + else { logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name << ". Simulation must end on day 365 and reservoir level must be " @@ -96,7 +97,7 @@ class FinalReservoirLevelRuntimeData } } - bool preCheckYearlyInflow(double totalYearInflows, AreaName name) + bool preCheckYearlyInflow(double totalYearInflows, const AreaName& name) const { if ((-deltaReservoirLevel) * reservoirCapacity > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh @@ -111,7 +112,7 @@ class FinalReservoirLevelRuntimeData return true; } - bool preCheckRuleCurves(AreaName name) + bool preCheckRuleCurves(const AreaName& name) const { if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) { diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index ea739f06dd..16884533e3 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -48,11 +48,16 @@ bool hydroLevelsData::reset(const Study& study) void hydroLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const { + /** + * This function is inherited from dataInterface class as pure virtual member function and it + * must be overriden. Function does not have body because it can not provide desired + * functionality due to lack of necessary function parameters. + */ } void hydroLevelsData::saveToINIFileHydroLevel(const Study& study, Yuni::IO::File::Stream& file, - std::string addToPrefix) const + const std::string& addToPrefix) const { // Prefix CString<512, false> prefix; @@ -95,7 +100,7 @@ bool hydroLevelsData::apply(Study& study) return true; } -bool hydroLevelsData::applyHydroLevels(Matrix& scenarioHydroLevels) +bool hydroLevelsData::applyHydroLevels(Matrix& scenarioHydroLevels) const { scenarioHydroLevels.copyFrom(pHydroLevelsRules); return true; diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h index 07eb802839..349dab4886 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.h @@ -57,10 +57,10 @@ class hydroLevelsData final : public dataInterface /*! ** \brief Export the data into a mere INI file */ - void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const; + void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; void saveToINIFileHydroLevel(const Study& study, Yuni::IO::File::Stream& file, - std::string addToPrefix) const; + const std::string& addToPrefix) const; /*! ** \brief Assign a single value @@ -81,7 +81,7 @@ class hydroLevelsData final : public dataInterface void set_value(uint x, uint y, double value); bool apply(Study& study); - bool applyHydroLevels(Matrix& scenarioHydroLevels); + bool applyHydroLevels(Matrix& scenarioHydroLevels) const; private: //! Hydro levels overlay (0 if auto) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 90b14e33d0..0c472fd4e0 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -354,7 +354,7 @@ bool HydroManagement::checkMinGeneration(uint numSpace) void HydroManagement::prepareFinalReservoirLevelData(uint numSpace, uint year) { study.areas.each( - [&](Data::Area& area) + [this, &numSpace, &year](Data::Area& area) { auto& data = pAreas[numSpace][area.index]; if (area.hydro.finalReservoirLevelRuntimeData.deltaLevel.empty()) diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index c5f9c70a1e..10a89cd54d 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -60,7 +60,6 @@ void ApplyCustomScenario(Data::Study& study) // final reservoir level functions and pre-checks FinalReservoirLevel(study.scenarioInitialHydroLevels, study.scenarioFinalHydroLevels, - study.calendar, study.parameters, study.areas); } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 24246a9a03..9ebe60eaa7 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -28,12 +28,9 @@ #include "hydro-final-reservoir-level-functions.h" #include -namespace Antares +namespace Antares::Solver { -namespace Solver -{ -void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Date::Calendar& calendar, +static void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, const Data::Parameters& parameters, uint year) { @@ -41,10 +38,10 @@ void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, finLevData.yearIndex = year; } -void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, +static void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - Data::Area& area) + const Data::Area& area) { finLevData.initialReservoirLevel = scenarioInitialHydroLevels[area.index][finLevData.yearIndex]; finLevData.finalReservoirLevel = scenarioFinalHydroLevels[area.index][finLevData.yearIndex]; @@ -53,8 +50,7 @@ void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, } void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Date::Calendar& calendar, - Data::Area& area) + const Data::Area& area) { finLevData.initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; // month [0-11] finLevData.reservoirCapacity = area.hydro.reservoirCapacity; @@ -70,7 +66,6 @@ void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, Da void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const Date::Calendar& calendar, const Data::Parameters& parameters, const Data::AreaList& areas) { @@ -78,11 +73,16 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, for (uint yearIndex = 0; yearIndex != scenarioFinalHydroLevels.height; ++yearIndex) { areas.each( - [&](Data::Area& area) + [&scenarioInitialHydroLevels, + &scenarioFinalHydroLevels, + ¶meters, + &areas, + &preChecksPasses, + &yearIndex](Data::Area& area) { auto& finLevData = area.hydro.finalReservoirLevelRuntimeData; finLevData.fillEmpty(); - initializeGeneralData(finLevData, calendar, parameters, yearIndex); + initializeGeneralData(finLevData, parameters, yearIndex); initializePerAreaData( finLevData, scenarioInitialHydroLevels, scenarioFinalHydroLevels, area); @@ -90,7 +90,7 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, && !isnan(finLevData.finalReservoirLevel) && !isnan(finLevData.initialReservoirLevel)) { - initializePreCheckData(finLevData, calendar, area); + initializePreCheckData(finLevData, area); finLevData.assignEndLevelAndDelta(); // pre-check 0 -> simulation must end on day 365 and reservoir level must be @@ -103,15 +103,15 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, // calculate (partial)yearly inflows const Data::DataSeriesHydro& data = *area.hydro.series; - int tsHydroIndex = data.timeseriesNumbers[0][finLevData.yearIndex]; + uint tsHydroIndex = data.timeseriesNumbers[0][finLevData.yearIndex]; auto& inflowsmatrix = area.hydro.series->storage; auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; - double totalInflows = finLevData.calculateTotalInflows(srcinflows); // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if (!finLevData.preCheckYearlyInflow(totalInflows, area.name)) + if (double totalInflows = finLevData.calculateTotalInflows(srcinflows); + !finLevData.preCheckYearlyInflow(totalInflows, area.name)) preChecksPasses = false; // pre-check 2 -> final reservoir level set by the user is within the @@ -128,5 +128,4 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, } } -} // namespace Solver -} // namespace Antares \ No newline at end of file +} // namespace Anatres::Solver \ No newline at end of file diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 20b4451fc3..da2aaffe0e 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -29,16 +29,12 @@ #include -namespace Antares -{ -namespace Solver +namespace Antares::Solver { void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const Date::Calendar& calendar, const Data::Parameters& parameters, const Data::AreaList& areas); -} // namespace Solver -} // namespace Antares +} // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_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 6d4f2dcffc..f01affa6f6 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 @@ -46,30 +46,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->hydroInitialLevels.width()); - assert((uint)x < pRules->hydroInitialLevels.height()); - double val = fromStringToHydroLevel(value, 100.) / 100.; - pRules->hydroInitialLevels.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->hydroInitialLevels.width()); - assert((uint)x < pRules->hydroInitialLevels.height()); - return pRules->hydroInitialLevels.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 +73,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 From ede74c4f1a3fac08f4715ad54f517e16343fa2ab Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Wed, 21 Jun 2023 12:05:37 +0200 Subject: [PATCH 408/490] Additional code smells resolved --- .../hydro-final-reservoir-level-functions.cpp | 1 - ...io-builder-hydro-final-levels-renderer.cpp | 28 ++++++++----------- 2 files changed, 12 insertions(+), 17 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 9ebe60eaa7..13d7f6d733 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -76,7 +76,6 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, [&scenarioInitialHydroLevels, &scenarioFinalHydroLevels, ¶meters, - &areas, &preChecksPasses, &yearIndex](Data::Area& area) { 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 index f8fffbfea3..b00ee5eb8b 100644 --- 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 @@ -46,30 +46,26 @@ wxString hydroFinalLevelsScBuilderRenderer::cellValue(int x, int y) const bool hydroFinalLevelsScBuilderRenderer::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->hydroFinalLevels.width()); - assert((uint)x < pRules->hydroFinalLevels.height()); - double val = fromStringToHydroLevel(value, 100.) / 100.; - pRules->hydroFinalLevels.set_value(x, y, val); - return true; - } + 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) + if (!(!study) && !(!pRules) && (uint)x < study->parameters.nbYears + && (uint)y < study->areas.size()) { - if ((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.; - } + assert((uint)y < pRules->hydroFinalLevels.width()); + assert((uint)x < pRules->hydroFinalLevels.height()); + return pRules->hydroFinalLevels.get_value(x, y) * 100.; } return 0.; } From 9cda9d52ce657875fd8497b27a2d24653a36fb68 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Wed, 21 Jun 2023 12:09:42 +0200 Subject: [PATCH 409/490] Exclude parentheses --- .../renderer/scenario-builder-hydro-final-levels-renderer.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index b00ee5eb8b..1d4e6d56b7 100644 --- 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 @@ -73,7 +73,7 @@ double hydroFinalLevelsScBuilderRenderer::cellNumericValue(int x, int y) const IRenderer::CellStyle hydroFinalLevelsScBuilderRenderer::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 From 1c8e178d948efc917f3d76d35d80c338fb815f44 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 22 Jun 2023 11:16:54 +0200 Subject: [PATCH 410/490] add explanation comments --- src/libs/antares/study/parts/hydro/container.h | 8 +++++++- 1 file changed, 7 insertions(+), 1 deletion(-) diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 0b0194fac2..17d7c9174f 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -40,7 +40,11 @@ namespace Antares::Data class FinalReservoirLevelRuntimeData { public: - // FInal reservoir level runtime data + // Final reservoir level runtime data + + // vectors containing data necessary for final reservoir level calculation + // for one area and all MC years + // vector indexes correspond to the MC years std::vector includeFinalReservoirLevel; std::vector endLevel; std::vector deltaLevel; @@ -49,9 +53,11 @@ class FinalReservoirLevelRuntimeData uint simEndDay; // simulation year + // overwritten after each MC year uint yearIndex; // data per area + // data overwritten after each MC year double initialReservoirLevel; double finalReservoirLevel; double deltaReservoirLevel; From 6b045e086aa80318c4d6c065116ae2f96af3ec19 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 22 Jun 2023 11:17:10 +0200 Subject: [PATCH 411/490] Date, authors --- .../simulation/hydro-final-reservoir-level-functions.cpp | 4 ++-- src/solver/simulation/hydro-final-reservoir-level-functions.h | 4 ++-- .../renderer/scenario-builder-hydro-final-levels-renderer.cpp | 4 ++-- .../renderer/scenario-builder-hydro-final-levels-renderer.h | 4 ++-- 4 files changed, 8 insertions(+), 8 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 13d7f6d733..6aaccf4dd6 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index da2aaffe0e..ac6d08f1fa 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** 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 index 1d4e6d56b7..809767e8e6 100644 --- 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 @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** 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 index ddbdd39eef..85a7c87e0f 100644 --- 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 @@ -1,6 +1,6 @@ /* -** Copyright 2007-2018 RTE -** Authors: Antares_Simulator Team +** Copyright 2007-2023 RTE +** Authors: RTE-international / Redstork / Antares_Simulator Team ** ** This file is part of Antares_Simulator. ** From 85e2ae29b7d6c0b4caa1eb2bc796c36e85de066d Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 22 Jun 2023 12:46:46 +0200 Subject: [PATCH 412/490] move prefix to the constructor of hydroLevelsData --- .../study/scenario-builder/hydroLevelsData.cpp | 16 +++++----------- .../study/scenario-builder/hydroLevelsData.h | 9 +++++---- .../antares/study/scenario-builder/rules.cpp | 4 ++-- src/libs/antares/study/scenario-builder/rules.h | 6 ++++-- 4 files changed, 16 insertions(+), 19 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index 16884533e3..bc73517a07 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -36,6 +36,11 @@ namespace Data { namespace ScenarioBuilder { +hydroLevelsData::hydroLevelsData(std::string& saveToINIFilePrefix) : +addToPrefix(saveToINIFilePrefix) +{ +} + bool hydroLevelsData::reset(const Study& study) { const uint nbYears = study.parameters.nbYears; @@ -47,17 +52,6 @@ bool hydroLevelsData::reset(const Study& study) } void hydroLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const -{ - /** - * This function is inherited from dataInterface class as pure virtual member function and it - * must be overriden. Function does not have body because it can not provide desired - * functionality due to lack of necessary function parameters. - */ -} - -void hydroLevelsData::saveToINIFileHydroLevel(const Study& study, - Yuni::IO::File::Stream& file, - const std::string& addToPrefix) const { // Prefix CString<512, false> prefix; diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h index 349dab4886..6c14c9509a 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.h @@ -45,7 +45,9 @@ class hydroLevelsData final : public dataInterface using MatrixType = Matrix; public: - // We use default constructor and destructor + // Constructor + + hydroLevelsData(std::string& saveToINIFilePrefix); //! \name Data manupulation //@{ @@ -58,9 +60,6 @@ class hydroLevelsData final : public dataInterface ** \brief Export the data into a mere INI file */ void saveToINIFile(const Study& study, Yuni::IO::File::Stream& file) const override; - void saveToINIFileHydroLevel(const Study& study, - Yuni::IO::File::Stream& file, - const std::string& addToPrefix) const; /*! ** \brief Assign a single value @@ -86,6 +85,8 @@ class hydroLevelsData final : public dataInterface private: //! Hydro levels overlay (0 if auto) MatrixType pHydroLevelsRules; + // prefix to be added when calling saveToINIFileHydroLevel + std::string& addToPrefix; }; // class hydroLevelsData diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index bd315ad98d..b455435bc9 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -64,8 +64,8 @@ void Rules::saveToINIFile(Yuni::IO::File::Stream& file) const linksNTC[i].saveToINIFile(study_, file); } // hydro levels - hydroInitialLevels.saveToINIFileHydroLevel(study_, file, "hl,"); - hydroFinalLevels.saveToINIFileHydroLevel(study_, file, "hfl,"); + hydroInitialLevels.saveToINIFile(study_, file); + hydroFinalLevels.saveToINIFile(study_, file); } binding_constraints.saveToINIFile(study_, file); file << '\n'; diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index bf1acc2f83..f85e0a3db4 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -118,9 +118,11 @@ class Rules final : private Yuni::NonCopyable std::vector renewable; //! hydro initial levels - hydroLevelsData hydroInitialLevels; + std::string prefixInitial = "hl"; + hydroLevelsData hydroInitialLevels = hydroLevelsData(prefixInitial); //! hydro final levels - hydroLevelsData hydroFinalLevels; + std::string prefixFinal = "hfl"; + hydroLevelsData hydroFinalLevels = hydroLevelsData(prefixFinal); // Links NTC std::vector linksNTC; From 1d7b185e8b543f1c957cfdf7d8837c398aab20b4 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 22 Jun 2023 16:13:06 +0200 Subject: [PATCH 413/490] fix hl-hfl bug --- src/libs/antares/study/scenario-builder/rules.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index f85e0a3db4..1f97e01c46 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -118,10 +118,10 @@ class Rules final : private Yuni::NonCopyable std::vector renewable; //! hydro initial levels - std::string prefixInitial = "hl"; + std::string prefixInitial = "hl,"; hydroLevelsData hydroInitialLevels = hydroLevelsData(prefixInitial); //! hydro final levels - std::string prefixFinal = "hfl"; + std::string prefixFinal = "hfl,"; hydroLevelsData hydroFinalLevels = hydroLevelsData(prefixFinal); // Links NTC From c81c69bdad020414c3e62b7594fe053626d1459c Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Mon, 3 Jul 2023 13:32:49 +0200 Subject: [PATCH 414/490] Testing final reservoir level functions --- .../hydro-final-reservoir-level-functions.cpp | 4 +- .../hydro-final-reservoir-level-functions.h | 13 + .../src/solver/simulation/CMakeLists.txt | 29 ++ ...-hydro-final-reservoir-level-functions.cpp | 267 ++++++++++++++++++ 4 files changed, 311 insertions(+), 2 deletions(-) create mode 100644 src/tests/src/solver/simulation/test-hydro-final-reservoir-level-functions.cpp diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 6aaccf4dd6..5c36b2aad7 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -30,7 +30,7 @@ namespace Antares::Solver { -static void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, +void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, const Data::Parameters& parameters, uint year) { @@ -38,7 +38,7 @@ static void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevDa finLevData.yearIndex = year; } -static void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, +void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, const Data::Area& area) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index ac6d08f1fa..da0b618ff4 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,6 +31,19 @@ namespace Antares::Solver { +void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, + const Data::Parameters& parameters, + uint year); + +void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, + const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const Data::Area& area); + +void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, + const Data::Area& area); + +void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, Data::Area& area); void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, const Data::Parameters& parameters, diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index 06fa99fb9d..03e9ae312c 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -85,3 +85,32 @@ add_test(NAME time_series COMMAND test-time_series) set_property(TEST time_series PROPERTY LABELS unit) +# =================================== +# Tests on hydro final reservoir level functions +# =================================== +set(SRC_HYDRO_FINAL_LEVEL + ${src_solver_simulation}/hydro-final-reservoir-level-functions.h + ${src_solver_simulation}/hydro-final-reservoir-level-functions.cpp +) + +add_executable(test-hydro_final + test-hydro-final-reservoir-level-functions.cpp + ${SRC_HYDRO_FINAL_LEVEL}) + +target_include_directories(test-hydro_final + PRIVATE + "${src_solver_simulation}" + "${src_libs_antares_study}" +) +target_link_libraries(test-hydro_final + PRIVATE + Boost::unit_test_framework + libantares-core + libantares-solver-simulation +) + +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..dcba226ce5 --- /dev/null +++ b/src/tests/src/solver/simulation/test-hydro-final-reservoir-level-functions.cpp @@ -0,0 +1,267 @@ +// +// Created by Nikola Ilic on 23/06/23. +// +#define BOOST_TEST_MODULE hydro - final - level +#define WIN32_LEAN_AND_MEAN +#include + +#include "hydro-final-reservoir-level-functions.h" +#include + +using namespace Antares::Solver; +using namespace Antares::Data; + +void InstantiateAreaHydroStorage(Matrix& storage, double seed, uint nbYears) +{ + for (uint i = 0; i < nbYears; i++) + { + for (uint days = 0; days < DAYS_PER_YEAR; days++) + { + if (days == 0) + storage[i][days] = seed + 1; + + if (days == DAYS_PER_YEAR - 1) + storage[i][days] = seed + 2; + + storage[i][days] = seed; + } + } +} + +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() + { + // Parameters data + // endDay must be 365, see preCheckStartAndEndSim function + Parameters& parameters = study->parameters; + + uint& endDay = parameters.simulationDays.end; + uint& nbYears = parameters.nbYears; + endDay = 365; + nbYears = 2; + + // Creating two dummy areas and instantiating necessary values for testing + area_1 = study->areaAdd("Area1"); + area_2 = study->areaAdd("Area2"); + + // Enable reservoir management + area_1->hydro.reservoirManagement = true; + area_2->hydro.reservoirManagement = true; + + // Disable water values + area_1->hydro.useWaterValue = false; + area_2->hydro.useWaterValue = false; + + // For extracting how many areas are in area map + AreaList& areas = study->areas; + Area::Map& areasMap = areas.areas; + + // Level date must be 0, see preCheckStartAndEndSim function + auto& initializeReservoirLevelDateArea1 = area_1->hydro.initializeReservoirLevelDate; + auto& initializeReservoirLevelDateArea2 = area_2->hydro.initializeReservoirLevelDate; + + initializeReservoirLevelDateArea1 = 0; + initializeReservoirLevelDateArea2 = 0; + + // Initialize reservoir capacity + auto& reservoirCapacityArea1 = area_1->hydro.reservoirCapacity; + auto& reservoirCapacityArea2 = area_2->hydro.reservoirCapacity; + + reservoirCapacityArea1 = 340.; + reservoirCapacityArea2 = 300; + + // Initialize reservoir max and min levels, but just for the last day in year + auto& reservoirLevelArea1 = area_1->hydro.reservoirLevel; + auto& reservoirLevelArea2 = area_2->hydro.reservoirLevel; + + reservoirLevelArea1.reset(3, DAYS_PER_YEAR, true); + reservoirLevelArea2.reset(3, DAYS_PER_YEAR, true); + + auto& reservoirLevelArea1Min + = reservoirLevelArea1[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + auto& reservoirLevelArea2Min + = reservoirLevelArea2[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + + auto& reservoirLevelArea1Max + = reservoirLevelArea1[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + auto& reservoirLevelArea2Max + = reservoirLevelArea2[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + + reservoirLevelArea1Min = 2.4; + reservoirLevelArea1Max = 6.5; + + reservoirLevelArea2Min = 2.7; + reservoirLevelArea2Max = 6.4; + + // Defining necessary references for initial and final level matrices + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + + // Initializing dimension of matrices + uint width = nbYears; + uint height = areasMap.size(); + + // Setting matrices dimension Scenario Builder Initial and Finals levels matrices + scenarioInitialHydroLevels.resize(width, height); + scenarioFinalHydroLevels.resize(width, height); + + // Instantiating matrices with some random values + scenarioInitialHydroLevels[0][0] = 2.3; + scenarioInitialHydroLevels[0][1] = 4.2; + scenarioInitialHydroLevels[1][0] = 1.5; + scenarioInitialHydroLevels[1][1] = 2.4; + + scenarioFinalHydroLevels[0][0] = 3.4; + scenarioFinalHydroLevels[0][1] = 5.1; + scenarioFinalHydroLevels[1][0] = 3.5; + scenarioFinalHydroLevels[1][1] = 4.3; + + // References for timeseriesNumbers data and instantiating timeseriesNumbers matrices + Matrix& timeseriesNumbersArea1 = area_1->hydro.series->timeseriesNumbers; + Matrix& timeseriesNumbersArea2 = area_2->hydro.series->timeseriesNumbers; + + timeseriesNumbersArea1.resize(nbYears, 1); + timeseriesNumbersArea2.resize(nbYears, 1); + + timeseriesNumbersArea1[0][0] = 0; + timeseriesNumbersArea1[0][1] = 1; + + timeseriesNumbersArea2[0][0] = 0; + timeseriesNumbersArea2[0][1] = 1; + + // Instantiating areas storage TS's + auto& storageArea1 = area_1->hydro.series->storage; + auto& storageArea2 = area_2->hydro.series->storage; + + storageArea1.resize(nbYears, 365); + storageArea2.resize(nbYears, 365); + + InstantiateAreaHydroStorage(storageArea1, 200., nbYears); + InstantiateAreaHydroStorage(storageArea2, 300., nbYears); + } + + ~Fixture() = default; + + Study::Ptr study = std::make_shared(); + Area* area_1; + Area* area_2; +}; + +BOOST_FIXTURE_TEST_SUITE(s, Fixture) + +BOOST_AUTO_TEST_CASE(Testing_initializeGeneralData_function_for_area_1) +{ + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + year = 5; + + auto& RuntimeData = area_1->hydro.finalReservoirLevelRuntimeData; + + initializeGeneralData(RuntimeData, parameters, year); + + BOOST_CHECK_EQUAL(RuntimeData.simEndDay, parameters.simulationDays.end); + BOOST_CHECK_EQUAL(RuntimeData.yearIndex, year); +} + +BOOST_AUTO_TEST_CASE(Testing_initializePerAreaData_function_for_area_2s) +{ + FinalReservoirLevelRuntimeData& finLevData = area_2->hydro.finalReservoirLevelRuntimeData; + auto& initialReservoirLevel = finLevData.initialReservoirLevel; + auto& finalReservoirLevel = finLevData.finalReservoirLevel; + auto& deltaReservoirLevel = finLevData.deltaReservoirLevel; + + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + + auto& InitialHydroLevelsRef = scenarioInitialHydroLevels[1][0]; + auto& FinalHydroLevelsRef = scenarioFinalHydroLevels[1][0]; + + initializePerAreaData( + finLevData, scenarioInitialHydroLevels, scenarioFinalHydroLevels, *area_2); + + BOOST_CHECK_EQUAL(initialReservoirLevel, InitialHydroLevelsRef); + BOOST_CHECK_EQUAL(finalReservoirLevel, FinalHydroLevelsRef); + BOOST_CHECK_EQUAL(deltaReservoirLevel, (InitialHydroLevelsRef - FinalHydroLevelsRef)); +} + +BOOST_AUTO_TEST_CASE(Testing_initializePreCheckData_function_for_area_2) +{ + FinalReservoirLevelRuntimeData& finLevData = area_2->hydro.finalReservoirLevelRuntimeData; + + auto& initReservoirLvlMonth = finLevData.initReservoirLvlMonth; + auto& reservoirCapacity = finLevData.reservoirCapacity; + + auto& HydroinitializeReservoirLevelDate = area_2->hydro.initializeReservoirLevelDate; + auto& HydroreservoirCapacity = area_2->hydro.reservoirCapacity; + + HydroinitializeReservoirLevelDate = 0; + HydroreservoirCapacity = 250.3; + + initializePreCheckData(finLevData, *area_2); + + BOOST_CHECK_EQUAL(initReservoirLvlMonth, HydroinitializeReservoirLevelDate); + BOOST_CHECK_EQUAL(reservoirCapacity, HydroreservoirCapacity); +} + +BOOST_AUTO_TEST_CASE(Testing_ruleCurveForSimEndReal_function_for_area_1) +{ + FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + auto& reservoirLevel = area_1->hydro.reservoirLevel; + + auto& lowLevelLastDay = finLevData.lowLevelLastDay; + auto& highLevelLastDay = finLevData.highLevelLastDay; + + auto& HydroreservoirLevelMinimum = reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + auto& HydroreservoirLevelMaximum = reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + + HydroreservoirLevelMinimum = 5.7; + HydroreservoirLevelMaximum = 13.5; + + ruleCurveForSimEndReal(finLevData, *area_1); + + BOOST_CHECK_EQUAL(HydroreservoirLevelMinimum, lowLevelLastDay); + BOOST_CHECK_EQUAL(HydroreservoirLevelMaximum, highLevelLastDay); +} + +BOOST_AUTO_TEST_CASE( + Testing_FinalReservoirLevel_function_preChecksPasses_local_variable_equals_true) +{ + // Defining necessary references for areas run time data + FinalReservoirLevelRuntimeData& finLevDataArea1 = area_1->hydro.finalReservoirLevelRuntimeData; + FinalReservoirLevelRuntimeData& finLevDataArea2 = area_2->hydro.finalReservoirLevelRuntimeData; + + Parameters& parameters = study->parameters; + AreaList& areas = study->areas; + + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + + FinalReservoirLevel(scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, areas); + + BOOST_CHECK(finLevDataArea1.includeFinalReservoirLevel.at(0)); + BOOST_CHECK(finLevDataArea1.includeFinalReservoirLevel.at(1)); + BOOST_CHECK(finLevDataArea2.includeFinalReservoirLevel.at(0)); + BOOST_CHECK(finLevDataArea2.includeFinalReservoirLevel.at(1)); + + BOOST_CHECK_EQUAL(finLevDataArea1.endLevel.at(0), scenarioFinalHydroLevels[0][0]); + BOOST_CHECK_EQUAL(finLevDataArea1.endLevel.at(1), scenarioFinalHydroLevels[0][1]); + BOOST_CHECK_EQUAL(finLevDataArea2.endLevel.at(0), scenarioFinalHydroLevels[1][0]); + BOOST_CHECK_EQUAL(finLevDataArea2.endLevel.at(1), scenarioFinalHydroLevels[1][1]); + + BOOST_CHECK_EQUAL(finLevDataArea1.deltaLevel.at(0), + (scenarioInitialHydroLevels[0][0] - scenarioFinalHydroLevels[0][0])); + BOOST_CHECK_EQUAL(finLevDataArea1.deltaLevel.at(1), + (scenarioInitialHydroLevels[0][1] - scenarioFinalHydroLevels[0][1])); + + BOOST_CHECK_EQUAL(finLevDataArea2.deltaLevel.at(0), + (scenarioInitialHydroLevels[1][0] - scenarioFinalHydroLevels[1][0])); + BOOST_CHECK_EQUAL(finLevDataArea2.deltaLevel.at(1), + (scenarioInitialHydroLevels[1][1] - scenarioFinalHydroLevels[1][1])); +} + +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file From 8067c9fd95ab190e2960ec2eb83163499fddb256 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Mon, 3 Jul 2023 13:41:29 +0200 Subject: [PATCH 415/490] Testing sc buildr file read --- .../test-sc-builder-file-read-line.cpp | 50 ++++++++++++++++++- 1 file changed, 49 insertions(+), 1 deletion(-) 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 d8df864da1..fb6ec392d9 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 @@ -309,7 +309,7 @@ BOOST_AUTO_TEST_CASE(on_rn_cluster32_of_area3_and_on_year_2__solar_TS_number_4_i // ======================== -// Tests on Hydro levels +// Tests on Hydro initial levels // ======================== BOOST_AUTO_TEST_CASE(on_area1_and_on_year_17__hydro_level_0_123_is_chosen__reading_OK) { @@ -392,6 +392,54 @@ BOOST_AUTO_TEST_CASE(on_link_area2_area3_and_on_year_19__ntc_TS_number_6_is_chos BOOST_CHECK_EQUAL(link_23->timeseriesNumbers[0][yearNumber.to()], tsNumber.to() - 1); } +// ======================== +// Tests on Hydro final levels +// ======================== +BOOST_AUTO_TEST_CASE(on_area1_and_on_year_8__hydro_level_0_342_is_chosen__reading_OK) +{ + 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.hydroFinalLevels.get_value(yearNumber.to(), area_1->index), + level.to()); + + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioFinalHydroLevels[area_1->index][yearNumber.to()], + level.to()); +} + +BOOST_AUTO_TEST_CASE(on_area2_and_on_year_1__hydro_level_2_4_is_chosen_level_lowered_to_1__reading_OK) +{ + 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.hydroFinalLevels.get_value(yearNumber.to(), area_2->index), + 1.); + + BOOST_CHECK(my_rule.apply()); + BOOST_CHECK_EQUAL(study->scenarioFinalHydroLevels[area_2->index][yearNumber.to()], + 1.); +} + +BOOST_AUTO_TEST_CASE(on_area3_and_on_year_3__hydro_level_neg_5_2_is_chosen__level_raised_to_0__reading_OK) +{ + 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 Binding Constraints // ======================== From 1d4832ca14748369070747e3326966e4a31d23a0 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Mon, 3 Jul 2023 13:46:42 +0200 Subject: [PATCH 416/490] Testing sc builder file save --- .../test-sc-builder-file-save.cpp | 24 ++++++++++++++++++- 1 file changed, 23 insertions(+), 1 deletion(-) 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 04a8119b51..cf54da0e13 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 @@ -390,7 +390,7 @@ BOOST_AUTO_TEST_CASE( } // ======================== -// Tests on Hydro levels +// Tests on Hydro initial levels // ======================== BOOST_AUTO_TEST_CASE( HYDRO_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical) @@ -411,6 +411,28 @@ BOOST_AUTO_TEST_CASE( BOOST_CHECK(files_identical(path_to_generated_file, referenceFile.path())); } +// ======================== +// Tests on Hydro final levels +// ======================== +BOOST_AUTO_TEST_CASE( + HYDRO_FINAL_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical) +{ + my_rule->hydroFinalLevels.set(area_1->index, 4, 8); + my_rule->hydroFinalLevels.set(area_2->index, 11, 3); + my_rule->hydroFinalLevels.set(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 // ====================== From 130fcba68a8b5ffe6e02d8ceb131adb7979da21e Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Mon, 3 Jul 2023 16:04:54 +0200 Subject: [PATCH 417/490] fix bug + add unit tests for container.h --- ...-hydro-final-reservoir-level-functions.cpp | 79 ++++++++++++++++++- 1 file changed, 77 insertions(+), 2 deletions(-) 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 index dcba226ce5..82db8602b4 100644 --- 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 @@ -125,8 +125,8 @@ struct Fixture Matrix& timeseriesNumbersArea1 = area_1->hydro.series->timeseriesNumbers; Matrix& timeseriesNumbersArea2 = area_2->hydro.series->timeseriesNumbers; - timeseriesNumbersArea1.resize(nbYears, 1); - timeseriesNumbersArea2.resize(nbYears, 1); + timeseriesNumbersArea1.resize(nbYears, 2); + timeseriesNumbersArea2.resize(nbYears, 2); timeseriesNumbersArea1[0][0] = 0; timeseriesNumbersArea1[0][1] = 1; @@ -228,6 +228,81 @@ BOOST_AUTO_TEST_CASE(Testing_ruleCurveForSimEndReal_function_for_area_1) BOOST_CHECK_EQUAL(HydroreservoirLevelMaximum, highLevelLastDay); } +BOOST_AUTO_TEST_CASE(calculateTotalInflows_function_for_area_1) +{ + FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + + auto& inflowsmatrix = area_1->hydro.series->storage; + auto& srcinflows = inflowsmatrix[0]; + + double total_inflow_expected = DAYS_PER_YEAR * 200; + double total_inflow_calculated = finLevData.calculateTotalInflows(srcinflows); + + BOOST_CHECK_EQUAL(total_inflow_expected, total_inflow_calculated); +} + +BOOST_AUTO_TEST_CASE(preCheckStartAndEndSim_function_for_area_1) +{ + FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + + const AreaName& areaName = "TestName"; + + finLevData.simEndDay = DAYS_PER_YEAR; + finLevData.initReservoirLvlMonth = 0; + + bool error_calculated = finLevData.preCheckStartAndEndSim(areaName); + BOOST_CHECK_EQUAL(true, error_calculated); + + finLevData.simEndDay = DAYS_PER_YEAR - 1; + + error_calculated = finLevData.preCheckStartAndEndSim(areaName); + BOOST_CHECK_EQUAL(false, error_calculated); + + finLevData.simEndDay = DAYS_PER_YEAR; + finLevData.initReservoirLvlMonth = 3; + + error_calculated = finLevData.preCheckStartAndEndSim(areaName); + BOOST_CHECK_EQUAL(false, error_calculated); +} + +BOOST_AUTO_TEST_CASE(preCheckYearlyInflow_function_for_area_1) +{ + FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + + const AreaName& areaName = "TestName"; + double totalYearInflows = 100; + + finLevData.deltaReservoirLevel = -0.1; + finLevData.reservoirCapacity = 1500; + + bool error_calculated = finLevData.preCheckYearlyInflow(totalYearInflows, areaName); + BOOST_CHECK_EQUAL(false, error_calculated); + + finLevData.reservoirCapacity = 0.5; + + error_calculated = finLevData.preCheckYearlyInflow(totalYearInflows, areaName); + BOOST_CHECK_EQUAL(true, error_calculated); +} + +BOOST_AUTO_TEST_CASE(preCheckRuleCurves_function_for_area_1) +{ + FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + + const AreaName& areaName = "TestName"; + + finLevData.finalReservoirLevel = 88; + finLevData.lowLevelLastDay = 50; + finLevData.highLevelLastDay = 99; + + bool error_calculated = finLevData.preCheckRuleCurves(areaName); + BOOST_CHECK_EQUAL(true, error_calculated); + + finLevData.highLevelLastDay = 66; + + error_calculated = finLevData.preCheckRuleCurves(areaName); + BOOST_CHECK_EQUAL(false, error_calculated); +} + BOOST_AUTO_TEST_CASE( Testing_FinalReservoirLevel_function_preChecksPasses_local_variable_equals_true) { From 0969175c59f09e42563c95b2e68354715271cab3 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Mon, 3 Jul 2023 16:42:47 +0200 Subject: [PATCH 418/490] unit test fix --- .../simulation/test-hydro-final-reservoir-level-functions.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) 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 index 82db8602b4..094af4af4b 100644 --- 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 @@ -278,7 +278,7 @@ BOOST_AUTO_TEST_CASE(preCheckYearlyInflow_function_for_area_1) bool error_calculated = finLevData.preCheckYearlyInflow(totalYearInflows, areaName); BOOST_CHECK_EQUAL(false, error_calculated); - finLevData.reservoirCapacity = 0.5; + finLevData.deltaReservoirLevel = -0.05; error_calculated = finLevData.preCheckYearlyInflow(totalYearInflows, areaName); BOOST_CHECK_EQUAL(true, error_calculated); From 52b389ccee84edcb96869276fb8e467046d470b1 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Tue, 4 Jul 2023 09:32:40 +0200 Subject: [PATCH 419/490] Bugfix --- .../test-hydro-final-reservoir-level-functions.cpp | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) 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 index 094af4af4b..cb521a17fb 100644 --- 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 @@ -73,7 +73,7 @@ struct Fixture auto& reservoirCapacityArea2 = area_2->hydro.reservoirCapacity; reservoirCapacityArea1 = 340.; - reservoirCapacityArea2 = 300; + reservoirCapacityArea2 = 300.; // Initialize reservoir max and min levels, but just for the last day in year auto& reservoirLevelArea1 = area_1->hydro.reservoirLevel; @@ -125,8 +125,8 @@ struct Fixture Matrix& timeseriesNumbersArea1 = area_1->hydro.series->timeseriesNumbers; Matrix& timeseriesNumbersArea2 = area_2->hydro.series->timeseriesNumbers; - timeseriesNumbersArea1.resize(nbYears, 2); - timeseriesNumbersArea2.resize(nbYears, 2); + timeseriesNumbersArea1.resize(1, nbYears); + timeseriesNumbersArea2.resize(1, nbYears); timeseriesNumbersArea1[0][0] = 0; timeseriesNumbersArea1[0][1] = 1; @@ -168,7 +168,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeGeneralData_function_for_area_1) BOOST_CHECK_EQUAL(RuntimeData.yearIndex, year); } -BOOST_AUTO_TEST_CASE(Testing_initializePerAreaData_function_for_area_2s) +BOOST_AUTO_TEST_CASE(Testing_initializePerAreaData_function_for_area_2) { FinalReservoirLevelRuntimeData& finLevData = area_2->hydro.finalReservoirLevelRuntimeData; auto& initialReservoirLevel = finLevData.initialReservoirLevel; From bbc8fa28d745027d69a312c438948cf2df550a14 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Tue, 4 Jul 2023 12:18:51 +0200 Subject: [PATCH 420/490] Memory access violatin fix --- .../test-hydro-final-reservoir-level-functions.cpp | 5 +++++ 1 file changed, 5 insertions(+) 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 index cb521a17fb..4ab01f25ba 100644 --- 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 @@ -175,6 +175,11 @@ BOOST_AUTO_TEST_CASE(Testing_initializePerAreaData_function_for_area_2) auto& finalReservoirLevel = finLevData.finalReservoirLevel; auto& deltaReservoirLevel = finLevData.deltaReservoirLevel; + initialReservoirLevel = 0.; + finalReservoirLevel = 0.; + deltaReservoirLevel = 0.; + finLevData.yearIndex = 0; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; From 9e7b1158c68971d52dac7b110ee13d2b2848eae2 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Thu, 27 Jul 2023 14:07:54 +0200 Subject: [PATCH 421/490] FinalReservoirLevels class with area ptr --- src/libs/antares/study/area/area.h | 2 ++ src/libs/antares/study/area/list.cpp | 12 ++++++++++++ src/libs/antares/study/parts/hydro/container.h | 3 +++ .../hydro-final-reservoir-level-functions.cpp | 7 +++++++ 4 files changed, 24 insertions(+) diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 1f7287c7f1..954ed8ae2a 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -865,6 +865,8 @@ void AreaListEnsureDataRenewableTimeSeries(AreaList* l); */ void AreaListEnsureDataThermalPrepro(AreaList* l); +void AreaListEnsureFinalReservoirLevelRuntimeDataAreaPtr(AreaList* l); + } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 2e245060a7..bd0397a484 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1040,6 +1040,7 @@ void AreaList::ensureDataIsInitialized(Parameters& params, bool loadOnlyNeeded) AreaListEnsureDataHydroTimeSeries(this); AreaListEnsureDataThermalTimeSeries(this); AreaListEnsureDataRenewableTimeSeries(this); + AreaListEnsureFinalReservoirLevelRuntimeDataAreaPtr(this); if (loadOnlyNeeded) { @@ -1321,6 +1322,17 @@ void AreaListEnsureDataHydroTimeSeries(AreaList* l) }); } +void AreaListEnsureFinalReservoirLevelRuntimeDataAreaPtr(AreaList* l) +{ + /* Asserts */ + assert(l); + + l->each([&](Data::Area& area) { + if (!area.hydro.finalReservoirLevelRuntimeData.areaPtr) + area.hydro.finalReservoirLevelRuntimeData.areaPtr = &area; + }); +} + void AreaListEnsureDataHydroPrepro(AreaList* l) { /* Asserts */ diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 17d7c9174f..3e8ff0c657 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -65,6 +65,9 @@ class FinalReservoirLevelRuntimeData double lowLevelLastDay; double highLevelLastDay; int initReservoirLvlMonth; + Area* areaPtr; + + FinalReservoirLevelRuntimeData() : areaPtr(nullptr) {} // methods: diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 5c36b2aad7..9af7f970dc 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -69,6 +69,13 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, const Data::Parameters& parameters, const Data::AreaList& areas) { + //Code for testing + uint in = 10; + for (uint i = 0; i < areas.size(); i++) + { + in = areas[i]->hydro.finalReservoirLevelRuntimeData.areaPtr->index; + } + bool preChecksPasses = true; for (uint yearIndex = 0; yearIndex != scenarioFinalHydroLevels.height; ++yearIndex) { From a9a56c3b04440fe084a0f76edd8dbc939c5cf657 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Thu, 27 Jul 2023 19:40:31 +0200 Subject: [PATCH 422/490] New implementation --- src/libs/antares/CMakeLists.txt | 4 +- src/libs/antares/study/area/area.h | 2 +- src/libs/antares/study/area/list.cpp | 8 +- .../antares/study/parts/hydro/container.cpp | 3 +- .../antares/study/parts/hydro/container.h | 100 +------------- .../parts/hydro/finallevelinflowsmodifyer.cpp | 127 ++++++++++++++++++ .../parts/hydro/finallevelinflowsmodifyer.h | 95 +++++++++++++ src/libs/antares/study/parts/parts.h | 1 + src/solver/hydro/management/management.cpp | 6 +- src/solver/simulation/apply-scenario.cpp | 20 ++- .../hydro-final-reservoir-level-functions.cpp | 117 +++++----------- .../hydro-final-reservoir-level-functions.h | 15 +-- .../src/solver/simulation/CMakeLists.txt | 26 ---- ...-hydro-final-reservoir-level-functions.cpp | 3 +- 14 files changed, 290 insertions(+), 237 deletions(-) create mode 100644 src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp create mode 100644 src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h diff --git a/src/libs/antares/CMakeLists.txt b/src/libs/antares/CMakeLists.txt index 5261d18cc1..5232506023 100644 --- a/src/libs/antares/CMakeLists.txt +++ b/src/libs/antares/CMakeLists.txt @@ -272,7 +272,9 @@ set(SRC_STUDY_PART_HYDRO study/parts/hydro/allocation.h study/parts/hydro/allocation.hxx study/parts/hydro/allocation.cpp - ) + study/parts/hydro/finallevelinflowsmodifyer.h + study/parts/hydro/finallevelinflowsmodifyer.cpp +) source_group("study\\part\\hydro" FILES ${SRC_STUDY_PART_HYDRO}) set(SRC_STUDY_UI diff --git a/src/libs/antares/study/area/area.h b/src/libs/antares/study/area/area.h index 954ed8ae2a..0cec30fd41 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -865,7 +865,7 @@ void AreaListEnsureDataRenewableTimeSeries(AreaList* l); */ void AreaListEnsureDataThermalPrepro(AreaList* l); -void AreaListEnsureFinalReservoirLevelRuntimeDataAreaPtr(AreaList* l); +void AreaListEnsureFinalLevelInflowsModifyerAreaPtr(AreaList* l); } // namespace Data } // namespace Antares diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index bd0397a484..4ebb32ecd5 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1040,7 +1040,7 @@ void AreaList::ensureDataIsInitialized(Parameters& params, bool loadOnlyNeeded) AreaListEnsureDataHydroTimeSeries(this); AreaListEnsureDataThermalTimeSeries(this); AreaListEnsureDataRenewableTimeSeries(this); - AreaListEnsureFinalReservoirLevelRuntimeDataAreaPtr(this); + AreaListEnsureFinalLevelInflowsModifyerAreaPtr(this); if (loadOnlyNeeded) { @@ -1322,14 +1322,14 @@ void AreaListEnsureDataHydroTimeSeries(AreaList* l) }); } -void AreaListEnsureFinalReservoirLevelRuntimeDataAreaPtr(AreaList* l) +void AreaListEnsureFinalLevelInflowsModifyerAreaPtr(AreaList* l) { /* Asserts */ assert(l); l->each([&](Data::Area& area) { - if (!area.hydro.finalReservoirLevelRuntimeData.areaPtr) - area.hydro.finalReservoirLevelRuntimeData.areaPtr = &area; + if (!area.hydro.finalLevelInflowsModifyer->areaPtr) + area.hydro.finalLevelInflowsModifyer->areaPtr = &area; }); } diff --git a/src/libs/antares/study/parts/hydro/container.cpp b/src/libs/antares/study/parts/hydro/container.cpp index 88fe12ee36..bb4cf63702 100644 --- a/src/libs/antares/study/parts/hydro/container.cpp +++ b/src/libs/antares/study/parts/hydro/container.cpp @@ -57,7 +57,8 @@ PartHydro::PartHydro() : pumpingEfficiency(1.), hydroModulable(false), prepro(nullptr), - series(nullptr) + series(nullptr), + finalLevelInflowsModifyer(std::make_shared()) { } diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 3e8ff0c657..c43f3a2b10 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -37,103 +37,8 @@ namespace Antares::Data /*! ** \brief Final Reservoir Level data for a single area */ -class FinalReservoirLevelRuntimeData -{ -public: - // Final reservoir level runtime data - - // vectors containing data necessary for final reservoir level calculation - // for one area and all MC years - // vector indexes correspond to the MC years - std::vector includeFinalReservoirLevel; - std::vector endLevel; - std::vector deltaLevel; - - // Simulation Data - uint simEndDay; - - // simulation year - // overwritten after each MC year - uint yearIndex; - - // data per area - // data overwritten after each MC year - double initialReservoirLevel; - double finalReservoirLevel; - double deltaReservoirLevel; - double reservoirCapacity; - double lowLevelLastDay; - double highLevelLastDay; - int initReservoirLvlMonth; - Area* areaPtr; - - FinalReservoirLevelRuntimeData() : areaPtr(nullptr) {} - - // methods: - - void fillEmpty() - { - includeFinalReservoirLevel.push_back(false); - endLevel.push_back(0.); - deltaLevel.push_back(0.); - } - - void assignEndLevelAndDelta() - { - includeFinalReservoirLevel.at(yearIndex) = true; - endLevel.at(yearIndex) = finalReservoirLevel; - deltaLevel.at(yearIndex) = deltaReservoirLevel; - } - - double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows) const - { - double totalYearInflows = 0.0; - for (uint day = 0; day < DAYS_PER_YEAR; ++day) - totalYearInflows += srcinflows[day]; - return totalYearInflows; - } - bool preCheckStartAndEndSim(const AreaName& name) const - { - if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) - return true; - else - { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name - << ". Simulation must end on day 365 and reservoir level must be " - "initiated in January"; - return false; - } - } - - bool preCheckYearlyInflow(double totalYearInflows, const AreaName& name) const - { - if ((-deltaReservoirLevel) * reservoirCapacity - > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh - // (energy) - { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name - << ". Incompatible total inflows: " << totalYearInflows - << " with initial: " << initialReservoirLevel - << " and final: " << finalReservoirLevel << " reservoir levels."; - return false; - } - return true; - } - - bool preCheckRuleCurves(const AreaName& name) const - { - if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) - { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << name - << ". Specifed final reservoir level: " << finalReservoirLevel - << " is incompatible with reservoir level rule curve [" << lowLevelLastDay - << " , " << highLevelLastDay << "]"; - return false; - } - return true; - } -}; +class FinalLevelInflowsModifyer; /*! ** \brief Hydro for a single area @@ -274,7 +179,8 @@ class PartHydro DataSeriesHydro* series; //! Data for final reservoir level - FinalReservoirLevelRuntimeData finalReservoirLevelRuntimeData; + + std::shared_ptr finalLevelInflowsModifyer; }; // class PartHydro diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp new file mode 100644 index 0000000000..3b1ec512c6 --- /dev/null +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -0,0 +1,127 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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 "finallevelinflowsmodifyer.h" + +namespace Antares +{ +namespace Data +{ + +void FinalLevelInflowsModifyer::fillEmpty() +{ + includeFinalReservoirLevel.push_back(false); + endLevel.push_back(0.); + deltaLevel.push_back(0.); +} + +void FinalLevelInflowsModifyer::assignEndLevelAndDelta() +{ + includeFinalReservoirLevel.at(yearIndex) = true; + endLevel.at(yearIndex) = finalReservoirLevel; + deltaLevel.at(yearIndex) = deltaReservoirLevel; +} + +double FinalLevelInflowsModifyer::calculateTotalInflows( + Antares::Memory::Stored::Type& srcinflows) const +{ + double totalYearInflows = 0.0; + for (uint day = 0; day < DAYS_PER_YEAR; ++day) + totalYearInflows += srcinflows[day]; + return totalYearInflows; +} + +bool FinalLevelInflowsModifyer::preCheckStartAndEndSim() const +{ + if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) + return true; + else + { + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaPtr->name + << ". Simulation must end on day 365 and reservoir level must be " + "initiated in January"; + return false; + } +} + +bool FinalLevelInflowsModifyer::preCheckYearlyInflow(double totalYearInflows) const +{ + if ((-deltaReservoirLevel) * reservoirCapacity + > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh + // (energy) + { + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaPtr->name + << ". Incompatible total inflows: " << totalYearInflows + << " with initial: " << initialReservoirLevel + << " and final: " << finalReservoirLevel << " reservoir levels."; + return false; + } + return true; +} + +bool FinalLevelInflowsModifyer::preCheckRuleCurves() const +{ + if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) + { + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaPtr->name + << ". Specifed final reservoir level: " << finalReservoirLevel + << " is incompatible with reservoir level rule curve [" << lowLevelLastDay + << " , " << highLevelLastDay << "]"; + return false; + } + return true; +} + +void FinalLevelInflowsModifyer::initializeGeneralData(const Data::Parameters& parameters, uint year) +{ + simEndDay = parameters.simulationDays.end; + yearIndex = year; +} + +void FinalLevelInflowsModifyer::initializePerAreaData( + const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels) +{ + initialReservoirLevel = scenarioInitialHydroLevels[areaPtr->index][yearIndex]; + finalReservoirLevel = scenarioFinalHydroLevels[areaPtr->index][yearIndex]; + deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; +} + +void FinalLevelInflowsModifyer::initializePreCheckData() +{ + initReservoirLvlMonth = areaPtr->hydro.initializeReservoirLevelDate; // month [0-11] + reservoirCapacity = areaPtr->hydro.reservoirCapacity; +} + +void FinalLevelInflowsModifyer::ruleCurveForSimEndReal() +{ + lowLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + highLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; +} + +} // namespace Data +} // namespace Antares \ No newline at end of file diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h new file mode 100644 index 0000000000..27365843d0 --- /dev/null +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -0,0 +1,95 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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_FINAL_LEVEL_INFLOWS_MODIFYER_H__ +#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__ + +#include "../../area/area.h" + +namespace Antares::Data +{ + +/*! + ** \brief Final Reservoir Level data for a single area + */ +class FinalLevelInflowsModifyer +{ +public: + // Final reservoir level runtime data + + // vectors containing data necessary for final reservoir level calculation + // for one area and all MC years + // vector indexes correspond to the MC years + std::vector includeFinalReservoirLevel; + std::vector endLevel; + std::vector deltaLevel; + + // Simulation Data + uint simEndDay; + + // simulation year + // overwritten after each MC year + uint yearIndex; + + // data per area + // data overwritten after each MC year + double initialReservoirLevel; + double finalReservoirLevel; + double deltaReservoirLevel; + double reservoirCapacity; + double lowLevelLastDay; + double highLevelLastDay; + int initReservoirLvlMonth; + Area* areaPtr; + + FinalLevelInflowsModifyer() : areaPtr(nullptr) + { + } + + // methods: + + void fillEmpty(); + + void assignEndLevelAndDelta(); + + double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows) const; + + bool preCheckStartAndEndSim() const; + + bool preCheckYearlyInflow(double totalYearInflows) const; + + bool preCheckRuleCurves() const; + + void initializeGeneralData(const Data::Parameters& parameters, uint year); + + void initializePerAreaData(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels); + void initializePreCheckData(); + void ruleCurveForSimEndReal(); +}; +} // namespace Antares::Data + +#endif /*__ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__*/ \ No newline at end of file diff --git a/src/libs/antares/study/parts/parts.h b/src/libs/antares/study/parts/parts.h index d59933f179..d9bb088ad3 100644 --- a/src/libs/antares/study/parts/parts.h +++ b/src/libs/antares/study/parts/parts.h @@ -39,6 +39,7 @@ // Hydro #include "hydro/prepro.h" #include "hydro/series.h" +#include "hydro/finallevelinflowsmodifyer.h" #include "hydro/container.h" // Wind diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 0c472fd4e0..b8130134bb 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -357,13 +357,13 @@ void HydroManagement::prepareFinalReservoirLevelData(uint numSpace, uint year) [this, &numSpace, &year](Data::Area& area) { auto& data = pAreas[numSpace][area.index]; - if (area.hydro.finalReservoirLevelRuntimeData.deltaLevel.empty()) + if (area.hydro.finalLevelInflowsModifyer->deltaLevel.empty()) return; - if (!area.hydro.finalReservoirLevelRuntimeData.includeFinalReservoirLevel[year]) + if (!area.hydro.finalLevelInflowsModifyer->includeFinalReservoirLevel[year]) return; - double delta = area.hydro.finalReservoirLevelRuntimeData.deltaLevel[year]; + double delta = area.hydro.finalLevelInflowsModifyer->deltaLevel[year]; // must be done before prepareMonthlyTargetGenerations if (delta > 0) data.inflows[0] += delta; diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 10a89cd54d..559aeb7afe 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -57,11 +57,21 @@ void ApplyCustomScenario(Data::Study& study) study.scenarioRulesDestroy(); logs.info(); - // final reservoir level functions and pre-checks - FinalReservoirLevel(study.scenarioInitialHydroLevels, - study.scenarioFinalHydroLevels, - study.parameters, - study.areas); + auto& areas = study.areas; + + for (uint yearIndex = 0; yearIndex != study.scenarioFinalHydroLevels.height; ++yearIndex) + { + areas.each( + [&study, &yearIndex](Data::Area& area) + { + auto& finalinflows = area.hydro.finalLevelInflowsModifyer; + FinalReservoirLevel(study.scenarioInitialHydroLevels, + study.scenarioFinalHydroLevels, + study.parameters, + finalinflows, + yearIndex); + }); + } } } // namespace Antares::Solver diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 9af7f970dc..ce2174ec3b 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -30,102 +30,49 @@ namespace Antares::Solver { -void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Data::Parameters& parameters, - uint year) -{ - finLevData.simEndDay = parameters.simulationDays.end; - finLevData.yearIndex = year; -} - -void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const Data::Area& area) -{ - finLevData.initialReservoirLevel = scenarioInitialHydroLevels[area.index][finLevData.yearIndex]; - finLevData.finalReservoirLevel = scenarioFinalHydroLevels[area.index][finLevData.yearIndex]; - finLevData.deltaReservoirLevel - = finLevData.initialReservoirLevel - finLevData.finalReservoirLevel; -} - -void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Data::Area& area) -{ - finLevData.initReservoirLvlMonth = area.hydro.initializeReservoirLevelDate; // month [0-11] - finLevData.reservoirCapacity = area.hydro.reservoirCapacity; -} - -void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, Data::Area& area) -{ - finLevData.lowLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - finLevData.highLevelLastDay - = area.hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; -} void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, const Data::Parameters& parameters, - const Data::AreaList& areas) + std::shared_ptr finalinflows, + uint yearIndex) { - //Code for testing - uint in = 10; - for (uint i = 0; i < areas.size(); i++) - { - in = areas[i]->hydro.finalReservoirLevelRuntimeData.areaPtr->index; - } - bool preChecksPasses = true; - for (uint yearIndex = 0; yearIndex != scenarioFinalHydroLevels.height; ++yearIndex) - { - areas.each( - [&scenarioInitialHydroLevels, - &scenarioFinalHydroLevels, - ¶meters, - &preChecksPasses, - &yearIndex](Data::Area& area) - { - auto& finLevData = area.hydro.finalReservoirLevelRuntimeData; - finLevData.fillEmpty(); - initializeGeneralData(finLevData, parameters, yearIndex); - initializePerAreaData( - finLevData, scenarioInitialHydroLevels, scenarioFinalHydroLevels, area); + finalinflows->fillEmpty(); + finalinflows->initializeGeneralData(parameters, yearIndex); + finalinflows->initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); - if (area.hydro.reservoirManagement && !area.hydro.useWaterValue - && !isnan(finLevData.finalReservoirLevel) - && !isnan(finLevData.initialReservoirLevel)) - { - initializePreCheckData(finLevData, area); - finLevData.assignEndLevelAndDelta(); + if (finalinflows->areaPtr->hydro.reservoirManagement + && !finalinflows->areaPtr->hydro.useWaterValue && !isnan(finalinflows->finalReservoirLevel) + && !isnan(finalinflows->initialReservoirLevel)) + { + finalinflows->initializePreCheckData(); + finalinflows->assignEndLevelAndDelta(); - // pre-check 0 -> simulation must end on day 365 and reservoir level must be - // initiated in January - if (!finLevData.preCheckStartAndEndSim(area.name)) - preChecksPasses = false; + // pre-check 0 -> simulation must end on day 365 and reservoir level must be + // initiated in January + if (!finalinflows->preCheckStartAndEndSim()) + preChecksPasses = false; - // rule curve values for simEndDayReal - ruleCurveForSimEndReal(finLevData, area); + // rule curve values for simEndDayReal + finalinflows->ruleCurveForSimEndReal(); - // calculate (partial)yearly inflows - const Data::DataSeriesHydro& data = *area.hydro.series; - uint tsHydroIndex = data.timeseriesNumbers[0][finLevData.yearIndex]; - auto& inflowsmatrix = area.hydro.series->storage; - auto& srcinflows - = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; + // calculate (partial)yearly inflows + const Data::DataSeriesHydro& data = *finalinflows->areaPtr->hydro.series; + uint tsHydroIndex = data.timeseriesNumbers[0][finalinflows->yearIndex]; + auto& inflowsmatrix = finalinflows->areaPtr->hydro.series->storage; + auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; - // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ - // yearly_inflows - if (double totalInflows = finLevData.calculateTotalInflows(srcinflows); - !finLevData.preCheckYearlyInflow(totalInflows, area.name)) - preChecksPasses = false; + // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ + // yearly_inflows + if (double totalInflows = finalinflows->calculateTotalInflows(srcinflows); + !finalinflows->preCheckYearlyInflow(totalInflows)) + preChecksPasses = false; - // pre-check 2 -> final reservoir level set by the user is within the - // rule curves for the final day - if (!finLevData.preCheckRuleCurves(area.name)) - preChecksPasses = false; - } - }); + // pre-check 2 -> final reservoir level set by the user is within the + // rule curves for the final day + if (!finalinflows->preCheckRuleCurves()) + preChecksPasses = false; } if (!preChecksPasses) { @@ -134,4 +81,4 @@ void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, } } -} // namespace Anatres::Solver \ No newline at end of file +} // namespace Antares::Solver \ No newline at end of file diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index da0b618ff4..bcb89d6886 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,23 +31,12 @@ namespace Antares::Solver { -void initializeGeneralData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Data::Parameters& parameters, - uint year); -void initializePerAreaData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const Data::Area& area); - -void initializePreCheckData(Data::FinalReservoirLevelRuntimeData& finLevData, - const Data::Area& area); - -void ruleCurveForSimEndReal(Data::FinalReservoirLevelRuntimeData& finLevData, Data::Area& area); void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, const Data::Parameters& parameters, - const Data::AreaList& areas); + std::shared_ptr finalinflows, + uint yearIndex); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index 03e9ae312c..330d55ebe1 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -88,29 +88,3 @@ set_property(TEST time_series PROPERTY LABELS unit) # =================================== # Tests on hydro final reservoir level functions # =================================== -set(SRC_HYDRO_FINAL_LEVEL - ${src_solver_simulation}/hydro-final-reservoir-level-functions.h - ${src_solver_simulation}/hydro-final-reservoir-level-functions.cpp -) - -add_executable(test-hydro_final - test-hydro-final-reservoir-level-functions.cpp - ${SRC_HYDRO_FINAL_LEVEL}) - -target_include_directories(test-hydro_final - PRIVATE - "${src_solver_simulation}" - "${src_libs_antares_study}" -) -target_link_libraries(test-hydro_final - PRIVATE - Boost::unit_test_framework - libantares-core - libantares-solver-simulation -) - -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 index 4ab01f25ba..87957daf8c 100644 --- 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 @@ -1,6 +1,7 @@ // // Created by Nikola Ilic on 23/06/23. // +/* #define BOOST_TEST_MODULE hydro - final - level #define WIN32_LEAN_AND_MEAN #include @@ -344,4 +345,4 @@ BOOST_AUTO_TEST_CASE( (scenarioInitialHydroLevels[1][1] - scenarioFinalHydroLevels[1][1])); } -BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file +BOOST_AUTO_TEST_SUITE_END()*/ \ No newline at end of file From 3e988d8973f0a08822407100a2a7e0e959ad8ea8 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Thu, 27 Jul 2023 19:44:18 +0200 Subject: [PATCH 423/490] Function name modification --- src/solver/hydro/management/management.cpp | 4 ++-- src/solver/hydro/management/management.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index b8130134bb..f70ab19a75 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -351,7 +351,7 @@ bool HydroManagement::checkMinGeneration(uint numSpace) return ret; } -void HydroManagement::prepareFinalReservoirLevelData(uint numSpace, uint year) +void HydroManagement::changeInflowsDueToFinalLevels(uint numSpace, uint year) { study.areas.each( [this, &numSpace, &year](Data::Area& area) @@ -528,7 +528,7 @@ void HydroManagement::operator()(double* randomReservoirLevel, AntaresSolverEmergencyShutdown(); } - prepareFinalReservoirLevelData(numSpace, y); + changeInflowsDueToFinalLevels(numSpace, y); if (parameters.adequacy()) prepareNetDemand(numSpace); diff --git a/src/solver/hydro/management/management.h b/src/solver/hydro/management/management.h index 9b1404c92f..5bd8a7b3df 100644 --- a/src/solver/hydro/management/management.h +++ b/src/solver/hydro/management/management.h @@ -76,7 +76,7 @@ class HydroManagement final //! Prepare inflows scaling for each area void prepareInflowsScaling(uint numSpace); //! prepare data for Final reservoir level - void prepareFinalReservoirLevelData(uint numSpace, uint yearIndex); + void changeInflowsDueToFinalLevels(uint numSpace, uint yearIndex); //! Prepare minimum generation scaling for each area void minGenerationScaling(uint numSpace); //! check Monthly minimum generation is lower than available inflows From 15b840d30b3be55215042cb5cf6c1f9a22e2073c Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 28 Jul 2023 10:01:23 +0200 Subject: [PATCH 424/490] saveToINIFilePrefix -> iniFilePrefix renaming --- src/libs/antares/study/scenario-builder/hydroLevelsData.cpp | 4 ++-- src/libs/antares/study/scenario-builder/hydroLevelsData.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index bc73517a07..5aabfcec9d 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -36,8 +36,8 @@ namespace Data { namespace ScenarioBuilder { -hydroLevelsData::hydroLevelsData(std::string& saveToINIFilePrefix) : -addToPrefix(saveToINIFilePrefix) +hydroLevelsData::hydroLevelsData(std::string& iniFilePrefix) : +addToPrefix(iniFilePrefix) { } diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h index 6c14c9509a..f31b0d4643 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.h @@ -47,7 +47,7 @@ class hydroLevelsData final : public dataInterface public: // Constructor - hydroLevelsData(std::string& saveToINIFilePrefix); + hydroLevelsData(std::string& iniFilePrefix); //! \name Data manupulation //@{ From e58cde45db4e36808eee0f9e342ed042ab4313d5 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 28 Jul 2023 11:10:33 +0200 Subject: [PATCH 425/490] small refactor --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 54 +++++++++---------- .../parts/hydro/finallevelinflowsmodifyer.h | 1 + 2 files changed, 28 insertions(+), 27 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 3b1ec512c6..9d46d8218c 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -39,6 +39,33 @@ void FinalLevelInflowsModifyer::fillEmpty() deltaLevel.push_back(0.); } +void FinalLevelInflowsModifyer::initializeGeneralData(const Data::Parameters& parameters, uint year) +{ + simEndDay = parameters.simulationDays.end; + yearIndex = year; +} + +void FinalLevelInflowsModifyer::initializePerAreaData( + const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels) +{ + initialReservoirLevel = scenarioInitialHydroLevels[areaPtr->index][yearIndex]; + finalReservoirLevel = scenarioFinalHydroLevels[areaPtr->index][yearIndex]; + deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; +} + +void FinalLevelInflowsModifyer::initializePreCheckData() +{ + initReservoirLvlMonth = areaPtr->hydro.initializeReservoirLevelDate; // month [0-11] + reservoirCapacity = areaPtr->hydro.reservoirCapacity; +} + +void FinalLevelInflowsModifyer::ruleCurveForSimEndReal() +{ + lowLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + highLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; +} + void FinalLevelInflowsModifyer::assignEndLevelAndDelta() { includeFinalReservoirLevel.at(yearIndex) = true; @@ -96,32 +123,5 @@ bool FinalLevelInflowsModifyer::preCheckRuleCurves() const return true; } -void FinalLevelInflowsModifyer::initializeGeneralData(const Data::Parameters& parameters, uint year) -{ - simEndDay = parameters.simulationDays.end; - yearIndex = year; -} - -void FinalLevelInflowsModifyer::initializePerAreaData( - const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels) -{ - initialReservoirLevel = scenarioInitialHydroLevels[areaPtr->index][yearIndex]; - finalReservoirLevel = scenarioFinalHydroLevels[areaPtr->index][yearIndex]; - deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; -} - -void FinalLevelInflowsModifyer::initializePreCheckData() -{ - initReservoirLvlMonth = areaPtr->hydro.initializeReservoirLevelDate; // month [0-11] - reservoirCapacity = areaPtr->hydro.reservoirCapacity; -} - -void FinalLevelInflowsModifyer::ruleCurveForSimEndReal() -{ - lowLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - highLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; -} - } // namespace Data } // namespace Antares \ No newline at end of file diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 27365843d0..bce22e51ba 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -88,6 +88,7 @@ class FinalLevelInflowsModifyer void initializePerAreaData(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels); void initializePreCheckData(); + void ruleCurveForSimEndReal(); }; } // namespace Antares::Data From a90d15443a1e62421c3be8625d8f5e4ce053b1a2 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Fri, 28 Jul 2023 11:44:16 +0200 Subject: [PATCH 426/490] Move Constructor definition into .cpp file --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 2 ++ .../antares/study/parts/hydro/finallevelinflowsmodifyer.h | 5 ++--- 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 9d46d8218c..6885386692 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -32,6 +32,8 @@ namespace Antares namespace Data { +FinalLevelInflowsModifyer::FinalLevelInflowsModifyer() : areaPtr(nullptr) {} + void FinalLevelInflowsModifyer::fillEmpty() { includeFinalReservoirLevel.push_back(false); diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index bce22e51ba..eeea2d03a1 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -65,9 +65,8 @@ class FinalLevelInflowsModifyer int initReservoirLvlMonth; Area* areaPtr; - FinalLevelInflowsModifyer() : areaPtr(nullptr) - { - } + // Constructor + FinalLevelInflowsModifyer(); // methods: From 7f66eb60b64c2e0e21ce117253e80b86d149a197 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Fri, 28 Jul 2023 15:02:11 +0200 Subject: [PATCH 427/490] Refactoring --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 65 ++++++++++++++++++- .../parts/hydro/finallevelinflowsmodifyer.h | 30 ++++++--- src/solver/simulation/apply-scenario.cpp | 15 +---- .../hydro-final-reservoir-level-functions.cpp | 65 +++++-------------- .../hydro-final-reservoir-level-functions.h | 6 +- 5 files changed, 106 insertions(+), 75 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 6885386692..308d5c3701 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -32,7 +32,9 @@ namespace Antares namespace Data { -FinalLevelInflowsModifyer::FinalLevelInflowsModifyer() : areaPtr(nullptr) {} +FinalLevelInflowsModifyer::FinalLevelInflowsModifyer() : areaPtr(nullptr) +{ +} void FinalLevelInflowsModifyer::fillEmpty() { @@ -125,5 +127,66 @@ bool FinalLevelInflowsModifyer::preCheckRuleCurves() const return true; } +void FinalLevelInflowsModifyer::initializeData(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const Data::Parameters& parameters) +{ + fillEmpty(); + initializeGeneralData(parameters, yearIndex); + initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); + initializePreCheckData(); +} + +bool FinalLevelInflowsModifyer::isActive() +{ + if (areaPtr->hydro.reservoirManagement && !areaPtr->hydro.useWaterValue + && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) + { + return true; + } + else + { + return false; + } +} + +void FinalLevelInflowsModifyer::updateInflows() +{ + bool preChecksPasses = true; + + assignEndLevelAndDelta(); + + // pre-check 0 -> simulation must end on day 365 and reservoir level must be + // initiated in January + if (!preCheckStartAndEndSim()) + preChecksPasses = false; + + // rule curve values for simEndDayReal + ruleCurveForSimEndReal(); + + // calculate (partial)yearly inflows + const Data::DataSeriesHydro& data = *areaPtr->hydro.series; + uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex]; + auto& inflowsmatrix = areaPtr->hydro.series->storage; + auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; + + // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ + // yearly_inflows + if (double totalInflows = calculateTotalInflows(srcinflows); + !preCheckYearlyInflow(totalInflows)) + preChecksPasses = false; + + // pre-check 2 -> final reservoir level set by the user is within the + // rule curves for the final day + if (!preCheckRuleCurves()) + preChecksPasses = false; + + if (!preChecksPasses) + { + logs.fatal() << "At least one year has failed final reservoir level pre-checks."; + AntaresSolverEmergencyShutdown(); + } +} + } // namespace Data } // namespace Antares \ No newline at end of file diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index eeea2d03a1..67da9e2bb8 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -28,6 +28,7 @@ #define __ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__ #include "../../area/area.h" +#include namespace Antares::Data { @@ -37,16 +38,9 @@ namespace Antares::Data */ class FinalLevelInflowsModifyer { -public: +private: // Final reservoir level runtime data - // vectors containing data necessary for final reservoir level calculation - // for one area and all MC years - // vector indexes correspond to the MC years - std::vector includeFinalReservoirLevel; - std::vector endLevel; - std::vector deltaLevel; - // Simulation Data uint simEndDay; @@ -63,11 +57,21 @@ class FinalLevelInflowsModifyer double lowLevelLastDay; double highLevelLastDay; int initReservoirLvlMonth; + +public: Area* areaPtr; + // vectors containing data necessary for final reservoir level calculation + // for one area and all MC years + // vector indexes correspond to the MC years + std::vector includeFinalReservoirLevel; + std::vector endLevel; + std::vector deltaLevel; + // Constructor FinalLevelInflowsModifyer(); +private: // methods: void fillEmpty(); @@ -87,8 +91,16 @@ class FinalLevelInflowsModifyer void initializePerAreaData(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels); void initializePreCheckData(); - + void ruleCurveForSimEndReal(); + +public: + void initializeData(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const Data::Parameters& parameters); + bool isActive(); + + void updateInflows(); }; } // namespace Antares::Data diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 559aeb7afe..682d672a1c 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -57,20 +57,11 @@ void ApplyCustomScenario(Data::Study& study) study.scenarioRulesDestroy(); logs.info(); - auto& areas = study.areas; + uint numberMCYears = study.scenarioFinalHydroLevels.height; - for (uint yearIndex = 0; yearIndex != study.scenarioFinalHydroLevels.height; ++yearIndex) + for (uint yearIndex = 0; yearIndex != numberMCYears; ++yearIndex) { - areas.each( - [&study, &yearIndex](Data::Area& area) - { - auto& finalinflows = area.hydro.finalLevelInflowsModifyer; - FinalReservoirLevel(study.scenarioInitialHydroLevels, - study.scenarioFinalHydroLevels, - study.parameters, - finalinflows, - yearIndex); - }); + prepareFinalReservoirLevelData(study, yearIndex); } } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index ce2174ec3b..9deaa32952 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -26,59 +26,28 @@ */ #include "hydro-final-reservoir-level-functions.h" -#include namespace Antares::Solver { -void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const Data::Parameters& parameters, - std::shared_ptr finalinflows, - uint yearIndex) +void prepareFinalReservoirLevelData(Data::Study& study, uint yearIndex) { - bool preChecksPasses = true; - finalinflows->fillEmpty(); - finalinflows->initializeGeneralData(parameters, yearIndex); - finalinflows->initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); - - if (finalinflows->areaPtr->hydro.reservoirManagement - && !finalinflows->areaPtr->hydro.useWaterValue && !isnan(finalinflows->finalReservoirLevel) - && !isnan(finalinflows->initialReservoirLevel)) - { - finalinflows->initializePreCheckData(); - finalinflows->assignEndLevelAndDelta(); - - // pre-check 0 -> simulation must end on day 365 and reservoir level must be - // initiated in January - if (!finalinflows->preCheckStartAndEndSim()) - preChecksPasses = false; - - // rule curve values for simEndDayReal - finalinflows->ruleCurveForSimEndReal(); - - // calculate (partial)yearly inflows - const Data::DataSeriesHydro& data = *finalinflows->areaPtr->hydro.series; - uint tsHydroIndex = data.timeseriesNumbers[0][finalinflows->yearIndex]; - auto& inflowsmatrix = finalinflows->areaPtr->hydro.series->storage; - auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; - - // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ - // yearly_inflows - if (double totalInflows = finalinflows->calculateTotalInflows(srcinflows); - !finalinflows->preCheckYearlyInflow(totalInflows)) - preChecksPasses = false; - - // pre-check 2 -> final reservoir level set by the user is within the - // rule curves for the final day - if (!finalinflows->preCheckRuleCurves()) - preChecksPasses = false; - } - if (!preChecksPasses) - { - logs.fatal() << "At least one year has failed final reservoir level pre-checks."; - AntaresSolverEmergencyShutdown(); - } + study.areas.each( + [&study, &yearIndex](Data::Area& area) + { + auto& finalinflows = area.hydro.finalLevelInflowsModifyer; + auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; + auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; + auto& parameters = study.parameters; + + finalinflows->initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters); + + if (!finalinflows->isActive()) + return; + + finalinflows->updateInflows(); + }); } } // namespace Antares::Solver \ No newline at end of file diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index bcb89d6886..664bb4dc64 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -32,11 +32,7 @@ namespace Antares::Solver { -void FinalReservoirLevel(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const Data::Parameters& parameters, - std::shared_ptr finalinflows, - uint yearIndex); +void prepareFinalReservoirLevelData(Data::Study& study, uint yearIndex); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ From c7decacaff3c9798028675285427de7064a21497 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Fri, 28 Jul 2023 18:55:11 +0200 Subject: [PATCH 428/490] Exclude return statement --- .../simulation/hydro-final-reservoir-level-functions.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 9deaa32952..eb89bb71aa 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -44,9 +44,9 @@ void prepareFinalReservoirLevelData(Data::Study& study, uint yearIndex) scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters); if (!finalinflows->isActive()) - return; - - finalinflows->updateInflows(); + { + finalinflows->updateInflows(); + } }); } From f5afafbaadbddc3e144922ea1743218638ba9aca Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Fri, 28 Jul 2023 19:32:05 +0200 Subject: [PATCH 429/490] Passing MC year to initialzeData function --- .../study/parts/hydro/finallevelinflowsmodifyer.cpp | 5 +++-- .../antares/study/parts/hydro/finallevelinflowsmodifyer.h | 3 ++- .../simulation/hydro-final-reservoir-level-functions.cpp | 8 ++++---- .../simulation/hydro-final-reservoir-level-functions.h | 2 +- 4 files changed, 10 insertions(+), 8 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 308d5c3701..2eec0f83d2 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -129,10 +129,11 @@ bool FinalLevelInflowsModifyer::preCheckRuleCurves() const void FinalLevelInflowsModifyer::initializeData(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const Data::Parameters& parameters) + const Data::Parameters& parameters, + uint year) { fillEmpty(); - initializeGeneralData(parameters, yearIndex); + initializeGeneralData(parameters, year); initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); initializePreCheckData(); } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 67da9e2bb8..e43dc4f868 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -97,7 +97,8 @@ class FinalLevelInflowsModifyer public: void initializeData(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const Data::Parameters& parameters); + const Data::Parameters& parameters, + uint year); bool isActive(); void updateInflows(); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index eb89bb71aa..8bfbc3f373 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -30,10 +30,10 @@ namespace Antares::Solver { -void prepareFinalReservoirLevelData(Data::Study& study, uint yearIndex) +void prepareFinalReservoirLevelData(Data::Study& study, uint year) { study.areas.each( - [&study, &yearIndex](Data::Area& area) + [&study, &year](Data::Area& area) { auto& finalinflows = area.hydro.finalLevelInflowsModifyer; auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; @@ -41,9 +41,9 @@ void prepareFinalReservoirLevelData(Data::Study& study, uint yearIndex) auto& parameters = study.parameters; finalinflows->initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters); + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - if (!finalinflows->isActive()) + if (finalinflows->isActive()) { finalinflows->updateInflows(); } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 664bb4dc64..26b3b5730a 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -32,7 +32,7 @@ namespace Antares::Solver { -void prepareFinalReservoirLevelData(Data::Study& study, uint yearIndex); +void prepareFinalReservoirLevelData(Data::Study& study, uint year); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ From 81df539f936ad33f0d3d6f51e4ed3fb96580b788 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 28 Jul 2023 20:02:09 +0200 Subject: [PATCH 430/490] refactor: calculateTotalInflows +prepareFinalReservoirLevelDataPerMcY +makeChecks --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 29 ++++++++++--------- .../parts/hydro/finallevelinflowsmodifyer.h | 4 ++- src/solver/simulation/apply-scenario.cpp | 7 +---- .../hydro-final-reservoir-level-functions.cpp | 13 ++++++++- .../hydro-final-reservoir-level-functions.h | 4 +-- 5 files changed, 33 insertions(+), 24 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 2eec0f83d2..c90592f9fa 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -77,9 +77,14 @@ void FinalLevelInflowsModifyer::assignEndLevelAndDelta() deltaLevel.at(yearIndex) = deltaReservoirLevel; } -double FinalLevelInflowsModifyer::calculateTotalInflows( - Antares::Memory::Stored::Type& srcinflows) const +double FinalLevelInflowsModifyer::calculateTotalInflows() const { + // calculate yearly inflows + const Data::DataSeriesHydro& data = *areaPtr->hydro.series; + uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex]; + auto& inflowsmatrix = areaPtr->hydro.series->storage; + auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; + double totalYearInflows = 0.0; for (uint day = 0; day < DAYS_PER_YEAR; ++day) totalYearInflows += srcinflows[day]; @@ -153,27 +158,23 @@ bool FinalLevelInflowsModifyer::isActive() void FinalLevelInflowsModifyer::updateInflows() { - bool preChecksPasses = true; - assignEndLevelAndDelta(); + // rule curve values for simEndDayReal + ruleCurveForSimEndReal(); +} + +void FinalLevelInflowsModifyer::makeChecks() +{ + bool preChecksPasses = true; // pre-check 0 -> simulation must end on day 365 and reservoir level must be // initiated in January if (!preCheckStartAndEndSim()) preChecksPasses = false; - // rule curve values for simEndDayReal - ruleCurveForSimEndReal(); - - // calculate (partial)yearly inflows - const Data::DataSeriesHydro& data = *areaPtr->hydro.series; - uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex]; - auto& inflowsmatrix = areaPtr->hydro.series->storage; - auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; - // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if (double totalInflows = calculateTotalInflows(srcinflows); + if (double totalInflows = calculateTotalInflows(); !preCheckYearlyInflow(totalInflows)) preChecksPasses = false; diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index e43dc4f868..a52b323ee4 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -78,7 +78,7 @@ class FinalLevelInflowsModifyer void assignEndLevelAndDelta(); - double calculateTotalInflows(Antares::Memory::Stored::Type& srcinflows) const; + double calculateTotalInflows() const; bool preCheckStartAndEndSim() const; @@ -102,6 +102,8 @@ class FinalLevelInflowsModifyer bool isActive(); void updateInflows(); + + void makeChecks(); }; } // namespace Antares::Data diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 682d672a1c..372ed15cf8 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -57,12 +57,7 @@ void ApplyCustomScenario(Data::Study& study) study.scenarioRulesDestroy(); logs.info(); - uint numberMCYears = study.scenarioFinalHydroLevels.height; - - for (uint yearIndex = 0; yearIndex != numberMCYears; ++yearIndex) - { - prepareFinalReservoirLevelData(study, yearIndex); - } + prepareFinalReservoirLevelData(study); } } // namespace Antares::Solver diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 8bfbc3f373..7fcd36fab4 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -30,7 +30,7 @@ namespace Antares::Solver { -void prepareFinalReservoirLevelData(Data::Study& study, uint year) +void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) { study.areas.each( [&study, &year](Data::Area& area) @@ -46,8 +46,19 @@ void prepareFinalReservoirLevelData(Data::Study& study, uint year) if (finalinflows->isActive()) { finalinflows->updateInflows(); + finalinflows->makeChecks(); } }); } +void prepareFinalReservoirLevelData(Data::Study& study) +{ + uint numberMCYears = study.scenarioFinalHydroLevels.height; + + for (uint yearIndex = 0; yearIndex != numberMCYears; ++yearIndex) + { + prepareFinalReservoirLevelDataPerMcY(study, yearIndex); + } +} + } // namespace Antares::Solver \ No newline at end of file diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 26b3b5730a..797939f8c9 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,8 +31,8 @@ namespace Antares::Solver { - -void prepareFinalReservoirLevelData(Data::Study& study, uint year); +void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year); +void prepareFinalReservoirLevelData(Data::Study& study); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ From 581c4df996ea846f2f20e100df29365429646ce9 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 28 Jul 2023 20:16:10 +0200 Subject: [PATCH 431/490] typo --- src/libs/antares/study/area/list.cpp | 4 +-- .../antares/study/parts/hydro/container.cpp | 2 +- .../antares/study/parts/hydro/container.h | 4 +-- .../parts/hydro/finallevelinflowsmodifyer.cpp | 30 +++++++++---------- .../parts/hydro/finallevelinflowsmodifyer.h | 4 +-- src/solver/hydro/management/management.cpp | 6 ++-- .../hydro-final-reservoir-level-functions.cpp | 2 +- 7 files changed, 26 insertions(+), 26 deletions(-) diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 4ebb32ecd5..83c55e4d27 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1328,8 +1328,8 @@ void AreaListEnsureFinalLevelInflowsModifyerAreaPtr(AreaList* l) assert(l); l->each([&](Data::Area& area) { - if (!area.hydro.finalLevelInflowsModifyer->areaPtr) - area.hydro.finalLevelInflowsModifyer->areaPtr = &area; + if (!area.hydro.finalLevelInflowsModifier->areaPtr) + area.hydro.finalLevelInflowsModifier->areaPtr = &area; }); } diff --git a/src/libs/antares/study/parts/hydro/container.cpp b/src/libs/antares/study/parts/hydro/container.cpp index bb4cf63702..647f1a5b1a 100644 --- a/src/libs/antares/study/parts/hydro/container.cpp +++ b/src/libs/antares/study/parts/hydro/container.cpp @@ -58,7 +58,7 @@ PartHydro::PartHydro() : hydroModulable(false), prepro(nullptr), series(nullptr), - finalLevelInflowsModifyer(std::make_shared()) + finalLevelInflowsModifier(std::make_shared()) { } diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index c43f3a2b10..c509031968 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -38,7 +38,7 @@ namespace Antares::Data ** \brief Final Reservoir Level data for a single area */ -class FinalLevelInflowsModifyer; +class FinalLevelInflowsModifier; /*! ** \brief Hydro for a single area @@ -180,7 +180,7 @@ class PartHydro //! Data for final reservoir level - std::shared_ptr finalLevelInflowsModifyer; + std::shared_ptr finalLevelInflowsModifier; }; // class PartHydro diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index c90592f9fa..25d7cfbb60 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -32,24 +32,24 @@ namespace Antares namespace Data { -FinalLevelInflowsModifyer::FinalLevelInflowsModifyer() : areaPtr(nullptr) +FinalLevelInflowsModifier::FinalLevelInflowsModifier() : areaPtr(nullptr) { } -void FinalLevelInflowsModifyer::fillEmpty() +void FinalLevelInflowsModifier::fillEmpty() { includeFinalReservoirLevel.push_back(false); endLevel.push_back(0.); deltaLevel.push_back(0.); } -void FinalLevelInflowsModifyer::initializeGeneralData(const Data::Parameters& parameters, uint year) +void FinalLevelInflowsModifier::initializeGeneralData(const Data::Parameters& parameters, uint year) { simEndDay = parameters.simulationDays.end; yearIndex = year; } -void FinalLevelInflowsModifyer::initializePerAreaData( +void FinalLevelInflowsModifier::initializePerAreaData( const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels) { @@ -58,26 +58,26 @@ void FinalLevelInflowsModifyer::initializePerAreaData( deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; } -void FinalLevelInflowsModifyer::initializePreCheckData() +void FinalLevelInflowsModifier::initializePreCheckData() { initReservoirLvlMonth = areaPtr->hydro.initializeReservoirLevelDate; // month [0-11] reservoirCapacity = areaPtr->hydro.reservoirCapacity; } -void FinalLevelInflowsModifyer::ruleCurveForSimEndReal() +void FinalLevelInflowsModifier::ruleCurveForSimEndReal() { lowLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; highLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; } -void FinalLevelInflowsModifyer::assignEndLevelAndDelta() +void FinalLevelInflowsModifier::assignEndLevelAndDelta() { includeFinalReservoirLevel.at(yearIndex) = true; endLevel.at(yearIndex) = finalReservoirLevel; deltaLevel.at(yearIndex) = deltaReservoirLevel; } -double FinalLevelInflowsModifyer::calculateTotalInflows() const +double FinalLevelInflowsModifier::calculateTotalInflows() const { // calculate yearly inflows const Data::DataSeriesHydro& data = *areaPtr->hydro.series; @@ -91,7 +91,7 @@ double FinalLevelInflowsModifyer::calculateTotalInflows() const return totalYearInflows; } -bool FinalLevelInflowsModifyer::preCheckStartAndEndSim() const +bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const { if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) return true; @@ -104,7 +104,7 @@ bool FinalLevelInflowsModifyer::preCheckStartAndEndSim() const } } -bool FinalLevelInflowsModifyer::preCheckYearlyInflow(double totalYearInflows) const +bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) const { if ((-deltaReservoirLevel) * reservoirCapacity > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh @@ -119,7 +119,7 @@ bool FinalLevelInflowsModifyer::preCheckYearlyInflow(double totalYearInflows) co return true; } -bool FinalLevelInflowsModifyer::preCheckRuleCurves() const +bool FinalLevelInflowsModifier::preCheckRuleCurves() const { if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) { @@ -132,7 +132,7 @@ bool FinalLevelInflowsModifyer::preCheckRuleCurves() const return true; } -void FinalLevelInflowsModifyer::initializeData(const Matrix& scenarioInitialHydroLevels, +void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, const Data::Parameters& parameters, uint year) @@ -143,7 +143,7 @@ void FinalLevelInflowsModifyer::initializeData(const Matrix& scenarioIni initializePreCheckData(); } -bool FinalLevelInflowsModifyer::isActive() +bool FinalLevelInflowsModifier::isActive() { if (areaPtr->hydro.reservoirManagement && !areaPtr->hydro.useWaterValue && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) @@ -156,14 +156,14 @@ bool FinalLevelInflowsModifyer::isActive() } } -void FinalLevelInflowsModifyer::updateInflows() +void FinalLevelInflowsModifier::updateInflows() { assignEndLevelAndDelta(); // rule curve values for simEndDayReal ruleCurveForSimEndReal(); } -void FinalLevelInflowsModifyer::makeChecks() +void FinalLevelInflowsModifier::makeChecks() { bool preChecksPasses = true; diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index a52b323ee4..4cc2909183 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -36,7 +36,7 @@ namespace Antares::Data /*! ** \brief Final Reservoir Level data for a single area */ -class FinalLevelInflowsModifyer +class FinalLevelInflowsModifier { private: // Final reservoir level runtime data @@ -69,7 +69,7 @@ class FinalLevelInflowsModifyer std::vector deltaLevel; // Constructor - FinalLevelInflowsModifyer(); + FinalLevelInflowsModifier(); private: // methods: diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index f70ab19a75..bc42c5ef14 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -357,13 +357,13 @@ void HydroManagement::changeInflowsDueToFinalLevels(uint numSpace, uint year) [this, &numSpace, &year](Data::Area& area) { auto& data = pAreas[numSpace][area.index]; - if (area.hydro.finalLevelInflowsModifyer->deltaLevel.empty()) + if (area.hydro.finalLevelInflowsModifier->deltaLevel.empty()) return; - if (!area.hydro.finalLevelInflowsModifyer->includeFinalReservoirLevel[year]) + if (!area.hydro.finalLevelInflowsModifier->includeFinalReservoirLevel[year]) return; - double delta = area.hydro.finalLevelInflowsModifyer->deltaLevel[year]; + double delta = area.hydro.finalLevelInflowsModifier->deltaLevel[year]; // must be done before prepareMonthlyTargetGenerations if (delta > 0) data.inflows[0] += delta; diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 7fcd36fab4..8fa79075ba 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -35,7 +35,7 @@ void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) study.areas.each( [&study, &year](Data::Area& area) { - auto& finalinflows = area.hydro.finalLevelInflowsModifyer; + auto& finalinflows = area.hydro.finalLevelInflowsModifier; auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; auto& parameters = study.parameters; From e03c09264d6b93ed52766bf3ab7fb9fd2584dc33 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 28 Jul 2023 20:24:36 +0200 Subject: [PATCH 432/490] typo --- .../hydro-final-reservoir-level-functions.cpp | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 8fa79075ba..3e95c36da3 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -35,18 +35,18 @@ void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) study.areas.each( [&study, &year](Data::Area& area) { - auto& finalinflows = area.hydro.finalLevelInflowsModifier; + auto& finalInflows = area.hydro.finalLevelInflowsModifier; auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; auto& parameters = study.parameters; - finalinflows->initializeData( + finalInflows->initializeData( scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - if (finalinflows->isActive()) + if (finalInflows->isActive()) { - finalinflows->updateInflows(); - finalinflows->makeChecks(); + finalInflows->updateInflows(); + finalInflows->makeChecks(); } }); } From 96c7eb2334272bafea92d2d7a76e84ac6d8d5188 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sat, 29 Jul 2023 10:34:17 +0200 Subject: [PATCH 433/490] fix build fail --- src/libs/antares/study/parts/hydro/container.h | 1 + 1 file changed, 1 insertion(+) diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index c509031968..315744646c 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -31,6 +31,7 @@ #include "series.h" #include "../../fwd.h" #include "allocation.h" +#include namespace Antares::Data { From 55da2607779d2addb0076495306da1f1c5db9ff6 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sat, 29 Jul 2023 15:49:47 +0200 Subject: [PATCH 434/490] refactor - fix unit tests --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 25d7cfbb60..d373f2c3fc 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -137,6 +137,8 @@ void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioIni const Data::Parameters& parameters, uint year) { + if (!areaPtr) + return; fillEmpty(); initializeGeneralData(parameters, year); initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); @@ -145,7 +147,7 @@ void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioIni bool FinalLevelInflowsModifier::isActive() { - if (areaPtr->hydro.reservoirManagement && !areaPtr->hydro.useWaterValue + if (areaPtr && areaPtr->hydro.reservoirManagement && !areaPtr->hydro.useWaterValue && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) { return true; From 53a7180763cb6efb1763219f3febd45b05f706a4 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sat, 29 Jul 2023 16:19:54 +0200 Subject: [PATCH 435/490] add areaPtr to unit test-s --- .../end-to-end/binding_constraints/test_binding_constraints.cpp | 1 + src/tests/end-to-end/simple_study/simple-study.cpp | 1 + 2 files changed, 2 insertions(+) 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 cc4a7f5573..7e188d8c51 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 @@ -42,6 +42,7 @@ void simulationBetweenDays(Study::Ptr study, const unsigned int firstDay, const Area* addAreaToStudy(Study::Ptr study, const std::string& areaName, double loadInArea) { Area* area = study->areaAdd(areaName); + area->hydro.finalLevelInflowsModifier->areaPtr = area; BOOST_CHECK(area != NULL); 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 ae70234fc6..0d3f311fe2 100644 --- a/src/tests/end-to-end/simple_study/simple-study.cpp +++ b/src/tests/end-to-end/simple_study/simple-study.cpp @@ -12,6 +12,7 @@ using namespace Antares::Data; Area* addArea(Study::Ptr pStudy, const std::string& areaName, int nbTS) { Area* pArea = pStudy->areaAdd(areaName); + pArea->hydro.finalLevelInflowsModifier->areaPtr = pArea; BOOST_CHECK(pArea != NULL); From 46c36e88e82e49a60c552c06a88951d6281dac53 Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Mon, 31 Jul 2023 15:00:44 +0200 Subject: [PATCH 436/490] New implementation for overriden apply function --- .../scenario-builder/hydroLevelsData.cpp | 13 ++++-------- .../study/scenario-builder/hydroLevelsData.h | 21 +++++++++++++++---- .../antares/study/scenario-builder/rules.cpp | 4 ++-- .../antares/study/scenario-builder/rules.h | 4 ++-- 4 files changed, 25 insertions(+), 17 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index 5aabfcec9d..40bfb1d019 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -36,8 +36,9 @@ namespace Data { namespace ScenarioBuilder { -hydroLevelsData::hydroLevelsData(std::string& iniFilePrefix) : -addToPrefix(iniFilePrefix) +hydroLevelsData::hydroLevelsData(std::string& iniFilePrefix, + std::function applyToTarget) : + addToPrefix(iniFilePrefix), applyToTarget_(applyToTarget) { } @@ -90,13 +91,7 @@ void hydroLevelsData::set_value(uint x, uint y, double value) bool hydroLevelsData::apply(Study& study) { - study.scenarioInitialHydroLevels.copyFrom(pHydroLevelsRules); - return true; -} - -bool hydroLevelsData::applyHydroLevels(Matrix& scenarioHydroLevels) const -{ - scenarioHydroLevels.copyFrom(pHydroLevelsRules); + applyToTarget_(study, pHydroLevelsRules); return true; } diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h index f31b0d4643..70f615c632 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.h @@ -28,6 +28,7 @@ #define __LIBS_STUDY_SCENARIO_BUILDER_DATA_HYDRO_LEVELS_H__ #include "scBuilderDataInterface.h" +#include namespace Antares { @@ -46,8 +47,9 @@ class hydroLevelsData final : public dataInterface public: // Constructor - - hydroLevelsData(std::string& iniFilePrefix); + + hydroLevelsData(std::string& iniFilePrefix, + std::function&)> applyToTarget); //! \name Data manupulation //@{ @@ -79,8 +81,7 @@ class hydroLevelsData final : public dataInterface void set_value(uint x, uint y, double value); - bool apply(Study& study); - bool applyHydroLevels(Matrix& scenarioHydroLevels) const; + bool apply(Study& study) override; private: //! Hydro levels overlay (0 if auto) @@ -88,6 +89,8 @@ class hydroLevelsData final : public dataInterface // prefix to be added when calling saveToINIFileHydroLevel std::string& addToPrefix; + std::function&)> applyToTarget_; + }; // class hydroLevelsData // class hydroLevelsData : inline functions @@ -114,6 +117,16 @@ 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 diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index b455435bc9..0a673c6f28 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -379,8 +379,8 @@ bool Rules::apply() returned_status = renewable[i].apply(study_) && returned_status; returned_status = linksNTC[i].apply(study_) && returned_status; } - returned_status = hydroInitialLevels.applyHydroLevels(study_.scenarioInitialHydroLevels) && returned_status; - returned_status = hydroFinalLevels.applyHydroLevels(study_.scenarioFinalHydroLevels) && 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 diff --git a/src/libs/antares/study/scenario-builder/rules.h b/src/libs/antares/study/scenario-builder/rules.h index 1f97e01c46..2f90287b51 100644 --- a/src/libs/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/scenario-builder/rules.h @@ -119,10 +119,10 @@ class Rules final : private Yuni::NonCopyable //! hydro initial levels std::string prefixInitial = "hl,"; - hydroLevelsData hydroInitialLevels = hydroLevelsData(prefixInitial); + hydroLevelsData hydroInitialLevels = hydroLevelsData(prefixInitial, initLevelApply); //! hydro final levels std::string prefixFinal = "hfl,"; - hydroLevelsData hydroFinalLevels = hydroLevelsData(prefixFinal); + hydroLevelsData hydroFinalLevels = hydroLevelsData(prefixFinal, finalLevelApply); // Links NTC std::vector linksNTC; From 7cf06f1a41c1179e4e18f840cc604167aead527b Mon Sep 17 00:00:00 2001 From: NikolaIlic Date: Mon, 31 Jul 2023 16:19:46 +0200 Subject: [PATCH 437/490] typo --- src/libs/antares/study/scenario-builder/hydroLevelsData.h | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.h b/src/libs/antares/study/scenario-builder/hydroLevelsData.h index 70f615c632..0ebbcf3b67 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.h @@ -49,7 +49,7 @@ class hydroLevelsData final : public dataInterface // Constructor hydroLevelsData(std::string& iniFilePrefix, - std::function&)> applyToTarget); + std::function applyToTarget); //! \name Data manupulation //@{ @@ -89,7 +89,7 @@ class hydroLevelsData final : public dataInterface // prefix to be added when calling saveToINIFileHydroLevel std::string& addToPrefix; - std::function&)> applyToTarget_; + std::function applyToTarget_; }; // class hydroLevelsData From 3cb2a9ae8d570439f734cdeea6fe241d400eca0a Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?Florian=20Omn=C3=A8s?= Date: Fri, 4 Aug 2023 11:34:56 +0200 Subject: [PATCH 438/490] Remove std::shared_ptr around FinalLevelInflowsModifier (#1490) --- src/libs/antares/study/area/area.cpp | 5 +- src/libs/antares/study/area/area.h | 5 -- src/libs/antares/study/area/list.cpp | 12 ----- .../antares/study/parts/hydro/container.cpp | 4 +- .../antares/study/parts/hydro/container.h | 15 ++---- .../parts/hydro/finallevelinflowsmodifyer.cpp | 46 ++++++++----------- .../parts/hydro/finallevelinflowsmodifyer.h | 24 ++++++---- src/solver/hydro/management/management.cpp | 46 +++++++++---------- .../hydro-final-reservoir-level-functions.cpp | 8 ++-- .../test_binding_constraints.cpp | 1 - .../end-to-end/simple_study/simple-study.cpp | 1 - 11 files changed, 69 insertions(+), 98 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index 48995d3deb..e0f7a35688 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -50,6 +50,7 @@ Area::Area() : enabled(true), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), + hydro(*this), nodalOptimization(anoAll), spreadUnsuppliedEnergyCost(0.), spreadSpilledEnergyCost(0.), @@ -66,6 +67,7 @@ Area::Area(const AnyString& name, uint nbParallelYears) : index((uint)(-1)), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), + hydro(*this), nodalOptimization(anoAll), spreadUnsuppliedEnergyCost(0.), spreadSpilledEnergyCost(0.), @@ -84,6 +86,7 @@ Area::Area(const AnyString& name, const AnyString& id, uint nbParallelYears, uin index(indx), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR), + hydro(*this), nodalOptimization(anoAll), spreadUnsuppliedEnergyCost(0.), spreadSpilledEnergyCost(0.), @@ -530,4 +533,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 index 93759eb322..f24b6df1eb 100644 --- a/src/libs/antares/study/area/area.h +++ b/src/libs/antares/study/area/area.h @@ -853,11 +853,6 @@ void AreaListEnsureDataRenewableTimeSeries(AreaList* l); */ void AreaListEnsureDataThermalPrepro(AreaList* l); - /*! -** \brief Ensure data for FinalLevelInflowsModifier are initialized -*/ -void AreaListEnsureFinalLevelInflowsModifyerAreaPtr(AreaList* l); - /*! ** \brief to check that Area name does not contains character * */ diff --git a/src/libs/antares/study/area/list.cpp b/src/libs/antares/study/area/list.cpp index 5cc33f6711..c9aee7c564 100644 --- a/src/libs/antares/study/area/list.cpp +++ b/src/libs/antares/study/area/list.cpp @@ -1043,7 +1043,6 @@ void AreaList::ensureDataIsInitialized(Parameters& params, bool loadOnlyNeeded) AreaListEnsureDataHydroTimeSeries(this); AreaListEnsureDataThermalTimeSeries(this); AreaListEnsureDataRenewableTimeSeries(this); - AreaListEnsureFinalLevelInflowsModifyerAreaPtr(this); if (loadOnlyNeeded) { @@ -1325,17 +1324,6 @@ void AreaListEnsureDataHydroTimeSeries(AreaList* l) }); } -void AreaListEnsureFinalLevelInflowsModifyerAreaPtr(AreaList* l) -{ - /* Asserts */ - assert(l); - - l->each([&](Data::Area& area) { - if (!area.hydro.finalLevelInflowsModifier->areaPtr) - area.hydro.finalLevelInflowsModifier->areaPtr = &area; - }); -} - void AreaListEnsureDataHydroPrepro(AreaList* l) { /* Asserts */ diff --git a/src/libs/antares/study/parts/hydro/container.cpp b/src/libs/antares/study/parts/hydro/container.cpp index c91f948d2d..b48867be33 100644 --- a/src/libs/antares/study/parts/hydro/container.cpp +++ b/src/libs/antares/study/parts/hydro/container.cpp @@ -39,7 +39,7 @@ namespace Antares { namespace Data { -PartHydro::PartHydro() : +PartHydro::PartHydro(const Data::Area& area) : interDailyBreakdown(0.), intraDailyModulation(2.), intermonthlyBreakdown(0), @@ -58,7 +58,7 @@ PartHydro::PartHydro() : hydroModulable(false), prepro(nullptr), series(nullptr), - finalLevelInflowsModifier(std::make_shared()) + finalLevelInflowsModifier(*this, area.index, area.name) { } diff --git a/src/libs/antares/study/parts/hydro/container.h b/src/libs/antares/study/parts/hydro/container.h index 315744646c..c0356cff42 100644 --- a/src/libs/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/parts/hydro/container.h @@ -31,16 +31,10 @@ #include "series.h" #include "../../fwd.h" #include "allocation.h" -#include +#include "finallevelinflowsmodifyer.h" namespace Antares::Data { -/*! - ** \brief Final Reservoir Level data for a single area - */ - -class FinalLevelInflowsModifier; - /*! ** \brief Hydro for a single area */ @@ -100,7 +94,7 @@ class PartHydro /*! ** \brief Default Constructor */ - PartHydro(); + PartHydro(const Data::Area& area); //! Destructor ~PartHydro(); @@ -180,12 +174,9 @@ class PartHydro DataSeriesHydro* series; //! Data for final reservoir level - - std::shared_ptr finalLevelInflowsModifier; - + FinalLevelInflowsModifier finalLevelInflowsModifier; }; // 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 diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index d373f2c3fc..780ec7f51d 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -25,14 +25,18 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ +#include #include "finallevelinflowsmodifyer.h" +#include "container.h" namespace Antares { namespace Data { - -FinalLevelInflowsModifier::FinalLevelInflowsModifier() : areaPtr(nullptr) +FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, + const unsigned int& areaIndex, + const AreaName& areaName) : + hydro(hydro), areaIndex(areaIndex), areaName(areaName) { } @@ -53,21 +57,21 @@ void FinalLevelInflowsModifier::initializePerAreaData( const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels) { - initialReservoirLevel = scenarioInitialHydroLevels[areaPtr->index][yearIndex]; - finalReservoirLevel = scenarioFinalHydroLevels[areaPtr->index][yearIndex]; + initialReservoirLevel = scenarioInitialHydroLevels[areaIndex][yearIndex]; + finalReservoirLevel = scenarioFinalHydroLevels[areaIndex][yearIndex]; deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; } void FinalLevelInflowsModifier::initializePreCheckData() { - initReservoirLvlMonth = areaPtr->hydro.initializeReservoirLevelDate; // month [0-11] - reservoirCapacity = areaPtr->hydro.reservoirCapacity; + initReservoirLvlMonth = hydro.initializeReservoirLevelDate; // month [0-11] + reservoirCapacity = hydro.reservoirCapacity; } void FinalLevelInflowsModifier::ruleCurveForSimEndReal() { - lowLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - highLevelLastDay = areaPtr->hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + lowLevelLastDay = hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + highLevelLastDay = hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; } void FinalLevelInflowsModifier::assignEndLevelAndDelta() @@ -80,9 +84,9 @@ void FinalLevelInflowsModifier::assignEndLevelAndDelta() double FinalLevelInflowsModifier::calculateTotalInflows() const { // calculate yearly inflows - const Data::DataSeriesHydro& data = *areaPtr->hydro.series; + const Data::DataSeriesHydro& data = *hydro.series; uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex]; - auto& inflowsmatrix = areaPtr->hydro.series->storage; + auto& inflowsmatrix = hydro.series->storage; auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; double totalYearInflows = 0.0; @@ -97,7 +101,7 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const return true; else { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaPtr->name + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName << ". Simulation must end on day 365 and reservoir level must be " "initiated in January"; return false; @@ -110,7 +114,7 @@ bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) co > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh // (energy) { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaPtr->name + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName << ". Incompatible total inflows: " << totalYearInflows << " with initial: " << initialReservoirLevel << " and final: " << finalReservoirLevel << " reservoir levels."; @@ -123,7 +127,7 @@ bool FinalLevelInflowsModifier::preCheckRuleCurves() const { if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaPtr->name + logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName << ". Specifed final reservoir level: " << finalReservoirLevel << " is incompatible with reservoir level rule curve [" << lowLevelLastDay << " , " << highLevelLastDay << "]"; @@ -137,8 +141,6 @@ void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioIni const Data::Parameters& parameters, uint year) { - if (!areaPtr) - return; fillEmpty(); initializeGeneralData(parameters, year); initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); @@ -147,15 +149,8 @@ void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioIni bool FinalLevelInflowsModifier::isActive() { - if (areaPtr && areaPtr->hydro.reservoirManagement && !areaPtr->hydro.useWaterValue - && !isnan(finalReservoirLevel) && !isnan(initialReservoirLevel)) - { - return true; - } - else - { - return false; - } + return hydro.reservoirManagement && !hydro.useWaterValue && !isnan(finalReservoirLevel) + && !isnan(initialReservoirLevel); } void FinalLevelInflowsModifier::updateInflows() @@ -176,8 +171,7 @@ void FinalLevelInflowsModifier::makeChecks() // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if (double totalInflows = calculateTotalInflows(); - !preCheckYearlyInflow(totalInflows)) + if (double totalInflows = calculateTotalInflows(); !preCheckYearlyInflow(totalInflows)) preChecksPasses = false; // pre-check 2 -> final reservoir level set by the user is within the diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 4cc2909183..d56a83d126 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -27,20 +27,26 @@ #ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__ #define __ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__ -#include "../../area/area.h" -#include +#include +#include +#include +#include namespace Antares::Data { - +class PartHydro; /*! ** \brief Final Reservoir Level data for a single area */ class FinalLevelInflowsModifier { -private: - // Final reservoir level runtime data +public: + FinalLevelInflowsModifier() = delete; + FinalLevelInflowsModifier(const PartHydro& hydro, + const unsigned int& areaIndex, + const AreaName& areaName); +private: // Simulation Data uint simEndDay; @@ -59,8 +65,9 @@ class FinalLevelInflowsModifier int initReservoirLvlMonth; public: - Area* areaPtr; - + const PartHydro& hydro; + const unsigned int& areaIndex; + const AreaName& areaName; // vectors containing data necessary for final reservoir level calculation // for one area and all MC years // vector indexes correspond to the MC years @@ -68,9 +75,6 @@ class FinalLevelInflowsModifier std::vector endLevel; std::vector deltaLevel; - // Constructor - FinalLevelInflowsModifier(); - private: // methods: diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 00d4803e36..6c4f2cfc47 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -234,12 +234,13 @@ bool HydroManagement::checkMonthlyMinGeneration(uint numSpace, uint tsIndex, con return true; } -bool HydroManagement::checkYearlyMinGeneration(uint numSpace, uint tsIndex, const Data::Area& area) const +bool HydroManagement::checkYearlyMinGeneration(uint numSpace, + uint tsIndex, + const Data::Area& area) const { const auto& data = pAreas[numSpace][area.index]; - if (area.hydro.followLoadModulations && - area.hydro.reservoirManagement && - data.totalYearMingen > data.totalYearInflows) + if (area.hydro.followLoadModulations && area.hydro.reservoirManagement + && data.totalYearMingen > data.totalYearInflows) { // Yearly minimum generation <= Yearly inflows logs.error() << "In Area " << area.name << " the minimum generation of " @@ -333,8 +334,7 @@ bool HydroManagement::checkHourlyMinGeneration(uint tsIndex, Data::Area& area) c bool HydroManagement::checkMinGeneration(uint numSpace) { bool ret = true; - study.areas.each([this, &numSpace, &ret](Data::Area& area) - { + study.areas.each([this, &numSpace, &ret](Data::Area& area) { uint z = area.index; const auto& ptchro = NumeroChroniquesTireesParPays[numSpace][z]; auto tsIndex = (uint)ptchro.Hydraulique; @@ -345,7 +345,7 @@ bool HydroManagement::checkMinGeneration(uint numSpace) ret = checkYearlyMinGeneration(numSpace, tsIndex, area) && ret; ret = checkWeeklyMinGeneration(tsIndex, area) && ret; } - + ret = checkHourlyMinGeneration(tsIndex, area) && ret; }); return ret; @@ -353,23 +353,21 @@ bool HydroManagement::checkMinGeneration(uint numSpace) void HydroManagement::changeInflowsDueToFinalLevels(uint numSpace, uint year) { - study.areas.each( - [this, &numSpace, &year](Data::Area& area) - { - auto& data = pAreas[numSpace][area.index]; - if (area.hydro.finalLevelInflowsModifier->deltaLevel.empty()) - return; - - if (!area.hydro.finalLevelInflowsModifier->includeFinalReservoirLevel[year]) - return; - - double delta = area.hydro.finalLevelInflowsModifier->deltaLevel[year]; - // must be done before prepareMonthlyTargetGenerations - if (delta > 0) - data.inflows[0] += delta; - else if (delta < 0) - data.inflows[11] += delta; - }); + study.areas.each([this, &numSpace, &year](Data::Area& area) { + auto& data = pAreas[numSpace][area.index]; + if (area.hydro.finalLevelInflowsModifier.deltaLevel.empty()) + return; + + if (!area.hydro.finalLevelInflowsModifier.includeFinalReservoirLevel[year]) + return; + + double delta = area.hydro.finalLevelInflowsModifier.deltaLevel[year]; + // must be done before prepareMonthlyTargetGenerations + if (delta > 0) + data.inflows[0] += delta; + else if (delta < 0) + data.inflows[11] += delta; + }); } template diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 3e95c36da3..d53e6b0aea 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -40,13 +40,13 @@ void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; auto& parameters = study.parameters; - finalInflows->initializeData( + finalInflows.initializeData( scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - if (finalInflows->isActive()) + if (finalInflows.isActive()) { - finalInflows->updateInflows(); - finalInflows->makeChecks(); + finalInflows.updateInflows(); + finalInflows.makeChecks(); } }); } 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 7e188d8c51..cc4a7f5573 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 @@ -42,7 +42,6 @@ void simulationBetweenDays(Study::Ptr study, const unsigned int firstDay, const Area* addAreaToStudy(Study::Ptr study, const std::string& areaName, double loadInArea) { Area* area = study->areaAdd(areaName); - area->hydro.finalLevelInflowsModifier->areaPtr = area; BOOST_CHECK(area != NULL); 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 0d3f311fe2..ae70234fc6 100644 --- a/src/tests/end-to-end/simple_study/simple-study.cpp +++ b/src/tests/end-to-end/simple_study/simple-study.cpp @@ -12,7 +12,6 @@ using namespace Antares::Data; Area* addArea(Study::Ptr pStudy, const std::string& areaName, int nbTS) { Area* pArea = pStudy->areaAdd(areaName); - pArea->hydro.finalLevelInflowsModifier->areaPtr = pArea; BOOST_CHECK(pArea != NULL); From 82bc568d4e1ef2a5d4263bb62b0efbc749a7f193 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sat, 5 Aug 2023 23:36:24 +0200 Subject: [PATCH 439/490] rename changeInflows function in HydroManagement --- src/solver/hydro/management/management.cpp | 4 ++-- src/solver/hydro/management/management.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 6c4f2cfc47..5bee274935 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -351,7 +351,7 @@ bool HydroManagement::checkMinGeneration(uint numSpace) return ret; } -void HydroManagement::changeInflowsDueToFinalLevels(uint numSpace, uint year) +void HydroManagement::changeInflowsToAccommodateFinalLevels(uint numSpace, uint year) { study.areas.each([this, &numSpace, &year](Data::Area& area) { auto& data = pAreas[numSpace][area.index]; @@ -526,7 +526,7 @@ void HydroManagement::operator()(double* randomReservoirLevel, AntaresSolverEmergencyShutdown(); } - changeInflowsDueToFinalLevels(numSpace, y); + changeInflowsToAccommodateFinalLevels(numSpace, y); if (parameters.adequacy()) prepareNetDemand(numSpace); diff --git a/src/solver/hydro/management/management.h b/src/solver/hydro/management/management.h index 5bd8a7b3df..7737c6a9c3 100644 --- a/src/solver/hydro/management/management.h +++ b/src/solver/hydro/management/management.h @@ -76,7 +76,7 @@ class HydroManagement final //! Prepare inflows scaling for each area void prepareInflowsScaling(uint numSpace); //! prepare data for Final reservoir level - void changeInflowsDueToFinalLevels(uint numSpace, uint yearIndex); + void changeInflowsToAccommodateFinalLevels(uint numSpace, uint yearIndex); //! Prepare minimum generation scaling for each area void minGenerationScaling(uint numSpace); //! check Monthly minimum generation is lower than available inflows From 2e9173e3cb9e0a46fea1442eca517941a1c320a3 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sun, 6 Aug 2023 01:02:30 +0200 Subject: [PATCH 440/490] small refactor - due to unit tests --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 15 ++++----------- .../study/parts/hydro/finallevelinflowsmodifyer.h | 4 +--- .../hydro-final-reservoir-level-functions.cpp | 9 +++++---- 3 files changed, 10 insertions(+), 18 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 780ec7f51d..fb7436718e 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -25,7 +25,6 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#include #include "finallevelinflowsmodifyer.h" #include "container.h" @@ -74,7 +73,7 @@ void FinalLevelInflowsModifier::ruleCurveForSimEndReal() highLevelLastDay = hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; } -void FinalLevelInflowsModifier::assignEndLevelAndDelta() +void FinalLevelInflowsModifier::updateInflows() { includeFinalReservoirLevel.at(yearIndex) = true; endLevel.at(yearIndex) = finalReservoirLevel; @@ -145,6 +144,7 @@ void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioIni initializeGeneralData(parameters, year); initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); initializePreCheckData(); + ruleCurveForSimEndReal(); } bool FinalLevelInflowsModifier::isActive() @@ -153,14 +153,7 @@ bool FinalLevelInflowsModifier::isActive() && !isnan(initialReservoirLevel); } -void FinalLevelInflowsModifier::updateInflows() -{ - assignEndLevelAndDelta(); - // rule curve values for simEndDayReal - ruleCurveForSimEndReal(); -} - -void FinalLevelInflowsModifier::makeChecks() +bool FinalLevelInflowsModifier::makeChecks() { bool preChecksPasses = true; @@ -182,8 +175,8 @@ void FinalLevelInflowsModifier::makeChecks() if (!preChecksPasses) { logs.fatal() << "At least one year has failed final reservoir level pre-checks."; - AntaresSolverEmergencyShutdown(); } + return preChecksPasses; } } // namespace Data diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index d56a83d126..f38dd234b1 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -80,8 +80,6 @@ class FinalLevelInflowsModifier void fillEmpty(); - void assignEndLevelAndDelta(); - double calculateTotalInflows() const; bool preCheckStartAndEndSim() const; @@ -107,7 +105,7 @@ class FinalLevelInflowsModifier void updateInflows(); - void makeChecks(); + bool makeChecks(); }; } // namespace Antares::Data diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index d53e6b0aea..8db5b42d01 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -26,6 +26,7 @@ */ #include "hydro-final-reservoir-level-functions.h" +#include namespace Antares::Solver { @@ -44,10 +45,10 @@ void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); if (finalInflows.isActive()) - { - finalInflows.updateInflows(); - finalInflows.makeChecks(); - } + if (finalInflows.makeChecks()) + finalInflows.updateInflows(); + else + AntaresSolverEmergencyShutdown(); }); } From 216d95177820022efffc9f5be49916a1976fd675 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sun, 6 Aug 2023 01:03:25 +0200 Subject: [PATCH 441/490] re-enable unit tests --- .../src/solver/simulation/CMakeLists.txt | 28 ++ ...-hydro-final-reservoir-level-functions.cpp | 318 +++++++++++------- 2 files changed, 220 insertions(+), 126 deletions(-) diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index 330d55ebe1..7506a8550e 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -88,3 +88,31 @@ set_property(TEST time_series PROPERTY LABELS unit) # =================================== # Tests on hydro final reservoir level functions # =================================== +set(SRC_HYDRO_FINAL_LEVEL + ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.h + ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.cpp + ${src_solver_simulation}/hydro-final-reservoir-level-functions.h + ${src_solver_simulation}/hydro-final-reservoir-level-functions.cpp +) + +add_executable(test-hydro_final + test-hydro-final-reservoir-level-functions.cpp + ${SRC_HYDRO_FINAL_LEVEL}) + +target_include_directories(test-hydro_final + PRIVATE + "${src_solver_simulation}" + "${src_libs_antares_study}" +) +target_link_libraries(test-hydro_final + PRIVATE + Boost::unit_test_framework + libantares-core + libantares-solver-simulation +) + +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 index 87957daf8c..d1617561f0 100644 --- 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 @@ -1,7 +1,7 @@ // // Created by Nikola Ilic on 23/06/23. // -/* + #define BOOST_TEST_MODULE hydro - final - level #define WIN32_LEAN_AND_MEAN #include @@ -155,194 +155,260 @@ struct Fixture BOOST_FIXTURE_TEST_SUITE(s, Fixture) -BOOST_AUTO_TEST_CASE(Testing_initializeGeneralData_function_for_area_1) +BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_pass) { auto& parameters = study->parameters; auto& year = parameters.nbYears; - year = 5; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 1; - auto& RuntimeData = area_1->hydro.finalReservoirLevelRuntimeData; + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - initializeGeneralData(RuntimeData, parameters, year); + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - BOOST_CHECK_EQUAL(RuntimeData.simEndDay, parameters.simulationDays.end); - BOOST_CHECK_EQUAL(RuntimeData.yearIndex, year); + // check when all is good + BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } -BOOST_AUTO_TEST_CASE(Testing_initializePerAreaData_function_for_area_2) +BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManagement) { - FinalReservoirLevelRuntimeData& finLevData = area_2->hydro.finalReservoirLevelRuntimeData; - auto& initialReservoirLevel = finLevData.initialReservoirLevel; - auto& finalReservoirLevel = finLevData.finalReservoirLevel; - auto& deltaReservoirLevel = finLevData.deltaReservoirLevel; - - initialReservoirLevel = 0.; - finalReservoirLevel = 0.; - deltaReservoirLevel = 0.; - finLevData.yearIndex = 0; - + auto& parameters = study->parameters; + auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + hydro.reservoirManagement = false; + year = 1; - auto& InitialHydroLevelsRef = scenarioInitialHydroLevels[1][0]; - auto& FinalHydroLevelsRef = scenarioFinalHydroLevels[1][0]; + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - initializePerAreaData( - finLevData, scenarioInitialHydroLevels, scenarioFinalHydroLevels, *area_2); + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - BOOST_CHECK_EQUAL(initialReservoirLevel, InitialHydroLevelsRef); - BOOST_CHECK_EQUAL(finalReservoirLevel, FinalHydroLevelsRef); - BOOST_CHECK_EQUAL(deltaReservoirLevel, (InitialHydroLevelsRef - FinalHydroLevelsRef)); + // check when reservoirManagement = false + BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } -BOOST_AUTO_TEST_CASE(Testing_initializePreCheckData_function_for_area_2) +BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) { - FinalReservoirLevelRuntimeData& finLevData = area_2->hydro.finalReservoirLevelRuntimeData; - - auto& initReservoirLvlMonth = finLevData.initReservoirLvlMonth; - auto& reservoirCapacity = finLevData.reservoirCapacity; - - auto& HydroinitializeReservoirLevelDate = area_2->hydro.initializeReservoirLevelDate; - auto& HydroreservoirCapacity = area_2->hydro.reservoirCapacity; + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + hydro.useWaterValue = true; + year = 1; - HydroinitializeReservoirLevelDate = 0; - HydroreservoirCapacity = 250.3; + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - initializePreCheckData(finLevData, *area_2); + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - BOOST_CHECK_EQUAL(initReservoirLvlMonth, HydroinitializeReservoirLevelDate); - BOOST_CHECK_EQUAL(reservoirCapacity, HydroreservoirCapacity); + // check when useWaterValue = true + BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } -BOOST_AUTO_TEST_CASE(Testing_ruleCurveForSimEndReal_function_for_area_1) +BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) { - FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; - auto& reservoirLevel = area_1->hydro.reservoirLevel; - - auto& lowLevelLastDay = finLevData.lowLevelLastDay; - auto& highLevelLastDay = finLevData.highLevelLastDay; - - auto& HydroreservoirLevelMinimum = reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - auto& HydroreservoirLevelMaximum = reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + scenarioInitialHydroLevels[1][1] = std::numeric_limits::quiet_NaN(); + auto& hydro = area_1->hydro; + year = 1; - HydroreservoirLevelMinimum = 5.7; - HydroreservoirLevelMaximum = 13.5; + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - ruleCurveForSimEndReal(finLevData, *area_1); + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - BOOST_CHECK_EQUAL(HydroreservoirLevelMinimum, lowLevelLastDay); - BOOST_CHECK_EQUAL(HydroreservoirLevelMaximum, highLevelLastDay); + // check when finalReservoirLevel = nan + BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } -BOOST_AUTO_TEST_CASE(calculateTotalInflows_function_for_area_1) +BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) { - FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 0; - auto& inflowsmatrix = area_1->hydro.series->storage; - auto& srcinflows = inflowsmatrix[0]; + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - double total_inflow_expected = DAYS_PER_YEAR * 200; - double total_inflow_calculated = finLevData.calculateTotalInflows(srcinflows); + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.isActive(); + finLevInfModify.updateInflows(); - BOOST_CHECK_EQUAL(total_inflow_expected, total_inflow_calculated); + double expectedEndLevel = 3.4; + double expectedDeltaLevel = -1.1; + bool calculatedIncludeFinResLev = finLevInfModify.includeFinalReservoirLevel.at(0); + double calculatedEndLevel = finLevInfModify.endLevel.at(0); + double calculatedDeltaLevel = finLevInfModify.deltaLevel.at(0); + + BOOST_CHECK_EQUAL(calculatedIncludeFinResLev, true); + BOOST_CHECK_EQUAL(calculatedEndLevel, expectedEndLevel); + BOOST_CHECK_EQUAL(calculatedDeltaLevel, expectedDeltaLevel); } -BOOST_AUTO_TEST_CASE(preCheckStartAndEndSim_function_for_area_1) +BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) { - FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 0; - const AreaName& areaName = "TestName"; + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevData.simEndDay = DAYS_PER_YEAR; - finLevData.initReservoirLvlMonth = 0; + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.isActive(); + finLevInfModify.updateInflows(); - bool error_calculated = finLevData.preCheckStartAndEndSim(areaName); - BOOST_CHECK_EQUAL(true, error_calculated); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), true); +} - finLevData.simEndDay = DAYS_PER_YEAR - 1; +BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitResLevel) +{ + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 0; + // initialize reservoir level != January + hydro.initializeReservoirLevelDate = 3; - error_calculated = finLevData.preCheckStartAndEndSim(areaName); - BOOST_CHECK_EQUAL(false, error_calculated); + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevData.simEndDay = DAYS_PER_YEAR; - finLevData.initReservoirLvlMonth = 3; + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.isActive(); + finLevInfModify.updateInflows(); - error_calculated = finLevData.preCheckStartAndEndSim(areaName); - BOOST_CHECK_EQUAL(false, error_calculated); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } -BOOST_AUTO_TEST_CASE(preCheckYearlyInflow_function_for_area_1) +BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) { - FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; - - const AreaName& areaName = "TestName"; - double totalYearInflows = 100; - - finLevData.deltaReservoirLevel = -0.1; - finLevData.reservoirCapacity = 1500; + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 0; + // simulation End Day != 365 + parameters.simulationDays.end = 300; - bool error_calculated = finLevData.preCheckYearlyInflow(totalYearInflows, areaName); - BOOST_CHECK_EQUAL(false, error_calculated); + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevData.deltaReservoirLevel = -0.05; + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.isActive(); + finLevInfModify.updateInflows(); - error_calculated = finLevData.preCheckYearlyInflow(totalYearInflows, areaName); - BOOST_CHECK_EQUAL(true, error_calculated); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } -BOOST_AUTO_TEST_CASE(preCheckRuleCurves_function_for_area_1) +BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) { - FinalReservoirLevelRuntimeData& finLevData = area_1->hydro.finalReservoirLevelRuntimeData; - - const AreaName& areaName = "TestName"; - - finLevData.finalReservoirLevel = 88; - finLevData.lowLevelLastDay = 50; - finLevData.highLevelLastDay = 99; + auto& parameters = study->parameters; + auto& year = parameters.nbYears; + Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; + Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 0; + // Lat Day Rule Curve = [2.4 - 6.5] + scenarioFinalHydroLevels[0][0] = 6.6; - bool error_calculated = finLevData.preCheckRuleCurves(areaName); - BOOST_CHECK_EQUAL(true, error_calculated); + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevData.highLevelLastDay = 66; + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.isActive(); + finLevInfModify.updateInflows(); - error_calculated = finLevData.preCheckRuleCurves(areaName); - BOOST_CHECK_EQUAL(false, error_calculated); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } -BOOST_AUTO_TEST_CASE( - Testing_FinalReservoirLevel_function_preChecksPasses_local_variable_equals_true) +BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) { - // Defining necessary references for areas run time data - FinalReservoirLevelRuntimeData& finLevDataArea1 = area_1->hydro.finalReservoirLevelRuntimeData; - FinalReservoirLevelRuntimeData& finLevDataArea2 = area_2->hydro.finalReservoirLevelRuntimeData; - - Parameters& parameters = study->parameters; - AreaList& areas = study->areas; - + auto& parameters = study->parameters; + auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; + auto& hydro = area_1->hydro; + year = 0; + hydro.reservoirCapacity = 185000; + scenarioInitialHydroLevels[0][0] = 10; + scenarioFinalHydroLevels[0][0] = 50; - FinalReservoirLevel(scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, areas); + // inflows = 200 MWh/day = 73 000 MWh/year + // res capacity = 185 000 -> 40% of reservoir is 74 000. So we are missing 1k. - BOOST_CHECK(finLevDataArea1.includeFinalReservoirLevel.at(0)); - BOOST_CHECK(finLevDataArea1.includeFinalReservoirLevel.at(1)); - BOOST_CHECK(finLevDataArea2.includeFinalReservoirLevel.at(0)); - BOOST_CHECK(finLevDataArea2.includeFinalReservoirLevel.at(1)); + auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - BOOST_CHECK_EQUAL(finLevDataArea1.endLevel.at(0), scenarioFinalHydroLevels[0][0]); - BOOST_CHECK_EQUAL(finLevDataArea1.endLevel.at(1), scenarioFinalHydroLevels[0][1]); - BOOST_CHECK_EQUAL(finLevDataArea2.endLevel.at(0), scenarioFinalHydroLevels[1][0]); - BOOST_CHECK_EQUAL(finLevDataArea2.endLevel.at(1), scenarioFinalHydroLevels[1][1]); + finLevInfModify.initializeData( + scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.isActive(); + finLevInfModify.updateInflows(); - BOOST_CHECK_EQUAL(finLevDataArea1.deltaLevel.at(0), - (scenarioInitialHydroLevels[0][0] - scenarioFinalHydroLevels[0][0])); - BOOST_CHECK_EQUAL(finLevDataArea1.deltaLevel.at(1), - (scenarioInitialHydroLevels[0][1] - scenarioFinalHydroLevels[0][1])); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); +} - BOOST_CHECK_EQUAL(finLevDataArea2.deltaLevel.at(0), - (scenarioInitialHydroLevels[1][0] - scenarioFinalHydroLevels[1][0])); - BOOST_CHECK_EQUAL(finLevDataArea2.deltaLevel.at(1), - (scenarioInitialHydroLevels[1][1] - scenarioFinalHydroLevels[1][1])); +BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_and_area_2) +{ + auto& hydro1 = area_1->hydro; + auto& hydro2 = area_2->hydro; + auto& modifierArea1 = hydro1.finalLevelInflowsModifier; + auto& modifierArea2 = hydro2.finalLevelInflowsModifier; + + FinalLevelInflowsModifier(hydro1, 0, "Area1"); + FinalLevelInflowsModifier(hydro2, 1, "Area2"); + + prepareFinalReservoirLevelData(*study); + + // extract data area 1 - year 1 and 2 + bool area_1_year_1_include_calculated = modifierArea1.includeFinalReservoirLevel.at(0); + bool area_1_year_2_include_calculated = modifierArea1.includeFinalReservoirLevel.at(1); + double area_1_year_1_endLev_calculated = modifierArea1.endLevel.at(0); + double area_1_year_2_endLev_calculated = modifierArea1.endLevel.at(1); + double area_1_year_1_deltaLev_calculated = modifierArea1.deltaLevel.at(0); + double area_1_year_2_deltaLev_calculated = modifierArea1.deltaLevel.at(1); + double area_1_year_1_deltaLev_expected = 2.3 - 3.4; + double area_1_year_2_deltaLev_expected = 4.2 - 5.1; + // check data area 1 - year 1 and 2 + BOOST_CHECK_EQUAL(area_1_year_1_include_calculated, true); + BOOST_CHECK_EQUAL(area_1_year_2_include_calculated, true); + BOOST_CHECK_EQUAL(area_1_year_1_endLev_calculated, 3.4); + BOOST_CHECK_EQUAL(area_1_year_2_endLev_calculated, 5.1); + BOOST_CHECK_EQUAL(area_1_year_1_deltaLev_calculated, area_1_year_1_deltaLev_expected); + BOOST_CHECK_EQUAL(area_1_year_2_deltaLev_calculated, area_1_year_2_deltaLev_expected); + + // extract data area 2 - year 1 and 2 + bool area_2_year_1_include_calculated = modifierArea2.includeFinalReservoirLevel.at(0); + bool area_2_year_2_include_calculated = modifierArea2.includeFinalReservoirLevel.at(1); + double area_2_year_1_endLev_calculated = modifierArea2.endLevel.at(0); + double area_2_year_2_endLev_calculated = modifierArea2.endLevel.at(1); + double area_2_year_1_deltaLev_calculated = modifierArea2.deltaLevel.at(0); + double area_2_year_2_deltaLev_calculated = modifierArea2.deltaLevel.at(1); + double area_2_year_1_deltaLev_expected = 1.5 - 3.5; + double area_2_year_2_deltaLev_expected = 2.4 - 4.3; + // check data area 2 - year 1 and 2 + BOOST_CHECK_EQUAL(area_2_year_1_include_calculated, true); + BOOST_CHECK_EQUAL(area_2_year_2_include_calculated, true); + BOOST_CHECK_EQUAL(area_2_year_1_endLev_calculated, 3.5); + BOOST_CHECK_EQUAL(area_2_year_2_endLev_calculated, 4.3); + BOOST_CHECK_EQUAL(area_2_year_1_deltaLev_calculated, area_2_year_1_deltaLev_expected); + BOOST_CHECK_EQUAL(area_2_year_2_deltaLev_calculated, area_2_year_2_deltaLev_expected); } -BOOST_AUTO_TEST_SUITE_END()*/ \ No newline at end of file +BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file From 38be3909f4f949e8d58910846de95fcc31bf7fb2 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Sun, 6 Aug 2023 03:04:30 +0200 Subject: [PATCH 442/490] refactor test files - fix fails? --- .../test-sc-builder-file-read-line.cpp | 90 ++++++++++--------- .../src/solver/simulation/CMakeLists.txt | 7 +- 2 files changed, 51 insertions(+), 46 deletions(-) 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 fb6ec392d9..f5f66127ec 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 @@ -350,48 +350,6 @@ BOOST_AUTO_TEST_CASE(on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__leve BOOST_CHECK_EQUAL(study->scenarioInitialHydroLevels[area_3->index][yearNumber.to()], 0.); } -// ====================== -// Tests on Links NTC -// ====================== -BOOST_AUTO_TEST_CASE(on_link_area1_area2_and_on_year_0__ntc_TS_number_10_is_chosen__reading_OK) -{ - AreaName yearNumber = "0"; - String tsNumber = "10"; - AreaName::Vector splitKey = {"ntc", "area 1", "area 2", yearNumber}; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber, false)); - - 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_AUTO_TEST_CASE(on_link_area1_area3_and_on_year_15__ntc_TS_number_7_is_chosen__reading_OK) -{ - AreaName yearNumber = "15"; - String tsNumber = "7"; - AreaName::Vector splitKey = { "ntc", "area 1", "area 3", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber, false)); - - 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_AUTO_TEST_CASE(on_link_area2_area3_and_on_year_19__ntc_TS_number_6_is_chosen__reading_OK) -{ - AreaName yearNumber = "19"; - String tsNumber = "6"; - AreaName::Vector splitKey = { "ntc", "area 2", "area 3", yearNumber }; - BOOST_CHECK(my_rule.readLine(splitKey, tsNumber, false)); - - 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); -} - // ======================== // Tests on Hydro final levels // ======================== @@ -410,7 +368,8 @@ BOOST_AUTO_TEST_CASE(on_area1_and_on_year_8__hydro_level_0_342_is_chosen__readin level.to()); } -BOOST_AUTO_TEST_CASE(on_area2_and_on_year_1__hydro_level_2_4_is_chosen_level_lowered_to_1__reading_OK) +BOOST_AUTO_TEST_CASE( + on_area2_and_on_year_1__hydro_level_2_4_is_chosen_level_lowered_to_1__reading_OK) { AreaName yearNumber = "1"; String level = "2.4"; @@ -425,7 +384,8 @@ BOOST_AUTO_TEST_CASE(on_area2_and_on_year_1__hydro_level_2_4_is_chosen_level_low 1.); } -BOOST_AUTO_TEST_CASE(on_area3_and_on_year_3__hydro_level_neg_5_2_is_chosen__level_raised_to_0__reading_OK) +BOOST_AUTO_TEST_CASE( + on_area3_and_on_year_3__hydro_level_neg_5_2_is_chosen__level_raised_to_0__reading_OK) { AreaName yearNumber = "3"; String level = "-5.2"; @@ -440,6 +400,48 @@ BOOST_AUTO_TEST_CASE(on_area3_and_on_year_3__hydro_level_neg_5_2_is_chosen__leve 0.); } +// ====================== +// Tests on Links NTC +// ====================== +BOOST_AUTO_TEST_CASE(on_link_area1_area2_and_on_year_0__ntc_TS_number_10_is_chosen__reading_OK) +{ + AreaName yearNumber = "0"; + String tsNumber = "10"; + AreaName::Vector splitKey = {"ntc", "area 1", "area 2", yearNumber}; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber, false)); + + 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_AUTO_TEST_CASE(on_link_area1_area3_and_on_year_15__ntc_TS_number_7_is_chosen__reading_OK) +{ + AreaName yearNumber = "15"; + String tsNumber = "7"; + AreaName::Vector splitKey = { "ntc", "area 1", "area 3", yearNumber }; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber, false)); + + 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_AUTO_TEST_CASE(on_link_area2_area3_and_on_year_19__ntc_TS_number_6_is_chosen__reading_OK) +{ + AreaName yearNumber = "19"; + String tsNumber = "6"; + AreaName::Vector splitKey = { "ntc", "area 2", "area 3", yearNumber }; + BOOST_CHECK(my_rule.readLine(splitKey, tsNumber, false)); + + 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); +} + // ======================== // Tests on Binding Constraints // ======================== diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index 7506a8550e..e46b4de08b 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -91,8 +91,6 @@ set_property(TEST time_series PROPERTY LABELS unit) set(SRC_HYDRO_FINAL_LEVEL ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.h ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.cpp - ${src_solver_simulation}/hydro-final-reservoir-level-functions.h - ${src_solver_simulation}/hydro-final-reservoir-level-functions.cpp ) add_executable(test-hydro_final @@ -111,6 +109,11 @@ target_link_libraries(test-hydro_final libantares-solver-simulation ) +# 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) From 050dcaa0e1234604a8a80f318cab70bea5ddf09f Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 14:19:51 +0200 Subject: [PATCH 443/490] Hydro final lvl (CR 25) - try fixes : --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 18 +++-------- .../hydro-final-reservoir-level-functions.cpp | 32 ++++++++++--------- 2 files changed, 22 insertions(+), 28 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index fb7436718e..fa7cd6f199 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -155,28 +155,20 @@ bool FinalLevelInflowsModifier::isActive() bool FinalLevelInflowsModifier::makeChecks() { - bool preChecksPasses = true; - // pre-check 0 -> simulation must end on day 365 and reservoir level must be // initiated in January - if (!preCheckStartAndEndSim()) - preChecksPasses = false; + bool checksOk = preCheckStartAndEndSim(); // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ // yearly_inflows - if (double totalInflows = calculateTotalInflows(); !preCheckYearlyInflow(totalInflows)) - preChecksPasses = false; + double totalInflows = calculateTotalInflows(); + checksOk = preCheckYearlyInflow(totalInflows) && checksOk; // pre-check 2 -> final reservoir level set by the user is within the // rule curves for the final day - if (!preCheckRuleCurves()) - preChecksPasses = false; + checksOk = preCheckRuleCurves() && checksOk; - if (!preChecksPasses) - { - logs.fatal() << "At least one year has failed final reservoir level pre-checks."; - } - return preChecksPasses; + return checksOk; } } // namespace Data diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 8db5b42d01..78d550244b 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -33,23 +33,25 @@ namespace Antares::Solver void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) { - study.areas.each( - [&study, &year](Data::Area& area) - { - auto& finalInflows = area.hydro.finalLevelInflowsModifier; - auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; - auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; - auto& parameters = study.parameters; + study.areas.each([&study, &year](Data::Area& area) + { + auto& finalInflows = area.hydro.finalLevelInflowsModifier; + auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; + auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; + auto& parameters = study.parameters; + + finalInflows.initializeData(scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - finalInflows.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + if (!finalInflows.isActive()) + return; - if (finalInflows.isActive()) - if (finalInflows.makeChecks()) - finalInflows.updateInflows(); - else - AntaresSolverEmergencyShutdown(); - }); + if (!finalInflows.makeChecks()) + { + AntaresSolverEmergencyShutdown(); + } + + finalInflows.updateInflows(); + }); } void prepareFinalReservoirLevelData(Data::Study& study) From e7e7ae3f8140474fce61afe33f42c65892d98982 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 14:59:04 +0200 Subject: [PATCH 444/490] Hydro final lvl (CR 25) - try fixes : move a function call --- src/solver/simulation/apply-scenario.cpp | 3 --- src/solver/simulation/solver.hxx | 4 ++++ 2 files changed, 4 insertions(+), 3 deletions(-) diff --git a/src/solver/simulation/apply-scenario.cpp b/src/solver/simulation/apply-scenario.cpp index 372ed15cf8..0b544bb1cd 100644 --- a/src/solver/simulation/apply-scenario.cpp +++ b/src/solver/simulation/apply-scenario.cpp @@ -27,7 +27,6 @@ #include "apply-scenario.h" #include -#include "hydro-final-reservoir-level-functions.h" namespace Antares::Solver { @@ -56,8 +55,6 @@ void ApplyCustomScenario(Data::Study& study) study.scenarioRulesDestroy(); logs.info(); - - prepareFinalReservoirLevelData(study); } } // namespace Antares::Solver diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index 741be23b4d..87f771ff9e 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -45,6 +45,7 @@ #include #include #include "BindingConstraintsTimeSeriesNumbersWriter.h" +#include "hydro-final-reservoir-level-functions.h" namespace Antares::Solver::Simulation { @@ -344,7 +345,10 @@ void ISimulation::run() } if (parameters.useCustomScenario) + { ApplyCustomScenario(study); + prepareFinalReservoirLevelData(study); + } // Launching the simulation for all years logs.info() << "MC-Years : [" << (study.runtime->rangeLimits.year[Data::rangeBegin] + 1) From 45f32461cb5115cc1bd36f6673b61c454cf47709 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 16:19:41 +0200 Subject: [PATCH 445/490] Hydro final lvl (CR 25) - try fixes : only simplify comments --- .../study/parts/hydro/finallevelinflowsmodifyer.cpp | 7 +++---- 1 file changed, 3 insertions(+), 4 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index fa7cd6f199..d7805981b8 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -155,16 +155,15 @@ bool FinalLevelInflowsModifier::isActive() bool FinalLevelInflowsModifier::makeChecks() { - // pre-check 0 -> simulation must end on day 365 and reservoir level must be + // Simulation must end on day 365 and reservoir level must be // initiated in January bool checksOk = preCheckStartAndEndSim(); - // pre-check 1 -> reservoir_levelDay_365 – reservoir_levelDay_1 ≤ - // yearly_inflows + // Reservoir_levelDay_365 – reservoir_levelDay_1 ≤ yearly_inflows double totalInflows = calculateTotalInflows(); checksOk = preCheckYearlyInflow(totalInflows) && checksOk; - // pre-check 2 -> final reservoir level set by the user is within the + // Final reservoir level set by the user is within the // rule curves for the final day checksOk = preCheckRuleCurves() && checksOk; From 5a8073b8dbbd982164a2a6470f54b3bfcf538de4 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 16:32:35 +0200 Subject: [PATCH 446/490] Hydro final lvl (CR 25) - try fixes : remove variables not needed --- .../test-hydro-final-reservoir-level-functions.cpp | 13 +++---------- 1 file changed, 3 insertions(+), 10 deletions(-) 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 index d1617561f0..f28aa56d14 100644 --- 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 @@ -58,16 +58,9 @@ struct Fixture area_1->hydro.useWaterValue = false; area_2->hydro.useWaterValue = false; - // For extracting how many areas are in area map - AreaList& areas = study->areas; - Area::Map& areasMap = areas.areas; - // Level date must be 0, see preCheckStartAndEndSim function - auto& initializeReservoirLevelDateArea1 = area_1->hydro.initializeReservoirLevelDate; - auto& initializeReservoirLevelDateArea2 = area_2->hydro.initializeReservoirLevelDate; - - initializeReservoirLevelDateArea1 = 0; - initializeReservoirLevelDateArea2 = 0; + area_1->hydro.initializeReservoirLevelDate = 0; + area_2->hydro.initializeReservoirLevelDate = 0; // Initialize reservoir capacity auto& reservoirCapacityArea1 = area_1->hydro.reservoirCapacity; @@ -105,7 +98,7 @@ struct Fixture // Initializing dimension of matrices uint width = nbYears; - uint height = areasMap.size(); + uint height = study->areas.size(); // Setting matrices dimension Scenario Builder Initial and Finals levels matrices scenarioInitialHydroLevels.resize(width, height); From 5ad6cdc18e6f27b00885e9e388da9bd8602df205 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 16:43:46 +0200 Subject: [PATCH 447/490] Hydro final lvl (CR 25) - try fixes : simplifying and clarifying tests --- .../test-hydro-final-reservoir-level-functions.cpp | 11 ++++------- 1 file changed, 4 insertions(+), 7 deletions(-) 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 index f28aa56d14..e3b3d99180 100644 --- 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 @@ -63,18 +63,15 @@ struct Fixture area_2->hydro.initializeReservoirLevelDate = 0; // Initialize reservoir capacity - auto& reservoirCapacityArea1 = area_1->hydro.reservoirCapacity; - auto& reservoirCapacityArea2 = area_2->hydro.reservoirCapacity; - - reservoirCapacityArea1 = 340.; - reservoirCapacityArea2 = 300.; + area_1->hydro.reservoirCapacity = 340.; + area_2->hydro.reservoirCapacity = 300.; // Initialize reservoir max and min levels, but just for the last day in year auto& reservoirLevelArea1 = area_1->hydro.reservoirLevel; auto& reservoirLevelArea2 = area_2->hydro.reservoirLevel; - reservoirLevelArea1.reset(3, DAYS_PER_YEAR, true); - reservoirLevelArea2.reset(3, DAYS_PER_YEAR, true); + reservoirLevelArea1.resize(3, DAYS_PER_YEAR, true); + reservoirLevelArea2.resize(3, DAYS_PER_YEAR, true); auto& reservoirLevelArea1Min = reservoirLevelArea1[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; From 4c376ab2f8794deb6b80967518a0b239b97155a7 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 17:03:51 +0200 Subject: [PATCH 448/490] Hydro final lvl (CR 25) - try fixes : simplifying and clarifying --- ...-hydro-final-reservoir-level-functions.cpp | 40 ++++++------------- 1 file changed, 12 insertions(+), 28 deletions(-) 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 index e3b3d99180..0dadf8094f 100644 --- 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 @@ -41,10 +41,8 @@ struct Fixture // endDay must be 365, see preCheckStartAndEndSim function Parameters& parameters = study->parameters; - uint& endDay = parameters.simulationDays.end; - uint& nbYears = parameters.nbYears; - endDay = 365; - nbYears = 2; + parameters.simulationDays.end = 365; + uint nbYears = parameters.nbYears = 2; // Creating two dummy areas and instantiating necessary values for testing area_1 = study->areaAdd("Area1"); @@ -66,40 +64,26 @@ struct Fixture area_1->hydro.reservoirCapacity = 340.; area_2->hydro.reservoirCapacity = 300.; - // Initialize reservoir max and min levels, but just for the last day in year - auto& reservoirLevelArea1 = area_1->hydro.reservoirLevel; - auto& reservoirLevelArea2 = area_2->hydro.reservoirLevel; + // 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; - reservoirLevelArea1.resize(3, DAYS_PER_YEAR, true); - reservoirLevelArea2.resize(3, DAYS_PER_YEAR, true); + 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; - auto& reservoirLevelArea1Min - = reservoirLevelArea1[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - auto& reservoirLevelArea2Min - = reservoirLevelArea2[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - - auto& reservoirLevelArea1Max - = reservoirLevelArea1[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; - auto& reservoirLevelArea2Max - = reservoirLevelArea2[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; - - reservoirLevelArea1Min = 2.4; - reservoirLevelArea1Max = 6.5; - - reservoirLevelArea2Min = 2.7; - reservoirLevelArea2Max = 6.4; // Defining necessary references for initial and final level matrices Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; // Initializing dimension of matrices - uint width = nbYears; - uint height = study->areas.size(); + uint areasCount = study->areas.size(); // Setting matrices dimension Scenario Builder Initial and Finals levels matrices - scenarioInitialHydroLevels.resize(width, height); - scenarioFinalHydroLevels.resize(width, height); + scenarioInitialHydroLevels.resize(nbYears, areasCount); + scenarioFinalHydroLevels.resize(nbYears, areasCount); // Instantiating matrices with some random values scenarioInitialHydroLevels[0][0] = 2.3; From e86860214cbf07a7560c1ef7720e86dda1623a8b Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 8 Aug 2023 18:12:11 +0200 Subject: [PATCH 449/490] Hydro final lvl (CR 25) - try fixes : simplifying ? --- ...-hydro-final-reservoir-level-functions.cpp | 39 ++++++++----------- 1 file changed, 17 insertions(+), 22 deletions(-) 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 index 0dadf8094f..8324ce520f 100644 --- 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 @@ -96,28 +96,23 @@ struct Fixture scenarioFinalHydroLevels[1][0] = 3.5; scenarioFinalHydroLevels[1][1] = 4.3; - // References for timeseriesNumbers data and instantiating timeseriesNumbers matrices - Matrix& timeseriesNumbersArea1 = area_1->hydro.series->timeseriesNumbers; - Matrix& timeseriesNumbersArea2 = area_2->hydro.series->timeseriesNumbers; - - timeseriesNumbersArea1.resize(1, nbYears); - timeseriesNumbersArea2.resize(1, nbYears); - - timeseriesNumbersArea1[0][0] = 0; - timeseriesNumbersArea1[0][1] = 1; - - timeseriesNumbersArea2[0][0] = 0; - timeseriesNumbersArea2[0][1] = 1; - - // Instantiating areas storage TS's - auto& storageArea1 = area_1->hydro.series->storage; - auto& storageArea2 = area_2->hydro.series->storage; - - storageArea1.resize(nbYears, 365); - storageArea2.resize(nbYears, 365); - - InstantiateAreaHydroStorage(storageArea1, 200., nbYears); - InstantiateAreaHydroStorage(storageArea2, 300., nbYears); + // Area 1 : inflows time series matrices + // ... time series numbers for each year + area_1->hydro.series->timeseriesNumbers.resize(1, nbYears); + area_1->hydro.series->timeseriesNumbers[0][0] = 0; + area_1->hydro.series->timeseriesNumbers[0][1] = 1; + + area_1->hydro.series->storage.resize(nbYears, 365); + InstantiateAreaHydroStorage(area_1->hydro.series->storage, 200., nbYears); + + // Area 2 : inflows time series matrices + // ... time series numbers for each year + area_2->hydro.series->timeseriesNumbers.resize(1, nbYears); + area_2->hydro.series->timeseriesNumbers[0][0] = 0; + area_2->hydro.series->timeseriesNumbers[0][1] = 1; + + area_2->hydro.series->storage.resize(nbYears, 365); + InstantiateAreaHydroStorage(area_2->hydro.series->storage, 300., nbYears); } ~Fixture() = default; From f1af30b61bc99459f414ca7dac2c9076486655ce Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Wed, 9 Aug 2023 10:51:10 +0200 Subject: [PATCH 450/490] Hydro final lvl (CR 25) - try fixes : clarify inflow time series --- ...-hydro-final-reservoir-level-functions.cpp | 43 +++++++++---------- 1 file changed, 21 insertions(+), 22 deletions(-) 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 index 8324ce520f..2e499df0ff 100644 --- 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 @@ -12,19 +12,14 @@ using namespace Antares::Solver; using namespace Antares::Data; -void InstantiateAreaHydroStorage(Matrix& storage, double seed, uint nbYears) +void fillMatrixWithValue(Matrix& storage, double value) { - for (uint i = 0; i < nbYears; i++) + uint nbTimeSeries = storage.width; + for (uint ts = 0; ts < nbTimeSeries; ts++) { for (uint days = 0; days < DAYS_PER_YEAR; days++) { - if (days == 0) - storage[i][days] = seed + 1; - - if (days == DAYS_PER_YEAR - 1) - storage[i][days] = seed + 2; - - storage[i][days] = seed; + storage[ts][days] = value; } } } @@ -96,23 +91,27 @@ struct Fixture scenarioFinalHydroLevels[1][0] = 3.5; scenarioFinalHydroLevels[1][1] = 4.3; - // Area 1 : inflows time series matrices - // ... time series numbers for each year - area_1->hydro.series->timeseriesNumbers.resize(1, nbYears); + // Inflows time series matrices : + uint nbInflowTS = 2; + // ... Area 1 : Inflows time series numbers for each year + area_1->hydro.series->timeseriesNumbers.resize(1, nbInflowTS); area_1->hydro.series->timeseriesNumbers[0][0] = 0; area_1->hydro.series->timeseriesNumbers[0][1] = 1; - - area_1->hydro.series->storage.resize(nbYears, 365); - InstantiateAreaHydroStorage(area_1->hydro.series->storage, 200., nbYears); - - // Area 2 : inflows time series matrices - // ... time series numbers for each year - area_2->hydro.series->timeseriesNumbers.resize(1, nbYears); + // ... Area 1 : Inflows time series + area_1->hydro.series->storage.resize(nbInflowTS, 365); + fillMatrixWithValue(area_1->hydro.series->storage, 200.); + area_1->hydro.series->storage[0][0] = 200. + 1.; //DAYS_PER_YEAR + 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.resize(1, nbInflowTS); area_2->hydro.series->timeseriesNumbers[0][0] = 0; area_2->hydro.series->timeseriesNumbers[0][1] = 1; - - area_2->hydro.series->storage.resize(nbYears, 365); - InstantiateAreaHydroStorage(area_2->hydro.series->storage, 300., nbYears); + // ... Area 2 : Inflows time series + area_2->hydro.series->storage.resize(nbInflowTS, 365); + fillMatrixWithValue(area_2->hydro.series->storage, 300.); + area_1->hydro.series->storage[0][0] = 300. + 1.; //DAYS_PER_YEAR + area_1->hydro.series->storage[0][DAYS_PER_YEAR - 1] = 300. + 2.; } ~Fixture() = default; From 2ceaee497a076d3e8e275f47308a527b451f0687 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Wed, 9 Aug 2023 11:00:32 +0200 Subject: [PATCH 451/490] Hydro final lvl (CR 25) - try fixes : clarify inflow time series (part 2) --- ...-hydro-final-reservoir-level-functions.cpp | 19 ++++--------------- 1 file changed, 4 insertions(+), 15 deletions(-) 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 index 2e499df0ff..3646482571 100644 --- 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 @@ -12,17 +12,6 @@ using namespace Antares::Solver; using namespace Antares::Data; -void fillMatrixWithValue(Matrix& storage, double value) -{ - uint nbTimeSeries = storage.width; - for (uint ts = 0; ts < nbTimeSeries; ts++) - { - for (uint days = 0; days < DAYS_PER_YEAR; days++) - { - storage[ts][days] = value; - } - } -} struct Fixture { @@ -99,7 +88,7 @@ struct Fixture area_1->hydro.series->timeseriesNumbers[0][1] = 1; // ... Area 1 : Inflows time series area_1->hydro.series->storage.resize(nbInflowTS, 365); - fillMatrixWithValue(area_1->hydro.series->storage, 200.); + area_1->hydro.series->storage.fill(200.); area_1->hydro.series->storage[0][0] = 200. + 1.; //DAYS_PER_YEAR area_1->hydro.series->storage[0][DAYS_PER_YEAR - 1] = 200. + 2.; @@ -109,9 +98,9 @@ struct Fixture area_2->hydro.series->timeseriesNumbers[0][1] = 1; // ... Area 2 : Inflows time series area_2->hydro.series->storage.resize(nbInflowTS, 365); - fillMatrixWithValue(area_2->hydro.series->storage, 300.); - area_1->hydro.series->storage[0][0] = 300. + 1.; //DAYS_PER_YEAR - area_1->hydro.series->storage[0][DAYS_PER_YEAR - 1] = 300. + 2.; + area_2->hydro.series->storage.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; From aeea5420081b4025396e644f44e50350f0b1ebe5 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Wed, 9 Aug 2023 13:37:27 +0200 Subject: [PATCH 452/490] Hydro final lvl (CR 25) - try improve : remove unnecessary comments --- ...est-hydro-final-reservoir-level-functions.cpp | 16 +++++----------- 1 file changed, 5 insertions(+), 11 deletions(-) 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 index 3646482571..6f1a4230af 100644 --- 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 @@ -21,22 +21,18 @@ struct Fixture Fixture& operator=(const Fixture&& f) = delete; Fixture() { - // Parameters data // endDay must be 365, see preCheckStartAndEndSim function Parameters& parameters = study->parameters; parameters.simulationDays.end = 365; uint nbYears = parameters.nbYears = 2; - // Creating two dummy areas and instantiating necessary values for testing area_1 = study->areaAdd("Area1"); area_2 = study->areaAdd("Area2"); - // Enable reservoir management area_1->hydro.reservoirManagement = true; area_2->hydro.reservoirManagement = true; - // Disable water values area_1->hydro.useWaterValue = false; area_2->hydro.useWaterValue = false; @@ -44,7 +40,6 @@ struct Fixture area_1->hydro.initializeReservoirLevelDate = 0; area_2->hydro.initializeReservoirLevelDate = 0; - // Initialize reservoir capacity area_1->hydro.reservoirCapacity = 340.; area_2->hydro.reservoirCapacity = 300.; @@ -58,18 +53,16 @@ struct Fixture area_2->hydro.reservoirLevel[PartHydro::maximum][DAYS_PER_YEAR - 1] = 6.4; - // Defining necessary references for initial and final level matrices + // Scenario builder for initial and final reservoir levels + // ------------------------------------------------------- Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - // Initializing dimension of matrices uint areasCount = study->areas.size(); - // Setting matrices dimension Scenario Builder Initial and Finals levels matrices scenarioInitialHydroLevels.resize(nbYears, areasCount); scenarioFinalHydroLevels.resize(nbYears, areasCount); - // Instantiating matrices with some random values scenarioInitialHydroLevels[0][0] = 2.3; scenarioInitialHydroLevels[0][1] = 4.2; scenarioInitialHydroLevels[1][0] = 1.5; @@ -80,7 +73,8 @@ struct Fixture scenarioFinalHydroLevels[1][0] = 3.5; scenarioFinalHydroLevels[1][1] = 4.3; - // Inflows time series matrices : + // Inflows time series matrices + // ----------------------------- uint nbInflowTS = 2; // ... Area 1 : Inflows time series numbers for each year area_1->hydro.series->timeseriesNumbers.resize(1, nbInflowTS); @@ -89,7 +83,7 @@ struct Fixture // ... Area 1 : Inflows time series area_1->hydro.series->storage.resize(nbInflowTS, 365); area_1->hydro.series->storage.fill(200.); - area_1->hydro.series->storage[0][0] = 200. + 1.; //DAYS_PER_YEAR + 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 From 02265571587371b0b42f0df953d9704f59caae9d Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Wed, 9 Aug 2023 13:57:54 +0200 Subject: [PATCH 453/490] Hydro final lvl (CR 25) - try improvement : better initialization + better call to initializeData(...) in a test --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 6 ++++-- .../antares/study/parts/hydro/finallevelinflowsmodifyer.h | 4 ++-- .../test-hydro-final-reservoir-level-functions.cpp | 2 +- 3 files changed, 7 insertions(+), 5 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index d7805981b8..4cfa45f1dd 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -149,8 +149,10 @@ void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioIni bool FinalLevelInflowsModifier::isActive() { - return hydro.reservoirManagement && !hydro.useWaterValue && !isnan(finalReservoirLevel) - && !isnan(initialReservoirLevel); + return hydro.reservoirManagement && + !hydro.useWaterValue && + finalReservoirLevel >= 0. && + initialReservoirLevel >= 0.; } bool FinalLevelInflowsModifier::makeChecks() diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index f38dd234b1..6c28f6d181 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -56,8 +56,8 @@ class FinalLevelInflowsModifier // data per area // data overwritten after each MC year - double initialReservoirLevel; - double finalReservoirLevel; + double initialReservoirLevel = -1.; + double finalReservoirLevel = -1.; double deltaReservoirLevel; double reservoirCapacity; double lowLevelLastDay; 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 index 6f1a4230af..069c404b50 100644 --- 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 @@ -115,7 +115,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_pass) auto& hydro = area_1->hydro; year = 1; - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); + auto finLevInfModify = FinalLevelInflowsModifier(hydro, area_1->index, area_1->name); finLevInfModify.initializeData( scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); From 83a9ede2c28b7848917b93a005bb4bc067975f76 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Wed, 9 Aug 2023 15:05:31 +0200 Subject: [PATCH 454/490] Hydro final lvl (CR 25) - try improvement : mainly make data members private (instead of public) --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.h | 2 +- src/solver/hydro/management/management.cpp | 6 ++++-- .../test-hydro-final-reservoir-level-functions.cpp | 5 ++--- 3 files changed, 7 insertions(+), 6 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 6c28f6d181..bc3a21a490 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -64,10 +64,10 @@ class FinalLevelInflowsModifier double highLevelLastDay; int initReservoirLvlMonth; -public: const PartHydro& hydro; const unsigned int& areaIndex; const AreaName& areaName; +public: // vectors containing data necessary for final reservoir level calculation // for one area and all MC years // vector indexes correspond to the MC years diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 5bee274935..b53dde809a 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -353,16 +353,18 @@ bool HydroManagement::checkMinGeneration(uint numSpace) void HydroManagement::changeInflowsToAccommodateFinalLevels(uint numSpace, uint year) { - study.areas.each([this, &numSpace, &year](Data::Area& area) { + study.areas.each([this, &numSpace, &year](Data::Area& area) + { auto& data = pAreas[numSpace][area.index]; + if (area.hydro.finalLevelInflowsModifier.deltaLevel.empty()) return; if (!area.hydro.finalLevelInflowsModifier.includeFinalReservoirLevel[year]) return; + // Must be done before prepareMonthlyTargetGenerations double delta = area.hydro.finalLevelInflowsModifier.deltaLevel[year]; - // must be done before prepareMonthlyTargetGenerations if (delta > 0) data.inflows[0] += delta; else if (delta < 0) 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 index 069c404b50..494f8330d5 100644 --- 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 @@ -106,21 +106,20 @@ struct Fixture BOOST_FIXTURE_TEST_SUITE(s, Fixture) -BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_pass) +BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) { auto& parameters = study->parameters; auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 1; + year = 0; auto finLevInfModify = FinalLevelInflowsModifier(hydro, area_1->index, area_1->name); finLevInfModify.initializeData( scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - // check when all is good BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } From 48713f50dd99b3af9c39d5b70a04d87eb917f612 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Wed, 9 Aug 2023 16:46:28 +0200 Subject: [PATCH 455/490] Hydro final lvl (CR 25) - try improvement : try to initialize data with constructor instead of setters + remove useless calls in tests --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 32 +++++---- .../parts/hydro/finallevelinflowsmodifyer.h | 12 ++-- .../hydro-final-reservoir-level-functions.cpp | 5 +- ...-hydro-final-reservoir-level-functions.cpp | 72 +++++++++++-------- 4 files changed, 68 insertions(+), 53 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 4cfa45f1dd..913aec1739 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -35,7 +35,11 @@ namespace Data FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, const unsigned int& areaIndex, const AreaName& areaName) : - hydro(hydro), areaIndex(areaIndex), areaName(areaName) + hydro(hydro), + areaIndex(areaIndex), + areaName(areaName), + initReservoirLvlMonth(hydro.initializeReservoirLevelDate), // month [0-11] + reservoirCapacity(hydro.reservoirCapacity) { } @@ -46,9 +50,13 @@ void FinalLevelInflowsModifier::fillEmpty() deltaLevel.push_back(0.); } -void FinalLevelInflowsModifier::initializeGeneralData(const Data::Parameters& parameters, uint year) +void FinalLevelInflowsModifier::setLastSiumlationDay(uint day) +{ + simEndDay = day; +} + +void FinalLevelInflowsModifier::setCurrentYear(uint year) { - simEndDay = parameters.simulationDays.end; yearIndex = year; } @@ -61,12 +69,6 @@ void FinalLevelInflowsModifier::initializePerAreaData( deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; } -void FinalLevelInflowsModifier::initializePreCheckData() -{ - initReservoirLvlMonth = hydro.initializeReservoirLevelDate; // month [0-11] - reservoirCapacity = hydro.reservoirCapacity; -} - void FinalLevelInflowsModifier::ruleCurveForSimEndReal() { lowLevelLastDay = hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; @@ -135,15 +137,15 @@ bool FinalLevelInflowsModifier::preCheckRuleCurves() const return true; } -void FinalLevelInflowsModifier::initializeData(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const Data::Parameters& parameters, - uint year) +void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const uint lastSimulationDay, + uint year) { fillEmpty(); - initializeGeneralData(parameters, year); + setLastSiumlationDay(lastSimulationDay); + setCurrentYear(year); initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); - initializePreCheckData(); ruleCurveForSimEndReal(); } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index bc3a21a490..046e8c4833 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -88,19 +88,19 @@ class FinalLevelInflowsModifier bool preCheckRuleCurves() const; - void initializeGeneralData(const Data::Parameters& parameters, uint year); + void setLastSiumlationDay(uint day); + void setCurrentYear(uint year); void initializePerAreaData(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels); - void initializePreCheckData(); void ruleCurveForSimEndReal(); public: - void initializeData(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const Data::Parameters& parameters, - uint year); + void initialize(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const uint lastSimulationDay, + uint year); bool isActive(); void updateInflows(); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 78d550244b..87412f1959 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -40,7 +40,10 @@ void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; auto& parameters = study.parameters; - finalInflows.initializeData(scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finalInflows.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); if (!finalInflows.isActive()) return; 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 index 494f8330d5..a436e97790 100644 --- 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 @@ -117,8 +117,10 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) auto finLevInfModify = FinalLevelInflowsModifier(hydro, area_1->index, area_1->name); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } @@ -135,8 +137,10 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManageme auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); // check when reservoirManagement = false BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -154,8 +158,10 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); // check when useWaterValue = true BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -173,10 +179,12 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); - // check when finalReservoirLevel = nan + // check when finalReservoirLevel = -1 BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } @@ -191,8 +199,10 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); finLevInfModify.isActive(); finLevInfModify.updateInflows(); @@ -218,10 +228,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - finLevInfModify.isActive(); - finLevInfModify.updateInflows(); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), true); } @@ -239,10 +249,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - finLevInfModify.isActive(); - finLevInfModify.updateInflows(); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -260,10 +270,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - finLevInfModify.isActive(); - finLevInfModify.updateInflows(); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -281,10 +291,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - finLevInfModify.isActive(); - finLevInfModify.updateInflows(); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -306,10 +316,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - finLevInfModify.initializeData( - scenarioInitialHydroLevels, scenarioFinalHydroLevels, parameters, year); - finLevInfModify.isActive(); - finLevInfModify.updateInflows(); + finLevInfModify.initialize(scenarioInitialHydroLevels, + scenarioFinalHydroLevels, + parameters.simulationDays.end, + year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } From 82d046e6451fc489c77631a27265dccc0c400317 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 10:15:50 +0200 Subject: [PATCH 456/490] Hydro final lvl (CR 25) - try improvement : class FinalLevelInflowsModifier : split data member initialization in 2 parts We have 2 kinds of data members : - data members which should be initialized in the constructor but cannot be for now - the current year data member initialization which is call every year (for a given area) Until we find a way to fully use the constructor to initialize the first kind of member data, we split initialization in 2 parts --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 40 +++++++++--------- .../parts/hydro/finallevelinflowsmodifyer.h | 23 +++++------ .../hydro-final-reservoir-level-functions.cpp | 34 +++++++++------ ...-hydro-final-reservoir-level-functions.cpp | 41 ++++++++++--------- 4 files changed, 75 insertions(+), 63 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 913aec1739..7e95d701f0 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -37,9 +37,7 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, const AreaName& areaName) : hydro(hydro), areaIndex(areaIndex), - areaName(areaName), - initReservoirLvlMonth(hydro.initializeReservoirLevelDate), // month [0-11] - reservoirCapacity(hydro.reservoirCapacity) + areaName(areaName) { } @@ -60,21 +58,13 @@ void FinalLevelInflowsModifier::setCurrentYear(uint year) yearIndex = year; } -void FinalLevelInflowsModifier::initializePerAreaData( - const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels) +void FinalLevelInflowsModifier::ComputeDeltaForCurrentYear() { - initialReservoirLevel = scenarioInitialHydroLevels[areaIndex][yearIndex]; - finalReservoirLevel = scenarioFinalHydroLevels[areaIndex][yearIndex]; + initialReservoirLevel = (*scenarioInitialHydroLevels_)[areaIndex][yearIndex]; + finalReservoirLevel = (*scenarioFinalHydroLevels_)[areaIndex][yearIndex]; deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; } -void FinalLevelInflowsModifier::ruleCurveForSimEndReal() -{ - lowLevelLastDay = hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - highLevelLastDay = hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; -} - void FinalLevelInflowsModifier::updateInflows() { includeFinalReservoirLevel.at(yearIndex) = true; @@ -98,6 +88,8 @@ double FinalLevelInflowsModifier::calculateTotalInflows() const bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const { + + int initReservoirLvlMonth = hydro.initializeReservoirLevelDate; // month [0-11] if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) return true; else @@ -111,6 +103,7 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) const { + double reservoirCapacity = hydro.reservoirCapacity; if ((-deltaReservoirLevel) * reservoirCapacity > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh // (energy) @@ -126,6 +119,9 @@ bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) co bool FinalLevelInflowsModifier::preCheckRuleCurves() const { + double lowLevelLastDay = hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + double highLevelLastDay = hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) { logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName @@ -139,16 +135,22 @@ bool FinalLevelInflowsModifier::preCheckRuleCurves() const void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay, - uint year) + const uint lastSimulationDay) { - fillEmpty(); + scenarioInitialHydroLevels_ = &scenarioInitialHydroLevels; + scenarioFinalHydroLevels_ = &scenarioFinalHydroLevels; + setLastSiumlationDay(lastSimulationDay); +} + +void FinalLevelInflowsModifier::initialize(uint year) +{ + fillEmpty(); setCurrentYear(year); - initializePerAreaData(scenarioInitialHydroLevels, scenarioFinalHydroLevels); - ruleCurveForSimEndReal(); + ComputeDeltaForCurrentYear(); } + bool FinalLevelInflowsModifier::isActive() { return hydro.reservoirManagement && diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 046e8c4833..d73d0925a7 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -59,14 +59,14 @@ class FinalLevelInflowsModifier double initialReservoirLevel = -1.; double finalReservoirLevel = -1.; double deltaReservoirLevel; - double reservoirCapacity; - double lowLevelLastDay; - double highLevelLastDay; - int initReservoirLvlMonth; const PartHydro& hydro; const unsigned int& areaIndex; const AreaName& areaName; + + const Matrix* scenarioInitialHydroLevels_ = nullptr; + const Matrix* scenarioFinalHydroLevels_ = nullptr; + public: // vectors containing data necessary for final reservoir level calculation // for one area and all MC years @@ -77,8 +77,10 @@ class FinalLevelInflowsModifier private: // methods: - + void setCurrentYear(uint year); void fillEmpty(); + void ComputeDeltaForCurrentYear(); + double calculateTotalInflows() const; @@ -89,18 +91,15 @@ class FinalLevelInflowsModifier bool preCheckRuleCurves() const; void setLastSiumlationDay(uint day); - void setCurrentYear(uint year); - - void initializePerAreaData(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels); - void ruleCurveForSimEndReal(); public: void initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay, - uint year); + const uint lastSimulationDay); + + void initialize(uint year); + bool isActive(); void updateInflows(); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 87412f1959..41f39467e5 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -31,19 +31,27 @@ namespace Antares::Solver { -void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) + + void initializeFinalLevelData(Data::Study& study) + { + study.areas.each([&study](Data::Area& area) + { + auto& finalInflows = area.hydro.finalLevelInflowsModifier; + + finalInflows.initialize(study.scenarioInitialHydroLevels, + study.scenarioFinalHydroLevels, + study.parameters.simulationDays.end); + }); + } + + +void updateInflowsDueToFinalLevels(Data::Study& study, uint year) { study.areas.each([&study, &year](Data::Area& area) { auto& finalInflows = area.hydro.finalLevelInflowsModifier; - auto& scenarioInitialHydroLevels = study.scenarioInitialHydroLevels; - auto& scenarioFinalHydroLevels = study.scenarioFinalHydroLevels; - auto& parameters = study.parameters; - - finalInflows.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + + finalInflows.initialize(year); if (!finalInflows.isActive()) return; @@ -59,11 +67,13 @@ void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year) void prepareFinalReservoirLevelData(Data::Study& study) { - uint numberMCYears = study.scenarioFinalHydroLevels.height; + initializeFinalLevelData(study); + + uint nbYears = study.parameters.nbYears; - for (uint yearIndex = 0; yearIndex != numberMCYears; ++yearIndex) + for (uint year = 0; year != nbYears; ++year) { - prepareFinalReservoirLevelDataPerMcY(study, yearIndex); + updateInflowsDueToFinalLevels(study, year); } } 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 index a436e97790..5f5abd7ed1 100644 --- 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 @@ -119,8 +119,8 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } @@ -139,8 +139,8 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManageme finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); // check when reservoirManagement = false BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -160,8 +160,8 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); // check when useWaterValue = true BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -181,8 +181,8 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); // check when finalReservoirLevel = -1 BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -201,8 +201,9 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); + finLevInfModify.isActive(); finLevInfModify.updateInflows(); @@ -230,8 +231,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), true); } @@ -251,8 +252,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -272,8 +273,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -293,8 +294,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -318,8 +319,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end, - year); + parameters.simulationDays.end); + finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } From 8b85b89e8a037083761ab7aba3f113ee3c8955c0 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 10:41:41 +0200 Subject: [PATCH 457/490] Hydro final lvl (CR 25) - try improvement : remove unused data member --- .../study/parts/hydro/finallevelinflowsmodifyer.cpp | 2 -- .../study/parts/hydro/finallevelinflowsmodifyer.h | 1 - .../test-hydro-final-reservoir-level-functions.cpp | 11 ----------- 3 files changed, 14 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 7e95d701f0..b7a57f0fb6 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -44,7 +44,6 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, void FinalLevelInflowsModifier::fillEmpty() { includeFinalReservoirLevel.push_back(false); - endLevel.push_back(0.); deltaLevel.push_back(0.); } @@ -68,7 +67,6 @@ void FinalLevelInflowsModifier::ComputeDeltaForCurrentYear() void FinalLevelInflowsModifier::updateInflows() { includeFinalReservoirLevel.at(yearIndex) = true; - endLevel.at(yearIndex) = finalReservoirLevel; deltaLevel.at(yearIndex) = deltaReservoirLevel; } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index d73d0925a7..1384e2d093 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -72,7 +72,6 @@ class FinalLevelInflowsModifier // for one area and all MC years // vector indexes correspond to the MC years std::vector includeFinalReservoirLevel; - std::vector endLevel; std::vector deltaLevel; private: 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 index 5f5abd7ed1..2ab5a45615 100644 --- 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 @@ -207,14 +207,11 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) finLevInfModify.isActive(); finLevInfModify.updateInflows(); - double expectedEndLevel = 3.4; double expectedDeltaLevel = -1.1; bool calculatedIncludeFinResLev = finLevInfModify.includeFinalReservoirLevel.at(0); - double calculatedEndLevel = finLevInfModify.endLevel.at(0); double calculatedDeltaLevel = finLevInfModify.deltaLevel.at(0); BOOST_CHECK_EQUAL(calculatedIncludeFinResLev, true); - BOOST_CHECK_EQUAL(calculatedEndLevel, expectedEndLevel); BOOST_CHECK_EQUAL(calculatedDeltaLevel, expectedDeltaLevel); } @@ -340,8 +337,6 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ // extract data area 1 - year 1 and 2 bool area_1_year_1_include_calculated = modifierArea1.includeFinalReservoirLevel.at(0); bool area_1_year_2_include_calculated = modifierArea1.includeFinalReservoirLevel.at(1); - double area_1_year_1_endLev_calculated = modifierArea1.endLevel.at(0); - double area_1_year_2_endLev_calculated = modifierArea1.endLevel.at(1); double area_1_year_1_deltaLev_calculated = modifierArea1.deltaLevel.at(0); double area_1_year_2_deltaLev_calculated = modifierArea1.deltaLevel.at(1); double area_1_year_1_deltaLev_expected = 2.3 - 3.4; @@ -349,16 +344,12 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ // check data area 1 - year 1 and 2 BOOST_CHECK_EQUAL(area_1_year_1_include_calculated, true); BOOST_CHECK_EQUAL(area_1_year_2_include_calculated, true); - BOOST_CHECK_EQUAL(area_1_year_1_endLev_calculated, 3.4); - BOOST_CHECK_EQUAL(area_1_year_2_endLev_calculated, 5.1); BOOST_CHECK_EQUAL(area_1_year_1_deltaLev_calculated, area_1_year_1_deltaLev_expected); BOOST_CHECK_EQUAL(area_1_year_2_deltaLev_calculated, area_1_year_2_deltaLev_expected); // extract data area 2 - year 1 and 2 bool area_2_year_1_include_calculated = modifierArea2.includeFinalReservoirLevel.at(0); bool area_2_year_2_include_calculated = modifierArea2.includeFinalReservoirLevel.at(1); - double area_2_year_1_endLev_calculated = modifierArea2.endLevel.at(0); - double area_2_year_2_endLev_calculated = modifierArea2.endLevel.at(1); double area_2_year_1_deltaLev_calculated = modifierArea2.deltaLevel.at(0); double area_2_year_2_deltaLev_calculated = modifierArea2.deltaLevel.at(1); double area_2_year_1_deltaLev_expected = 1.5 - 3.5; @@ -366,8 +357,6 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ // check data area 2 - year 1 and 2 BOOST_CHECK_EQUAL(area_2_year_1_include_calculated, true); BOOST_CHECK_EQUAL(area_2_year_2_include_calculated, true); - BOOST_CHECK_EQUAL(area_2_year_1_endLev_calculated, 3.5); - BOOST_CHECK_EQUAL(area_2_year_2_endLev_calculated, 4.3); BOOST_CHECK_EQUAL(area_2_year_1_deltaLev_calculated, area_2_year_1_deltaLev_expected); BOOST_CHECK_EQUAL(area_2_year_2_deltaLev_calculated, area_2_year_2_deltaLev_expected); } From ffd9f373fb46aa6c178317fbe8c53178ddd7c6c4 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 11:12:56 +0200 Subject: [PATCH 458/490] Hydro final lvl (CR 25) - try improvement : remove the fillEmpty() method --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 17 +++--- .../parts/hydro/finallevelinflowsmodifyer.h | 6 +- .../hydro-final-reservoir-level-functions.cpp | 3 +- ...-hydro-final-reservoir-level-functions.cpp | 60 +++++++++---------- 4 files changed, 42 insertions(+), 44 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index b7a57f0fb6..69b5b5025c 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -41,15 +41,9 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, { } -void FinalLevelInflowsModifier::fillEmpty() -{ - includeFinalReservoirLevel.push_back(false); - deltaLevel.push_back(0.); -} - void FinalLevelInflowsModifier::setLastSiumlationDay(uint day) { - simEndDay = day; + lastSimulationDay_ = day; } void FinalLevelInflowsModifier::setCurrentYear(uint year) @@ -88,7 +82,7 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const { int initReservoirLvlMonth = hydro.initializeReservoirLevelDate; // month [0-11] - if (simEndDay == DAYS_PER_YEAR && initReservoirLvlMonth == 0) + if (lastSimulationDay_ == DAYS_PER_YEAR && initReservoirLvlMonth == 0) return true; else { @@ -133,8 +127,12 @@ bool FinalLevelInflowsModifier::preCheckRuleCurves() const void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay) + const uint lastSimulationDay, + const uint nbYears) { + includeFinalReservoirLevel = std::move(std::vector(nbYears, false)); + deltaLevel = std::move(std::vector(nbYears, 0.)); + scenarioInitialHydroLevels_ = &scenarioInitialHydroLevels; scenarioFinalHydroLevels_ = &scenarioFinalHydroLevels; @@ -143,7 +141,6 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial void FinalLevelInflowsModifier::initialize(uint year) { - fillEmpty(); setCurrentYear(year); ComputeDeltaForCurrentYear(); } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 1384e2d093..72b9823b2e 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -48,7 +48,7 @@ class FinalLevelInflowsModifier private: // Simulation Data - uint simEndDay; + uint lastSimulationDay_ = 0; // simulation year // overwritten after each MC year @@ -77,7 +77,6 @@ class FinalLevelInflowsModifier private: // methods: void setCurrentYear(uint year); - void fillEmpty(); void ComputeDeltaForCurrentYear(); @@ -95,7 +94,8 @@ class FinalLevelInflowsModifier public: void initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay); + const uint lastSimulationDay, + const uint nbYears); void initialize(uint year); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 41f39467e5..75ffe77fbd 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -40,7 +40,8 @@ namespace Antares::Solver finalInflows.initialize(study.scenarioInitialHydroLevels, study.scenarioFinalHydroLevels, - study.parameters.simulationDays.end); + study.parameters.simulationDays.end, + study.parameters.nbYears); }); } 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 index 2ab5a45615..b2fb24a97a 100644 --- 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 @@ -109,17 +109,17 @@ BOOST_FIXTURE_TEST_SUITE(s, Fixture) BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; auto finLevInfModify = FinalLevelInflowsModifier(hydro, area_1->index, area_1->name); finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); @@ -128,18 +128,18 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManagement) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; hydro.reservoirManagement = false; - year = 1; + uint year = 1; auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); // check when reservoirManagement = false @@ -149,18 +149,18 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManageme BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; hydro.useWaterValue = true; - year = 1; + uint year = 1; auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); // check when useWaterValue = true @@ -170,18 +170,18 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; scenarioInitialHydroLevels[1][1] = std::numeric_limits::quiet_NaN(); auto& hydro = area_1->hydro; - year = 1; + uint year = 1; auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); // check when finalReservoirLevel = -1 @@ -191,17 +191,17 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); finLevInfModify.isActive(); @@ -218,17 +218,17 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), true); @@ -237,11 +237,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitResLevel) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; // initialize reservoir level != January hydro.initializeReservoirLevelDate = 3; @@ -249,7 +248,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); @@ -258,11 +258,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; // simulation End Day != 365 parameters.simulationDays.end = 300; @@ -270,7 +269,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); @@ -279,11 +279,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; // Lat Day Rule Curve = [2.4 - 6.5] scenarioFinalHydroLevels[0][0] = 6.6; @@ -291,7 +290,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); @@ -300,11 +300,10 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) { auto& parameters = study->parameters; - auto& year = parameters.nbYears; Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; auto& hydro = area_1->hydro; - year = 0; + uint year = 0; hydro.reservoirCapacity = 185000; scenarioInitialHydroLevels[0][0] = 10; scenarioFinalHydroLevels[0][0] = 50; @@ -316,7 +315,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) finLevInfModify.initialize(scenarioInitialHydroLevels, scenarioFinalHydroLevels, - parameters.simulationDays.end); + parameters.simulationDays.end, + parameters.nbYears); finLevInfModify.initialize(year); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); From a1d280c0e62e5d809e73c554088cedcbf5faf9fc Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 11:35:31 +0200 Subject: [PATCH 459/490] Hydro final lvl (CR 25) - try improvement : mainly remove setters not really useful --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 68 ++++++++----------- .../parts/hydro/finallevelinflowsmodifyer.h | 19 ++---- 2 files changed, 36 insertions(+), 51 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 69b5b5025c..0c1df1465e 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -35,41 +35,31 @@ namespace Data FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, const unsigned int& areaIndex, const AreaName& areaName) : - hydro(hydro), - areaIndex(areaIndex), - areaName(areaName) + hydro_(hydro), + areaIndex_(areaIndex), + areaName_(areaName) { } -void FinalLevelInflowsModifier::setLastSiumlationDay(uint day) -{ - lastSimulationDay_ = day; -} - -void FinalLevelInflowsModifier::setCurrentYear(uint year) -{ - yearIndex = year; -} - void FinalLevelInflowsModifier::ComputeDeltaForCurrentYear() { - initialReservoirLevel = (*scenarioInitialHydroLevels_)[areaIndex][yearIndex]; - finalReservoirLevel = (*scenarioFinalHydroLevels_)[areaIndex][yearIndex]; - deltaReservoirLevel = initialReservoirLevel - finalReservoirLevel; + initialReservoirLevel_ = (*scenarioInitialHydroLevels_)[areaIndex_][yearIndex_]; + finalReservoirLevel_ = (*scenarioFinalHydroLevels_)[areaIndex_][yearIndex_]; + deltaReservoirLevel_ = initialReservoirLevel_ - finalReservoirLevel_; } void FinalLevelInflowsModifier::updateInflows() { - includeFinalReservoirLevel.at(yearIndex) = true; - deltaLevel.at(yearIndex) = deltaReservoirLevel; + includeFinalReservoirLevel.at(yearIndex_) = true; + deltaLevel.at(yearIndex_) = deltaReservoirLevel_; } double FinalLevelInflowsModifier::calculateTotalInflows() const { // calculate yearly inflows - const Data::DataSeriesHydro& data = *hydro.series; - uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex]; - auto& inflowsmatrix = hydro.series->storage; + const Data::DataSeriesHydro& data = *hydro_.series; + uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex_]; + auto& inflowsmatrix = hydro_.series->storage; auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; double totalYearInflows = 0.0; @@ -81,12 +71,12 @@ double FinalLevelInflowsModifier::calculateTotalInflows() const bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const { - int initReservoirLvlMonth = hydro.initializeReservoirLevelDate; // month [0-11] + int initReservoirLvlMonth = hydro_.initializeReservoirLevelDate; // month [0-11] if (lastSimulationDay_ == DAYS_PER_YEAR && initReservoirLvlMonth == 0) return true; else { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName + logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ << ". Simulation must end on day 365 and reservoir level must be " "initiated in January"; return false; @@ -95,15 +85,15 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) const { - double reservoirCapacity = hydro.reservoirCapacity; - if ((-deltaReservoirLevel) * reservoirCapacity + double reservoirCapacity = hydro_.reservoirCapacity; + if ((-deltaReservoirLevel_) * reservoirCapacity > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh // (energy) { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName + logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ << ". Incompatible total inflows: " << totalYearInflows - << " with initial: " << initialReservoirLevel - << " and final: " << finalReservoirLevel << " reservoir levels."; + << " with initial: " << initialReservoirLevel_ + << " and final: " << finalReservoirLevel_ << " reservoir levels."; return false; } return true; @@ -111,13 +101,13 @@ bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) co bool FinalLevelInflowsModifier::preCheckRuleCurves() const { - double lowLevelLastDay = hydro.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - double highLevelLastDay = hydro.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; + double lowLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; + double highLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; - if (finalReservoirLevel < lowLevelLastDay || finalReservoirLevel > highLevelLastDay) + if (finalReservoirLevel_ < lowLevelLastDay || finalReservoirLevel_ > highLevelLastDay) { - logs.error() << "Year: " << yearIndex + 1 << ". Area: " << areaName - << ". Specifed final reservoir level: " << finalReservoirLevel + logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ + << ". Specifed final reservoir level: " << finalReservoirLevel_ << " is incompatible with reservoir level rule curve [" << lowLevelLastDay << " , " << highLevelLastDay << "]"; return false; @@ -136,22 +126,22 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial scenarioInitialHydroLevels_ = &scenarioInitialHydroLevels; scenarioFinalHydroLevels_ = &scenarioFinalHydroLevels; - setLastSiumlationDay(lastSimulationDay); + lastSimulationDay_ = lastSimulationDay; } void FinalLevelInflowsModifier::initialize(uint year) { - setCurrentYear(year); + yearIndex_ = year; ComputeDeltaForCurrentYear(); } bool FinalLevelInflowsModifier::isActive() { - return hydro.reservoirManagement && - !hydro.useWaterValue && - finalReservoirLevel >= 0. && - initialReservoirLevel >= 0.; + return hydro_.reservoirManagement && + !hydro_.useWaterValue && + finalReservoirLevel_ >= 0. && + initialReservoirLevel_ >= 0.; } bool FinalLevelInflowsModifier::makeChecks() diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 72b9823b2e..9519a1aaa9 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -52,17 +52,17 @@ class FinalLevelInflowsModifier // simulation year // overwritten after each MC year - uint yearIndex; + uint yearIndex_; // data per area // data overwritten after each MC year - double initialReservoirLevel = -1.; - double finalReservoirLevel = -1.; - double deltaReservoirLevel; + double initialReservoirLevel_ = -1.; + double finalReservoirLevel_ = -1.; + double deltaReservoirLevel_; - const PartHydro& hydro; - const unsigned int& areaIndex; - const AreaName& areaName; + const PartHydro& hydro_; + const unsigned int& areaIndex_; + const AreaName& areaName_; const Matrix* scenarioInitialHydroLevels_ = nullptr; const Matrix* scenarioFinalHydroLevels_ = nullptr; @@ -76,10 +76,8 @@ class FinalLevelInflowsModifier private: // methods: - void setCurrentYear(uint year); void ComputeDeltaForCurrentYear(); - double calculateTotalInflows() const; bool preCheckStartAndEndSim() const; @@ -88,9 +86,6 @@ class FinalLevelInflowsModifier bool preCheckRuleCurves() const; - void setLastSiumlationDay(uint day); - - public: void initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, From 3f087e4e464d64aacd7390b7f34e8cc0bc79de14 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 13:20:15 +0200 Subject: [PATCH 460/490] Hydro final lvl (CR 25) - try improvement : mainly renaming and harmless reordering --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 8 ++--- .../parts/hydro/finallevelinflowsmodifyer.h | 30 ++++++------------- 2 files changed, 13 insertions(+), 25 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 0c1df1465e..da4f044b5c 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -43,8 +43,8 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, void FinalLevelInflowsModifier::ComputeDeltaForCurrentYear() { - initialReservoirLevel_ = (*scenarioInitialHydroLevels_)[areaIndex_][yearIndex_]; - finalReservoirLevel_ = (*scenarioFinalHydroLevels_)[areaIndex_][yearIndex_]; + initialReservoirLevel_ = (*InitialLevels_)[yearIndex_]; + finalReservoirLevel_ = (*FinalLevels_)[yearIndex_]; deltaReservoirLevel_ = initialReservoirLevel_ - finalReservoirLevel_; } @@ -123,8 +123,8 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial includeFinalReservoirLevel = std::move(std::vector(nbYears, false)); deltaLevel = std::move(std::vector(nbYears, 0.)); - scenarioInitialHydroLevels_ = &scenarioInitialHydroLevels; - scenarioFinalHydroLevels_ = &scenarioFinalHydroLevels; + InitialLevels_ = &(scenarioInitialHydroLevels.entry[areaIndex_]); + FinalLevels_ = &(scenarioFinalHydroLevels.entry[areaIndex_]); lastSimulationDay_ = lastSimulationDay; } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 9519a1aaa9..55b2899249 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -47,25 +47,21 @@ class FinalLevelInflowsModifier const AreaName& areaName); private: - // Simulation Data uint lastSimulationDay_ = 0; - // simulation year - // overwritten after each MC year - uint yearIndex_; - - // data per area - // data overwritten after each MC year - double initialReservoirLevel_ = -1.; - double finalReservoirLevel_ = -1.; - double deltaReservoirLevel_; - + // Data from area (remaining unchanged throughout simulation) const PartHydro& hydro_; const unsigned int& areaIndex_; const AreaName& areaName_; + const Matrix::ColumnType* InitialLevels_ = nullptr; + const Matrix::ColumnType* FinalLevels_ = nullptr; - const Matrix* scenarioInitialHydroLevels_ = nullptr; - const Matrix* scenarioFinalHydroLevels_ = nullptr; + + // Data changing at each MC year + uint yearIndex_; + double initialReservoirLevel_ = -1.; + double finalReservoirLevel_ = -1.; + double deltaReservoirLevel_; public: // vectors containing data necessary for final reservoir level calculation @@ -75,15 +71,10 @@ class FinalLevelInflowsModifier std::vector deltaLevel; private: - // methods: void ComputeDeltaForCurrentYear(); - double calculateTotalInflows() const; - bool preCheckStartAndEndSim() const; - bool preCheckYearlyInflow(double totalYearInflows) const; - bool preCheckRuleCurves() const; public: @@ -93,11 +84,8 @@ class FinalLevelInflowsModifier const uint nbYears); void initialize(uint year); - bool isActive(); - void updateInflows(); - bool makeChecks(); }; } // namespace Antares::Data From a3514d532f4647b0c22cf7a0e7c8a3f8c3d22bcc Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 13:44:26 +0200 Subject: [PATCH 461/490] Hydro final lvl (CR 25) - try improvement : remove redondant check --- src/solver/hydro/management/management.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index b53dde809a..820ca68756 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -357,9 +357,6 @@ void HydroManagement::changeInflowsToAccommodateFinalLevels(uint numSpace, uint { auto& data = pAreas[numSpace][area.index]; - if (area.hydro.finalLevelInflowsModifier.deltaLevel.empty()) - return; - if (!area.hydro.finalLevelInflowsModifier.includeFinalReservoirLevel[year]) return; From 62381588345acddd10f06272c808dda5b45b8a3d Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 16:13:04 +0200 Subject: [PATCH 462/490] Hydro final lvl (CR 25) - try improvement : renaming and splitting functions --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 14 ++++---- .../parts/hydro/finallevelinflowsmodifyer.h | 6 ++-- .../hydro-final-reservoir-level-functions.cpp | 30 +++++++++------- .../hydro-final-reservoir-level-functions.h | 4 +-- src/solver/simulation/solver.hxx | 2 +- ...-hydro-final-reservoir-level-functions.cpp | 36 ++++++++++++------- 6 files changed, 53 insertions(+), 39 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index da4f044b5c..aa1a0a3626 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -41,16 +41,15 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, { } -void FinalLevelInflowsModifier::ComputeDeltaForCurrentYear() +void FinalLevelInflowsModifier::ComputeDelta() { initialReservoirLevel_ = (*InitialLevels_)[yearIndex_]; finalReservoirLevel_ = (*FinalLevels_)[yearIndex_]; deltaReservoirLevel_ = initialReservoirLevel_ - finalReservoirLevel_; } -void FinalLevelInflowsModifier::updateInflows() +void FinalLevelInflowsModifier::storeDeltaLevels() { - includeFinalReservoirLevel.at(yearIndex_) = true; deltaLevel.at(yearIndex_) = deltaReservoirLevel_; } @@ -86,9 +85,7 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) const { double reservoirCapacity = hydro_.reservoirCapacity; - if ((-deltaReservoirLevel_) * reservoirCapacity - > totalYearInflows) // ROR time-series in MW (power), SP time-series in MWh - // (energy) + if (-deltaReservoirLevel_ * reservoirCapacity > totalYearInflows) { logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ << ". Incompatible total inflows: " << totalYearInflows @@ -129,10 +126,9 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial lastSimulationDay_ = lastSimulationDay; } -void FinalLevelInflowsModifier::initialize(uint year) +void FinalLevelInflowsModifier::setCurrentYear(uint year) { yearIndex_ = year; - ComputeDeltaForCurrentYear(); } @@ -158,6 +154,8 @@ bool FinalLevelInflowsModifier::makeChecks() // rule curves for the final day checksOk = preCheckRuleCurves() && checksOk; + includeFinalReservoirLevel.at(yearIndex_) = checksOk; + return checksOk; } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 55b2899249..f21d2a03ae 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -71,7 +71,6 @@ class FinalLevelInflowsModifier std::vector deltaLevel; private: - void ComputeDeltaForCurrentYear(); double calculateTotalInflows() const; bool preCheckStartAndEndSim() const; bool preCheckYearlyInflow(double totalYearInflows) const; @@ -83,9 +82,10 @@ class FinalLevelInflowsModifier const uint lastSimulationDay, const uint nbYears); - void initialize(uint year); + void setCurrentYear(uint year); + void ComputeDelta(); bool isActive(); - void updateInflows(); + void storeDeltaLevels(); bool makeChecks(); }; } // namespace Antares::Data diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 75ffe77fbd..9f96623fd1 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -46,27 +46,33 @@ namespace Antares::Solver } -void updateInflowsDueToFinalLevels(Data::Study& study, uint year) + +bool CheckFinalReservoirLevelsForArea(Data::FinalLevelInflowsModifier & finalInflows, uint year) +{ + finalInflows.setCurrentYear(year); + finalInflows.ComputeDelta(); + + if (!finalInflows.isActive() || !finalInflows.makeChecks()) + return false; + + finalInflows.storeDeltaLevels(); + return true; +} + +void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) { study.areas.each([&study, &year](Data::Area& area) { auto& finalInflows = area.hydro.finalLevelInflowsModifier; - - finalInflows.initialize(year); - - if (!finalInflows.isActive()) - return; - - if (!finalInflows.makeChecks()) + if (!CheckFinalReservoirLevelsForArea(finalInflows, year)) { AntaresSolverEmergencyShutdown(); } - - finalInflows.updateInflows(); }); + } -void prepareFinalReservoirLevelData(Data::Study& study) +void CheckFinalReservoirLevelsInput(Data::Study& study) { initializeFinalLevelData(study); @@ -74,7 +80,7 @@ void prepareFinalReservoirLevelData(Data::Study& study) for (uint year = 0; year != nbYears; ++year) { - updateInflowsDueToFinalLevels(study, year); + CheckFinalReservoirLevelsForYear(study, year); } } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 797939f8c9..2414f57f1f 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,8 +31,8 @@ namespace Antares::Solver { -void prepareFinalReservoirLevelDataPerMcY(Data::Study& study, uint year); -void prepareFinalReservoirLevelData(Data::Study& study); +bool CheckFinalReservoirLevelsForArea(Data::FinalLevelInflowsModifier& finalInflows, uint year); +void CheckFinalReservoirLevelsInput(Data::Study& study); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index 87f771ff9e..9b5a42e926 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -347,7 +347,7 @@ void ISimulation::run() if (parameters.useCustomScenario) { ApplyCustomScenario(study); - prepareFinalReservoirLevelData(study); + CheckFinalReservoirLevelsInput(study); } // Launching the simulation for all years 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 index b2fb24a97a..2d8cd0efe5 100644 --- 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 @@ -120,7 +120,8 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } @@ -140,7 +141,8 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManageme scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); // check when reservoirManagement = false BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -161,7 +163,8 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); // check when useWaterValue = true BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -182,7 +185,8 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); // check when finalReservoirLevel = -1 BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -202,10 +206,11 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); - finLevInfModify.isActive(); - finLevInfModify.updateInflows(); + finLevInfModify.makeChecks(); + finLevInfModify.storeDeltaLevels(); double expectedDeltaLevel = -1.1; bool calculatedIncludeFinResLev = finLevInfModify.includeFinalReservoirLevel.at(0); @@ -229,7 +234,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), true); } @@ -250,7 +256,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -271,7 +278,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -292,7 +300,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -317,7 +326,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.initialize(year); + finLevInfModify.setCurrentYear(year); + finLevInfModify.ComputeDelta(); BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); } @@ -332,7 +342,7 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ FinalLevelInflowsModifier(hydro1, 0, "Area1"); FinalLevelInflowsModifier(hydro2, 1, "Area2"); - prepareFinalReservoirLevelData(*study); + CheckFinalReservoirLevelsInput(*study); // extract data area 1 - year 1 and 2 bool area_1_year_1_include_calculated = modifierArea1.includeFinalReservoirLevel.at(0); From a18f238509dce3ffb27a89796baa8a8581c62ffa Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 16:21:21 +0200 Subject: [PATCH 463/490] Hydro final lvl (CR 25) - try improvement : mistake correction --- .../simulation/hydro-final-reservoir-level-functions.cpp | 5 ++++- 1 file changed, 4 insertions(+), 1 deletion(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 9f96623fd1..d633e453c8 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -52,7 +52,10 @@ bool CheckFinalReservoirLevelsForArea(Data::FinalLevelInflowsModifier & finalInf finalInflows.setCurrentYear(year); finalInflows.ComputeDelta(); - if (!finalInflows.isActive() || !finalInflows.makeChecks()) + if (!finalInflows.isActive()) + return true; + + if (!finalInflows.makeChecks()) return false; finalInflows.storeDeltaLevels(); From 89f340bb0c62c20aadc961e4d381105d5253c243 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 16:28:52 +0200 Subject: [PATCH 464/490] Hydro final lvl (CR 25) - try improvement : renaming --- .../simulation/hydro-final-reservoir-level-functions.cpp | 4 ++-- src/solver/simulation/hydro-final-reservoir-level-functions.h | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index d633e453c8..453970f30c 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -47,7 +47,7 @@ namespace Antares::Solver -bool CheckFinalReservoirLevelsForArea(Data::FinalLevelInflowsModifier & finalInflows, uint year) +bool CheckInfeasibilityForFinalLevelsInArea(Data::FinalLevelInflowsModifier & finalInflows, uint year) { finalInflows.setCurrentYear(year); finalInflows.ComputeDelta(); @@ -67,7 +67,7 @@ void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) study.areas.each([&study, &year](Data::Area& area) { auto& finalInflows = area.hydro.finalLevelInflowsModifier; - if (!CheckFinalReservoirLevelsForArea(finalInflows, year)) + if (!CheckInfeasibilityForFinalLevelsInArea(finalInflows, year)) { AntaresSolverEmergencyShutdown(); } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 2414f57f1f..66c90e4e3b 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,7 +31,7 @@ namespace Antares::Solver { -bool CheckFinalReservoirLevelsForArea(Data::FinalLevelInflowsModifier& finalInflows, uint year); +bool CheckInfeasibilityForFinalLevelsInArea(Data::FinalLevelInflowsModifier& finalInflows, uint year); void CheckFinalReservoirLevelsInput(Data::Study& study); } // namespace Antares::Solver From d926f1b2896cc47106a563352d01f2c3ee33c263 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 17:03:41 +0200 Subject: [PATCH 465/490] Hydro final lvl (CR 25) - try improvement : add the current year as parameter to make it clear we're dealing with a particular year --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 44 ++++++++----------- .../parts/hydro/finallevelinflowsmodifyer.h | 16 +++---- .../hydro-final-reservoir-level-functions.cpp | 7 ++- ...-hydro-final-reservoir-level-functions.cpp | 44 +++++++------------ 4 files changed, 46 insertions(+), 65 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index aa1a0a3626..7e6c7fd244 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -41,23 +41,23 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, { } -void FinalLevelInflowsModifier::ComputeDelta() +void FinalLevelInflowsModifier::ComputeDelta(uint year) { - initialReservoirLevel_ = (*InitialLevels_)[yearIndex_]; - finalReservoirLevel_ = (*FinalLevels_)[yearIndex_]; + initialReservoirLevel_ = (*InitialLevels_)[year]; + finalReservoirLevel_ = (*FinalLevels_)[year]; deltaReservoirLevel_ = initialReservoirLevel_ - finalReservoirLevel_; } -void FinalLevelInflowsModifier::storeDeltaLevels() +void FinalLevelInflowsModifier::storeDeltaLevels(uint year) { - deltaLevel.at(yearIndex_) = deltaReservoirLevel_; + deltaLevel.at(year) = deltaReservoirLevel_; } -double FinalLevelInflowsModifier::calculateTotalInflows() const +double FinalLevelInflowsModifier::calculateTotalInflows(uint year) const { // calculate yearly inflows const Data::DataSeriesHydro& data = *hydro_.series; - uint tsHydroIndex = data.timeseriesNumbers[0][yearIndex_]; + uint tsHydroIndex = data.timeseriesNumbers[0][year]; auto& inflowsmatrix = hydro_.series->storage; auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; @@ -67,7 +67,7 @@ double FinalLevelInflowsModifier::calculateTotalInflows() const return totalYearInflows; } -bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const +bool FinalLevelInflowsModifier::preCheckStartAndEndSim(uint year) const { int initReservoirLvlMonth = hydro_.initializeReservoirLevelDate; // month [0-11] @@ -75,19 +75,19 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim() const return true; else { - logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ + logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ << ". Simulation must end on day 365 and reservoir level must be " "initiated in January"; return false; } } -bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) const +bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows, uint year) const { double reservoirCapacity = hydro_.reservoirCapacity; if (-deltaReservoirLevel_ * reservoirCapacity > totalYearInflows) { - logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ + logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ << ". Incompatible total inflows: " << totalYearInflows << " with initial: " << initialReservoirLevel_ << " and final: " << finalReservoirLevel_ << " reservoir levels."; @@ -96,14 +96,14 @@ bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows) co return true; } -bool FinalLevelInflowsModifier::preCheckRuleCurves() const +bool FinalLevelInflowsModifier::preCheckRuleCurves(uint year) const { double lowLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; double highLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; if (finalReservoirLevel_ < lowLevelLastDay || finalReservoirLevel_ > highLevelLastDay) { - logs.error() << "Year: " << yearIndex_ + 1 << ". Area: " << areaName_ + logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ << ". Specifed final reservoir level: " << finalReservoirLevel_ << " is incompatible with reservoir level rule curve [" << lowLevelLastDay << " , " << highLevelLastDay << "]"; @@ -126,12 +126,6 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial lastSimulationDay_ = lastSimulationDay; } -void FinalLevelInflowsModifier::setCurrentYear(uint year) -{ - yearIndex_ = year; -} - - bool FinalLevelInflowsModifier::isActive() { return hydro_.reservoirManagement && @@ -140,21 +134,21 @@ bool FinalLevelInflowsModifier::isActive() initialReservoirLevel_ >= 0.; } -bool FinalLevelInflowsModifier::makeChecks() +bool FinalLevelInflowsModifier::makeChecks(uint year) { // Simulation must end on day 365 and reservoir level must be // initiated in January - bool checksOk = preCheckStartAndEndSim(); + bool checksOk = preCheckStartAndEndSim(year); // Reservoir_levelDay_365 – reservoir_levelDay_1 ≤ yearly_inflows - double totalInflows = calculateTotalInflows(); - checksOk = preCheckYearlyInflow(totalInflows) && checksOk; + double totalInflows = calculateTotalInflows(year); + checksOk = preCheckYearlyInflow(totalInflows, year) && checksOk; // Final reservoir level set by the user is within the // rule curves for the final day - checksOk = preCheckRuleCurves() && checksOk; + checksOk = preCheckRuleCurves(year) && checksOk; - includeFinalReservoirLevel.at(yearIndex_) = checksOk; + includeFinalReservoirLevel.at(year) = checksOk; return checksOk; } diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index f21d2a03ae..0102493414 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -58,7 +58,6 @@ class FinalLevelInflowsModifier // Data changing at each MC year - uint yearIndex_; double initialReservoirLevel_ = -1.; double finalReservoirLevel_ = -1.; double deltaReservoirLevel_; @@ -71,10 +70,10 @@ class FinalLevelInflowsModifier std::vector deltaLevel; private: - double calculateTotalInflows() const; - bool preCheckStartAndEndSim() const; - bool preCheckYearlyInflow(double totalYearInflows) const; - bool preCheckRuleCurves() const; + double calculateTotalInflows(uint year) const; + bool preCheckStartAndEndSim(uint year) const; + bool preCheckYearlyInflow(double totalYearInflows, uint year) const; + bool preCheckRuleCurves(uint year) const; public: void initialize(const Matrix& scenarioInitialHydroLevels, @@ -82,11 +81,10 @@ class FinalLevelInflowsModifier const uint lastSimulationDay, const uint nbYears); - void setCurrentYear(uint year); - void ComputeDelta(); + void ComputeDelta(uint year); bool isActive(); - void storeDeltaLevels(); - bool makeChecks(); + void storeDeltaLevels(uint year); + bool makeChecks(uint year); }; } // namespace Antares::Data diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 453970f30c..66eb0f25a0 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -49,16 +49,15 @@ namespace Antares::Solver bool CheckInfeasibilityForFinalLevelsInArea(Data::FinalLevelInflowsModifier & finalInflows, uint year) { - finalInflows.setCurrentYear(year); - finalInflows.ComputeDelta(); + finalInflows.ComputeDelta(year); if (!finalInflows.isActive()) return true; - if (!finalInflows.makeChecks()) + if (!finalInflows.makeChecks(year)) return false; - finalInflows.storeDeltaLevels(); + finalInflows.storeDeltaLevels(year); return true; } 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 index 2d8cd0efe5..81e27a14e4 100644 --- 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 @@ -120,8 +120,7 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } @@ -141,8 +140,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManageme scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); // check when reservoirManagement = false BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -163,8 +161,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); // check when useWaterValue = true BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -185,8 +182,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); // check when finalReservoirLevel = -1 BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -206,11 +202,10 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); - finLevInfModify.makeChecks(); - finLevInfModify.storeDeltaLevels(); + finLevInfModify.makeChecks(year); + finLevInfModify.storeDeltaLevels(year); double expectedDeltaLevel = -1.1; bool calculatedIncludeFinResLev = finLevInfModify.includeFinalReservoirLevel.at(0); @@ -234,10 +229,9 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), true); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), true); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitResLevel) @@ -256,10 +250,9 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) @@ -278,10 +271,9 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) @@ -300,10 +292,9 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) @@ -326,10 +317,9 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.setCurrentYear(year); - finLevInfModify.ComputeDelta(); + finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(), false); + BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); } BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_and_area_2) From db83d09b2cb96cc57a19d8eeba7693c828d7a511 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 17:23:18 +0200 Subject: [PATCH 466/490] Hydro final lvl (CR 25) - try improvement : add a new general function to class FinalLevelInflowsModifier --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 15 ++++++++ .../parts/hydro/finallevelinflowsmodifyer.h | 7 ++-- .../hydro-final-reservoir-level-functions.cpp | 37 +++++-------------- .../hydro-final-reservoir-level-functions.h | 1 - ...-hydro-final-reservoir-level-functions.cpp | 28 +++++--------- 5 files changed, 39 insertions(+), 49 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 7e6c7fd244..9180e725d1 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -41,6 +41,21 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, { } +bool FinalLevelInflowsModifier::CheckInfeasibility(uint year) +{ + ComputeDelta(year); + + if (!isActive()) + return true; + + if (!makeChecks(year)) + return false; + + storeDeltaLevels(year); + return true; + +} + void FinalLevelInflowsModifier::ComputeDelta(uint year) { initialReservoirLevel_ = (*InitialLevels_)[year]; diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 0102493414..a583359998 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -70,6 +70,9 @@ class FinalLevelInflowsModifier std::vector deltaLevel; private: + void ComputeDelta(uint year); + bool makeChecks(uint year); + void storeDeltaLevels(uint year); double calculateTotalInflows(uint year) const; bool preCheckStartAndEndSim(uint year) const; bool preCheckYearlyInflow(double totalYearInflows, uint year) const; @@ -81,10 +84,8 @@ class FinalLevelInflowsModifier const uint lastSimulationDay, const uint nbYears); - void ComputeDelta(uint year); + bool CheckInfeasibility(uint year); bool isActive(); - void storeDeltaLevels(uint year); - bool makeChecks(uint year); }; } // namespace Antares::Data diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 66eb0f25a0..c4e4837444 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -31,34 +31,17 @@ namespace Antares::Solver { - - void initializeFinalLevelData(Data::Study& study) - { - study.areas.each([&study](Data::Area& area) - { - auto& finalInflows = area.hydro.finalLevelInflowsModifier; - - finalInflows.initialize(study.scenarioInitialHydroLevels, - study.scenarioFinalHydroLevels, - study.parameters.simulationDays.end, - study.parameters.nbYears); - }); - } - - - -bool CheckInfeasibilityForFinalLevelsInArea(Data::FinalLevelInflowsModifier & finalInflows, uint year) +void initializeFinalLevelData(Data::Study& study) { - finalInflows.ComputeDelta(year); - - if (!finalInflows.isActive()) - return true; - - if (!finalInflows.makeChecks(year)) - return false; + study.areas.each([&study](Data::Area& area) + { + auto& finalInflows = area.hydro.finalLevelInflowsModifier; - finalInflows.storeDeltaLevels(year); - return true; + finalInflows.initialize(study.scenarioInitialHydroLevels, + study.scenarioFinalHydroLevels, + study.parameters.simulationDays.end, + study.parameters.nbYears); + }); } void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) @@ -66,7 +49,7 @@ void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) study.areas.each([&study, &year](Data::Area& area) { auto& finalInflows = area.hydro.finalLevelInflowsModifier; - if (!CheckInfeasibilityForFinalLevelsInArea(finalInflows, year)) + if (!finalInflows.CheckInfeasibility(year)) { AntaresSolverEmergencyShutdown(); } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 66c90e4e3b..6ad8f4170f 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,7 +31,6 @@ namespace Antares::Solver { -bool CheckInfeasibilityForFinalLevelsInArea(Data::FinalLevelInflowsModifier& finalInflows, uint year); void CheckFinalReservoirLevelsInput(Data::Study& study); } // namespace Antares::Solver 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 index 81e27a14e4..a77323e729 100644 --- 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 @@ -120,7 +120,7 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); + finLevInfModify.CheckInfeasibility(year); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } @@ -140,7 +140,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManageme scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); + finLevInfModify.CheckInfeasibility(year); // check when reservoirManagement = false BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -161,7 +161,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); + finLevInfModify.CheckInfeasibility(year); // check when useWaterValue = true BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -182,7 +182,7 @@ BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); + finLevInfModify.CheckInfeasibility(year); // check when finalReservoirLevel = -1 BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); @@ -202,10 +202,7 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); - - finLevInfModify.makeChecks(year); - finLevInfModify.storeDeltaLevels(year); + finLevInfModify.CheckInfeasibility(year); double expectedDeltaLevel = -1.1; bool calculatedIncludeFinResLev = finLevInfModify.includeFinalReservoirLevel.at(0); @@ -229,9 +226,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), true); + BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), true); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitResLevel) @@ -250,9 +246,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitRes scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); + BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) @@ -271,9 +266,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); + BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) @@ -292,9 +286,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); + BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) @@ -317,9 +310,8 @@ BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) scenarioFinalHydroLevels, parameters.simulationDays.end, parameters.nbYears); - finLevInfModify.ComputeDelta(year); - BOOST_CHECK_EQUAL(finLevInfModify.makeChecks(year), false); + BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_and_area_2) From 69f587919cd5b3b3cb82daf36afa516c3e0c9d5a Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 17:32:30 +0200 Subject: [PATCH 467/490] Hydro final lvl (CR 25) - try improvement : add a new isApplicable function to class FinalLevelInflowsModifier --- .../study/parts/hydro/finallevelinflowsmodifyer.cpp | 9 +++++++-- .../study/parts/hydro/finallevelinflowsmodifyer.h | 4 +++- src/solver/hydro/management/management.cpp | 2 +- .../test-hydro-final-reservoir-level-functions.cpp | 12 ++++++------ 4 files changed, 17 insertions(+), 10 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 9180e725d1..7213525b51 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -132,7 +132,7 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial const uint lastSimulationDay, const uint nbYears) { - includeFinalReservoirLevel = std::move(std::vector(nbYears, false)); + isApplicable_ = std::move(std::vector(nbYears, false)); deltaLevel = std::move(std::vector(nbYears, 0.)); InitialLevels_ = &(scenarioInitialHydroLevels.entry[areaIndex_]); @@ -163,10 +163,15 @@ bool FinalLevelInflowsModifier::makeChecks(uint year) // rule curves for the final day checksOk = preCheckRuleCurves(year) && checksOk; - includeFinalReservoirLevel.at(year) = checksOk; + isApplicable_.at(year) = checksOk; return checksOk; } +bool FinalLevelInflowsModifier::isApplicable(uint year) +{ + return isApplicable_.at(year); +} + } // namespace Data } // namespace Antares \ No newline at end of file diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index a583359998..3165467d3f 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -62,11 +62,12 @@ class FinalLevelInflowsModifier double finalReservoirLevel_ = -1.; double deltaReservoirLevel_; + std::vector isApplicable_; + public: // vectors containing data necessary for final reservoir level calculation // for one area and all MC years // vector indexes correspond to the MC years - std::vector includeFinalReservoirLevel; std::vector deltaLevel; private: @@ -85,6 +86,7 @@ class FinalLevelInflowsModifier const uint nbYears); bool CheckInfeasibility(uint year); + bool isApplicable(uint year); bool isActive(); }; } // namespace Antares::Data diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 820ca68756..d8f37cfe12 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -357,7 +357,7 @@ void HydroManagement::changeInflowsToAccommodateFinalLevels(uint numSpace, uint { auto& data = pAreas[numSpace][area.index]; - if (!area.hydro.finalLevelInflowsModifier.includeFinalReservoirLevel[year]) + if (!area.hydro.finalLevelInflowsModifier.isApplicable(year)) return; // Must be done before prepareMonthlyTargetGenerations 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 index a77323e729..dce6f2610d 100644 --- 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 @@ -205,8 +205,8 @@ BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) finLevInfModify.CheckInfeasibility(year); double expectedDeltaLevel = -1.1; - bool calculatedIncludeFinResLev = finLevInfModify.includeFinalReservoirLevel.at(0); - double calculatedDeltaLevel = finLevInfModify.deltaLevel.at(0); + bool calculatedIncludeFinResLev = finLevInfModify.isApplicable(year); + double calculatedDeltaLevel = finLevInfModify.deltaLevel.at(year); BOOST_CHECK_EQUAL(calculatedIncludeFinResLev, true); BOOST_CHECK_EQUAL(calculatedDeltaLevel, expectedDeltaLevel); @@ -327,8 +327,8 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ CheckFinalReservoirLevelsInput(*study); // extract data area 1 - year 1 and 2 - bool area_1_year_1_include_calculated = modifierArea1.includeFinalReservoirLevel.at(0); - bool area_1_year_2_include_calculated = modifierArea1.includeFinalReservoirLevel.at(1); + bool area_1_year_1_include_calculated = modifierArea1.isApplicable(0); + bool area_1_year_2_include_calculated = modifierArea1.isApplicable(1); double area_1_year_1_deltaLev_calculated = modifierArea1.deltaLevel.at(0); double area_1_year_2_deltaLev_calculated = modifierArea1.deltaLevel.at(1); double area_1_year_1_deltaLev_expected = 2.3 - 3.4; @@ -340,8 +340,8 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ BOOST_CHECK_EQUAL(area_1_year_2_deltaLev_calculated, area_1_year_2_deltaLev_expected); // extract data area 2 - year 1 and 2 - bool area_2_year_1_include_calculated = modifierArea2.includeFinalReservoirLevel.at(0); - bool area_2_year_2_include_calculated = modifierArea2.includeFinalReservoirLevel.at(1); + bool area_2_year_1_include_calculated = modifierArea2.isApplicable(0); + bool area_2_year_2_include_calculated = modifierArea2.isApplicable(1); double area_2_year_1_deltaLev_calculated = modifierArea2.deltaLevel.at(0); double area_2_year_2_deltaLev_calculated = modifierArea2.deltaLevel.at(1); double area_2_year_1_deltaLev_expected = 1.5 - 3.5; From ddd00b2c1691baa874521cb344802b60b410885c Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 10 Aug 2023 17:44:49 +0200 Subject: [PATCH 468/490] Hydro final lvl (CR 25) - try improvement : a bit of cleaning --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 28 ++++++------------- 1 file changed, 9 insertions(+), 19 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 7213525b51..99824b3fdd 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -28,16 +28,12 @@ #include "finallevelinflowsmodifyer.h" #include "container.h" -namespace Antares -{ -namespace Data +namespace Antares::Data { FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, const unsigned int& areaIndex, const AreaName& areaName) : - hydro_(hydro), - areaIndex_(areaIndex), - areaName_(areaName) + hydro_(hydro), areaIndex_(areaIndex), areaName_(areaName) { } @@ -88,13 +84,11 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim(uint year) const int initReservoirLvlMonth = hydro_.initializeReservoirLevelDate; // month [0-11] if (lastSimulationDay_ == DAYS_PER_YEAR && initReservoirLvlMonth == 0) return true; - else - { - logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ - << ". Simulation must end on day 365 and reservoir level must be " - "initiated in January"; - return false; - } + + logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ + << ". Simulation must end on day 365 and reservoir level must be " + "initiated in January"; + return false; } bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows, uint year) const @@ -134,10 +128,8 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial { isApplicable_ = std::move(std::vector(nbYears, false)); deltaLevel = std::move(std::vector(nbYears, 0.)); - InitialLevels_ = &(scenarioInitialHydroLevels.entry[areaIndex_]); FinalLevels_ = &(scenarioFinalHydroLevels.entry[areaIndex_]); - lastSimulationDay_ = lastSimulationDay; } @@ -151,8 +143,7 @@ bool FinalLevelInflowsModifier::isActive() bool FinalLevelInflowsModifier::makeChecks(uint year) { - // Simulation must end on day 365 and reservoir level must be - // initiated in January + // Simulation must end on day 365 and reservoir level must be initiated in January bool checksOk = preCheckStartAndEndSim(year); // Reservoir_levelDay_365 – reservoir_levelDay_1 ≤ yearly_inflows @@ -173,5 +164,4 @@ bool FinalLevelInflowsModifier::isApplicable(uint year) return isApplicable_.at(year); } -} // namespace Data -} // namespace Antares \ No newline at end of file +} // namespace Antares::Data From 135b751af09851ad24fc7157f1300ad11704374c Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Fri, 11 Aug 2023 11:53:13 +0200 Subject: [PATCH 469/490] Hydro final lvl (CR 25) - try improvement : clarifying all unit tests (except last one) --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 10 +- ...-hydro-final-reservoir-level-functions.cpp | 250 +++++++----------- 2 files changed, 109 insertions(+), 151 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 99824b3fdd..d6e7777999 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -30,6 +30,12 @@ namespace Antares::Data { + +bool isValidLevel(double level) +{ + return (level < 0. || isnan(level)) ? false : true; +} + FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, const unsigned int& areaIndex, const AreaName& areaName) : @@ -137,8 +143,8 @@ bool FinalLevelInflowsModifier::isActive() { return hydro_.reservoirManagement && !hydro_.useWaterValue && - finalReservoirLevel_ >= 0. && - initialReservoirLevel_ >= 0.; + isValidLevel(finalReservoirLevel_) && + isValidLevel(initialReservoirLevel_); } bool FinalLevelInflowsModifier::makeChecks(uint year) 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 index dce6f2610d..bc9d419d83 100644 --- 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 @@ -21,11 +21,9 @@ struct Fixture Fixture& operator=(const Fixture&& f) = delete; Fixture() { - // endDay must be 365, see preCheckStartAndEndSim function - Parameters& parameters = study->parameters; - - parameters.simulationDays.end = 365; - uint nbYears = parameters.nbYears = 2; + // Simulation last day must be 365 so that final level checks succeeds + study->parameters.simulationDays.end = 365; + uint nbYears = study->parameters.nbYears = 2; area_1 = study->areaAdd("Area1"); area_2 = study->areaAdd("Area2"); @@ -55,23 +53,20 @@ struct Fixture // Scenario builder for initial and final reservoir levels // ------------------------------------------------------- - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - uint areasCount = study->areas.size(); - scenarioInitialHydroLevels.resize(nbYears, areasCount); - scenarioFinalHydroLevels.resize(nbYears, areasCount); + study->scenarioInitialHydroLevels.resize(nbYears, areasCount); + study->scenarioFinalHydroLevels.resize(nbYears, areasCount); - scenarioInitialHydroLevels[0][0] = 2.3; - scenarioInitialHydroLevels[0][1] = 4.2; - scenarioInitialHydroLevels[1][0] = 1.5; - scenarioInitialHydroLevels[1][1] = 2.4; + study->scenarioInitialHydroLevels[0][0] = 2.3; + study->scenarioInitialHydroLevels[0][1] = 4.2; + study->scenarioInitialHydroLevels[1][0] = 1.5; + study->scenarioInitialHydroLevels[1][1] = 2.4; - scenarioFinalHydroLevels[0][0] = 3.4; - scenarioFinalHydroLevels[0][1] = 5.1; - scenarioFinalHydroLevels[1][0] = 3.5; - scenarioFinalHydroLevels[1][1] = 4.3; + 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 // ----------------------------- @@ -108,208 +103,165 @@ BOOST_FIXTURE_TEST_SUITE(s, Fixture) BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; uint year = 0; + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - auto finLevInfModify = FinalLevelInflowsModifier(hydro, area_1->index, area_1->name); + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); finLevInfModify.CheckInfeasibility(year); BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); } -BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_resManagement) +BOOST_AUTO_TEST_CASE(reservoir_management_is_false_for_area_1___modifier_is_not_active) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; - hydro.reservoirManagement = false; - uint year = 1; - - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + area_1->hydro.reservoirManagement = false; + uint year = 0; + + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); + + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); + finLevInfModify.CheckInfeasibility(year); // check when reservoirManagement = false BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } -BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_watValues) +BOOST_AUTO_TEST_CASE(use_water_value_is_true_for_area_1___modifier_is_not_active) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; - hydro.useWaterValue = true; - uint year = 1; - - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + area_1->hydro.useWaterValue = true; + uint year = 0; + + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); + + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); + finLevInfModify.CheckInfeasibility(year); // check when useWaterValue = true BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } -BOOST_AUTO_TEST_CASE(Testing_initializeData_function_for_area_1_fail_NaN) +BOOST_AUTO_TEST_CASE(initial_level_from_scenariobuilder_is_NaN_for_area_1_and_year_0____modifier_is_not_active) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - scenarioInitialHydroLevels[1][1] = std::numeric_limits::quiet_NaN(); - auto& hydro = area_1->hydro; - uint year = 1; - - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 1, "Area1"); - - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + uint year = 0; + study->scenarioInitialHydroLevels[area_1->index][year] = std::numeric_limits::quiet_NaN(); + + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); + + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); + finLevInfModify.CheckInfeasibility(year); - // check when finalReservoirLevel = -1 BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } -BOOST_AUTO_TEST_CASE(Testing_updateInflows_function_for_area_1) +BOOST_AUTO_TEST_CASE(checking_level_configuration_is_ok_for_area_1_and_year_0___delta_level_as_expected) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; uint year = 0; - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); + + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); finLevInfModify.CheckInfeasibility(year); double expectedDeltaLevel = -1.1; - bool calculatedIncludeFinResLev = finLevInfModify.isApplicable(year); - double calculatedDeltaLevel = finLevInfModify.deltaLevel.at(year); - - BOOST_CHECK_EQUAL(calculatedIncludeFinResLev, true); - BOOST_CHECK_EQUAL(calculatedDeltaLevel, expectedDeltaLevel); + BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), true); + BOOST_CHECK_EQUAL(finLevInfModify.deltaLevel.at(year), expectedDeltaLevel); } -BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_pass) +BOOST_AUTO_TEST_CASE(input_level_configuration_has_nothing_wrong_for_area_1___check_succeeds) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; uint year = 0; + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); - - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), true); } -BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_preCheckInitResLevel) +BOOST_AUTO_TEST_CASE(initial_level_month_for_area_1_is_not_january___check_fails) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; uint year = 0; - // initialize reservoir level != January - hydro.initializeReservoirLevelDate = 3; + area_1->hydro.initializeReservoirLevelDate = 3; // initialize reservoir level != January - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } -BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_EndSimDay) +BOOST_AUTO_TEST_CASE(simulation_last_day_is_not_365___check_fails) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; uint year = 0; - // simulation End Day != 365 - parameters.simulationDays.end = 300; + study->parameters.simulationDays.end = 300; - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } -BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_RuleCurve) +BOOST_AUTO_TEST_CASE(Final_level_not_between_rule_curves_for_area_1___check_fails) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; uint year = 0; - // Lat Day Rule Curve = [2.4 - 6.5] - scenarioFinalHydroLevels[0][0] = 6.6; + // Rule Curves on last simulation day = [2.4 - 6.5] + study->scenarioFinalHydroLevels[area_1->index][year] = 6.6; - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } -BOOST_AUTO_TEST_CASE(Testing_makeChecks_function_for_area_1_fail_ResCapacity) +BOOST_AUTO_TEST_CASE(diff_between_init_and_final_levels_are_bigger_than_yearly_inflows_for_area_1___check_fails) { - auto& parameters = study->parameters; - Matrix& scenarioInitialHydroLevels = study->scenarioInitialHydroLevels; - Matrix& scenarioFinalHydroLevels = study->scenarioFinalHydroLevels; - auto& hydro = area_1->hydro; + area_1->hydro.reservoirCapacity = 185000; uint year = 0; - hydro.reservoirCapacity = 185000; - scenarioInitialHydroLevels[0][0] = 10; - scenarioFinalHydroLevels[0][0] = 50; + study->scenarioInitialHydroLevels[area_1->index][year] = 10; + study->scenarioFinalHydroLevels[area_1->index][year] = 50; - // inflows = 200 MWh/day = 73 000 MWh/year - // res capacity = 185 000 -> 40% of reservoir is 74 000. So we are missing 1k. + // Inflows = 200 MWh/day = 73 000 MWh/year + // (50 - 10) x Reservoir capacity == 74 000 > 73 000. - auto finLevInfModify = FinalLevelInflowsModifier(hydro, 0, "Area1"); + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - finLevInfModify.initialize(scenarioInitialHydroLevels, - scenarioFinalHydroLevels, - parameters.simulationDays.end, - parameters.nbYears); + finLevInfModify.initialize(study->scenarioInitialHydroLevels, + study->scenarioFinalHydroLevels, + study->parameters.simulationDays.end, + study->parameters.nbYears); BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } @@ -321,8 +273,8 @@ BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_ auto& modifierArea1 = hydro1.finalLevelInflowsModifier; auto& modifierArea2 = hydro2.finalLevelInflowsModifier; - FinalLevelInflowsModifier(hydro1, 0, "Area1"); - FinalLevelInflowsModifier(hydro2, 1, "Area2"); + FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); + FinalLevelInflowsModifier(area_2->hydro, area_2->index, area_2->name); CheckFinalReservoirLevelsInput(*study); From 13ea8c54544368e1f4b559ac7f0238ea7f744eca Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Fri, 11 Aug 2023 13:22:10 +0200 Subject: [PATCH 470/490] Hydro final lvl (CR 25) - try improvement : clarify last unit test + renaming --- .../hydro-final-reservoir-level-functions.cpp | 15 +++--- .../hydro-final-reservoir-level-functions.h | 2 +- src/solver/simulation/solver.hxx | 2 +- ...-hydro-final-reservoir-level-functions.cpp | 50 ++++++------------- 4 files changed, 22 insertions(+), 47 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index c4e4837444..4edfcd1a70 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -35,12 +35,10 @@ void initializeFinalLevelData(Data::Study& study) { study.areas.each([&study](Data::Area& area) { - auto& finalInflows = area.hydro.finalLevelInflowsModifier; - - finalInflows.initialize(study.scenarioInitialHydroLevels, - study.scenarioFinalHydroLevels, - study.parameters.simulationDays.end, - study.parameters.nbYears); + area.hydro.finalLevelInflowsModifier.initialize(study.scenarioInitialHydroLevels, + study.scenarioFinalHydroLevels, + study.parameters.simulationDays.end, + study.parameters.nbYears); }); } @@ -48,8 +46,7 @@ void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) { study.areas.each([&study, &year](Data::Area& area) { - auto& finalInflows = area.hydro.finalLevelInflowsModifier; - if (!finalInflows.CheckInfeasibility(year)) + if (!area.hydro.finalLevelInflowsModifier.CheckInfeasibility(year)) { AntaresSolverEmergencyShutdown(); } @@ -57,7 +54,7 @@ void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) } -void CheckFinalReservoirLevelsInput(Data::Study& study) +void CheckFinalReservoirLevelsConfiguration(Data::Study& study) { initializeFinalLevelData(study); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 6ad8f4170f..588d0dcb18 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,7 +31,7 @@ namespace Antares::Solver { -void CheckFinalReservoirLevelsInput(Data::Study& study); +void CheckFinalReservoirLevelsConfiguration(Data::Study& study); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ diff --git a/src/solver/simulation/solver.hxx b/src/solver/simulation/solver.hxx index 9b5a42e926..aa64c3a4ab 100644 --- a/src/solver/simulation/solver.hxx +++ b/src/solver/simulation/solver.hxx @@ -347,7 +347,7 @@ void ISimulation::run() if (parameters.useCustomScenario) { ApplyCustomScenario(study); - CheckFinalReservoirLevelsInput(study); + CheckFinalReservoirLevelsConfiguration(study); } // Launching the simulation for all years 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 index bc9d419d83..b04d1a5bee 100644 --- 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 @@ -266,43 +266,21 @@ BOOST_AUTO_TEST_CASE(diff_between_init_and_final_levels_are_bigger_than_yearly_i BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), false); } -BOOST_AUTO_TEST_CASE(Testing_prepareFinalReservoirLevelData_function_for_area_1_and_area_2) +BOOST_AUTO_TEST_CASE(check_all_areas_final_reservoir_levels_when_config_is_ok___all_checks_succeed) { - auto& hydro1 = area_1->hydro; - auto& hydro2 = area_2->hydro; - auto& modifierArea1 = hydro1.finalLevelInflowsModifier; - auto& modifierArea2 = hydro2.finalLevelInflowsModifier; - - FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - FinalLevelInflowsModifier(area_2->hydro, area_2->index, area_2->name); - - CheckFinalReservoirLevelsInput(*study); - - // extract data area 1 - year 1 and 2 - bool area_1_year_1_include_calculated = modifierArea1.isApplicable(0); - bool area_1_year_2_include_calculated = modifierArea1.isApplicable(1); - double area_1_year_1_deltaLev_calculated = modifierArea1.deltaLevel.at(0); - double area_1_year_2_deltaLev_calculated = modifierArea1.deltaLevel.at(1); - double area_1_year_1_deltaLev_expected = 2.3 - 3.4; - double area_1_year_2_deltaLev_expected = 4.2 - 5.1; - // check data area 1 - year 1 and 2 - BOOST_CHECK_EQUAL(area_1_year_1_include_calculated, true); - BOOST_CHECK_EQUAL(area_1_year_2_include_calculated, true); - BOOST_CHECK_EQUAL(area_1_year_1_deltaLev_calculated, area_1_year_1_deltaLev_expected); - BOOST_CHECK_EQUAL(area_1_year_2_deltaLev_calculated, area_1_year_2_deltaLev_expected); - - // extract data area 2 - year 1 and 2 - bool area_2_year_1_include_calculated = modifierArea2.isApplicable(0); - bool area_2_year_2_include_calculated = modifierArea2.isApplicable(1); - double area_2_year_1_deltaLev_calculated = modifierArea2.deltaLevel.at(0); - double area_2_year_2_deltaLev_calculated = modifierArea2.deltaLevel.at(1); - double area_2_year_1_deltaLev_expected = 1.5 - 3.5; - double area_2_year_2_deltaLev_expected = 2.4 - 4.3; - // check data area 2 - year 1 and 2 - BOOST_CHECK_EQUAL(area_2_year_1_include_calculated, true); - BOOST_CHECK_EQUAL(area_2_year_2_include_calculated, true); - BOOST_CHECK_EQUAL(area_2_year_1_deltaLev_calculated, area_2_year_1_deltaLev_expected); - BOOST_CHECK_EQUAL(area_2_year_2_deltaLev_calculated, area_2_year_2_deltaLev_expected); + CheckFinalReservoirLevelsConfiguration(*study); + + // Checks on Area 1 modifier + BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.isApplicable(0), true); + BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.isApplicable(1), true); + BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.deltaLevel.at(0), 2.3 - 3.4); + BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.deltaLevel.at(1), 4.2 - 5.1); + + // Checks on Area 2 modifier + BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.isApplicable(0), true); + BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.isApplicable(1), true); + BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.deltaLevel.at(0), 1.5 - 3.5); + BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.deltaLevel.at(1), 2.4 - 4.3); } BOOST_AUTO_TEST_SUITE_END() \ No newline at end of file From 6827cb4b847e4c82cb5cfbb25f4d5625800a07be Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Fri, 11 Aug 2023 13:30:05 +0200 Subject: [PATCH 471/490] [skip ci] Hydro final lvl (CR 25) - try improvement : re-ordering a class without change --- .../parts/hydro/finallevelinflowsmodifyer.h | 48 +++++++++---------- 1 file changed, 22 insertions(+), 26 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 3165467d3f..343729aa0a 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -45,31 +45,21 @@ class FinalLevelInflowsModifier FinalLevelInflowsModifier(const PartHydro& hydro, const unsigned int& areaIndex, const AreaName& areaName); + void initialize(const Matrix& scenarioInitialHydroLevels, + const Matrix& scenarioFinalHydroLevels, + const uint lastSimulationDay, + const uint nbYears); -private: - uint lastSimulationDay_ = 0; - - // Data from area (remaining unchanged throughout simulation) - const PartHydro& hydro_; - const unsigned int& areaIndex_; - const AreaName& areaName_; - const Matrix::ColumnType* InitialLevels_ = nullptr; - const Matrix::ColumnType* FinalLevels_ = nullptr; - - - // Data changing at each MC year - double initialReservoirLevel_ = -1.; - double finalReservoirLevel_ = -1.; - double deltaReservoirLevel_; - - std::vector isApplicable_; + bool CheckInfeasibility(uint year); + bool isApplicable(uint year); + bool isActive(); -public: // vectors containing data necessary for final reservoir level calculation // for one area and all MC years // vector indexes correspond to the MC years std::vector deltaLevel; + private: void ComputeDelta(uint year); bool makeChecks(uint year); @@ -79,15 +69,21 @@ class FinalLevelInflowsModifier bool preCheckYearlyInflow(double totalYearInflows, uint year) const; bool preCheckRuleCurves(uint year) const; -public: - void initialize(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay, - const uint nbYears); + uint lastSimulationDay_ = 0; - bool CheckInfeasibility(uint year); - bool isApplicable(uint year); - bool isActive(); + // Data from area (remaining unchanged throughout simulation) + const PartHydro& hydro_; + const unsigned int& areaIndex_; + const AreaName& areaName_; + const Matrix::ColumnType* InitialLevels_ = nullptr; + const Matrix::ColumnType* FinalLevels_ = nullptr; + + // Data changing at each MC year + double initialReservoirLevel_ = -1.; + double finalReservoirLevel_ = -1.; + double deltaReservoirLevel_; + + std::vector isApplicable_; }; } // namespace Antares::Data From 46f99485d222b0a132950d2cda933f93a79ec694 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Fri, 11 Aug 2023 15:09:58 +0200 Subject: [PATCH 472/490] Hydro final lvl (CR 25) - try improvement : fix a bug --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 4 +++- 1 file changed, 3 insertions(+), 1 deletion(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index d6e7777999..4845a67eac 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -167,7 +167,9 @@ bool FinalLevelInflowsModifier::makeChecks(uint year) bool FinalLevelInflowsModifier::isApplicable(uint year) { - return isApplicable_.at(year); + // If isApplicable_.size() == 0, then instance was not properly initialized + // and is not applicable. + return isApplicable_.size() && isApplicable_.at(year); } } // namespace Antares::Data From a12ce37fbbeae7291f297d1e46acf1a20bc7ccdd Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Fri, 11 Aug 2023 15:45:04 +0200 Subject: [PATCH 473/490] Hydro final lvl (CR 25) - try improvement : add a new test : when final level modifier not initialized, it cannot be applicable --- .../test-hydro-final-reservoir-level-functions.cpp | 7 +++++++ 1 file changed, 7 insertions(+) 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 index b04d1a5bee..f35b5d5b3b 100644 --- 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 @@ -169,6 +169,13 @@ BOOST_AUTO_TEST_CASE(initial_level_from_scenariobuilder_is_NaN_for_area_1_and_ye BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); } +BOOST_AUTO_TEST_CASE(final_level_modifier_not_initialized____modifier_not_applicable) +{ + auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); + uint year = 0; + BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); +} + BOOST_AUTO_TEST_CASE(checking_level_configuration_is_ok_for_area_1_and_year_0___delta_level_as_expected) { uint year = 0; From 31a444c18522b6bb51cc75d0b44216b9fa3a3ef0 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Fri, 11 Aug 2023 16:28:26 +0200 Subject: [PATCH 474/490] Hydro final lvl (CR 25) - try improvement : make isActive private, reducing the class interface --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 2 +- .../parts/hydro/finallevelinflowsmodifyer.h | 2 +- ...est-hydro-final-reservoir-level-functions.cpp | 16 ++++++++-------- 3 files changed, 10 insertions(+), 10 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 4845a67eac..8d981967a4 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -169,7 +169,7 @@ bool FinalLevelInflowsModifier::isApplicable(uint year) { // If isApplicable_.size() == 0, then instance was not properly initialized // and is not applicable. - return isApplicable_.size() && isApplicable_.at(year); + return isActive() && isApplicable_.size() && isApplicable_.at(year); } } // namespace Antares::Data diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 343729aa0a..ecd29ea2de 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -52,7 +52,6 @@ class FinalLevelInflowsModifier bool CheckInfeasibility(uint year); bool isApplicable(uint year); - bool isActive(); // vectors containing data necessary for final reservoir level calculation // for one area and all MC years @@ -61,6 +60,7 @@ class FinalLevelInflowsModifier private: + bool isActive(); void ComputeDelta(uint year); bool makeChecks(uint year); void storeDeltaLevels(uint year); 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 index f35b5d5b3b..f926eaeb23 100644 --- 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 @@ -101,7 +101,7 @@ struct Fixture BOOST_FIXTURE_TEST_SUITE(s, Fixture) -BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) +BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_applicable) { uint year = 0; auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); @@ -113,10 +113,10 @@ BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_active) finLevInfModify.CheckInfeasibility(year); - BOOST_CHECK_EQUAL(finLevInfModify.isActive(), true); + BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), true); } -BOOST_AUTO_TEST_CASE(reservoir_management_is_false_for_area_1___modifier_is_not_active) +BOOST_AUTO_TEST_CASE(reservoir_management_is_false_for_area_1___modifier_is_not_applicable) { area_1->hydro.reservoirManagement = false; uint year = 0; @@ -131,10 +131,10 @@ BOOST_AUTO_TEST_CASE(reservoir_management_is_false_for_area_1___modifier_is_not_ finLevInfModify.CheckInfeasibility(year); // check when reservoirManagement = false - BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); + BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); } -BOOST_AUTO_TEST_CASE(use_water_value_is_true_for_area_1___modifier_is_not_active) +BOOST_AUTO_TEST_CASE(use_water_value_is_true_for_area_1___modifier_is_not_applicable) { area_1->hydro.useWaterValue = true; uint year = 0; @@ -149,10 +149,10 @@ BOOST_AUTO_TEST_CASE(use_water_value_is_true_for_area_1___modifier_is_not_active finLevInfModify.CheckInfeasibility(year); // check when useWaterValue = true - BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); + BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); } -BOOST_AUTO_TEST_CASE(initial_level_from_scenariobuilder_is_NaN_for_area_1_and_year_0____modifier_is_not_active) +BOOST_AUTO_TEST_CASE(initial_level_from_scenariobuilder_is_NaN_for_area_1_and_year_0____modifier_not_applicable) { uint year = 0; study->scenarioInitialHydroLevels[area_1->index][year] = std::numeric_limits::quiet_NaN(); @@ -166,7 +166,7 @@ BOOST_AUTO_TEST_CASE(initial_level_from_scenariobuilder_is_NaN_for_area_1_and_ye finLevInfModify.CheckInfeasibility(year); - BOOST_CHECK_EQUAL(finLevInfModify.isActive(), false); + BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); } BOOST_AUTO_TEST_CASE(final_level_modifier_not_initialized____modifier_not_applicable) From 67ac666d47df90651d95908451c9002a5569408e Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 17 Aug 2023 10:28:55 +0200 Subject: [PATCH 475/490] Hydro final lvl (CR 25) - try improvement : correction after review --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 8d981967a4..568d6b067d 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -33,7 +33,7 @@ namespace Antares::Data bool isValidLevel(double level) { - return (level < 0. || isnan(level)) ? false : true; + return level >= 0. && !isnan(level); } FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, @@ -132,8 +132,8 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial const uint lastSimulationDay, const uint nbYears) { - isApplicable_ = std::move(std::vector(nbYears, false)); - deltaLevel = std::move(std::vector(nbYears, 0.)); + isApplicable_.assign(nbYears, false); + deltaLevel.assign(nbYears, 0.); InitialLevels_ = &(scenarioInitialHydroLevels.entry[areaIndex_]); FinalLevels_ = &(scenarioFinalHydroLevels.entry[areaIndex_]); lastSimulationDay_ = lastSimulationDay; From 3de3bcf9df6714cabe70c5c4ea841dfa013e9530 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 17 Aug 2023 11:06:01 +0200 Subject: [PATCH 476/490] refactor isValidLevel & initialize --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 8d981967a4..0c16a979d7 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -33,7 +33,7 @@ namespace Antares::Data bool isValidLevel(double level) { - return (level < 0. || isnan(level)) ? false : true; + return level >= 0. && !isnan(level); } FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, @@ -132,8 +132,8 @@ void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitial const uint lastSimulationDay, const uint nbYears) { - isApplicable_ = std::move(std::vector(nbYears, false)); - deltaLevel = std::move(std::vector(nbYears, 0.)); + isApplicable_.assign(nbYears, false); + deltaLevel.assign(nbYears, 0.); InitialLevels_ = &(scenarioInitialHydroLevels.entry[areaIndex_]); FinalLevels_ = &(scenarioFinalHydroLevels.entry[areaIndex_]); lastSimulationDay_ = lastSimulationDay; From d7811fce569ebb7ae4ab950d60a4205fb1d6a5a8 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 17 Aug 2023 11:06:20 +0200 Subject: [PATCH 477/490] make study const --- .../simulation/hydro-final-reservoir-level-functions.cpp | 6 +++--- .../simulation/hydro-final-reservoir-level-functions.h | 2 +- 2 files changed, 4 insertions(+), 4 deletions(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 4edfcd1a70..774dff9742 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -31,7 +31,7 @@ namespace Antares::Solver { -void initializeFinalLevelData(Data::Study& study) +void initializeFinalLevelData(const Data::Study& study) { study.areas.each([&study](Data::Area& area) { @@ -42,7 +42,7 @@ void initializeFinalLevelData(Data::Study& study) }); } -void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) +void CheckFinalReservoirLevelsForYear(const Data::Study& study, uint year) { study.areas.each([&study, &year](Data::Area& area) { @@ -54,7 +54,7 @@ void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) } -void CheckFinalReservoirLevelsConfiguration(Data::Study& study) +void CheckFinalReservoirLevelsConfiguration(const Data::Study& study) { initializeFinalLevelData(study); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 588d0dcb18..29c0882114 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -31,7 +31,7 @@ namespace Antares::Solver { -void CheckFinalReservoirLevelsConfiguration(Data::Study& study); +void CheckFinalReservoirLevelsConfiguration(const Data::Study& study); } // namespace Antares::Solver #endif // __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ From 07d85d77e0350c0af967fae5aae3f4a48e2bd767 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 17 Aug 2023 12:04:29 +0200 Subject: [PATCH 478/490] Hydro final lvl (CR 25) - try improvement : correction after merge --- src/libs/antares/study/area/area.cpp | 3 +++ .../antares/study/scenario-builder/rules.cpp | 4 ++-- .../hydro-final-reservoir-level-functions.cpp | 4 ++-- .../test-sc-builder-file-read-line.cpp | 8 +++----- .../test-sc-builder-file-save.cpp | 20 +++++++++---------- 5 files changed, 19 insertions(+), 20 deletions(-) diff --git a/src/libs/antares/study/area/area.cpp b/src/libs/antares/study/area/area.cpp index 8c977b2f38..c865633a3b 100644 --- a/src/libs/antares/study/area/area.cpp +++ b/src/libs/antares/study/area/area.cpp @@ -45,6 +45,7 @@ void Area::internalInitialize() } Area::Area() : + hydro(*this), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR) { @@ -52,6 +53,7 @@ Area::Area() : } Area::Area(const AnyString& name) : + hydro(*this), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR) { @@ -61,6 +63,7 @@ Area::Area(const AnyString& name) : } Area::Area(const AnyString& name, const AnyString& id, uint indx) : + hydro(*this), reserves(fhrMax, HOURS_PER_YEAR), miscGen(fhhMax, HOURS_PER_YEAR) { diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index 7cb483fc1c..b9707e703f 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -269,7 +269,7 @@ bool Rules::readInitialHydroLevels(const AreaName::Vector& splitKey, String valu return false; double val = fromStringToHydroLevel(value, 1.); - hydroLevels.setTSnumber(area->index, year, val); + hydroInitialLevels.setTSnumber(area->index, year, val); return true; } @@ -283,7 +283,7 @@ bool Rules::readFinalHydroLevels(const AreaName::Vector& splitKey, String value, return false; double finalLevel = fromStringToHydroLevel(value, 1.); - hydroFinalLevels.set(area->index, year, finalLevel); + hydroFinalLevels.setTSnumber(area->index, year, finalLevel); return true; } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 4edfcd1a70..9e017abb7c 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -26,7 +26,7 @@ */ #include "hydro-final-reservoir-level-functions.h" -#include +#include namespace Antares::Solver { @@ -48,7 +48,7 @@ void CheckFinalReservoirLevelsForYear(Data::Study& study, uint year) { if (!area.hydro.finalLevelInflowsModifier.CheckInfeasibility(year)) { - AntaresSolverEmergencyShutdown(); + throw FatalError("hydro final level : infeasibility"); } }); 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 9bbe2491ff..fa99a05034 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 @@ -353,7 +353,7 @@ BOOST_FIXTURE_TEST_CASE(on_area3_and_on_year_5__hydro_level_neg_3_5_is_chosen__l // ======================== // Tests on Hydro final levels // ======================== -BOOST_AUTO_TEST_CASE(on_area1_and_on_year_8__hydro_level_0_342_is_chosen__reading_OK) +BOOST_FIXTURE_TEST_CASE(on_area1_and_on_year_8__hydro_level_0_342_is_chosen__reading_OK, Fixture) { AreaName yearNumber = "8"; String level = "0.342"; @@ -368,8 +368,7 @@ BOOST_AUTO_TEST_CASE(on_area1_and_on_year_8__hydro_level_0_342_is_chosen__readin level.to()); } -BOOST_AUTO_TEST_CASE( - on_area2_and_on_year_1__hydro_level_2_4_is_chosen_level_lowered_to_1__reading_OK) +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 = "1"; String level = "2.4"; @@ -384,8 +383,7 @@ BOOST_AUTO_TEST_CASE( 1.); } -BOOST_AUTO_TEST_CASE( - on_area3_and_on_year_3__hydro_level_neg_5_2_is_chosen__level_raised_to_0__reading_OK) +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"; 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 7cf2f4e4d8..169ce3fc6f 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 @@ -397,12 +397,11 @@ BOOST_FIXTURE_TEST_CASE( // ======================== // 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) +BOOST_FIXTURE_TEST_CASE(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(); @@ -419,12 +418,11 @@ BOOST_FIXTURE_TEST_CASE( // ======================== // Tests on Hydro final levels // ======================== -BOOST_AUTO_TEST_CASE( - HYDRO_FINAL_LEVEL__TS_number_for_many_areas_and_years__generated_and_ref_sc_buider_files_are_identical) +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.set(area_1->index, 4, 8); - my_rule->hydroFinalLevels.set(area_2->index, 11, 3); - my_rule->hydroFinalLevels.set(area_3->index, 15, 2); + 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(); @@ -497,7 +495,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(); From 5c297a09d3e9e8dd82ea3d68daf08f799af1adb4 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 17 Aug 2023 13:44:04 +0200 Subject: [PATCH 479/490] Correcting sub module vcpkg --- vcpkg | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/vcpkg b/vcpkg index 501db0f17e..9d47b24eac 160000 --- a/vcpkg +++ b/vcpkg @@ -1 +1 @@ -Subproject commit 501db0f17ef6df184fcdbfbe0f87cde2313b6ab1 +Subproject commit 9d47b24eacbd1cd94f139457ef6cd35e5d92cc84 From a6220800eb00cebe589bd8d5459988a355c634dd Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 17 Aug 2023 13:56:23 +0200 Subject: [PATCH 480/490] [skip ci] Hydro final lvl (CR 25) - try improvement : very small cleaning --- src/solver/simulation/hydro-final-reservoir-level-functions.cpp | 1 - 1 file changed, 1 deletion(-) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index e840549c42..09735e0990 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -51,7 +51,6 @@ void CheckFinalReservoirLevelsForYear(const Data::Study& study, uint year) throw FatalError("hydro final level : infeasibility"); } }); - } void CheckFinalReservoirLevelsConfiguration(const Data::Study& study) From c4a9eaa1504ba5714ab90f2483ac5ab54f8cd480 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 14 Sep 2023 17:41:03 +0200 Subject: [PATCH 481/490] Hydro final lvl (CR 25) - try improvement : correction after merge --- src/CMakeLists.txt | 1 + src/libs/antares/study/CMakeLists.txt | 2 ++ .../parts/hydro/finallevelinflowsmodifyer.cpp | 26 +++++++++---------- .../parts/hydro/finallevelinflowsmodifyer.h | 26 +++++++++---------- .../hydro-final-reservoir-level-functions.h | 2 +- .../src/solver/simulation/CMakeLists.txt | 5 ++-- ...-hydro-final-reservoir-level-functions.cpp | 2 +- 7 files changed, 33 insertions(+), 31 deletions(-) diff --git a/src/CMakeLists.txt b/src/CMakeLists.txt index 077445d3b7..e734092e4e 100644 --- a/src/CMakeLists.txt +++ b/src/CMakeLists.txt @@ -5,6 +5,7 @@ set(ANTARES_VERSION_HI 8) set(ANTARES_VERSION_LO 7) set(ANTARES_VERSION_REVISION 0) + # Beta release set(ANTARES_BETA 0) set(ANTARES_RC 0) diff --git a/src/libs/antares/study/CMakeLists.txt b/src/libs/antares/study/CMakeLists.txt index 0f0dbaa197..2fac217506 100644 --- a/src/libs/antares/study/CMakeLists.txt +++ b/src/libs/antares/study/CMakeLists.txt @@ -254,6 +254,8 @@ set(SRC_STUDY_PART_HYDRO parts/hydro/allocation.h parts/hydro/allocation.hxx parts/hydro/allocation.cpp + parts/hydro/finallevelinflowsmodifyer.h + parts/hydro/finallevelinflowsmodifyer.cpp ) source_group("study\\part\\hydro" FILES ${SRC_STUDY_PART_HYDRO}) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 568d6b067d..36b6809c98 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -43,7 +43,7 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, { } -bool FinalLevelInflowsModifier::CheckInfeasibility(uint year) +bool FinalLevelInflowsModifier::CheckInfeasibility(unsigned int year) { ComputeDelta(year); @@ -58,33 +58,33 @@ bool FinalLevelInflowsModifier::CheckInfeasibility(uint year) } -void FinalLevelInflowsModifier::ComputeDelta(uint year) +void FinalLevelInflowsModifier::ComputeDelta(unsigned int year) { initialReservoirLevel_ = (*InitialLevels_)[year]; finalReservoirLevel_ = (*FinalLevels_)[year]; deltaReservoirLevel_ = initialReservoirLevel_ - finalReservoirLevel_; } -void FinalLevelInflowsModifier::storeDeltaLevels(uint year) +void FinalLevelInflowsModifier::storeDeltaLevels(unsigned int year) { deltaLevel.at(year) = deltaReservoirLevel_; } -double FinalLevelInflowsModifier::calculateTotalInflows(uint year) const +double FinalLevelInflowsModifier::calculateTotalInflows(unsigned int year) const { // calculate yearly inflows const Data::DataSeriesHydro& data = *hydro_.series; - uint tsHydroIndex = data.timeseriesNumbers[0][year]; + unsigned int tsHydroIndex = data.timeseriesNumbers[0][year]; auto& inflowsmatrix = hydro_.series->storage; auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; double totalYearInflows = 0.0; - for (uint day = 0; day < DAYS_PER_YEAR; ++day) + for (unsigned int day = 0; day < DAYS_PER_YEAR; ++day) totalYearInflows += srcinflows[day]; return totalYearInflows; } -bool FinalLevelInflowsModifier::preCheckStartAndEndSim(uint year) const +bool FinalLevelInflowsModifier::preCheckStartAndEndSim(unsigned int year) const { int initReservoirLvlMonth = hydro_.initializeReservoirLevelDate; // month [0-11] @@ -97,7 +97,7 @@ bool FinalLevelInflowsModifier::preCheckStartAndEndSim(uint year) const return false; } -bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows, uint year) const +bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows, unsigned int year) const { double reservoirCapacity = hydro_.reservoirCapacity; if (-deltaReservoirLevel_ * reservoirCapacity > totalYearInflows) @@ -111,7 +111,7 @@ bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows, ui return true; } -bool FinalLevelInflowsModifier::preCheckRuleCurves(uint year) const +bool FinalLevelInflowsModifier::preCheckRuleCurves(unsigned int year) const { double lowLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; double highLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; @@ -129,8 +129,8 @@ bool FinalLevelInflowsModifier::preCheckRuleCurves(uint year) const void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay, - const uint nbYears) + const unsigned int lastSimulationDay, + const unsigned int nbYears) { isApplicable_.assign(nbYears, false); deltaLevel.assign(nbYears, 0.); @@ -147,7 +147,7 @@ bool FinalLevelInflowsModifier::isActive() isValidLevel(initialReservoirLevel_); } -bool FinalLevelInflowsModifier::makeChecks(uint year) +bool FinalLevelInflowsModifier::makeChecks(unsigned int year) { // Simulation must end on day 365 and reservoir level must be initiated in January bool checksOk = preCheckStartAndEndSim(year); @@ -165,7 +165,7 @@ bool FinalLevelInflowsModifier::makeChecks(uint year) return checksOk; } -bool FinalLevelInflowsModifier::isApplicable(uint year) +bool FinalLevelInflowsModifier::isApplicable(unsigned int year) { // If isApplicable_.size() == 0, then instance was not properly initialized // and is not applicable. diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index ecd29ea2de..0c9f3e3708 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -28,8 +28,6 @@ #define __ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__ #include -#include -#include #include namespace Antares::Data @@ -47,11 +45,11 @@ class FinalLevelInflowsModifier const AreaName& areaName); void initialize(const Matrix& scenarioInitialHydroLevels, const Matrix& scenarioFinalHydroLevels, - const uint lastSimulationDay, - const uint nbYears); + const unsigned int lastSimulationDay, + const unsigned int nbYears); - bool CheckInfeasibility(uint year); - bool isApplicable(uint year); + bool CheckInfeasibility(unsigned int year); + bool isApplicable(unsigned int year); // vectors containing data necessary for final reservoir level calculation // for one area and all MC years @@ -61,15 +59,15 @@ class FinalLevelInflowsModifier private: bool isActive(); - void ComputeDelta(uint year); - bool makeChecks(uint year); - void storeDeltaLevels(uint year); - double calculateTotalInflows(uint year) const; - bool preCheckStartAndEndSim(uint year) const; - bool preCheckYearlyInflow(double totalYearInflows, uint year) const; - bool preCheckRuleCurves(uint year) const; + void ComputeDelta(unsigned int year); + bool makeChecks(unsigned int year); + void storeDeltaLevels(unsigned int year); + double calculateTotalInflows(unsigned int year) const; + bool preCheckStartAndEndSim(unsigned int year) const; + bool preCheckYearlyInflow(double totalYearInflows, unsigned int year) const; + bool preCheckRuleCurves(unsigned int year) const; - uint lastSimulationDay_ = 0; + unsigned int lastSimulationDay_ = 0; // Data from area (remaining unchanged throughout simulation) const PartHydro& hydro_; diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/hydro-final-reservoir-level-functions.h index 29c0882114..93518bf2d0 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.h @@ -27,7 +27,7 @@ #ifndef __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ #define __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ -#include +#include namespace Antares::Solver { diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index f27664875e..74ceea6ef6 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -107,8 +107,9 @@ target_include_directories(test-hydro_final target_link_libraries(test-hydro_final PRIVATE Boost::unit_test_framework - libantares-core - libantares-solver-simulation + Antares::study + antares-solver-simulation + Antares::array ) # Linux 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 index f926eaeb23..4edf657601 100644 --- 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 @@ -7,7 +7,7 @@ #include #include "hydro-final-reservoir-level-functions.h" -#include +#include using namespace Antares::Solver; using namespace Antares::Data; From ddd1fdc23700aa7ca41f31d136e6c19604ccc329 Mon Sep 17 00:00:00 2001 From: Milos <97689304+Milos-RTEi@users.noreply.github.com> Date: Thu, 28 Sep 2023 14:50:14 +0200 Subject: [PATCH 482/490] Update Final reservoir level implementation - cr25 (#1564) * fix - isApplicable * add logs if fin-lvl not applicable * fix - only check active years * fix - failed unit test yearFilter * refactor unit test * improve info log + refactor * CR-25 - add-info : correction after merge from develop --------- Co-authored-by: Guillaume PIERRE --- .../parts/hydro/finallevelinflowsmodifyer.cpp | 17 ++++++++++++++++- .../parts/hydro/finallevelinflowsmodifyer.h | 1 + .../hydro-final-reservoir-level-functions.cpp | 5 +++-- ...st-hydro-final-reservoir-level-functions.cpp | 2 ++ 4 files changed, 22 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 36b6809c98..83648840c0 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -46,6 +46,7 @@ FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, bool FinalLevelInflowsModifier::CheckInfeasibility(unsigned int year) { ComputeDelta(year); + logInfoFinLvlNotApplicable(year); if (!isActive()) return true; @@ -147,6 +148,20 @@ bool FinalLevelInflowsModifier::isActive() isValidLevel(initialReservoirLevel_); } +// if the user specifies the final reservoir level, but does not specifies initial reservoir level +// or uses wrong hydro options +// we should inform the user that the final reservoir level wont be reached +void FinalLevelInflowsModifier::logInfoFinLvlNotApplicable(unsigned int year) +{ + if (isValidLevel(finalReservoirLevel_) + && (!hydro_.reservoirManagement || hydro_.useWaterValue + || !isValidLevel(initialReservoirLevel_))) + logs.info() << "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 "; +} + bool FinalLevelInflowsModifier::makeChecks(unsigned int year) { // Simulation must end on day 365 and reservoir level must be initiated in January @@ -169,7 +184,7 @@ bool FinalLevelInflowsModifier::isApplicable(unsigned int year) { // If isApplicable_.size() == 0, then instance was not properly initialized // and is not applicable. - return isActive() && isApplicable_.size() && isApplicable_.at(year); + return !isApplicable_.empty() && isApplicable_.at(year); } } // namespace Antares::Data diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 0c9f3e3708..492c313448 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -59,6 +59,7 @@ class FinalLevelInflowsModifier private: bool isActive(); + void logInfoFinLvlNotApplicable(uint year); void ComputeDelta(unsigned int year); bool makeChecks(unsigned int year); void storeDeltaLevels(unsigned int year); diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 09735e0990..8fada405e0 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -56,12 +56,13 @@ void CheckFinalReservoirLevelsForYear(const Data::Study& study, uint year) void CheckFinalReservoirLevelsConfiguration(const Data::Study& study) { initializeFinalLevelData(study); - + uint nbYears = study.parameters.nbYears; for (uint year = 0; year != nbYears; ++year) { - CheckFinalReservoirLevelsForYear(study, year); + if (study.parameters.yearsFilter.at(year)) + CheckFinalReservoirLevelsForYear(study, year); } } 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 index 4edf657601..58450ce096 100644 --- 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 @@ -55,6 +55,8 @@ struct Fixture // ------------------------------------------------------- uint areasCount = study->areas.size(); + study->parameters.yearsFilter.assign(2, true); + study->scenarioInitialHydroLevels.resize(nbYears, areasCount); study->scenarioFinalHydroLevels.resize(nbYears, areasCount); From d98717c62c3631c9f2167e835048278cc94adcf5 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Fri, 27 Oct 2023 11:44:13 +0200 Subject: [PATCH 483/490] bug fix - after merge develop --- .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 5 +---- .../test-hydro-final-reservoir-level-functions.cpp | 4 ++-- 2 files changed, 3 insertions(+), 6 deletions(-) diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 83648840c0..2b832bda75 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -74,10 +74,7 @@ void FinalLevelInflowsModifier::storeDeltaLevels(unsigned int year) double FinalLevelInflowsModifier::calculateTotalInflows(unsigned int year) const { // calculate yearly inflows - const Data::DataSeriesHydro& data = *hydro_.series; - unsigned int tsHydroIndex = data.timeseriesNumbers[0][year]; - auto& inflowsmatrix = hydro_.series->storage; - auto& srcinflows = inflowsmatrix[tsHydroIndex < inflowsmatrix.width ? tsHydroIndex : 0]; + auto const& srcinflows = hydro_.series->storage.getColumn(year); double totalYearInflows = 0.0; for (unsigned int day = 0; day < DAYS_PER_YEAR; ++day) 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 index 58450ce096..2192ada4a2 100644 --- 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 @@ -79,7 +79,7 @@ struct Fixture area_1->hydro.series->timeseriesNumbers[0][1] = 1; // ... Area 1 : Inflows time series area_1->hydro.series->storage.resize(nbInflowTS, 365); - area_1->hydro.series->storage.fill(200.); + 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.; @@ -89,7 +89,7 @@ struct Fixture area_2->hydro.series->timeseriesNumbers[0][1] = 1; // ... Area 2 : Inflows time series area_2->hydro.series->storage.resize(nbInflowTS, 365); - area_2->hydro.series->storage.fill(300.); + 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.; } From c07364900a7f0bcc86fc5c9cc52e32eeff593172 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Wed, 15 Nov 2023 17:31:34 +0100 Subject: [PATCH 484/490] remove numspace from changeInflowsToAccommodateFinalLevels --- src/solver/hydro/management/management.cpp | 8 ++++---- src/solver/hydro/management/management.h | 2 +- 2 files changed, 5 insertions(+), 5 deletions(-) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 9172c6d80c..b2c5c203ef 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -376,11 +376,11 @@ bool HydroManagement::checkMinGeneration(uint year) const return ret; } -void HydroManagement::changeInflowsToAccommodateFinalLevels(uint numSpace, uint year) +void HydroManagement::changeInflowsToAccommodateFinalLevels(uint year) { - areas_.each([this, &numSpace, &year](Data::Area& area) + areas_.each([this, &year](Data::Area& area) { - auto& data = tmpDataByArea_[numSpace][area.index]; + auto& data = tmpDataByArea_[area.index]; if (!area.hydro.finalLevelInflowsModifier.isApplicable(year)) return; @@ -523,7 +523,7 @@ void HydroManagement::makeVentilation(double* randomReservoirLevel, throw FatalError("hydro management: invalid minimum generation"); } - changeInflowsToAccommodateFinalLevels(numSpace, y); + changeInflowsToAccommodateFinalLevels(y); prepareNetDemand(numSpace, y, parameters_.mode); prepareEffectiveDemand(); diff --git a/src/solver/hydro/management/management.h b/src/solver/hydro/management/management.h index eeb95bb919..77759ec170 100644 --- a/src/solver/hydro/management/management.h +++ b/src/solver/hydro/management/management.h @@ -123,7 +123,7 @@ class HydroManagement final //! Prepare inflows scaling for each area void prepareInflowsScaling(uint year); //! prepare data for Final reservoir level - void changeInflowsToAccommodateFinalLevels(uint numSpace, uint yearIndex); + void changeInflowsToAccommodateFinalLevels(uint yearIndex); //! Prepare minimum generation scaling for each area void minGenerationScaling(uint year); //! check Monthly minimum generation is lower than available inflows From 32e540ab93a943b93f955c3876256fd4e0dea1f6 Mon Sep 17 00:00:00 2001 From: Milos-RTEi Date: Thu, 18 Jan 2024 19:14:57 +0100 Subject: [PATCH 485/490] fix after merge - tmpDataByArea_ now accepts pointer to Area not area index --- src/solver/hydro/management/management.cpp | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index 85609f9d6a..90788819a9 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -376,7 +376,7 @@ void HydroManagement::changeInflowsToAccommodateFinalLevels(uint year) { areas_.each([this, &year](Data::Area& area) { - auto& data = tmpDataByArea_[area.index]; + auto& data = tmpDataByArea_[&area]; if (!area.hydro.finalLevelInflowsModifier.isApplicable(year)) return; From 90092c34da304f6bc2d0680d5b31d260f4adfa5b Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Thu, 11 Apr 2024 16:42:30 +0200 Subject: [PATCH 486/490] CR 25 (hydro final level) : correction after merge --- src/libs/antares/study/CMakeLists.txt | 2 +- .../antares/study}/parts/hydro/finallevelinflowsmodifyer.h | 1 + .../antares/study/parts/hydro/finallevelinflowsmodifyer.cpp | 4 ++-- src/solver/simulation/CMakeLists.txt | 2 +- .../simulation/hydro-final-reservoir-level-functions.cpp | 4 ++-- .../simulation}/hydro-final-reservoir-level-functions.h | 2 +- src/tests/src/solver/simulation/CMakeLists.txt | 2 +- .../simulation/test-hydro-final-reservoir-level-functions.cpp | 2 +- 8 files changed, 10 insertions(+), 9 deletions(-) rename src/libs/antares/study/{ => include/antares/study}/parts/hydro/finallevelinflowsmodifyer.h (99%) rename src/solver/simulation/{ => include/antares/solver/simulation}/hydro-final-reservoir-level-functions.h (97%) diff --git a/src/libs/antares/study/CMakeLists.txt b/src/libs/antares/study/CMakeLists.txt index 2f85cef5f6..0c8935648b 100644 --- a/src/libs/antares/study/CMakeLists.txt +++ b/src/libs/antares/study/CMakeLists.txt @@ -127,7 +127,7 @@ set(SRC_STUDY_PART_HYDRO include/antares/study/parts/hydro/allocation.h include/antares/study/parts/hydro/allocation.hxx parts/hydro/allocation.cpp - parts/hydro/finallevelinflowsmodifyer.h + include/antares/study/parts/hydro/finallevelinflowsmodifyer.h parts/hydro/finallevelinflowsmodifyer.cpp include/antares/study/parts/hydro/hydromaxtimeseriesreader.h parts/hydro/hydromaxtimeseriesreader.cpp diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h b/src/libs/antares/study/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h similarity index 99% rename from src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h rename to src/libs/antares/study/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h index 492c313448..670357dd3c 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ b/src/libs/antares/study/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h @@ -33,6 +33,7 @@ namespace Antares::Data { class PartHydro; + /*! ** \brief Final Reservoir Level data for a single area */ diff --git a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp index 2b832bda75..d23e6678d9 100644 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp @@ -25,8 +25,8 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#include "finallevelinflowsmodifyer.h" -#include "container.h" +#include "antares/study/parts/hydro/finallevelinflowsmodifyer.h" +#include "antares/study/parts/hydro/container.h" namespace Antares::Data { diff --git a/src/solver/simulation/CMakeLists.txt b/src/solver/simulation/CMakeLists.txt index 76920249a2..698c2258cc 100644 --- a/src/solver/simulation/CMakeLists.txt +++ b/src/solver/simulation/CMakeLists.txt @@ -44,7 +44,7 @@ set(SRC_SIMULATION include/antares/solver/simulation/adequacy_patch_runtime_data.h adequacy_patch_runtime_data.cpp include/antares/solver/simulation/ITimeSeriesNumbersWriter.h - hydro-final-reservoir-level-functions.h + include/antares/solver/simulation/hydro-final-reservoir-level-functions.h hydro-final-reservoir-level-functions.cpp TimeSeriesNumbersWriter.cpp include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h) diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index 8fada405e0..f8a43c3dff 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -25,8 +25,8 @@ ** SPDX-License-Identifier: licenceRef-GPL3_WITH_RTE-Exceptions */ -#include "hydro-final-reservoir-level-functions.h" -#include +#include "antares/solver/simulation/hydro-final-reservoir-level-functions.h" +#include namespace Antares::Solver { diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.h b/src/solver/simulation/include/antares/solver/simulation/hydro-final-reservoir-level-functions.h similarity index 97% rename from src/solver/simulation/hydro-final-reservoir-level-functions.h rename to src/solver/simulation/include/antares/solver/simulation/hydro-final-reservoir-level-functions.h index 93518bf2d0..4b60c4cc8f 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.h +++ b/src/solver/simulation/include/antares/solver/simulation/hydro-final-reservoir-level-functions.h @@ -27,7 +27,7 @@ #ifndef __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ #define __SOLVER_SIMULATION_HYDRO_FINAL_RESERVOIR_PRE_CHECKS_H__ -#include +#include "antares/study/study.h" namespace Antares::Solver { diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index 5d68ffcbb8..f8df8044d9 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -93,7 +93,7 @@ set_property(TEST time_series PROPERTY LABELS unit) # Tests on hydro final reservoir level functions # =================================== set(SRC_HYDRO_FINAL_LEVEL - ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.h + ${src_libs_antares_study}/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.cpp ) 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 index 2192ada4a2..035a54f52d 100644 --- 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 @@ -6,7 +6,7 @@ #define WIN32_LEAN_AND_MEAN #include -#include "hydro-final-reservoir-level-functions.h" +#include "include/antares/solver/simulation/hydro-final-reservoir-level-functions.h" #include using namespace Antares::Solver; From e12eb488fbd70a66903b1f9fefddcf813a2349b6 Mon Sep 17 00:00:00 2001 From: guilpier-code <62292552+guilpier-code@users.noreply.github.com> Date: Fri, 7 Jun 2024 09:09:45 +0200 Subject: [PATCH 487/490] Hydro final levels (CR 25) : corrections and cleaning (#2040) See comments to know more about this PR intentions. Furthermore, a study testing final levels can be found here below. Please read this study's user's notes for the test goals and how to fulfill them. [final-levels.zip](https://github.com/AntaresSimulatorTeam/Antares_Simulator/files/15126508/final-levels.zip) --- src/libs/antares/study/CMakeLists.txt | 4 +- .../antares/study/parts/hydro/container.h | 5 +- .../study/parts/hydro/finalLevelValidator.h | 73 +++++ .../parts/hydro/finallevelinflowsmodifyer.h | 90 ------- .../study/include/antares/study/parts/parts.h | 1 - .../study/scenario-builder/hydroLevelsData.h | 4 +- .../antares/study/scenario-builder/rules.h | 6 +- .../antares/study/parts/hydro/container.cpp | 4 +- .../study/parts/hydro/finalLevelValidator.cpp | 157 +++++++++++ .../parts/hydro/finallevelinflowsmodifyer.cpp | 187 ------------- .../scenario-builder/hydroLevelsData.cpp | 11 +- src/solver/hydro/management/management.cpp | 12 +- src/solver/hydro/management/monthly.cpp | 4 +- .../hydro-final-reservoir-level-functions.cpp | 59 ++-- .../end-to-end/simple_study/simple-study.cpp | 3 +- src/tests/end-to-end/utils/utils.cpp | 1 + .../src/solver/simulation/CMakeLists.txt | 8 +- ...-hydro-final-reservoir-level-functions.cpp | 253 ++++++++---------- 18 files changed, 402 insertions(+), 480 deletions(-) create mode 100644 src/libs/antares/study/include/antares/study/parts/hydro/finalLevelValidator.h delete mode 100644 src/libs/antares/study/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h create mode 100644 src/libs/antares/study/parts/hydro/finalLevelValidator.cpp delete mode 100644 src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp diff --git a/src/libs/antares/study/CMakeLists.txt b/src/libs/antares/study/CMakeLists.txt index 0c8935648b..d16672a72c 100644 --- a/src/libs/antares/study/CMakeLists.txt +++ b/src/libs/antares/study/CMakeLists.txt @@ -127,8 +127,8 @@ set(SRC_STUDY_PART_HYDRO include/antares/study/parts/hydro/allocation.h include/antares/study/parts/hydro/allocation.hxx parts/hydro/allocation.cpp - include/antares/study/parts/hydro/finallevelinflowsmodifyer.h - parts/hydro/finallevelinflowsmodifyer.cpp + include/antares/study/parts/hydro/finalLevelValidator.h + parts/hydro/finalLevelValidator.cpp include/antares/study/parts/hydro/hydromaxtimeseriesreader.h parts/hydro/hydromaxtimeseriesreader.cpp ) 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 index c1a23e4a53..5a287de348 100644 --- a/src/libs/antares/study/include/antares/study/parts/hydro/container.h +++ b/src/libs/antares/study/include/antares/study/parts/hydro/container.h @@ -21,11 +21,11 @@ #ifndef __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ #define __ANTARES_LIBS_STUDY_PARTS_HYDRO_CONTAINER_H__ +#include #include "prepro.h" #include "series.h" #include "../../fwd.h" #include "allocation.h" -#include "finallevelinflowsmodifyer.h" namespace Antares::Data { @@ -164,8 +164,7 @@ class PartHydro Matrix dailyNbHoursAtGenPmax; Matrix dailyNbHoursAtPumpPmax; - //! Data for final reservoir level - FinalLevelInflowsModifier finalLevelInflowsModifier; + std::vector> deltaBetweenFinalAndInitialLevels; }; // class PartHydro // Interpolates a water value from a table according to a level and a day. 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/finallevelinflowsmodifyer.h b/src/libs/antares/study/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h deleted file mode 100644 index 670357dd3c..0000000000 --- a/src/libs/antares/study/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h +++ /dev/null @@ -1,90 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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_FINAL_LEVEL_INFLOWS_MODIFYER_H__ -#define __ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__ - -#include -#include - -namespace Antares::Data -{ -class PartHydro; - -/*! - ** \brief Final Reservoir Level data for a single area - */ -class FinalLevelInflowsModifier -{ -public: - FinalLevelInflowsModifier() = delete; - FinalLevelInflowsModifier(const PartHydro& hydro, - const unsigned int& areaIndex, - const AreaName& areaName); - void initialize(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const unsigned int lastSimulationDay, - const unsigned int nbYears); - - bool CheckInfeasibility(unsigned int year); - bool isApplicable(unsigned int year); - - // vectors containing data necessary for final reservoir level calculation - // for one area and all MC years - // vector indexes correspond to the MC years - std::vector deltaLevel; - - -private: - bool isActive(); - void logInfoFinLvlNotApplicable(uint year); - void ComputeDelta(unsigned int year); - bool makeChecks(unsigned int year); - void storeDeltaLevels(unsigned int year); - double calculateTotalInflows(unsigned int year) const; - bool preCheckStartAndEndSim(unsigned int year) const; - bool preCheckYearlyInflow(double totalYearInflows, unsigned int year) const; - bool preCheckRuleCurves(unsigned int year) const; - - unsigned int lastSimulationDay_ = 0; - - // Data from area (remaining unchanged throughout simulation) - const PartHydro& hydro_; - const unsigned int& areaIndex_; - const AreaName& areaName_; - const Matrix::ColumnType* InitialLevels_ = nullptr; - const Matrix::ColumnType* FinalLevels_ = nullptr; - - // Data changing at each MC year - double initialReservoirLevel_ = -1.; - double finalReservoirLevel_ = -1.; - double deltaReservoirLevel_; - - std::vector isApplicable_; -}; -} // namespace Antares::Data - -#endif /*__ANTARES_LIBS_STUDY_PARTS_HYDRO_FINAL_LEVEL_INFLOWS_MODIFYER_H__*/ \ No newline at end of file diff --git a/src/libs/antares/study/include/antares/study/parts/parts.h b/src/libs/antares/study/include/antares/study/parts/parts.h index d247b60394..7f02083486 100644 --- a/src/libs/antares/study/include/antares/study/parts/parts.h +++ b/src/libs/antares/study/include/antares/study/parts/parts.h @@ -31,7 +31,6 @@ // Hydro #include "hydro/prepro.h" #include "hydro/series.h" -#include "hydro/finallevelinflowsmodifyer.h" #include "hydro/container.h" #include "hydro/hydromaxtimeseriesreader.h" 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 index 8f2b48c4e0..ae6c2d4b5a 100644 --- a/src/libs/antares/study/include/antares/study/scenario-builder/hydroLevelsData.h +++ b/src/libs/antares/study/include/antares/study/scenario-builder/hydroLevelsData.h @@ -42,7 +42,7 @@ class hydroLevelsData final : public dataInterface public: // Constructor - hydroLevelsData(std::string& iniFilePrefix, + hydroLevelsData(const std::string& iniFilePrefix, std::function applyToTarget); //! \name Data manupulation @@ -81,7 +81,7 @@ class hydroLevelsData final : public dataInterface //! Hydro levels overlay (0 if auto) MatrixType pHydroLevelsRules; // prefix to be added when calling saveToINIFileHydroLevel - std::string& addToPrefix; + const std::string addToPrefix_; std::function applyToTarget_; diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/rules.h b/src/libs/antares/study/include/antares/study/scenario-builder/rules.h index 400d549d9d..54f8453572 100644 --- a/src/libs/antares/study/include/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/include/antares/study/scenario-builder/rules.h @@ -121,11 +121,9 @@ class Rules final : private Yuni::NonCopyable std::vector renewable; //! hydro initial levels - std::string prefixInitial = "hl,"; - hydroLevelsData hydroInitialLevels = hydroLevelsData(prefixInitial, initLevelApply); + hydroLevelsData hydroInitialLevels = hydroLevelsData("hl,", initLevelApply); //! hydro final levels - std::string prefixFinal = "hfl,"; - hydroLevelsData hydroFinalLevels = hydroLevelsData(prefixFinal, finalLevelApply); + hydroLevelsData hydroFinalLevels = hydroLevelsData("hfl,", finalLevelApply); // Links NTC std::vector linksNTC; diff --git a/src/libs/antares/study/parts/hydro/container.cpp b/src/libs/antares/study/parts/hydro/container.cpp index 652226ae91..362bd91099 100644 --- a/src/libs/antares/study/parts/hydro/container.cpp +++ b/src/libs/antares/study/parts/hydro/container.cpp @@ -49,8 +49,7 @@ PartHydro::PartHydro(const Data::Area& area) : pumpingEfficiency(1.), hydroModulable(false), prepro(nullptr), - series(nullptr), - finalLevelInflowsModifier(*this, area.index, area.name) + series(nullptr) { } @@ -127,6 +126,7 @@ bool PartHydro::LoadFromFolder(Study& study, const AnyString& folder) 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)) { 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..50d21efac5 --- /dev/null +++ b/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp @@ -0,0 +1,157 @@ +/* +** Copyright 2007-2023 RTE +** Authors: Antares_Simulator Team +** +** This file is part of Antares_Simulator. +** +** Antares_Simulator is free software: you can redistribute it and/or modify +** it under the terms of the GNU General Public License as published by +** the Free Software Foundation, either version 3 of the License, or +** (at your option) any later version. +** +** There are special exceptions to the terms and conditions of the +** license as they are applied to this software. View the full text of +** the exceptions in file COPYING.txt in the directory of this software +** distribution +** +** Antares_Simulator is distributed in the hope that it will be useful, +** but WITHOUT ANY WARRANTY; without even the implied warranty of +** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the +** GNU General Public License for more details. +** +** You should have 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) + : hydro_(hydro), + areaName_(areaName), + areaIndex_(areaIndex), + initialLevel_(initialLevel), + finalLevel_(finalLevel), + year_(year), + lastSimulationDay_(lastSimulationDay), + firstMonthOfSimulation_(firstMonthOfSimulation) +{ +} + +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.info() << "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 +{ + int 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 + auto const& 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/finallevelinflowsmodifyer.cpp b/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp deleted file mode 100644 index d23e6678d9..0000000000 --- a/src/libs/antares/study/parts/hydro/finallevelinflowsmodifyer.cpp +++ /dev/null @@ -1,187 +0,0 @@ -/* -** Copyright 2007-2023 RTE -** Authors: Antares_Simulator Team -** -** This file is part of Antares_Simulator. -** -** Antares_Simulator is free software: you can redistribute it and/or modify -** it under the terms of the GNU General Public License as published by -** the Free Software Foundation, either version 3 of the License, or -** (at your option) any later version. -** -** There are special exceptions to the terms and conditions of the -** license as they are applied to this software. View the full text of -** the exceptions in file COPYING.txt in the directory of this software -** distribution -** -** Antares_Simulator is distributed in the hope that it will be useful, -** but WITHOUT ANY WARRANTY; without even the implied warranty of -** MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the -** GNU General Public License for more details. -** -** You should have 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/finallevelinflowsmodifyer.h" -#include "antares/study/parts/hydro/container.h" - -namespace Antares::Data -{ - -bool isValidLevel(double level) -{ - return level >= 0. && !isnan(level); -} - -FinalLevelInflowsModifier::FinalLevelInflowsModifier(const PartHydro& hydro, - const unsigned int& areaIndex, - const AreaName& areaName) : - hydro_(hydro), areaIndex_(areaIndex), areaName_(areaName) -{ -} - -bool FinalLevelInflowsModifier::CheckInfeasibility(unsigned int year) -{ - ComputeDelta(year); - logInfoFinLvlNotApplicable(year); - - if (!isActive()) - return true; - - if (!makeChecks(year)) - return false; - - storeDeltaLevels(year); - return true; - -} - -void FinalLevelInflowsModifier::ComputeDelta(unsigned int year) -{ - initialReservoirLevel_ = (*InitialLevels_)[year]; - finalReservoirLevel_ = (*FinalLevels_)[year]; - deltaReservoirLevel_ = initialReservoirLevel_ - finalReservoirLevel_; -} - -void FinalLevelInflowsModifier::storeDeltaLevels(unsigned int year) -{ - deltaLevel.at(year) = deltaReservoirLevel_; -} - -double FinalLevelInflowsModifier::calculateTotalInflows(unsigned int year) const -{ - // calculate yearly inflows - auto const& 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 FinalLevelInflowsModifier::preCheckStartAndEndSim(unsigned int year) const -{ - - int initReservoirLvlMonth = hydro_.initializeReservoirLevelDate; // month [0-11] - if (lastSimulationDay_ == DAYS_PER_YEAR && initReservoirLvlMonth == 0) - return true; - - logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ - << ". Simulation must end on day 365 and reservoir level must be " - "initiated in January"; - return false; -} - -bool FinalLevelInflowsModifier::preCheckYearlyInflow(double totalYearInflows, unsigned int year) const -{ - double reservoirCapacity = hydro_.reservoirCapacity; - if (-deltaReservoirLevel_ * reservoirCapacity > totalYearInflows) - { - logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ - << ". Incompatible total inflows: " << totalYearInflows - << " with initial: " << initialReservoirLevel_ - << " and final: " << finalReservoirLevel_ << " reservoir levels."; - return false; - } - return true; -} - -bool FinalLevelInflowsModifier::preCheckRuleCurves(unsigned int year) const -{ - double lowLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::minimum][DAYS_PER_YEAR - 1]; - double highLevelLastDay = hydro_.reservoirLevel[Data::PartHydro::maximum][DAYS_PER_YEAR - 1]; - - if (finalReservoirLevel_ < lowLevelLastDay || finalReservoirLevel_ > highLevelLastDay) - { - logs.error() << "Year: " << year + 1 << ". Area: " << areaName_ - << ". Specifed final reservoir level: " << finalReservoirLevel_ - << " is incompatible with reservoir level rule curve [" << lowLevelLastDay - << " , " << highLevelLastDay << "]"; - return false; - } - return true; -} - -void FinalLevelInflowsModifier::initialize(const Matrix& scenarioInitialHydroLevels, - const Matrix& scenarioFinalHydroLevels, - const unsigned int lastSimulationDay, - const unsigned int nbYears) -{ - isApplicable_.assign(nbYears, false); - deltaLevel.assign(nbYears, 0.); - InitialLevels_ = &(scenarioInitialHydroLevels.entry[areaIndex_]); - FinalLevels_ = &(scenarioFinalHydroLevels.entry[areaIndex_]); - lastSimulationDay_ = lastSimulationDay; -} - -bool FinalLevelInflowsModifier::isActive() -{ - return hydro_.reservoirManagement && - !hydro_.useWaterValue && - isValidLevel(finalReservoirLevel_) && - isValidLevel(initialReservoirLevel_); -} - -// if the user specifies the final reservoir level, but does not specifies initial reservoir level -// or uses wrong hydro options -// we should inform the user that the final reservoir level wont be reached -void FinalLevelInflowsModifier::logInfoFinLvlNotApplicable(unsigned int year) -{ - if (isValidLevel(finalReservoirLevel_) - && (!hydro_.reservoirManagement || hydro_.useWaterValue - || !isValidLevel(initialReservoirLevel_))) - logs.info() << "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 "; -} - -bool FinalLevelInflowsModifier::makeChecks(unsigned int year) -{ - // Simulation must end on day 365 and reservoir level must be initiated in January - bool checksOk = preCheckStartAndEndSim(year); - - // Reservoir_levelDay_365 – reservoir_levelDay_1 ≤ yearly_inflows - double totalInflows = calculateTotalInflows(year); - checksOk = preCheckYearlyInflow(totalInflows, year) && checksOk; - - // Final reservoir level set by the user is within the - // rule curves for the final day - checksOk = preCheckRuleCurves(year) && checksOk; - - isApplicable_.at(year) = checksOk; - - return checksOk; -} - -bool FinalLevelInflowsModifier::isApplicable(unsigned int year) -{ - // If isApplicable_.size() == 0, then instance was not properly initialized - // and is not applicable. - return !isApplicable_.empty() && isApplicable_.at(year); -} - -} // namespace Antares::Data diff --git a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp index 64b46eb112..43630300fa 100644 --- a/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp +++ b/src/libs/antares/study/scenario-builder/hydroLevelsData.cpp @@ -26,9 +26,10 @@ namespace Antares::Data::ScenarioBuilder { -hydroLevelsData::hydroLevelsData(std::string& iniFilePrefix, +hydroLevelsData::hydroLevelsData(const std::string& iniFilePrefix, std::function applyToTarget) : - addToPrefix(iniFilePrefix), applyToTarget_(applyToTarget) + addToPrefix_(iniFilePrefix), + applyToTarget_(applyToTarget) { } @@ -44,10 +45,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 += addToPrefix; - // Turning values into strings (precision 4) std::ostringstream value_into_string; value_into_string << std::setprecision(4); @@ -67,7 +64,7 @@ void hydroLevelsData::saveToINIFile(const Study& study, Yuni::IO::File::Stream& 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 } diff --git a/src/solver/hydro/management/management.cpp b/src/solver/hydro/management/management.cpp index b0595f08a5..0ac172a2f3 100644 --- a/src/solver/hydro/management/management.cpp +++ b/src/solver/hydro/management/management.cpp @@ -368,15 +368,15 @@ void HydroManagement::changeInflowsToAccommodateFinalLevels(uint year) { auto& data = tmpDataByArea_[&area]; - if (!area.hydro.finalLevelInflowsModifier.isApplicable(year)) + if (!area.hydro.deltaBetweenFinalAndInitialLevels[year].has_value()) return; // Must be done before prepareMonthlyTargetGenerations - double delta = area.hydro.finalLevelInflowsModifier.deltaLevel[year]; - if (delta > 0) - data.inflows[0] += delta; - else if (delta < 0) - data.inflows[11] += delta; + double delta = area.hydro.deltaBetweenFinalAndInitialLevels[year].value(); + if (delta < 0) + data.inflows[0] -= delta; + else if (delta > 0) + data.inflows[11] -= delta; }); } diff --git a/src/solver/hydro/management/monthly.cpp b/src/solver/hydro/management/monthly.cpp index 958004e33b..9eab972373 100644 --- a/src/solver/hydro/management/monthly.cpp +++ b/src/solver/hydro/management/monthly.cpp @@ -152,8 +152,6 @@ void HydroManagement::prepareMonthlyOptimalGenerations(double* random_reservoir_ if (area.hydro.reservoirManagement) lvi = random_reservoir_level[indexArea]; - indexArea++; - double solutionCost = 0.; double solutionCostNoised = 0.; @@ -285,6 +283,8 @@ void HydroManagement::prepareMonthlyOptimalGenerations(double* random_reservoir_ auto content = buffer.str(); resultWriter_.addEntryFromBuffer(path.str(), content); } + + indexArea++; }); } diff --git a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp index f8a43c3dff..32f2d4dfa2 100644 --- a/src/solver/simulation/hydro-final-reservoir-level-functions.cpp +++ b/src/solver/simulation/hydro-final-reservoir-level-functions.cpp @@ -26,44 +26,43 @@ */ #include "antares/solver/simulation/hydro-final-reservoir-level-functions.h" +#include "antares/study/parts/hydro/finalLevelValidator.h" #include namespace Antares::Solver { -void initializeFinalLevelData(const Data::Study& study) -{ - study.areas.each([&study](Data::Area& area) - { - area.hydro.finalLevelInflowsModifier.initialize(study.scenarioInitialHydroLevels, - study.scenarioFinalHydroLevels, - study.parameters.simulationDays.end, - study.parameters.nbYears); - }); -} - -void CheckFinalReservoirLevelsForYear(const Data::Study& study, uint year) -{ - study.areas.each([&study, &year](Data::Area& area) - { - if (!area.hydro.finalLevelInflowsModifier.CheckInfeasibility(year)) - { - throw FatalError("hydro final level : infeasibility"); - } - }); -} - void CheckFinalReservoirLevelsConfiguration(const Data::Study& study) { - initializeFinalLevelData(study); + study.areas.each([&study](Data::Area &area) + { + uint nbYears = study.parameters.nbYears; + for (uint year = 0; year != nbYears; ++year) + { + if (! study.parameters.yearsFilter.at(year)) + continue; - uint nbYears = study.parameters.nbYears; + double initialLevel = study.scenarioInitialHydroLevels.entry[area.index][year]; + double finalLevel = study.scenarioFinalHydroLevels.entry[area.index][year]; - for (uint year = 0; year != nbYears; ++year) - { - if (study.parameters.yearsFilter.at(year)) - CheckFinalReservoirLevelsForYear(study, year); - } -} + Data::FinalLevelValidator validator(area.hydro, + area.index, + area.name, + initialLevel, + finalLevel, + year, + study.parameters.simulationDays.end, + study.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 \ No newline at end of file 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 2a71bff01c..89e95c603e 100644 --- a/src/tests/end-to-end/simple_study/simple-study.cpp +++ b/src/tests/end-to-end/simple_study/simple-study.cpp @@ -80,11 +80,12 @@ struct HydroMaxPowerStudy : public StudyBuilder HydroMaxPowerStudy::HydroMaxPowerStudy() { simulationBetweenDays(0, 14); - setNumberMCyears(1); area = addAreaToStudy("Area"); area->thermal.unsuppliedEnergyCost = 1; + setNumberMCyears(1); + TimeSeriesConfigurer loadTSconfig(area->load.series.timeSeries); loadTSconfig.setColumnCount(1).fillColumnWith(0, loadInArea); diff --git a/src/tests/end-to-end/utils/utils.cpp b/src/tests/end-to-end/utils/utils.cpp index b9c2f00500..3888cf7eea 100644 --- a/src/tests/end-to-end/utils/utils.cpp +++ b/src/tests/end-to-end/utils/utils.cpp @@ -214,6 +214,7 @@ 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) diff --git a/src/tests/src/solver/simulation/CMakeLists.txt b/src/tests/src/solver/simulation/CMakeLists.txt index f8df8044d9..3ba8f09755 100644 --- a/src/tests/src/solver/simulation/CMakeLists.txt +++ b/src/tests/src/solver/simulation/CMakeLists.txt @@ -92,14 +92,8 @@ set_property(TEST time_series PROPERTY LABELS unit) # =================================== # Tests on hydro final reservoir level functions # =================================== -set(SRC_HYDRO_FINAL_LEVEL - ${src_libs_antares_study}/include/antares/study/parts/hydro/finallevelinflowsmodifyer.h - ${src_libs_antares_study}/parts/hydro/finallevelinflowsmodifyer.cpp -) -add_executable(test-hydro_final - test-hydro-final-reservoir-level-functions.cpp - ${SRC_HYDRO_FINAL_LEVEL}) +add_executable(test-hydro_final test-hydro-final-reservoir-level-functions.cpp) target_include_directories(test-hydro_final PRIVATE 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 index 035a54f52d..c087503192 100644 --- 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 @@ -7,6 +7,7 @@ #include #include "include/antares/solver/simulation/hydro-final-reservoir-level-functions.h" +#include "include/antares/study/parts/hydro/finalLevelValidator.h" #include using namespace Antares::Solver; @@ -23,6 +24,7 @@ struct 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"); @@ -34,7 +36,7 @@ struct Fixture area_1->hydro.useWaterValue = false; area_2->hydro.useWaterValue = false; - // Level date must be 0, see preCheckStartAndEndSim function + // Level date must be 0, see hydroAllocationStartMatchesSimulation function area_1->hydro.initializeReservoirLevelDate = 0; area_2->hydro.initializeReservoirLevelDate = 0; @@ -50,6 +52,11 @@ struct Fixture 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 // ------------------------------------------------------- @@ -101,161 +108,133 @@ struct Fixture Area* area_2; }; -BOOST_FIXTURE_TEST_SUITE(s, Fixture) +BOOST_FIXTURE_TEST_SUITE(final_level_validator, Fixture) -BOOST_AUTO_TEST_CASE(initialize_modifier_for_area_1___modifier_is_applicable) +BOOST_AUTO_TEST_CASE(all_parameters_good___check_succeeds_and_final_level_is_usable) { uint year = 0; - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - finLevInfModify.CheckInfeasibility(year); - - BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), true); + 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(reservoir_management_is_false_for_area_1___modifier_is_not_applicable) +BOOST_AUTO_TEST_CASE(no_reservoir_management___check_succeeds_but_final_level_not_usable) { - area_1->hydro.reservoirManagement = false; uint year = 0; - - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - finLevInfModify.CheckInfeasibility(year); - - // check when reservoirManagement = false - BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); + 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_for_area_1___modifier_is_not_applicable) +BOOST_AUTO_TEST_CASE(use_water_value_is_true___check_succeeds_but_final_level_not_usable) { area_1->hydro.useWaterValue = true; uint year = 0; - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - finLevInfModify.CheckInfeasibility(year); - - // check when useWaterValue = true - BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), 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(initial_level_from_scenariobuilder_is_NaN_for_area_1_and_year_0____modifier_not_applicable) +BOOST_AUTO_TEST_CASE(final_level_not_set_by_user____check_succeeds_but_final_level_not_usable) { uint year = 0; - study->scenarioInitialHydroLevels[area_1->index][year] = std::numeric_limits::quiet_NaN(); - - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - finLevInfModify.CheckInfeasibility(year); - - BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); + 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(final_level_modifier_not_initialized____modifier_not_applicable) -{ - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - uint year = 0; - BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), false); -} - -BOOST_AUTO_TEST_CASE(checking_level_configuration_is_ok_for_area_1_and_year_0___delta_level_as_expected) -{ - uint year = 0; - - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - finLevInfModify.CheckInfeasibility(year); - - double expectedDeltaLevel = -1.1; - BOOST_CHECK_EQUAL(finLevInfModify.isApplicable(year), true); - BOOST_CHECK_EQUAL(finLevInfModify.deltaLevel.at(year), expectedDeltaLevel); -} - -BOOST_AUTO_TEST_CASE(input_level_configuration_has_nothing_wrong_for_area_1___check_succeeds) -{ - uint year = 0; - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), true); -} - -BOOST_AUTO_TEST_CASE(initial_level_month_for_area_1_is_not_january___check_fails) +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 - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), 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(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); } -BOOST_AUTO_TEST_CASE(simulation_last_day_is_not_365___check_fails) +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; - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), 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(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); } -BOOST_AUTO_TEST_CASE(Final_level_not_between_rule_curves_for_area_1___check_fails) +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; - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), 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(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); } -BOOST_AUTO_TEST_CASE(diff_between_init_and_final_levels_are_bigger_than_yearly_inflows_for_area_1___check_fails) +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; @@ -264,32 +243,34 @@ BOOST_AUTO_TEST_CASE(diff_between_init_and_final_levels_are_bigger_than_yearly_i // Inflows = 200 MWh/day = 73 000 MWh/year // (50 - 10) x Reservoir capacity == 74 000 > 73 000. - - auto finLevInfModify = FinalLevelInflowsModifier(area_1->hydro, area_1->index, area_1->name); - - finLevInfModify.initialize(study->scenarioInitialHydroLevels, - study->scenarioFinalHydroLevels, - study->parameters.simulationDays.end, - study->parameters.nbYears); - - BOOST_CHECK_EQUAL(finLevInfModify.CheckInfeasibility(year), 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(), false); + BOOST_CHECK_EQUAL(validator.finalLevelFineForUse(), false); } -BOOST_AUTO_TEST_CASE(check_all_areas_final_reservoir_levels_when_config_is_ok___all_checks_succeed) +BOOST_AUTO_TEST_CASE(check_all_areas_final_levels_when_config_is_ok___all_checks_succeed) { CheckFinalReservoirLevelsConfiguration(*study); // Checks on Area 1 modifier - BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.isApplicable(0), true); - BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.isApplicable(1), true); - BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.deltaLevel.at(0), 2.3 - 3.4); - BOOST_CHECK_EQUAL(area_1->hydro.finalLevelInflowsModifier.deltaLevel.at(1), 4.2 - 5.1); + 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.finalLevelInflowsModifier.isApplicable(0), true); - BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.isApplicable(1), true); - BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.deltaLevel.at(0), 1.5 - 3.5); - BOOST_CHECK_EQUAL(area_2->hydro.finalLevelInflowsModifier.deltaLevel.at(1), 2.4 - 4.3); + 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() \ No newline at end of file From 1b7039a8e64e2f03e0070e7af06a69a3906df483 Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Mon, 17 Jun 2024 15:40:10 +0200 Subject: [PATCH 488/490] CR 25 (hydro final level) : correction after merge/update from develop --- .../antares/study/scenario-builder/rules.cpp | 96 ++++++++++--------- src/solver/simulation/CMakeLists.txt | 7 +- 2 files changed, 57 insertions(+), 46 deletions(-) diff --git a/src/libs/antares/study/scenario-builder/rules.cpp b/src/libs/antares/study/scenario-builder/rules.cpp index 633da4db60..fd79f07f7c 100644 --- a/src/libs/antares/study/scenario-builder/rules.cpp +++ b/src/libs/antares/study/scenario-builder/rules.cpp @@ -404,8 +404,11 @@ bool Rules::readLine(const AreaName::Vector& splitKey, String value, bool update return readSolar(splitKey, value, updaterMode); } else if (kind_of_scenario == "hl") + { return readInitialHydroLevels(splitKey, value, updaterMode); + } else if (kind_of_scenario == "hfl") + { return readFinalHydroLevels(splitKey, value, updaterMode); } else if (kind_of_scenario == "ntc") @@ -419,61 +422,64 @@ bool Rules::readLine(const AreaName::Vector& splitKey, String value, bool update return false; } - bool Rules::apply() +bool Rules::apply() +{ + bool returned_status = true; + if (pAreaCount) { - bool returned_status = true; - if (pAreaCount) + returned_status = load.apply(study_) && returned_status; + returned_status = solar.apply(study_) && returned_status; + returned_status = hydro.apply(study_) && returned_status; + returned_status = wind.apply(study_) && returned_status; + for (uint i = 0; i != pAreaCount; ++i) { - returned_status = load.apply(study_) && returned_status; - returned_status = solar.apply(study_) && returned_status; - returned_status = hydro.apply(study_) && returned_status; - returned_status = wind.apply(study_) && returned_status; - for (uint i = 0; i != pAreaCount; ++i) - { - returned_status = thermal[i].apply(study_) && returned_status; - 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 = binding_constraints.apply(study_) && returned_status; + returned_status = thermal[i].apply(study_) && returned_status; + returned_status = renewable[i].apply(study_) && returned_status; + returned_status = linksNTC[i].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; } - - void Rules::sendWarningsForDisabledClusters() + else { - for (auto it = disabledClustersOnRuleActive.begin(); - it != disabledClustersOnRuleActive.end(); - it++) + returned_status = false; + } + return returned_status; +} + +void Rules::sendWarningsForDisabledClusters() +{ + for (auto it = disabledClustersOnRuleActive.begin(); + it != disabledClustersOnRuleActive.end(); + it++) + { + std::vector& scenariiForCurrentCluster = it->second; + 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. + 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) { - std::vector& scenariiForCurrentCluster = it->second; - 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. - 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() << listYears; + 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() << listYears; } +} } // namespace Antares::Data::ScenarioBuilder diff --git a/src/solver/simulation/CMakeLists.txt b/src/solver/simulation/CMakeLists.txt index dcfbe091a3..0d2bc666eb 100644 --- a/src/solver/simulation/CMakeLists.txt +++ b/src/solver/simulation/CMakeLists.txt @@ -47,7 +47,12 @@ set(SRC_SIMULATION include/antares/solver/simulation/hydro-final-reservoir-level-functions.h hydro-final-reservoir-level-functions.cpp TimeSeriesNumbersWriter.cpp - include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.h) + include/antares/solver/simulation/BindingConstraintsTimeSeriesNumbersWriter.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}) # From 76237a6a0d8aba01d7d5d44246735ca088107dce Mon Sep 17 00:00:00 2001 From: Guillaume PIERRE Date: Tue, 18 Jun 2024 11:22:00 +0200 Subject: [PATCH 489/490] CR 25 (hydro final level) : corrections due to review --- .../study/include/antares/study/scenario-builder/rules.h | 4 ++-- src/libs/antares/study/parts/hydro/finalLevelValidator.cpp | 2 +- 2 files changed, 3 insertions(+), 3 deletions(-) diff --git a/src/libs/antares/study/include/antares/study/scenario-builder/rules.h b/src/libs/antares/study/include/antares/study/scenario-builder/rules.h index d1e3dbaa06..ff5261d64a 100644 --- a/src/libs/antares/study/include/antares/study/scenario-builder/rules.h +++ b/src/libs/antares/study/include/antares/study/scenario-builder/rules.h @@ -120,9 +120,9 @@ class Rules final: private Yuni::NonCopyable std::vector renewable; //! hydro initial levels - hydroLevelsData hydroInitialLevels = hydroLevelsData("hl,", initLevelApply); + hydroLevelsData hydroInitialLevels = {"hl,", initLevelApply}; //! hydro final levels - hydroLevelsData hydroFinalLevels = hydroLevelsData("hfl,", finalLevelApply); + hydroLevelsData hydroFinalLevels = {"hfl,", finalLevelApply}; // Links NTC std::vector linksNTC; diff --git a/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp b/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp index 50d21efac5..2229f75f97 100644 --- a/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp +++ b/src/libs/antares/study/parts/hydro/finalLevelValidator.cpp @@ -78,7 +78,7 @@ bool FinalLevelValidator::compatibleWithReservoirProperties() if (hydro_.reservoirManagement && !hydro_.useWaterValue) return true; - logs.info() << "Final reservoir level not applicable! Year:" << year_ + 1 + 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 "; From 9794966b291a110695288f64e2ea3fcbbc7b19dc Mon Sep 17 00:00:00 2001 From: guilpier-code <62292552+guilpier-code@users.noreply.github.com> Date: Wed, 19 Jun 2024 18:46:20 +0200 Subject: [PATCH 490/490] Fixing hydro debug (#2176) Recall : **Hydro allocation** is done at the beginning of each MC year, and ends with a quantity of hydro energy for each day of the year. These daily quantities are to be used as daily hydro generations in the optimization problem. The **hydro debug** functionality allows to print (if asked by user) on disk a **report** about **hydro allocation results**. This hydro allocation report is broken (a crash comes up). It was broken since January 2023 (a commit can be supplied if needed). This PR to fix this crash. --- src/solver/hydro/management/daily.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/src/solver/hydro/management/daily.cpp b/src/solver/hydro/management/daily.cpp index 8391b523d0..c19922c414 100644 --- a/src/solver/hydro/management/daily.cpp +++ b/src/solver/hydro/management/daily.cpp @@ -362,6 +362,7 @@ inline void HydroManagement::prepareDailyOptimalGenerations( if (debugData) { + dayYear = 0; for (uint month = 0; month != 12; ++month) { auto daysPerMonth = calendar_.months[month].days; @@ -371,6 +372,7 @@ inline void HydroManagement::prepareDailyOptimalGenerations( auto dYear = day + dayYear; debugData->DailyTargetGen[dYear] = dailyTargetGen[dYear]; } + dayYear += daysPerMonth; } }