diff --git a/GridKit/LinearAlgebra/Vector/Vector.cpp b/GridKit/LinearAlgebra/Vector/Vector.cpp index 819f2de48..389995e4b 100644 --- a/GridKit/LinearAlgebra/Vector/Vector.cpp +++ b/GridKit/LinearAlgebra/Vector/Vector.cpp @@ -1,6 +1,7 @@ #include #include +#include #include #include @@ -1089,9 +1090,11 @@ namespace GridKit std::fill(gpu_updated_, gpu_updated_ + k_, is_updated); } - // template class Vector; + template class Vector; template class Vector; template class Vector; + template class Vector; + template class Vector; } // namespace LinearAlgebra } // namespace GridKit diff --git a/GridKit/Model/Evaluator.hpp b/GridKit/Model/Evaluator.hpp index 270b5875e..2e5a73e4f 100644 --- a/GridKit/Model/Evaluator.hpp +++ b/GridKit/Model/Evaluator.hpp @@ -1,10 +1,11 @@ #pragma once -#include +#include #include #include #include +#include #include #include @@ -12,6 +13,8 @@ namespace GridKit { namespace Model { + namespace memory = GridKit::memory; + /*! * @brief Abstract class describing a model. * @@ -25,6 +28,7 @@ namespace GridKit using RealT = typename GridKit::ScalarTraits::RealT; using CsrMatrixT = GridKit::LinearAlgebra::CsrMatrix; using CooMatrixT = GridKit::LinearAlgebra::CooMatrix; + using VectorT = GridKit::LinearAlgebra::Vector; Evaluator() { @@ -122,55 +126,168 @@ namespace GridKit /** * @brief Get the absolute tolerance for each variable in the model * - * @return a reference to the absolute tolerance vector. + * @return the absolute tolerance vector. * * @pre `setAbsoluteTolerance` must have been called first. */ - virtual std::vector& absoluteTolerance() = 0; + virtual VectorT& absoluteTolerance() + { + return abs_tol_; + } + /** * @brief Get the absolute tolerance for each variable in the model * - * @return a const reference to the absolute tolerance vector. + * @return the absolute tolerance vector. * * @pre `setAbsoluteTolerance` must have been called first. */ - virtual const std::vector& absoluteTolerance() const = 0; + virtual const VectorT& absoluteTolerance() const + { + return abs_tol_; + } - virtual std::vector& y() = 0; - virtual const std::vector& y() const = 0; + virtual VectorT& y() + { + return y_; + } - virtual std::vector& yp() = 0; - virtual const std::vector& yp() const = 0; + virtual const VectorT& y() const + { + return y_; + } - virtual std::vector& tag() = 0; - virtual const std::vector& tag() const = 0; + virtual VectorT& yp() + { + return yp_; + } - virtual std::vector& yB() = 0; - virtual const std::vector& yB() const = 0; + virtual const VectorT& yp() const + { + return yp_; + } - virtual std::vector& ypB() = 0; - virtual const std::vector& ypB() const = 0; + /** + * @brief Get the differential/algebraic tag for each variable. + * + * Entries are scalar values for direct transfer to solver vectors. + */ + virtual VectorT& tag() + { + return tag_; + } - virtual std::vector& param() = 0; - virtual const std::vector& param() const = 0; + /** + * @brief Get the differential/algebraic tag for each variable. + */ + virtual const VectorT& tag() const + { + return tag_; + } + + virtual VectorT& yB() = 0; + virtual const VectorT& yB() const = 0; - virtual std::vector& param_up() = 0; - virtual const std::vector& param_up() const = 0; + virtual VectorT& ypB() = 0; + virtual const VectorT& ypB() const = 0; - virtual std::vector& param_lo() = 0; - virtual const std::vector& param_lo() const = 0; + virtual VectorT& param() = 0; + virtual const VectorT& param() const = 0; - virtual std::vector& getResidual() = 0; - virtual const std::vector& getResidual() const = 0; + virtual VectorT& param_up() = 0; + virtual const VectorT& param_up() const = 0; - virtual std::vector& getIntegrand() = 0; - virtual const std::vector& getIntegrand() const = 0; + virtual VectorT& param_lo() = 0; + virtual const VectorT& param_lo() const = 0; + + virtual VectorT& getResidual() + { + return f_; + } - virtual std::vector& getAdjointResidual() = 0; - virtual const std::vector& getAdjointResidual() const = 0; + virtual const VectorT& getResidual() const + { + return f_; + } + + virtual VectorT& getIntegrand() = 0; + virtual const VectorT& getIntegrand() const = 0; + + virtual VectorT& getAdjointResidual() = 0; + virtual const VectorT& getAdjointResidual() const = 0; + + virtual VectorT& getAdjointIntegrand() = 0; + virtual const VectorT& getAdjointIntegrand() const = 0; + + /** + * @brief Bind this evaluator's state and residual vectors. + */ + virtual void bind(VectorT& y, VectorT& yp, VectorT& f, VectorT& tag, VectorT& abs_tol, IdxT offset) + { + const IdxT n = size(); + assert(!allocated_); + assert(offset + n <= y.getSize()); + assert(offset + n <= yp.getSize()); + assert(offset + n <= f.getSize()); + assert(offset + n <= tag.getSize()); + assert(offset + n <= abs_tol.getSize()); + + y_.resize(n); + y_.setData(y.getData() + offset); + + yp_.resize(n); + yp_.setData(yp.getData() + offset); + + f_.resize(n); + f_.setData(f.getData() + offset); + + tag_.resize(n); + tag_.setData(tag.getData() + offset); + + abs_tol_.resize(n); + abs_tol_.setData(abs_tol.getData() + offset); + + offset_ = offset; + allocated_ = true; + } + + protected: + /** + * @brief Allocate this evaluator's state and residual vectors. + */ + void allocateVectors(IdxT n) + { + y_.resize(n); + y_.allocate(memory::HOST); + y_.setToZero(memory::HOST); + + yp_.resize(n); + yp_.allocate(memory::HOST); + yp_.setToZero(memory::HOST); + + f_.resize(n); + f_.allocate(memory::HOST); + f_.setToZero(memory::HOST); + + tag_.resize(n); + tag_.allocate(memory::HOST); + tag_.setToZero(memory::HOST); + + abs_tol_.resize(n); + abs_tol_.allocate(memory::HOST); + abs_tol_.setToZero(memory::HOST); + + offset_ = 0; + allocated_ = true; + } - virtual std::vector& getAdjointIntegrand() = 0; - virtual const std::vector& getAdjointIntegrand() const = 0; + VectorT y_; + VectorT yp_; + VectorT f_; + VectorT tag_; + VectorT abs_tol_; + IdxT offset_{0}; + bool allocated_{false}; }; } // namespace Model diff --git a/GridKit/Model/PhasorDynamics/Branch/BranchEnzyme.cpp b/GridKit/Model/PhasorDynamics/Branch/BranchEnzyme.cpp index cd8b73aa6..9094a60ac 100644 --- a/GridKit/Model/PhasorDynamics/Branch/BranchEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Branch/BranchEnzyme.cpp @@ -42,12 +42,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDwb, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual11>::eval(this, static_cast(bus1_->size()), - static_cast((bus1_->y()).size()), + static_cast((bus1_->y()).getSize()), (bus1_->getResidualIndices()).data(), (bus1_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus1_->y()).data(), + y_.getData(), + yp_.getData(), + bus1_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -57,12 +57,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDwb, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual22>::eval(this, static_cast(bus2_->size()), - static_cast((bus2_->y()).size()), + static_cast((bus2_->y()).getSize()), (bus2_->getResidualIndices()).data(), (bus2_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus2_->y()).data(), + y_.getData(), + yp_.getData(), + bus2_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -72,12 +72,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDwb, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual12>::eval(this, static_cast(bus1_->size()), - static_cast((bus2_->y()).size()), + static_cast((bus2_->y()).getSize()), (bus1_->getResidualIndices()).data(), (bus2_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus2_->y()).data(), + y_.getData(), + yp_.getData(), + bus2_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -87,12 +87,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDwb, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual21>::eval(this, static_cast(bus2_->size()), - static_cast((bus1_->y()).size()), + static_cast((bus1_->y()).getSize()), (bus2_->getResidualIndices()).data(), (bus1_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus1_->y()).data(), + y_.getData(), + yp_.getData(), + bus1_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Branch/BranchImpl.hpp b/GridKit/Model/PhasorDynamics/Branch/BranchImpl.hpp index 6b3a51bba..aa09995d6 100644 --- a/GridKit/Model/PhasorDynamics/Branch/BranchImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Branch/BranchImpl.hpp @@ -119,6 +119,21 @@ namespace GridKit template int Branch::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } + auto size = static_cast(size_); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(this->tag_.getSize() == size); + assert(this->abs_tol_.getSize() == size); + + variable_indices_.resize(size); + residual_indices_.resize(size); + wb_.resize(2); h_.resize(2); diff --git a/GridKit/Model/PhasorDynamics/Bus/Bus.hpp b/GridKit/Model/PhasorDynamics/Bus/Bus.hpp index 229325710..55f679497 100644 --- a/GridKit/Model/PhasorDynamics/Bus/Bus.hpp +++ b/GridKit/Model/PhasorDynamics/Bus/Bus.hpp @@ -60,42 +60,42 @@ namespace GridKit virtual ScalarT& Vr() override final { - return y_[0]; + return y_.getData()[0]; } virtual const ScalarT& Vr() const override final { - return y_[0]; + return y_.getData()[0]; } virtual ScalarT& Vi() override final { - return y_[1]; + return y_.getData()[1]; } virtual const ScalarT& Vi() const override final { - return y_[1]; + return y_.getData()[1]; } virtual ScalarT& Ir() override final { - return f_[0]; + return f_.getData()[0]; } virtual const ScalarT& Ir() const override final { - return f_[0]; + return f_.getData()[0]; } virtual ScalarT& Ii() override final { - return f_[1]; + return f_.getData()[1]; } virtual const ScalarT& Ii() const override final { - return f_[1]; + return f_.getData()[1]; } protected: diff --git a/GridKit/Model/PhasorDynamics/Bus/BusImpl.hpp b/GridKit/Model/PhasorDynamics/Bus/BusImpl.hpp index 122102c4b..380ef6e10 100644 --- a/GridKit/Model/PhasorDynamics/Bus/BusImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Bus/BusImpl.hpp @@ -101,28 +101,29 @@ namespace GridKit } /*! - * @brief allocate method resizes local solution and residual vectors. + * @brief Allocate bus storage and index maps. */ template int Bus::allocate() { - // Temporary while we use std::vector in the code + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } size_t size = static_cast(size_); - // Resize component model data - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); - - // Default variable and residual index mapping to local index for (IdxT j = 0; j < size_; ++j) { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; } return 0; @@ -144,8 +145,10 @@ namespace GridKit template int Bus::tagDifferentiable() { - tag_[0] = false; - tag_[1] = false; + auto* tag = tag_.getData(); + + tag[0] = false; + tag[1] = false; return 0; } @@ -164,7 +167,7 @@ namespace GridKit template int Bus::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -175,10 +178,13 @@ namespace GridKit int Bus::initialize() { // std::cout << "Initialize Bus..." << std::endl; - y_[0] = Vr0_; - y_[1] = Vi0_; - yp_[0] = 0.0; - yp_[1] = 0.0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = Vr0_; + y[1] = Vi0_; + yp[0] = 0.0; + yp[1] = 0.0; return 0; } @@ -194,8 +200,10 @@ namespace GridKit int Bus::evaluateResidual() { // std::cout << "Evaluating residual of a PQ bus ...\n"; - f_[0] = 0.0; - f_[1] = 0.0; + auto* f = f_.getData(); + + f[0] = 0.0; + f[1] = 0.0; return 0; } } // namespace PhasorDynamics diff --git a/GridKit/Model/PhasorDynamics/Bus/BusInfiniteImpl.hpp b/GridKit/Model/PhasorDynamics/Bus/BusInfiniteImpl.hpp index e5b0cfa7f..c263f4780 100644 --- a/GridKit/Model/PhasorDynamics/Bus/BusInfiniteImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Bus/BusInfiniteImpl.hpp @@ -99,11 +99,26 @@ namespace GridKit } /*! - * @brief allocate method resizes local solution and residual vectors. + * @brief Allocate bus storage and index maps. */ template int BusInfinite::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } + auto size = static_cast(size_); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(this->tag_.getSize() == size); + assert(this->abs_tol_.getSize() == size); + + variable_indices_.resize(size); + residual_indices_.resize(size); + return 0; } diff --git a/GridKit/Model/PhasorDynamics/BusBase.hpp b/GridKit/Model/PhasorDynamics/BusBase.hpp index 3ecfecec2..5795765fc 100644 --- a/GridKit/Model/PhasorDynamics/BusBase.hpp +++ b/GridKit/Model/PhasorDynamics/BusBase.hpp @@ -1,5 +1,7 @@ #pragma once +#include +#include #include #include #include @@ -34,6 +36,7 @@ namespace GridKit using CooMatrixT = typename Model::Evaluator::CooMatrixT; using BusTypeT = typename BusData::BusType; using MonitorT = Model::VariableMonitor; + using VectorT = typename Model::Evaluator::VectorT; BusBase() = default; @@ -54,52 +57,32 @@ namespace GridKit return nnz_; } - std::vector& y() override - { - return y_; - } - - const std::vector& y() const override - { - return y_; - } - - std::vector& yp() override - { - return yp_; - } - - const std::vector& yp() const override - { - return yp_; - } - - std::vector& tag() override + VectorT& tag() override { return tag_; } - const std::vector& tag() const override + const VectorT& tag() const override { return tag_; } - std::vector& absoluteTolerance() override + VectorT& absoluteTolerance() override { return abs_tol_; } - const std::vector& absoluteTolerance() const override + const VectorT& absoluteTolerance() const override { return abs_tol_; } - std::vector& getResidual() override + VectorT& getResidual() override { return f_; } - const std::vector& getResidual() const override + const VectorT& getResidual() const override { return f_; } @@ -136,6 +119,17 @@ namespace GridKit return residual_indices_; } + protected: + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::offset_; + using Model::Evaluator::allocated_; + using Model::Evaluator::allocateVectors; + + public: /// Pure virtual function, returns bus type (DEFAULT or SLACK). virtual BusTypeT BusType() const { @@ -188,11 +182,6 @@ namespace GridKit /// Global (system-level) residual indices std::vector residual_indices_; - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; std::vector g_; CsrMatrixT* csr_jac_{nullptr}; @@ -231,52 +220,52 @@ namespace GridKit throw NotImplementedError(__func__); } - [[noreturn]] std::vector& yB() override + [[noreturn]] VectorT& yB() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& yB() const override + [[noreturn]] const VectorT& yB() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& ypB() override + [[noreturn]] VectorT& ypB() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& ypB() const override + [[noreturn]] const VectorT& ypB() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& param() override + [[noreturn]] VectorT& param() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& param() const override + [[noreturn]] const VectorT& param() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& param_up() override + [[noreturn]] VectorT& param_up() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& param_up() const override + [[noreturn]] const VectorT& param_up() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& param_lo() override + [[noreturn]] VectorT& param_lo() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& param_lo() const override + [[noreturn]] const VectorT& param_lo() const override { throw NotImplementedError(__func__); } @@ -301,32 +290,32 @@ namespace GridKit throw NotImplementedError(__func__); } - [[noreturn]] std::vector& getIntegrand() override + [[noreturn]] VectorT& getIntegrand() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& getIntegrand() const override + [[noreturn]] const VectorT& getIntegrand() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& getAdjointResidual() override + [[noreturn]] VectorT& getAdjointResidual() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& getAdjointResidual() const override + [[noreturn]] const VectorT& getAdjointResidual() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& getAdjointIntegrand() override + [[noreturn]] VectorT& getAdjointIntegrand() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& getAdjointIntegrand() const override + [[noreturn]] const VectorT& getAdjointIntegrand() const override { throw NotImplementedError(__func__); } diff --git a/GridKit/Model/PhasorDynamics/BusFault/BusFaultEnzyme.cpp b/GridKit/Model/PhasorDynamics/BusFault/BusFaultEnzyme.cpp index eeaf98b26..b96719c4f 100644 --- a/GridKit/Model/PhasorDynamics/BusFault/BusFaultEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/BusFault/BusFaultEnzyme.cpp @@ -40,12 +40,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, @@ -55,13 +55,13 @@ namespace GridKit IdxT nnz_tmp = nnz_; GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus_->y()).data(), + y_.getData(), + yp_.getData(), + bus_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -77,11 +77,11 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDy, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual>::eval(this, static_cast(bus_->size()), - y_.size(), + static_cast(y_.getSize()), (bus_->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, diff --git a/GridKit/Model/PhasorDynamics/BusFault/BusFaultImpl.hpp b/GridKit/Model/PhasorDynamics/BusFault/BusFaultImpl.hpp index b0589aaf1..2b638280c 100644 --- a/GridKit/Model/PhasorDynamics/BusFault/BusFaultImpl.hpp +++ b/GridKit/Model/PhasorDynamics/BusFault/BusFaultImpl.hpp @@ -84,9 +84,13 @@ namespace GridKit monitor_->set(Variable::state, [this] { return status_; }); monitor_->set(Variable::ir, [this] - { return y_[0]; }); + { + auto* y = y_.getData(); + return y[0]; }); monitor_->set(Variable::ii, [this] - { return y_[1]; }); + { + auto* y = y_.getData(); + return y[1]; }); size_ = 2; setDerivedParams(); @@ -113,26 +117,31 @@ namespace GridKit template int BusFault::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } // std::cout << "Allocate BusFault..." << std::endl; + auto size = static_cast(size_); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(this->f_.getSize() == size); + assert(tag_.getSize() == size); + assert(this->abs_tol_.getSize() == size); - auto size = static_cast(size_); // avoid compiler warnings - f_.resize(size); - y_.resize(size); - yp_.resize(size); - abs_tol_.resize(size); - tag_.resize(size); - variable_indices_.resize(size); - residual_indices_.resize(size); + this->variable_indices_.resize(size); + this->residual_indices_.resize(size); // Resize coupling data wb_.resize(2); h_.resize(2); - // Default variable and residual index mapping to local index + // Default variable and residual index mapping to global indices for (IdxT j = 0; j < size_; ++j) { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); + this->setVariableIndex(j, this->offset_ + j); + this->setResidualIndex(j, this->offset_ + j); } return 0; @@ -145,23 +154,26 @@ namespace GridKit template int BusFault::initialize() { + auto* y = y_.getData(); + auto* yp = yp_.getData(); + if (status_) { ScalarT vr = Vr(); ScalarT vi = Vi(); ScalarT ir = -(vr * G_ - vi * B_); ScalarT ii = -(vr * B_ + vi * G_); - y_[0] = ir; - y_[1] = ii; + y[0] = ir; + y[1] = ii; } else { - y_[0] = 0.0; - y_[1] = 0.0; + y[0] = 0.0; + y[1] = 0.0; } - yp_[0] = 0.0; - yp_[1] = 0.0; + yp[0] = 0.0; + yp[1] = 0.0; return 0; } @@ -172,8 +184,10 @@ namespace GridKit template int BusFault::tagDifferentiable() { - tag_[0] = false; - tag_[1] = false; + auto* tag = tag_.getData(); + + tag[0] = false; + tag[1] = false; return 0; } @@ -193,7 +207,7 @@ namespace GridKit template int BusFault::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -247,18 +261,24 @@ namespace GridKit { if (status_) { - wb_[0] = Vr(); - wb_[1] = Vi(); - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), f_.data()); - evaluateBusResidual(y_.data(), yp_.data(), wb_.data(), h_.data()); + wb_[0] = Vr(); + wb_[1] = Vi(); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), f); + evaluateBusResidual(y, yp, wb_.data(), h_.data()); Ir() += h_[0]; Ii() += h_[1]; } else { - wb_[0] = 0.0; - wb_[1] = 0.0; - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), f_.data()); + wb_[0] = 0.0; + wb_[1] = 0.0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), f); } return 0; diff --git a/GridKit/Model/PhasorDynamics/BusToSignalAdapter/BusToSignalAdapterImpl.hpp b/GridKit/Model/PhasorDynamics/BusToSignalAdapter/BusToSignalAdapterImpl.hpp index 4ae676ccc..33b400443 100644 --- a/GridKit/Model/PhasorDynamics/BusToSignalAdapter/BusToSignalAdapterImpl.hpp +++ b/GridKit/Model/PhasorDynamics/BusToSignalAdapter/BusToSignalAdapterImpl.hpp @@ -52,6 +52,21 @@ namespace GridKit template int BusToSignalAdapter::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } + auto size = static_cast(size_); + + assert(this->y_.getSize() == size); + assert(this->yp_.getSize() == size); + assert(this->f_.getSize() == size); + assert(this->tag_.getSize() == size); + assert(this->abs_tol_.getSize() == size); + + this->variable_indices_.resize(size); + this->residual_indices_.resize(size); + static constexpr auto VREAL = BusToSignalAdapterInternalVariables::VREAL; static constexpr auto VIMAG = BusToSignalAdapterInternalVariables::VIMAG; diff --git a/GridKit/Model/PhasorDynamics/CMakeLists.txt b/GridKit/Model/PhasorDynamics/CMakeLists.txt index baf76ab90..0782fd2fc 100644 --- a/GridKit/Model/PhasorDynamics/CMakeLists.txt +++ b/GridKit/Model/PhasorDynamics/CMakeLists.txt @@ -20,6 +20,8 @@ gridkit_add_library( INTERFACE GridKit::utilities_logger INTERFACE + GridKit::dense_vector + INTERFACE GridKit::sparse_matrix) target_link_libraries( diff --git a/GridKit/Model/PhasorDynamics/Component.hpp b/GridKit/Model/PhasorDynamics/Component.hpp index 8cfdd0c78..8461080a6 100644 --- a/GridKit/Model/PhasorDynamics/Component.hpp +++ b/GridKit/Model/PhasorDynamics/Component.hpp @@ -1,5 +1,7 @@ #pragma once +#include +#include #include #include @@ -26,6 +28,7 @@ namespace GridKit using RealT = typename Model::Evaluator::RealT; using CsrMatrixT = typename Model::Evaluator::CsrMatrixT; using CooMatrixT = typename Model::Evaluator::CooMatrixT; + using VectorT = typename Model::Evaluator::VectorT; Component() = default; @@ -72,52 +75,32 @@ namespace GridKit return nnz_; } - std::vector& y() override - { - return y_; - } - - const std::vector& y() const override - { - return y_; - } - - std::vector& yp() override - { - return yp_; - } - - const std::vector& yp() const override - { - return yp_; - } - - std::vector& tag() override + VectorT& tag() override { return tag_; } - const std::vector& tag() const override + const VectorT& tag() const override { return tag_; } - std::vector& absoluteTolerance() override + VectorT& absoluteTolerance() override { return abs_tol_; } - const std::vector& absoluteTolerance() const override + const VectorT& absoluteTolerance() const override { return abs_tol_; } - std::vector& getResidual() override + VectorT& getResidual() override { return f_; } - const std::vector& getResidual() const override + const VectorT& getResidual() const override { return f_; } @@ -164,6 +147,17 @@ namespace GridKit return coo_jac_; } + protected: + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::offset_; + using Model::Evaluator::allocated_; + using Model::Evaluator::allocateVectors; + + public: /// @todo Remove this method. It should be part of DynamicSolver class. bool hasJacobian() override { @@ -252,11 +246,6 @@ namespace GridKit /// Global (system-level) residual indices std::vector residual_indices_; - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; std::vector g_; IdxT* J_rows_buffer_{nullptr}; @@ -305,52 +294,52 @@ namespace GridKit throw NotImplementedError(__func__); } - [[noreturn]] std::vector& yB() override + [[noreturn]] VectorT& yB() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& yB() const override + [[noreturn]] const VectorT& yB() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& ypB() override + [[noreturn]] VectorT& ypB() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& ypB() const override + [[noreturn]] const VectorT& ypB() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& param() override + [[noreturn]] VectorT& param() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& param() const override + [[noreturn]] const VectorT& param() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& param_up() override + [[noreturn]] VectorT& param_up() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& param_up() const override + [[noreturn]] const VectorT& param_up() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& param_lo() override + [[noreturn]] VectorT& param_lo() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& param_lo() const override + [[noreturn]] const VectorT& param_lo() const override { throw NotImplementedError(__func__); } @@ -375,32 +364,32 @@ namespace GridKit throw NotImplementedError(__func__); } - [[noreturn]] std::vector& getIntegrand() override + [[noreturn]] VectorT& getIntegrand() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& getIntegrand() const override + [[noreturn]] const VectorT& getIntegrand() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& getAdjointResidual() override + [[noreturn]] VectorT& getAdjointResidual() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& getAdjointResidual() const override + [[noreturn]] const VectorT& getAdjointResidual() const override { throw NotImplementedError(__func__); } - [[noreturn]] std::vector& getAdjointIntegrand() override + [[noreturn]] VectorT& getAdjointIntegrand() override { throw NotImplementedError(__func__); } - [[noreturn]] const std::vector& getAdjointIntegrand() const override + [[noreturn]] const VectorT& getAdjointIntegrand() const override { throw NotImplementedError(__func__); } diff --git a/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Enzyme.cpp b/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Enzyme.cpp index ad974d4ed..77c59abf4 100644 --- a/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Enzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Enzyme.cpp @@ -43,12 +43,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -58,12 +58,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), alpha_, @@ -74,13 +74,13 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus_->y()).data(), + y_.getData(), + yp_.getData(), + bus_->y().getData(), ws_.data(), J_rows_buffer_, J_cols_buffer_, @@ -89,12 +89,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDws, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), ws_.size(), (this->getResidualIndices()).data(), ws_indices_.data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Impl.hpp b/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Impl.hpp index a06c788e9..a8e61a031 100644 --- a/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Impl.hpp +++ b/GridKit/Model/PhasorDynamics/Exciter/IEEET1/Ieeet1Impl.hpp @@ -78,15 +78,25 @@ namespace GridKit template int Ieeet1::allocate() { - // Resize component model data + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } auto size = static_cast(size_); // avoid compiler warnings - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize bus data wb_.resize(2); @@ -99,17 +109,11 @@ namespace GridKit ws_[1] = 0.0; ws_indices_[1] = INVALID_INDEX; - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - // Set output signals if (signals_.template isAssigned()) { - signals_.template getSignalNode()->set(&y_[7], &(this->getVariableIndex(7))); + auto* y = y_.getData(); + signals_.template getSignalNode()->set(&y[7], &(this->getVariableIndex(7))); } return 0; @@ -154,7 +158,7 @@ namespace GridKit * F(y, yp=0, t=0) = 0 exactly for every residual equation. * * Inputs: - * - EFD assigned by the generator (read from y_[7]). + * - EFD assigned by the generator. * - Bus voltage, used to form the sensed terminal voltage magnitude. * - Attached external signals (omega, V_S) * @@ -166,6 +170,8 @@ namespace GridKit // External Variables ScalarT efd0{0}; + auto* y = y_.getData(); + auto* yp = yp_.getData(); // Initial Efd set by generator // The exciter object has no way of knowing if the generator @@ -175,7 +181,7 @@ namespace GridKit // other variables. if (signals_.template isAssigned()) { - efd0 = y_[7]; ///<- generator needs to be initialized first + efd0 = y[7]; ///<- generator needs to be initialized first } ScalarT omega{0}; @@ -204,19 +210,19 @@ namespace GridKit vref_ = Ec + vtr + vf - vUEL_ - vOEL_ - vs; - y_[0] = Ec; // y0 - vts - Sensed term volt - y_[1] = vr; // y1 - vr - Voltage reg - y_[2] = efdp; // y2 - efdp - Efd pre mult - y_[3] = vfx; // y3 - vfx - Exciter feedback - y_[4] = vtr; // y4 - vtr - Term Volt Err - y_[5] = vf; // y5 - vf - Feedback volt - y_[6] = ve; // y6 - ve - Excit. Cntrl Volt - y_[7] = efd0; // y7 - efd - Efd - y_[8] = ksat; // y8 - ksat - Saturation - - for (size_t i = 0; i < yp_.size(); ++i) + y[0] = Ec; // y0 - vts - Sensed term volt + y[1] = vr; // y1 - vr - Voltage reg + y[2] = efdp; // y2 - efdp - Efd pre mult + y[3] = vfx; // y3 - vfx - Exciter feedback + y[4] = vtr; // y4 - vtr - Term Volt Err + y[5] = vf; // y5 - vf - Feedback volt + y[6] = ve; // y6 - ve - Excit. Cntrl Volt + y[7] = efd0; // y7 - efd - Efd + y[8] = ksat; // y8 - ksat - Saturation + + for (IdxT i = 0; i < yp_.getSize(); ++i) { - yp_[i] = 0.0; + yp[i] = 0.0; } return 0; @@ -230,15 +236,17 @@ namespace GridKit template int Ieeet1::tagDifferentiable() { - tag_[0] = true; // y0 - vts - Sensed term volt - tag_[1] = true; // y1 - vr - Voltage reg - tag_[2] = true; // y2 - efdp - Efd pre mult - tag_[3] = true; // y3 - vfx - Exciter feedback - tag_[4] = false; // y4 - vtr - Term Volt Err - tag_[5] = false; // y5 - vf - Feedback volt - tag_[6] = false; // y6 - ve - Excit. Cntrl Volt - tag_[7] = false; // y7 - efd - Efd - tag_[8] = false; // y8 - ksat - Saturation + auto* tag = tag_.getData(); + + tag[0] = true; // y0 - vts - Sensed term volt + tag[1] = true; // y1 - vr - Voltage reg + tag[2] = true; // y2 - efdp - Efd pre mult + tag[3] = true; // y3 - vfx - Exciter feedback + tag[4] = false; // y4 - vtr - Term Volt Err + tag[5] = false; // y5 - vf - Feedback volt + tag[6] = false; // y6 - ve - Excit. Cntrl Volt + tag[7] = false; // y7 - efd - Efd + tag[8] = false; // y8 - ksat - Saturation return 0; } @@ -258,7 +266,7 @@ namespace GridKit template int Ieeet1::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -347,7 +355,10 @@ namespace GridKit wb_[1] = bus_->Vi(); // Residual evaluation - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), ws_.data(), f_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), ws_.data(), f); return 0; } @@ -441,9 +452,13 @@ namespace GridKit { using Variable = ModelDataT::MonitorableVariables; monitor_->set(Variable::efd, [this] - { return y_[7]; }); + { + auto* y = y_.getData(); + return y[7]; }); monitor_->set(Variable::ksat, [this] - { return SB_ * Math::qramp(y_[2] - SA_); }); + { + auto* y = y_.getData(); + return SB_ * Math::qramp(y[2] - SA_); }); } } // namespace Exciter } // namespace PhasorDynamics diff --git a/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiEnzyme.cpp b/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiEnzyme.cpp index 9b1f2f65b..d7debf0fe 100644 --- a/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiEnzyme.cpp @@ -38,12 +38,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -53,12 +53,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), alpha_, @@ -69,13 +69,13 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus_->y()).data(), + y_.getData(), + yp_.getData(), + bus_->y().getData(), ws_.data(), J_rows_buffer_, J_cols_buffer_, @@ -84,12 +84,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDws, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), ws_.size(), (this->getResidualIndices()).data(), ws_indices_.data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiImpl.hpp b/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiImpl.hpp index 273756447..cc80bf79f 100644 --- a/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Exciter/SEXS-PTI/SexsPtiImpl.hpp @@ -57,14 +57,25 @@ namespace GridKit template int SexsPti::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } auto size = static_cast(size_); - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } wb_.resize(2); @@ -73,16 +84,11 @@ namespace GridKit ws_[0] = 0.0; ws_indices_[0] = INVALID_INDEX; - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - if (signals_.template isAssigned()) { + auto* y = y_.getData(); signals_.template getSignalNode()->set( - &y_[1], &(this->getVariableIndex(1))); + &y[1], &(this->getVariableIndex(1))); } return 0; @@ -146,9 +152,12 @@ namespace GridKit int SexsPti::initialize() { ScalarT efd0{0.0}; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + if (signals_.template isAssigned()) { - efd0 = y_[1]; + efd0 = y[1]; } ScalarT vreal = bus_->Vr(); @@ -159,13 +168,13 @@ namespace GridKit vref_ = Ec + vtr; - y_[0] = vr; - y_[1] = efd0; - y_[2] = vtr; + y[0] = vr; + y[1] = efd0; + y[2] = vtr; for (IdxT i = 0; i < size_; ++i) { - yp_[static_cast(i)] = 0.0; + yp[static_cast(i)] = 0.0; } return 0; @@ -174,9 +183,11 @@ namespace GridKit template int SexsPti::tagDifferentiable() { - tag_[0] = true; - tag_[1] = true; - tag_[2] = false; + auto* tag = tag_.getData(); + + tag[0] = true; + tag[1] = true; + tag[2] = false; return 0; } @@ -196,7 +207,7 @@ namespace GridKit template int SexsPti::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -240,7 +251,10 @@ namespace GridKit wb_[0] = bus_->Vr(); wb_[1] = bus_->Vi(); - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), ws_.data(), f_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), ws_.data(), f); return 0; } @@ -284,7 +298,9 @@ namespace GridKit { using Variable = typename ModelDataT::MonitorableVariables; monitor_->set(Variable::efd, [this] - { return y_[1]; }); + { + auto* y = y_.getData(); + return y[1]; }); } } // namespace Exciter diff --git a/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Enzyme.cpp b/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Enzyme.cpp index 12839407c..b247628a1 100644 --- a/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Enzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Enzyme.cpp @@ -42,12 +42,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -57,12 +57,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), alpha_, @@ -73,12 +73,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDws, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), ws_.size(), (this->getResidualIndices()).data(), ws_indices_.data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Impl.hpp b/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Impl.hpp index 7069f9ef2..521aa1a77 100644 --- a/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Impl.hpp +++ b/GridKit/Model/PhasorDynamics/Governor/Tgov1/Tgov1Impl.hpp @@ -166,15 +166,26 @@ namespace GridKit template int Tgov1::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } // Allocate local component data auto size = static_cast(size_); // avoid compiler warnings - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize signal variable data ws_.resize(1); @@ -182,17 +193,11 @@ namespace GridKit ws_[0] = 0.0; ws_indices_[0] = INVALID_INDEX; - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - // Set output signals if (signals_.template isAssigned()) { - signals_.template getSignalNode()->set(&y_[2], &(this->getVariableIndex(2))); + auto* y = y_.getData(); + signals_.template getSignalNode()->set(&y[2], &(this->getVariableIndex(2))); } return 0; @@ -230,24 +235,26 @@ namespace GridKit ScalarT p0{0}; // Initial mechanical = initial electric torque + auto* y = y_.getData(); + auto* yp = yp_.getData(); if (signals_.template isAssigned()) { // System base -> governor base for governor initialization. - p0 = toComponentBase(y_[2]); ///<- generator needs to be initialized first + p0 = toComponentBase(y[2]); ///<- generator needs to be initialized first } // Input Variables (Parameter for now) pref_ = R_ * p0; // Internal States - y_[0] = (T3_ - T2_) * p0; // y0 - Ptx (Turbine Power ) - y_[1] = p0; // y1 - Pv (Valve Position) - y_[2] = toSystemBase(p0); // y2 - Pm (Mech Power, System Base) + y[0] = (T3_ - T2_) * p0; // y0 - Ptx (Turbine Power ) + y[1] = p0; // y1 - Pv (Valve Position) + y[2] = toSystemBase(p0); // y2 - Pm (Mech Power, System Base) // D.V. Derivative - yp_[0] = 0.0; // Ptx - yp_[1] = 0.0; // Pv - yp_[2] = 0.0; // Pm + yp[0] = 0.0; // Ptx + yp[1] = 0.0; // Pv + yp[2] = 0.0; // Pm return 0; } @@ -258,10 +265,11 @@ namespace GridKit template int Tgov1::tagDifferentiable() { + auto* tag = tag_.getData(); - tag_[0] = true; // Pv - tag_[1] = true; // Ptx - tag_[2] = false; // Pmech + tag[0] = true; // Pv + tag[1] = true; // Ptx + tag[2] = false; // Pmech return 0; } @@ -281,7 +289,7 @@ namespace GridKit template int Tgov1::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -337,7 +345,10 @@ namespace GridKit ws_indices_[0] = signals_.template readExternalVariableIndex(); } - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), ws_.data(), f_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), ws_.data(), f); return 0; } diff --git a/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZEnzyme.cpp b/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZEnzyme.cpp index 3099d2072..4e5304cf4 100644 --- a/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZEnzyme.cpp @@ -40,12 +40,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, @@ -54,13 +54,13 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus_->y()).data(), + y_.getData(), + yp_.getData(), + bus_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -69,11 +69,11 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDy, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual>::eval(this, static_cast(bus_->size()), - y_.size(), + static_cast(y_.getSize()), (bus_->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZImpl.hpp b/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZImpl.hpp index efc2235a1..1762493e3 100644 --- a/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Load/LoadZ/LoadZImpl.hpp @@ -83,26 +83,32 @@ namespace GridKit template int LoadZ::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } + // std::cout << "Allocate Load..." << std::endl; + auto size = static_cast(size_); // avoid compiler warnings - f_.resize(size); - y_.resize(size); - yp_.resize(size); - abs_tol_.resize(size); - tag_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize coupling data wb_.resize(2); h_.resize(2); - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - return 0; } @@ -118,11 +124,13 @@ namespace GridKit ScalarT ir = -(g_ * vr - b_ * vi); ScalarT ii = -(b_ * vr + g_ * vi); - y_[0] = ir; - y_[1] = ii; + auto* y = y_.getData(); + auto* yp = yp_.getData(); - yp_[0] = 0.0; - yp_[1] = 0.0; + y[0] = ir; + y[1] = ii; + yp[0] = 0.0; + yp[1] = 0.0; return 0; } @@ -133,8 +141,10 @@ namespace GridKit template int LoadZ::tagDifferentiable() { - tag_[0] = false; - tag_[1] = false; + auto* tag = tag_.getData(); + + tag[0] = false; + tag[1] = false; return 0; } @@ -154,7 +164,7 @@ namespace GridKit template int LoadZ::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -205,10 +215,13 @@ namespace GridKit template int LoadZ::evaluateResidual() { - wb_[0] = Vr(); - wb_[1] = Vi(); - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), f_.data()); - evaluateBusResidual(y_.data(), yp_.data(), wb_.data(), h_.data()); + wb_[0] = Vr(); + wb_[1] = Vi(); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), f); + evaluateBusResidual(y, yp, wb_.data(), h_.data()); Ir() += h_[0]; Ii() += h_[1]; @@ -238,9 +251,13 @@ namespace GridKit using Variable = typename ModelDataT::MonitorableVariables; monitor_->set(Variable::p, [this] - { return Vr() * y_[0] + Vi() * y_[1]; }); + { + auto* y = y_.getData(); + return Vr() * y[0] + Vi() * y[1]; }); monitor_->set(Variable::q, [this] - { return Vi() * y_[0] - Vr() * y_[1]; }); + { + auto* y = y_.getData(); + return Vi() * y[0] - Vr() * y[1]; }); } } // namespace PhasorDynamics diff --git a/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPEnzyme.cpp b/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPEnzyme.cpp index 9455f4f72..b067c0cbd 100644 --- a/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPEnzyme.cpp @@ -35,12 +35,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, @@ -49,13 +49,13 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus_->y()).data(), + y_.getData(), + yp_.getData(), + bus_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -64,11 +64,11 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDy, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual>::eval(this, static_cast(bus_->size()), - y_.size(), + static_cast(y_.getSize()), (bus_->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPImpl.hpp b/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPImpl.hpp index 18cd2c7f5..143426852 100644 --- a/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Load/LoadZIP/LoadZIPImpl.hpp @@ -103,26 +103,32 @@ namespace GridKit template int LoadZIP::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } + // std::cout << "Allocate Load..." << std::endl; + auto size = static_cast(size_); // avoid compiler warnings - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize coupling data wb_.resize(2); h_.resize(2); - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - return 0; } @@ -141,11 +147,13 @@ namespace GridKit const ScalarT V = std::sqrt(V2); const ScalarT zip = alphaZ_ + alphaI_ * Vnom_ / V + alphaP_ * Vnom2 / V2; - y_[0] = -(G_ * vr + B_ * vi) * zip; - y_[1] = -(G_ * vi - B_ * vr) * zip; + auto* y = y_.getData(); + auto* yp = yp_.getData(); - yp_[0] = 0.0; - yp_[1] = 0.0; + y[0] = -(G_ * vr + B_ * vi) * zip; + y[1] = -(G_ * vi - B_ * vr) * zip; + yp[0] = 0.0; + yp[1] = 0.0; return 0; } @@ -155,8 +163,10 @@ namespace GridKit template int LoadZIP::tagDifferentiable() { - tag_[0] = false; - tag_[1] = false; + auto* tag = tag_.getData(); + + tag[0] = false; + tag[1] = false; return 0; } @@ -175,7 +185,7 @@ namespace GridKit template int LoadZIP::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -205,10 +215,13 @@ namespace GridKit template int LoadZIP::evaluateResidual() { - wb_[0] = Vr(); - wb_[1] = Vi(); - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), f_.data()); - evaluateBusResidual(y_.data(), yp_.data(), wb_.data(), h_.data()); + wb_[0] = Vr(); + wb_[1] = Vi(); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), f); + evaluateBusResidual(y, yp, wb_.data(), h_.data()); Ir() += h_[0]; Ii() += h_[1]; @@ -267,15 +280,25 @@ namespace GridKit using Variable = typename ModelDataT::MonitorableVariables; monitor_->set(Variable::ir, [this] - { return y_[0]; }); + { + auto* y = y_.getData(); + return y[0]; }); monitor_->set(Variable::ii, [this] - { return y_[1]; }); + { + auto* y = y_.getData(); + return y[1]; }); monitor_->set(Variable::im, [this] - { return std::sqrt(y_[0] * y_[0] + y_[1] * y_[1]); }); + { + auto* y = y_.getData(); + return std::sqrt(y[0] * y[0] + y[1] * y[1]); }); monitor_->set(Variable::p, [this] - { return Vr() * y_[0] + Vi() * y_[1]; }); + { + auto* y = y_.getData(); + return Vr() * y[0] + Vi() * y[1]; }); monitor_->set(Variable::q, [this] - { return Vi() * y_[0] - Vr() * y_[1]; }); + { + auto* y = y_.getData(); + return Vi() * y[0] - Vr() * y[1]; }); } } // namespace PhasorDynamics diff --git a/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestEnzyme.cpp b/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestEnzyme.cpp index a1ff9f40c..4c1af73d9 100644 --- a/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestEnzyme.cpp @@ -44,12 +44,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -59,12 +59,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), alpha_, @@ -75,12 +75,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDws, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), ws_.size(), (this->getResidualIndices()).data(), ws_indices_.data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, diff --git a/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestImpl.hpp b/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestImpl.hpp index 302e5bc63..d49925f95 100644 --- a/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestImpl.hpp +++ b/GridKit/Model/PhasorDynamics/Stabilizer/IEEEST/IeeestImpl.hpp @@ -157,30 +157,36 @@ namespace GridKit template int Ieeest::allocate() { + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } auto size = static_cast(size_); - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } ws_.resize(1); ws_indices_.resize(1); ws_[0] = 0.0; ws_indices_[0] = INVALID_INDEX; - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - if (signals_.template isAssigned()) { + auto* y = y_.getData(); signals_.template getSignalNode()->set( - &y_[11], &(this->getVariableIndex(11))); + &y[11], &(this->getVariableIndex(11))); } return 0; @@ -217,10 +223,13 @@ namespace GridKit template int Ieeest::initialize() { + auto* y = y_.getData(); + auto* yp = yp_.getData(); + for (IdxT i = 0; i < size_; ++i) { - y_[static_cast(i)] = 0.0; - yp_[static_cast(i)] = 0.0; + y[static_cast(i)] = 0.0; + yp[static_cast(i)] = 0.0; } return 0; @@ -229,18 +238,20 @@ namespace GridKit template int Ieeest::tagDifferentiable() { - tag_[0] = true; - tag_[1] = true; - tag_[2] = true; - tag_[3] = true; - tag_[4] = (T2_ != 0.0); - tag_[5] = (T4_ != 0.0); - tag_[6] = (T6_ != 0.0); - tag_[7] = false; - tag_[8] = false; - tag_[9] = false; - tag_[10] = false; - tag_[11] = false; + auto* tag = tag_.getData(); + + tag[0] = true; + tag[1] = true; + tag[2] = true; + tag[3] = true; + tag[4] = (T2_ != 0.0); + tag[5] = (T4_ != 0.0); + tag[6] = (T6_ != 0.0); + tag[7] = false; + tag[8] = false; + tag[9] = false; + tag[10] = false; + tag[11] = false; return 0; } @@ -260,7 +271,7 @@ namespace GridKit template int Ieeest::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -322,7 +333,10 @@ namespace GridKit ws_indices_[0] = signals_.template readExternalVariableIndex(); } - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), ws_.data(), f_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), ws_.data(), f); return 0; } @@ -338,7 +352,7 @@ namespace GridKit { using Variable = typename ModelDataT::MonitorableVariables; monitor_->set(Variable::vss, [this] - { return y_[11]; }); + { return y_.getData()[11]; }); } } // namespace Stabilizer diff --git a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouEnzyme.cpp b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouEnzyme.cpp index 5a89473dc..834d027ab 100644 --- a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouEnzyme.cpp @@ -41,12 +41,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -56,12 +56,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), alpha_, @@ -72,12 +72,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -87,12 +87,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDws, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), ws_.size(), (this->getResidualIndices()).data(), ws_indices_.data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -103,11 +103,11 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDy, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual>::eval(this, static_cast(bus_->size()), - y_.size(), + static_cast(y_.getSize()), (bus_->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, diff --git a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouImpl.hpp b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouImpl.hpp index 523a7563a..a2a2bd3ab 100644 --- a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouImpl.hpp +++ b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENROU/GenrouImpl.hpp @@ -292,19 +292,33 @@ namespace GridKit using Variable = typename ModelDataT::MonitorableVariables; // Convert monitored terminal values to system base. monitor_->set(Variable::ir, [this] - { return toSystemBase(y_[15]); }); + { + auto* y = y_.getData(); + return toSystemBase(y[15]); }); monitor_->set(Variable::ii, [this] - { return toSystemBase(y_[16]); }); + { + auto* y = y_.getData(); + return toSystemBase(y[16]); }); monitor_->set(Variable::p, [this] - { return toSystemBase(Vr() * y_[15] + Vi() * y_[16]); }); + { + auto* y = y_.getData(); + return toSystemBase(Vr() * y[15] + Vi() * y[16]); }); monitor_->set(Variable::q, [this] - { return toSystemBase(Vi() * y_[15] - Vr() * y_[16]); }); + { + auto* y = y_.getData(); + return toSystemBase(Vi() * y[15] - Vr() * y[16]); }); monitor_->set(Variable::delta, [this] - { return y_[0]; }); + { + auto* y = y_.getData(); + return y[0]; }); monitor_->set(Variable::omega, [this] - { return y_[1]; }); + { + auto* y = y_.getData(); + return y[1]; }); monitor_->set(Variable::speed, [this] - { return 1.0 + y_[1]; }); + { + auto* y = y_.getData(); + return 1.0 + y[1]; }); } /** @@ -323,15 +337,25 @@ namespace GridKit template int Genrou::allocate() { - // Resize component model data + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } auto size = static_cast(size_); - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); - abs_tol_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize bus data wb_.resize(2); @@ -343,17 +367,11 @@ namespace GridKit ws_indices_[0] = INVALID_INDEX; ws_indices_[1] = INVALID_INDEX; - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - // Set output signals if (signals_.template isAssigned()) { - signals_.template getSignalNode()->set(&y_[1], &(this->getVariableIndex(1))); + auto* y = y_.getData(); + signals_.template getSignalNode()->set(&y[1], &(this->getVariableIndex(1))); } return 0; @@ -464,31 +482,33 @@ namespace GridKit // Assign from converged values using flux-linkage forms ScalarT omega(0.0); - - y_[0] = delta; - y_[1] = omega; - y_[2] = Eqp; - y_[3] = psidp; - y_[4] = psiqp; - y_[5] = Edp; - y_[6] = psiqpp = -psiqp * Xq4_ - Edp * Xq5_; - y_[7] = psidpp = psidp * Xd4_ + Eqp * Xd5_; - y_[8] = psipp = std::sqrt(psiqpp * psiqpp + psidpp * psidpp); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = delta; + y[1] = omega; + y[2] = Eqp; + y[3] = psidp; + y[4] = psiqp; + y[5] = Edp; + y[6] = psiqpp = -psiqp * Xq4_ - Edp * Xq5_; + y[7] = psidpp = psidp * Xd4_ + Eqp * Xd5_; + y[8] = psipp = std::sqrt(psiqpp * psiqpp + psidpp * psidpp); ScalarT psipp_sat = psipp - SA_; - y_[9] = ksat = (psipp_sat > ZERO) ? SB_ * psipp_sat * psipp_sat : ScalarT{ZERO}; - y_[10] = vd = -psiqpp * (ONE + omega); - y_[11] = vq = psidpp * (ONE + omega); - y_[12] = (psidpp - id * Xdpp_) * iq - (psiqpp - iq * Xdpp_) * id; - y_[13] = id; - y_[14] = iq; - y_[15] = ir; - y_[16] = ii; - y_[17] = G_ * (vd * std::sin(delta) + vq * std::cos(delta)) - - B_ * (vd * -std::cos(delta) + vq * std::sin(delta)); - y_[18] = B_ * (vd * std::sin(delta) + vq * std::cos(delta)) - + G_ * (vd * -std::cos(delta) + vq * std::sin(delta)); - - ScalarT Te = y_[12]; + y[9] = ksat = (psipp_sat > ZERO) ? SB_ * psipp_sat * psipp_sat : ScalarT{ZERO}; + y[10] = vd = -psiqpp * (ONE + omega); + y[11] = vq = psidpp * (ONE + omega); + y[12] = (psidpp - id * Xdpp_) * iq - (psiqpp - iq * Xdpp_) * id; + y[13] = id; + y[14] = iq; + y[15] = ir; + y[16] = ii; + y[17] = G_ * (vd * std::sin(delta) + vq * std::cos(delta)) + - B_ * (vd * -std::cos(delta) + vq * std::sin(delta)); + y[18] = B_ * (vd * std::sin(delta) + vq * std::cos(delta)) + + G_ * (vd * -std::cos(delta) + vq * std::sin(delta)); + + ScalarT Te = y[12]; // Convert Te to system base for governor PM signal. pmech_set_ = toSystemBase(Te); if (signals_.template isAttached()) @@ -504,7 +524,7 @@ namespace GridKit for (IdxT i = 0; i < size_; ++i) { - yp_[static_cast(i)] = 0.0; + yp[static_cast(i)] = 0.0; } return 0; @@ -516,9 +536,11 @@ namespace GridKit template int Genrou::tagDifferentiable() { + auto* tag = tag_.getData(); + for (IdxT i = 0; i < size_; ++i) { - tag_[static_cast(i)] = i < 6; + tag[static_cast(i)] = i < 6; } return 0; } @@ -538,7 +560,7 @@ namespace GridKit template int Genrou::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -669,8 +691,11 @@ namespace GridKit wb_[1] = Vi(); // Residual evaluation - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), ws_.data(), f_.data()); - evaluateBusResidual(y_.data(), yp_.data(), wb_.data(), h_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), ws_.data(), f); + evaluateBusResidual(y, yp, wb_.data(), h_.data()); // Genrou contribution to bus algebraic equations Ir() += h_[0]; diff --git a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalEnzyme.cpp b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalEnzyme.cpp index 8d5796908..185eb20d7 100644 --- a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalEnzyme.cpp @@ -41,12 +41,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -56,12 +56,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), alpha_, @@ -72,12 +72,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -87,12 +87,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDws, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidualWithSignal>::eval(this, - f_.size(), + static_cast(f_.getSize()), ws_.size(), (this->getResidualIndices()).data(), ws_indices_.data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), ws_.data(), J_rows_buffer_, @@ -103,11 +103,11 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDy, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual>::eval(this, static_cast(bus_->size()), - y_.size(), + static_cast(y_.getSize()), (bus_->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, diff --git a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalImpl.hpp b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalImpl.hpp index 318759aaf..b3763591f 100644 --- a/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalImpl.hpp +++ b/GridKit/Model/PhasorDynamics/SynchronousMachine/GENSAL/GensalImpl.hpp @@ -149,37 +149,69 @@ namespace GridKit using Variable = typename ModelDataT::MonitorableVariables; // Convert monitored terminal values to system base. monitor_->set(Variable::ir, [this] - { return toSystemBase(y_[12]); }); + { + auto* y = y_.getData(); + return toSystemBase(y[12]); }); monitor_->set(Variable::ii, [this] - { return toSystemBase(y_[13]); }); + { + auto* y = y_.getData(); + return toSystemBase(y[13]); }); monitor_->set(Variable::p, [this] - { return toSystemBase(Vr() * y_[12] + Vi() * y_[13]); }); + { + auto* y = y_.getData(); + return toSystemBase(Vr() * y[12] + Vi() * y[13]); }); monitor_->set(Variable::q, [this] - { return toSystemBase(Vi() * y_[12] - Vr() * y_[13]); }); + { + auto* y = y_.getData(); + return toSystemBase(Vi() * y[12] - Vr() * y[13]); }); monitor_->set(Variable::delta, [this] - { return y_[0]; }); + { + auto* y = y_.getData(); + return y[0]; }); monitor_->set(Variable::omega, [this] - { return y_[1]; }); + { + auto* y = y_.getData(); + return y[1]; }); monitor_->set(Variable::speed, [this] - { return 1.0 + y_[1]; }); + { + auto* y = y_.getData(); + return 1.0 + y[1]; }); monitor_->set(Variable::Eqp, [this] - { return y_[2]; }); + { + auto* y = y_.getData(); + return y[2]; }); monitor_->set(Variable::psidp, [this] - { return y_[3]; }); + { + auto* y = y_.getData(); + return y[3]; }); monitor_->set(Variable::psiqpp, [this] - { return y_[4]; }); + { + auto* y = y_.getData(); + return y[4]; }); monitor_->set(Variable::psidpp, [this] - { return y_[5]; }); + { + auto* y = y_.getData(); + return y[5]; }); monitor_->set(Variable::vd, [this] - { return y_[7]; }); + { + auto* y = y_.getData(); + return y[7]; }); monitor_->set(Variable::vq, [this] - { return y_[8]; }); + { + auto* y = y_.getData(); + return y[8]; }); monitor_->set(Variable::te, [this] - { return y_[9]; }); + { + auto* y = y_.getData(); + return y[9]; }); monitor_->set(Variable::id, [this] - { return y_[10]; }); + { + auto* y = y_.getData(); + return y[10]; }); monitor_->set(Variable::iq, [this] - { return y_[11]; }); + { + auto* y = y_.getData(); + return y[11]; }); } /** @@ -198,15 +230,25 @@ namespace GridKit template int Gensal::allocate() { - // Resize component model data + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } auto size = static_cast(size_); - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize bus data wb_.resize(2); @@ -218,17 +260,11 @@ namespace GridKit ws_indices_[0] = INVALID_INDEX; ws_indices_[1] = INVALID_INDEX; - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - // Set output signals if (signals_.template isAssigned()) { - signals_.template getSignalNode()->set(&y_[1], &(this->getVariableIndex(1))); + auto* y = y_.getData(); + signals_.template getSignalNode()->set(&y[1], &(this->getVariableIndex(1))); } return 0; @@ -299,24 +335,27 @@ namespace GridKit ScalarT ksat = SB_ * Eqp_sat * Eqp_sat * Math::sigmoid(Eqp_sat); ScalarT Te = (psidpp - id * Xdpp_) * iq - (psiqpp - iq * Xdpp_) * id; - y_[0] = delta; - y_[1] = omega; - y_[2] = Eqp; - y_[3] = psidp; - y_[4] = psiqpp; - y_[5] = psidpp; - y_[6] = ksat; - y_[7] = vd; - y_[8] = vq; - y_[9] = Te; - y_[10] = id; - y_[11] = iq; - y_[12] = ir; - y_[13] = ii; - y_[14] = G_ * (vd * std::sin(delta) + vq * std::cos(delta)) - - B_ * (vd * -std::cos(delta) + vq * std::sin(delta)); - y_[15] = B_ * (vd * std::sin(delta) + vq * std::cos(delta)) - + G_ * (vd * -std::cos(delta) + vq * std::sin(delta)); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = delta; + y[1] = omega; + y[2] = Eqp; + y[3] = psidp; + y[4] = psiqpp; + y[5] = psidpp; + y[6] = ksat; + y[7] = vd; + y[8] = vq; + y[9] = Te; + y[10] = id; + y[11] = iq; + y[12] = ir; + y[13] = ii; + y[14] = G_ * (vd * std::sin(delta) + vq * std::cos(delta)) + - B_ * (vd * -std::cos(delta) + vq * std::sin(delta)); + y[15] = B_ * (vd * std::sin(delta) + vq * std::cos(delta)) + + G_ * (vd * -std::cos(delta) + vq * std::sin(delta)); // Convert Te to system base for governor PM signal. pmech_set_ = toSystemBase(Te); @@ -333,7 +372,7 @@ namespace GridKit for (IdxT i = 0; i < size_; ++i) { - yp_[static_cast(i)] = 0.0; + yp[static_cast(i)] = 0.0; } return 0; @@ -345,9 +384,11 @@ namespace GridKit template int Gensal::tagDifferentiable() { + auto* tag = tag_.getData(); + for (IdxT i = 0; i < size_; ++i) { - tag_[static_cast(i)] = i < 5; + tag[static_cast(i)] = i < 5; } return 0; } @@ -367,7 +408,7 @@ namespace GridKit template int Gensal::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -491,8 +532,11 @@ namespace GridKit wb_[1] = Vi(); // Residual evaluation - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), ws_.data(), f_.data()); - evaluateBusResidual(y_.data(), yp_.data(), wb_.data(), h_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), ws_.data(), f); + evaluateBusResidual(y, yp, wb_.data(), h_.data()); // Gensal contribution to bus algebraic equations Ir() += h_[0]; diff --git a/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalEnzyme.cpp b/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalEnzyme.cpp index 5ec2d4d31..0e9d3b8fe 100644 --- a/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalEnzyme.cpp +++ b/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalEnzyme.cpp @@ -40,12 +40,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDy, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, @@ -54,12 +54,12 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDyp, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), - y_.size(), + static_cast(f_.getSize()), + static_cast(y_.getSize()), (this->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), alpha_, J_rows_buffer_, @@ -69,13 +69,13 @@ namespace GridKit GridKit::Enzyme::Sparse::DfDwb, GridKit::Enzyme::Sparse::MemberFunctions::InternalResidual>::eval(this, - f_.size(), + static_cast(f_.getSize()), static_cast(bus_->size()), (this->getResidualIndices()).data(), (bus_->getVariableIndices()).data(), - y_.data(), - yp_.data(), - (bus_->y()).data(), + y_.getData(), + yp_.getData(), + bus_->y().getData(), J_rows_buffer_, J_cols_buffer_, J_vals_buffer_, @@ -84,11 +84,11 @@ namespace GridKit GridKit::Enzyme::Sparse::DhDy, GridKit::Enzyme::Sparse::MemberFunctions::BusResidual>::eval(this, static_cast(bus_->size()), - y_.size(), + static_cast(y_.getSize()), (bus_->getResidualIndices()).data(), (this->getVariableIndices()).data(), - y_.data(), - yp_.data(), + y_.getData(), + yp_.getData(), wb_.data(), J_rows_buffer_, J_cols_buffer_, diff --git a/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalImpl.hpp b/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalImpl.hpp index e65140258..d530a3458 100644 --- a/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalImpl.hpp +++ b/GridKit/Model/PhasorDynamics/SynchronousMachine/GenClassical/GenClassicalImpl.hpp @@ -147,17 +147,29 @@ namespace GridKit { using Variable = typename ModelDataT::MonitorableVariables; monitor_->set(Variable::ir, [this] - { return toSystemBase(y_[3]); }); + { + auto* y = y_.getData(); + return toSystemBase(y[3]); }); monitor_->set(Variable::ii, [this] - { return toSystemBase(y_[4]); }); + { + auto* y = y_.getData(); + return toSystemBase(y[4]); }); monitor_->set(Variable::p, [this] - { return toSystemBase(Vr() * y_[3] + Vi() * y_[4]); }); + { + auto* y = y_.getData(); + return toSystemBase(Vr() * y[3] + Vi() * y[4]); }); monitor_->set(Variable::q, [this] - { return toSystemBase(Vi() * y_[3] - Vr() * y_[4]); }); + { + auto* y = y_.getData(); + return toSystemBase(Vi() * y[3] - Vr() * y[4]); }); monitor_->set(Variable::delta, [this] - { return y_[0]; }); + { + auto* y = y_.getData(); + return y[0]; }); monitor_->set(Variable::omega, [this] - { return y_[1]; }); + { + auto* y = y_.getData(); + return y[1]; }); } /** @@ -176,27 +188,30 @@ namespace GridKit template int GenClassical::allocate() { - // Resize component model data + if (!this->allocated_) + { + this->allocateVectors(this->size_); + } auto size = static_cast(size_); - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + variable_indices_.resize(size); residual_indices_.resize(size); + for (IdxT j = 0; j < size_; ++j) + { + variable_indices_[static_cast(j)] = this->offset_ + j; + residual_indices_[static_cast(j)] = this->offset_ + j; + } // Resize coupling data wb_.resize(2); h_.resize(2); - // Default variable and residual index mapping to local index - for (IdxT j = 0; j < size_; ++j) - { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); - } - return 0; } @@ -220,16 +235,19 @@ namespace GridKit ScalarT Ep = std::sqrt(Er * Er + Ei * Ei); ScalarT Te = G_ * Ep * Ep - Ep * ((G_ * vr - B_ * vi) * std::cos(delta) + (B_ * vr + G_ * vi) * std::sin(delta)); - y_[0] = delta; - y_[1] = omega; - y_[2] = Te; - y_[3] = ir; - y_[4] = ii; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = delta; + y[1] = omega; + y[2] = Te; + y[3] = ir; + y[4] = ii; pmech_set_ = Te; ep_set_ = Ep; for (size_t i = 0; i < static_cast(size_); ++i) - yp_[i] = 0.0; + yp[i] = 0.0; return 0; } @@ -240,9 +258,11 @@ namespace GridKit template int GenClassical::tagDifferentiable() { + auto* tag = tag_.getData(); + for (IdxT i = 0; i < size_; ++i) { - tag_[static_cast(i)] = i < 2; + tag[static_cast(i)] = i < 2; } return 0; } @@ -262,7 +282,7 @@ namespace GridKit template int GenClassical::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -336,8 +356,11 @@ namespace GridKit wb_[0] = Vr(); wb_[1] = Vi(); - evaluateInternalResidual(y_.data(), yp_.data(), wb_.data(), f_.data()); - evaluateBusResidual(y_.data(), yp_.data(), wb_.data(), h_.data()); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + evaluateInternalResidual(y, yp, wb_.data(), f); + evaluateBusResidual(y, yp, wb_.data(), h_.data()); Ir() += h_[0]; Ii() += h_[1]; diff --git a/GridKit/Model/PhasorDynamics/SystemModel.hpp b/GridKit/Model/PhasorDynamics/SystemModel.hpp index 2f0524535..38d5ed1f6 100644 --- a/GridKit/Model/PhasorDynamics/SystemModel.hpp +++ b/GridKit/Model/PhasorDynamics/SystemModel.hpp @@ -55,6 +55,9 @@ namespace GridKit using Component::residual_indices_; using Component::csr_jac_; using Component::map_to_csr_; + using Component::offset_; + using Component::allocated_; + using Component::allocateVectors; public: using ScalarT = scalar_type; @@ -92,7 +95,11 @@ namespace GridKit int evaluateResidual() override; int evaluateJacobian() override; - void updateVariables(); + CsrMatrixT* getCsrJacobian() const override + { + return csr_jac_; + } + void updateTime(RealT t, RealT a) override; void addBus(BusT* bus); diff --git a/GridKit/Model/PhasorDynamics/SystemModelImpl.hpp b/GridKit/Model/PhasorDynamics/SystemModelImpl.hpp index b020f8f72..b985d9cfe 100644 --- a/GridKit/Model/PhasorDynamics/SystemModelImpl.hpp +++ b/GridKit/Model/PhasorDynamics/SystemModelImpl.hpp @@ -1,4 +1,5 @@ #include +#include #include #include @@ -423,11 +424,10 @@ namespace GridKit } /** - * @brief Allocate buses, components, and system objects. + * @brief Allocate buses, components, and system metadata. * - * This method first allocates bus objects, then component objects, - * and computes system size (number of unknowns). Once the size is - * computed, system global objects are allocated. + * This method computes the system size, allocates the system vectors, + * binds child models to contiguous slices, and allocates child internals. * * @post size_ >= 1 * @@ -436,45 +436,62 @@ namespace GridKit int SystemModel::allocate() { size_ = 0; - - // Allocate all buses for (const auto& bus : buses_) { - bus->allocate(); - for (IdxT j = 0; j < bus->size(); ++j) - { - bus->setVariableIndex(j, size_ + j); - bus->setResidualIndex(j, size_ + j); - } size_ += bus->size(); } - - // Allocate all components for (const auto& component : components_) { - component->allocate(); - for (IdxT j = 0; j < component->size(); ++j) - { - component->setVariableIndex(j, size_ + j); - component->setResidualIndex(j, size_ + j); - } size_ += component->size(); } - // Allocate global vectors - y_.resize(size_); - yp_.resize(size_); - f_.resize(size_); - tag_.resize(size_); - abs_tol_.resize(size_); - variable_indices_.resize(size_); - residual_indices_.resize(size_); + auto size = static_cast(size_); + + if (!allocated_) + { + allocateVectors(size_); + } + + assert(y_.getSize() == size); + assert(yp_.getSize() == size); + assert(f_.getSize() == size); + assert(tag_.getSize() == size); + assert(abs_tol_.getSize() == size); + + IdxT child_offset = 0; + for (const auto& bus : buses_) + { + bus->bind(y_, yp_, f_, tag_, abs_tol_, child_offset); + child_offset += bus->size(); + } + + for (const auto& component : components_) + { + component->bind(y_, yp_, f_, tag_, abs_tol_, child_offset); + child_offset += component->size(); + } + + assert(child_offset == size_); - // Default variable and residual index mapping to local index + variable_indices_.resize(size); + residual_indices_.resize(size); for (IdxT j = 0; j < size_; ++j) { - this->setVariableIndex(j, j); - this->setResidualIndex(j, j); + variable_indices_[static_cast(j)] = offset_ + j; + residual_indices_[static_cast(j)] = offset_ + j; + } + + assert(variable_indices_.size() == static_cast(size_)); + assert(residual_indices_.size() == static_cast(size_)); + + for (const auto& bus : buses_) + { + bus->allocate(); + } + + for (const auto& component : components_) + { + component->allocate(); } // Verify component configuration @@ -571,43 +588,25 @@ namespace GridKit * Also, generators may write to control devices (e.g. governors, * exciters, etc.) during the initialization. * - * @todo Implement writting to system vectors in a thread-safe way. + * @todo Make initialization writes to system vectors thread-safe. * - * @note Currently assuming each component stores variables contiguously in memory and - * that these are simply concateneted in the global system. + * @note Each bus and component is bound to a contiguous slice of the global system state. */ template int SystemModel::initialize() { + // Buses initialize first: components may read bus values during their own + // initialization. Writes land directly in the global vector storage. for (const auto& bus : buses_) { bus->initialize(); } - for (const auto& bus : buses_) - { - for (IdxT j = 0; j < bus->size(); ++j) - { - y_[bus->getVariableIndex(j)] = bus->y()[j]; - yp_[bus->getVariableIndex(j)] = bus->yp()[j]; - } - } - - // Initialize components for (const auto& component : components_) { component->initialize(); } - for (const auto& component : components_) - { - for (IdxT j = 0; j < component->size(); ++j) - { - y_[component->getVariableIndex(j)] = component->y()[j]; - yp_[component->getVariableIndex(j)] = component->yp()[j]; - } - } - return 0; } @@ -674,19 +673,11 @@ namespace GridKit for (const auto& bus : buses_) { bus->tagDifferentiable(); - for (IdxT j = 0; j < bus->size(); ++j) - { - tag_[bus->getVariableIndex(j)] = bus->tag()[j]; - } } for (const auto& component : components_) { component->tagDifferentiable(); - for (IdxT j = 0; j < component->size(); ++j) - { - tag_[component->getVariableIndex(j)] = component->tag()[j]; - } } return 0; @@ -705,25 +696,14 @@ namespace GridKit template int SystemModel::setAbsoluteTolerance(RealT rel_tol) { - IdxT offset = 0; for (const auto& bus : buses_) { bus->setAbsoluteTolerance(rel_tol); - for (IdxT j = 0; j < bus->size(); ++j) - { - abs_tol_[offset + j] = bus->absoluteTolerance()[j]; - } - offset += bus->size(); } for (const auto& component : components_) { component->setAbsoluteTolerance(rel_tol); - for (IdxT j = 0; j < component->size(); ++j) - { - abs_tol_[offset + j] = component->absoluteTolerance()[j]; - } - offset += component->size(); } return 0; @@ -732,26 +712,20 @@ namespace GridKit /** * @brief Compute system residual vector * - * First, update bus and component variables from the system solution - * vector. Next, evaluate residuals in buses and components, and - * then copy values to the global residual vector. + * Buses and components are bound to the system state during allocation. + * Residual evaluation therefore reads the current system values and + * writes residuals directly into the global residual vector. * * @warning Residuals must be computed for buses, before component * residuals are computed. Buses own residuals for currents * Ir and Ii, but the contributions to these residuals come * from components. Buses assign their residual values, while components - * add to those values by in-place adition. This is why (for now) bus + * add to those values by in-place addition. This is why (for now) bus * residuals need to be computed first. - * - * @todo Here, components write to local values, which are then copied - * to global system vectors. Make components write to the system - * vectors directly. */ template int SystemModel::evaluateResidual() { - updateVariables(); - for (const auto& bus : buses_) { bus->evaluateResidual(); @@ -762,23 +736,6 @@ namespace GridKit component->evaluateResidual(); } - // Update residual vector - for (const auto& bus : buses_) - { - for (IdxT j = 0; j < bus->size(); ++j) - { - f_[bus->getResidualIndex(j)] = bus->getResidual()[j]; - } - } - - for (const auto& component : components_) - { - for (IdxT j = 0; j < component->size(); ++j) - { - f_[component->getResidualIndex(j)] = component->getResidual()[j]; - } - } - return 0; } @@ -977,30 +934,6 @@ namespace GridKit return 0; } - /** - * @brief Update variables in buses and components - */ - template - void SystemModel::updateVariables() - { - for (const auto& bus : buses_) - { - for (IdxT j = 0; j < bus->size(); ++j) - { - bus->y()[j] = y_[bus->getVariableIndex(j)]; - bus->yp()[j] = yp_[bus->getVariableIndex(j)]; - } - } - for (const auto& component : components_) - { - for (IdxT j = 0; j < component->size(); ++j) - { - component->y()[j] = y_[component->getVariableIndex(j)]; - component->yp()[j] = yp_[component->getVariableIndex(j)]; - } - } - } - /** * @brief Update time * @@ -1014,8 +947,6 @@ namespace GridKit { component->updateTime(t, a); } - - updateVariables(); } /** diff --git a/GridKit/Model/PowerElectronics/Bus/GroundedBus.hpp b/GridKit/Model/PowerElectronics/Bus/GroundedBus.hpp index c79ddfc63..3d04114f4 100644 --- a/GridKit/Model/PowerElectronics/Bus/GroundedBus.hpp +++ b/GridKit/Model/PowerElectronics/Bus/GroundedBus.hpp @@ -22,7 +22,8 @@ namespace GridKit if (int err_code = NodeBase::initialize()) return err_code; - y()[0] = voltage_; + auto* y_data = y().getData(); + y_data[0] = voltage_; return 0; } diff --git a/GridKit/Model/PowerElectronics/CMakeLists.txt b/GridKit/Model/PowerElectronics/CMakeLists.txt index fee2e752f..98dce1148 100644 --- a/GridKit/Model/PowerElectronics/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/CMakeLists.txt @@ -2,6 +2,9 @@ add_library(power_electronics_circuit_node INTERFACE) target_include_directories( power_electronics_circuit_node INTERFACE $ $) +target_link_libraries( + power_electronics_circuit_node + INTERFACE GridKit::dense_vector) add_library(GridKit::power_electronics_circuit_node ALIAS power_electronics_circuit_node) diff --git a/GridKit/Model/PowerElectronics/Capacitor/CMakeLists.txt b/GridKit/Model/PowerElectronics/Capacitor/CMakeLists.txt index 49aad14b6..4a7bd323c 100644 --- a/GridKit/Model/PowerElectronics/Capacitor/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/Capacitor/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_capacitor SOURCES Capacitor.cpp - HEADERS Capacitor.hpp) + HEADERS Capacitor.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/Capacitor/Capacitor.cpp b/GridKit/Model/PowerElectronics/Capacitor/Capacitor.cpp index f21ebaa6a..e950b5bfc 100644 --- a/GridKit/Model/PowerElectronics/Capacitor/Capacitor.cpp +++ b/GridKit/Model/PowerElectronics/Capacitor/Capacitor.cpp @@ -59,17 +59,21 @@ namespace GridKit template int Capacitor::evaluateInternalResidual() { - f_int_[0] = -C_ * yp_int_[0] + y_[0] - y_[1] - y_int_[0]; + auto* y = y_.getData(); + + f_int_[0] = -C_ * yp_int_[0] + y[0] - y[1] - y_int_[0]; return 0; } template int Capacitor::evaluateExternalResidual() { + auto* f = f_.getData(); + // input - f_[0] = C_ * yp_int_[0]; + f[0] = C_ * yp_int_[0]; // output - f_[1] = -C_ * yp_int_[0]; + f[1] = -C_ * yp_int_[0]; return 0; } diff --git a/GridKit/Model/PowerElectronics/CircuitComponent.hpp b/GridKit/Model/PowerElectronics/CircuitComponent.hpp index 995135f08..15e8ca419 100644 --- a/GridKit/Model/PowerElectronics/CircuitComponent.hpp +++ b/GridKit/Model/PowerElectronics/CircuitComponent.hpp @@ -17,9 +17,19 @@ namespace GridKit template class CircuitComponent : public Model::Evaluator { + protected: + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::allocated_; + using Model::Evaluator::allocateVectors; + public: using RealT = typename Model::Evaluator::RealT; using CsrMatrixT = typename Model::Evaluator::CsrMatrixT; + using VectorT = typename Model::Evaluator::VectorT; CircuitComponent() = default; @@ -96,10 +106,10 @@ namespace GridKit connection_nodes_ = std::make_unique(static_cast(size_)); - y_.resize(static_cast(size_)); - yp_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); - f_.resize(static_cast(size_)); + if (!allocated_) + { + allocateVectors(size_); + } return 0; } @@ -259,132 +269,132 @@ namespace GridKit return size_opt_; } - std::vector& y() final + VectorT& y() final { return y_; } - const std::vector& y() const final + const VectorT& y() const final { return y_; } - std::vector& yp() final + VectorT& yp() final { return yp_; } - const std::vector& yp() const final + const VectorT& yp() const final { return yp_; } - std::vector& tag() final + VectorT& tag() final { return tag_; } - const std::vector& tag() const final + const VectorT& tag() const final { return tag_; } - std::vector& absoluteTolerance() final + VectorT& absoluteTolerance() final { return abs_tol_; } - const std::vector& absoluteTolerance() const final + const VectorT& absoluteTolerance() const final { return abs_tol_; } - std::vector& yB() final + VectorT& yB() final { return yB_; } - const std::vector& yB() const final + const VectorT& yB() const final { return yB_; } - std::vector& ypB() final + VectorT& ypB() final { return ypB_; } - const std::vector& ypB() const final + const VectorT& ypB() const final { return ypB_; } - std::vector& param() final + VectorT& param() final { return param_; } - const std::vector& param() const final + const VectorT& param() const final { return param_; } - std::vector& param_up() final + VectorT& param_up() final { return param_up_; } - const std::vector& param_up() const final + const VectorT& param_up() const final { return param_up_; } - std::vector& param_lo() final + VectorT& param_lo() final { return param_lo_; } - const std::vector& param_lo() const final + const VectorT& param_lo() const final { return param_lo_; } - std::vector& getResidual() final + VectorT& getResidual() final { return f_; } - const std::vector& getResidual() const final + const VectorT& getResidual() const final { return f_; } - std::vector& getIntegrand() final + VectorT& getIntegrand() final { return g_; } - const std::vector& getIntegrand() const final + const VectorT& getIntegrand() const final { return g_; } - std::vector& getAdjointResidual() final + VectorT& getAdjointResidual() final { return fB_; } - const std::vector& getAdjointResidual() const final + const VectorT& getAdjointResidual() const final { return fB_; } - std::vector& getAdjointIntegrand() final + VectorT& getAdjointIntegrand() final { return gB_; } - const std::vector& getAdjointIntegrand() const final + const VectorT& getAdjointIntegrand() const final { return gB_; } @@ -423,21 +433,16 @@ namespace GridKit /// @brief A pointer to the internal residuals of this component ScalarT* f_int_; - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; - std::vector g_; - - std::vector yB_; - std::vector ypB_; - std::vector fB_; - std::vector gB_; - - std::vector param_; - std::vector param_up_; - std::vector param_lo_; + VectorT g_; + + VectorT yB_; + VectorT ypB_; + VectorT fB_; + VectorT gB_; + + VectorT param_; + VectorT param_up_; + VectorT param_lo_; RealT time_; RealT alpha_; diff --git a/GridKit/Model/PowerElectronics/CircuitNode.hpp b/GridKit/Model/PowerElectronics/CircuitNode.hpp index 07b14b9df..b0dc2d485 100644 --- a/GridKit/Model/PowerElectronics/CircuitNode.hpp +++ b/GridKit/Model/PowerElectronics/CircuitNode.hpp @@ -15,7 +15,16 @@ namespace GridKit template class CircuitNode : public Model::Evaluator { - using RealT = typename Model::Evaluator::RealT; + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::allocated_; + using Model::Evaluator::allocateVectors; + + using RealT = typename Model::Evaluator::RealT; + using VectorT = typename Model::Evaluator::VectorT; public: CircuitNode() @@ -45,35 +54,32 @@ namespace GridKit // Voltage accessor ScalarT& V() { - return y_[0]; + return y_.getData()[0]; } const ScalarT& V() const { - return y_[0]; + return y_.getData()[0]; } // KCL residual accessor ScalarT& I() { - return f_[0]; + return f_.getData()[0]; } const ScalarT& I() const { - return f_[0]; + return f_.getData()[0]; } // Allocate storage for a single-node voltage and KCL residual int allocate() { - size_t size = static_cast(size_); - - y_.resize(size); - yp_.resize(size); - f_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + if (!allocated_) + { + allocateVectors(size_); + } variable_indices_[0] = 0; residual_indices_[0] = 0; @@ -86,8 +92,11 @@ namespace GridKit */ int initialize() { - y_[0] = V0_; - yp_[0] = 0.0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = V0_; + yp[0] = 0.0; return 0; } @@ -97,7 +106,9 @@ namespace GridKit */ int tagDifferentiable() { - tag_[0] = false; + auto* tag = tag_.getData(); + + tag[0] = false; return 0; } @@ -116,7 +127,7 @@ namespace GridKit */ int setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -129,7 +140,9 @@ namespace GridKit */ int evaluateResidual() { - f_[0] = 0.0; + auto* f = f_.getData(); + + f[0] = 0.0; return 0; } @@ -178,21 +191,15 @@ namespace GridKit std::map variable_indices_; std::map residual_indices_; - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; - - std::vector g_{}; - std::vector param_{}; - std::vector param_up_{}; - std::vector param_lo_{}; + VectorT g_{}; + VectorT param_{}; + VectorT param_up_{}; + VectorT param_lo_{}; - std::vector yB_{}; - std::vector ypB_{}; - std::vector fB_{}; - std::vector gB_{}; + VectorT yB_{}; + VectorT ypB_{}; + VectorT fB_{}; + VectorT gB_{}; RealT time_{0}; RealT alpha_{0}; @@ -225,132 +232,132 @@ namespace GridKit // No time to update in node models } - std::vector& y() final + VectorT& y() final { return y_; } - const std::vector& y() const final + const VectorT& y() const final { return y_; } - std::vector& yp() final + VectorT& yp() final { return yp_; } - const std::vector& yp() const final + const VectorT& yp() const final { return yp_; } - std::vector& tag() final + VectorT& tag() final { return tag_; } - const std::vector& tag() const final + const VectorT& tag() const final { return tag_; } - std::vector& absoluteTolerance() final + VectorT& absoluteTolerance() final { return abs_tol_; } - const std::vector& absoluteTolerance() const final + const VectorT& absoluteTolerance() const final { return abs_tol_; } - std::vector& yB() final + VectorT& yB() final { return yB_; } - const std::vector& yB() const final + const VectorT& yB() const final { return yB_; } - std::vector& ypB() final + VectorT& ypB() final { return ypB_; } - const std::vector& ypB() const final + const VectorT& ypB() const final { return ypB_; } - std::vector& param() final + VectorT& param() final { return param_; } - const std::vector& param() const final + const VectorT& param() const final { return param_; } - std::vector& param_up() final + VectorT& param_up() final { return param_up_; } - const std::vector& param_up() const final + const VectorT& param_up() const final { return param_up_; } - std::vector& param_lo() final + VectorT& param_lo() final { return param_lo_; } - const std::vector& param_lo() const final + const VectorT& param_lo() const final { return param_lo_; } - std::vector& getResidual() final + VectorT& getResidual() final { return f_; } - const std::vector& getResidual() const final + const VectorT& getResidual() const final { return f_; } - std::vector& getIntegrand() final + VectorT& getIntegrand() final { return g_; } - const std::vector& getIntegrand() const final + const VectorT& getIntegrand() const final { return g_; } - std::vector& getAdjointResidual() final + VectorT& getAdjointResidual() final { return fB_; } - const std::vector& getAdjointResidual() const final + const VectorT& getAdjointResidual() const final { return fB_; } - std::vector& getAdjointIntegrand() final + VectorT& getAdjointIntegrand() final { return gB_; } - const std::vector& getAdjointIntegrand() const final + const VectorT& getAdjointIntegrand() const final { return gB_; } diff --git a/GridKit/Model/PowerElectronics/DistributedGenerator/CMakeLists.txt b/GridKit/Model/PowerElectronics/DistributedGenerator/CMakeLists.txt index 8443f1c62..f42fe6a29 100644 --- a/GridKit/Model/PowerElectronics/DistributedGenerator/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/DistributedGenerator/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_disgen SOURCES DistributedGenerator.cpp - HEADERS DistributedGenerator.hpp) + HEADERS DistributedGenerator.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/DistributedGenerator/DistributedGenerator.cpp b/GridKit/Model/PowerElectronics/DistributedGenerator/DistributedGenerator.cpp index 797022531..02984b539 100644 --- a/GridKit/Model/PowerElectronics/DistributedGenerator/DistributedGenerator.cpp +++ b/GridKit/Model/PowerElectronics/DistributedGenerator/DistributedGenerator.cpp @@ -92,7 +92,7 @@ namespace GridKit template int DistributedGenerator::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -105,10 +105,11 @@ namespace GridKit { ScalarT omega = wb_ - mp_ * y_int_[0]; ScalarT delta = refframe_ ? ScalarT(0.0) : y_int_[12]; + auto* y = y_.getData(); // Take incoming voltages to current rotator reference frame - ScalarT vbd_in = std::cos(delta) * y_[1] + std::sin(delta) * y_[2]; - ScalarT vbq_in = -std::sin(delta) * y_[1] + std::cos(delta) * y_[2]; + ScalarT vbd_in = std::cos(delta) * y[1] + std::sin(delta) * y[2]; + ScalarT vbq_in = -std::sin(delta) * y[1] + std::cos(delta) * y[2]; // ### Internal Componenets ## // P and Q equations @@ -145,7 +146,7 @@ namespace GridKit // Rotor difference angle if (!refframe_) - f_int_[12] = -yp_int_[12] + omega - y_[0]; + f_int_[12] = -yp_int_[12] + omega - y[0]; return 0; } @@ -155,20 +156,23 @@ namespace GridKit { ScalarT omega = wb_ - mp_ * y_int_[0]; ScalarT delta = refframe_ ? ScalarT(0.0) : y_int_[12]; + auto* y = y_.getData(); + auto* f = f_.getData(); + // ref common ref motor angle if (refframe_) { - f_[0] = omega - y_[0]; + f[0] = omega - y[0]; } else { - f_[0] = 0.0; + f[0] = 0.0; } // output // current transformed to common frame - f_[1] = std::cos(delta) * y_int_[10] - std::sin(delta) * y_int_[11]; - f_[2] = std::sin(delta) * y_int_[10] + std::cos(delta) * y_int_[11]; + f[1] = std::cos(delta) * y_int_[10] - std::sin(delta) * y_int_[11]; + f[2] = std::sin(delta) * y_int_[10] + std::cos(delta) * y_int_[11]; return 0; } @@ -377,7 +381,10 @@ namespace GridKit wb_ - mp_ * static_cast(y_int_[0]), }; if (!refframe_) - valtemp.push_back((1.0 / Lc_) * (sin(delta) * static_cast(y_[1]) - cos(delta) * static_cast(y_[2]))); + { + auto* y = y_.getData(); + valtemp.push_back((1.0 / Lc_) * (sin(delta) * static_cast(y[1]) - cos(delta) * static_cast(y[2]))); + } this->setJacValues(rtemp, ctemp, valtemp); // r = 14 @@ -396,7 +403,10 @@ namespace GridKit -rLc_ / Lc_ - alpha_, }; if (!refframe_) - valtemp.push_back((1.0 / Lc_) * (cos(delta) * static_cast(y_[1]) + sin(delta) * static_cast(y_[2]))); + { + auto* y = y_.getData(); + valtemp.push_back((1.0 / Lc_) * (cos(delta) * static_cast(y[1]) + sin(delta) * static_cast(y[2]))); + } this->setJacValues(rtemp, ctemp, valtemp); if (!refframe_) diff --git a/GridKit/Model/PowerElectronics/InductionMotor/CMakeLists.txt b/GridKit/Model/PowerElectronics/InductionMotor/CMakeLists.txt index 46e2f645c..df4e46fa4 100644 --- a/GridKit/Model/PowerElectronics/InductionMotor/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/InductionMotor/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_inductionmotor SOURCES InductionMotor.cpp - HEADERS InductionMotor.hpp) + HEADERS InductionMotor.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/InductionMotor/InductionMotor.cpp b/GridKit/Model/PowerElectronics/InductionMotor/InductionMotor.cpp index 337c4fe7c..e0b2004c0 100644 --- a/GridKit/Model/PowerElectronics/InductionMotor/InductionMotor.cpp +++ b/GridKit/Model/PowerElectronics/InductionMotor/InductionMotor.cpp @@ -70,22 +70,28 @@ namespace GridKit template int InductionMotor::evaluateInternalResidual() { - f_int_[0] = (1.0 / 3.0) * (2.0 * y_[0] - y_[1] - y_[2]) - Rs_ * y_int_[0] - (Lls_ + Lms_) * yp_int_[0] - Lms_ * yp_int_[1]; - f_int_[1] = (1.0 / std::sqrt(3.0)) * (-y_[1] + y_[2]) - Rs_ * y_int_[1] - (Lls_ + Lms_) * yp_int_[1] - Lms_ * yp_int_[0]; - f_int_[2] = (y_[0] + y_[1] + y_[2]) / 3.0 - Rs_ * y_int_[2] - Lls_ * yp_int_[7]; - f_int_[3] = Rr_ * y_int_[3] + (Llr_ + Lms_) * yp_int_[8] + Lms_ * yp_int_[0] - (P_ / 2.0) * y_[3] * ((Llr_ + Lms_) * y_int_[4] + Lms_ * y_int_[1]); - f_int_[4] = Rr_ * y_int_[4] + (Llr_ + Lms_) * yp_int_[9] + Lms_ * yp_int_[1] + (P_ / 2.0) * y_[3] * ((Llr_ + Lms_) * y_int_[3] + Lms_ * y_int_[0]); + auto* y = y_.getData(); + + f_int_[0] = (1.0 / 3.0) * (2.0 * y[0] - y[1] - y[2]) - Rs_ * y_int_[0] - (Lls_ + Lms_) * yp_int_[0] - Lms_ * yp_int_[1]; + f_int_[1] = (1.0 / std::sqrt(3.0)) * (-y[1] + y[2]) - Rs_ * y_int_[1] - (Lls_ + Lms_) * yp_int_[1] - Lms_ * yp_int_[0]; + f_int_[2] = (y[0] + y[1] + y[2]) / 3.0 - Rs_ * y_int_[2] - Lls_ * yp_int_[7]; + f_int_[3] = Rr_ * y_int_[3] + (Llr_ + Lms_) * yp_int_[8] + Lms_ * yp_int_[0] - (P_ / 2.0) * y[3] * ((Llr_ + Lms_) * y_int_[4] + Lms_ * y_int_[1]); + f_int_[4] = Rr_ * y_int_[4] + (Llr_ + Lms_) * yp_int_[9] + Lms_ * yp_int_[1] + (P_ / 2.0) * y[3] * ((Llr_ + Lms_) * y_int_[3] + Lms_ * y_int_[0]); return 0; } template int InductionMotor::evaluateExternalResidual() { - f_[0] = y_int_[0] + y_int_[2]; - f_[1] = (-1.0 / 2.0) * y_int_[0] - (std::sqrt(3.0) / 2.0) * y_int_[1] + y_int_[2]; - f_[2] = (-1.0 / 2.0) * y_int_[0] + (std::sqrt(3.0) / 2.0) * y_int_[1] + y_int_[2]; - f_[3] = RJ_ * yp_[3] - (3.0 / 4.0) * P_ * Lms_ * (y_[5] * y_int_[4] - y_int_[1] * y_int_[3]); - f_[4] = yp_[4] - y_[3]; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + + f[0] = y_int_[0] + y_int_[2]; + f[1] = (-1.0 / 2.0) * y_int_[0] - (std::sqrt(3.0) / 2.0) * y_int_[1] + y_int_[2]; + f[2] = (-1.0 / 2.0) * y_int_[0] + (std::sqrt(3.0) / 2.0) * y_int_[1] + y_int_[2]; + f[3] = RJ_ * yp[3] - (3.0 / 4.0) * P_ * Lms_ * (y[5] * y_int_[4] - y_int_[1] * y_int_[3]); + f[4] = yp[4] - y[3]; return 0; } diff --git a/GridKit/Model/PowerElectronics/Inductor/CMakeLists.txt b/GridKit/Model/PowerElectronics/Inductor/CMakeLists.txt index 8bb22f467..b00478d2d 100644 --- a/GridKit/Model/PowerElectronics/Inductor/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/Inductor/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_inductor SOURCES Inductor.cpp - HEADERS Inductor.hpp) + HEADERS Inductor.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/Inductor/Inductor.cpp b/GridKit/Model/PowerElectronics/Inductor/Inductor.cpp index 5a8527c55..3a52a84d3 100644 --- a/GridKit/Model/PowerElectronics/Inductor/Inductor.cpp +++ b/GridKit/Model/PowerElectronics/Inductor/Inductor.cpp @@ -66,7 +66,7 @@ namespace GridKit template int Inductor::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -77,17 +77,21 @@ namespace GridKit template int Inductor::evaluateInternalResidual() { - f_int_[0] = -L_ * yp_int_[0] + y_[1] - y_[0]; + auto* y = y_.getData(); + + f_int_[0] = -L_ * yp_int_[0] + y[1] - y[0]; return 0; } template int Inductor::evaluateExternalResidual() { + auto* f = f_.getData(); + // input - f_[0] = -y_int_[0]; + f[0] = -y_int_[0]; // output - f_[1] = y_int_[0]; + f[1] = y_int_[0]; return 0; } diff --git a/GridKit/Model/PowerElectronics/LinearTransformer/CMakeLists.txt b/GridKit/Model/PowerElectronics/LinearTransformer/CMakeLists.txt index 0c2c9b7f7..8a2bcb6dd 100644 --- a/GridKit/Model/PowerElectronics/LinearTransformer/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/LinearTransformer/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_lineartrasnformer SOURCES LinearTransformer.cpp - HEADERS LinearTransformer.hpp) + HEADERS LinearTransformer.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/LinearTransformer/LinearTransformer.cpp b/GridKit/Model/PowerElectronics/LinearTransformer/LinearTransformer.cpp index 615b43578..e6e69130e 100644 --- a/GridKit/Model/PowerElectronics/LinearTransformer/LinearTransformer.cpp +++ b/GridKit/Model/PowerElectronics/LinearTransformer/LinearTransformer.cpp @@ -71,16 +71,20 @@ namespace GridKit template int LinearTransformer::evaluateInternalResidual() { - f_int_[0] = y_[0] - R0_ * y_int_[0] - L0_ * yp_int_[0] - M_ * yp_int_[1]; - f_int_[1] = y_[1] - R1_ * y_int_[1] - M_ * yp_int_[0] - L1_ * yp_int_[1]; + auto* y = y_.getData(); + + f_int_[0] = y[0] - R0_ * y_int_[0] - L0_ * yp_int_[0] - M_ * yp_int_[1]; + f_int_[1] = y[1] - R1_ * y_int_[1] - M_ * yp_int_[0] - L1_ * yp_int_[1]; return 0; } template int LinearTransformer::evaluateExternalResidual() { - f_[0] = y_int_[0]; - f_[1] = y_int_[1]; + auto* f = f_.getData(); + + f[0] = y_int_[0]; + f[1] = y_int_[1]; return 0; } diff --git a/GridKit/Model/PowerElectronics/MicrogridBusDQ/CMakeLists.txt b/GridKit/Model/PowerElectronics/MicrogridBusDQ/CMakeLists.txt index 2cb3c90e4..7d3626bd0 100644 --- a/GridKit/Model/PowerElectronics/MicrogridBusDQ/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/MicrogridBusDQ/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_microbusdq SOURCES MicrogridBusDQ.cpp - HEADERS MicrogridBusDQ.hpp) + HEADERS MicrogridBusDQ.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/MicrogridBusDQ/MicrogridBusDQ.cpp b/GridKit/Model/PowerElectronics/MicrogridBusDQ/MicrogridBusDQ.cpp index c6e78d2b3..9cb6a7f5d 100644 --- a/GridKit/Model/PowerElectronics/MicrogridBusDQ/MicrogridBusDQ.cpp +++ b/GridKit/Model/PowerElectronics/MicrogridBusDQ/MicrogridBusDQ.cpp @@ -91,9 +91,12 @@ namespace GridKit template int MicrogridBusDQ::evaluateExternalResidual() { + auto* y = y_.getData(); + auto* f = f_.getData(); + // bus voltage - f_[0] = -y_[0] / RN_; - f_[1] = -y_[1] / RN_; + f[0] = -y[0] / RN_; + f[1] = -y[1] / RN_; return 0; } diff --git a/GridKit/Model/PowerElectronics/MicrogridLine/CMakeLists.txt b/GridKit/Model/PowerElectronics/MicrogridLine/CMakeLists.txt index d5d0b6bee..e4ce2b4e8 100644 --- a/GridKit/Model/PowerElectronics/MicrogridLine/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/MicrogridLine/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_microline SOURCES MicrogridLine.cpp - HEADERS MicrogridLine.hpp) + HEADERS MicrogridLine.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/MicrogridLine/MicrogridLine.cpp b/GridKit/Model/PowerElectronics/MicrogridLine/MicrogridLine.cpp index c0896889a..8bdac9b11 100644 --- a/GridKit/Model/PowerElectronics/MicrogridLine/MicrogridLine.cpp +++ b/GridKit/Model/PowerElectronics/MicrogridLine/MicrogridLine.cpp @@ -80,7 +80,7 @@ namespace GridKit template int MicrogridLine::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -91,8 +91,10 @@ namespace GridKit template int MicrogridLine::evaluateInternalResidual() { - f_int_[0] = -yp_int_[0] - (R_ / L_) * y_int_[0] + y_[0] * y_int_[1] + (y_[1] - y_[3]) / L_; - f_int_[1] = -yp_int_[1] - (R_ / L_) * y_int_[1] - y_[0] * y_int_[0] + (y_[2] - y_[4]) / L_; + auto* y = y_.getData(); + + f_int_[0] = -yp_int_[0] - (R_ / L_) * y_int_[0] + y[0] * y_int_[1] + (y[1] - y[3]) / L_; + f_int_[1] = -yp_int_[1] - (R_ / L_) * y_int_[1] - y[0] * y_int_[0] + (y[2] - y[4]) / L_; return 0; } @@ -100,16 +102,18 @@ namespace GridKit template int MicrogridLine::evaluateExternalResidual() { + auto* f = f_.getData(); + // ref motor - f_[0] = 0.0; + f[0] = 0.0; // Port 1 - f_[1] = -y_int_[0]; - f_[2] = -y_int_[1]; + f[1] = -y_int_[0]; + f[2] = -y_int_[1]; // Port 2 - f_[3] = y_int_[0]; - f_[4] = y_int_[1]; + f[3] = y_int_[0]; + f[4] = y_int_[1]; return 0; } @@ -136,12 +140,13 @@ namespace GridKit std::vector rcord(ccord.size(), 5); std::vector vals{}; - vals = {static_cast(y_int_[1]), (1.0 / L_), -(1.0 / L_), -(R_ / L_) - alpha_, static_cast(y_[0])}; + auto* y = y_.getData(); + vals = {static_cast(y_int_[1]), (1.0 / L_), -(1.0 / L_), -(R_ / L_) - alpha_, static_cast(y[0])}; this->setJacValues(rcord, ccord, vals); std::vector ccor2{0, 2, 4, 5, 6}; std::fill(rcord.begin(), rcord.end(), 6); - vals = {-static_cast(y_int_[0]), (1.0 / L_), -(1.0 / L_), -static_cast(y_[0]), -(R_ / L_) - alpha_}; + vals = {-static_cast(y_int_[0]), (1.0 / L_), -(1.0 / L_), -static_cast(y[0]), -(R_ / L_) - alpha_}; this->setJacValues(rcord, ccor2, vals); return 0; diff --git a/GridKit/Model/PowerElectronics/MicrogridLoad/CMakeLists.txt b/GridKit/Model/PowerElectronics/MicrogridLoad/CMakeLists.txt index bf45b8ede..83946d13c 100644 --- a/GridKit/Model/PowerElectronics/MicrogridLoad/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/MicrogridLoad/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_microload SOURCES MicrogridLoad.cpp - HEADERS MicrogridLoad.hpp) + HEADERS MicrogridLoad.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/MicrogridLoad/MicrogridLoad.cpp b/GridKit/Model/PowerElectronics/MicrogridLoad/MicrogridLoad.cpp index d3e9a143d..d55994f94 100644 --- a/GridKit/Model/PowerElectronics/MicrogridLoad/MicrogridLoad.cpp +++ b/GridKit/Model/PowerElectronics/MicrogridLoad/MicrogridLoad.cpp @@ -76,7 +76,7 @@ namespace GridKit template int MicrogridLoad::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -86,8 +86,10 @@ namespace GridKit template int MicrogridLoad::evaluateInternalResidual() { - f_int_[0] = -yp_int_[0] - (R_ / L_) * y_int_[0] + y_[0] * y_int_[1] + y_[1] / L_; - f_int_[1] = -yp_int_[1] - (R_ / L_) * y_int_[1] - y_[0] * y_int_[0] + y_[2] / L_; + auto* y = y_.getData(); + + f_int_[0] = -yp_int_[0] - (R_ / L_) * y_int_[0] + y[0] * y_int_[1] + y[1] / L_; + f_int_[1] = -yp_int_[1] - (R_ / L_) * y_int_[1] - y[0] * y_int_[0] + y[2] / L_; return 0; } @@ -95,14 +97,16 @@ namespace GridKit template int MicrogridLoad::evaluateExternalResidual() { + auto* f = f_.getData(); + // ref motor - f_[0] = 0.0; + f[0] = 0.0; // only input for loads // input - f_[1] = -y_int_[0]; - f_[2] = -y_int_[1]; + f[1] = -y_int_[0]; + f[2] = -y_int_[1]; return 0; } @@ -129,12 +133,13 @@ namespace GridKit std::vector rcord(ccord.size(), 3); std::vector vals{}; - vals = {static_cast(y_int_[1]), (1.0 / L_), -(R_ / L_) - alpha_, static_cast(y_[0])}; + auto* y = y_.getData(); + vals = {static_cast(y_int_[1]), (1.0 / L_), -(R_ / L_) - alpha_, static_cast(y[0])}; this->setJacValues(rcord, ccord, vals); std::vector ccor2{0, 2, 3, 4}; std::fill(rcord.begin(), rcord.end(), 4); - vals = {-static_cast(y_int_[0]), (1.0 / L_), -static_cast(y_[0]), -(R_ / L_) - alpha_}; + vals = {-static_cast(y_int_[0]), (1.0 / L_), -static_cast(y[0]), -(R_ / L_) - alpha_}; this->setJacValues(rcord, ccor2, vals); return 0; diff --git a/GridKit/Model/PowerElectronics/NodeBase.hpp b/GridKit/Model/PowerElectronics/NodeBase.hpp index 3147f6817..5ce20a73a 100644 --- a/GridKit/Model/PowerElectronics/NodeBase.hpp +++ b/GridKit/Model/PowerElectronics/NodeBase.hpp @@ -11,8 +11,18 @@ namespace GridKit template class NodeBase : public Model::Evaluator { + protected: + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::allocated_; + using Model::Evaluator::allocateVectors; + public: - using RealT = typename Model::Evaluator::RealT; + using RealT = typename Model::Evaluator::RealT; + using VectorT = typename Model::Evaluator::VectorT; NodeBase(size_t n_intern, size_t n_extern) : n_intern_(n_intern), n_extern_(n_extern) @@ -48,42 +58,42 @@ namespace GridKit { } - std::vector& y() final + VectorT& y() final { return y_; } - const std::vector& y() const final + const VectorT& y() const final { return y_; } - std::vector& yp() final + VectorT& yp() final { return yp_; } - const std::vector& yp() const final + const VectorT& yp() const final { return yp_; } - std::vector& tag() final + VectorT& tag() final { return tag_; } - const std::vector& tag() const final + const VectorT& tag() const final { return tag_; } - std::vector& absoluteTolerance() final + VectorT& absoluteTolerance() final { return abs_tol_; } - const std::vector& absoluteTolerance() const final + const VectorT& absoluteTolerance() const final { return abs_tol_; } @@ -127,15 +137,13 @@ namespace GridKit int allocate() override { - // Temporary while we use std::vector in the code size_t size = static_cast(n_intern_ + n_extern_); - // Resize component model data - f_.resize(size); - y_.resize(size); - yp_.resize(size); - tag_.resize(size); - abs_tol_.resize(size); + if (!allocated_) + { + allocateVectors(static_cast(size)); + } + variable_indices_.resize(size); residual_indices_.resize(size); @@ -163,7 +171,7 @@ namespace GridKit */ int setAbsoluteTolerance(RealT rel_tol) final { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -193,12 +201,6 @@ namespace GridKit std::vector variable_indices_; ///< Global (system-level) variable indices std::vector residual_indices_; ///< Global (system-level) residual indices - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; - IdxT* J_rows_buffer_{nullptr}; IdxT* J_cols_buffer_{nullptr}; RealT* J_vals_buffer_{nullptr}; @@ -207,15 +209,15 @@ namespace GridKit // Adjoint sensitivity members // - std::vector g_{}; - std::vector yB_{}; - std::vector ypB_{}; - std::vector fB_{}; - std::vector gB_{}; + VectorT g_{}; + VectorT yB_{}; + VectorT ypB_{}; + VectorT fB_{}; + VectorT gB_{}; - std::vector param_{}; - std::vector param_up_{}; - std::vector param_lo_{}; + VectorT param_{}; + VectorT param_up_{}; + VectorT param_lo_{}; std::unique_ptr connection_nodes_; @@ -232,61 +234,61 @@ namespace GridKit return 0; } - std::vector& yB() final + VectorT& yB() final { throw "ERROR: Method not implemented!\n"; return yB_; } - const std::vector& yB() const final + const VectorT& yB() const final { throw "ERROR: Method not implemented!\n"; return yB_; } - std::vector& ypB() final + VectorT& ypB() final { throw "ERROR: Method not implemented!\n"; return ypB_; } - const std::vector& ypB() const final + const VectorT& ypB() const final { throw "ERROR: Method not implemented!\n"; return ypB_; } - std::vector& param() final + VectorT& param() final { throw "ERROR: Method not implemented!\n"; return param_; } - const std::vector& param() const final + const VectorT& param() const final { throw "ERROR: Method not implemented!\n"; return param_; } - std::vector& param_up() final + VectorT& param_up() final { throw "ERROR: Method not implemented!\n"; return param_up_; } - const std::vector& param_up() const final + const VectorT& param_up() const final { throw "ERROR: Method not implemented!\n"; return param_up_; } - std::vector& param_lo() final + VectorT& param_lo() final { throw "ERROR: Method not implemented!\n"; return param_lo_; } - const std::vector& param_lo() const final + const VectorT& param_lo() const final { throw "ERROR: Method not implemented!\n"; return param_lo_; @@ -316,47 +318,47 @@ namespace GridKit return 1; } - std::vector& getResidual() final + VectorT& getResidual() final { return f_; } - const std::vector& getResidual() const final + const VectorT& getResidual() const final { return f_; } - std::vector& getIntegrand() final + VectorT& getIntegrand() final { throw "ERROR: Method not implemented!\n"; return g_; } - const std::vector& getIntegrand() const final + const VectorT& getIntegrand() const final { throw "ERROR: Method not implemented!\n"; return g_; } - std::vector& getAdjointResidual() final + VectorT& getAdjointResidual() final { throw "ERROR: Method not implemented!\n"; return fB_; } - const std::vector& getAdjointResidual() const final + const VectorT& getAdjointResidual() const final { throw "ERROR: Method not implemented!\n"; return fB_; } - std::vector& getAdjointIntegrand() final + VectorT& getAdjointIntegrand() final { throw "ERROR: Method not implemented!\n"; return gB_; } - const std::vector& getAdjointIntegrand() const final + const VectorT& getAdjointIntegrand() const final { throw "ERROR: Method not implemented!\n"; return gB_; diff --git a/GridKit/Model/PowerElectronics/Resistor/CMakeLists.txt b/GridKit/Model/PowerElectronics/Resistor/CMakeLists.txt index aa3c25a80..3bed9d678 100644 --- a/GridKit/Model/PowerElectronics/Resistor/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/Resistor/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_resistor SOURCES Resistor.cpp - HEADERS Resistor.hpp) + HEADERS Resistor.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/Resistor/Resistor.cpp b/GridKit/Model/PowerElectronics/Resistor/Resistor.cpp index 87d86cab4..740548cb5 100644 --- a/GridKit/Model/PowerElectronics/Resistor/Resistor.cpp +++ b/GridKit/Model/PowerElectronics/Resistor/Resistor.cpp @@ -67,7 +67,7 @@ namespace GridKit template int Resistor::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -84,10 +84,13 @@ namespace GridKit template int Resistor::evaluateExternalResidual() { + auto* y = y_.getData(); + auto* f = f_.getData(); + // input - f_[0] = (y_[0] - y_[1]) / R_; + f[0] = (y[0] - y[1]) / R_; // ouput - f_[1] = (y_[1] - y_[0]) / R_; + f[1] = (y[1] - y[0]) / R_; return 0; } diff --git a/GridKit/Model/PowerElectronics/SynchronousMachine/CMakeLists.txt b/GridKit/Model/PowerElectronics/SynchronousMachine/CMakeLists.txt index 9a7b81528..4e685097a 100644 --- a/GridKit/Model/PowerElectronics/SynchronousMachine/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/SynchronousMachine/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_synmachine SOURCES SynchronousMachine.cpp - HEADERS SynchronousMachine.hpp) + HEADERS SynchronousMachine.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/SynchronousMachine/SynchronousMachine.cpp b/GridKit/Model/PowerElectronics/SynchronousMachine/SynchronousMachine.cpp index 6231421e5..f69790427 100644 --- a/GridKit/Model/PowerElectronics/SynchronousMachine/SynchronousMachine.cpp +++ b/GridKit/Model/PowerElectronics/SynchronousMachine/SynchronousMachine.cpp @@ -101,9 +101,11 @@ namespace GridKit ScalarT cos23p = std::cos((P_ / 2.0) * y_int_[0] + (2.0 / 3.0) * M_PI); ScalarT sin23p = std::sin((P_ / 2.0) * y_int_[0] + (2.0 / 3.0) * M_PI); - f_int_[0] = (-2.0 / 3.0) * (y_[0] * cos1 + y_[1] * cos23m + y_[2] * cos23p) + Rs_ * y_int_[1] + (Lls_ + Lmq_) * yp_int_[1] + Lmq_ * yp_int_[4] + Lmq_ * yp_int_[5] + y_[4] * (P_ / 2.0) * ((Lls_ + Lmd_) * y_int_[2] + Lmd_ * y_int_[6] + Lmd_ * y_int_[7]); - f_int_[1] = (-2.0 / 3.0) * (y_[0] * sin1 - y_[1] * sin23m - y_[2] * sin23p) + Rs_ * y_int_[2] + (Lls_ + Lmd_) * yp_int_[2] + Lmd_ * yp_int_[6] + Lmd_ * yp_int_[7] - y_[4] * (P_ / 2.0) * ((Lls_ + Lmq_) * y_int_[1] + Lmq_ * y_int_[4] + Lmq_ * y_int_[5]); - f_int_[2] = (-1.0 / 3.0) * (y_[0] + y_[1] + y_[2]) + Rs_ * y_int_[3] + Lls_ * yp_int_[3]; + auto* y = y_.getData(); + + f_int_[0] = (-2.0 / 3.0) * (y[0] * cos1 + y[1] * cos23m + y[2] * cos23p) + Rs_ * y_int_[1] + (Lls_ + Lmq_) * yp_int_[1] + Lmq_ * yp_int_[4] + Lmq_ * yp_int_[5] + y[4] * (P_ / 2.0) * ((Lls_ + Lmd_) * y_int_[2] + Lmd_ * y_int_[6] + Lmd_ * y_int_[7]); + f_int_[1] = (-2.0 / 3.0) * (y[0] * sin1 - y[1] * sin23m - y[2] * sin23p) + Rs_ * y_int_[2] + (Lls_ + Lmd_) * yp_int_[2] + Lmd_ * yp_int_[6] + Lmd_ * yp_int_[7] - y[4] * (P_ / 2.0) * ((Lls_ + Lmq_) * y_int_[1] + Lmq_ * y_int_[4] + Lmq_ * y_int_[5]); + f_int_[2] = (-1.0 / 3.0) * (y[0] + y[1] + y[2]) + Rs_ * y_int_[3] + Lls_ * yp_int_[3]; f_int_[3] = rkq1 * y_int_[4] + (llkq1 + Lmq_) * yp_int_[4] + Lmq_ * yp_int_[1] + Lmq_ * yp_int_[5]; f_int_[4] = rkq1 * y_int_[4] + (llkq1 + Lmq_) * yp_int_[4] + Lmq_ * yp_int_[1] + Lmq_ * yp_int_[5]; return 0; @@ -122,11 +124,15 @@ namespace GridKit ScalarT cos23p = std::cos((P_ / 2.0) * y_int_[0] + (2.0 / 3.0) * M_PI); ScalarT sin23p = std::sin((P_ / 2.0) * y_int_[0] + (2.0 / 3.0) * M_PI); - f_[0] = y_int_[1] * cos1 + y_int_[2] * sin1 + y_int_[3]; - f_[1] = y_int_[1] * cos23m + y_int_[2] * sin23m + y_int_[3]; - f_[2] = y_int_[1] * cos23p + y_int_[2] * sin23p + y_int_[3]; - f_[3] = RJ_ * yp_[4] - (3.0 / 4.0) * P_ * (Lmd_ * y_int_[1] * (y_int_[2] + y_int_[6] + y_int_[7]) - Lmq_ * y_int_[2] * (y_int_[1] + y_int_[4] + y_[0])); - f_[4] = yp_int_[0] - y_[4]; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + + f[0] = y_int_[1] * cos1 + y_int_[2] * sin1 + y_int_[3]; + f[1] = y_int_[1] * cos23m + y_int_[2] * sin23m + y_int_[3]; + f[2] = y_int_[1] * cos23p + y_int_[2] * sin23p + y_int_[3]; + f[3] = RJ_ * yp[4] - (3.0 / 4.0) * P_ * (Lmd_ * y_int_[1] * (y_int_[2] + y_int_[6] + y_int_[7]) - Lmq_ * y_int_[2] * (y_int_[1] + y_int_[4] + y[0])); + f[4] = yp_int_[0] - y[4]; return 0; } diff --git a/GridKit/Model/PowerElectronics/SystemModelPowerElectronics.hpp b/GridKit/Model/PowerElectronics/SystemModelPowerElectronics.hpp index 62cbfd96f..b5ee174d7 100644 --- a/GridKit/Model/PowerElectronics/SystemModelPowerElectronics.hpp +++ b/GridKit/Model/PowerElectronics/SystemModelPowerElectronics.hpp @@ -4,6 +4,7 @@ #include #include +#include #include #include #include @@ -16,6 +17,49 @@ namespace GridKit { + /** + * Writes a vector to a file in Matrix Market format + * + * @param vec The vector to write + * @param filename The name of the output file + * @param header Additional header information/comments + * @return true if the write was successful, false otherwise + */ + template + void writeVectorToMatrixMarket(const VectorT& vec, const std::string& filename, const std::string& header) + { + std::ofstream outFile(filename); + + if (!outFile.is_open()) + { + std::cerr << "Error: Could not open file " << filename << " for writing." << std::endl; + return; + } + + // Uncomment to write Matrix Market header + // outFile << "%%MatrixMarket vector array real general" << std::endl; + + // Write additional header information as comments + if (!header.empty()) + { + outFile << "% " << header << std::endl; + } + + // Write the vector size + outFile << vec.getSize() << std::endl; + + // Write the vector elements + outFile << std::scientific << std::setprecision(16); + auto* vec_data = vec.getData(); + for (std::size_t i = 0; i < vec.getSize(); ++i) + { + outFile << vec_data[i] << std::endl; + } + + outFile.close(); + return; + } + template class PowerElectronicsModel : public CircuitComponent { @@ -38,6 +82,8 @@ namespace GridKit using CircuitComponent::f_int_; using CircuitComponent::tag_; using CircuitComponent::abs_tol_; + using CircuitComponent::allocated_; + using CircuitComponent::allocateVectors; public: /** @@ -136,12 +182,10 @@ namespace GridKit n_extern_ = 0; size_ = n_intern_ + n_extern_; - // Allocate global vectors - y_.resize(size_); - yp_.resize(size_); - f_.resize(size_); - tag_.resize(size_); - abs_tol_.resize(size_); + if (!allocated_) + { + allocateVectors(static_cast(size_)); + } { // Start node internal indexing after all component internals for proper KLU ordering size_t node_internal_idx = component_internal_size; @@ -161,14 +205,17 @@ namespace GridKit // The offset for each component's internal variables in the system vector. // They start at 0, and are stacked on top of each other. size_t component_internal_idx = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); for (component_type* comp : components_) { comp->allocate(); // Update component internal pointers to their correct offsets - comp->setInternalPointer(&y_[component_internal_idx]); - comp->setInternalDerivativePointer(&yp_[component_internal_idx]); - comp->setInternalResidualPointer(&f_[component_internal_idx]); + comp->setInternalPointer(&y[component_internal_idx]); + comp->setInternalDerivativePointer(&yp[component_internal_idx]); + comp->setInternalResidualPointer(&f[component_internal_idx]); const auto& external_indices = comp->getExternIndices(); for (size_t i = 0; i < comp->size(); i++) @@ -289,18 +336,21 @@ namespace GridKit */ int distributeVectors() { + auto* y_system = y_.getData(); + auto* yp_system = yp_.getData(); + for (component_type* component : components_) { - std::vector& y = component->y(); - std::vector& yp = component->yp(); + auto* y = component->y().getData(); + auto* yp = component->yp().getData(); const std::set& externals = component->getExternIndices(); for (size_t j : externals) { if (component->getNodeConnection(j) != neg1_) { - y[j] = y_[component->getNodeConnection(j)]; - yp[j] = yp_[component->getNodeConnection(j)]; + y[j] = y_system[component->getNodeConnection(j)]; + yp[j] = yp_system[component->getNodeConnection(j)]; } else { @@ -314,6 +364,7 @@ namespace GridKit int tagDifferentiable() final { + std::fill(tag_.getData(), tag_.getData() + tag_.getSize(), ScalarT{0.0}); return 0; } @@ -331,7 +382,7 @@ namespace GridKit */ int setAbsoluteTolerance(RealT rel_tol) final { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -342,9 +393,11 @@ namespace GridKit */ int evaluateInternalResidual() final { - for (IdxT i = 0; i < this->f_.size(); i++) + auto* f = f_.getData(); + + for (IdxT i = 0; i < this->f_.getSize(); i++) { - f_[i] = 0.0; + f[i] = 0.0; } this->distributeVectors(); @@ -363,15 +416,15 @@ namespace GridKit if (int err_code = component->evaluateExternalResidual()) return err_code; - const std::vector& residual = component->getResidual(); - const std::set& externals = component->getExternIndices(); + auto* residual = component->getResidual().getData(); + const std::set& externals = component->getExternIndices(); for (size_t j : externals) { //@todo should do a different grounding check if (component->getNodeConnection(j) != neg1_) { - f_[component->getNodeConnection(j)] += residual[j]; + f[component->getNodeConnection(j)] += residual[j]; } } } diff --git a/GridKit/Model/PowerElectronics/TransmissionLine/CMakeLists.txt b/GridKit/Model/PowerElectronics/TransmissionLine/CMakeLists.txt index d24e46a27..5a924a3b4 100644 --- a/GridKit/Model/PowerElectronics/TransmissionLine/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/TransmissionLine/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_tranline SOURCES TransmissionLine.cpp - HEADERS TransmissionLine.hpp) + HEADERS TransmissionLine.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/TransmissionLine/TransmissionLine.cpp b/GridKit/Model/PowerElectronics/TransmissionLine/TransmissionLine.cpp index 9f518ddb8..307a89171 100644 --- a/GridKit/Model/PowerElectronics/TransmissionLine/TransmissionLine.cpp +++ b/GridKit/Model/PowerElectronics/TransmissionLine/TransmissionLine.cpp @@ -84,11 +84,13 @@ namespace GridKit template int TransmissionLine::evaluateInternalResidual() { + auto* y = y_.getData(); + // Voltage drop accross terminals - ScalarT V1re = y_[0] - y_[4]; - ScalarT V1im = y_[1] - y_[5]; - ScalarT V2re = y_[2] - y_[6]; - ScalarT V2im = y_[3] - y_[7]; + ScalarT V1re = y[0] - y[4]; + ScalarT V1im = y[1] - y[5]; + ScalarT V2re = y[2] - y[6]; + ScalarT V2im = y[3] - y[7]; // Internal variables // row 1 @@ -105,18 +107,20 @@ namespace GridKit template int TransmissionLine::evaluateExternalResidual() { + auto* f = f_.getData(); + // input - f_[0] = y_int_[0]; - f_[1] = y_int_[1]; + f[0] = y_int_[0]; + f[1] = y_int_[1]; - f_[2] = y_int_[2]; - f_[3] = y_int_[3]; + f[2] = y_int_[2]; + f[3] = y_int_[3]; // ouput - f_[4] = -y_int_[0]; - f_[5] = -y_int_[1]; + f[4] = -y_int_[0]; + f[5] = -y_int_[1]; - f_[6] = -y_int_[2]; - f_[7] = -y_int_[3]; + f[6] = -y_int_[2]; + f[7] = -y_int_[3]; return 0; } diff --git a/GridKit/Model/PowerElectronics/VoltageSource/CMakeLists.txt b/GridKit/Model/PowerElectronics/VoltageSource/CMakeLists.txt index cb1e2ed81..07be55ffd 100644 --- a/GridKit/Model/PowerElectronics/VoltageSource/CMakeLists.txt +++ b/GridKit/Model/PowerElectronics/VoltageSource/CMakeLists.txt @@ -1,4 +1,5 @@ gridkit_add_library( power_elec_voltagesource SOURCES VoltageSource.cpp - HEADERS VoltageSource.hpp) + HEADERS VoltageSource.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerElectronics/VoltageSource/VoltageSource.cpp b/GridKit/Model/PowerElectronics/VoltageSource/VoltageSource.cpp index f2967c7bd..3896f999d 100644 --- a/GridKit/Model/PowerElectronics/VoltageSource/VoltageSource.cpp +++ b/GridKit/Model/PowerElectronics/VoltageSource/VoltageSource.cpp @@ -67,7 +67,7 @@ namespace GridKit template int VoltageSource::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -78,17 +78,21 @@ namespace GridKit int VoltageSource::evaluateInternalResidual() { // internal - f_int_[0] = y_[1] - y_[0] - V_; + auto* y = y_.getData(); + + f_int_[0] = y[1] - y[0] - V_; return 0; } template int VoltageSource::evaluateExternalResidual() { + auto* f = f_.getData(); + // input - f_[0] = -y_int_[0]; + f[0] = -y_int_[0]; // ouput - f_[1] = y_int_[0]; + f[1] = y_int_[0]; return 0; } diff --git a/GridKit/Model/PowerFlow/Branch/CMakeLists.txt b/GridKit/Model/PowerFlow/Branch/CMakeLists.txt index ed0e7baf7..b1a982071 100644 --- a/GridKit/Model/PowerFlow/Branch/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Branch/CMakeLists.txt @@ -6,4 +6,5 @@ gridkit_add_library( branch SOURCES Branch.cpp - HEADERS Branch.hpp) + HEADERS Branch.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Bus/BusPQ.cpp b/GridKit/Model/PowerFlow/Bus/BusPQ.cpp index 4cc8a450c..739384a41 100644 --- a/GridKit/Model/PowerFlow/Bus/BusPQ.cpp +++ b/GridKit/Model/PowerFlow/Bus/BusPQ.cpp @@ -69,16 +69,20 @@ namespace GridKit template int BusPQ::allocate() { + using VectorT = typename ModelEvaluatorImpl::VectorT; + auto allocate_host_vector = [](VectorT& vector, IdxT n) + { + vector.resize(n); + vector.allocate(memory::HOST); + vector.setDataUpdated(memory::HOST); + }; + // std::cout << "Allocate PQ bus ..." << std::endl; - f_.resize(static_cast(size_)); - y_.resize(static_cast(size_)); - yp_.resize(static_cast(size_)); - tag_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); + this->allocateVectors(size_); - fB_.resize(static_cast(size_)); - yB_.resize(static_cast(size_)); - ypB_.resize(static_cast(size_)); + allocate_host_vector(fB_, size_); + allocate_host_vector(yB_, size_); + allocate_host_vector(ypB_, size_); return 0; } @@ -86,8 +90,9 @@ namespace GridKit template int BusPQ::tagDifferentiable() { - tag_[0] = false; - tag_[1] = false; + auto* tag = tag_.getData(); + tag[0] = false; + tag[1] = false; return 0; } @@ -106,7 +111,7 @@ namespace GridKit template int BusPQ::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -117,10 +122,12 @@ namespace GridKit int BusPQ::initialize() { // std::cout << "Initialize BusPQ..." << std::endl; - y_[0] = V0_; - y_[1] = theta0_; - yp_[0] = 0.0; - yp_[1] = 0.0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + y[0] = V0_; + y[1] = theta0_; + yp[0] = 0.0; + yp[1] = 0.0; return 0; } @@ -136,8 +143,9 @@ namespace GridKit int BusPQ::evaluateResidual() { // std::cout << "Evaluating residual of a PQ bus ...\n"; - f_[0] = 0.0; - f_[1] = 0.0; + auto* f = f_.getData(); + f[0] = 0.0; + f[1] = 0.0; return 0; } @@ -148,10 +156,12 @@ namespace GridKit int BusPQ::initializeAdjoint() { // std::cout << "Initialize BusPQ..." << std::endl; - yB_[0] = 0.0; - yB_[1] = 0.0; - ypB_[0] = 0.0; - ypB_[1] = 0.0; + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + yB[0] = 0.0; + yB[1] = 0.0; + ypB[0] = 0.0; + ypB[1] = 0.0; return 0; } @@ -159,8 +169,9 @@ namespace GridKit template int BusPQ::evaluateAdjointResidual() { - fB_[0] = 0.0; - fB_[1] = 0.0; + auto* fB = fB_.getData(); + fB[0] = 0.0; + fB[1] = 0.0; return 0; } diff --git a/GridKit/Model/PowerFlow/Bus/BusPQ.hpp b/GridKit/Model/PowerFlow/Bus/BusPQ.hpp index c3382740d..8519b8bc4 100644 --- a/GridKit/Model/PowerFlow/Bus/BusPQ.hpp +++ b/GridKit/Model/PowerFlow/Bus/BusPQ.hpp @@ -46,82 +46,82 @@ namespace GridKit virtual ScalarT& V() { - return y_[0]; + return y_.getData()[0]; } virtual const ScalarT& V() const { - return y_[0]; + return y_.getData()[0]; } virtual ScalarT& theta() { - return y_[1]; + return y_.getData()[1]; } virtual const ScalarT& theta() const { - return y_[1]; + return y_.getData()[1]; } virtual ScalarT& P() { - return f_[0]; + return f_.getData()[0]; } virtual const ScalarT& P() const { - return f_[0]; + return f_.getData()[0]; } virtual ScalarT& Q() { - return f_[1]; + return f_.getData()[1]; } virtual const ScalarT& Q() const { - return f_[1]; + return f_.getData()[1]; } virtual ScalarT& lambdaP() { - return yB_[0]; + return yB_.getData()[0]; } virtual const ScalarT& lambdaP() const { - return yB_[0]; + return yB_.getData()[0]; } virtual ScalarT& lambdaQ() { - return yB_[1]; + return yB_.getData()[1]; } virtual const ScalarT& lambdaQ() const { - return yB_[1]; + return yB_.getData()[1]; } virtual ScalarT& PB() { - return fB_[0]; + return fB_.getData()[0]; } virtual const ScalarT& PB() const { - return fB_[0]; + return fB_.getData()[0]; } virtual ScalarT& QB() { - return fB_[1]; + return fB_.getData()[1]; } virtual const ScalarT& QB() const { - return fB_[1]; + return fB_.getData()[1]; } virtual int BusType() const diff --git a/GridKit/Model/PowerFlow/Bus/BusPV.cpp b/GridKit/Model/PowerFlow/Bus/BusPV.cpp index bde6dd49b..3b577f620 100644 --- a/GridKit/Model/PowerFlow/Bus/BusPV.cpp +++ b/GridKit/Model/PowerFlow/Bus/BusPV.cpp @@ -67,16 +67,20 @@ namespace GridKit template int BusPV::allocate() { + using VectorT = typename ModelEvaluatorImpl::VectorT; + auto allocate_host_vector = [](VectorT& vector, IdxT n) + { + vector.resize(n); + vector.allocate(memory::HOST); + vector.setDataUpdated(memory::HOST); + }; + // std::cout << "Allocate PV bus ..." << std::endl; - f_.resize(static_cast(size_)); - y_.resize(static_cast(size_)); - yp_.resize(static_cast(size_)); - tag_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); + this->allocateVectors(size_); - fB_.resize(static_cast(size_)); - yB_.resize(static_cast(size_)); - ypB_.resize(static_cast(size_)); + allocate_host_vector(fB_, size_); + allocate_host_vector(yB_, size_); + allocate_host_vector(ypB_, size_); return 0; } @@ -84,7 +88,8 @@ namespace GridKit template int BusPV::tagDifferentiable() { - tag_[0] = false; + auto* tag = tag_.getData(); + tag[0] = false; return 0; } @@ -103,7 +108,7 @@ namespace GridKit template int BusPV::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -114,8 +119,9 @@ namespace GridKit int BusPV::initialize() { // std::cout << "Initialize BusPV..." << std::endl; - theta() = theta0_; - yp_[0] = 0.0; + theta() = theta0_; + auto* yp = yp_.getData(); + yp[0] = 0.0; return 0; } @@ -144,8 +150,10 @@ namespace GridKit int BusPV::initializeAdjoint() { // std::cout << "Initialize BusPV..." << std::endl; - yB_[0] = 0.0; - ypB_[0] = 0.0; + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + yB[0] = 0.0; + ypB[0] = 0.0; return 0; } @@ -153,7 +161,8 @@ namespace GridKit template int BusPV::evaluateAdjointResidual() { - fB_[0] = 0.0; + auto* fB = fB_.getData(); + fB[0] = 0.0; return 0; } diff --git a/GridKit/Model/PowerFlow/Bus/BusPV.hpp b/GridKit/Model/PowerFlow/Bus/BusPV.hpp index 4b7816254..235414ca0 100644 --- a/GridKit/Model/PowerFlow/Bus/BusPV.hpp +++ b/GridKit/Model/PowerFlow/Bus/BusPV.hpp @@ -58,22 +58,22 @@ namespace GridKit virtual ScalarT& theta() { - return y_[0]; + return y_.getData()[0]; } virtual const ScalarT& theta() const { - return y_[0]; + return y_.getData()[0]; } virtual ScalarT& P() { - return f_[0]; + return f_.getData()[0]; } virtual const ScalarT& P() const { - return f_[0]; + return f_.getData()[0]; } virtual ScalarT& Q() diff --git a/GridKit/Model/PowerFlow/Bus/CMakeLists.txt b/GridKit/Model/PowerFlow/Bus/CMakeLists.txt index f06511289..0844657ce 100644 --- a/GridKit/Model/PowerFlow/Bus/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Bus/CMakeLists.txt @@ -12,4 +12,5 @@ gridkit_add_library( BusFactory.hpp BusPQ.hpp BusPV.hpp - BusSlack.hpp) + BusSlack.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Generator/CMakeLists.txt b/GridKit/Model/PowerFlow/Generator/CMakeLists.txt index 1136651f2..d010f9e89 100644 --- a/GridKit/Model/PowerFlow/Generator/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Generator/CMakeLists.txt @@ -10,4 +10,5 @@ gridkit_add_library( GeneratorFactory.hpp GeneratorPQ.hpp GeneratorPV.hpp - GeneratorSlack.hpp) + GeneratorSlack.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Generator2/CMakeLists.txt b/GridKit/Model/PowerFlow/Generator2/CMakeLists.txt index 0c64cc1a7..35e15178d 100644 --- a/GridKit/Model/PowerFlow/Generator2/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Generator2/CMakeLists.txt @@ -6,4 +6,5 @@ gridkit_add_library( generator2 SOURCES Generator2.cpp - HEADERS Generator2.hpp) + HEADERS Generator2.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Generator2/Generator2.cpp b/GridKit/Model/PowerFlow/Generator2/Generator2.cpp index eb8bd440e..255a39ec7 100644 --- a/GridKit/Model/PowerFlow/Generator2/Generator2.cpp +++ b/GridKit/Model/PowerFlow/Generator2/Generator2.cpp @@ -49,38 +49,44 @@ namespace GridKit template int Generator2::allocate() { - tag_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); return 0; } template int Generator2::tagDifferentiable() { - tag_[0] = true; - tag_[1] = true; + auto* tag = tag_.getData(); + + tag[0] = true; + tag[1] = true; return 0; } template int Generator2::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } template int Generator2::initialize() { + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* param = param_.getData(); + auto* param_up = param_up_.getData(); + auto* param_lo = param_lo_.getData(); + // Set optimization parameter value and bounds - param_[0] = Pm_; - param_up_[0] = 1.5; - param_lo_[0] = 0.5; + param[0] = Pm_; + param_up[0] = 1.5; + param_lo[0] = 0.5; - y_[0] = asin((Pm_ * Xdp_) / (Eqp_ * V())) + theta(); // <~ asin(Pm/Pmax) - y_[1] = omega_s_; - yp_[0] = 0.0; - yp_[1] = 0.0; + y[0] = asin((Pm_ * Xdp_) / (Eqp_ * V())) + theta(); // <~ asin(Pm/Pmax) + y[1] = omega_s_; + yp[0] = 0.0; + yp[1] = 0.0; return 0; } @@ -88,8 +94,13 @@ namespace GridKit template int Generator2::evaluateResidual() { - f_[0] = -yp_[0] + omega_b_ * (y_[1] - omega_s_); - f_[1] = -yp_[1] + omega_s_ / (2.0 * H_) * (param_[0] - Eqp_ / Xdp_ * V() * sin(y_[0] - theta()) - D_ * (y_[1] - omega_s_)); + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + auto* param = param_.getData(); + + f[0] = -yp[0] + omega_b_ * (y[1] - omega_s_); + f[1] = -yp[1] + omega_s_ / (2.0 * H_) * (param[0] - Eqp_ / Xdp_ * V() * sin(y[0] - theta()) - D_ * (y[1] - omega_s_)); return 0; } @@ -104,17 +115,24 @@ namespace GridKit template int Generator2::evaluateIntegrand() { - g_[0] = frequencyPenalty(y_[1]); + auto* y = y_.getData(); + auto* g = g_.getData(); + + g[0] = frequencyPenalty(y[1]); return 0; } template int Generator2::initializeAdjoint() { - yB_[0] = 0.0; - yB_[1] = 0.0; - ypB_[0] = 0.0; - ypB_[1] = frequencyPenaltyDer(y_[1]); + auto* y = y_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + + yB[0] = 0.0; + yB[1] = 0.0; + ypB[0] = 0.0; + ypB[1] = frequencyPenaltyDer(y[1]); return 0; } @@ -122,8 +140,13 @@ namespace GridKit template int Generator2::evaluateAdjointResidual() { - fB_[0] = -ypB_[0] + omega_s_ / (2.0 * H_) * Eqp_ / Xdp_ * V() * cos(y_[0] - theta()) * yB_[1]; - fB_[1] = -ypB_[1] + omega_s_ / (2.0 * H_) * D_ * yB_[1] - omega_b_ * yB_[0] + frequencyPenaltyDer(y_[1]); + auto* y = y_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* fB = fB_.getData(); + + fB[0] = -ypB[0] + omega_s_ / (2.0 * H_) * Eqp_ / Xdp_ * V() * cos(y[0] - theta()) * yB[1]; + fB[1] = -ypB[1] + omega_s_ / (2.0 * H_) * D_ * yB[1] - omega_b_ * yB[0] + frequencyPenaltyDer(y[1]); return 0; } @@ -139,7 +162,10 @@ namespace GridKit int Generator2::evaluateAdjointIntegrand() { // std::cout << "Evaluate adjoint Integrand for Gen2..." << std::endl; - gB_[0] = -omega_s_ / (2.0 * H_) * yB_[1]; + auto* yB = yB_.getData(); + auto* gB = gB_.getData(); + + gB[0] = -omega_s_ / (2.0 * H_) * yB[1]; return 0; } diff --git a/GridKit/Model/PowerFlow/Generator4/CMakeLists.txt b/GridKit/Model/PowerFlow/Generator4/CMakeLists.txt index ac6252e2c..3abacf840 100644 --- a/GridKit/Model/PowerFlow/Generator4/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Generator4/CMakeLists.txt @@ -8,4 +8,5 @@ gridkit_add_library( generator4 SOURCES Generator4.cpp - HEADERS Generator4.hpp) + HEADERS Generator4.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Generator4/Generator4.cpp b/GridKit/Model/PowerFlow/Generator4/Generator4.cpp index 296a56867..10f9bbe67 100644 --- a/GridKit/Model/PowerFlow/Generator4/Generator4.cpp +++ b/GridKit/Model/PowerFlow/Generator4/Generator4.cpp @@ -57,9 +57,6 @@ namespace GridKit int Generator4::allocate() { // std::cout << "Allocate Generator4..." << std::endl; - tag_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); - return 0; } @@ -102,31 +99,38 @@ namespace GridKit const ScalarT Ed = V() * sin(theta() - delta) + Rs_ * Id + Xqp_ * Iq; const ScalarT Eq = V() * cos(theta() - delta) + Rs_ * Iq - Xdp_ * Id; - y_[0] = delta; - y_[1] = omega_s_; - y_[2] = Ed; - y_[3] = Eq; - y_[4] = Id; - y_[5] = Iq; - yp_[0] = 0.0; - yp_[1] = 0.0; - yp_[2] = 0.0; - yp_[3] = 0.0; - yp_[4] = 0.0; - yp_[5] = 0.0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = delta; + y[1] = omega_s_; + y[2] = Ed; + y[3] = Eq; + y[4] = Id; + y[5] = Iq; + yp[0] = 0.0; + yp[1] = 0.0; + yp[2] = 0.0; + yp[3] = 0.0; + yp[4] = 0.0; + yp[5] = 0.0; // Set control parameter values here. Ef_ = Eq - (Xd_ - Xdp_) * Id; // <~ set to steady state value Pm_ = Ed * Id + Eq * Iq + (Xdp_ - Xqp_) * Id * Iq; // <~ set to steady state value // Initialize optimization parameters - param_[0] = Pm_; - param_up_[0] = 1.5; - param_lo_[0] = 0.0; + auto* param = param_.getData(); + auto* param_up = param_up_.getData(); + auto* param_lo = param_lo_.getData(); + + param[0] = Pm_; + param_up[0] = 1.5; + param_lo[0] = 0.0; - param_[1] = Ef_; - param_up_[1] = 1.7; - param_lo_[1] = 0.0; + param[1] = Ef_; + param_up[1] = 1.7; + param_lo[1] = 0.0; return 0; } @@ -137,14 +141,16 @@ namespace GridKit template int Generator4::tagDifferentiable() { - tag_[0] = true; - tag_[1] = true; - tag_[2] = true; - tag_[3] = true; + auto* tag = tag_.getData(); + + tag[0] = true; + tag[1] = true; + tag[2] = true; + tag[3] = true; for (IdxT i = 4; i < size_; ++i) { - tag_[static_cast(i)] = false; + tag[static_cast(i)] = false; } return 0; @@ -165,7 +171,7 @@ namespace GridKit template int Generator4::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -201,12 +207,14 @@ namespace GridKit int Generator4::evaluateResidual() { // std::cout << "Evaluate residual for Generator4..." << std::endl; - f_[0] = dotDelta() - omega_b_ * (omega() - omega_s_); - f_[1] = (2.0 * H_) / omega_s_ * dotOmega() - Pm() + Eqp() * Iq() + Edp() * Id() + (-Xdp_ + Xqp_) * Id() * Iq() + D_ * (omega() - omega_s_); - f_[2] = Tq0p_ * dotEdp() + Edp() - (Xq_ - Xqp_) * Iq(); - f_[3] = Td0p_ * dotEqp() + Eqp() + (Xd_ - Xdp_) * Id() - Ef(); - f_[4] = Rs_ * Id() - Xqp_ * Iq() + V() * sin(delta() - theta()) - Edp(); - f_[5] = Xdp_ * Id() + Rs_ * Iq() + V() * cos(delta() - theta()) - Eqp(); + auto* f = f_.getData(); + + f[0] = dotDelta() - omega_b_ * (omega() - omega_s_); + f[1] = (2.0 * H_) / omega_s_ * dotOmega() - Pm() + Eqp() * Iq() + Edp() * Id() + (-Xdp_ + Xqp_) * Id() * Iq() + D_ * (omega() - omega_s_); + f[2] = Tq0p_ * dotEdp() + Edp() - (Xq_ - Xqp_) * Iq(); + f[3] = Td0p_ * dotEqp() + Eqp() + (Xd_ - Xdp_) * Id() - Ef(); + f[4] = Rs_ * Id() - Xqp_ * Iq() + V() * sin(delta() - theta()) - Edp(); + f[5] = Xdp_ * Id() + Rs_ * Iq() + V() * cos(delta() - theta()) - Eqp(); // Compute active and reactive load provided by the infinite bus. P() += Pg(); @@ -227,7 +235,10 @@ namespace GridKit int Generator4::evaluateIntegrand() { // std::cout << "Evaluate Integrand for Generator4..." << std::endl; - g_[0] = frequencyPenalty(y_[1]); + auto* y = y_.getData(); + auto* g = g_.getData(); + + g[0] = frequencyPenalty(y[1]); return 0; } @@ -235,12 +246,16 @@ namespace GridKit int Generator4::initializeAdjoint() { // std::cout << "Initialize adjoint for Generator4..." << std::endl; + auto* y = y_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + for (IdxT i = 0; i < size_; ++i) { - yB_[static_cast(i)] = 0.0; - ypB_[static_cast(i)] = 0.0; + yB[static_cast(i)] = 0.0; + ypB[static_cast(i)] = 0.0; } - ypB_[1] = frequencyPenaltyDer(y_[1]); + ypB[1] = frequencyPenaltyDer(y[1]); return 0; } @@ -266,13 +281,17 @@ namespace GridKit ScalarT sinPhi = sin(delta() - theta()); ScalarT cosPhi = cos(delta() - theta()); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* fB = fB_.getData(); + // Generator adjoint - fB_[0] = ypB_[0] - yB_[4] * V() * cosPhi + yB_[5] * V() * sinPhi; - fB_[1] = 2.0 * H_ / omega_s_ * ypB_[1] + yB_[0] * omega_b_ - yB_[1] * D_ + frequencyPenaltyDer(omega()); - fB_[2] = Tq0p_ * ypB_[2] - yB_[1] * Id() - yB_[2] + yB_[4]; - fB_[3] = Td0p_ * ypB_[3] - yB_[1] * Iq() - yB_[3] + yB_[5]; - fB_[4] = -yB_[1] * (Edp() + (Xqp_ - Xdp_) * Iq()) - yB_[3] * (Xd_ - Xdp_) - yB_[4] * Rs_ - yB_[5] * Xdp_; - fB_[5] = -yB_[1] * (Eqp() + (Xqp_ - Xdp_) * Id()) + yB_[2] * (Xq_ - Xqp_) + yB_[4] * Xqp_ - yB_[5] * Rs_; + fB[0] = ypB[0] - yB[4] * V() * cosPhi + yB[5] * V() * sinPhi; + fB[1] = 2.0 * H_ / omega_s_ * ypB[1] + yB[0] * omega_b_ - yB[1] * D_ + frequencyPenaltyDer(omega()); + fB[2] = Tq0p_ * ypB[2] - yB[1] * Id() - yB[2] + yB[4]; + fB[3] = Td0p_ * ypB[3] - yB[1] * Iq() - yB[3] + yB[5]; + fB[4] = -yB[1] * (Edp() + (Xqp_ - Xdp_) * Iq()) - yB[3] * (Xd_ - Xdp_) - yB[4] * Rs_ - yB[5] * Xdp_; + fB[5] = -yB[1] * (Eqp() + (Xqp_ - Xdp_) * Id()) + yB[2] * (Xq_ - Xqp_) + yB[4] * Xqp_ - yB[5] * Rs_; return 0; } @@ -289,8 +308,11 @@ namespace GridKit int Generator4::evaluateAdjointIntegrand() { // std::cout << "Evaluate adjoint Integrand for Generator4..." << std::endl; - gB_[0] = yB_[1]; - gB_[1] = yB_[3]; + auto* yB = yB_.getData(); + auto* gB = gB_.getData(); + + gB[0] = yB[1]; + gB[1] = yB[3]; return 0; } @@ -308,7 +330,8 @@ namespace GridKit template ScalarT Generator4::Pg() { - return y_[5] * V() * cos(theta() - y_[0]) + y_[4] * V() * sin(theta() - y_[0]); + auto* y = y_.getData(); + return y[5] * V() * cos(theta() - y[0]) + y[4] * V() * sin(theta() - y[0]); } /** @@ -319,7 +342,8 @@ namespace GridKit template ScalarT Generator4::Qg() { - return y_[5] * V() * sin(theta() - y_[0]) - y_[4] * V() * cos(theta() - y_[0]); + auto* y = y_.getData(); + return y[5] * V() * sin(theta() - y[0]) - y[4] * V() * cos(theta() - y[0]); } /** diff --git a/GridKit/Model/PowerFlow/Generator4/Generator4.hpp b/GridKit/Model/PowerFlow/Generator4/Generator4.hpp index d4b163e96..f5d0e862d 100644 --- a/GridKit/Model/PowerFlow/Generator4/Generator4.hpp +++ b/GridKit/Model/PowerFlow/Generator4/Generator4.hpp @@ -106,12 +106,12 @@ namespace GridKit private: const ScalarT& Pm() const { - return param_[0]; + return param_.getData()[0]; } const ScalarT& Ef() const { - return param_[1]; + return param_.getData()[1]; } ScalarT Pg(); @@ -126,52 +126,52 @@ namespace GridKit const ScalarT dotDelta() const { - return yp_[0]; + return yp_.getData()[0]; } const ScalarT dotOmega() const { - return yp_[1]; + return yp_.getData()[1]; } const ScalarT dotEdp() const { - return yp_[2]; + return yp_.getData()[2]; } const ScalarT dotEqp() const { - return yp_[3]; + return yp_.getData()[3]; } const ScalarT delta() const { - return y_[0]; + return y_.getData()[0]; } const ScalarT omega() const { - return y_[1]; + return y_.getData()[1]; } const ScalarT Edp() const { - return y_[2]; + return y_.getData()[2]; } const ScalarT Eqp() const { - return y_[3]; + return y_.getData()[3]; } const ScalarT Id() const { - return y_[4]; + return y_.getData()[4]; } const ScalarT Iq() const { - return y_[5]; + return y_.getData()[5]; } private: diff --git a/GridKit/Model/PowerFlow/Generator4Governor/CMakeLists.txt b/GridKit/Model/PowerFlow/Generator4Governor/CMakeLists.txt index 41ec72b07..c70ffbe93 100644 --- a/GridKit/Model/PowerFlow/Generator4Governor/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Generator4Governor/CMakeLists.txt @@ -8,4 +8,5 @@ gridkit_add_library( generator4governor SOURCES Generator4Governor.cpp - HEADERS Generator4Governor.hpp) + HEADERS Generator4Governor.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.cpp b/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.cpp index 6caaa9674..d58022ad4 100644 --- a/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.cpp +++ b/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.cpp @@ -67,9 +67,6 @@ namespace GridKit int Generator4Governor::allocate() { // std::cout << "Allocate Gen2..." << std::endl; - tag_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); - return 0; } @@ -112,38 +109,45 @@ namespace GridKit const ScalarT Edp = V() * sin(delta - theta()) + Rs_ * Id - Xqp_ * Iq; const ScalarT Eqp = V() * cos(delta - theta()) + Rs_ * Iq + Xdp_ * Id; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + // Initialize generator - y_[static_cast(offsetGen_ + 0)] = delta; - y_[static_cast(offsetGen_ + 1)] = omega_s_ + 0.2; // <~ this is hack to perturb omega - y_[static_cast(offsetGen_ + 2)] = Edp; - y_[static_cast(offsetGen_ + 3)] = Eqp; - y_[static_cast(offsetGen_ + 4)] = Id; - y_[static_cast(offsetGen_ + 5)] = Iq; - yp_[static_cast(offsetGen_ + 0)] = 0.0; - yp_[static_cast(offsetGen_ + 1)] = 0.0; - yp_[static_cast(offsetGen_ + 2)] = 0.0; - yp_[static_cast(offsetGen_ + 3)] = 0.0; - yp_[static_cast(offsetGen_ + 4)] = 0.0; - yp_[static_cast(offsetGen_ + 5)] = 0.0; + y[static_cast(offsetGen_ + 0)] = delta; + y[static_cast(offsetGen_ + 1)] = omega_s_ + 0.2; // <~ this is hack to perturb omega + y[static_cast(offsetGen_ + 2)] = Edp; + y[static_cast(offsetGen_ + 3)] = Eqp; + y[static_cast(offsetGen_ + 4)] = Id; + y[static_cast(offsetGen_ + 5)] = Iq; + yp[static_cast(offsetGen_ + 0)] = 0.0; + yp[static_cast(offsetGen_ + 1)] = 0.0; + yp[static_cast(offsetGen_ + 2)] = 0.0; + yp[static_cast(offsetGen_ + 3)] = 0.0; + yp[static_cast(offsetGen_ + 4)] = 0.0; + yp[static_cast(offsetGen_ + 5)] = 0.0; Pm0_ = Edp * Id + Eqp * Iq + (Xqp_ - Xdp_) * Id * Iq; // <~ set to steady state value Ef0_ = Eqp + (Xd_ - Xdp_) * Id; // <~ set to steady state value // Initialize governor - y_[static_cast(offsetGov_ + 0)] = Pm0_; - y_[static_cast(offsetGov_ + 1)] = 0.0; - y_[static_cast(offsetGov_ + 2)] = 0.0; - yp_[static_cast(offsetGov_ + 0)] = 0.0; - yp_[static_cast(offsetGov_ + 1)] = 0.0; - yp_[static_cast(offsetGov_ + 2)] = 0.0; + y[static_cast(offsetGov_ + 0)] = Pm0_; + y[static_cast(offsetGov_ + 1)] = 0.0; + y[static_cast(offsetGov_ + 2)] = 0.0; + yp[static_cast(offsetGov_ + 0)] = 0.0; + yp[static_cast(offsetGov_ + 1)] = 0.0; + yp[static_cast(offsetGov_ + 2)] = 0.0; + + auto* param = param_.getData(); + auto* param_up = param_up_.getData(); + auto* param_lo = param_lo_.getData(); - param_[1] = K_; - param_up_[1] = 20.0; - param_lo_[1] = 0.0; + param[1] = K_; + param_up[1] = 20.0; + param_lo[1] = 0.0; - param_[0] = T2_; - param_up_[0] = 5.5; - param_lo_[0] = 0.1; + param[0] = T2_; + param_up[0] = 5.5; + param_lo[0] = 0.1; return 0; } @@ -154,17 +158,19 @@ namespace GridKit template int Generator4Governor::tagDifferentiable() { - // std::cout << "size of tag vector is " << tag_.size() << "\n"; - tag_[static_cast(offsetGen_ + 0)] = true; - tag_[static_cast(offsetGen_ + 1)] = true; - tag_[static_cast(offsetGen_ + 2)] = true; - tag_[static_cast(offsetGen_ + 3)] = true; - tag_[static_cast(offsetGen_ + 4)] = false; - tag_[static_cast(offsetGen_ + 5)] = false; - - tag_[static_cast(offsetGov_ + 0)] = true; - tag_[static_cast(offsetGov_ + 1)] = true; - tag_[static_cast(offsetGov_ + 2)] = false; + // std::cout << "size of tag vector is " << tag_.getSize() << "\n"; + auto* tag = tag_.getData(); + + tag[static_cast(offsetGen_ + 0)] = true; + tag[static_cast(offsetGen_ + 1)] = true; + tag[static_cast(offsetGen_ + 2)] = true; + tag[static_cast(offsetGen_ + 3)] = true; + tag[static_cast(offsetGen_ + 4)] = false; + tag[static_cast(offsetGen_ + 5)] = false; + + tag[static_cast(offsetGov_ + 0)] = true; + tag[static_cast(offsetGov_ + 1)] = true; + tag[static_cast(offsetGov_ + 2)] = false; return 0; } @@ -172,7 +178,7 @@ namespace GridKit template int Generator4Governor::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -215,22 +221,26 @@ namespace GridKit template int Generator4Governor::evaluateResidual() { + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* f = f_.getData(); + // Generator equations - f_[static_cast(offsetGen_ + 0)] = dotDelta() - omega_b_ * (omega() - omega_s_); - f_[static_cast(offsetGen_ + 1)] = (2.0 * H_) / omega_s_ * dotOmega() - Lm(y_[static_cast(offsetGov_ + 0)]) + Eqp() * Iq() + Edp() * Id() + (-Xdp_ + Xqp_) * Id() * Iq() + D_ * (omega() - omega_s_); - f_[static_cast(offsetGen_ + 2)] = Tq0p_ * dotEdp() + Edp() - (Xq_ - Xqp_) * Iq(); - f_[static_cast(offsetGen_ + 3)] = Td0p_ * dotEqp() + Eqp() + (Xd_ - Xdp_) * Id() - Ef0_; - f_[static_cast(offsetGen_ + 4)] = Rs_ * Id() - Xqp_ * Iq() + V() * sin(delta() - theta()) - Edp(); - f_[static_cast(offsetGen_ + 5)] = Xdp_ * Id() + Rs_ * Iq() + V() * cos(delta() - theta()) - Eqp(); + f[static_cast(offsetGen_ + 0)] = dotDelta() - omega_b_ * (omega() - omega_s_); + f[static_cast(offsetGen_ + 1)] = (2.0 * H_) / omega_s_ * dotOmega() - Lm(y[static_cast(offsetGov_ + 0)]) + Eqp() * Iq() + Edp() * Id() + (-Xdp_ + Xqp_) * Id() * Iq() + D_ * (omega() - omega_s_); + f[static_cast(offsetGen_ + 2)] = Tq0p_ * dotEdp() + Edp() - (Xq_ - Xqp_) * Iq(); + f[static_cast(offsetGen_ + 3)] = Td0p_ * dotEqp() + Eqp() + (Xd_ - Xdp_) * Id() - Ef0_; + f[static_cast(offsetGen_ + 4)] = Rs_ * Id() - Xqp_ * Iq() + V() * sin(delta() - theta()) - Edp(); + f[static_cast(offsetGen_ + 5)] = Xdp_ * Id() + Rs_ * Iq() + V() * cos(delta() - theta()) - Eqp(); // Bus equations P() += Pg(); Q() += Qg(); // Governor equations - f_[static_cast(offsetGov_ + 0)] = yp_[static_cast(offsetGov_ + 0)] - Ln(y_[static_cast(offsetGov_ + 2)]); - f_[static_cast(offsetGov_ + 1)] = T1() * yp_[static_cast(offsetGov_ + 1)] + y_[static_cast(offsetGov_ + 1)] - (1.0 - T2() / T1()) * (omega() - omega_s_); - f_[static_cast(offsetGov_ + 2)] = T3() * y_[static_cast(offsetGov_ + 2)] - Pm0_ + Lm(y_[static_cast(offsetGov_ + 0)]) + K() * y_[static_cast(offsetGov_ + 1)] + K() * T2() / T1() * (omega() - omega_s_); + f[static_cast(offsetGov_ + 0)] = yp[static_cast(offsetGov_ + 0)] - Ln(y[static_cast(offsetGov_ + 2)]); + f[static_cast(offsetGov_ + 1)] = T1() * yp[static_cast(offsetGov_ + 1)] + y[static_cast(offsetGov_ + 1)] - (1.0 - T2() / T1()) * (omega() - omega_s_); + f[static_cast(offsetGov_ + 2)] = T3() * y[static_cast(offsetGov_ + 2)] - Pm0_ + Lm(y[static_cast(offsetGov_ + 0)]) + K() * y[static_cast(offsetGov_ + 1)] + K() * T2() / T1() * (omega() - omega_s_); return 0; } @@ -252,7 +262,9 @@ namespace GridKit int Generator4Governor::evaluateIntegrand() { // std::cout << "Evaluate Integrand for Gen2..." << std::endl; - g_[0] = frequencyPenalty(omega()); + auto* g = g_.getData(); + + g[0] = frequencyPenalty(omega()); return 0; } @@ -260,12 +272,15 @@ namespace GridKit int Generator4Governor::initializeAdjoint() { // std::cout << "Initialize adjoint for Generator4Governor..." << std::endl; + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + for (IdxT i = 0; i < size_; ++i) { - yB_[static_cast(i)] = 0.0; - ypB_[static_cast(i)] = 0.0; + yB[static_cast(i)] = 0.0; + ypB[static_cast(i)] = 0.0; } - ypB_[static_cast(offsetGen_ + 1)] = frequencyPenaltyDer(omega()); + ypB[static_cast(offsetGen_ + 1)] = frequencyPenaltyDer(omega()); return 0; } @@ -304,27 +319,32 @@ namespace GridKit ScalarT sinPhi = sin(delta() - theta()); ScalarT cosPhi = cos(delta() - theta()); + auto* y = y_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* fB = fB_.getData(); + // Generator adjoint - fB_[static_cast(offsetGen_ + 0)] = ypB_[static_cast(offsetGen_ + 0)] - yB_[static_cast(offsetGen_ + 4)] * V() * cosPhi + yB_[static_cast(offsetGen_ + 5)] * V() * sinPhi; - fB_[static_cast(offsetGen_ + 1)] = 2.0 * H_ / omega_s_ * ypB_[static_cast(offsetGen_ + 1)] + yB_[static_cast(offsetGen_ + 0)] * omega_b_ - yB_[static_cast(offsetGen_ + 1)] * D_ + frequencyPenaltyDer(omega()) - + yB_[static_cast(offsetGov_ + 1)] * (1.0 - T2() / T1()) - yB_[static_cast(offsetGov_ + 2)] * K() * T2() / T1(); - fB_[static_cast(offsetGen_ + 2)] = Tq0p_ * ypB_[static_cast(offsetGen_ + 2)] - yB_[static_cast(offsetGen_ + 1)] * Id() - yB_[static_cast(offsetGen_ + 2)] + yB_[static_cast(offsetGen_ + 4)] - + lambdaP() * Id() - lambdaQ() * Iq(); - fB_[static_cast(offsetGen_ + 3)] = Td0p_ * ypB_[static_cast(offsetGen_ + 3)] - yB_[static_cast(offsetGen_ + 1)] * Iq() - yB_[static_cast(offsetGen_ + 3)] + yB_[static_cast(offsetGen_ + 5)] - + lambdaP() * Iq() + lambdaQ() * Id(); - fB_[static_cast(offsetGen_ + 4)] = -yB_[static_cast(offsetGen_ + 1)] * (Edp() + (Xqp_ - Xdp_) * Iq()) - yB_[static_cast(offsetGen_ + 3)] * (Xd_ - Xdp_) - yB_[static_cast(offsetGen_ + 4)] * Rs_ - yB_[static_cast(offsetGen_ + 5)] * Xdp_ - + lambdaP() * (Edp() + (Xqp_ - Xdp_) * Iq() - 2.0 * Rs_ * Id()) + lambdaQ() * (Eqp() - 2.0 * Xdp_ * Id()); - fB_[static_cast(offsetGen_ + 5)] = -yB_[static_cast(offsetGen_ + 1)] * (Eqp() + (Xqp_ - Xdp_) * Id()) + yB_[static_cast(offsetGen_ + 2)] * (Xq_ - Xqp_) + yB_[static_cast(offsetGen_ + 4)] * Xqp_ - yB_[static_cast(offsetGen_ + 5)] * Rs_ - + lambdaP() * (Eqp() + (Xqp_ - Xdp_) * Id() - 2.0 * Rs_ * Iq()) - lambdaQ() * (Edp() + 2.0 * Xqp_ * Iq()); + fB[static_cast(offsetGen_ + 0)] = ypB[static_cast(offsetGen_ + 0)] - yB[static_cast(offsetGen_ + 4)] * V() * cosPhi + yB[static_cast(offsetGen_ + 5)] * V() * sinPhi; + fB[static_cast(offsetGen_ + 1)] = 2.0 * H_ / omega_s_ * ypB[static_cast(offsetGen_ + 1)] + yB[static_cast(offsetGen_ + 0)] * omega_b_ - yB[static_cast(offsetGen_ + 1)] * D_ + frequencyPenaltyDer(omega()) + + yB[static_cast(offsetGov_ + 1)] * (1.0 - T2() / T1()) - yB[static_cast(offsetGov_ + 2)] * K() * T2() / T1(); + fB[static_cast(offsetGen_ + 2)] = Tq0p_ * ypB[static_cast(offsetGen_ + 2)] - yB[static_cast(offsetGen_ + 1)] * Id() - yB[static_cast(offsetGen_ + 2)] + yB[static_cast(offsetGen_ + 4)] + + lambdaP() * Id() - lambdaQ() * Iq(); + fB[static_cast(offsetGen_ + 3)] = Td0p_ * ypB[static_cast(offsetGen_ + 3)] - yB[static_cast(offsetGen_ + 1)] * Iq() - yB[static_cast(offsetGen_ + 3)] + yB[static_cast(offsetGen_ + 5)] + + lambdaP() * Iq() + lambdaQ() * Id(); + fB[static_cast(offsetGen_ + 4)] = -yB[static_cast(offsetGen_ + 1)] * (Edp() + (Xqp_ - Xdp_) * Iq()) - yB[static_cast(offsetGen_ + 3)] * (Xd_ - Xdp_) - yB[static_cast(offsetGen_ + 4)] * Rs_ - yB[static_cast(offsetGen_ + 5)] * Xdp_ + + lambdaP() * (Edp() + (Xqp_ - Xdp_) * Iq() - 2.0 * Rs_ * Id()) + lambdaQ() * (Eqp() - 2.0 * Xdp_ * Id()); + fB[static_cast(offsetGen_ + 5)] = -yB[static_cast(offsetGen_ + 1)] * (Eqp() + (Xqp_ - Xdp_) * Id()) + yB[static_cast(offsetGen_ + 2)] * (Xq_ - Xqp_) + yB[static_cast(offsetGen_ + 4)] * Xqp_ - yB[static_cast(offsetGen_ + 5)] * Rs_ + + lambdaP() * (Eqp() + (Xqp_ - Xdp_) * Id() - 2.0 * Rs_ * Iq()) - lambdaQ() * (Edp() + 2.0 * Xqp_ * Iq()); // Bus adjoint - PB() += (-yB_[static_cast(offsetGen_ + 4)] * sinPhi - yB_[static_cast(offsetGen_ + 5)] * cosPhi); - QB() += (yB_[static_cast(offsetGen_ + 4)] * V() * cosPhi - yB_[static_cast(offsetGen_ + 5)] * V() * sinPhi); + PB() += (-yB[static_cast(offsetGen_ + 4)] * sinPhi - yB[static_cast(offsetGen_ + 5)] * cosPhi); + QB() += (yB[static_cast(offsetGen_ + 4)] * V() * cosPhi - yB[static_cast(offsetGen_ + 5)] * V() * sinPhi); // Governor adjoint - fB_[static_cast(offsetGov_ + 0)] = ypB_[static_cast(offsetGov_ + 0)] - yB_[static_cast(offsetGov_ + 2)] * dLm(y_[static_cast(offsetGov_ + 0)]) + yB_[static_cast(offsetGen_ + 1)] * dLm(y_[static_cast(offsetGov_ + 0)]); - fB_[static_cast(offsetGov_ + 1)] = ypB_[static_cast(offsetGov_ + 1)] * T1() - yB_[static_cast(offsetGov_ + 1)] - yB_[static_cast(offsetGov_ + 2)] * K(); - fB_[static_cast(offsetGov_ + 2)] = yB_[static_cast(offsetGov_ + 0)] * dLn(y_[static_cast(offsetGov_ + 2)]) - yB_[static_cast(offsetGov_ + 2)] * T3(); + fB[static_cast(offsetGov_ + 0)] = ypB[static_cast(offsetGov_ + 0)] - yB[static_cast(offsetGov_ + 2)] * dLm(y[static_cast(offsetGov_ + 0)]) + yB[static_cast(offsetGen_ + 1)] * dLm(y[static_cast(offsetGov_ + 0)]); + fB[static_cast(offsetGov_ + 1)] = ypB[static_cast(offsetGov_ + 1)] * T1() - yB[static_cast(offsetGov_ + 1)] - yB[static_cast(offsetGov_ + 2)] * K(); + fB[static_cast(offsetGov_ + 2)] = yB[static_cast(offsetGov_ + 0)] * dLn(y[static_cast(offsetGov_ + 2)]) - yB[static_cast(offsetGov_ + 2)] * T3(); return 0; } @@ -341,12 +361,15 @@ namespace GridKit int Generator4Governor::evaluateAdjointIntegrand() { // std::cout << "Evaluate adjoint Integrand for Gen2..." << std::endl; + auto* y = y_.getData(); + auto* yB = yB_.getData(); + auto* gB = gB_.getData(); // K adjoint - gB_[1] = -yB_[static_cast(offsetGov_ + 2)] * (y_[static_cast(offsetGov_ + 1)] + T2() / T1() * (omega() - omega_s_)); + gB[1] = -yB[static_cast(offsetGov_ + 2)] * (y[static_cast(offsetGov_ + 1)] + T2() / T1() * (omega() - omega_s_)); // T2 adjoint - gB_[0] = -yB_[static_cast(offsetGov_ + 1)] * (omega() - omega_s_) / T1() - yB_[static_cast(offsetGov_ + 2)] * K() / T1() * (omega() - omega_s_); + gB[0] = -yB[static_cast(offsetGov_ + 1)] * (omega() - omega_s_) / T1() - yB[static_cast(offsetGov_ + 2)] * K() / T1() * (omega() - omega_s_); return 0; } diff --git a/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.hpp b/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.hpp index 52f400157..3fd7e37b7 100644 --- a/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.hpp +++ b/GridKit/Model/PowerFlow/Generator4Governor/Generator4Governor.hpp @@ -152,57 +152,57 @@ namespace GridKit const ScalarT dotDelta() const { - return yp_[static_cast(offsetGen_ + 0)]; + return yp_.getData()[static_cast(offsetGen_ + 0)]; } const ScalarT dotOmega() const { - return yp_[static_cast(offsetGen_ + 1)]; + return yp_.getData()[static_cast(offsetGen_ + 1)]; } const ScalarT dotEdp() const { - return yp_[static_cast(offsetGen_ + 2)]; + return yp_.getData()[static_cast(offsetGen_ + 2)]; } const ScalarT dotEqp() const { - return yp_[static_cast(offsetGen_ + 3)]; + return yp_.getData()[static_cast(offsetGen_ + 3)]; } const ScalarT delta() const { - return y_[static_cast(offsetGen_ + 0)]; + return y_.getData()[static_cast(offsetGen_ + 0)]; } const ScalarT omega() const { - return y_[static_cast(offsetGen_ + 1)]; + return y_.getData()[static_cast(offsetGen_ + 1)]; } const ScalarT Edp() const { - return y_[static_cast(offsetGen_ + 2)]; + return y_.getData()[static_cast(offsetGen_ + 2)]; } const ScalarT Eqp() const { - return y_[static_cast(offsetGen_ + 3)]; + return y_.getData()[static_cast(offsetGen_ + 3)]; } const ScalarT Id() const { - return y_[static_cast(offsetGen_ + 4)]; + return y_.getData()[static_cast(offsetGen_ + 4)]; } const ScalarT Iq() const { - return y_[static_cast(offsetGen_ + 5)]; + return y_.getData()[static_cast(offsetGen_ + 5)]; } const ScalarT K() const { - return param_[1]; + return param_.getData()[1]; } const ScalarT T1() const @@ -212,7 +212,7 @@ namespace GridKit const ScalarT T2() const { - return param_[0]; + return param_.getData()[0]; } const ScalarT T3() const diff --git a/GridKit/Model/PowerFlow/Generator4Param/CMakeLists.txt b/GridKit/Model/PowerFlow/Generator4Param/CMakeLists.txt index 48f7f5b39..33fd2c59a 100644 --- a/GridKit/Model/PowerFlow/Generator4Param/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Generator4Param/CMakeLists.txt @@ -8,4 +8,5 @@ gridkit_add_library( generator4param SOURCES Generator4Param.cpp - HEADERS Generator4Param.hpp) + HEADERS Generator4Param.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.cpp b/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.cpp index e08e33f73..13a0ac6e3 100644 --- a/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.cpp +++ b/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.cpp @@ -54,9 +54,6 @@ namespace GridKit int Generator4Param::allocate() { // std::cout << "Allocate Generator4Param..." << std::endl; - tag_.resize(static_cast(size_)); - abs_tol_.resize(static_cast(size_)); - return 0; } @@ -99,35 +96,34 @@ namespace GridKit const ScalarT Ed = V() * sin(theta() - delta) + Rs_ * Id + Xqp_ * Iq; const ScalarT Eq = V() * cos(theta() - delta) + Rs_ * Iq - Xdp_ * Id; - y_[0] = delta; - y_[1] = omega_s_; - y_[2] = Ed; - y_[3] = Eq; - y_[4] = Id; - y_[5] = Iq; - yp_[0] = 0.0; - yp_[1] = 0.0; - yp_[2] = 0.0; - yp_[3] = 0.0; - yp_[4] = 0.0; - yp_[5] = 0.0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + + y[0] = delta; + y[1] = omega_s_; + y[2] = Ed; + y[3] = Eq; + y[4] = Id; + y[5] = Iq; + yp[0] = 0.0; + yp[1] = 0.0; + yp[2] = 0.0; + yp[3] = 0.0; + yp[4] = 0.0; + yp[5] = 0.0; // Set control parameter values here. Ef_ = Eq - (Xd_ - Xdp_) * Id; // <~ set to steady state value Pm_ = Ed * Id + Eq * Iq + (Xdp_ - Xqp_) * Id * Iq; // <~ set to steady state value // Initialize optimization parameters - param_[0] = H_; - param_up_[0] = 10.0; - param_lo_[0] = 2.0; - - // param_[0] = Pm_; - // param_up_[0] = 1.5; - // param_lo_[0] = 0.0; + auto* param = param_.getData(); + auto* param_up = param_up_.getData(); + auto* param_lo = param_lo_.getData(); - // param_[1] = Ef_; - // param_up_[1] = 1.7; - // param_lo_[1] = 0.0; + param[0] = H_; + param_up[0] = 10.0; + param_lo[0] = 2.0; return 0; } @@ -138,14 +134,16 @@ namespace GridKit template int Generator4Param::tagDifferentiable() { - tag_[0] = true; - tag_[1] = true; - tag_[2] = true; - tag_[3] = true; + auto* tag = tag_.getData(); + + tag[0] = true; + tag[1] = true; + tag[2] = true; + tag[3] = true; for (IdxT i = 4; i < size_; ++i) { - tag_[static_cast(i)] = false; + tag[static_cast(i)] = false; } return 0; @@ -154,7 +152,7 @@ namespace GridKit template int Generator4Param::setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -190,12 +188,14 @@ namespace GridKit int Generator4Param::evaluateResidual() { // std::cout << "Evaluate residual for Generator4Param..." << std::endl; - f_[0] = dotDelta() - omega_b_ * (omega() - omega_s_); - f_[1] = (2.0 * H()) / omega_s_ * dotOmega() - Pm() + Eqp() * Iq() + Edp() * Id() + (-Xdp_ + Xqp_) * Id() * Iq() + D_ * (omega() - omega_s_); - f_[2] = Tq0p_ * dotEdp() + Edp() - (Xq_ - Xqp_) * Iq(); - f_[3] = Td0p_ * dotEqp() + Eqp() + (Xd_ - Xdp_) * Id() - Ef(); - f_[4] = Rs_ * Id() - Xqp_ * Iq() + V() * sin(delta() - theta()) - Edp(); - f_[5] = Xdp_ * Id() + Rs_ * Iq() + V() * cos(delta() - theta()) - Eqp(); + auto* f = f_.getData(); + + f[0] = dotDelta() - omega_b_ * (omega() - omega_s_); + f[1] = (2.0 * H()) / omega_s_ * dotOmega() - Pm() + Eqp() * Iq() + Edp() * Id() + (-Xdp_ + Xqp_) * Id() * Iq() + D_ * (omega() - omega_s_); + f[2] = Tq0p_ * dotEdp() + Edp() - (Xq_ - Xqp_) * Iq(); + f[3] = Td0p_ * dotEqp() + Eqp() + (Xd_ - Xdp_) * Id() - Ef(); + f[4] = Rs_ * Id() - Xqp_ * Iq() + V() * sin(delta() - theta()) - Edp(); + f[5] = Xdp_ * Id() + Rs_ * Iq() + V() * cos(delta() - theta()) - Eqp(); // Compute active and reactive load provided by the infinite bus. P() += Pg(); @@ -218,7 +218,9 @@ namespace GridKit int Generator4Param::evaluateIntegrand() { // std::cout << "Evaluate Integrand for Generator4Param..." << std::endl; - g_[0] = trajectoryPenalty(time_); + auto* g = g_.getData(); + + g[0] = trajectoryPenalty(time_); return 0; } @@ -226,14 +228,16 @@ namespace GridKit int Generator4Param::initializeAdjoint() { // std::cout << "Initialize adjoint for Generator4Param..." << std::endl; + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + for (IdxT i = 0; i < size_; ++i) { - yB_[static_cast(i)] = 0.0; - ypB_[static_cast(i)] = 0.0; + yB[static_cast(i)] = 0.0; + ypB[static_cast(i)] = 0.0; } - // ypB_[1] = frequencyPenaltyDer(y_[1]); - ypB_[2] = -trajectoryPenaltyDerEdp(time_) / Tq0p_; - ypB_[3] = -trajectoryPenaltyDerEqp(time_) / Td0p_; + ypB[2] = -trajectoryPenaltyDerEdp(time_) / Tq0p_; + ypB[3] = -trajectoryPenaltyDerEqp(time_) / Td0p_; return 0; } @@ -259,13 +263,17 @@ namespace GridKit ScalarT sinPhi = sin(delta() - theta()); ScalarT cosPhi = cos(delta() - theta()); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* fB = fB_.getData(); + // Generator adjoint - fB_[0] = ypB_[0] - yB_[4] * V() * cosPhi + yB_[5] * V() * sinPhi; - fB_[1] = 2.0 * H() / omega_s_ * ypB_[1] + yB_[0] * omega_b_ - yB_[1] * D_; //+ frequencyPenaltyDer(omega()); - fB_[2] = Tq0p_ * ypB_[2] - yB_[1] * Id() - yB_[2] + yB_[4] + trajectoryPenaltyDerEdp(time_); - fB_[3] = Td0p_ * ypB_[3] - yB_[1] * Iq() - yB_[3] + yB_[5] + trajectoryPenaltyDerEqp(time_); - fB_[4] = -yB_[1] * (Edp() + (Xqp_ - Xdp_) * Iq()) - yB_[3] * (Xd_ - Xdp_) - yB_[4] * Rs_ - yB_[5] * Xdp_; - fB_[5] = -yB_[1] * (Eqp() + (Xqp_ - Xdp_) * Id()) + yB_[2] * (Xq_ - Xqp_) + yB_[4] * Xqp_ - yB_[5] * Rs_; + fB[0] = ypB[0] - yB[4] * V() * cosPhi + yB[5] * V() * sinPhi; + fB[1] = 2.0 * H() / omega_s_ * ypB[1] + yB[0] * omega_b_ - yB[1] * D_; //+ frequencyPenaltyDer(omega()); + fB[2] = Tq0p_ * ypB[2] - yB[1] * Id() - yB[2] + yB[4] + trajectoryPenaltyDerEdp(time_); + fB[3] = Td0p_ * ypB[3] - yB[1] * Iq() - yB[3] + yB[5] + trajectoryPenaltyDerEqp(time_); + fB[4] = -yB[1] * (Edp() + (Xqp_ - Xdp_) * Iq()) - yB[3] * (Xd_ - Xdp_) - yB[4] * Rs_ - yB[5] * Xdp_; + fB[5] = -yB[1] * (Eqp() + (Xqp_ - Xdp_) * Id()) + yB[2] * (Xq_ - Xqp_) + yB[4] * Xqp_ - yB[5] * Rs_; return 0; } @@ -282,7 +290,10 @@ namespace GridKit int Generator4Param::evaluateAdjointIntegrand() { // std::cout << "Evaluate adjoint Integrand for Generator4Param..." << std::endl; - gB_[0] = -2.0 * yB_[1] * dotOmega() / omega_s_; + auto* yB = yB_.getData(); + auto* gB = gB_.getData(); + + gB[0] = -2.0 * yB[1] * dotOmega() / omega_s_; return 0; } @@ -300,7 +311,8 @@ namespace GridKit template ScalarT Generator4Param::Pg() { - return y_[5] * V() * cos(theta() - y_[0]) + y_[4] * V() * sin(theta() - y_[0]); + auto* y = y_.getData(); + return y[5] * V() * cos(theta() - y[0]) + y[4] * V() * sin(theta() - y[0]); } /** @@ -311,7 +323,8 @@ namespace GridKit template ScalarT Generator4Param::Qg() { - return y_[5] * V() * sin(theta() - y_[0]) - y_[4] * V() * cos(theta() - y_[0]); + auto* y = y_.getData(); + return y[5] * V() * sin(theta() - y[0]) - y[4] * V() * cos(theta() - y[0]); } /** diff --git a/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.hpp b/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.hpp index bc1b94321..d01c5b043 100644 --- a/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.hpp +++ b/GridKit/Model/PowerFlow/Generator4Param/Generator4Param.hpp @@ -120,19 +120,17 @@ namespace GridKit private: const ScalarT& H() const { - return param_[0]; + return param_.getData()[0]; } const ScalarT& Pm() const { return Pm_; - // return param_[0]; } const ScalarT& Ef() const { return Ef_; - // return param_[1]; } ScalarT Pg(); @@ -145,52 +143,52 @@ namespace GridKit const ScalarT dotDelta() const { - return yp_[0]; + return yp_.getData()[0]; } const ScalarT dotOmega() const { - return yp_[1]; + return yp_.getData()[1]; } const ScalarT dotEdp() const { - return yp_[2]; + return yp_.getData()[2]; } const ScalarT dotEqp() const { - return yp_[3]; + return yp_.getData()[3]; } const ScalarT delta() const { - return y_[0]; + return y_.getData()[0]; } const ScalarT omega() const { - return y_[1]; + return y_.getData()[1]; } const ScalarT Edp() const { - return y_[2]; + return y_.getData()[2]; } const ScalarT Eqp() const { - return y_[3]; + return y_.getData()[3]; } const ScalarT Id() const { - return y_[4]; + return y_.getData()[4]; } const ScalarT Iq() const { - return y_[5]; + return y_.getData()[5]; } private: diff --git a/GridKit/Model/PowerFlow/Load/CMakeLists.txt b/GridKit/Model/PowerFlow/Load/CMakeLists.txt index c00bfc959..57e4eb5b6 100644 --- a/GridKit/Model/PowerFlow/Load/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/Load/CMakeLists.txt @@ -6,4 +6,5 @@ gridkit_add_library( load SOURCES Load.cpp - HEADERS Load.hpp) + HEADERS Load.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/MiniGrid/CMakeLists.txt b/GridKit/Model/PowerFlow/MiniGrid/CMakeLists.txt index e814b5852..d76d79ceb 100644 --- a/GridKit/Model/PowerFlow/MiniGrid/CMakeLists.txt +++ b/GridKit/Model/PowerFlow/MiniGrid/CMakeLists.txt @@ -6,4 +6,5 @@ gridkit_add_library( minigrid SOURCES MiniGrid.cpp - HEADERS MiniGrid.hpp) + HEADERS MiniGrid.hpp + LINK_LIBRARIES GridKit::dense_vector) diff --git a/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.cpp b/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.cpp index 8dc9e8e5f..9f3c8f82e 100644 --- a/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.cpp +++ b/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.cpp @@ -67,9 +67,10 @@ namespace GridKit template int MiniGrid::evaluateResidual() { - f_[0] = -Pl2_ - V2() * (V1_ * B12_ * sin(th2() - th1_) + V3_ * B23_ * sin(th2() - th3())); - f_[1] = -Ql2_ + V2() * (V1_ * B12_ * cos(th2() - th1_) + B22_ * V2() + V3_ * B23_ * cos(th2() - th3())); - f_[2] = Pg3_ - V3_ * (V1_ * B13_ * sin(th3() - th1_) + V2() * B23_ * sin(th3() - th2())); + auto* f = f_.getData(); + f[0] = -Pl2_ - V2() * (V1_ * B12_ * sin(th2() - th1_) + V3_ * B23_ * sin(th2() - th3())); + f[1] = -Ql2_ + V2() * (V1_ * B12_ * cos(th2() - th1_) + B22_ * V2() + V3_ * B23_ * cos(th2() - th3())); + f[2] = Pg3_ - V3_ * (V1_ * B13_ * sin(th3() - th1_) + V2() * B23_ * sin(th3() - th2())); return 0; } diff --git a/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.hpp b/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.hpp index 2f69e08bf..7c8fb5132 100644 --- a/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.hpp +++ b/GridKit/Model/PowerFlow/MiniGrid/MiniGrid.hpp @@ -69,32 +69,32 @@ namespace GridKit // const accessors are public ScalarT const& th2() const { - return y_[0]; + return y_.getData()[0]; } ScalarT const& V2() const { - return y_[1]; + return y_.getData()[1]; } ScalarT const& th3() const { - return y_[2]; + return y_.getData()[2]; } ScalarT& th2() { - return y_[0]; + return y_.getData()[0]; } ScalarT& V2() { - return y_[1]; + return y_.getData()[1]; } ScalarT& th3() { - return y_[2]; + return y_.getData()[2]; } private: diff --git a/GridKit/Model/PowerFlow/ModelEvaluatorImpl.hpp b/GridKit/Model/PowerFlow/ModelEvaluatorImpl.hpp index 7f071904a..07eefeb24 100644 --- a/GridKit/Model/PowerFlow/ModelEvaluatorImpl.hpp +++ b/GridKit/Model/PowerFlow/ModelEvaluatorImpl.hpp @@ -15,8 +15,17 @@ namespace GridKit template class ModelEvaluatorImpl : public Model::Evaluator { + protected: + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::allocateVectors; + public: - using RealT = typename Model::Evaluator::RealT; + using RealT = typename Model::Evaluator::RealT; + using VectorT = typename Model::Evaluator::VectorT; ModelEvaluatorImpl() : size_(0), @@ -27,20 +36,43 @@ namespace GridKit ModelEvaluatorImpl(IdxT size, IdxT size_quad, IdxT size_opt) : size_(size), + nnz_(0), size_quad_(size_quad), size_opt_(size_opt), - y_(static_cast(size_)), - yp_(static_cast(size_)), - f_(static_cast(size_)), - g_(static_cast(size_quad_)), - yB_(static_cast(size_)), - ypB_(static_cast(size_)), - fB_(static_cast(size_)), - gB_(static_cast(size_opt_)), - param_(static_cast(size_opt_)), - param_up_(static_cast(size_opt_)), - param_lo_(static_cast(size_opt_)) + g_(size_quad_), + yB_(size_), + ypB_(size_), + fB_(size_), + gB_(size_opt_), + param_(size_opt_), + param_up_(size_opt_), + param_lo_(size_opt_) { + allocateVectors(size_); + + g_.allocate(memory::HOST); + g_.setDataUpdated(memory::HOST); + + yB_.allocate(memory::HOST); + yB_.setDataUpdated(memory::HOST); + + ypB_.allocate(memory::HOST); + ypB_.setDataUpdated(memory::HOST); + + fB_.allocate(memory::HOST); + fB_.setDataUpdated(memory::HOST); + + gB_.allocate(memory::HOST); + gB_.setDataUpdated(memory::HOST); + + param_.allocate(memory::HOST); + param_.setDataUpdated(memory::HOST); + + param_up_.allocate(memory::HOST); + param_up_.setDataUpdated(memory::HOST); + + param_lo_.allocate(memory::HOST); + param_lo_.setDataUpdated(memory::HOST); } virtual IdxT size() @@ -80,132 +112,132 @@ namespace GridKit msa = max_steps_; } - std::vector& y() + VectorT& y() { return y_; } - const std::vector& y() const + const VectorT& y() const { return y_; } - std::vector& yp() + VectorT& yp() { return yp_; } - const std::vector& yp() const + const VectorT& yp() const { return yp_; } - std::vector& tag() + VectorT& tag() { return tag_; } - const std::vector& tag() const + const VectorT& tag() const { return tag_; } - std::vector& absoluteTolerance() + VectorT& absoluteTolerance() { return abs_tol_; } - const std::vector& absoluteTolerance() const + const VectorT& absoluteTolerance() const { return abs_tol_; } - std::vector& yB() + VectorT& yB() { return yB_; } - const std::vector& yB() const + const VectorT& yB() const { return yB_; } - std::vector& ypB() + VectorT& ypB() { return ypB_; } - const std::vector& ypB() const + const VectorT& ypB() const { return ypB_; } - std::vector& param() + VectorT& param() { return param_; } - const std::vector& param() const + const VectorT& param() const { return param_; } - std::vector& param_up() + VectorT& param_up() { return param_up_; } - const std::vector& param_up() const + const VectorT& param_up() const { return param_up_; } - std::vector& param_lo() + VectorT& param_lo() { return param_lo_; } - const std::vector& param_lo() const + const VectorT& param_lo() const { return param_lo_; } - std::vector& getResidual() + VectorT& getResidual() { return f_; } - const std::vector& getResidual() const + const VectorT& getResidual() const { return f_; } - std::vector& getIntegrand() + VectorT& getIntegrand() { return g_; } - const std::vector& getIntegrand() const + const VectorT& getIntegrand() const { return g_; } - std::vector& getAdjointResidual() + VectorT& getAdjointResidual() { return fB_; } - const std::vector& getAdjointResidual() const + const VectorT& getAdjointResidual() const { return fB_; } - std::vector& getAdjointIntegrand() + VectorT& getAdjointIntegrand() { return gB_; } - const std::vector& getAdjointIntegrand() const + const VectorT& getAdjointIntegrand() const { return gB_; } @@ -222,21 +254,16 @@ namespace GridKit IdxT size_quad_; IdxT size_opt_; - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; - std::vector g_; - - std::vector yB_; - std::vector ypB_; - std::vector fB_; - std::vector gB_; - - std::vector param_; - std::vector param_up_; - std::vector param_lo_; + VectorT g_; + + VectorT yB_; + VectorT ypB_; + VectorT fB_; + VectorT gB_; + + VectorT param_; + VectorT param_up_; + VectorT param_lo_; RealT time_; RealT alpha_; diff --git a/GridKit/Model/PowerFlow/SystemModel.hpp b/GridKit/Model/PowerFlow/SystemModel.hpp index e174b4346..7715b6b6b 100644 --- a/GridKit/Model/PowerFlow/SystemModel.hpp +++ b/GridKit/Model/PowerFlow/SystemModel.hpp @@ -27,6 +27,7 @@ namespace GridKit using bus_type = Model::Evaluator; using component_type = Model::Evaluator; using RealT = typename ModelEvaluatorImpl::RealT; + using VectorT = typename ModelEvaluatorImpl::VectorT; using ModelEvaluatorImpl::size_; using ModelEvaluatorImpl::size_quad_; @@ -101,21 +102,23 @@ namespace GridKit } // Allocate global vectors - y_.resize(size_); - yp_.resize(size_); - yB_.resize(size_); - ypB_.resize(size_); - f_.resize(size_); - fB_.resize(size_); - tag_.resize(size_); - abs_tol_.resize(size_); - - g_.resize(size_quad_); - gB_.resize(size_quad_ * size_opt_); - - param_.resize(size_opt_); - param_lo_.resize(size_opt_); - param_up_.resize(size_opt_); + this->allocateVectors(size_); + + auto allocate_host_vector = [](VectorT& vector, IdxT n) + { + vector.resize(n); + vector.allocate(memory::HOST); + vector.setDataUpdated(memory::HOST); + }; + + allocate_host_vector(yB_, size_); + allocate_host_vector(ypB_, size_); + allocate_host_vector(fB_, size_); + allocate_host_vector(g_, size_quad_); + allocate_host_vector(gB_, size_quad_ * size_opt_); + allocate_host_vector(param_, size_opt_); + allocate_host_vector(param_lo_, size_opt_); + allocate_host_vector(param_up_, size_opt_); assert(size_quad_ == 1 or size_quad_ == 0); @@ -151,8 +154,13 @@ namespace GridKit int initialize() { // Set initial values for global solution vectors - IdxT varOffset = 0; - IdxT optOffset = 0; + IdxT varOffset = 0; + IdxT optOffset = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* param = param_.getData(); + auto* param_lo = param_lo_.getData(); + auto* param_up = param_up_.getData(); for (const auto& bus : buses_) { @@ -161,18 +169,24 @@ namespace GridKit for (const auto& bus : buses_) { + auto* bus_y = dataOrNull(bus->y()); + auto* bus_yp = dataOrNull(bus->yp()); + auto* bus_param = dataOrNull(bus->param()); + auto* bus_param_lo = dataOrNull(bus->param_lo()); + auto* bus_param_up = dataOrNull(bus->param_up()); + for (IdxT j = 0; j < bus->size(); ++j) { - y_[varOffset + j] = bus->y()[j]; - yp_[varOffset + j] = bus->yp()[j]; + y[varOffset + j] = bus_y[j]; + yp[varOffset + j] = bus_yp[j]; } varOffset += bus->size(); for (IdxT j = 0; j < bus->sizeParams(); ++j) { - param_[optOffset + j] = bus->param()[j]; - param_lo_[optOffset + j] = bus->param_lo()[j]; - param_up_[optOffset + j] = bus->param_up()[j]; + param[optOffset + j] = bus_param[j]; + param_lo[optOffset + j] = bus_param_lo[j]; + param_up[optOffset + j] = bus_param_up[j]; } optOffset += bus->sizeParams(); } @@ -185,18 +199,24 @@ namespace GridKit for (const auto& component : components_) { + auto* component_y = dataOrNull(component->y()); + auto* component_yp = dataOrNull(component->yp()); + auto* component_param = dataOrNull(component->param()); + auto* component_param_lo = dataOrNull(component->param_lo()); + auto* component_param_up = dataOrNull(component->param_up()); + for (IdxT j = 0; j < component->size(); ++j) { - y_[varOffset + j] = component->y()[j]; - yp_[varOffset + j] = component->yp()[j]; + y[varOffset + j] = component_y[j]; + yp[varOffset + j] = component_yp[j]; } varOffset += component->size(); for (IdxT j = 0; j < component->sizeParams(); ++j) { - param_[optOffset + j] = component->param()[j]; - param_lo_[optOffset + j] = component->param_lo()[j]; - param_up_[optOffset + j] = component->param_up()[j]; + param[optOffset + j] = component_param[j]; + param_lo[optOffset + j] = component_param_lo[j]; + param_up[optOffset + j] = component_param_up[j]; } optOffset += component->sizeParams(); } @@ -214,13 +234,17 @@ namespace GridKit int tagDifferentiable() { // Set initial values for global solution vectors - IdxT offset = 0; + IdxT offset = 0; + auto* tag = tag_.getData(); + for (const auto& bus : buses_) { bus->tagDifferentiable(); + auto* bus_tag = dataOrNull(bus->tag()); + for (IdxT j = 0; j < bus->size(); ++j) { - tag_[offset + j] = bus->tag()[j]; + tag[offset + j] = bus_tag[j]; } offset += bus->size(); } @@ -228,9 +252,11 @@ namespace GridKit for (const auto& component : components_) { component->tagDifferentiable(); + auto* component_tag = dataOrNull(component->tag()); + for (IdxT j = 0; j < component->size(); ++j) { - tag_[offset + j] = component->tag()[j]; + tag[offset + j] = component_tag[j]; } offset += component->size(); } @@ -253,13 +279,17 @@ namespace GridKit int setAbsoluteTolerance(RealT rel_tol) { // Set initial values for global solution vectors - IdxT offset = 0; + IdxT offset = 0; + auto* abs_tol = abs_tol_.getData(); + for (const auto& bus : buses_) { bus->setAbsoluteTolerance(rel_tol); + auto* bus_abs_tol = dataOrNull(bus->absoluteTolerance()); + for (IdxT j = 0; j < bus->size(); ++j) { - abs_tol_[offset + j] = bus->absoluteTolerance()[j]; + abs_tol[offset + j] = bus_abs_tol[j]; } offset += bus->size(); } @@ -267,9 +297,11 @@ namespace GridKit for (const auto& component : components_) { component->setAbsoluteTolerance(rel_tol); + auto* component_abs_tol = dataOrNull(component->absoluteTolerance()); + for (IdxT j = 0; j < component->size(); ++j) { - abs_tol_[offset + j] = component->absoluteTolerance()[j]; + abs_tol[offset + j] = component_abs_tol[j]; } offset += component->size(); } @@ -298,20 +330,29 @@ namespace GridKit int evaluateResidual() { // Update variables - IdxT varOffset = 0; - IdxT optOffset = 0; + IdxT varOffset = 0; + IdxT optOffset = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* param = param_.getData(); + auto* f = f_.getData(); + for (const auto& bus : buses_) { + auto* bus_y = dataOrNull(bus->y()); + auto* bus_yp = dataOrNull(bus->yp()); + auto* bus_param = dataOrNull(bus->param()); + for (IdxT j = 0; j < bus->size(); ++j) { - bus->y()[j] = y_[varOffset + j]; - bus->yp()[j] = yp_[varOffset + j]; + bus_y[j] = y[varOffset + j]; + bus_yp[j] = yp[varOffset + j]; } varOffset += bus->size(); for (IdxT j = 0; j < bus->sizeParams(); ++j) { - bus->param()[j] = param_[optOffset + j]; + bus_param[j] = param[optOffset + j]; } optOffset += bus->sizeParams(); @@ -320,16 +361,20 @@ namespace GridKit for (const auto& component : components_) { + auto* component_y = dataOrNull(component->y()); + auto* component_yp = dataOrNull(component->yp()); + auto* component_param = dataOrNull(component->param()); + for (IdxT j = 0; j < component->size(); ++j) { - component->y()[j] = y_[varOffset + j]; - component->yp()[j] = yp_[varOffset + j]; + component_y[j] = y[varOffset + j]; + component_yp[j] = yp[varOffset + j]; } varOffset += component->size(); for (IdxT j = 0; j < component->sizeParams(); ++j) { - component->param()[j] = param_[optOffset + j]; + component_param[j] = param[optOffset + j]; } optOffset += component->sizeParams(); @@ -340,18 +385,22 @@ namespace GridKit IdxT resOffset = 0; for (const auto& bus : buses_) { + auto* bus_f = dataOrNull(bus->getResidual()); + for (IdxT j = 0; j < bus->size(); ++j) { - f_[resOffset + j] = bus->getResidual()[j]; + f[resOffset + j] = bus_f[j]; } resOffset += bus->size(); } for (const auto& component : components_) { + auto* component_f = dataOrNull(component->getResidual()); + for (IdxT j = 0; j < component->size(); ++j) { - f_[resOffset + j] = component->getResidual()[j]; + f[resOffset + j] = component_f[j]; } resOffset += component->size(); } @@ -378,20 +427,29 @@ namespace GridKit int evaluateIntegrand() { // Update variables - IdxT varOffset = 0; - IdxT optOffset = 0; + IdxT varOffset = 0; + IdxT optOffset = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* param = param_.getData(); + auto* g = g_.getData(); + for (const auto& bus : buses_) { + auto* bus_y = dataOrNull(bus->y()); + auto* bus_yp = dataOrNull(bus->yp()); + auto* bus_param = dataOrNull(bus->param()); + for (IdxT j = 0; j < bus->size(); ++j) { - bus->y()[j] = y_[varOffset + j]; - bus->yp()[j] = yp_[varOffset + j]; + bus_y[j] = y[varOffset + j]; + bus_yp[j] = yp[varOffset + j]; } varOffset += bus->size(); for (IdxT j = 0; j < bus->sizeParams(); ++j) { - bus->param()[j] = param_[optOffset + j]; + bus_param[j] = param[optOffset + j]; } optOffset += bus->sizeParams(); @@ -400,16 +458,20 @@ namespace GridKit for (const auto& component : components_) { + auto* component_y = dataOrNull(component->y()); + auto* component_yp = dataOrNull(component->yp()); + auto* component_param = dataOrNull(component->param()); + for (IdxT j = 0; j < component->size(); ++j) { - component->y()[j] = y_[varOffset + j]; - component->yp()[j] = yp_[varOffset + j]; + component_y[j] = y[varOffset + j]; + component_yp[j] = yp[varOffset + j]; } varOffset += component->size(); for (IdxT j = 0; j < component->sizeParams(); ++j) { - component->param()[j] = param_[optOffset + j]; + component_param[j] = param[optOffset + j]; } optOffset += component->sizeParams(); @@ -420,18 +482,22 @@ namespace GridKit IdxT intOffset = 0; for (const auto& bus : buses_) { + auto* bus_g = dataOrNull(bus->getIntegrand()); + for (IdxT j = 0; j < bus->sizeQuadrature(); ++j) { - g_[intOffset + j] = bus->getIntegrand()[j]; + g[intOffset + j] = bus_g[j]; } intOffset += bus->sizeQuadrature(); } for (const auto& component : components_) { + auto* component_g = dataOrNull(component->getIntegrand()); + for (IdxT j = 0; j < component->sizeQuadrature(); ++j) { - g_[intOffset + j] = component->getIntegrand()[j]; + g[intOffset + j] = component_g[j]; } intOffset += component->sizeQuadrature(); } @@ -447,22 +513,31 @@ namespace GridKit */ int initializeAdjoint() { - IdxT offset = 0; - IdxT optOffset = 0; + IdxT offset = 0; + IdxT optOffset = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* param = param_.getData(); // Update bus variables and optimization parameters for (const auto& bus : buses_) { + auto* bus_y = dataOrNull(bus->y()); + auto* bus_yp = dataOrNull(bus->yp()); + auto* bus_param = dataOrNull(bus->param()); + for (IdxT j = 0; j < bus->size(); ++j) { - bus->y()[j] = y_[offset + j]; - bus->yp()[j] = yp_[offset + j]; + bus_y[j] = y[offset + j]; + bus_yp[j] = yp[offset + j]; } offset += bus->size(); for (IdxT j = 0; j < bus->sizeParams(); ++j) { - bus->param()[j] = param_[optOffset + j]; + bus_param[j] = param[optOffset + j]; } optOffset += bus->sizeParams(); } @@ -470,16 +545,20 @@ namespace GridKit // Update component variables and optimization parameters for (const auto& component : components_) { + auto* component_y = dataOrNull(component->y()); + auto* component_yp = dataOrNull(component->yp()); + auto* component_param = dataOrNull(component->param()); + for (IdxT j = 0; j < component->size(); ++j) { - component->y()[j] = y_[offset + j]; - component->yp()[j] = yp_[offset + j]; + component_y[j] = y[offset + j]; + component_yp[j] = yp[offset + j]; } offset += component->size(); for (IdxT j = 0; j < component->sizeParams(); ++j) { - component->param()[j] = param_[optOffset + j]; + component_param[j] = param[optOffset + j]; } optOffset += component->sizeParams(); } @@ -491,11 +570,13 @@ namespace GridKit for (const auto& bus : buses_) { bus->initializeAdjoint(); + auto* bus_yB = dataOrNull(bus->yB()); + auto* bus_ypB = dataOrNull(bus->ypB()); for (IdxT j = 0; j < bus->size(); ++j) { - yB_[offset + j] = bus->yB()[j]; - ypB_[offset + j] = bus->ypB()[j]; + yB[offset + j] = bus_yB[j]; + ypB[offset + j] = bus_ypB[j]; } offset += bus->size(); } @@ -504,11 +585,13 @@ namespace GridKit for (const auto& component : components_) { component->initializeAdjoint(); + auto* component_yB = dataOrNull(component->yB()); + auto* component_ypB = dataOrNull(component->ypB()); for (IdxT j = 0; j < component->size(); ++j) { - yB_[offset + j] = component->yB()[j]; - ypB_[offset + j] = component->ypB()[j]; + yB[offset + j] = component_yB[j]; + ypB[offset + j] = component_ypB[j]; } offset += component->size(); } @@ -525,42 +608,60 @@ namespace GridKit */ int evaluateAdjointResidual() { - IdxT varOffset = 0; - IdxT optOffset = 0; + IdxT varOffset = 0; + IdxT optOffset = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* param = param_.getData(); + auto* fB = fB_.getData(); // Update variables in component models for (const auto& bus : buses_) { + auto* bus_y = dataOrNull(bus->y()); + auto* bus_yp = dataOrNull(bus->yp()); + auto* bus_yB = dataOrNull(bus->yB()); + auto* bus_ypB = dataOrNull(bus->ypB()); + auto* bus_param = dataOrNull(bus->param()); + for (IdxT j = 0; j < bus->size(); ++j) { - bus->y()[j] = y_[varOffset + j]; - bus->yp()[j] = yp_[varOffset + j]; - bus->yB()[j] = yB_[varOffset + j]; - bus->ypB()[j] = ypB_[varOffset + j]; + bus_y[j] = y[varOffset + j]; + bus_yp[j] = yp[varOffset + j]; + bus_yB[j] = yB[varOffset + j]; + bus_ypB[j] = ypB[varOffset + j]; } varOffset += bus->size(); for (IdxT j = 0; j < bus->sizeParams(); ++j) { - bus->param()[j] = param_[optOffset + j]; + bus_param[j] = param[optOffset + j]; } optOffset += bus->sizeParams(); } for (const auto& component : components_) { + auto* component_y = dataOrNull(component->y()); + auto* component_yp = dataOrNull(component->yp()); + auto* component_yB = dataOrNull(component->yB()); + auto* component_ypB = dataOrNull(component->ypB()); + auto* component_param = dataOrNull(component->param()); + for (IdxT j = 0; j < component->size(); ++j) { - component->y()[j] = y_[varOffset + j]; - component->yp()[j] = yp_[varOffset + j]; - component->yB()[j] = yB_[varOffset + j]; - component->ypB()[j] = ypB_[varOffset + j]; + component_y[j] = y[varOffset + j]; + component_yp[j] = yp[varOffset + j]; + component_yB[j] = yB[varOffset + j]; + component_ypB[j] = ypB[varOffset + j]; } varOffset += component->size(); for (IdxT j = 0; j < component->sizeParams(); ++j) { - component->param()[j] = param_[optOffset + j]; + component_param[j] = param[optOffset + j]; } optOffset += component->sizeParams(); } @@ -579,18 +680,22 @@ namespace GridKit IdxT resOffset = 0; for (const auto& bus : buses_) { + auto* bus_fB = dataOrNull(bus->getAdjointResidual()); + for (IdxT j = 0; j < bus->size(); ++j) { - fB_[resOffset + j] = bus->getAdjointResidual()[j]; + fB[resOffset + j] = bus_fB[j]; } resOffset += bus->size(); } for (const auto& component : components_) { + auto* component_fB = dataOrNull(component->getAdjointResidual()); + for (IdxT j = 0; j < component->size(); ++j) { - fB_[resOffset + j] = component->getAdjointResidual()[j]; + fB[resOffset + j] = component_fB[j]; } resOffset += component->size(); } @@ -610,40 +715,59 @@ namespace GridKit int evaluateAdjointIntegrand() { // First, update variables - IdxT varOffset = 0; - IdxT optOffset = 0; + IdxT varOffset = 0; + IdxT optOffset = 0; + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* yB = yB_.getData(); + auto* ypB = ypB_.getData(); + auto* param = param_.getData(); + auto* gB = gB_.getData(); + for (const auto& bus : buses_) { + auto* bus_y = dataOrNull(bus->y()); + auto* bus_yp = dataOrNull(bus->yp()); + auto* bus_yB = dataOrNull(bus->yB()); + auto* bus_ypB = dataOrNull(bus->ypB()); + auto* bus_param = dataOrNull(bus->param()); + for (IdxT j = 0; j < bus->size(); ++j) { - bus->y()[j] = y_[varOffset + j]; - bus->yp()[j] = yp_[varOffset + j]; - bus->yB()[j] = yB_[varOffset + j]; - bus->ypB()[j] = ypB_[varOffset + j]; + bus_y[j] = y[varOffset + j]; + bus_yp[j] = yp[varOffset + j]; + bus_yB[j] = yB[varOffset + j]; + bus_ypB[j] = ypB[varOffset + j]; } varOffset += bus->size(); for (IdxT j = 0; j < bus->sizeParams(); ++j) { - bus->param()[j] = param_[optOffset + j]; + bus_param[j] = param[optOffset + j]; } optOffset += bus->sizeParams(); } for (const auto& component : components_) { + auto* component_y = dataOrNull(component->y()); + auto* component_yp = dataOrNull(component->yp()); + auto* component_yB = dataOrNull(component->yB()); + auto* component_ypB = dataOrNull(component->ypB()); + auto* component_param = dataOrNull(component->param()); + for (IdxT j = 0; j < component->size(); ++j) { - component->y()[j] = y_[varOffset + j]; - component->yp()[j] = yp_[varOffset + j]; - component->yB()[j] = yB_[varOffset + j]; - component->ypB()[j] = ypB_[varOffset + j]; + component_y[j] = y[varOffset + j]; + component_yp[j] = yp[varOffset + j]; + component_yB[j] = yB[varOffset + j]; + component_ypB[j] = ypB[varOffset + j]; } varOffset += component->size(); for (IdxT j = 0; j < component->sizeParams(); ++j) { - component->param()[j] = param_[optOffset + j]; + component_param[j] = param[optOffset + j]; } optOffset += component->sizeParams(); } @@ -654,9 +778,11 @@ namespace GridKit if (component->sizeQuadrature() == 1) { component->evaluateAdjointIntegrand(); + auto* component_gB = dataOrNull(component->getAdjointIntegrand()); + for (IdxT j = 0; j < size_opt_; ++j) { - gB_[j] = component->getAdjointIntegrand()[j]; + gB[j] = component_gB[j]; } break; } @@ -683,6 +809,11 @@ namespace GridKit } private: + static ScalarT* dataOrNull(VectorT& vector) + { + return vector.getSize() == 0 ? nullptr : vector.getData(); + } + std::vector buses_; std::vector components_; diff --git a/GridKit/Model/PowerFlow/SystemModelPowerFlow.hpp b/GridKit/Model/PowerFlow/SystemModelPowerFlow.hpp index 44b8a75fb..ef4ff2299 100644 --- a/GridKit/Model/PowerFlow/SystemModelPowerFlow.hpp +++ b/GridKit/Model/PowerFlow/SystemModelPowerFlow.hpp @@ -148,10 +148,7 @@ namespace GridKit } // Allocate global vectors - y_.resize(size_); - f_.resize(size_); - tag_.resize(size_); - abs_tol_.resize(size_); + this->allocateVectors(size_); return 0; } @@ -174,7 +171,8 @@ namespace GridKit int initialize() { // Set initial values for global solution vectors - IdxT varOffset = 0; + IdxT varOffset = 0; + auto* y = y_.getData(); for (const auto& bus : buses_) { @@ -183,9 +181,14 @@ namespace GridKit for (const auto& bus : buses_) { - for (IdxT j = 0; j < bus->size(); ++j) + if (bus->y().getSize() > 0) { - y_[varOffset + j] = bus->y()[j]; + auto* bus_y = bus->y().getData(); + + for (IdxT j = 0; j < bus->size(); ++j) + { + y[varOffset + j] = bus_y[j]; + } } varOffset += bus->size(); } @@ -198,9 +201,14 @@ namespace GridKit for (const auto& component : components_) { - for (IdxT j = 0; j < component->size(); ++j) + if (component->y().getSize() > 0) { - y_[varOffset + j] = component->y()[j]; + auto* component_y = component->y().getData(); + + for (IdxT j = 0; j < component->size(); ++j) + { + y[varOffset + j] = component_y[j]; + } } varOffset += component->size(); } @@ -233,7 +241,7 @@ namespace GridKit */ int setAbsoluteTolerance(RealT rel_tol) { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } @@ -258,12 +266,20 @@ namespace GridKit int evaluateResidual() { // Update variables - IdxT varOffset = 0; + IdxT varOffset = 0; + auto* y = y_.getData(); + auto* f = f_.getData(); + for (const auto& bus : buses_) { - for (IdxT j = 0; j < bus->size(); ++j) + if (bus->y().getSize() > 0) { - bus->y()[j] = y_[varOffset + j]; + auto* bus_y = bus->y().getData(); + + for (IdxT j = 0; j < bus->size(); ++j) + { + bus_y[j] = y[varOffset + j]; + } } varOffset += bus->size(); bus->evaluateResidual(); @@ -271,9 +287,14 @@ namespace GridKit for (const auto& component : components_) { - for (IdxT j = 0; j < component->size(); ++j) + if (component->y().getSize() > 0) { - component->y()[j] = y_[varOffset + j]; + auto* component_y = component->y().getData(); + + for (IdxT j = 0; j < component->size(); ++j) + { + component_y[j] = y[varOffset + j]; + } } varOffset += component->size(); component->evaluateResidual(); @@ -283,18 +304,28 @@ namespace GridKit IdxT resOffset = 0; for (const auto& bus : buses_) { - for (IdxT j = 0; j < bus->size(); ++j) + if (bus->getResidual().getSize() > 0) { - f_[resOffset + j] = bus->getResidual()[j]; + auto* bus_f = bus->getResidual().getData(); + + for (IdxT j = 0; j < bus->size(); ++j) + { + f[resOffset + j] = bus_f[j]; + } } resOffset += bus->size(); } for (const auto& component : components_) { - for (IdxT j = 0; j < component->size(); ++j) + if (component->getResidual().getSize() > 0) { - f_[resOffset + j] = component->getResidual()[j]; + auto* component_f = component->getResidual().getData(); + + for (IdxT j = 0; j < component->size(); ++j) + { + f[resOffset + j] = component_f[j]; + } } resOffset += component->size(); } diff --git a/GridKit/Solver/Dynamic/CMakeLists.txt b/GridKit/Solver/Dynamic/CMakeLists.txt index 2d7fa0152..8c9a32c8b 100644 --- a/GridKit/Solver/Dynamic/CMakeLists.txt +++ b/GridKit/Solver/Dynamic/CMakeLists.txt @@ -24,7 +24,9 @@ if(GRIDKIT_ENABLE_SUNDIALS_SPARSE) PUBLIC GridKit::utilities_logger PUBLIC - GridKit::sparse_matrix) + GridKit::sparse_matrix + PUBLIC + GridKit::dense_vector) else() gridkit_add_library( solvers_dyn @@ -40,5 +42,7 @@ else() PUBLIC GridKit::utilities_logger PUBLIC - GridKit::sparse_matrix) + GridKit::sparse_matrix + PUBLIC + GridKit::dense_vector) endif() diff --git a/GridKit/Solver/Dynamic/Ida.cpp b/GridKit/Solver/Dynamic/Ida.cpp index 9007bbf44..cd4d686ed 100644 --- a/GridKit/Solver/Dynamic/Ida.cpp +++ b/GridKit/Solver/Dynamic/Ida.cpp @@ -728,8 +728,7 @@ namespace AnalysisManager model->updateTime(tres, 0.0); model->evaluateResidual(); - const std::vector& f = model->getResidual(); - copyVec(f, rr); + copyVec(model->getResidual(), rr); return 0; } @@ -794,8 +793,7 @@ namespace AnalysisManager model->updateTime(tt, 0.0); model->evaluateIntegrand(); - const std::vector& g = model->getIntegrand(); - copyVec(g, rhsQ); + copyVec(model->getIntegrand(), rhsQ); return 0; } @@ -818,8 +816,7 @@ namespace AnalysisManager model->updateTime(tt, 0.0); model->evaluateAdjointResidual(); - const std::vector& fB = model->getAdjointResidual(); - copyVec(fB, rrB); + copyVec(model->getAdjointResidual(), rrB); return 0; } @@ -842,73 +839,53 @@ namespace AnalysisManager model->updateTime(tt, 0.0); model->evaluateAdjointIntegrand(); - const std::vector& gB = model->getAdjointIntegrand(); - copyVec(gB, rhsQB); + copyVec(model->getAdjointIntegrand(), rhsQB); return 0; } /** - * @brief Copy SUNDIALS N_Vector to std::vector + * @brief Copy SUNDIALS N_Vector to Vector * * @tparam ScalarT * @tparam IdxT */ template - void Ida::copyVec(const N_Vector x, std::vector& y) + void Ida::copyVec(const N_Vector x, VectorT& y) { const auto xsize = static_cast(N_VGetLength(x)); - if (xsize != y.size()) + const auto ysize = static_cast(y.getSize()); + if (xsize != ysize) { - std::cerr << "\nN_Vector size (" << xsize << ") does not match std::vector size (" - << y.size() << ").\n\n"; + std::cerr << "\nN_Vector size (" << xsize << ") does not match vector size (" + << y.getSize() << ").\n\n"; throw SundialsException(); } const ScalarT* xdata = N_VGetArrayPointer(x); - std::copy_n(xdata, y.size(), y.begin()); + std::copy_n(xdata, ysize, y.getData()); } /** - * @brief Copy std::vector to SUNDIALS N_Vector + * @brief Copy Vector to SUNDIALS N_Vector * * @tparam ScalarT * @tparam IdxT */ template - void Ida::copyVec(const std::vector& x, N_Vector y) + void Ida::copyVec(const VectorT& x, N_Vector y) { const auto ysize = static_cast(N_VGetLength(y)); - if (x.size() != ysize) + const auto xsize = static_cast(x.getSize()); + if (xsize != ysize) { - std::cerr << "\nstd::vector size (" << x.size() << ") does not match N_Vector size (" + std::cerr << "\nvector size (" << x.getSize() << ") does not match N_Vector size (" << ysize << ").\n\n"; throw SundialsException(); } ScalarT* ydata = N_VGetArrayPointer(y); - std::copy(x.cbegin(), x.cend(), ydata); - } - - /** - * @brief Copy std::vector to SUNDIALS N_Vector - * - * @tparam ScalarT - * @tparam IdxT - */ - template - void Ida::copyVec(const std::vector& x, N_Vector y) - { - const auto ysize = static_cast(N_VGetLength(y)); - if (x.size() != ysize) - { - std::cerr << "\nstd::vector size (" << x.size() << ") does not match N_Vector size (" - << ysize << ").\n\n"; - throw SundialsException(); - } - - ScalarT* ydata = N_VGetArrayPointer(y); - std::copy(x.cbegin(), x.cend(), ydata); + std::copy_n(x.getData(), xsize, ydata); } /** diff --git a/GridKit/Solver/Dynamic/Ida.hpp b/GridKit/Solver/Dynamic/Ida.hpp index 1cdcd1269..fe421577f 100644 --- a/GridKit/Solver/Dynamic/Ida.hpp +++ b/GridKit/Solver/Dynamic/Ida.hpp @@ -45,7 +45,8 @@ namespace AnalysisManager { using DynamicSolver::model_; - using RealT = typename GridKit::ScalarTraits::RealT; + using RealT = typename GridKit::ScalarTraits::RealT; + using VectorT = typename GridKit::Model::Evaluator::VectorT; public: Ida(GridKit::Model::Evaluator* model); @@ -235,9 +236,8 @@ namespace AnalysisManager private: // static void copyMat(Model::Evaluator::Mat& J, SlsMat Jida); - static void copyVec(const N_Vector x, std::vector& y); - static void copyVec(const std::vector& x, N_Vector y); - static void copyVec(const std::vector& x, N_Vector y); + static void copyVec(const N_Vector x, VectorT& y); + static void copyVec(const VectorT& x, N_Vector y); // int check_flag(void *flagvalue, const char *funcname, int opt); static void checkAllocation(void* v, const char* functionName); diff --git a/GridKit/Solver/Optimization/DynamicConstraint.cpp b/GridKit/Solver/Optimization/DynamicConstraint.cpp index 291dbd285..3d703aa26 100644 --- a/GridKit/Solver/Optimization/DynamicConstraint.cpp +++ b/GridKit/Solver/Optimization/DynamicConstraint.cpp @@ -62,10 +62,12 @@ namespace AnalysisManager assert(m == 1); // Get boundaries for the optimization parameters + auto* param_lo = model_->param_lo().getData(); + auto* param_up = model_->param_up().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) { - x_l[i] = model_->param_lo()[static_cast(i)]; - x_u[i] = model_->param_up()[static_cast(i)]; + x_l[i] = param_lo[static_cast(i)]; + x_u[i] = param_up[static_cast(i)]; } // No boundaries for fictitious parameter x[n] @@ -96,8 +98,9 @@ namespace AnalysisManager assert(init_lambda == false); // Initialize optimization parameters x + auto* param = model_->param().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) - x[i] = model_->param()[static_cast(i)]; + x[i] = param[static_cast(i)]; // Initialize fictitious parameter x[n-1] to zero x[model_->sizeParams()] = 0.0; @@ -140,9 +143,10 @@ namespace AnalysisManager Number* g) { // Update optimization parameters + auto* param = model_->param().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) { - model_->param()[static_cast(i)] = x[i]; + param[static_cast(i)] = x[i]; // std::cout << "x[" << i << "] = " << x[i] << "\n"; } @@ -190,8 +194,9 @@ namespace AnalysisManager else { // Update optimization parameters + auto* param = model_->param().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) - model_->param()[static_cast(i)] = x[i]; + param[static_cast(i)] = x[i]; // evaluate the gradient of the objective function grad_{x} f(x) // This is creating and deleting adjoint system for each iteration! diff --git a/GridKit/Solver/Optimization/DynamicObjective.cpp b/GridKit/Solver/Optimization/DynamicObjective.cpp index 8a90efbfc..6fa80085e 100644 --- a/GridKit/Solver/Optimization/DynamicObjective.cpp +++ b/GridKit/Solver/Optimization/DynamicObjective.cpp @@ -61,10 +61,12 @@ namespace AnalysisManager assert(m == 0); // Get boundaries for the optimization parameters + auto* param_lo = model_->param_lo().getData(); + auto* param_up = model_->param_up().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) { - x_l[i] = model_->param_lo()[static_cast(i)]; - x_u[i] = model_->param_up()[static_cast(i)]; + x_l[i] = param_lo[static_cast(i)]; + x_u[i] = param_up[static_cast(i)]; } return true; @@ -87,8 +89,9 @@ namespace AnalysisManager assert(init_lambda == false); // Initialize optimization parameters x + auto* param = model_->param().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) - x[i] = model_->param()[static_cast(i)]; + x[i] = param[static_cast(i)]; return true; } @@ -100,8 +103,9 @@ namespace AnalysisManager Number& obj_value) { // Update optimization parameters + auto* param = model_->param().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) - model_->param()[static_cast(i)] = x[i]; + param[static_cast(i)] = x[i]; // Evaluate objective function integrator_->getSavedInitialCondition(); @@ -123,8 +127,9 @@ namespace AnalysisManager { assert(model_->sizeParams() == static_cast(n)); // Update optimization parameters + auto* param = model_->param().getData(); for (IdxT i = 0; i < model_->sizeParams(); ++i) - model_->param()[static_cast(i)] = x[i]; + param[static_cast(i)] = x[i]; // evaluate the gradient of the objective function grad_{x} f(x) // This is creating and deleting adjoint system for each iteration! diff --git a/GridKit/Solver/SteadyState/CMakeLists.txt b/GridKit/Solver/SteadyState/CMakeLists.txt index c51d1be5b..2fe0f154c 100644 --- a/GridKit/Solver/SteadyState/CMakeLists.txt +++ b/GridKit/Solver/SteadyState/CMakeLists.txt @@ -9,4 +9,8 @@ gridkit_add_library( solvers_steady SOURCES Kinsol.cpp HEADERS Kinsol.hpp SteadyStateSolver.hpp - LINK_LIBRARIES PUBLIC SUNDIALS::kinsol) + LINK_LIBRARIES + PUBLIC + SUNDIALS::kinsol + PUBLIC + GridKit::dense_vector) diff --git a/GridKit/Solver/SteadyState/Kinsol.cpp b/GridKit/Solver/SteadyState/Kinsol.cpp index aa04fe4e6..4da2d1481 100644 --- a/GridKit/Solver/SteadyState/Kinsol.cpp +++ b/GridKit/Solver/SteadyState/Kinsol.cpp @@ -139,24 +139,23 @@ namespace AnalysisManager copyVec(yy, model->y()); model->evaluateResidual(); - const std::vector& f = model->getResidual(); - copyVec(f, rr); + copyVec(model->getResidual(), rr); return 0; } template - void Kinsol::copyVec(const N_Vector x, std::vector& y) + void Kinsol::copyVec(const N_Vector x, VectorT& y) { const ScalarT* xdata = N_VGetArrayPointer(x); - std::copy_n(xdata, y.size(), y.begin()); + std::copy_n(xdata, static_cast(y.getSize()), y.getData()); } template - void Kinsol::copyVec(const std::vector& x, N_Vector y) + void Kinsol::copyVec(const VectorT& x, N_Vector y) { ScalarT* ydata = N_VGetArrayPointer(y); - std::copy_n(x.cbegin(), x.size(), ydata); + std::copy_n(x.getData(), static_cast(x.getSize()), ydata); } template diff --git a/GridKit/Solver/SteadyState/Kinsol.hpp b/GridKit/Solver/SteadyState/Kinsol.hpp index 89fc6c720..b867d936e 100644 --- a/GridKit/Solver/SteadyState/Kinsol.hpp +++ b/GridKit/Solver/SteadyState/Kinsol.hpp @@ -29,7 +29,8 @@ namespace AnalysisManager { using SteadyStateSolver::model_; - using RealT = typename GridKit::ScalarTraits::RealT; + using RealT = typename GridKit::ScalarTraits::RealT; + using VectorT = typename GridKit::Model::Evaluator::VectorT; static_assert(std::is_same_v, "RealT must be the same type as sunrealtype"); @@ -140,9 +141,8 @@ namespace AnalysisManager private: // static void copyMat(Model::Evaluator::Mat& J, SlsMat Jida); - static void copyVec(const N_Vector x, std::vector& y); - static void copyVec(const std::vector& x, N_Vector y); - static void copyVec(const std::vector& x, N_Vector y); + static void copyVec(const N_Vector x, VectorT& y); + static void copyVec(const VectorT& x, N_Vector y); // int check_flag(void *flagvalue, const char *funcname, int opt); static inline void checkAllocation(void* v, const char* functionName); diff --git a/examples/Enzyme/PowerElectronics/main.cpp b/examples/Enzyme/PowerElectronics/main.cpp index 351378d51..e0d94da2d 100644 --- a/examples/Enzyme/PowerElectronics/main.cpp +++ b/examples/Enzyme/PowerElectronics/main.cpp @@ -189,8 +189,8 @@ int main() for (size_t i = 0; i < dg->getExternSize(); i++) { - y[i] = dg->y()[i]; - res[i] = dg->getResidual()[i]; + y[i] = dg->y().getData()[i]; + res[i] = dg->getResidual().getData()[i]; } DenseMatrix jac_ref_dense(dg->size(), dg->size()); diff --git a/examples/Experimental/AdjointSensitivity/AdjointSensitivity.cpp b/examples/Experimental/AdjointSensitivity/AdjointSensitivity.cpp index 1d67cf0ec..df8bc4ceb 100644 --- a/examples/Experimental/AdjointSensitivity/AdjointSensitivity.cpp +++ b/examples/Experimental/AdjointSensitivity/AdjointSensitivity.cpp @@ -83,10 +83,11 @@ int main() // Compute gradient of the objective function numerically std::vector dGdp(model->sizeParams()); + auto* param = model->param().getData(); for (unsigned i = 0; i < model->sizeParams(); ++i) { - model->param()[i] += eps; + param[i] += eps; idas->getSavedInitialCondition(); idas->initializeSimulation(t_init); idas->initializeQuadrature(); @@ -98,7 +99,7 @@ int main() double g2 = Q[0]; // restore parameter to original value - model->param()[i] -= eps; + param[i] -= eps; // Evaluate dG/dp numerically dGdp[i] = (g2 - g1) / eps; diff --git a/examples/Experimental/DynamicConstrainedOpt/DynamicConstrainedOpt.cpp b/examples/Experimental/DynamicConstrainedOpt/DynamicConstrainedOpt.cpp index f80bb994b..2efd1a4c4 100644 --- a/examples/Experimental/DynamicConstrainedOpt/DynamicConstrainedOpt.cpp +++ b/examples/Experimental/DynamicConstrainedOpt/DynamicConstrainedOpt.cpp @@ -94,8 +94,10 @@ int main() Ipopt::SmartPtr ipoptDynamicObjectiveInterface = new IpoptInterface::DynamicObjective(&idas); + auto* param = model.param().getData(); + // Initialize problem - model.param()[0] = Pm; + param[0] = Pm; // Solve the problem status = ipoptApp->OptimizeTNLP(ipoptDynamicObjectiveInterface); @@ -106,7 +108,7 @@ int main() // Print result std::cout << "\nSucess:\n The problem solved in " << ipoptApp->Statistics()->IterationCount() << " iterations!\n" - << " Optimal value of Pm = " << model.param()[0] << "\n" + << " Optimal value of Pm = " << param[0] << "\n" << " The final value of the objective function G(Pm) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } @@ -115,7 +117,7 @@ int main() double* results = new double[model.sizeParams()]; for (unsigned i = 0; i < model.sizeParams(); ++i) { - results[i] = model.param()[i]; + results[i] = param[i]; } // Create dynamic constraint interface to Ipopt solver @@ -123,7 +125,7 @@ int main() new IpoptInterface::DynamicConstraint(&idas); // Initialize problem - model.param()[0] = Pm; + param[0] = Pm; // Solve the problem status = ipoptApp->OptimizeTNLP(ipoptDynamicConstraintInterface); @@ -134,7 +136,7 @@ int main() // Print result std::cout << "\nSucess:\n The problem solved in " << ipoptApp->Statistics()->IterationCount() << " iterations!\n" - << " Optimal value of Pm = " << model.param()[0] << "\n" + << " Optimal value of Pm = " << param[0] << "\n" << " The final value of the objective function G(Pm) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } @@ -143,7 +145,7 @@ int main() int retval = 0; for (unsigned i = 0; i < model.sizeParams(); ++i) { - if (!isEqual(results[i], model.param()[i], 10 * tol)) + if (!isEqual(results[i], param[i], 10 * tol)) --retval; } diff --git a/examples/Experimental/GenConstLoad/GenConstLoad.cpp b/examples/Experimental/GenConstLoad/GenConstLoad.cpp index 9446ce5bb..c96307fa5 100644 --- a/examples/Experimental/GenConstLoad/GenConstLoad.cpp +++ b/examples/Experimental/GenConstLoad/GenConstLoad.cpp @@ -88,9 +88,11 @@ int main() Ipopt::SmartPtr ipoptDynamicObjectiveInterface = new IpoptInterface::DynamicObjective(idas); + auto* param = model->param().getData(); + // Initialize problem - model->param()[0] = T2; - model->param()[1] = K; + param[0] = T2; + param[1] = K; // Solve the problem status = ipoptApp->OptimizeTNLP(ipoptDynamicObjectiveInterface); @@ -102,9 +104,9 @@ int main() << ipoptApp->Statistics()->IterationCount() << " iterations!\n"; std::cout << "Optimal value: T2 = " - << model->param()[0] + << param[0] << ", K = " - << model->param()[1] << "\n"; + << param[1] << "\n"; std::cout << "The final value of the objective function G(T2,K) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } diff --git a/examples/Experimental/GenInfiniteBus/GenInfiniteBus.cpp b/examples/Experimental/GenInfiniteBus/GenInfiniteBus.cpp index d196348fd..dfa8ac89c 100644 --- a/examples/Experimental/GenInfiniteBus/GenInfiniteBus.cpp +++ b/examples/Experimental/GenInfiniteBus/GenInfiniteBus.cpp @@ -100,9 +100,11 @@ int main() Ipopt::SmartPtr ipoptDynamicObjectiveInterface = new IpoptInterface::DynamicObjective(&idas); + auto* param = model.param().getData(); + // Initialize the problem - model.param()[0] = Pm; - model.param()[1] = Ef; + param[0] = Pm; + param[1] = Ef; // Solve the problem status = ipoptApp->OptimizeTNLP(ipoptDynamicObjectiveInterface); @@ -113,8 +115,8 @@ int main() // Print result std::cout << "\nSucess:\n The problem solved in " << ipoptApp->Statistics()->IterationCount() << " iterations!\n" - << " Optimal value of Pm = " << model.param()[0] << "\n" - << " Optimal value of Ef = " << model.param()[1] << "\n" + << " Optimal value of Pm = " << param[0] << "\n" + << " Optimal value of Ef = " << param[1] << "\n" << " The final value of the objective function G(Pm,Ef) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } @@ -127,12 +129,12 @@ int main() double* results = new double[model.sizeParams()]; for (unsigned i = 0; i < model.sizeParams(); ++i) { - results[i] = model.param()[i]; + results[i] = param[i]; } // Initialize the problem - model.param()[0] = Pm; - model.param()[1] = Ef; + param[0] = Pm; + param[1] = Ef; // Solve the problem status = ipoptApp->OptimizeTNLP(ipoptDynamicConstraintInterface); @@ -143,8 +145,8 @@ int main() // Print result std::cout << "\nSucess:\n The problem solved in " << ipoptApp->Statistics()->IterationCount() << " iterations!\n" - << " Optimal value of Pm = " << model.param()[0] << "\n" - << " Optimal value of Ef = " << model.param()[1] << "\n" + << " Optimal value of Pm = " << param[0] << "\n" + << " Optimal value of Ef = " << param[1] << "\n" << " The final value of the objective function G(Pm,Ef) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } @@ -153,7 +155,7 @@ int main() int retval = 0; for (unsigned i = 0; i < model.sizeParams(); ++i) { - if (!isEqual(results[i], model.param()[i], 100 * tol)) + if (!isEqual(results[i], param[i], 100 * tol)) --retval; } diff --git a/examples/Experimental/ParameterEstimation/ParameterEstimation.cpp b/examples/Experimental/ParameterEstimation/ParameterEstimation.cpp index 7d286f0ed..a62eac32f 100644 --- a/examples/Experimental/ParameterEstimation/ParameterEstimation.cpp +++ b/examples/Experimental/ParameterEstimation/ParameterEstimation.cpp @@ -82,8 +82,10 @@ int main() // Set integration time for dynamic constrained optimization idas.setIntegrationTime(t_init, t_final, 100); + auto* param = model.param().getData(); + // Guess value of inertia coefficient - model.param()[0] = 3.0; + param[0] = 3.0; // Create an instance of the IpoptApplication Ipopt::SmartPtr ipoptApp = IpoptApplicationFactory(); @@ -115,7 +117,7 @@ int main() // Print result std::cout << "\nSucess:\n The problem solved in " << ipoptApp->Statistics()->IterationCount() << " iterations!\n" - << " Optimal value of H = " << model.param()[0] << "\n" + << " Optimal value of H = " << param[0] << "\n" << " The final value of the objective function G(H) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } @@ -124,11 +126,11 @@ int main() double* results = new double[model.sizeParams()]; for (unsigned i = 0; i < model.sizeParams(); ++i) { - results[i] = model.param()[i]; + results[i] = param[i]; } // Guess value of inertia coefficient - model.param()[0] = 3.0; + param[0] = 3.0; // Create dynamic constraint interface to Ipopt solver Ipopt::SmartPtr ipoptDynamicConstraintInterface = @@ -143,7 +145,7 @@ int main() // Print result std::cout << "\nSucess:\n The problem solved in " << ipoptApp->Statistics()->IterationCount() << " iterations!\n" - << " Optimal value of H = " << model.param()[0] << "\n" + << " Optimal value of H = " << param[0] << "\n" << " The final value of the objective function G(H) = " << ipoptApp->Statistics()->FinalObjective() << "\n\n"; } @@ -152,7 +154,7 @@ int main() int retval = 0; for (unsigned i = 0; i < model.sizeParams(); ++i) { - if (!isEqual(results[i], model.param()[i], 100 * tol)) + if (!isEqual(results[i], param[i], 100 * tol)) --retval; } diff --git a/examples/PhasorDynamics/Small/TenGen/Classical/TenGenClassical.cpp b/examples/PhasorDynamics/Small/TenGen/Classical/TenGenClassical.cpp index 485cfd682..2bf8796e2 100644 --- a/examples/PhasorDynamics/Small/TenGen/Classical/TenGenClassical.cpp +++ b/examples/PhasorDynamics/Small/TenGen/Classical/TenGenClassical.cpp @@ -123,7 +123,7 @@ int main() auto output_cb = [&](real_type t) { - std::vector& yval = sys.y(); + auto* yval = sys.y().getData(); // Output time out << t << ","; diff --git a/examples/PhasorDynamics/Small/TenGen/Genrou/TenGenGenrou.cpp b/examples/PhasorDynamics/Small/TenGen/Genrou/TenGenGenrou.cpp index 658557d6c..815938e97 100644 --- a/examples/PhasorDynamics/Small/TenGen/Genrou/TenGenGenrou.cpp +++ b/examples/PhasorDynamics/Small/TenGen/Genrou/TenGenGenrou.cpp @@ -118,7 +118,7 @@ int main() auto output_cb = [&](real_type t) { - std::vector& yval = sys.y(); + auto* yval = sys.y().getData(); // Output time out << t << ","; diff --git a/examples/PhasorDynamics/Tiny/ThreeBus/Basic/ThreeBusBasic.cpp b/examples/PhasorDynamics/Tiny/ThreeBus/Basic/ThreeBusBasic.cpp index 1c3a3bd66..80a070511 100644 --- a/examples/PhasorDynamics/Tiny/ThreeBus/Basic/ThreeBusBasic.cpp +++ b/examples/PhasorDynamics/Tiny/ThreeBus/Basic/ThreeBusBasic.cpp @@ -210,7 +210,7 @@ int main() auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); // Bus 1 -> +2 // Bus 2 -> +2 diff --git a/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassical.cpp b/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassical.cpp index c1906acb1..9b047459a 100644 --- a/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassical.cpp +++ b/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassical.cpp @@ -187,7 +187,7 @@ int main() auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, 1 + static_cast(y_val[7]), diff --git a/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassicalJson.cpp b/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassicalJson.cpp index 4892d1b1b..e70668184 100644 --- a/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassicalJson.cpp +++ b/examples/PhasorDynamics/Tiny/ThreeBus/Classical/ThreeBusClassicalJson.cpp @@ -134,7 +134,7 @@ int main(int argc, const char* argv[]) auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, 1 + static_cast(y_val[7]), diff --git a/examples/PhasorDynamics/Tiny/ThreeBus/ZipLoad/ThreeBusZipLoadJson.cpp b/examples/PhasorDynamics/Tiny/ThreeBus/ZipLoad/ThreeBusZipLoadJson.cpp index 3caf9d8bf..c213a3ec4 100644 --- a/examples/PhasorDynamics/Tiny/ThreeBus/ZipLoad/ThreeBusZipLoadJson.cpp +++ b/examples/PhasorDynamics/Tiny/ThreeBus/ZipLoad/ThreeBusZipLoadJson.cpp @@ -132,7 +132,7 @@ int main(int argc, const char* argv[]) auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, 1 + static_cast(y_val[7]), diff --git a/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasic.cpp b/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasic.cpp index 92fcc4227..a5f45b0ee 100644 --- a/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasic.cpp +++ b/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasic.cpp @@ -133,7 +133,7 @@ int main() // push it into output, which is updated outside the callback. auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, static_cast(y_val[0]), diff --git a/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasicJson.cpp b/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasicJson.cpp index 1efb9ba3f..b5667b292 100644 --- a/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasicJson.cpp +++ b/examples/PhasorDynamics/Tiny/TwoBus/Basic/TwoBusBasicJson.cpp @@ -113,7 +113,7 @@ int main(int argc, const char* argv[]) // push it into output, which is updated outside the callback. auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, static_cast(y_val[0]), diff --git a/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1.cpp b/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1.cpp index 65c946364..1d38c44a8 100644 --- a/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1.cpp +++ b/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1.cpp @@ -182,7 +182,7 @@ int main() // push it into output, which is updated outside the callback. auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); // Note Omega of gen is at state index 5! (Each added signal shifted by 1) // Bus -> 2 States diff --git a/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1Json.cpp b/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1Json.cpp index 692e9431a..b18130a90 100644 --- a/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1Json.cpp +++ b/examples/PhasorDynamics/Tiny/TwoBus/Ieeet1/TwoBusIeeet1Json.cpp @@ -113,7 +113,7 @@ int main(int argc, const char* argv[]) // push it into output, which is updated outside the callback. auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); // Note Omega of gen is at state index 5! (Each added signal shifted by 1) // Bus -> 2 States diff --git a/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1.cpp b/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1.cpp index e6291e694..f38d90cb9 100644 --- a/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1.cpp +++ b/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1.cpp @@ -156,7 +156,7 @@ int main() // push it into output, which is updated outside the callback. auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, static_cast(y_val[0]), diff --git a/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1Json.cpp b/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1Json.cpp index 55d2ebd14..b601af47a 100644 --- a/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1Json.cpp +++ b/examples/PhasorDynamics/Tiny/TwoBus/Tgov1/TwoBusTgov1Json.cpp @@ -117,7 +117,7 @@ int main(int argc, const char* argv[]) // push it into output, which is updated outside the callback. auto output_cb = [&](real_type t) { - std::vector& y_val = sys.y(); + auto* y_val = sys.y().getData(); output.push_back(OutputData{t, static_cast(y_val[0]), diff --git a/examples/PowerElectronics/DistributedGeneratorTest/DGTest.cpp b/examples/PowerElectronics/DistributedGeneratorTest/DGTest.cpp index 15709c95f..b1e94ec0c 100644 --- a/examples/PowerElectronics/DistributedGeneratorTest/DGTest.cpp +++ b/examples/PowerElectronics/DistributedGeneratorTest/DGTest.cpp @@ -2,6 +2,7 @@ #define _USE_MATH_DEFINES #include +#include #include #include #include @@ -73,12 +74,13 @@ int main(int /* argc */, char const** /* argv */) bus.allocate(); dg.allocate(); - dg.y() = t2; - dg.yp() = t1; - dg.getResidual() = res; + std::copy(t2.begin(), t2.end(), dg.y().getData()); + std::copy(t1.begin(), t1.end(), dg.yp().getData()); + std::copy(res.begin(), res.end(), dg.getResidual().getData()); + auto* dg_res = dg.getResidual().getData(); dg.setInternalPointer(&t2[dg.getExternSize()]); dg.setInternalDerivativePointer(&t1[dg.getExternSize()]); - dg.setInternalResidualPointer(&dg.getResidual()[dg.getExternSize()]); + dg.setInternalResidualPointer(&dg_res[dg.getExternSize()]); dg.evaluateResidual(); @@ -103,7 +105,7 @@ int main(int /* argc */, char const** /* argv */) double error_allowed = 10 * std::numeric_limits::epsilon(); for (size_t i = 0; i < true_vec.size(); i++) { - double error = std::abs(true_vec[i] - dg.getResidual()[i]) / std::abs(1.0 + true_vec[i]); + double error = std::abs(true_vec[i] - dg_res[i]) / std::abs(1.0 + true_vec[i]); if (error > error_allowed) { std::cout << "Model error for equation " << i << " is: " << error << "\n"; diff --git a/examples/PowerElectronics/Microgrid/Microgrid.cpp b/examples/PowerElectronics/Microgrid/Microgrid.cpp index 035a8df0f..1beadfff0 100644 --- a/examples/PowerElectronics/Microgrid/Microgrid.cpp +++ b/examples/PowerElectronics/Microgrid/Microgrid.cpp @@ -162,32 +162,35 @@ int main(int /* argc */, char const** /* argv */) sysmodel->allocate(); - std::cout << sysmodel->y().size() << std::endl; + std::cout << sysmodel->y().getSize() << std::endl; + + auto* y = sysmodel->y().getData(); + auto* yp = sysmodel->yp().getData(); // Create initial points for states for (size_t i = 0; i < sysmodel->size(); i++) { - sysmodel->y()[i] = 0.0; - sysmodel->yp()[i] = 0.0; + y[i] = 0.0; + yp[i] = 0.0; } // Create initial derivatives specifics generated in MATLAB // DGs 1 - sysmodel->yp()[2] = parms1.Vn_; - sysmodel->yp()[4] = parms1.Kpv_ * parms1.Vn_; - sysmodel->yp()[6] = (parms1.Kpc_ * parms1.Kpv_ * parms1.Vn_) / parms1.Lf_; - sysmodel->yp()[12 + 2] = parms1.Vn_; - sysmodel->yp()[12 + 4] = parms1.Kpv_ * parms1.Vn_; - sysmodel->yp()[12 + 6] = (parms1.Kpc_ * parms1.Kpv_ * parms1.Vn_) / parms1.Lf_; + yp[2] = parms1.Vn_; + yp[4] = parms1.Kpv_ * parms1.Vn_; + yp[6] = (parms1.Kpc_ * parms1.Kpv_ * parms1.Vn_) / parms1.Lf_; + yp[12 + 2] = parms1.Vn_; + yp[12 + 4] = parms1.Kpv_ * parms1.Vn_; + yp[12 + 6] = (parms1.Kpc_ * parms1.Kpv_ * parms1.Vn_) / parms1.Lf_; for (size_t i = 2; i < 4; i++) { - sysmodel->yp()[13 * i - 1 + 2] = parms2.Vn_; - sysmodel->yp()[13 * i - 1 + 4] = parms2.Kpv_ * parms2.Vn_; - sysmodel->yp()[13 * i - 1 + 6] = (parms2.Kpc_ * parms2.Kpv_ * parms2.Vn_) / parms2.Lf_; + yp[13 * i - 1 + 2] = parms2.Vn_; + yp[13 * i - 1 + 4] = parms2.Kpv_ * parms2.Vn_; + yp[13 * i - 1 + 6] = (parms2.Kpc_ * parms2.Kpv_ * parms2.Vn_) / parms2.Lf_; } // since the intial P_com = 0 - sysmodel->y()[dg_signal.getNodeConnection(0)] = parms1.wb_; + y[dg_signal.getNodeConnection(0)] = parms1.wb_; sysmodel->initialize(); sysmodel->evaluateResidual(); @@ -195,11 +198,12 @@ int main(int /* argc */, char const** /* argv */) // Optional debuging output if (debug_output) { - std::vector& fres = sysmodel->getResidual(); + auto& fres = sysmodel->getResidual(); + auto* fres_data = fres.getData(); std::cout << "Verify initial resisdual is zero: {\n"; - for (size_t i = 0; i < fres.size(); i++) + for (size_t i = 0; i < fres.getSize(); i++) { - std::cout << i << " :" << fres[i] << "\n"; + std::cout << i << " :" << fres_data[i] << "\n"; } std::cout << "}\n"; } @@ -229,15 +233,16 @@ int main(int /* argc */, char const** /* argv */) idas->runSimulation(t_final); - std::vector& yfinial = sysmodel->y(); + auto& yfinial = sysmodel->y(); + auto* yfinial_data = yfinial.getData(); // Optional debugging output if (debug_output) { std::cout << "Final vector y\n"; - for (size_t i = 0; i < yfinial.size(); i++) + for (size_t i = 0; i < yfinial.getSize(); i++) { - std::cout << yfinial[i] << "\n"; + std::cout << yfinial_data[i] << "\n"; } } @@ -319,7 +324,7 @@ int main(int /* argc */, char const** /* argv */) double max_error = 0.0; for (size_t i = 0; i < true_vec.size(); i++) { - double error = std::abs(true_vec[i] - yfinial[i]) / std::abs(1.0 + true_vec[i]); + double error = std::abs(true_vec[i] - yfinial_data[i]) / std::abs(1.0 + true_vec[i]); if (error > max_error) max_error = error; if (error > error_allowed) diff --git a/examples/PowerElectronics/RLCircuit/RLCircuit.cpp b/examples/PowerElectronics/RLCircuit/RLCircuit.cpp index f6ada5c01..51be38662 100644 --- a/examples/PowerElectronics/RLCircuit/RLCircuit.cpp +++ b/examples/PowerElectronics/RLCircuit/RLCircuit.cpp @@ -60,28 +60,32 @@ int main(int /* argc */, char const** /* argv */) sysmodel.allocate(); - std::cout << sysmodel.y().size() << std::endl; + std::cout << sysmodel.y().getSize() << std::endl; + + auto* y = sysmodel.y().getData(); + auto* yp = sysmodel.yp().getData(); // Grounding for IDA. If no grounding then circuit is \mu > 1 // v_0 (grounded) // Create initial points - sysmodel.y()[0] = 0.0; // i_L - sysmodel.y()[1] = 0.0; // i_s - sysmodel.y()[2] = vinit; // v_1 - sysmodel.y()[3] = vinit; // v_2 + y[0] = 0.0; // i_L + y[1] = 0.0; // i_s + y[2] = vinit; // v_1 + y[3] = vinit; // v_2 - sysmodel.yp()[0] = -vinit / linit; // i'_s - sysmodel.yp()[1] = -vinit / linit; // i'_L - sysmodel.yp()[2] = 0.0; // v'_1 - sysmodel.yp()[3] = 0.0; // v'_2 + yp[0] = -vinit / linit; // i'_s + yp[1] = -vinit / linit; // i'_L + yp[2] = 0.0; // v'_1 + yp[3] = 0.0; // v'_2 sysmodel.initialize(); sysmodel.evaluateResidual(); std::cout << "Verify initial resisdual is zero: {"; - for (double i : sysmodel.getResidual()) + auto& residual = sysmodel.getResidual(); + for (std::size_t i = 0; i < residual.getSize(); ++i) { - std::cout << i << ", "; + std::cout << residual.getData()[i] << ", "; } std::cout << "}\n"; @@ -104,12 +108,13 @@ int main(int /* argc */, char const** /* argv */) idas.runSimulation(t_final); - std::vector& yfinial = sysmodel.y(); + auto& yfinial = sysmodel.y(); + auto* yfinial_data = yfinial.getData(); std::cout << "Final vector y\n"; - for (size_t i = 0; i < yfinial.size(); i++) + for (size_t i = 0; i < yfinial.getSize(); i++) { - std::cout << yfinial[i] << "\n"; + std::cout << yfinial_data[i] << "\n"; } std::vector yexact(4); @@ -121,9 +126,9 @@ int main(int /* argc */, char const** /* argv */) yexact[3] = vinit + rinit * yexact[0]; std::cout << "Element-wise relative error at t=" << t_final << "\n"; - for (size_t i = 0; i < yfinial.size(); i++) + for (size_t i = 0; i < yfinial.getSize(); i++) { - std::cout << abs((yfinial[i] - yexact[i]) / yexact[i]) << "\n"; + std::cout << abs((yfinial_data[i] - yexact[i]) / yexact[i]) << "\n"; } std::cerr << idas.getStats().report() << '\n'; diff --git a/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogrid.cpp b/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogrid.cpp index a8f0aaae2..11e127806 100644 --- a/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogrid.cpp +++ b/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogrid.cpp @@ -235,36 +235,40 @@ int test(index_type Nsize, real_type error_tol, bool debug_output) if (debug_output) { - std::cout << sys_model->y().size() << std::endl; + std::cout << sys_model->y().getSize() << std::endl; } + auto* y = sys_model->y().getData(); + auto* yp = sys_model->yp().getData(); + // Create initial points for states. Every state is to specified to the zero intially for (index_type i = 0; i < sys_model->size(); i++) { - sys_model->y()[i] = 0.0; - sys_model->yp()[i] = 0.0; + y[i] = 0.0; + yp[i] = 0.0; } // Create initial derivatives specifics generated in MATLAB for (index_type i = 0; i < 2 * Nsize; i++) { - sys_model->yp()[13 * i - 1 + 2] = DGParams_list[i].Vn_; - sys_model->yp()[13 * i - 1 + 4] = DGParams_list[i].Kpv_ * DGParams_list[i].Vn_; - sys_model->yp()[13 * i - 1 + 6] = (DGParams_list[i].Kpc_ * DGParams_list[i].Kpv_ * DGParams_list[i].Vn_) / DGParams_list[i].Lf_; + yp[13 * i - 1 + 2] = DGParams_list[i].Vn_; + yp[13 * i - 1 + 4] = DGParams_list[i].Kpv_ * DGParams_list[i].Vn_; + yp[13 * i - 1 + 6] = (DGParams_list[i].Kpc_ * DGParams_list[i].Kpv_ * DGParams_list[i].Vn_) / DGParams_list[i].Lf_; } // since the intial P_com = 0, the set the intial vector to the reference frame - sys_model->y()[dg_signal.getNodeConnection(0)] = DG_parms1.wb_; + y[dg_signal.getNodeConnection(0)] = DG_parms1.wb_; sys_model->initialize(); sys_model->evaluateResidual(); - std::vector& fres = sys_model->getResidual(); + auto& fres = sys_model->getResidual(); + auto* fres_data = fres.getData(); if (debug_output) { std::cout << "Verify initial resisdual is zero: {\n"; - for (index_type i = 0; i < fres.size(); i++) + for (index_type i = 0; i < fres.getSize(); i++) { - std::cout << i << " : " << fres[i] << "\n"; + std::cout << i << " : " << fres_data[i] << "\n"; } std::cout << "}\n"; } @@ -290,14 +294,15 @@ int test(index_type Nsize, real_type error_tol, bool debug_output) idas->runSimulation(t_final); - std::vector& yfinal = sys_model->y(); + auto& yfinal = sys_model->y(); + auto* yfinal_data = yfinal.getData(); if (debug_output) { std::cout << "Final Vector y\n"; - for (index_type i = 0; i < yfinal.size(); i++) + for (index_type i = 0; i < yfinal.getSize(); i++) { - std::cout << i << " : " << yfinal[i] << "\n"; + std::cout << i << " : " << yfinal_data[i] << "\n"; } } @@ -312,9 +317,9 @@ int test(index_type Nsize, real_type error_tol, bool debug_output) { // Print the Elementwise Relative Error if (debug_output) - std::cout << i << " : " << abs(true_vec->at(i) - yfinal[i]) / abs(true_vec->at(i)) << "\n"; + std::cout << i << " : " << abs(true_vec->at(i) - yfinal_data[i]) / abs(true_vec->at(i)) << "\n"; - sum_top += (true_vec->at(i) - yfinal[i]) * (true_vec->at(i) - yfinal[i]); + sum_top += (true_vec->at(i) - yfinal_data[i]) * (true_vec->at(i) - yfinal_data[i]); sum_bottom += (true_vec->at(i) * true_vec->at(i)); } diff --git a/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogridArbitrary.cpp b/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogridArbitrary.cpp index ac08eb785..8f7c0f338 100644 --- a/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogridArbitrary.cpp +++ b/examples/PowerElectronics/ScaleMicrogrid/ScaleMicrogridArbitrary.cpp @@ -224,23 +224,26 @@ int printMicrogridSystems(index_type N_size) // allocate all the initial conditions sys_model.allocate(); + auto* y = sys_model.y().getData(); + auto* yp = sys_model.yp().getData(); + // Create Initial points for states. Every state is set to zero initially for (index_type i = 0; i < sys_model.size(); i++) { - sys_model.y()[i] = 0.0; - sys_model.yp()[i] = 0.0; + y[i] = 0.0; + yp[i] = 0.0; } // Create Initial derivatives specifics generated in MATLAB for (index_type i = 0; i < 2 * N_size; i++) { - sys_model.yp()[13 * i - 1 + 3] = DGParams_list[i].Vn_; - sys_model.yp()[13 * i - 1 + 5] = DGParams_list[i].Kpv_ * DGParams_list[i].Vn_; - sys_model.yp()[13 * i - 1 + 7] = (DGParams_list[i].Kpc_ * DGParams_list[i].Kpv_ * DGParams_list[i].Vn_) / DGParams_list[i].Lf_; + yp[13 * i - 1 + 3] = DGParams_list[i].Vn_; + yp[13 * i - 1 + 5] = DGParams_list[i].Kpv_ * DGParams_list[i].Vn_; + yp[13 * i - 1 + 7] = (DGParams_list[i].Kpc_ * DGParams_list[i].Kpv_ * DGParams_list[i].Vn_) / DGParams_list[i].Lf_; } // since the initial P_com = 0, set the initial vector to the reference frame - sys_model.y()[dg_signal.getNodeConnection(0)] = DG_parms1.wb_; + y[dg_signal.getNodeConnection(0)] = DG_parms1.wb_; sys_model.initialize(); sys_model.evaluateResidual(); diff --git a/tests/UnitTests/LinearAlgebra/Vector/VectorTests.hpp b/tests/UnitTests/LinearAlgebra/Vector/VectorTests.hpp index c6b48a189..145c5ce9e 100644 --- a/tests/UnitTests/LinearAlgebra/Vector/VectorTests.hpp +++ b/tests/UnitTests/LinearAlgebra/Vector/VectorTests.hpp @@ -191,7 +191,7 @@ namespace GridKit z.allocate(memory::HOST); z.copyFromExternal(y, memspace_, memory::HOST); - const ScalarT* z_data = z.getData(memory::HOST); + const ScalarT* z_data = z.getData(); if (z_data == nullptr) { @@ -378,14 +378,15 @@ namespace GridKit x.syncData(memory::HOST); } + auto* x_data = x.getData(); for (IdxT i = 0; i < x.getSize(); ++i) { // std::cout << x->getData("cpu")[i] << "\n"; - if (!isEqual(x.getData(memory::HOST)[i], answer)) + if (!isEqual(x_data[i], answer)) { std::cout << std::setprecision(16); success = false; - std::cout << "Solution vector element x[" << i << "] = " << x.getData(memory::HOST)[i] + std::cout << "Solution vector element x[" << i << "] = " << x_data[i] << ", expected: " << answer << "\n"; break; } diff --git a/tests/UnitTests/LinearAlgebra/Vector/runVectorTests.cpp b/tests/UnitTests/LinearAlgebra/Vector/runVectorTests.cpp index 53bacdb87..013fd6058 100644 --- a/tests/UnitTests/LinearAlgebra/Vector/runVectorTests.cpp +++ b/tests/UnitTests/LinearAlgebra/Vector/runVectorTests.cpp @@ -21,7 +21,6 @@ int main(int, char**) // result += test.copyToExternal(50); result += test.resize(100, 50); - result += test.setToConst(50); result += test.setToConst(50); } diff --git a/tests/UnitTests/PhasorDynamics/BusFaultTests.hpp b/tests/UnitTests/PhasorDynamics/BusFaultTests.hpp index 3e5ea1083..ca2f92ba8 100644 --- a/tests/UnitTests/PhasorDynamics/BusFaultTests.hpp +++ b/tests/UnitTests/PhasorDynamics/BusFaultTests.hpp @@ -64,14 +64,16 @@ namespace GridKit fault.allocate(); fault.initialize(); fault.evaluateResidual(); - std::vector res = fault.getResidual(); + auto& res = fault.getResidual(); + auto* res_data = res.getData(); + auto* yp = fault.yp().getData(); - for (size_t i = 0; i < res.size(); ++i) + for (size_t i = 0; i < res.getSize(); ++i) { - if (!isEqual(res[i], 0.0)) + if (!isEqual(res_data[i], 0.0)) { std::cout << "Incorrect result: " - << fault.yp()[i] << " != 0\n"; + << yp[i] << " != 0\n"; success = false; break; } @@ -123,33 +125,42 @@ namespace GridKit bus.initialize(); fault.initialize(); + auto* fault_y = fault.y().getData(); for (size_t i = 0; i < fault.size(); ++i) { - fault.y()[i].setVariableNumber(i); ///< fault independent variables + fault_y[i].setVariableNumber(i); ///< fault independent variables } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + fault.size()); // Bus independent variables + bus_y[i].setVariableNumber(i + fault.size()); // Bus independent variables } bus.evaluateResidual(); fault.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_y = fault.getResidual(); + auto& residual_y_view = fault.getResidual(); + std::vector residual_y( + residual_y_view.getData(), + residual_y_view.getData() + residual_y_view.getSize()); // Get d/dy' bus.initialize(); fault.initialize(); + auto* fault_yp = fault.yp().getData(); for (size_t i = 0; i < fault.size(); ++i) { - fault.yp()[i].setVariableNumber(i); ///< fault independent variables + fault_yp[i].setVariableNumber(i); ///< fault independent variables } bus.evaluateResidual(); fault.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_yp = fault.getResidual(); + auto& residual_yp_view = fault.getResidual(); + std::vector residual_yp( + residual_yp_view.getData(), + residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/ExciterIeeet1Tests.hpp b/tests/UnitTests/PhasorDynamics/ExciterIeeet1Tests.hpp index 294951379..91f292c38 100644 --- a/tests/UnitTests/PhasorDynamics/ExciterIeeet1Tests.hpp +++ b/tests/UnitTests/PhasorDynamics/ExciterIeeet1Tests.hpp @@ -61,12 +61,13 @@ namespace GridKit exciter.evaluateResidual(); - const auto& residual = exciter.getResidual(); - for (size_t i = 0; i < residual.size(); ++i) + const auto& residual = exciter.getResidual(); + const auto* residual_data = residual.getData(); + for (size_t i = 0; i < residual.getSize(); ++i) { - if (!isEqual(residual[i], static_cast(0.0))) + if (!isEqual(residual_data[i], static_cast(0.0))) { - std::cout << "Non-zero Ieeet1 residual at index " << i << ": " << residual[i] << "\n"; + std::cout << "Non-zero Ieeet1 residual at index " << i << ": " << residual_data[i] << "\n"; success = false; } } @@ -91,16 +92,20 @@ namespace GridKit exciter.initialize(); exciter.tagDifferentiable(); - success *= (exciter.tag()[0]); + const auto* tag = exciter.tag().getData(); + auto* y = exciter.y().getData(); + auto* yp = exciter.yp().getData(); + success *= (tag[0] != static_cast(0.0)); - exciter.yp()[0] = 123.0; + yp[0] = 123.0; exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[0], static_cast(-123.0)); + const auto* f = exciter.getResidual().getData(); + success *= isEqual(f[0], static_cast(-123.0)); - exciter.yp()[0] = 0.0; - exciter.y()[0] = 4.0; + yp[0] = 0.0; + y[0] = 4.0; exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[0], static_cast(1.0e3)); + success *= isEqual(f[0], static_cast(1.0e3)); return success.report(__func__); } @@ -147,33 +152,38 @@ namespace GridKit bus.initialize(); exciter.initialize(); + auto* exciter_y = exciter.y().getData(); for (size_t i = 0; i < exciter.size(); ++i) { - exciter.y()[i].setVariableNumber(i); ///< Exciter independent variables + exciter_y[i].setVariableNumber(i); ///< Exciter independent variables } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + exciter.size()); // Bus independent variables + bus_y[i].setVariableNumber(i + exciter.size()); // Bus independent variables } bus.evaluateResidual(); exciter.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_y = exciter.getResidual(); + auto& residual_y_view = exciter.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); // Get d/dy' bus.initialize(); exciter.initialize(); + auto* exciter_yp = exciter.yp().getData(); for (size_t i = 0; i < exciter.size(); ++i) { - exciter.yp()[i].setVariableNumber(i); ///< Exciter independent variables + exciter_yp[i].setVariableNumber(i); ///< Exciter independent variables } bus.evaluateResidual(); exciter.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_yp = exciter.getResidual(); + auto& residual_yp_view = exciter.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/ExciterSexsPtiTests.hpp b/tests/UnitTests/PhasorDynamics/ExciterSexsPtiTests.hpp index 6aa61e04a..1116bdc9b 100644 --- a/tests/UnitTests/PhasorDynamics/ExciterSexsPtiTests.hpp +++ b/tests/UnitTests/PhasorDynamics/ExciterSexsPtiTests.hpp @@ -73,19 +73,21 @@ namespace GridKit exciter.initialize(); exciter.evaluateResidual(); - success *= efd_node.linked(); - success *= (efd_node.getVariableIndex() == 1); - success *= isEqual(efd_node.read(), static_cast(1.2), kTol); - success *= isEqual(exciter.y()[0], static_cast(-0.048), kTol); - success *= isEqual(exciter.y()[1], static_cast(1.2), kTol); - success *= isEqual(exciter.y()[2], static_cast(0.12), kTol); - - const auto& f = exciter.getResidual(); - for (size_t i = 0; i < f.size(); ++i) + success *= efd_node.linked(); + success *= (efd_node.getVariableIndex() == 1); + success *= isEqual(efd_node.read(), static_cast(1.2), kTol); + const auto* y = exciter.y().getData(); + success *= isEqual(y[0], static_cast(-0.048), kTol); + success *= isEqual(y[1], static_cast(1.2), kTol); + success *= isEqual(y[2], static_cast(0.12), kTol); + + const auto& f = exciter.getResidual(); + const auto* f_data = f.getData(); + for (size_t i = 0; i < f.getSize(); ++i) { - if (!isEqual(f[i], static_cast(0.0), kTol)) + if (!isEqual(f_data[i], static_cast(0.0), kTol)) { - std::cout << "Non-zero SEXS-PTI residual at index " << i << ": " << f[i] << "\n"; + std::cout << "Non-zero SEXS-PTI residual at index " << i << ": " << f_data[i] << "\n"; success = false; } } @@ -121,7 +123,8 @@ namespace GridKit exciter.initialize(); exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[2], vs_value, kTol); + const auto* f = exciter.getResidual().getData(); + success *= isEqual(f[2], vs_value, kTol); return success.report(__func__); } @@ -138,51 +141,55 @@ namespace GridKit PhasorDynamics::Exciter::SexsPti exciter(&bus, data); exciter.allocate(); exciter.initialize(); - exciter.yp()[0] = 0.0; - exciter.yp()[1] = 0.0; + auto* y = exciter.y().getData(); + auto* yp = exciter.yp().getData(); + + yp[0] = 0.0; + yp[1] = 0.0; // Windup: Efd = 10 is far above Efdmax = 5 and the pre-limit // derivative f = +15 drives further past the limit. The indicator // saturates to 0, so residual[1] = 0 exactly. - exciter.y()[0] = -1.0; - exciter.y()[1] = 10.0; - exciter.y()[2] = 1.0; + y[0] = -1.0; + y[1] = 10.0; + y[2] = 1.0; exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[1], static_cast(0.0), kTol); + const auto* f = exciter.getResidual().getData(); + success *= isEqual(f[1], static_cast(0.0), kTol); // Release: same over-limit Efd, but f = -37.5 < 0 restores toward // the interior. The indicator saturates to 1, so residual[1] = f. - exciter.y()[0] = 1.0; - exciter.y()[1] = 10.0; - exciter.y()[2] = 0.0; + y[0] = 1.0; + y[1] = 10.0; + y[2] = 0.0; exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[1], static_cast(-37.5), kTol); + success *= isEqual(f[1], static_cast(-37.5), kTol); // Mirror (windup below Efdmin): Efd = -10 with f = -15 drives further // past the lower limit. Indicator saturates to 0, residual[1] = 0. - exciter.y()[0] = 1.0; - exciter.y()[1] = -10.0; - exciter.y()[2] = -1.0; + y[0] = 1.0; + y[1] = -10.0; + y[2] = -1.0; exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[1], static_cast(0.0), kTol); + success *= isEqual(f[1], static_cast(0.0), kTol); // Mirror (release above Efdmin): Efd = -10 with f = +37.5 pulls back // toward the interior. Indicator saturates to 1, residual[1] = f. - exciter.y()[0] = -1.0; - exciter.y()[1] = -10.0; - exciter.y()[2] = 0.0; + y[0] = -1.0; + y[1] = -10.0; + y[2] = 0.0; exciter.evaluateResidual(); - success *= isEqual(exciter.getResidual()[1], static_cast(37.5), kTol); + success *= isEqual(f[1], static_cast(37.5), kTol); // Regression guard: Efd barely above Efdmax with a small positive f. // Here the sigmoid is not fully saturated, so the residual is small // but not exactly zero; it should still be orders of magnitude below // f = 0.125 itself. - exciter.y()[0] = -0.2575; - exciter.y()[1] = 5.05; - exciter.y()[2] = 0.0; + y[0] = -0.2575; + y[1] = 5.05; + y[2] = 0.0; exciter.evaluateResidual(); - success *= (std::abs(exciter.getResidual()[1]) < static_cast(0.1)); + success *= (std::abs(f[1]) < static_cast(0.1)); return success.report(__func__); } @@ -292,9 +299,11 @@ namespace GridKit constexpr IdxT consumer_vtr_residual = 4; constexpr IdxT source_efd_variable = 6; - system.y()[source_efd_variable] = 0.75; + auto* y = system.y().getData(); + y[source_efd_variable] = 0.75; success *= (system.evaluateResidual() == 0); - success *= isEqual(system.getResidual()[consumer_vtr_residual], + const auto* f = system.getResidual().getData(); + success *= isEqual(f[consumer_vtr_residual], static_cast(0.75), kTol); @@ -343,33 +352,38 @@ namespace GridKit bus.initialize(); exciter.initialize(); + auto* exciter_y = exciter.y().getData(); for (size_t i = 0; i < exciter.size(); ++i) { - exciter.y()[i].setVariableNumber(i); ///< Exciter independent variables + exciter_y[i].setVariableNumber(i); ///< Exciter independent variables } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + exciter.size()); // Bus independent variables + bus_y[i].setVariableNumber(i + exciter.size()); // Bus independent variables } bus.evaluateResidual(); exciter.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_y = exciter.getResidual(); + auto& residual_y_view = exciter.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); // Get d/dy' bus.initialize(); exciter.initialize(); + auto* exciter_yp = exciter.yp().getData(); for (size_t i = 0; i < exciter.size(); ++i) { - exciter.yp()[i].setVariableNumber(i); ///< Exciter independent variables + exciter_yp[i].setVariableNumber(i); ///< Exciter independent variables } bus.evaluateResidual(); exciter.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_yp = exciter.getResidual(); + auto& residual_yp_view = exciter.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/GenClassicalTests.hpp b/tests/UnitTests/PhasorDynamics/GenClassicalTests.hpp index da944041b..7ffbe359c 100644 --- a/tests/UnitTests/PhasorDynamics/GenClassicalTests.hpp +++ b/tests/UnitTests/PhasorDynamics/GenClassicalTests.hpp @@ -116,28 +116,32 @@ namespace GridKit gen.setEp(Ep); // Set variable values matching the answer key - gen.y()[0] = M_PI; // delta - gen.y()[1] = 1.0; // omega - gen.y()[2] = 2.0; // telec - gen.y()[3] = -2.0; // ir - gen.y()[4] = -4.0; // ii + auto* y = gen.y().getData(); + auto* yp = gen.yp().getData(); + + y[0] = M_PI; // delta + y[1] = 1.0; // omega + y[2] = 2.0; // telec + y[3] = -2.0; // ir + y[4] = -4.0; // ii // Set derivative values matching the answer key - gen.yp()[0] = 2 * M_PI * 60.0; // delta_dot - gen.yp()[1] = -1.5; // omega_dot - gen.yp()[2] = 0; - gen.yp()[3] = 0; - gen.yp()[4] = 0; + yp[0] = 2 * M_PI * 60.0; // delta_dot + yp[1] = -1.5; // omega_dot + yp[2] = 0; + yp[3] = 0; + yp[4] = 0; gen.evaluateResidual(); - std::vector& residual = gen.getResidual(); + auto& residual = gen.getResidual(); + auto* residual_data = residual.getData(); for (size_t i = 0; i < res_answer.size(); ++i) { - if (!isEqual(residual[i], res_answer[i], tol_)) + if (!isEqual(residual_data[i], res_answer[i], tol_)) { std::cout << "Incorrect result for residual " << i << ": " - << residual[i] << " != " << res_answer[i] << "\n"; + << residual_data[i] << " != " << res_answer[i] << "\n"; success = false; break; } @@ -230,20 +234,22 @@ namespace GridKit gen.allocate(); gen.initialize(); + const auto* y = gen.y().getData(); + const auto* yp = gen.yp().getData(); for (size_t i = 0; i < var_answer.size(); ++i) { - if (!isEqual(gen.y()[i], var_answer[i], tol_)) + if (!isEqual(y[i], var_answer[i], tol_)) { std::cout << "Incorrect result: " - << gen.y()[i] << " != " << var_answer[i] << "\n"; + << y[i] << " != " << var_answer[i] << "\n"; success = false; break; } - if (!isEqual(gen.yp()[i], 0.0, tol_)) + if (!isEqual(yp[i], 0.0, tol_)) { std::cout << "Incorrect result: " - << gen.yp()[i] << " != 0\n"; + << yp[i] << " != 0\n"; success = false; break; } @@ -277,14 +283,16 @@ namespace GridKit gen.allocate(); gen.initialize(); gen.evaluateResidual(); - std::vector res = gen.getResidual(); + auto& res = gen.getResidual(); + auto* res_data = res.getData(); + auto* yp = gen.yp().getData(); - for (size_t i = 0; i < res.size(); ++i) + for (size_t i = 0; i < res.getSize(); ++i) { - if (!isEqual(res[i], 0.0, tol_)) + if (!isEqual(res_data[i], 0.0, tol_)) { std::cout << "Incorrect result: " - << gen.yp()[i] << " != 0\n"; + << yp[i] << " != 0\n"; success = false; break; } @@ -339,33 +347,38 @@ namespace GridKit bus.initialize(); gen.initialize(); + auto* gen_y = gen.y().getData(); for (size_t i = 0; i < gen.size(); ++i) { - gen.y()[i].setVariableNumber(i); ///< Generator independent variables + gen_y[i].setVariableNumber(i); ///< Generator independent variables } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + gen.size()); // Bus independent variables + bus_y[i].setVariableNumber(i + gen.size()); // Bus independent variables } bus.evaluateResidual(); gen.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_y = gen.getResidual(); + auto& residual_y_view = gen.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); // Get d/dy' bus.initialize(); gen.initialize(); + auto* gen_yp = gen.yp().getData(); for (size_t i = 0; i < gen.size(); ++i) { - gen.yp()[i].setVariableNumber(i); ///< Generator independent variables + gen_yp[i].setVariableNumber(i); ///< Generator independent variables } bus.evaluateResidual(); gen.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_yp = gen.getResidual(); + auto& residual_yp_view = gen.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/GenrouTests.hpp b/tests/UnitTests/PhasorDynamics/GenrouTests.hpp index 11d27a89f..f3391b14f 100644 --- a/tests/UnitTests/PhasorDynamics/GenrouTests.hpp +++ b/tests/UnitTests/PhasorDynamics/GenrouTests.hpp @@ -126,10 +126,11 @@ namespace GridKit // Require results to be within machine precision auto tol = 10 * std::numeric_limits::epsilon(); - const std::vector& f = gen.getResidual(); - for (const auto& f_val : f) + const auto& f = gen.getResidual(); + const auto* f_data = f.getData(); + for (std::size_t i = 0; i < f.getSize(); ++i) { - if (!isEqual(f_val, 0.0, tol)) + if (!isEqual(f_data[i], 0.0, tol)) success = false; } @@ -250,43 +251,47 @@ namespace GridKit // but this needs to be better handled in the model implementation. // Set variable values matching the answer key - gen.y()[0] = M_PI; // delta - gen.y()[1] = 2.0; // omega - gen.y()[2] = 2.0; // Eqp - gen.y()[3] = .1; // psidp - gen.y()[4] = .01; // psiqp - gen.y()[5] = .6; // Edp - gen.y()[6] = .2; // psiqp - gen.y()[7] = .03; // psidpp - gen.y()[8] = .01; // psipp - gen.y()[9] = 2; // ksat - gen.y()[10] = .8; // vd - gen.y()[11] = .4; // vq - gen.y()[12] = 2; // telec - gen.y()[13] = 1.1; // id - gen.y()[14] = .3; // iq - gen.y()[15] = .9; // ir - gen.y()[16] = .25; // ii - gen.y()[17] = .3; // inr - gen.y()[18] = .15; // ini + auto* y = gen.y().getData(); + auto* yp = gen.yp().getData(); + + y[0] = M_PI; // delta + y[1] = 2.0; // omega + y[2] = 2.0; // Eqp + y[3] = .1; // psidp + y[4] = .01; // psiqp + y[5] = .6; // Edp + y[6] = .2; // psiqp + y[7] = .03; // psidpp + y[8] = .01; // psipp + y[9] = 2; // ksat + y[10] = .8; // vd + y[11] = .4; // vq + y[12] = 2; // telec + y[13] = 1.1; // id + y[14] = .3; // iq + y[15] = .9; // ir + y[16] = .25; // ii + y[17] = .3; // inr + y[18] = .15; // ini // Set derivative values matching the answer key - gen.yp()[0] = 2 * M_PI * 60.0; // delta_dot - gen.yp()[1] = -1.5; // omega_dot - gen.yp()[2] = 1; // Eqp_dot - gen.yp()[3] = 1; // psidp_dot - gen.yp()[4] = 1; // psiqp_dot - gen.yp()[5] = 1; // Edp_dot + yp[0] = 2 * M_PI * 60.0; // delta_dot + yp[1] = -1.5; // omega_dot + yp[2] = 1; // Eqp_dot + yp[3] = 1; // psidp_dot + yp[4] = 1; // psiqp_dot + yp[5] = 1; // Edp_dot gen.evaluateResidual(); - std::vector& residual = gen.getResidual(); + auto& residual = gen.getResidual(); + auto* residual_data = residual.getData(); for (size_t i = 0; i < res_answer.size(); ++i) { - if (!isEqual(residual[i], res_answer[i], tol_)) + if (!isEqual(residual_data[i], res_answer[i], tol_)) { std::cout << "Incorrect result for residual " << i << ": " - << residual[i] << " != " << res_answer[i] << "\n"; + << residual_data[i] << " != " << res_answer[i] << "\n"; success = false; break; } @@ -361,33 +366,38 @@ namespace GridKit bus.initialize(); gen.initialize(); + auto* gen_y = gen.y().getData(); for (size_t i = 0; i < gen.size(); ++i) { - gen.y()[i].setVariableNumber(i); ///< Generator independent variables + gen_y[i].setVariableNumber(i); ///< Generator independent variables } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + gen.size()); // Bus independent variables + bus_y[i].setVariableNumber(i + gen.size()); // Bus independent variables } bus.evaluateResidual(); gen.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_y = gen.getResidual(); + auto& residual_y_view = gen.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); // Get d/dy' bus.initialize(); gen.initialize(); + auto* gen_yp = gen.yp().getData(); for (size_t i = 0; i < gen.size(); ++i) { - gen.yp()[i].setVariableNumber(i); ///< Generator independent variables + gen_yp[i].setVariableNumber(i); ///< Generator independent variables } bus.evaluateResidual(); gen.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residual_yp = gen.getResidual(); + auto& residual_yp_view = gen.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/GensalTests.hpp b/tests/UnitTests/PhasorDynamics/GensalTests.hpp index 13b8bc7ff..7e5b69257 100644 --- a/tests/UnitTests/PhasorDynamics/GensalTests.hpp +++ b/tests/UnitTests/PhasorDynamics/GensalTests.hpp @@ -99,10 +99,11 @@ namespace GridKit gen.initialize(); gen.evaluateResidual(); - const std::vector& f = gen.getResidual(); - for (const auto& f_val : f) + const auto& f = gen.getResidual(); + const auto* f_data = f.getData(); + for (std::size_t i = 0; i < f.getSize(); ++i) { - if (!isEqual(f_val, 0.0, tol_)) + if (!isEqual(f_data[i], 0.0, tol_)) { success = false; break; @@ -139,10 +140,11 @@ namespace GridKit gen.initialize(); gen.evaluateResidual(); - const std::vector& f = gen.getResidual(); - for (const auto& f_val : f) + const auto& f = gen.getResidual(); + const auto* f_data = f.getData(); + for (std::size_t i = 0; i < f.getSize(); ++i) { - if (!isEqual(f_val, 0.0, tol_)) + if (!isEqual(f_data[i], 0.0, tol_)) { success = false; break; @@ -169,12 +171,15 @@ namespace GridKit gen.setSystemBase(50.0, 100.0e6); gen.allocate(); - gen.y()[1] = 1.0; - gen.yp()[0] = TWO * M_PI * 50.0; + auto* y = gen.y().getData(); + auto* yp = gen.yp().getData(); + y[1] = 1.0; + yp[0] = TWO * M_PI * 50.0; gen.evaluateResidual(); - success *= isEqual(gen.getResidual()[0], 0.0, tol_); + const auto* f = gen.getResidual().getData(); + success *= isEqual(f[0], 0.0, tol_); return success.report(__func__); } @@ -283,38 +288,42 @@ namespace GridKit gen.allocate(); - gen.y()[0] = M_PI; // delta - gen.y()[1] = 1.0; // omega - gen.y()[2] = 2.0; // Eqp - gen.y()[3] = 0.5; // psidp - gen.y()[4] = -0.75; // psiqpp - gen.y()[5] = 1.0; // psidpp - gen.y()[6] = 0.2; // ksat - gen.y()[7] = 0.4; // vd - gen.y()[8] = 0.6; // vq - gen.y()[9] = 1.5; // telec - gen.y()[10] = 0.25; // id - gen.y()[11] = -0.5; // iq - gen.y()[12] = 0.75; // ir - gen.y()[13] = -0.25; // ii - gen.y()[14] = 0.1; // inr - gen.y()[15] = -0.2; // ini - - gen.yp()[0] = 2 * M_PI * 60.0; // delta_dot - gen.yp()[1] = -1.0; // omega_dot - gen.yp()[2] = 0.3; // Eqp_dot - gen.yp()[3] = -0.7; // psidp_dot - gen.yp()[4] = 0.9; // psiqpp_dot + auto* y = gen.y().getData(); + auto* yp = gen.yp().getData(); + + y[0] = M_PI; // delta + y[1] = 1.0; // omega + y[2] = 2.0; // Eqp + y[3] = 0.5; // psidp + y[4] = -0.75; // psiqpp + y[5] = 1.0; // psidpp + y[6] = 0.2; // ksat + y[7] = 0.4; // vd + y[8] = 0.6; // vq + y[9] = 1.5; // telec + y[10] = 0.25; // id + y[11] = -0.5; // iq + y[12] = 0.75; // ir + y[13] = -0.25; // ii + y[14] = 0.1; // inr + y[15] = -0.2; // ini + + yp[0] = 2 * M_PI * 60.0; // delta_dot + yp[1] = -1.0; // omega_dot + yp[2] = 0.3; // Eqp_dot + yp[3] = -0.7; // psidp_dot + yp[4] = 0.9; // psiqpp_dot gen.evaluateResidual(); - std::vector& residual = gen.getResidual(); + auto& residual = gen.getResidual(); + auto* residual_data = residual.getData(); for (size_t i = 0; i < res_answer.size(); ++i) { - if (!isEqual(residual[i], res_answer[i], tol_)) + if (!isEqual(residual_data[i], res_answer[i], tol_)) { std::cout << "Incorrect result for residual " << i << ": " - << residual[i] << " != " << res_answer[i] << "\n"; + << residual_data[i] << " != " << res_answer[i] << "\n"; success = false; break; } @@ -359,30 +368,35 @@ namespace GridKit bus.initialize(); gen.initialize(); + auto* gen_y = gen.y().getData(); for (size_t i = 0; i < gen.size(); ++i) { - gen.y()[i].setVariableNumber(i); + gen_y[i].setVariableNumber(i); } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + gen.size()); + bus_y[i].setVariableNumber(i + gen.size()); } bus.evaluateResidual(); gen.evaluateResidual(); - std::vector residual_y = gen.getResidual(); + auto& residual_y_view = gen.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); bus.initialize(); gen.initialize(); + auto* gen_yp = gen.yp().getData(); for (size_t i = 0; i < gen.size(); ++i) { - gen.yp()[i].setVariableNumber(i); + gen_yp[i].setVariableNumber(i); } bus.evaluateResidual(); gen.evaluateResidual(); - std::vector residual_yp = gen.getResidual(); + auto& residual_yp_view = gen.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/GovernorTgov1Tests.hpp b/tests/UnitTests/PhasorDynamics/GovernorTgov1Tests.hpp index 1d76548e4..f48044209 100644 --- a/tests/UnitTests/PhasorDynamics/GovernorTgov1Tests.hpp +++ b/tests/UnitTests/PhasorDynamics/GovernorTgov1Tests.hpp @@ -120,23 +120,27 @@ namespace GridKit gov.evaluateResidual(); // Set variable values matching the answer key - gov.y()[0] = 1.0; // Ptx - gov.y()[1] = 1.0; // Pv - gov.y()[2] = static_cast(10.0) / static_cast(15.0); // Pmech + auto* y = gov.y().getData(); + auto* yp = gov.yp().getData(); + + y[0] = 1.0; // Ptx + y[1] = 1.0; // Pv + y[2] = static_cast(10.0) / static_cast(15.0); // Pmech // Set derivative values matching the answer key - gov.yp()[0] = static_cast(8.0) / static_cast(15.0); // ptx_dot - gov.yp()[1] = 2.0; // pv_dot + yp[0] = static_cast(8.0) / static_cast(15.0); // ptx_dot + yp[1] = 2.0; // pv_dot gov.evaluateResidual(); - std::vector& residual = gov.getResidual(); + auto& residual = gov.getResidual(); + auto* residual_data = residual.getData(); for (size_t i = 0; i < res_answer.size(); ++i) { - if (!isEqual(residual[i], res_answer[i], tol_)) + if (!isEqual(residual_data[i], res_answer[i], tol_)) { std::cout << "Incorrect result for residual " << i << ": " - << residual[i] << " != " << res_answer[i] << "\n"; + << residual_data[i] << " != " << res_answer[i] << "\n"; success = false; break; } @@ -215,10 +219,11 @@ namespace GridKit // Require results to be within machine precision auto tol = 10 * std::numeric_limits::epsilon(); - const std::vector& f = gov.getResidual(); - for (const auto& f_val : f) + const auto& f = gov.getResidual(); + const auto* f_data = f.getData(); + for (std::size_t i = 0; i < f.getSize(); ++i) { - if (!isEqual(f_val, 0.0, tol)) + if (!isEqual(f_data[i], 0.0, tol)) success = false; } @@ -310,33 +315,38 @@ namespace GridKit gen.initialize(); gov.initialize(); + auto* gov_y = gov.y().getData(); for (size_t i = 0; i < gov.size(); ++i) { - gov.y()[i].setVariableNumber(i); // Governor independent variables + gov_y[i].setVariableNumber(i); // Governor independent variables } - gen.y()[1].setVariableNumber(gov.size()); // omega as an additional independent variable + auto* gen_y = gen.y().getData(); + gen_y[1].setVariableNumber(gov.size()); // omega as an additional independent variable bus.evaluateResidual(); gen.evaluateResidual(); gov.evaluateResidual(); // Computes the residual and the Jacobian values by tracking // the dependencies - std::vector residual_y = gov.getResidual(); + auto& residual_y_view = gov.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); // Get d/dy' bus.initialize(); gen.initialize(); gov.initialize(); + auto* gov_yp = gov.yp().getData(); for (size_t i = 0; i < gov.size(); ++i) { - gov.yp()[i].setVariableNumber(i); ///< Governor independent variables + gov_yp[i].setVariableNumber(i); ///< Governor independent variables } bus.evaluateResidual(); gen.evaluateResidual(); gov.evaluateResidual(); // Computes the residual and the Jacobian values by tracking // the dependencies - std::vector residual_yp = gov.getResidual(); + auto& residual_yp_view = gov.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print the dependencies for (size_t i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/LoadZIPTests.hpp b/tests/UnitTests/PhasorDynamics/LoadZIPTests.hpp index bd3f2f688..7442e00c8 100644 --- a/tests/UnitTests/PhasorDynamics/LoadZIPTests.hpp +++ b/tests/UnitTests/PhasorDynamics/LoadZIPTests.hpp @@ -68,10 +68,12 @@ namespace GridKit bus.initialize(); load.initialize(); - success *= isEqual(load.y()[0], static_cast(-3.2), tol_); - success *= isEqual(load.y()[1], static_cast(-2.6), tol_); - success *= isEqual(load.yp()[0], static_cast(0.0), tol_); - success *= isEqual(load.yp()[1], static_cast(0.0), tol_); + const auto* y = load.y().getData(); + const auto* yp = load.yp().getData(); + success *= isEqual(y[0], static_cast(-3.2), tol_); + success *= isEqual(y[1], static_cast(-2.6), tol_); + success *= isEqual(yp[0], static_cast(0.0), tol_); + success *= isEqual(yp[1], static_cast(0.0), tol_); return success.report(__func__); } @@ -95,10 +97,11 @@ namespace GridKit bus.evaluateResidual(); load.evaluateResidual(); - success *= isEqual(load.getResidual()[0], static_cast(128.0 / 75.0), tol_); - success *= isEqual(load.getResidual()[1], static_cast(104.0 / 75.0), tol_); - success *= isEqual(bus.Ir(), static_cast(-3.2), tol_); - success *= isEqual(bus.Ii(), static_cast(-2.6), tol_); + const auto* f = load.getResidual().getData(); + success *= isEqual(f[0], static_cast(128.0 / 75.0), tol_); + success *= isEqual(f[1], static_cast(104.0 / 75.0), tol_); + success *= isEqual(bus.Ir(), static_cast(-3.2), tol_); + success *= isEqual(bus.Ii(), static_cast(-2.6), tol_); return success.report(__func__); } @@ -181,30 +184,37 @@ namespace GridKit bus.initialize(); load.initialize(); + auto* load_y = load.y().getData(); for (size_t i = 0; i < load.size(); ++i) { - load.y()[i].setVariableNumber(i); + load_y[i].setVariableNumber(i); } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + load.size()); + bus_y[i].setVariableNumber(i + load.size()); } bus.evaluateResidual(); - load.evaluateResidual(); - auto residual_y = load.getResidual(); + load.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking + ///< the dependencies + auto& residual_y_view = load.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); bus.initialize(); load.initialize(); + auto* load_yp = load.yp().getData(); for (size_t i = 0; i < load.size(); ++i) { - load.yp()[i].setVariableNumber(i); + load_yp[i].setVariableNumber(i); } bus.evaluateResidual(); - load.evaluateResidual(); - auto residual_yp = load.getResidual(); + load.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking + ///< the dependencies + auto& residual_yp_view = load.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); std::vector dependencies(residual_y.size()); for (IdxT i = 0; i < residual_y.size(); ++i) diff --git a/tests/UnitTests/PhasorDynamics/LoadZTests.hpp b/tests/UnitTests/PhasorDynamics/LoadZTests.hpp index 5df7cd27f..45799310f 100644 --- a/tests/UnitTests/PhasorDynamics/LoadZTests.hpp +++ b/tests/UnitTests/PhasorDynamics/LoadZTests.hpp @@ -104,26 +104,29 @@ namespace GridKit bus.initialize(); load.initialize(); + auto* load_y = load.y().getData(); for (size_t i = 0; i < load.size(); ++i) { - load.y()[i].setVariableNumber(i); ///< load independent variables + load_y[i].setVariableNumber(i); ///< load independent variables } + auto* bus_y = bus.y().getData(); for (size_t i = 0; i < bus.size(); ++i) { - bus.y()[i].setVariableNumber(i + load.size()); // Bus independent variables + bus_y[i].setVariableNumber(i + load.size()); // Bus independent variables } bus.evaluateResidual(); load.evaluateResidual(); ///< Computes the residual and the Jacobian values by tracking ///< the dependencies - std::vector residuals = load.getResidual(); - std::vector ref = analyticalJacobian(R, X); + auto& residuals = load.getResidual(); + auto* residual_data = residuals.getData(); + std::vector ref = analyticalJacobian(R, X); /// Compare dependencies computed automatically to the ones computed analytically - for (size_t i = 0; i < residuals.size(); ++i) + for (size_t i = 0; i < residuals.getSize(); ++i) { - DependencyTracking::Variable res = residuals[i]; + DependencyTracking::Variable res = residual_data[i]; const DependencyTracking::Variable::DependencyMap& dependencies = res.getDependencies(); success *= (GridKit::Testing::isEqual(dependencies, ref[i])); } diff --git a/tests/UnitTests/PhasorDynamics/StabilizerIeeestTests.hpp b/tests/UnitTests/PhasorDynamics/StabilizerIeeestTests.hpp index 15b64876f..b008b3a56 100644 --- a/tests/UnitTests/PhasorDynamics/StabilizerIeeestTests.hpp +++ b/tests/UnitTests/PhasorDynamics/StabilizerIeeestTests.hpp @@ -73,13 +73,14 @@ namespace GridKit stab.initialize(); stab.evaluateResidual(); - auto tol = 10 * std::numeric_limits::epsilon(); - const auto& f = stab.getResidual(); - for (size_t i = 0; i < f.size(); ++i) + auto tol = 10 * std::numeric_limits::epsilon(); + const auto& f = stab.getResidual(); + auto* f_data = f.getData(); + for (size_t i = 0; i < f.getSize(); ++i) { - if (!isEqual(f[i], 0.0, tol)) + if (!isEqual(f_data[i], 0.0, tol)) { - std::cout << "Non-zero residual at index " << i << ": " << f[i] << "\n"; + std::cout << "Non-zero residual at index " << i << ": " << f_data[i] << "\n"; success = false; } } @@ -140,16 +141,17 @@ namespace GridKit }; // Looser tolerance for f[11] — Math::clamp is a smooth ramp approximation. - const auto loose_tol = static_cast(1.0e-4); - auto& residual = stab.getResidual(); + const auto loose_tol = static_cast(1.0e-4); + auto& residual = stab.getResidual(); + auto* residual_data = residual.getData(); for (size_t i = 0; i < res_answer.size(); ++i) { auto test_tol = (i == 11) ? loose_tol : static_cast(10 * std::numeric_limits::epsilon()); - if (!isEqual(residual[i], res_answer[i], test_tol)) + if (!isEqual(residual_data[i], res_answer[i], test_tol)) { std::cout << "Incorrect result for residual " << i << ": " - << std::setprecision(15) << residual[i] + << std::setprecision(15) << residual_data[i] << " != " << res_answer[i] << "\n"; success = false; } @@ -212,9 +214,10 @@ namespace GridKit stab.initialize(); // --- d/dy: tag internal variables as independent --- + auto* y = stab.y().getData(); for (size_t i = 0; i < stab.size(); ++i) { - stab.y()[i].setVariableNumber(i); + y[i].setVariableNumber(i); } // Tag external signal u as an additional independent variable u_value.setVariableNumber(stab.size()); @@ -223,20 +226,23 @@ namespace GridKit setStatePointDep(stab); stab.evaluateResidual(); - std::vector residual_y = stab.getResidual(); + auto& residual_y_view = stab.getResidual(); + std::vector residual_y(residual_y_view.getData(), residual_y_view.getData() + residual_y_view.getSize()); // --- d/dy': tag derivatives as independent --- stab.initialize(); + auto* yp = stab.yp().getData(); for (size_t i = 0; i < stab.size(); ++i) { - stab.yp()[i].setVariableNumber(i); + yp[i].setVariableNumber(i); } u_value = 0.5; setStatePointDep(stab); stab.evaluateResidual(); - std::vector residual_yp = stab.getResidual(); + auto& residual_yp_view = stab.getResidual(); + std::vector residual_yp(residual_yp_view.getData(), residual_yp_view.getData() + residual_yp_view.getSize()); // Print dependencies for debugging for (size_t i = 0; i < residual_y.size(); ++i) @@ -360,26 +366,29 @@ namespace GridKit */ void setStatePoint(PhasorDynamics::Stabilizer::Ieeest& stab) { - stab.y()[0] = 0.1; // x1 - stab.y()[1] = 0.2; // x2 - stab.y()[2] = 0.3; // x3 - stab.y()[3] = 0.4; // x4 - stab.y()[4] = 0.5; // x5 - stab.y()[5] = 0.6; // x6 - stab.y()[6] = 0.7; // x7 - stab.y()[7] = 0.8; // v4 - stab.y()[8] = 0.9; // v5 - stab.y()[9] = 1.0; // v6 - stab.y()[10] = 0.05; // v7 (within limiter range) - stab.y()[11] = 0.05; // Vss (model output) - - stab.yp()[0] = 0.01; // x1_dot - stab.yp()[1] = 0.02; // x2_dot - stab.yp()[2] = 0.03; // x3_dot - stab.yp()[3] = 0.04; // x4_dot - stab.yp()[4] = 0.05; // x5_dot - stab.yp()[5] = 0.06; // x6_dot - stab.yp()[6] = 0.07; // x7_dot + auto* y = stab.y().getData(); + auto* yp = stab.yp().getData(); + + y[0] = 0.1; // x1 + y[1] = 0.2; // x2 + y[2] = 0.3; // x3 + y[3] = 0.4; // x4 + y[4] = 0.5; // x5 + y[5] = 0.6; // x6 + y[6] = 0.7; // x7 + y[7] = 0.8; // v4 + y[8] = 0.9; // v5 + y[9] = 1.0; // v6 + y[10] = 0.05; // v7 (within limiter range) + y[11] = 0.05; // Vss (model output) + + yp[0] = 0.01; // x1_dot + yp[1] = 0.02; // x2_dot + yp[2] = 0.03; // x3_dot + yp[3] = 0.04; // x4_dot + yp[4] = 0.05; // x5_dot + yp[5] = 0.06; // x6_dot + yp[6] = 0.07; // x7_dot } /** @@ -388,26 +397,29 @@ namespace GridKit */ void setStatePointDep(PhasorDynamics::Stabilizer::Ieeest& stab) { - stab.y()[0].setValue(0.1); - stab.y()[1].setValue(0.2); - stab.y()[2].setValue(0.3); - stab.y()[3].setValue(0.4); - stab.y()[4].setValue(0.5); - stab.y()[5].setValue(0.6); - stab.y()[6].setValue(0.7); - stab.y()[7].setValue(0.8); - stab.y()[8].setValue(0.9); - stab.y()[9].setValue(1.0); - stab.y()[10].setValue(0.05); - stab.y()[11].setValue(0.05); - - stab.yp()[0].setValue(0.01); - stab.yp()[1].setValue(0.02); - stab.yp()[2].setValue(0.03); - stab.yp()[3].setValue(0.04); - stab.yp()[4].setValue(0.05); - stab.yp()[5].setValue(0.06); - stab.yp()[6].setValue(0.07); + auto* y = stab.y().getData(); + auto* yp = stab.yp().getData(); + + y[0].setValue(0.1); + y[1].setValue(0.2); + y[2].setValue(0.3); + y[3].setValue(0.4); + y[4].setValue(0.5); + y[5].setValue(0.6); + y[6].setValue(0.7); + y[7].setValue(0.8); + y[8].setValue(0.9); + y[9].setValue(1.0); + y[10].setValue(0.05); + y[11].setValue(0.05); + + yp[0].setValue(0.01); + yp[1].setValue(0.02); + yp[2].setValue(0.03); + yp[3].setValue(0.04); + yp[4].setValue(0.05); + yp[5].setValue(0.06); + yp[6].setValue(0.07); } }; // class StabilizerIeeestTests diff --git a/tests/UnitTests/PhasorDynamics/SystemTests.hpp b/tests/UnitTests/PhasorDynamics/SystemTests.hpp index a973a4cca..3e64ee9a3 100644 --- a/tests/UnitTests/PhasorDynamics/SystemTests.hpp +++ b/tests/UnitTests/PhasorDynamics/SystemTests.hpp @@ -1,8 +1,10 @@ #pragma once +#include #include #include #include +#include #include #include @@ -11,6 +13,7 @@ #include #include #include +#include #include #include #include @@ -153,6 +156,72 @@ namespace GridKit return success.report(__func__); } + TestOutcome elementStateAliasesSystemState() + { + TestStatus success = true; + + PhasorDynamics::SystemModel system; + + PhasorDynamics::Bus bus1(1.0, 2.0); + PhasorDynamics::Bus bus2(3.0, 4.0); + system.addBus(&bus1); + system.addBus(&bus2); + + PhasorDynamics::Branch branch(&bus1, &bus2, 0.0, 1.0, 0.0, 0.0); + system.addComponent(&branch); + + PhasorDynamics::LoadZ load(&bus2, 1.0, 1.0); + system.addComponent(&load); + + system.allocate(); + system.initialize(); + + const auto bus2_vr_index = static_cast(bus2.getVariableIndex(0)); + const auto bus2_vi_index = static_cast(bus2.getVariableIndex(1)); + const auto load_ir_index = static_cast(load.getVariableIndex(0)); + const auto load_ii_index = static_cast(load.getVariableIndex(1)); + + auto* system_y = system.y().getData(); + auto* load_y = load.y().getData(); + system_y[bus2_vr_index] = 5.0; + system_y[bus2_vi_index] = 6.0; + success *= isEqual(bus2.Vr(), static_cast(5.0)); + success *= isEqual(bus2.Vi(), static_cast(6.0)); + + bus2.Vr() = 7.0; + bus2.Vi() = 8.0; + success *= isEqual(system_y[bus2_vr_index], static_cast(7.0)); + success *= isEqual(system_y[bus2_vi_index], static_cast(8.0)); + + system_y[load_ir_index] = 9.0; + system_y[load_ii_index] = 10.0; + success *= isEqual(load_y[0], static_cast(9.0)); + success *= isEqual(load_y[1], static_cast(10.0)); + + load_y[0] = 11.0; + load_y[1] = 12.0; + success *= isEqual(system_y[load_ir_index], static_cast(11.0)); + success *= isEqual(system_y[load_ii_index], static_cast(12.0)); + + auto* bus2_tag = bus2.tag().getData(); + auto* system_tag = system.tag().getData(); + bus2_tag[0] = 1.0; + success *= isEqual(system_tag[bus2_vr_index], static_cast(1.0)); + + system_tag[bus2_vr_index] = 0.0; + success *= isEqual(bus2_tag[0], static_cast(0.0)); + + auto* load_abs_tol = load.absoluteTolerance().getData(); + auto* system_abs_tol = system.absoluteTolerance().getData(); + load_abs_tol[0] = 0.123; + success *= isEqual(system_abs_tol[load_ir_index], static_cast(0.123)); + + system_abs_tol[load_ii_index] = 0.456; + success *= isEqual(load_abs_tol[1], static_cast(0.456)); + + return success.report(__func__); + } + /** * @brief Test for exception when signals are incorrectly configured */ @@ -168,7 +237,6 @@ namespace GridKit status *= throws( [&]() { sys.allocate(); }); - return status.report(__func__); } @@ -232,28 +300,30 @@ namespace GridKit system.initialize(); // Set independent variables + auto* y = system.y().getData(); for (size_t i = 0; i < system.size(); ++i) { - system.y()[i].setVariableNumber(i); + y[i].setVariableNumber(i); } // Evaluate and get the system residuals system.evaluateResidual(); - std::vector residual = system.getResidual(); + auto& residual = system.getResidual(); + auto* residual_data = residual.getData(); // Print the dependencies - for (size_t i = 0; i < residual.size(); ++i) + for (size_t i = 0; i < residual.getSize(); ++i) { std::cout << i << "th residual: "; - (residual[i]).print(std::cout); + residual_data[i].print(std::cout); std::cout << "\n"; } // Extract the dependencies - std::vector dependencies(residual.size()); - for (IdxT i = 0; i < residual.size(); ++i) + std::vector dependencies(residual.getSize()); + for (IdxT i = 0; i < residual.getSize(); ++i) { - dependencies[i] = (residual[i]).getDependencies(); + dependencies[i] = residual_data[i].getDependencies(); } return dependencies; diff --git a/tests/UnitTests/PhasorDynamics/runSystemTests.cpp b/tests/UnitTests/PhasorDynamics/runSystemTests.cpp index a8b432be2..b337028aa 100644 --- a/tests/UnitTests/PhasorDynamics/runSystemTests.cpp +++ b/tests/UnitTests/PhasorDynamics/runSystemTests.cpp @@ -10,6 +10,7 @@ int main() result += test.constructor(); result += test.composer(); + result += test.elementStateAliasesSystemState(); #ifdef GRIDKIT_ENABLE_ENZYME result += test.jacobian(); #endif diff --git a/tests/UnitTests/Solver/Dynamic/CMakeLists.txt b/tests/UnitTests/Solver/Dynamic/CMakeLists.txt index 93b92a471..e385f518c 100644 --- a/tests/UnitTests/Solver/Dynamic/CMakeLists.txt +++ b/tests/UnitTests/Solver/Dynamic/CMakeLists.txt @@ -2,7 +2,10 @@ add_executable(test_ida runIdaTests.cpp) target_link_libraries( - test_ida GridKit::solvers_dyn GridKit::testing) + test_ida + GridKit::solvers_dyn + GridKit::dense_vector + GridKit::testing) add_test(NAME IDATest COMMAND $) diff --git a/tests/UnitTests/Solver/Dynamic/IdaTests.hpp b/tests/UnitTests/Solver/Dynamic/IdaTests.hpp index 3962d76db..cda9a41e9 100644 --- a/tests/UnitTests/Solver/Dynamic/IdaTests.hpp +++ b/tests/UnitTests/Solver/Dynamic/IdaTests.hpp @@ -14,8 +14,18 @@ namespace GridKit template class NullEvaluator : public Model::Evaluator { + protected: + using Model::Evaluator::y_; + using Model::Evaluator::yp_; + using Model::Evaluator::f_; + using Model::Evaluator::tag_; + using Model::Evaluator::abs_tol_; + using Model::Evaluator::allocated_; + using Model::Evaluator::allocateVectors; + public: - using RealT = typename Model::Evaluator::RealT; + using RealT = typename Model::Evaluator::RealT; + using VectorT = typename Model::Evaluator::VectorT; NullEvaluator() { @@ -23,19 +33,31 @@ namespace GridKit int allocate() override { + if (!allocated_) + { + allocateVectors(size()); + } return 0; } int initialize() override { - y_ = {0}; - yp_ = {0}; - - tag_ = {false}; - abs_tol_ = {0}; - - f_ = {0}; - g_ = {0}; + if (!allocated_) + { + allocate(); + } + + auto* y = y_.getData(); + auto* yp = yp_.getData(); + auto* tag = tag_.getData(); + auto* abs_tol = abs_tol_.getData(); + auto* f = f_.getData(); + + y[0] = 0.0; + yp[0] = 0.0; + tag[0] = 0.0; + abs_tol[0] = 0.0; + f[0] = 0.0; return 0; } @@ -71,13 +93,15 @@ namespace GridKit int setAbsoluteTolerance(RealT rel_tol) override { - std::fill(abs_tol_.begin(), abs_tol_.end(), rel_tol); + std::fill(abs_tol_.getData(), abs_tol_.getData() + abs_tol_.getSize(), rel_tol); return 0; } int evaluateResidual() override { - f_ = y_; + auto* f = f_.getData(); + const auto* y = y_.getData(); + f[0] = y[0]; return 0; } @@ -110,137 +134,97 @@ namespace GridKit { } - std::vector& y() override - { - return y_; - } - - const std::vector& y() const override - { - return y_; - } - - std::vector& yp() override - { - return yp_; - } - - const std::vector& yp() const override - { - return yp_; - } - - std::vector& tag() override - { - return tag_; - } - - const std::vector& tag() const override - { - return tag_; - } - - std::vector& absoluteTolerance() override - { - return abs_tol_; - } - - const std::vector& absoluteTolerance() const override - { - return abs_tol_; - } - - std::vector& yB() override + VectorT& yB() override { return yB_; } - const std::vector& yB() const override + const VectorT& yB() const override { return yB_; } - std::vector& ypB() override + VectorT& ypB() override { return ypB_; } - const std::vector& ypB() const override + const VectorT& ypB() const override { return ypB_; } - std::vector& param() override + VectorT& param() override { return param_; } - const std::vector& param() const override + const VectorT& param() const override { return param_; } - std::vector& param_up() override + VectorT& param_up() override { return param_up_; } - const std::vector& param_up() const override + const VectorT& param_up() const override { return param_up_; } - std::vector& param_lo() override + VectorT& param_lo() override { return param_lo_; } - const std::vector& param_lo() const override + const VectorT& param_lo() const override { return param_lo_; } - std::vector& getResidual() override + VectorT& getResidual() override { return f_; } - const std::vector& getResidual() const override + const VectorT& getResidual() const override { return f_; } GridKit::LinearAlgebra::CsrMatrix* getCsrJacobian() const override { - return csr_jac_; + return nullptr; } - std::vector& getIntegrand() override + VectorT& getIntegrand() override { return g_; } - const std::vector& getIntegrand() const override + const VectorT& getIntegrand() const override { return g_; } - std::vector& getAdjointResidual() override + VectorT& getAdjointResidual() override { return fB_; } - const std::vector& getAdjointResidual() const override + const VectorT& getAdjointResidual() const override { return fB_; } - std::vector& getAdjointIntegrand() override + VectorT& getAdjointIntegrand() override { return gB_; } - const std::vector& getAdjointIntegrand() const override + const VectorT& getAdjointIntegrand() const override { return gB_; } @@ -251,23 +235,16 @@ namespace GridKit } protected: - std::vector y_; - std::vector yp_; - std::vector tag_; - std::vector abs_tol_; - std::vector f_; - std::vector g_; - - std::vector yB_; - std::vector ypB_; - std::vector fB_; - std::vector gB_; - - GridKit::LinearAlgebra::CsrMatrix* csr_jac_; - - std::vector param_; - std::vector param_up_; - std::vector param_lo_; + VectorT g_; + + VectorT yB_; + VectorT ypB_; + VectorT fB_; + VectorT gB_; + + VectorT param_; + VectorT param_up_; + VectorT param_lo_; }; template @@ -278,13 +255,28 @@ namespace GridKit int initialize() override { - this->y_ = {0, 0}; - this->yp_ = {0, 0}; - this->tag_ = {true, false}; - this->abs_tol_ = {0, 0}; - this->f_ = {0, 0}; - this->g_ = {0}; - t_ = 0; + if (!this->allocated_) + { + this->allocate(); + } + + auto* y = this->y_.getData(); + auto* yp = this->yp_.getData(); + auto* tag = this->tag_.getData(); + auto* abs_tol = this->abs_tol_.getData(); + auto* f = this->f_.getData(); + + y[0] = 0.0; + y[1] = 0.0; + yp[0] = 0.0; + yp[1] = 0.0; + tag[0] = 1.0; + tag[1] = 0.0; + abs_tol[0] = 0.0; + abs_tol[1] = 0.0; + f[0] = 0.0; + f[1] = 0.0; + t_ = 0.0; return 0; } @@ -296,8 +288,12 @@ namespace GridKit int evaluateResidual() override { static constexpr RealT OMEGA = 100.0; - this->f_[0] = this->yp_[0]; - this->f_[1] = this->y_[1] - std::sin(OMEGA * t_); + auto* f = this->f_.getData(); + const auto* y = this->y_.getData(); + const auto* yp = this->yp_.getData(); + + f[0] = yp[0]; + f[1] = y[1] - std::sin(OMEGA * t_); return 0; }