From ed895f48b73fcf437fa972d59222984f348643a8 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 10 Jul 2024 21:47:08 -0700 Subject: [PATCH 01/19] Introduced smart pointers in some functions, removed some unnecessary functions with pointer arguments, and fixed a memory leak. --- .../dg_advection_local_rom_matrix_interp.cpp | 8 +- lib/algo/DMD.cpp | 18 ++-- lib/algo/DMD.h | 2 +- lib/algo/DMDc.cpp | 22 ++--- lib/algo/DMDc.h | 2 +- lib/algo/greedy/GreedySampler.cpp | 1 - .../manifold_interp/VectorInterpolator.cpp | 7 +- lib/algo/manifold_interp/VectorInterpolator.h | 3 +- lib/linalg/BasisGenerator.cpp | 4 +- lib/linalg/Matrix.h | 24 ----- lib/linalg/Vector.cpp | 59 +------------ lib/linalg/Vector.h | 88 ++----------------- lib/linalg/svd/IncrementalSVD.cpp | 4 +- lib/linalg/svd/IncrementalSVDBrand.cpp | 9 +- 14 files changed, 50 insertions(+), 201 deletions(-) mode change 100755 => 100644 lib/algo/DMD.cpp diff --git a/examples/prom/dg_advection_local_rom_matrix_interp.cpp b/examples/prom/dg_advection_local_rom_matrix_interp.cpp index abbe6621c..4958cb49d 100644 --- a/examples/prom/dg_advection_local_rom_matrix_interp.cpp +++ b/examples/prom/dg_advection_local_rom_matrix_interp.cpp @@ -697,7 +697,7 @@ int main(int argc, char *argv[]) CAROM::Matrix *M_hat_carom, *K_hat_carom; DenseMatrix *M_hat, *K_hat; - CAROM::Vector *b_hat_carom, *u_init_hat_carom; + std::shared_ptr b_hat_carom, u_init_hat_carom; Vector *b_hat, *u_init_hat; Vector u_init(*U); @@ -770,11 +770,11 @@ int main(int argc, char *argv[]) Vector b_vec = *B; CAROM::Vector b_carom(b_vec.GetData(), b_vec.Size(), true); - b_hat_carom = spatialbasis->transposeMult(&b_carom); + b_hat_carom.reset(spatialbasis->transposeMult(&b_carom)); if (interp_prep) b_hat_carom->write("b_hat_" + std::to_string(f_factor)); b_hat = new Vector(b_hat_carom->getData(), b_hat_carom->dim()); - u_init_hat_carom = new CAROM::Vector(numColumnRB, false); + u_init_hat_carom.reset(new CAROM::Vector(numColumnRB, false)); ComputeCtAB_vec(K_mat, *U, *spatialbasis, *u_init_hat_carom); if (interp_prep) u_init_hat_carom->write("u_init_hat_" + std::to_string( f_factor)); @@ -1012,8 +1012,6 @@ int main(int argc, char *argv[]) delete K_hat_carom; delete M_hat; delete K_hat; - delete b_hat_carom; - delete u_init_hat_carom; delete b_hat; delete u_init_hat; delete u_in; diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp old mode 100755 new mode 100644 index a66f3b65b..2ea11e77e --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -144,7 +144,6 @@ DMD::~DMD() delete d_phi_imaginary; delete d_phi_real_squared_inverse; delete d_phi_imaginary_squared_inverse; - delete d_projected_init_real; delete d_projected_init_imaginary; } @@ -607,15 +606,15 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) Vector* rhs_real = d_phi_real->transposeMult(init); Vector* rhs_imaginary = d_phi_imaginary->transposeMult(init); - Vector* d_projected_init_real_1 = d_phi_real_squared_inverse->mult(rhs_real); + Vector* d_projected_init_real_1 = d_phi_real_squared_inverse->mult(*rhs_real); Vector* d_projected_init_real_2 = d_phi_imaginary_squared_inverse->mult( - rhs_imaginary); - d_projected_init_real = d_projected_init_real_1->plus(d_projected_init_real_2); + *rhs_imaginary); + d_projected_init_real = d_projected_init_real_1->plus(*d_projected_init_real_2); Vector* d_projected_init_imaginary_1 = d_phi_real_squared_inverse->mult( - rhs_imaginary); + *rhs_imaginary); Vector* d_projected_init_imaginary_2 = d_phi_imaginary_squared_inverse->mult( - rhs_real); + *rhs_real); d_projected_init_imaginary = d_projected_init_imaginary_2->minus( d_projected_init_imaginary_1); @@ -655,9 +654,10 @@ DMD::predict(double t, int deg) Matrix* d_phi_mult_eigs_imaginary = d_phi_pair.second; Vector* d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( - d_projected_init_real); + *d_projected_init_real); + Vector* d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( - d_projected_init_imaginary); + *d_projected_init_imaginary); Vector* d_predicted_state_real = d_predicted_state_real_1->minus( d_predicted_state_real_2); addOffset(d_predicted_state_real, t, deg); @@ -820,7 +820,7 @@ DMD::load(std::string base_file_name) d_phi_imaginary_squared_inverse->read(full_file_name); full_file_name = base_file_name + "_projected_init_real"; - d_projected_init_real = new Vector(); + d_projected_init_real.reset(new Vector()); d_projected_init_real->read(full_file_name); full_file_name = base_file_name + "_projected_init_imaginary"; diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index ba3750251..d5cd7b5f9 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -435,7 +435,7 @@ class DMD /** * @brief The real part of the projected initial condition. */ - Vector* d_projected_init_real = NULL; + std::shared_ptr d_projected_init_real; /** * @brief The imaginary part of the projected initial condition. diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index 7e4591767..d92da293d 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -150,7 +150,6 @@ DMDc::~DMDc() delete d_phi_imaginary; delete d_phi_real_squared_inverse; delete d_phi_imaginary_squared_inverse; - delete d_projected_init_real; delete d_projected_init_imaginary; } @@ -659,15 +658,15 @@ DMDc::project(const Vector* init, const Matrix* controls, double t_offset) Vector* init_real = d_phi_real->transposeMult(init); Vector* init_imaginary = d_phi_imaginary->transposeMult(init); - Vector* d_projected_init_real_1 = d_phi_real_squared_inverse->mult(init_real); + Vector* d_projected_init_real_1 = d_phi_real_squared_inverse->mult(*init_real); Vector* d_projected_init_real_2 = d_phi_imaginary_squared_inverse->mult( - init_imaginary); - d_projected_init_real = d_projected_init_real_1->plus(d_projected_init_real_2); + *init_imaginary); + d_projected_init_real = d_projected_init_real_1->plus(*d_projected_init_real_2); Vector* d_projected_init_imaginary_1 = d_phi_real_squared_inverse->mult( - init_imaginary); + *init_imaginary); Vector* d_projected_init_imaginary_2 = d_phi_imaginary_squared_inverse->mult( - init_real); + *init_real); d_projected_init_imaginary = d_projected_init_imaginary_2->minus( d_projected_init_imaginary_1); @@ -730,9 +729,10 @@ DMDc::predict(double t) Matrix* d_phi_mult_eigs_imaginary = d_phi_pair.second; Vector* d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( - d_projected_init_real); + *d_projected_init_real); + Vector* d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( - d_projected_init_imaginary); + *d_projected_init_imaginary); Vector* d_predicted_state_real = d_predicted_state_real_1->minus( d_predicted_state_real_2); addOffset(d_predicted_state_real); @@ -754,9 +754,9 @@ DMDc::predict(double t) d_projected_controls_real->getColumn(k, *f_control_real); d_projected_controls_imaginary->getColumn(k, *f_control_imaginary); d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( - f_control_real); + *f_control_real); d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( - f_control_imaginary); + *f_control_imaginary); *d_predicted_state_real += *d_predicted_state_real_1; *d_predicted_state_real -= *d_predicted_state_real_2; @@ -921,7 +921,7 @@ DMDc::load(std::string base_file_name) d_phi_imaginary_squared_inverse->read(full_file_name); full_file_name = base_file_name + "_projected_init_real"; - d_projected_init_real = new Vector(); + d_projected_init_real.reset(new Vector()); d_projected_init_real->read(full_file_name); full_file_name = base_file_name + "_projected_init_imaginary"; diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index f298c4cae..7a8c4e642 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -416,7 +416,7 @@ class DMDc /** * @brief The real part of the projected initial condition. */ - Vector* d_projected_init_real = NULL; + std::shared_ptr d_projected_init_real; /** * @brief The imaginary part of the projected initial condition. diff --git a/lib/algo/greedy/GreedySampler.cpp b/lib/algo/greedy/GreedySampler.cpp index ec41da39e..d3b8a3e41 100644 --- a/lib/algo/greedy/GreedySampler.cpp +++ b/lib/algo/greedy/GreedySampler.cpp @@ -1239,7 +1239,6 @@ GreedySampler::generateRandomPoints(int num_points) std::shared_ptr GreedySampler::getNearestROM(Vector point) { - CAROM_VERIFY(point.dim() == d_parameter_points[0].dim()); double closest_dist_to_points = INT_MAX; diff --git a/lib/algo/manifold_interp/VectorInterpolator.cpp b/lib/algo/manifold_interp/VectorInterpolator.cpp index c11f4d8dd..7b09dcd62 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.cpp +++ b/lib/algo/manifold_interp/VectorInterpolator.cpp @@ -104,7 +104,7 @@ Vector* VectorInterpolator::obtainLogInterpolatedVector( return obtainInterpolatedVector(d_gammas, d_lambda_T, d_interp_method, rbf); } -Vector* VectorInterpolator::interpolate(Vector* point) +std::shared_ptr VectorInterpolator::interpolate(Vector* point) { if (d_gammas.size() == 0) { @@ -139,8 +139,9 @@ Vector* VectorInterpolator::interpolate(Vector* point) Vector* log_interpolated_vector = obtainLogInterpolatedVector(rbf); // The exp mapping is X + the interpolated gamma - Vector* interpolated_vector = d_rotated_reduced_vectors[d_ref_point]->plus( - log_interpolated_vector); + std::shared_ptr interpolated_vector = + d_rotated_reduced_vectors[d_ref_point]->plus( + *log_interpolated_vector); delete log_interpolated_vector; return interpolated_vector; } diff --git a/lib/algo/manifold_interp/VectorInterpolator.h b/lib/algo/manifold_interp/VectorInterpolator.h index a1fdf5fe3..fb213ff5c 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.h +++ b/lib/algo/manifold_interp/VectorInterpolator.h @@ -14,6 +14,7 @@ #define included_VectorInterpolator_h #include "Interpolator.h" +#include #include #include @@ -68,7 +69,7 @@ class VectorInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - Vector* interpolate(Vector* point); + std::shared_ptr interpolate(Vector* point); private: diff --git a/lib/linalg/BasisGenerator.cpp b/lib/linalg/BasisGenerator.cpp index 9e2cec4ae..fa5cda5f6 100644 --- a/lib/linalg/BasisGenerator.cpp +++ b/lib/linalg/BasisGenerator.cpp @@ -227,7 +227,7 @@ BasisGenerator::computeNextSampleTime( Vector* l = basis->transposeMult(u_vec); // basisl = basis * l - Vector* basisl = basis->mult(l); + Vector* basisl = basis->mult(*l); // Compute u - basisl. Vector* eta = u_vec.minus(basisl); @@ -240,7 +240,7 @@ BasisGenerator::computeNextSampleTime( l = basis->transposeMult(rhs_vec); // basisl = basis * l - basisl = basis->mult(l); + basisl = basis->mult(*l); // Compute rhs - basisl. Vector* eta_dot = rhs_vec.minus(basisl); diff --git a/lib/linalg/Matrix.h b/lib/linalg/Matrix.h index 68414b4dc..7bcb092b8 100644 --- a/lib/linalg/Matrix.h +++ b/lib/linalg/Matrix.h @@ -380,30 +380,6 @@ class Matrix return result; } - /** - * @brief Multiplies this Matrix with other and returns the product, - * pointer version. - * - * Supports multiplication of an undistributed Matrix and Vector - * returning an undistributed Vector, and multiplication of a distributed - * Matrix and an undistributed Vector returning a distributed Vector. - * - * @pre other != 0 - * @pre !other->distributed() - * @pre numColumns() == other->dim() - * - * @param[in] other The Vector to multiply with this. - * - * @return The product Vector. - */ - Vector* - mult( - const Vector* other) const - { - CAROM_VERIFY(other != 0); - return mult(*other); - } - /** * @brief Multiplies this Matrix with other and fills result with the * answer. diff --git a/lib/linalg/Vector.cpp b/lib/linalg/Vector.cpp index 490ee31ca..7cb11ff6b 100644 --- a/lib/linalg/Vector.cpp +++ b/lib/linalg/Vector.cpp @@ -164,21 +164,6 @@ Vector::transform(Vector& result, transformer(d_dim, result.d_vec); } -void -Vector::transform(Vector*& result, - std::function transformer) const { - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_dim, d_distributed); - } - else { - result->setSize(d_dim); - result->d_distributed = d_distributed; - } - transformer(d_dim, result->d_vec); -} - Vector& Vector::transform( std::function @@ -200,24 +185,6 @@ Vector::transform(Vector& result, delete origVector; } -void -Vector::transform(Vector*& result, - std::function - transformer) const { - // If the result has not been allocated then do so. Otherwise size it - // correctly. - Vector* origVector = new Vector(*this); - if (result == 0) { - result = new Vector(d_dim, d_distributed); - } - else { - result->setSize(d_dim); - result->d_distributed = d_distributed; - } - transformer(d_dim, origVector->d_vec, result->d_vec); - delete origVector; -} - double Vector::inner_product( const Vector& other) const @@ -248,7 +215,7 @@ Vector::norm() const double Vector::norm2() const { - double norm2 = inner_product(this); + double norm2 = inner_product(*this); return norm2; } @@ -262,30 +229,6 @@ Vector::normalize() return Norm; } -void -Vector::plus( - const Vector& other, - Vector*& result) const -{ - CAROM_ASSERT(result == 0 || result->distributed() == distributed()); - CAROM_ASSERT(distributed() == other.distributed()); - CAROM_VERIFY(dim() == other.dim()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_dim, d_distributed); - } - else { - result->setSize(d_dim); - } - - // Do the addition. - for (int i = 0; i < d_dim; ++i) { - result->d_vec[i] = d_vec[i] + other.d_vec[i]; - } -} - void Vector::plus( const Vector& other, diff --git a/lib/linalg/Vector.h b/lib/linalg/Vector.h index 0f7624f65..72d3b6c94 100644 --- a/lib/linalg/Vector.h +++ b/lib/linalg/Vector.h @@ -16,6 +16,7 @@ #define included_Vector_h #include "utils/Utilities.h" +#include #include #include @@ -204,21 +205,6 @@ class Vector std::function transformer) const; - /** - * @brief Transform a vector using a supplied function and store the - * results in another vector. - * - * @param[out] result A vector which will store the transformed result. - * - * @param[in] transformer A transformer function which takes in as input a - * size and transforms the origVector and stores the result in - * resultVector. - */ - void - transform(Vector*& result, - std::function - transformer) const; - /** * @brief Sets the length of the vector and reallocates storage if * needed. All values are initialized to zero. @@ -228,8 +214,7 @@ class Vector * the Vector on this processor. */ void - setSize( - int dim) + setSize(int dim) { if (dim > d_alloc_size) { if (!d_owns_data) { @@ -284,27 +269,6 @@ class Vector inner_product( const Vector& other) const; - /** - * @brief Inner product, pointer version. - * - * For distributed Vectors this is a parallel operation. - * - * @pre other != 0 - * @pre dim() == other->dim() - * @pre distributed() == other->distributed() - * - * @param[in] other The Vector to form the inner product with this. - * - * @return The inner product of this and other. - */ - double - inner_product( - const Vector* other) const - { - CAROM_VERIFY(other != 0); - return inner_product(*other); - } - /** * @brief Form the norm of this. * @@ -345,52 +309,14 @@ class Vector * * @return this + other */ - Vector* - plus( - const Vector& other) const - { - Vector* result = 0; - plus(other, result); - return result; - } - - /** - * @brief Adds other and this and returns the result, pointer version. - * - * @pre other != 0 - * @pre distributed() == other->distributed() - * @pre dim() == other->dim() - * - * @param[in] other The other summand. - * - * @return this + other - */ - Vector* - plus( - const Vector* other) const + std::unique_ptr + plus(const Vector& other) const { - CAROM_VERIFY(other != 0); - return plus(*other); + Vector *result = new Vector(d_dim, d_distributed); + plus(other, *result); + return std::unique_ptr(result); } - /** - * @brief Adds other and this and fills result with the answer. - * - * Result will be allocated if unallocated or resized appropriately if - * already allocated. - * - * @pre result == 0 || result->distributed() == distributed() - * @pre distributed() == other.distributed() - * @pre dim() == other.dim() - * - * @param[in] other The other summand. - * @param[out] result this + other - */ - void - plus( - const Vector& other, - Vector*& result) const; - /** * @brief Adds other and this and fills result with the answer. * diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index 5c5e912c4..556a411aa 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -288,13 +288,13 @@ IncrementalSVD::buildIncrementalSVD( Vector* l = d_basis->transposeMult(u_vec); // basisl = basis * l - Vector* basisl = d_basis->mult(l); + Vector* basisl = d_basis->mult(*l); // Computing as k = sqrt(u.u - 2.0*l.l + basisl.basisl) // results in catastrophic cancellation, and must be avoided. // Instead we compute as k = sqrt((u-basisl).(u-basisl)). Vector* e_proj = u_vec.minus(basisl); - double k = e_proj->inner_product(e_proj); + double k = e_proj->inner_product(*e_proj); delete e_proj; if (k <= 0) { diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index b4648ab58..de32c67c1 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -148,8 +148,13 @@ IncrementalSVDBrand::buildIncrementalSVD( // (accurate down to the machine precision) Vector u_vec(u, d_dim, true); Vector e_proj(u, d_dim, true); - e_proj -= *(d_U->mult(d_U->transposeMult(e_proj))); // Gram-Schmidt - e_proj -= *(d_U->mult(d_U->transposeMult(e_proj))); // Re-orthogonalization + + Vector *tmp = d_U->transposeMult(e_proj); + + e_proj -= *(d_U->mult(*tmp)); // Gram-Schmidt + e_proj -= *(d_U->mult(*tmp)); // Re-orthogonalization + + delete tmp; double k = e_proj.inner_product(e_proj); if (k <= 0) { From 601372e7a16890bdd65fd041854ae39546eec04e Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 10 Jul 2024 22:16:49 -0700 Subject: [PATCH 02/19] Update unit tests. --- unit_tests/test_Matrix.cpp | 2 +- unit_tests/test_Vector.cpp | 243 +++++++++---------------------------- 2 files changed, 57 insertions(+), 188 deletions(-) diff --git a/unit_tests/test_Matrix.cpp b/unit_tests/test_Matrix.cpp index 4fe5a35ed..7ee71c623 100644 --- a/unit_tests/test_Matrix.cpp +++ b/unit_tests/test_Matrix.cpp @@ -1560,7 +1560,7 @@ TEST(MatrixSerialTest, Test_mult_Vector_pointer) * */ CAROM::Vector *w; - w = asymmetric_matrix.mult(v); + w = asymmetric_matrix.mult(*v); EXPECT_FALSE(w->distributed()); EXPECT_EQ(w->dim(), 2); EXPECT_DOUBLE_EQ((*w)(0), 2.0); diff --git a/unit_tests/test_Vector.cpp b/unit_tests/test_Vector.cpp index 45ab890a2..2c4d5a688 100644 --- a/unit_tests/test_Vector.cpp +++ b/unit_tests/test_Vector.cpp @@ -309,75 +309,6 @@ TEST(VectorSerialTest, Test_inner_product_const_reference) EXPECT_DOUBLE_EQ(y.inner_product(y), 169); } -TEST(VectorSerialTest, Test_inner_product_const_pointer) -{ - CAROM::Vector *v = new CAROM::Vector(2, false); - (*v)(0) = 1; - (*v)(1) = 1; - CAROM::Vector *w = new CAROM::Vector(2, false); - (*w)(0) = -1; - (*w)(1) = 1; - CAROM::Vector *x = new CAROM::Vector(2, false); - (*x)(0) = 3; - (*x)(1) = 4; - CAROM::Vector *y = new CAROM::Vector(2, false); - (*y)(0) = 5; - (*y)(1) = 12; - - /* [ 1, 1]^{T} [ 1, 1] = 2 */ - EXPECT_DOUBLE_EQ(v->inner_product(v), 2); - - /* [ 1, 1]^{T} [-1, 1] = 0 */ - EXPECT_DOUBLE_EQ(v->inner_product(w), 0); - - /* [ 1, 1]^{T} [ 3, 4] = 7 */ - EXPECT_DOUBLE_EQ(v->inner_product(x), 7); - - /* [ 1, 1]^{T} [ 5, 12] = 17 */ - EXPECT_DOUBLE_EQ(v->inner_product(y), 17); - - /* [-1, 1]^{T} [ 1, 1] = 0 */ - EXPECT_DOUBLE_EQ(w->inner_product(v), 0); - - /* [-1, 1]^{T} [-1, 1] = 2 */ - EXPECT_DOUBLE_EQ(w->inner_product(w), 2); - - /* [-1, 1]^{T} [ 3, 4] = 1 */ - EXPECT_DOUBLE_EQ(w->inner_product(x), 1); - - /* [-1, 1]^{T} [ 5, 12] = 7 */ - EXPECT_DOUBLE_EQ(w->inner_product(y), 7); - - /* [ 3, 4]^{T} [ 1, 1] = 7 */ - EXPECT_DOUBLE_EQ(x->inner_product(v), 7); - - /* [ 3, 4]^{T} [-1, 1] = 1 */ - EXPECT_DOUBLE_EQ(x->inner_product(w), 1); - - /* [ 3, 4]^{T} [ 3, 4] = 25 */ - EXPECT_DOUBLE_EQ(x->inner_product(x), 25); - - /* [ 3, 4]^{T} [ 5, 12] = 63 */ - EXPECT_DOUBLE_EQ(x->inner_product(y), 63); - - /* [ 5, 12]^{T} [ 1, 1] = 17 */ - EXPECT_DOUBLE_EQ(y->inner_product(v), 17); - - /* [ 5, 12]^{T} [-1, 1] = 7 */ - EXPECT_DOUBLE_EQ(y->inner_product(w), 7); - - /* [ 5, 12]^{T} [ 3, 4] = 63 */ - EXPECT_DOUBLE_EQ(y->inner_product(x), 63); - - /* [ 5, 12]^{T} [ 5, 12] = 169 */ - EXPECT_DOUBLE_EQ(y->inner_product(y), 169); - - delete v; - delete w; - delete x; - delete y; -} - TEST(VectorSerialTest, Test_plus_const_reference) { CAROM::Vector v(2, false); @@ -393,102 +324,41 @@ TEST(VectorSerialTest, Test_plus_const_reference) y(0) = 5; y(1) = 12; - CAROM::Vector *result; - /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ - result = v.plus(v); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(v); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 2); + EXPECT_DOUBLE_EQ((*result)(1), 2); + } /* ( 1, 1) + (-1, 1) = ( 0, 2) */ - result = v.plus(w); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(w); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 0); + EXPECT_DOUBLE_EQ((*result)(1), 2); + } /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ - result = v.plus(x); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 4); - EXPECT_DOUBLE_EQ((*result)(1), 5); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(x); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 4); + EXPECT_DOUBLE_EQ((*result)(1), 5); + } /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ - result = v.plus(y); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 6); - EXPECT_DOUBLE_EQ((*result)(1), 13); - delete result; - result = NULL; -} - -TEST(VectorSerialTest, Test_plus_const_pointer) -{ - CAROM::Vector *v = new CAROM::Vector(2, false); - (*v)(0) = 1; - (*v)(1) = 1; - CAROM::Vector *w = new CAROM::Vector(2, false); - (*w)(0) = -1; - (*w)(1) = 1; - CAROM::Vector *x = new CAROM::Vector(2, false); - (*x)(0) = 3; - (*x)(1) = 4; - CAROM::Vector *y = new CAROM::Vector(2, false); - (*y)(0) = 5; - (*y)(1) = 12; - - CAROM::Vector *result; - - /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ - result = v->plus(v); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - /* ( 1, 1) + (-1, 1) = ( 0, 2) */ - result = v->plus(w); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ - result = v->plus(x); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 4); - EXPECT_DOUBLE_EQ((*result)(1), 5); - delete result; - result = NULL; - - /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ - result = v->plus(y); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 6); - EXPECT_DOUBLE_EQ((*result)(1), 13); - delete result; - result = NULL; - - delete v; - delete w; - delete x; - delete y; + { + std::unique_ptr result = v.plus(y); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 6); + EXPECT_DOUBLE_EQ((*result)(1), 13); + } } /* TODO(oxberry1@llnl.gov): Test cases where pointer already allocated */ @@ -513,43 +383,42 @@ TEST(VectorSerialTest, Test_plus_const_reference_pointer) CAROM::Vector::plus tries to assign to that memory, resulting in a segfault. */ - CAROM::Vector *result = NULL; /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ - v.plus(v, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(v); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 2); + EXPECT_DOUBLE_EQ((*result)(1), 2); + } /* ( 1, 1) + (-1, 1) = ( 0, 2) */ - v.plus(w, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(w); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 0); + EXPECT_DOUBLE_EQ((*result)(1), 2); + } /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ - v.plus(x, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 4); - EXPECT_DOUBLE_EQ((*result)(1), 5); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(x); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 4); + EXPECT_DOUBLE_EQ((*result)(1), 5); + } /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ - v.plus(y, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 6); - EXPECT_DOUBLE_EQ((*result)(1), 13); - delete result; - result = NULL; + { + std::unique_ptr result = v.plus(y); + EXPECT_FALSE(result->distributed()); + EXPECT_EQ(result->dim(), 2); + EXPECT_DOUBLE_EQ((*result)(0), 6); + EXPECT_DOUBLE_EQ((*result)(1), 13); + } } /* From 7e221da23aafdd84ec3c7a9d7c6aacb2cef9071d Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 10 Jul 2024 22:35:43 -0700 Subject: [PATCH 03/19] Bug fix. --- lib/linalg/svd/IncrementalSVDBrand.cpp | 2 ++ 1 file changed, 2 insertions(+) diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index de32c67c1..7b683de59 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -152,6 +152,8 @@ IncrementalSVDBrand::buildIncrementalSVD( Vector *tmp = d_U->transposeMult(e_proj); e_proj -= *(d_U->mult(*tmp)); // Gram-Schmidt + delete tmp; + tmp = d_U->transposeMult(e_proj); e_proj -= *(d_U->mult(*tmp)); // Re-orthogonalization delete tmp; From 1f6df17cdd560a2faacb9da21709255a7b7ab07b Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Thu, 18 Jul 2024 18:27:59 -0700 Subject: [PATCH 04/19] More elimination of raw pointers in Vector class. --- examples/dmd/de_dg_advection_greedy.cpp | 23 +- .../de_parametric_heat_conduction_greedy.cpp | 17 +- examples/dmd/dg_advection.cpp | 6 +- examples/dmd/dg_euler.cpp | 21 +- examples/dmd/heat_conduction.cpp | 7 +- examples/dmd/local_dw_csv.cpp | 18 +- examples/dmd/local_tw_csv.cpp | 16 +- examples/dmd/nonlinear_elasticity.cpp | 14 +- examples/dmd/parametric_dw_csv.cpp | 33 +- examples/dmd/parametric_heat_conduction.cpp | 8 +- examples/dmd/parametric_tw_csv.cpp | 27 +- examples/dmd/wave_equation.cpp | 7 +- lib/algo/AdaptiveDMD.cpp | 11 +- lib/algo/AdaptiveDMD.h | 4 +- lib/algo/DMD.cpp | 29 +- lib/algo/DMD.h | 11 +- lib/algo/DMDc.cpp | 16 +- lib/algo/DMDc.h | 4 +- lib/algo/NonuniformDMD.cpp | 6 +- lib/algo/NonuniformDMD.h | 2 +- lib/algo/SnapshotDMD.cpp | 2 +- lib/algo/SnapshotDMD.h | 7 +- .../manifold_interp/PCHIPInterpolator.cpp | 15 +- lib/algo/manifold_interp/PCHIPInterpolator.h | 11 +- .../manifold_interp/VectorInterpolator.cpp | 19 +- lib/algo/manifold_interp/VectorInterpolator.h | 16 +- lib/linalg/BasisGenerator.cpp | 6 +- lib/linalg/Vector.cpp | 85 +--- lib/linalg/Vector.h | 148 +------ lib/linalg/svd/IncrementalSVD.cpp | 8 +- lib/linalg/svd/IncrementalSVDBrand.cpp | 10 +- unit_tests/test_DMD.cpp | 8 +- unit_tests/test_PCHIPInterpolator.cpp | 7 +- unit_tests/test_Vector.cpp | 397 +----------------- 34 files changed, 176 insertions(+), 843 deletions(-) diff --git a/examples/dmd/de_dg_advection_greedy.cpp b/examples/dmd/de_dg_advection_greedy.cpp index ad7191b20..0f57b95bf 100644 --- a/examples/dmd/de_dg_advection_greedy.cpp +++ b/examples/dmd/de_dg_advection_greedy.cpp @@ -644,10 +644,9 @@ double simulation() } dmd_prediction_timer.Start(); - CAROM::Vector* result_U = dmd_U->predict(t_final); + std::shared_ptr result_U = dmd_U->predict(t_final); dmd_prediction_timer.Stop(); - // 21. Calculate the relative error between the DMD final solution and the true solution. Vector dmd_solution_U(result_U->getData(), result_U->dim()); @@ -668,8 +667,6 @@ double simulation() dmd_prediction_timer.RealTime()); } - delete result_U; - return rel_diff; } @@ -740,8 +737,7 @@ double simulation() // THIS IS LIKE COMPUTING A RESIDUAL. t = t_final - 10.*dt; - CAROM::Vector* carom_tf_u_minus_some = dmd_U->predict(t); - + std::shared_ptr carom_tf_u_minus_some = dmd_U->predict(t); for(int i = 0; i < carom_tf_u_minus_some->dim(); i++) { @@ -749,8 +745,6 @@ double simulation() } u_gf->SetFromTrueDofs(*U); - - delete carom_tf_u_minus_some; } ts.push_back(t); @@ -925,8 +919,7 @@ double simulation() } - CAROM::Vector* result_U = dmd_U->predict(t_final); - + std::shared_ptr result_U = dmd_U->predict(t_final); Vector dmd_solution_U(result_U->getData(), result_U->dim()); @@ -945,8 +938,6 @@ double simulation() << rel_diff << std::endl; } - delete result_U; - if (myid == 0) { printf("Elapsed time for training DMD: %e second\n", @@ -956,7 +947,7 @@ double simulation() else if (online) { dmd_prediction_timer.Start(); - CAROM::Vector* result_U = dmd_U->predict(ts[0]); + std::shared_ptr result_U = dmd_U->predict(ts[0]); Vector initial_dmd_solution_U(result_U->getData(), result_U->dim()); u_gf->SetFromTrueDofs(initial_dmd_solution_U); @@ -972,8 +963,6 @@ double simulation() dmd_visit_dc.Save(); } - delete result_U; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -993,8 +982,6 @@ double simulation() dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_U; } } } @@ -1039,8 +1026,6 @@ double simulation() tot_true_solution_u_norm << std::endl; fout.close(); } - - delete result_U; } // 22. Calculate the relative error as commanded by the greedy algorithm. if (offline) diff --git a/examples/dmd/de_parametric_heat_conduction_greedy.cpp b/examples/dmd/de_parametric_heat_conduction_greedy.cpp index 60e532d87..68db41fad 100644 --- a/examples/dmd/de_parametric_heat_conduction_greedy.cpp +++ b/examples/dmd/de_parametric_heat_conduction_greedy.cpp @@ -467,15 +467,13 @@ double simulation() // compare the final FOM solution to the DMD predicted solution. t = t_final - 10.0 * dt; - CAROM::Vector* carom_tf_u_minus_some = dmd_u->predict(t); + std::shared_ptr carom_tf_u_minus_some = dmd_u->predict(t); Vector tf_u_minus_some(carom_tf_u_minus_some->getData(), carom_tf_u_minus_some->dim()); u = tf_u_minus_some; u_gf.SetFromTrueDofs(u); - - delete carom_tf_u_minus_some; } ts.push_back(t); @@ -683,7 +681,8 @@ double simulation() *true_solution_u, *true_solution_u)); } } - CAROM::Vector* result_u = dmd_u->predict(t_final); + + std::shared_ptr result_u = dmd_u->predict(t_final); Vector dmd_solution_u(result_u->getData(), result_u->dim()); Vector diff_u(true_solution_u->Size()); @@ -699,8 +698,6 @@ double simulation() << rel_diff << std::endl; } - delete result_u; - if (!de && myid == 0) { printf("Elapsed time for training DMD: %e second\n", @@ -730,7 +727,7 @@ double simulation() std::cout << "Predicting temperature using DMD at: " << ts[0] << std::endl; } - CAROM::Vector* result_u = dmd_u->predict(ts[0]); + std::shared_ptr result_u = dmd_u->predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); @@ -746,8 +743,6 @@ double simulation() dmd_visit_dc.Save(); } - delete result_u; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -766,8 +761,6 @@ double simulation() dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_u; } } } @@ -792,8 +785,6 @@ double simulation() printf("Elapsed time for predicting DMD: %e second\n", dmd_prediction_timer.RealTime()); } - - delete result_u; } // 19. Calculate the relative error as commanded by the greedy algorithm. diff --git a/examples/dmd/dg_advection.cpp b/examples/dmd/dg_advection.cpp index 1abdfef3d..008bac3dc 100644 --- a/examples/dmd/dg_advection.cpp +++ b/examples/dmd/dg_advection.cpp @@ -716,7 +716,7 @@ int main(int argc, char *argv[]) std::cout << "Predicting solution using DMD" << std::endl; } - CAROM::Vector* result_u = dmd_U.predict(ts[0]); + std::shared_ptr result_u = dmd_U.predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u->SetFromTrueDofs(initial_dmd_solution_u); @@ -733,8 +733,6 @@ int main(int argc, char *argv[]) dmd_dc->Save(); } - delete result_u; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -748,7 +746,6 @@ int main(int argc, char *argv[]) dmd_dc->SetCycle(i); dmd_dc->SetTime(ts[i]); dmd_dc->Save(); - delete result_u; } } } @@ -788,7 +785,6 @@ int main(int argc, char *argv[]) delete pmesh; delete ode_solver; delete pd; - delete result_u; #ifdef MFEM_USE_ADIOS2 if (adios2) { diff --git a/examples/dmd/dg_euler.cpp b/examples/dmd/dg_euler.cpp index f88d03813..cf5c7eb10 100644 --- a/examples/dmd/dg_euler.cpp +++ b/examples/dmd/dg_euler.cpp @@ -582,10 +582,10 @@ int main(int argc, char *argv[]) std::cout << "Predicting density, momentum, and energy using DMD" << std::endl; } - CAROM::Vector* result_dens = dmd_dens->predict(ts[0]); - CAROM::Vector* result_x_mom = dmd_x_mom->predict(ts[0]); - CAROM::Vector* result_y_mom = dmd_y_mom->predict(ts[0]); - CAROM::Vector* result_e = dmd_e->predict(ts[0]); + std::shared_ptr result_dens = dmd_dens->predict(ts[0]); + std::shared_ptr result_x_mom = dmd_x_mom->predict(ts[0]); + std::shared_ptr result_y_mom = dmd_y_mom->predict(ts[0]); + std::shared_ptr result_e = dmd_e->predict(ts[0]); Vector initial_dmd_solution_dens(result_dens->getData(), result_dens->dim()); Vector initial_dmd_solution_x_mom(result_x_mom->getData(), result_x_mom->dim()); Vector initial_dmd_solution_y_mom(result_y_mom->getData(), result_y_mom->dim()); @@ -604,10 +604,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.Save(); } - delete result_dens; - delete result_x_mom; - delete result_y_mom; - delete result_e; if (visit) { for (int i = 1; i < ts.size(); i++) @@ -630,11 +626,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_dens; - delete result_x_mom; - delete result_y_mom; - delete result_e; } } } @@ -701,10 +692,6 @@ int main(int argc, char *argv[]) // Free the used memory. delete ode_solver; - delete result_dens; - delete result_x_mom; - delete result_y_mom; - delete result_e; delete dmd_dens; delete dmd_x_mom; delete dmd_y_mom; diff --git a/examples/dmd/heat_conduction.cpp b/examples/dmd/heat_conduction.cpp index 3b229a87d..ca95e72dd 100644 --- a/examples/dmd/heat_conduction.cpp +++ b/examples/dmd/heat_conduction.cpp @@ -504,7 +504,7 @@ int main(int argc, char *argv[]) std::cout << "Predicting temperature using DMD" << std::endl; } - CAROM::Vector* result_u = dmd_u->predict(ts[0]); + std::shared_ptr result_u = dmd_u->predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); @@ -517,8 +517,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.Save(); } - delete result_u; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -532,8 +530,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_u; } } } @@ -566,7 +562,6 @@ int main(int argc, char *argv[]) // 16. Free the used memory. delete ode_solver; delete pmesh; - delete result_u; MPI_Finalize(); diff --git a/examples/dmd/local_dw_csv.cpp b/examples/dmd/local_dw_csv.cpp index 9a79c6c16..ba9afc30f 100644 --- a/examples/dmd/local_dw_csv.cpp +++ b/examples/dmd/local_dw_csv.cpp @@ -578,7 +578,7 @@ int main(int argc, char *argv[]) for (int k = 0; k < f_snapshots->numColumns(); ++k) { f_snapshots->getColumn(k, interp_snap); - CAROM::Vector* result = admd->predict(t_init+k*dtc); + std::shared_ptr result = admd->predict(t_init+k*dtc); Vector dmd_solution(result->getData(), dim); Vector true_solution(interp_snap.getData(), dim); @@ -600,7 +600,6 @@ int main(int argc, char *argv[]) cout << "Relative error of DMD prediction for interpolated snapshot #" << k << " is " << rel_error << endl; } - delete result; } if (myid == 0) { @@ -677,7 +676,7 @@ int main(int argc, char *argv[]) << " is read." << endl; } - CAROM::Vector* init_cond = nullptr; + std::shared_ptr init_cond; if (min_idx_snap == -1) { double curr_indicator_val = (indicator_idx.size() == 0) ? tval : @@ -697,13 +696,12 @@ int main(int argc, char *argv[]) cout << "Projecting initial condition at t = " << tval << " for DMD model #0." << endl; } - init_cond = new CAROM::Vector(dim, true); + init_cond.reset(new CAROM::Vector(dim, true)); for (int i = 0; i < dim; ++i) { init_cond->item(i) = sample[i]; } - dmd[curr_window]->projectInitialCondition(init_cond, tval); - delete init_cond; + dmd[curr_window]->projectInitialCondition(init_cond.get(), tval); dmd_preprocess_timer.Stop(); } else @@ -723,7 +721,7 @@ int main(int argc, char *argv[]) " using DMD model #" << curr_window << endl; } dmd_prediction_timer.Start(); - CAROM::Vector* result = dmd[curr_window]->predict(tval); + std::shared_ptr result = dmd[curr_window]->predict(tval); dmd_prediction_timer.Stop(); double curr_indicator_val = (indicator_idx.size() == 0) ? tval : result->item( @@ -764,7 +762,6 @@ int main(int argc, char *argv[]) { t_left = t_offset; } - delete init_cond; } t_offset = (t_left + t_right) / 2.0; } @@ -794,10 +791,8 @@ int main(int argc, char *argv[]) } init_cond = dmd[curr_window]->predict(t_offset); - dmd[curr_window+1]->projectInitialCondition(init_cond, t_offset); - delete init_cond; + dmd[curr_window+1]->projectInitialCondition(init_cond.get(), t_offset); - delete result; curr_window += 1; result = dmd[curr_window]->predict(tval); curr_indicator_val = (indicator_idx.size() == 0) ? tval : result->item( @@ -837,7 +832,6 @@ int main(int argc, char *argv[]) } } } - delete result; if (curr_window == numWindows-1 && curr_indicator_val >= indicator_val[numWindows]) diff --git a/examples/dmd/local_tw_csv.cpp b/examples/dmd/local_tw_csv.cpp index d6356f260..c11ed9bb2 100644 --- a/examples/dmd/local_tw_csv.cpp +++ b/examples/dmd/local_tw_csv.cpp @@ -612,7 +612,7 @@ int main(int argc, char *argv[]) for (int k = 0; k < f_snapshots->numColumns(); ++k) { f_snapshots->getColumn(k, interp_snap); - CAROM::Vector* result = admd->predict(t_init+k*dtc); + std::shared_ptr result = admd->predict(t_init+k*dtc); Vector dmd_solution(result->getData(), dim); Vector true_solution(interp_snap.getData(), dim); @@ -634,7 +634,6 @@ int main(int argc, char *argv[]) cout << "Relative error of DMD prediction for interpolated snapshot #" << k << " is " << rel_error << endl; } - delete result; } if (myid == 0) { @@ -762,7 +761,7 @@ int main(int argc, char *argv[]) if (idx_snap == 0) { dmd_preprocess_timer.Start(); - CAROM::Vector* init_cond = nullptr; + std::shared_ptr init_cond; for (int window = 0; window < numWindows; ++window) { if (myid == 0) @@ -772,7 +771,7 @@ int main(int argc, char *argv[]) } if (window == 0) { - init_cond = new CAROM::Vector(dim, true); + init_cond.reset(new CAROM::Vector(dim, true)); for (int i = 0; i < dim; ++i) { init_cond->item(i) = sample[i]; @@ -782,8 +781,7 @@ int main(int argc, char *argv[]) { init_cond = dmd[window-1]->predict(indicator_val[window]); } - dmd[window]->projectInitialCondition(init_cond); - delete init_cond; + dmd[window]->projectInitialCondition(init_cond.get()); } dmd_preprocess_timer.Stop(); } @@ -801,7 +799,7 @@ int main(int argc, char *argv[]) << " using DMD model #" << curr_window << endl; } dmd_prediction_timer.Start(); - CAROM::Vector* result = dmd[curr_window]->predict(t_final); + std::shared_ptr result = dmd[curr_window]->predict(t_final); dmd_prediction_timer.Stop(); if (myid == 0) { @@ -810,7 +808,6 @@ int main(int argc, char *argv[]) result->getData(), dim); } idx_snap = snap_bound[1]+1; // escape for-loop over idx_snap - delete result; } else // Verify DMD prediction results against dataset { @@ -824,7 +821,7 @@ int main(int argc, char *argv[]) << tval << " using DMD model #" << curr_window << endl; } dmd_prediction_timer.Start(); - CAROM::Vector* result = dmd[curr_window]->predict(tval); + std::shared_ptr result = dmd[curr_window]->predict(tval); dmd_prediction_timer.Stop(); // Calculate the relative error between the DMD final solution and the true solution. @@ -860,7 +857,6 @@ int main(int argc, char *argv[]) } } } - delete result; } } if (myid == 0 && t_final <= 0.0) diff --git a/examples/dmd/nonlinear_elasticity.cpp b/examples/dmd/nonlinear_elasticity.cpp index e409c5b9e..1791f42e8 100644 --- a/examples/dmd/nonlinear_elasticity.cpp +++ b/examples/dmd/nonlinear_elasticity.cpp @@ -627,8 +627,8 @@ int main(int argc, char *argv[]) true_solution_v = v_gf.GetTrueVector(); curr_window = 0; - CAROM::Vector* result_x = dmd_x[curr_window]->predict(ts[0]); - CAROM::Vector* result_v = dmd_v[curr_window]->predict(ts[0]); + std::shared_ptr result_x = dmd_x[curr_window]->predict(ts[0]); + std::shared_ptr result_v = dmd_v[curr_window]->predict(ts[0]); Vector initial_dmd_solution_x(result_x->getData(), result_x->dim()); Vector initial_dmd_solution_v(result_v->getData(), result_v->dim()); x_gf.SetFromTrueDofs(initial_dmd_solution_x); @@ -648,14 +648,11 @@ int main(int argc, char *argv[]) dmd_dc->Save(); } - delete result_x; - delete result_v; - for (int i = 1; i < ts.size(); i++) { if (i == ts.size() - 1 || (i % vis_steps) == 0) { - if(visit) + if (visit) { result_x = dmd_x[curr_window]->predict(ts[i]); result_v = dmd_v[curr_window]->predict(ts[i]); @@ -671,9 +668,6 @@ int main(int argc, char *argv[]) dmd_dc->SetTime(ts[i]); dmd_dc->Save(); pmesh->SwapNodes(nodes, owns_nodes); - - delete result_x; - delete result_v; } if (i % windowNumSamples == 0 && i < ts.size()-1) @@ -723,8 +717,6 @@ int main(int argc, char *argv[]) // 15. Free the used memory. delete ode_solver; delete pmesh; - delete result_x; - delete result_v; delete dc; delete dmd_dc; delete dmd_x[curr_window]; diff --git a/examples/dmd/parametric_dw_csv.cpp b/examples/dmd/parametric_dw_csv.cpp index 7ca9ce830..21c993a40 100644 --- a/examples/dmd/parametric_dw_csv.cpp +++ b/examples/dmd/parametric_dw_csv.cpp @@ -55,7 +55,7 @@ using namespace mfem; void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, std::vector& parameter_points, - std::vector& training_twep, + std::vector>& training_twep, CAROM::Vector* desired_point, std::string rbf, double closest_rbf_val); @@ -268,7 +268,8 @@ int main(int argc, char *argv[]) vector par_dir_list; // DATASET name vector num_train_snap; // DATASET size vector indicator_init, indicator_last; // DATASET indicator range - vector training_twep; // DATASET temporal endpoint + vector> + training_twep; // DATASET temporal endpoint csv_db.getStringVector(string(list_dir) + "/" + train_list + ".csv", training_par_list, false); @@ -534,7 +535,7 @@ int main(int argc, char *argv[]) } CAROM_VERIFY(numWindows == curr_window+1); - training_twep.push_back(twep); + training_twep.push_back(std::shared_ptr(twep)); csv_db.putDoubleArray(outputPath + "/" + par_dir + "_twep.csv", twep->getData(), numWindows+1); @@ -585,7 +586,7 @@ int main(int argc, char *argv[]) CAROM::Vector* twep = new CAROM::Vector(numWindows+1, false); csv_db.getDoubleArray(outputPath + "/" + par_dir + "_twep.csv", twep->getData(), numWindows+1); - training_twep.push_back(twep); + training_twep.push_back(std::shared_ptr(twep)); } par_dir_list.clear(); @@ -722,7 +723,7 @@ int main(int argc, char *argv[]) << " is read." << endl; } - CAROM::Vector* init_cond = nullptr; + std::shared_ptr init_cond; if (min_idx_snap == -1) { if (tval >= twep->item(0)) @@ -742,13 +743,12 @@ int main(int argc, char *argv[]) cout << "Projecting initial condition at t = " << tval << " for DMD model #0." << endl; } - init_cond = new CAROM::Vector(dim, true); + init_cond.reset(new CAROM::Vector(dim, true)); for (int i = 0; i < dim; ++i) { init_cond->item(i) = sample[i]; } - dmd[idx_dataset][curr_window]->projectInitialCondition(init_cond, tval); - delete init_cond; + dmd[idx_dataset][curr_window]->projectInitialCondition(init_cond.get(), tval); dmd_preprocess_timer.Stop(); } else @@ -768,7 +768,8 @@ int main(int argc, char *argv[]) " using DMD model #" << curr_window << endl; } dmd_prediction_timer.Start(); - CAROM::Vector* result = dmd[idx_dataset][curr_window]->predict(tval); + std::shared_ptr result = + dmd[idx_dataset][curr_window]->predict(tval); dmd_prediction_timer.Stop(); while (curr_window+1 < numWindows @@ -806,10 +807,9 @@ int main(int argc, char *argv[]) } init_cond = dmd[idx_dataset][curr_window]->predict(t_offset); - dmd[idx_dataset][curr_window+1]->projectInitialCondition(init_cond, t_offset); - delete init_cond; + dmd[idx_dataset][curr_window+1]->projectInitialCondition(init_cond.get(), + t_offset); - delete result; curr_window += 1; result = dmd[idx_dataset][curr_window]->predict(tval); } @@ -847,7 +847,6 @@ int main(int argc, char *argv[]) } } } - delete result; if (curr_window == numWindows-1 && tval >= twep->item(numWindows)) @@ -893,13 +892,7 @@ int main(int argc, char *argv[]) } } - delete[] sample; - for (int idx_dataset = 0; idx_dataset < training_twep.size(); ++idx_dataset) - { - delete training_twep[idx_dataset]; - } - for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) { delete testing_par_vectors[idx_dataset]; @@ -914,7 +907,7 @@ int main(int argc, char *argv[]) void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, std::vector& parameter_points, - std::vector& training_twep, + std::vector>& training_twep, CAROM::Vector* desired_point, std::string rbf = "G", double closest_rbf_val = 0.9) diff --git a/examples/dmd/parametric_heat_conduction.cpp b/examples/dmd/parametric_heat_conduction.cpp index e50d329c3..2c5ff2412 100644 --- a/examples/dmd/parametric_heat_conduction.cpp +++ b/examples/dmd/parametric_heat_conduction.cpp @@ -796,7 +796,7 @@ int main(int argc, char *argv[]) std::cout << "Predicting temperature using DMD at: " << ts[0] << std::endl; } - CAROM::Vector* result_u = dmd_u->predict(ts[0]); + std::shared_ptr result_u = dmd_u->predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); @@ -812,8 +812,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.Save(); } - delete result_u; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -832,8 +830,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_u; } } } @@ -858,8 +854,6 @@ int main(int argc, char *argv[]) printf("Elapsed time for predicting DMD: %e second\n", dmd_prediction_timer.RealTime()); } - - delete result_u; } if (myid == 0) diff --git a/examples/dmd/parametric_tw_csv.cpp b/examples/dmd/parametric_tw_csv.cpp index 1b132f8d9..babcf8987 100644 --- a/examples/dmd/parametric_tw_csv.cpp +++ b/examples/dmd/parametric_tw_csv.cpp @@ -761,10 +761,9 @@ int main(int argc, char *argv[]) << indicator_val[window] + offset_indicator * tvec[snap_bound[0]] << " for DMD model #" << window << endl; } - CAROM::Vector* init_cond = dmd[idx_dataset][window-1]->predict( - indicator_val[window]); - dmd[idx_dataset][window]->projectInitialCondition(init_cond); - delete init_cond; + std::shared_ptr init_cond = dmd[idx_dataset][window-1]->predict( + indicator_val[window]); + dmd[idx_dataset][window]->projectInitialCondition(init_cond.get()); } // Make a directory for this window, only on the first parameter. @@ -978,10 +977,10 @@ int main(int argc, char *argv[]) << indicator_val[window] + offset_indicator * tvec[snap_bound[0]] << " for DMD model #" << window << endl; } - CAROM::Vector* init_cond = nullptr; + std::shared_ptr init_cond; if (window == 0) { - init_cond = new CAROM::Vector(dim, true); + init_cond.reset(new CAROM::Vector(dim, true)); for (int i = 0; i < dim; ++i) { init_cond->item(i) = sample[i]; @@ -991,7 +990,7 @@ int main(int argc, char *argv[]) { init_cond = dmd[idx_dataset][window-1]->predict(indicator_val[window]); } - dmd[idx_dataset][window]->projectInitialCondition(init_cond); + dmd[idx_dataset][window]->projectInitialCondition(init_cond.get()); const double norm_init_cond = init_cond->norm(); if (myid == 0) @@ -1001,8 +1000,6 @@ int main(int argc, char *argv[]) << window - 1 << endl; } - delete init_cond; - if (window > 0 && indicator_val[window] < t_final) { // To save memory, delete dmd[idx_dataset][window] for windows @@ -1142,8 +1139,8 @@ int main(int argc, char *argv[]) } dmd_prediction_timer.Start(); - CAROM::Vector* result = dmd[idx_dataset][curr_window]->predict( - t_final - offset_indicator * tvec[snap_bound[0]]); + std::shared_ptr result = dmd[idx_dataset][curr_window]->predict( + t_final - offset_indicator * tvec[snap_bound[0]]); dmd_prediction_timer.Stop(); if (myid == 0) @@ -1159,7 +1156,6 @@ int main(int argc, char *argv[]) } idx_snap = snap_bound[1]+1; // escape for-loop over idx_snap - delete result; } else // Verify DMD prediction results against dataset { @@ -1177,8 +1173,9 @@ int main(int argc, char *argv[]) } dmd_prediction_timer.Start(); - CAROM::Vector* result = dmd[idx_dataset][curr_window]->predict( - tval - offset_indicator * tvec[snap_bound[0]]); + std::shared_ptr result = + dmd[idx_dataset][curr_window]->predict( + tval - offset_indicator * tvec[snap_bound[0]]); dmd_prediction_timer.Stop(); // Calculate the relative error between the DMD final solution and the true solution. @@ -1227,8 +1224,6 @@ int main(int argc, char *argv[]) { hdf_db->putDoubleArray(snap, result->getData(), dim); } - - delete result; } } if (myid == 0 && t_final <= 0.0) diff --git a/examples/dmd/wave_equation.cpp b/examples/dmd/wave_equation.cpp index d90316863..a05bf9205 100644 --- a/examples/dmd/wave_equation.cpp +++ b/examples/dmd/wave_equation.cpp @@ -597,7 +597,7 @@ int main(int argc, char *argv[]) // 10. Predict using DMD. cout << "Predicting temperature using DMD" << endl; - CAROM::Vector* result_u = nullptr; + std::shared_ptr result_u; VisItDataCollection dmd_visit_dc(io_dir+"/DMD_Wave_Equation", mesh); dmd_visit_dc.RegisterField("solution", &u_gf); curr_window = 0; @@ -608,7 +608,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(0); dmd_visit_dc.SetTime(0.0); dmd_visit_dc.Save(); - delete result_u; } for (int i = 1; i < ts.size(); i++) @@ -623,7 +622,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - delete result_u; } if (i % windowNumSamples == 0 && i < ts.size()-1) @@ -632,7 +630,7 @@ int main(int argc, char *argv[]) { result_u = dmd_u[curr_window]->predict(ts[i]); cout << "Projecting solution for new window at " << ts[i] << endl; - dmd_u[curr_window+1]->projectInitialCondition(result_u, ts[i]); + dmd_u[curr_window+1]->projectInitialCondition(result_u.get(), ts[i]); } delete dmd_u[curr_window]; curr_window++; @@ -662,7 +660,6 @@ int main(int argc, char *argv[]) // 12. Free the used memory. delete ode_solver; delete mesh; - delete result_u; delete dmd_u[curr_window]; return 0; } diff --git a/lib/algo/AdaptiveDMD.cpp b/lib/algo/AdaptiveDMD.cpp index a2d765019..7619ca1b7 100644 --- a/lib/algo/AdaptiveDMD.cpp +++ b/lib/algo/AdaptiveDMD.cpp @@ -36,14 +36,6 @@ AdaptiveDMD::AdaptiveDMD(int dim, double desired_dt, std::string rbf, d_closest_rbf_val = closest_rbf_val; } -AdaptiveDMD::~AdaptiveDMD() -{ - for (auto interp_snapshot : d_interp_snapshots) - { - delete interp_snapshot; - } -} - void AdaptiveDMD::train(double energy_fraction, const Matrix* W0, double linearity_tol) { @@ -139,7 +131,8 @@ void AdaptiveDMD::interpolateSnapshots() // Obtain the interpolated snapshot. CAROM::Vector* curr_interpolated_snapshot = obtainInterpolatedVector( d_snapshots, f_T, d_interp_method, rbf); - d_interp_snapshots.push_back(curr_interpolated_snapshot); + d_interp_snapshots.push_back(std::shared_ptr + (curr_interpolated_snapshot)); delete point; } diff --git a/lib/algo/AdaptiveDMD.h b/lib/algo/AdaptiveDMD.h index 1a7598928..b7166a476 100644 --- a/lib/algo/AdaptiveDMD.h +++ b/lib/algo/AdaptiveDMD.h @@ -62,7 +62,7 @@ class AdaptiveDMD : public DMD /** * @brief Destroy the AdaptiveDMD object */ - ~AdaptiveDMD(); + ~AdaptiveDMD() { } /** * @param[in] energy_fraction The energy fraction to keep after doing SVD. @@ -126,7 +126,7 @@ class AdaptiveDMD : public DMD /** * @brief std::vector holding the interpolated snapshots. */ - std::vector d_interp_snapshots; + std::vector> d_interp_snapshots; /** * @brief Internal function to obtain the interpolated snapshots. diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index 2ea11e77e..ad025b3b0 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -129,10 +129,6 @@ DMD::DMD(std::vector> eigs, Matrix* phi_real, DMD::~DMD() { - for (auto snapshot : d_snapshots) - { - delete snapshot; - } for (auto sampled_time : d_sampled_times) { delete sampled_time; @@ -144,7 +140,6 @@ DMD::~DMD() delete d_phi_imaginary; delete d_phi_real_squared_inverse; delete d_phi_imaginary_squared_inverse; - delete d_projected_init_imaginary; } void DMD::setOffset(Vector* offset_vector, int order) @@ -177,8 +172,6 @@ void DMD::takeSample(double* u_in, double t) { if (d_rank == 0) std::cout << "Removing existing snapshot at time: " << d_t_offset + d_sampled_times.back()->item(0) << std::endl; - Vector* last_snapshot = d_snapshots.back(); - delete last_snapshot; d_snapshots.pop_back(); d_sampled_times.pop_back(); } @@ -193,7 +186,7 @@ void DMD::takeSample(double* u_in, double t) CAROM_VERIFY(d_sampled_times.back()->item(0) < t); } - d_snapshots.push_back(sample); + d_snapshots.push_back(std::shared_ptr(sample)); Vector* sampled_time = new Vector(&t, 1, false); d_sampled_times.push_back(sampled_time); @@ -616,7 +609,7 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) Vector* d_projected_init_imaginary_2 = d_phi_imaginary_squared_inverse->mult( *rhs_real); d_projected_init_imaginary = d_projected_init_imaginary_2->minus( - d_projected_init_imaginary_1); + *d_projected_init_imaginary_1); delete d_phi_real_squared_2; delete d_projected_init_real_1; @@ -640,7 +633,7 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) d_init_projected = true; } -Vector* +std::shared_ptr DMD::predict(double t, int deg) { CAROM_VERIFY(d_trained); @@ -658,9 +651,10 @@ DMD::predict(double t, int deg) Vector* d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( *d_projected_init_imaginary); - Vector* d_predicted_state_real = d_predicted_state_real_1->minus( - d_predicted_state_real_2); - addOffset(d_predicted_state_real, t, deg); + std::shared_ptr d_predicted_state_real = + d_predicted_state_real_1->minus( + *d_predicted_state_real_2); + addOffset(*d_predicted_state_real, t, deg); delete d_phi_mult_eigs_real; delete d_phi_mult_eigs_imaginary; @@ -671,11 +665,11 @@ DMD::predict(double t, int deg) } void -DMD::addOffset(Vector*& result, double t, int deg) +DMD::addOffset(Vector & result, double t, int deg) { if (d_state_offset) { - *result += *d_state_offset; + result += *d_state_offset; } } @@ -731,7 +725,8 @@ DMD::getSnapshotMatrix() } const Matrix* -DMD::createSnapshotMatrix(std::vector snapshots) +DMD::createSnapshotMatrix(const std::vector> & + snapshots) { CAROM_VERIFY(snapshots.size() > 0); CAROM_VERIFY(snapshots[0]->dim() > 0); @@ -824,7 +819,7 @@ DMD::load(std::string base_file_name) d_projected_init_real->read(full_file_name); full_file_name = base_file_name + "_projected_init_imaginary"; - d_projected_init_imaginary = new Vector(); + d_projected_init_imaginary.reset(new Vector()); d_projected_init_imaginary->read(full_file_name); full_file_name = base_file_name + "_state_offset"; diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index d5cd7b5f9..e573b54f5 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -151,7 +151,7 @@ class DMD * @param[in] t The time of the output state * @param[in] deg The derivative degree of the output state */ - Vector* predict(double t, int deg = 0); + std::shared_ptr predict(double t, int deg = 0); /** * @brief Get the time offset contained within d_t_offset. @@ -320,12 +320,13 @@ class DMD /** * @brief Add the appropriate offset when predicting the solution. */ - virtual void addOffset(Vector*& result, double t = 0.0, int deg = 0); + virtual void addOffset(Vector & result, double t = 0.0, int deg = 0); /** * @brief Get the snapshot matrix contained within d_snapshots. */ - const Matrix* createSnapshotMatrix(std::vector snapshots); + const Matrix* createSnapshotMatrix(const std::vector> & + snapshots); /** * @brief The rank of the process this object belongs to. @@ -355,7 +356,7 @@ class DMD /** * @brief std::vector holding the snapshots. */ - std::vector d_snapshots; + std::vector> d_snapshots; /** * @brief The stored times of each sample. @@ -440,7 +441,7 @@ class DMD /** * @brief The imaginary part of the projected initial condition. */ - Vector* d_projected_init_imaginary = NULL; + std::shared_ptr d_projected_init_imaginary = NULL; /** * @brief A vector holding the complex eigenvalues of the eigenmodes. diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index d92da293d..09097e415 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -150,7 +150,6 @@ DMDc::~DMDc() delete d_phi_imaginary; delete d_phi_real_squared_inverse; delete d_phi_imaginary_squared_inverse; - delete d_projected_init_imaginary; } void DMDc::setOffset(Vector* offset_vector) @@ -668,7 +667,7 @@ DMDc::project(const Vector* init, const Matrix* controls, double t_offset) Vector* d_projected_init_imaginary_2 = d_phi_imaginary_squared_inverse->mult( *init_real); d_projected_init_imaginary = d_projected_init_imaginary_2->minus( - d_projected_init_imaginary_1); + *d_projected_init_imaginary_1); delete init_real; delete init_imaginary; @@ -733,9 +732,9 @@ DMDc::predict(double t) Vector* d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( *d_projected_init_imaginary); - Vector* d_predicted_state_real = d_predicted_state_real_1->minus( - d_predicted_state_real_2); - addOffset(d_predicted_state_real); + std::unique_ptr d_predicted_state_real = + d_predicted_state_real_1->minus(*d_predicted_state_real_2); + addOffset(*d_predicted_state_real); delete d_phi_mult_eigs_real; delete d_phi_mult_eigs_imaginary; @@ -768,15 +767,14 @@ DMDc::predict(double t) delete f_control_real; delete f_control_imaginary; - return d_predicted_state_real; } void -DMDc::addOffset(Vector*& result) +DMDc::addOffset(Vector & result) { if (d_state_offset) { - *result += *d_state_offset; + result += *d_state_offset; } } @@ -925,7 +923,7 @@ DMDc::load(std::string base_file_name) d_projected_init_real->read(full_file_name); full_file_name = base_file_name + "_projected_init_imaginary"; - d_projected_init_imaginary = new Vector(); + d_projected_init_imaginary.reset(new Vector()); d_projected_init_imaginary->read(full_file_name); full_file_name = base_file_name + "_state_offset"; diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index 7a8c4e642..6dc604256 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -291,7 +291,7 @@ class DMDc /** * @brief Add the state offset when predicting the solution. */ - virtual void addOffset(Vector*& result); + virtual void addOffset(Vector & result); /** * @brief Get the snapshot matrix contained within d_snapshots. @@ -421,7 +421,7 @@ class DMDc /** * @brief The imaginary part of the projected initial condition. */ - Vector* d_projected_init_imaginary = NULL; + std::shared_ptr d_projected_init_imaginary; /** * @brief The real part of the projected controls. diff --git a/lib/algo/NonuniformDMD.cpp b/lib/algo/NonuniformDMD.cpp index 9a0454322..72b25b276 100644 --- a/lib/algo/NonuniformDMD.cpp +++ b/lib/algo/NonuniformDMD.cpp @@ -115,7 +115,7 @@ NonuniformDMD::computeEigExp(std::complex eig, double t) } void -NonuniformDMD::addOffset(Vector*& result, double t, int deg) +NonuniformDMD::addOffset(Vector & result, double t, int deg) { CAROM_VERIFY(deg == 0 || deg == 1); if (deg == 0) @@ -123,14 +123,14 @@ NonuniformDMD::addOffset(Vector*& result, double t, int deg) DMD::addOffset(result); if (d_derivative_offset) { - result->plusAx(t, *d_derivative_offset); + result.plusAx(t, *d_derivative_offset); } } else { if (d_derivative_offset) { - *result += *d_derivative_offset; + result += *d_derivative_offset; } } } diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index 50761c6b2..bd56532c9 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -171,7 +171,7 @@ class NonuniformDMD : public DMD /** * @brief Add the appropriate offset when predicting the solution. */ - void addOffset(Vector*& result, double t, int deg) override; + void addOffset(Vector & result, double t, int deg) override; /** * @brief Derivative offset in snapshot. diff --git a/lib/algo/SnapshotDMD.cpp b/lib/algo/SnapshotDMD.cpp index cc7e78007..b3915061d 100644 --- a/lib/algo/SnapshotDMD.cpp +++ b/lib/algo/SnapshotDMD.cpp @@ -51,7 +51,7 @@ void SnapshotDMD::train(double energy_fraction, const Matrix* W0, void SnapshotDMD::interpolateToNSnapshots(int n) { PCHIPInterpolator* interp = new PCHIPInterpolator(); - std::vector new_snapshots; + std::vector> new_snapshots; std::vector new_times; interp->interpolate(d_sampled_times,d_snapshots,n,new_times,new_snapshots); diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index 404147a42..bc010f052 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -72,10 +72,9 @@ class SnapshotDMD : public DMD /** * @brief Returns a copy of the current snapshot vector "d_snapshots" */ - std::vector getSnapshotVectors() + std::vector> getSnapshotVectors() { - std::vector return_snapshots(d_snapshots); - return return_snapshots; + return d_snapshots; } protected: /** @@ -128,4 +127,4 @@ class SnapshotDMD : public DMD private: }; } -#endif \ No newline at end of file +#endif diff --git a/lib/algo/manifold_interp/PCHIPInterpolator.cpp b/lib/algo/manifold_interp/PCHIPInterpolator.cpp index dc0191a32..8dc07f81d 100644 --- a/lib/algo/manifold_interp/PCHIPInterpolator.cpp +++ b/lib/algo/manifold_interp/PCHIPInterpolator.cpp @@ -33,9 +33,9 @@ using namespace std; namespace CAROM { void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, - std::vector& snapshots, + std::vector>& snapshots, std::vector& output_ts, - std::vector& output_snapshots) + std::vector>& output_snapshots) { CAROM_VERIFY(snapshot_ts.size() == snapshots.size()); CAROM_VERIFY(snapshot_ts.size() > 2); @@ -60,7 +60,7 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, { Vector* temp_snapshot = new Vector(snapshots[0]->dim(), snapshots[0]->distributed()); - output_snapshots.push_back(temp_snapshot); + output_snapshots.push_back(std::shared_ptr(temp_snapshot)); } for(int i = 0; i < n_dim; ++i) @@ -134,12 +134,11 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, } } -void PCHIPInterpolator::interpolate(std::vector& - snapshot_ts, - std::vector& snapshots, +void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, + std::vector>& snapshots, int n_out, std::vector& output_ts, - std::vector& output_snapshots) + std::vector>& output_snapshots) { CAROM_VERIFY(snapshot_ts.size() == snapshots.size()); CAROM_VERIFY(snapshot_ts.size() > 0); @@ -219,4 +218,4 @@ int PCHIPInterpolator::sign(double a) const return 0; } -} \ No newline at end of file +} diff --git a/lib/algo/manifold_interp/PCHIPInterpolator.h b/lib/algo/manifold_interp/PCHIPInterpolator.h index 4fd2e7014..e0415d207 100644 --- a/lib/algo/manifold_interp/PCHIPInterpolator.h +++ b/lib/algo/manifold_interp/PCHIPInterpolator.h @@ -3,6 +3,7 @@ #include #include +#include namespace CAROM { @@ -38,9 +39,9 @@ class PCHIPInterpolator * from snapshot_ts */ void interpolate(std::vector& snapshot_ts, - std::vector& snapshots, + std::vector>& snapshots, std::vector& output_ts, - std::vector&output_snapshots); + std::vector>& output_snapshots); /** * @brief Compute new snapshots interpolated from snapshot_ts to @@ -56,10 +57,10 @@ class PCHIPInterpolator * from snapshot_ts */ void interpolate(std::vector& snapshot_ts, - std::vector& snapshots, + std::vector>& snapshots, int n_out, std::vector& output_ts, - std::vector& output_snapshots); + std::vector>& output_snapshots); private: @@ -74,4 +75,4 @@ class PCHIPInterpolator }; } -#endif \ No newline at end of file +#endif diff --git a/lib/algo/manifold_interp/VectorInterpolator.cpp b/lib/algo/manifold_interp/VectorInterpolator.cpp index 7b09dcd62..3b984cb64 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.cpp +++ b/lib/algo/manifold_interp/VectorInterpolator.cpp @@ -84,9 +84,6 @@ VectorInterpolator::~VectorInterpolator() delete d_rotated_reduced_vectors[i]; } } - - for (auto v : d_gammas) - delete v; } void VectorInterpolator::obtainLambda() @@ -116,13 +113,13 @@ std::shared_ptr VectorInterpolator::interpolate(Vector* point) { Vector* gamma = new Vector(d_rotated_reduced_vectors[d_ref_point]->dim(), d_rotated_reduced_vectors[d_ref_point]->distributed()); - d_gammas.push_back(gamma); + d_gammas.push_back(std::shared_ptr(gamma)); } else { // Gamma is Y - X - Vector* gamma = d_rotated_reduced_vectors[i]->minus( - *d_rotated_reduced_vectors[d_ref_point]); + std::shared_ptr gamma = d_rotated_reduced_vectors[i]->minus( + *d_rotated_reduced_vectors[d_ref_point]); d_gammas.push_back(gamma); } } @@ -146,7 +143,8 @@ std::shared_ptr VectorInterpolator::interpolate(Vector* point) return interpolated_vector; } -Vector* obtainInterpolatedVector(std::vector data, Matrix* f_T, +Vector* obtainInterpolatedVector(const std::vector> & + data, Matrix* f_T, std::string interp_method, std::vector& rbf) { Vector* interpolated_vector = new Vector(data[0]->dim(), @@ -187,9 +185,10 @@ Vector* obtainInterpolatedVector(std::vector data, Matrix* f_T, return interpolated_vector; } -Matrix* solveLinearSystem(std::vector parameter_points, - std::vector data, std::string interp_method, - std::string rbf, double& epsilon) +Matrix* solveLinearSystem(const std::vector & parameter_points, + const std::vector> & data, + std::string interp_method, + std::string rbf, double & epsilon) { int mpi_init, rank; MPI_Initialized(&mpi_init); diff --git a/lib/algo/manifold_interp/VectorInterpolator.h b/lib/algo/manifold_interp/VectorInterpolator.h index fb213ff5c..f00c1223f 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.h +++ b/lib/algo/manifold_interp/VectorInterpolator.h @@ -116,16 +116,18 @@ class VectorInterpolator : public Interpolator /** * @brief The reduced elements in tangential space. */ - std::vector d_gammas; + std::vector> d_gammas; }; -Vector* obtainInterpolatedVector(std::vector data, Matrix* f_T, - std::string interp_method, std::vector& rbf); - -Matrix* solveLinearSystem(std::vector parameter_points, - std::vector data, std::string interp_method, - std::string rbf, double& epsilon); +Vector* obtainInterpolatedVector(const std::vector> & + data, + Matrix* f_T, std::string interp_method, + std::vector& rbf); +Matrix* solveLinearSystem(const std::vector & parameter_points, + const std::vector> & data, + std::string interp_method, + std::string rbf, double & epsilon); } #endif diff --git a/lib/linalg/BasisGenerator.cpp b/lib/linalg/BasisGenerator.cpp index fa5cda5f6..acb10c26e 100644 --- a/lib/linalg/BasisGenerator.cpp +++ b/lib/linalg/BasisGenerator.cpp @@ -230,7 +230,7 @@ BasisGenerator::computeNextSampleTime( Vector* basisl = basis->mult(*l); // Compute u - basisl. - Vector* eta = u_vec.minus(basisl); + std::unique_ptr eta = u_vec.minus(*basisl); delete l; delete basisl; @@ -243,7 +243,7 @@ BasisGenerator::computeNextSampleTime( basisl = basis->mult(*l); // Compute rhs - basisl. - Vector* eta_dot = rhs_vec.minus(basisl); + std::unique_ptr eta_dot = rhs_vec.minus(*basisl); delete l; delete basisl; @@ -257,8 +257,6 @@ BasisGenerator::computeNextSampleTime( local_norm = val; } } - delete eta; - delete eta_dot; if (d_num_procs == 1) { global_norm = local_norm; } diff --git a/lib/linalg/Vector.cpp b/lib/linalg/Vector.cpp index 7cb11ff6b..21f3e58fe 100644 --- a/lib/linalg/Vector.cpp +++ b/lib/linalg/Vector.cpp @@ -121,7 +121,7 @@ Vector& Vector::operator += ( const Vector& rhs) { - CAROM_VERIFY(d_dim == rhs.d_dim); + CAROM_ASSERT(d_dim == rhs.d_dim); for(int i=0; idistributed() == distributed()); - CAROM_ASSERT(distributed() == other.distributed()); - CAROM_VERIFY(dim() == other.dim()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_dim, d_distributed); - } - else { - result->setSize(d_dim); - } - - // Do the addition. - for (int i = 0; i < d_dim; ++i) { - result->d_vec[i] = d_vec[i] + factor*other.d_vec[i]; - } -} - void Vector::plusAx( double factor, @@ -280,7 +255,7 @@ Vector::plusAx( { CAROM_ASSERT(result.distributed() == distributed()); CAROM_ASSERT(distributed() == other.distributed()); - CAROM_VERIFY(dim() == other.dim()); + CAROM_ASSERT(dim() == other.dim()); // Size result correctly. result.setSize(d_dim); @@ -297,7 +272,7 @@ Vector::plusEqAx( const Vector& other) { CAROM_ASSERT(distributed() == other.distributed()); - CAROM_VERIFY(dim() == other.dim()); + CAROM_ASSERT(dim() == other.dim()); // Do the addition. for (int i = 0; i < d_dim; ++i) { @@ -305,30 +280,6 @@ Vector::plusEqAx( } } -void -Vector::minus( - const Vector& other, - Vector*& result) const -{ - CAROM_ASSERT(result == 0 || result->distributed() == distributed()); - CAROM_ASSERT(distributed() == other.distributed()); - CAROM_VERIFY(dim() == other.dim()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_dim, d_distributed); - } - else { - result->setSize(d_dim); - } - - // Do the subtraction. - for (int i = 0; i < d_dim; ++i) { - result->d_vec[i] = d_vec[i] - other.d_vec[i]; - } -} - void Vector::minus( const Vector& other, @@ -336,7 +287,7 @@ Vector::minus( { CAROM_ASSERT(result.distributed() == distributed()); CAROM_ASSERT(distributed() == other.distributed()); - CAROM_VERIFY(dim() == other.dim()); + CAROM_ASSERT(dim() == other.dim()); // Size result correctly. result.setSize(d_dim); @@ -347,28 +298,6 @@ Vector::minus( } } -void -Vector::mult( - double factor, - Vector*& result) const -{ - CAROM_ASSERT(result == 0 || result->distributed() == distributed()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_dim, d_distributed); - } - else { - result->setSize(d_dim); - } - - // Do the multiplication. - for (int i = 0; i < d_dim; ++i) { - result->d_vec[i] = factor*d_vec[i]; - } -} - void Vector::mult( double factor, diff --git a/lib/linalg/Vector.h b/lib/linalg/Vector.h index 72d3b6c94..0361aa491 100644 --- a/lib/linalg/Vector.h +++ b/lib/linalg/Vector.h @@ -300,7 +300,7 @@ class Vector normalize(); /** - * @brief Adds other and this and returns the result, reference version. + * @brief Adds other and this and returns the result. * * @pre distributed() == other.distributed() * @pre dim() == other.dim() @@ -335,8 +335,7 @@ class Vector Vector& result) const; /** - * @brief Adds factor*other and this and returns the result, reference - * version. + * @brief Adds factor*other and this and returns the result. * * @pre distributed() == other.distributed() * @pre dim() == other.dim() @@ -346,57 +345,16 @@ class Vector * * @return this + factor*other */ - Vector* - plusAx( - double factor, - const Vector& other) - { - Vector* result = 0; - plusAx(factor, other, result); - return result; - } - - /** - * @brief Adds factor*other and this and returns the result, pointer - * version. - * - * @pre distributed() == other->distributed() - * @pre dim() == other->dim() - * - * @param[in] factor Multiplicative factor applied to other. - * @param[in] other The other summand. - * - * @return this + factor*other - */ - Vector* + std::unique_ptr plusAx( double factor, - const Vector* other) + const Vector& other) const { - CAROM_VERIFY(other != 0); - return plusAx(factor, *other); + Vector *result = new Vector(d_dim, d_distributed); + plusAx(factor, other, *result); + return std::unique_ptr(result); } - /** - * @brief Adds factor*other and this and fills result with the answer. - * - * Result will be allocated if unallocated or resized appropriately if - * already allocated. - * - * @pre result == 0 || result->distributed() == distributed() - * @pre distributed() == other.distributed() - * @pre dim() == other.dim() - * - * @param[in] factor Multiplicative factor applied to other. - * @param[in] other The other summand. - * @param[out] result this + factor*other - */ - void - plusAx( - double factor, - const Vector& other, - Vector*& result) const; - /** * @brief Adds factor*other and this and fills result with the answer. * @@ -417,7 +375,7 @@ class Vector Vector& result) const; /** - * @brief Adds factor*other to this, reference version. + * @brief Adds factor*other to this. * * @pre distributed() == other.distributed() * @pre dim() == other.dim() @@ -431,27 +389,7 @@ class Vector const Vector& other); /** - * @brief Adds factor*other to this, pointer version. - * - * @pre other != 0 - * @pre distributed() == other->distributed() - * @pre dim() == other->dim() - * - * @param[in] factor Multiplicative factor applied to other. - * @param[in] other The other summand. - */ - void - plusEqAx( - double factor, - const Vector* other) - { - CAROM_VERIFY(other != 0); - plusEqAx(factor, *other); - } - - /** - * @brief Subtracts other and this and returns the result, reference - * version. + * @brief Subtracts other and this and returns the result. * * @pre distributed() == other.distributed() * @pre dim() == other.dim() @@ -460,53 +398,15 @@ class Vector * * @return this - other */ - Vector* + std::unique_ptr minus( const Vector& other) const { - Vector* result = 0; - minus(other, result); - return result; - } - - /** - * @brief Subtracts other and this and returns the result, pointer - * version. - * - * @pre other != 0 - * @pre distributed() == other->distributed() - * @pre dim() == other->dim() - * - * @param[in] other The other subtrahand. - * - * @return this - other - */ - Vector* - minus( - const Vector* other) const - { - CAROM_VERIFY(other != 0); - return minus(*other); + Vector *result = new Vector(d_dim, d_distributed); + minus(other, *result); + return std::unique_ptr(result); } - /** - * @brief Subtracts other and this and fills result with the answer. - * - * Result will be allocated if unallocated or resized appropriately if - * already allocated. - * - * @pre result == 0 || result->distributed() == distributed() - * @pre distributed() == other.distributed() - * @pre dim() == other.dim() - * - * @param[in] other The other subtrahend. - * @param[out] result this - other - */ - void - minus( - const Vector& other, - Vector*& result) const; - /** * @brief Subtracts other and this and fills result with the answer. * @@ -532,29 +432,15 @@ class Vector * * @return factor*this */ - Vector* + std::unique_ptr mult( double factor) const { - Vector* result = 0; - mult(factor, result); - return result; + Vector *result = new Vector(d_dim, d_distributed); + mult(factor, *result); + return std::unique_ptr(result); } - /** - * @brief Multiplies this by the supplied constant and fills result with - * the answer. - * - * @pre result == 0 || result->distributed() == distributed() - * - * @param[in] factor Factor to multiply by. - * @param[out] result factor*this - */ - void - mult( - double factor, - Vector*& result) const; - /** * @brief Multiplies this by the supplied constant and fills result with * the answer. diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index 556a411aa..cfd505440 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -293,9 +293,8 @@ IncrementalSVD::buildIncrementalSVD( // Computing as k = sqrt(u.u - 2.0*l.l + basisl.basisl) // results in catastrophic cancellation, and must be avoided. // Instead we compute as k = sqrt((u-basisl).(u-basisl)). - Vector* e_proj = u_vec.minus(basisl); + std::unique_ptr e_proj = u_vec.minus(*basisl); double k = e_proj->inner_product(*e_proj); - delete e_proj; if (k <= 0) { if(d_rank == 0) printf("linearly dependent sample!\n"); @@ -363,15 +362,14 @@ IncrementalSVD::buildIncrementalSVD( // This sample is not linearly dependent. // Compute j - Vector* j = u_vec.minus(basisl); + std::unique_ptr j = u_vec.minus(*basisl); for (int i = 0; i < d_dim; ++i) { j->item(i) /= k; } // addNewSample will assign sigma to d_S hence it should not be // deleted upon return. - addNewSample(j, A, W, sigma); - delete j; + addNewSample(j.get(), A, W, sigma); } delete basisl; delete A; diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index 7b683de59..bab939f20 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -150,12 +150,14 @@ IncrementalSVDBrand::buildIncrementalSVD( Vector e_proj(u, d_dim, true); Vector *tmp = d_U->transposeMult(e_proj); - - e_proj -= *(d_U->mult(*tmp)); // Gram-Schmidt + Vector *tmp2 = d_U->mult(*tmp); + e_proj -= *tmp2; // Gram-Schmidt + delete tmp2; delete tmp; tmp = d_U->transposeMult(e_proj); - e_proj -= *(d_U->mult(*tmp)); // Re-orthogonalization - + tmp2 = d_U->mult(*tmp); + e_proj -= *tmp2; // Re-orthogonalization + delete tmp2; delete tmp; double k = e_proj.inner_product(e_proj); diff --git a/unit_tests/test_DMD.cpp b/unit_tests/test_DMD.cpp index 393538f7d..a2e956018 100644 --- a/unit_tests/test_DMD.cpp +++ b/unit_tests/test_DMD.cpp @@ -74,7 +74,7 @@ TEST(DMDTest, Test_DMD) dmd.takeSample(&sample3[row_offset[d_rank]], 2.0); dmd.train(2); - CAROM::Vector* result = dmd.predict(3.0); + std::shared_ptr result = dmd.predict(3.0); for (int i = 0; i < d_num_rows; i++) { EXPECT_NEAR(result->item(i), prediction_baseline[row_offset[d_rank] + i], 1e-3); @@ -82,11 +82,11 @@ TEST(DMDTest, Test_DMD) dmd.save("test_DMD"); CAROM::DMD dmd_load("test_DMD"); - CAROM::Vector* result_load = dmd_load.predict(3.0); + std::shared_ptr result_load = dmd_load.predict(3.0); for (int i = 0; i < d_num_rows; i++) { - EXPECT_NEAR(result_load->item(i), prediction_baseline[row_offset[d_rank] + i], - 1e-3); + EXPECT_NEAR(result_load->item(i), + prediction_baseline[row_offset[d_rank] + i], 1e-3); } } diff --git a/unit_tests/test_PCHIPInterpolator.cpp b/unit_tests/test_PCHIPInterpolator.cpp index 2d2b2d15d..c9dcf547c 100644 --- a/unit_tests/test_PCHIPInterpolator.cpp +++ b/unit_tests/test_PCHIPInterpolator.cpp @@ -60,8 +60,8 @@ TEST(InterpolationTest,test_accuracy) -0.077580693288345, -0.623537711025344, -0.971758328554163, -0.890773577229575, -0.536572918000435, -0.041614069121016, 0.560852411851254, 0.957953731078007, 0.938810668593539, 0.650287840157117}; - std::vector snapshots; - std::vector out_snapshots; + std::vector> snapshots; + std::vector> out_snapshots; std::vector reference_snapshots; std::vector times; std::vector out_times; @@ -73,7 +73,7 @@ TEST(InterpolationTest,test_accuracy) CAROM::Vector* temp_y = new CAROM::Vector(2,false); temp_y->item(0) = y[i]; temp_y->item(1) = y2[i]; - snapshots.push_back(temp_y); + snapshots.push_back(std::shared_ptr(temp_y)); } for(int i = 0; i < tq.size(); ++i) @@ -89,7 +89,6 @@ TEST(InterpolationTest,test_accuracy) CAROM::PCHIPInterpolator* interp = new CAROM::PCHIPInterpolator(); - interp->interpolate(times,snapshots,out_times,out_snapshots); for(int i = 0; i < out_snapshots.size(); ++i) diff --git a/unit_tests/test_Vector.cpp b/unit_tests/test_Vector.cpp index 2c4d5a688..b480f8c5b 100644 --- a/unit_tests/test_Vector.cpp +++ b/unit_tests/test_Vector.cpp @@ -474,7 +474,7 @@ TEST(VectorSerialTest, Test_plus_const_reference_reference) TODO(oxberry1@llnl.gov): Test with double argument set to something other than 1. */ -TEST(VectorSerialTest, Test_plusAx_const_reference) +TEST(VectorSerialTest, Test_plusAx_const_pointer) { CAROM::Vector v(2, false); v(0) = 1; @@ -489,7 +489,7 @@ TEST(VectorSerialTest, Test_plusAx_const_reference) y(0) = 5; y(1) = 12; - CAROM::Vector *result; + std::unique_ptr result; /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ result = v.plusAx(1.0, v); @@ -497,8 +497,6 @@ TEST(VectorSerialTest, Test_plusAx_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 2); EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; /* ( 1, 1) + (-1, 1) = ( 0, 2) */ result = v.plusAx(1.0, w); @@ -506,8 +504,6 @@ TEST(VectorSerialTest, Test_plusAx_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 0); EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ result = v.plusAx(1.0, x); @@ -515,8 +511,6 @@ TEST(VectorSerialTest, Test_plusAx_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 4); EXPECT_DOUBLE_EQ((*result)(1), 5); - delete result; - result = NULL; /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ result = v.plusAx(1.0, y); @@ -524,136 +518,6 @@ TEST(VectorSerialTest, Test_plusAx_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 6); EXPECT_DOUBLE_EQ((*result)(1), 13); - delete result; - result = NULL; -} - -/* - TODO(oxberry1@llnl.gov): Test with double argument set to - something other than 1. -*/ -TEST(VectorSerialTest, Test_plusAx_const_pointer) -{ - CAROM::Vector *v = new CAROM::Vector(2, false); - (*v)(0) = 1; - (*v)(1) = 1; - CAROM::Vector *w = new CAROM::Vector(2, false); - (*w)(0) = -1; - (*w)(1) = 1; - CAROM::Vector *x = new CAROM::Vector(2, false); - (*x)(0) = 3; - (*x)(1) = 4; - CAROM::Vector *y = new CAROM::Vector(2, false); - (*y)(0) = 5; - (*y)(1) = 12; - - CAROM::Vector *result; - - /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ - result = v->plusAx(1.0, v); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - /* ( 1, 1) + (-1, 1) = ( 0, 2) */ - result = v->plusAx(1.0, w); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ - result = v->plusAx(1.0, x); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 4); - EXPECT_DOUBLE_EQ((*result)(1), 5); - delete result; - result = NULL; - - /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ - result = v->plusAx(1.0, y); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 6); - EXPECT_DOUBLE_EQ((*result)(1), 13); - delete result; - result = NULL; - - delete v; - delete w; - delete x; - delete y; -} - -/* - TODO(oxberry1@llnl.gov): Test with double argument set to - something other than 1. -*/ -/* TODO(oxberry1@llnl.gov): Test cases where pointer already allocated */ -TEST(VectorSerialTest, Test_plusAx_const_reference_pointer) -{ - CAROM::Vector v(2, false); - v(0) = 1; - v(1) = 1; - CAROM::Vector w(2, false); - w(0) = -1; - w(1) = 1; - CAROM::Vector x(2, false); - x(0) = 3; - x(1) = 4; - CAROM::Vector y(2, false); - y(0) = 5; - y(1) = 12; - - /* - NOTE(oxberry1@llnl.gov): if assignment omitted, pointer has - indeterminate value that is probably non-NULL, so - CAROM::Vector::plus tries to assign to that memory, resulting in a - segfault. - */ - CAROM::Vector *result = NULL; - - /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ - v.plusAx(1.0, v, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - /* ( 1, 1) + (-1, 1) = ( 0, 2) */ - v.plusAx(1.0, w, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ - v.plusAx(1.0, x, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 4); - EXPECT_DOUBLE_EQ((*result)(1), 5); - delete result; - result = NULL; - - /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ - v.plusAx(1.0, y, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 6); - EXPECT_DOUBLE_EQ((*result)(1), 13); - delete result; - result = NULL; } /* @@ -663,7 +527,7 @@ TEST(VectorSerialTest, Test_plusAx_const_reference_pointer) /* TODO(oxberry1@llnl.gov): Test cases where output vector must be resized. */ -TEST(VectorSerialTest, Test_plusAx_const_reference_reference) +TEST(VectorSerialTest, Test_plusAx_const_reference) { CAROM::Vector v(2, false); v(0) = 1; @@ -713,7 +577,7 @@ TEST(VectorSerialTest, Test_plusAx_const_reference_reference) TODO(oxberry1@llnl.gov): Test with double argument set to something other than 1. */ -TEST(VectorSerialTest, Test_plusEqAx_const_reference) +TEST(VectorSerialTest, Test_plusEqAx_const) { CAROM::Vector v(2, false); v(0) = 1; @@ -763,66 +627,7 @@ TEST(VectorSerialTest, Test_plusEqAx_const_reference) EXPECT_DOUBLE_EQ(v(1), 13); } -/* - TODO(oxberry1@llnl.gov): Test with double argument set to - something other than 1. -*/ -TEST(VectorSerialTest, Test_plusEqAx_const_pointer) -{ - CAROM::Vector *v = new CAROM::Vector(2, false); - (*v)(0) = 1; - (*v)(1) = 1; - CAROM::Vector *w = new CAROM::Vector(2, false); - (*w)(0) = -1; - (*w)(1) = 1; - CAROM::Vector *x = new CAROM::Vector(2, false); - (*x)(0) = 3; - (*x)(1) = 4; - CAROM::Vector *y = new CAROM::Vector(2, false); - (*y)(0) = 5; - (*y)(1) = 12; - - /* ( 1, 1) + ( 1, 1) = ( 2, 2) */ - v->plusEqAx(1.0, v); - EXPECT_FALSE(v->distributed()); - EXPECT_EQ(v->dim(), 2); - EXPECT_DOUBLE_EQ((*v)(0), 2); - EXPECT_DOUBLE_EQ((*v)(1), 2); - - /* ( 1, 1) + (-1, 1) = ( 0, 2) */ - (*v)(0) = 1; - (*v)(1) = 1; - v->plusEqAx(1.0, w); - EXPECT_FALSE(v->distributed()); - EXPECT_EQ(v->dim(), 2); - EXPECT_DOUBLE_EQ((*v)(0), 0); - EXPECT_DOUBLE_EQ((*v)(1), 2); - - /* ( 1, 1) + ( 3, 4) = ( 4, 5) */ - (*v)(0) = 1; - (*v)(1) = 1; - v->plusEqAx(1.0, x); - EXPECT_FALSE(v->distributed()); - EXPECT_EQ(v->dim(), 2); - EXPECT_DOUBLE_EQ((*v)(0), 4); - EXPECT_DOUBLE_EQ((*v)(1), 5); - - /* ( 1, 1) + ( 5, 12) = ( 6, 13) */ - (*v)(0) = 1; - (*v)(1) = 1; - v->plusEqAx(1.0, y); - EXPECT_FALSE(v->distributed()); - EXPECT_EQ(v->dim(), 2); - EXPECT_DOUBLE_EQ((*v)(0), 6); - EXPECT_DOUBLE_EQ((*v)(1), 13); - - delete v; - delete w; - delete x; - delete y; -} - -TEST(VectorSerialTest, Test_minus_const_reference) +TEST(VectorSerialTest, Test_minus_const_pointer) { CAROM::Vector v(2, false); v(0) = 1; @@ -837,7 +642,7 @@ TEST(VectorSerialTest, Test_minus_const_reference) y(0) = 5; y(1) = 12; - CAROM::Vector *result; + std::unique_ptr result; /* ( 1, 1) - ( 1, 1) = ( 0, 0) */ result = v.minus(v); @@ -845,8 +650,6 @@ TEST(VectorSerialTest, Test_minus_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 0); EXPECT_DOUBLE_EQ((*result)(1), 0); - delete result; - result = NULL; /* ( 1, 1) - (-1, 1) = ( 2, 0) */ result = v.minus(w); @@ -854,8 +657,6 @@ TEST(VectorSerialTest, Test_minus_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 2); EXPECT_DOUBLE_EQ((*result)(1), 0); - delete result; - result = NULL; /* ( 1, 1) - ( 3, 4) = (-2, -3) */ result = v.minus(x); @@ -863,8 +664,6 @@ TEST(VectorSerialTest, Test_minus_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), -2); EXPECT_DOUBLE_EQ((*result)(1), -3); - delete result; - result = NULL; /* ( 1, 1) - ( 5, 12) = (-4, -11) */ result = v.minus(y); @@ -872,134 +671,12 @@ TEST(VectorSerialTest, Test_minus_const_reference) EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), -4); EXPECT_DOUBLE_EQ((*result)(1),-11); - delete result; - result = NULL; -} - -TEST(VectorSerialTest, Test_minus_const_pointer) -{ - CAROM::Vector *v = new CAROM::Vector(2, false); - (*v)(0) = 1; - (*v)(1) = 1; - CAROM::Vector *w = new CAROM::Vector(2, false); - (*w)(0) = -1; - (*w)(1) = 1; - CAROM::Vector *x = new CAROM::Vector(2, false); - (*x)(0) = 3; - (*x)(1) = 4; - CAROM::Vector *y = new CAROM::Vector(2, false); - (*y)(0) = 5; - (*y)(1) = 12; - - CAROM::Vector *result; - - /* ( 1, 1) - ( 1, 1) = ( 0, 0) */ - result = v->minus(v); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 0); - delete result; - result = NULL; - - /* ( 1, 1) - (-1, 1) = ( 2, 0) */ - result = v->minus(w); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 0); - delete result; - result = NULL; - - /* ( 1, 1) - ( 3, 4) = (-2, -3) */ - result = v->minus(x); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), -2); - EXPECT_DOUBLE_EQ((*result)(1), -3); - delete result; - result = NULL; - - /* ( 1, 1) - ( 5, 12) = (-4, -11) */ - result = v->minus(y); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), -4); - EXPECT_DOUBLE_EQ((*result)(1),-11); - delete result; - result = NULL; - - delete v; - delete w; - delete x; - delete y; -} - -/* TODO(oxberry1@llnl.gov): Test cases where pointer already allocated */ -TEST(VectorSerialTest, Test_minus_const_reference_pointer) -{ - CAROM::Vector v(2, false); - v(0) = 1; - v(1) = 1; - CAROM::Vector w(2, false); - w(0) = -1; - w(1) = 1; - CAROM::Vector x(2, false); - x(0) = 3; - x(1) = 4; - CAROM::Vector y(2, false); - y(0) = 5; - y(1) = 12; - - /* - NOTE(oxberry1@llnl.gov): if assignment omitted, pointer has - indeterminate value that is probably non-NULL, so - CAROM::Vector::minus tries to assign to that memory, resulting in a - segfault. - */ - CAROM::Vector *result = NULL; - - /* ( 1, 1) - ( 1, 1) = ( 0, 0) */ - v.minus(v, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 0); - EXPECT_DOUBLE_EQ((*result)(1), 0); - delete result; - result = NULL; - - /* ( 1, 1) - (-1, 1) = ( 2, 0) */ - v.minus(w, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 0); - delete result; - result = NULL; - - /* ( 1, 1) - ( 3, 4) = (-2, -3) */ - v.minus(x, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), -2); - EXPECT_DOUBLE_EQ((*result)(1), -3); - delete result; - result = NULL; - - /* ( 1, 1) - ( 5, 12) = (-4, -11) */ - v.minus(y, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), -4); - EXPECT_DOUBLE_EQ((*result)(1),-11); - delete result; - result = NULL; } /* TODO(oxberry1@llnl.gov): Test cases where output vector must be resized. */ -TEST(VectorSerialTest, Test_minus_const_reference_reference) +TEST(VectorSerialTest, Test_minus_const_reference) { CAROM::Vector v(2, false); v(0) = 1; @@ -1060,89 +737,31 @@ TEST(VectorSerialTest, Test_mult_double) y(0) = 5; y(1) = 12; - CAROM::Vector *result; + std::unique_ptr result; result = v.mult(2); EXPECT_FALSE(result->distributed()); EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 2); EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; result = w.mult(-5); EXPECT_FALSE(result->distributed()); EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 5); EXPECT_DOUBLE_EQ((*result)(1), -5); - delete result; - result = NULL; result = x.mult(3); EXPECT_FALSE(result->distributed()); EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 9); EXPECT_DOUBLE_EQ((*result)(1), 12); - delete result; - result = NULL; result = y.mult(0.5); EXPECT_FALSE(result->distributed()); EXPECT_EQ(result->dim(), 2); EXPECT_DOUBLE_EQ((*result)(0), 2.5); EXPECT_DOUBLE_EQ((*result)(1), 6); - delete result; - result = NULL; -} - -TEST(VectorSerialTest, Test_mult_double_pointer) -{ - CAROM::Vector v(2, false); - v(0) = 1; - v(1) = 1; - CAROM::Vector w(2, false); - w(0) = -1; - w(1) = 1; - CAROM::Vector x(2, false); - x(0) = 3; - x(1) = 4; - CAROM::Vector y(2, false); - y(0) = 5; - y(1) = 12; - - CAROM::Vector *result = NULL; - - v.mult(2, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2); - EXPECT_DOUBLE_EQ((*result)(1), 2); - delete result; - result = NULL; - - w.mult(-5, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 5); - EXPECT_DOUBLE_EQ((*result)(1), -5); - delete result; - result = NULL; - - x.mult(3, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 9); - EXPECT_DOUBLE_EQ((*result)(1), 12); - delete result; - result = NULL; - - y.mult(0.5, result); - EXPECT_FALSE(result->distributed()); - EXPECT_EQ(result->dim(), 2); - EXPECT_DOUBLE_EQ((*result)(0), 2.5); - EXPECT_DOUBLE_EQ((*result)(1), 6); - delete result; - result = NULL; } TEST(VectorSerialTest, Test_mult_double_reference) From 1eb634424dd8a0badf4ec6cd2eaa911c2cdd06ef Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 31 Jul 2024 16:24:36 -0700 Subject: [PATCH 05/19] Elimination of raw pointers in Matrix class. --- .../dmd/parametric_dmdc_heat_conduction.cpp | 11 +- .../prom/de_parametric_maxwell_greedy.cpp | 4 +- examples/prom/dg_advection_global_rom.cpp | 14 +- .../dg_advection_local_rom_matrix_interp.cpp | 46 ++- .../prom/elliptic_eigenproblem_global_rom.cpp | 5 +- examples/prom/grad_div_global_rom.cpp | 4 +- .../prom/linear_elasticity_global_rom.cpp | 4 +- examples/prom/maxwell_global_rom.cpp | 4 +- examples/prom/maxwell_local_rom_greedy.cpp | 4 +- examples/prom/mixed_nonlinear_diffusion.cpp | 73 ++-- .../prom/mixed_nonlinear_diffusion_eqp.hpp | 9 +- .../prom/nonlinear_elasticity_global_rom.cpp | 67 ++-- examples/prom/poisson_global_rom.cpp | 4 +- examples/prom/poisson_local_rom_greedy.cpp | 4 +- lib/algo/DMD.cpp | 190 ++++----- lib/algo/DMD.h | 21 +- lib/algo/DMDc.cpp | 199 ++++------ lib/algo/DMDc.h | 29 +- lib/algo/NonuniformDMD.cpp | 8 +- lib/algo/NonuniformDMD.h | 5 +- lib/algo/ParametricDMD.h | 27 +- lib/algo/ParametricDMDc.h | 43 +- lib/algo/SnapshotDMD.h | 8 +- lib/algo/manifold_interp/Interpolator.cpp | 34 +- lib/algo/manifold_interp/Interpolator.h | 23 +- .../manifold_interp/MatrixInterpolator.cpp | 154 +++----- lib/algo/manifold_interp/MatrixInterpolator.h | 24 +- .../manifold_interp/VectorInterpolator.cpp | 27 +- lib/algo/manifold_interp/VectorInterpolator.h | 12 +- lib/hyperreduction/Hyperreduction.cpp | 8 +- lib/hyperreduction/Hyperreduction.h | 3 +- lib/hyperreduction/QDEIM.cpp | 4 +- lib/hyperreduction/S_OPT.cpp | 43 +- lib/hyperreduction/S_OPT.h | 2 +- lib/linalg/BasisGenerator.cpp | 20 +- lib/linalg/BasisReader.h | 6 +- lib/linalg/Matrix.cpp | 310 +-------------- lib/linalg/Matrix.h | 373 +++--------------- lib/linalg/svd/IncrementalSVD.cpp | 21 +- lib/linalg/svd/IncrementalSVDBrand.cpp | 77 ++-- lib/linalg/svd/IncrementalSVDBrand.h | 2 +- lib/linalg/svd/IncrementalSVDFastUpdate.cpp | 39 +- lib/linalg/svd/IncrementalSVDFastUpdate.h | 2 +- lib/linalg/svd/IncrementalSVDStandard.cpp | 21 +- lib/linalg/svd/RandomizedSVD.cpp | 21 +- lib/linalg/svd/SVD.cpp | 6 - lib/linalg/svd/SVD.h | 6 +- lib/linalg/svd/StaticSVD.cpp | 34 +- unit_tests/test_IncrementalSVD.cpp | 2 +- unit_tests/test_Matrix.cpp | 366 +---------------- unit_tests/test_QR.cpp | 8 +- unit_tests/test_S_OPT.cpp | 12 +- 52 files changed, 672 insertions(+), 1771 deletions(-) diff --git a/examples/dmd/parametric_dmdc_heat_conduction.cpp b/examples/dmd/parametric_dmdc_heat_conduction.cpp index 9f7346322..10841be6a 100644 --- a/examples/dmd/parametric_dmdc_heat_conduction.cpp +++ b/examples/dmd/parametric_dmdc_heat_conduction.cpp @@ -770,7 +770,7 @@ int main(int argc, char *argv[]) std::fstream fin(io_dir + "/parameters.txt", std::ios_base::in); double curr_param; std::vector dmdc_paths; - std::vector controls; + std::vector> controls; std::vector param_vectors; while (fin >> curr_param) @@ -786,7 +786,7 @@ int main(int argc, char *argv[]) dmdc_paths.push_back(io_dir + "/" + to_string(curr_alpha) + "_" + to_string( curr_kappa) + "_" + to_string(curr_amp_in) + "_" + to_string(curr_amp_out) ); - CAROM::Matrix* curr_control = new CAROM::Matrix(); + std::shared_ptr curr_control(new CAROM::Matrix()); curr_control->read(io_dir + "/" + to_string(curr_alpha) + "_" + to_string( curr_kappa) + "_" + to_string(curr_amp_in) + "_" + to_string( curr_amp_out) + "_control"); @@ -810,22 +810,19 @@ int main(int argc, char *argv[]) dmd_training_timer.Start(); - CAROM::Matrix* controls_interpolated = new CAROM::Matrix(); + std::shared_ptr controls_interpolated(new CAROM::Matrix()); CAROM::getParametricDMDc(dmd_u, param_vectors, dmdc_paths, controls, controls_interpolated, desired_param, "G", "LS", closest_rbf_val); - dmd_u->project(init,controls_interpolated); + dmd_u->project(init,controls_interpolated.get()); dmd_training_timer.Stop(); delete desired_param; - delete controls_interpolated; for (auto m : param_vectors) delete m; - for (auto m : controls) - delete m; } if (predict) diff --git a/examples/prom/de_parametric_maxwell_greedy.cpp b/examples/prom/de_parametric_maxwell_greedy.cpp index 56e3db22c..abe4d769b 100644 --- a/examples/prom/de_parametric_maxwell_greedy.cpp +++ b/examples/prom/de_parametric_maxwell_greedy.cpp @@ -346,7 +346,8 @@ double simulation() CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -358,7 +359,6 @@ double simulation() // 24. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 25. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/dg_advection_global_rom.cpp b/examples/prom/dg_advection_global_rom.cpp index ab06e3548..11680f2f1 100644 --- a/examples/prom/dg_advection_global_rom.cpp +++ b/examples/prom/dg_advection_global_rom.cpp @@ -675,7 +675,8 @@ int main(int argc, char *argv[]) CAROM::Matrix *M_hat_carom, *K_hat_carom; DenseMatrix *M_hat, *K_hat; - CAROM::Vector *b_hat_carom, *u_init_hat_carom; + std::unique_ptr b_hat_carom; + CAROM::Vector *u_init_hat_carom; Vector *b_hat, *u_init_hat; Vector u_init(*U); @@ -768,7 +769,7 @@ int main(int argc, char *argv[]) Vector b_vec = *B; CAROM::Vector b_carom(b_vec.GetData(), b_vec.Size(), true); - b_hat_carom = spatialbasis->transposeMult(&b_carom); + b_hat_carom = spatialbasis->transposeMult(b_carom); b_hat = new Vector(b_hat_carom->getData(), b_hat_carom->dim()); u_init_hat_carom = new CAROM::Vector(numColumnRB, false); @@ -851,11 +852,11 @@ int main(int argc, char *argv[]) cout << "WARNING: FOM lifting for visualization is slow." << endl; CAROM::Vector u_hat_final_carom(u_hat->GetData(), u_hat->Size(), false); - CAROM::Vector* u_final_carom = spatialbasis->mult(u_hat_final_carom); + std::unique_ptr u_final_carom = spatialbasis->mult( + u_hat_final_carom); Vector u_final(u_final_carom->getData(), u_final_carom->dim()); u_final += u_init; u->SetFromTrueDofs(u_final); - delete u_final_carom; } dc->SetCycle(ti); @@ -892,7 +893,8 @@ int main(int argc, char *argv[]) if (online) { CAROM::Vector u_hat_final_carom(u_hat->GetData(), u_hat->Size(), false); - CAROM::Vector* u_final_carom = spatialbasis->mult(u_hat_final_carom); + std::unique_ptr u_final_carom = spatialbasis->mult( + u_hat_final_carom); Vector u_final(u_final_carom->getData(), u_final_carom->dim()); u_final += u_init; @@ -916,12 +918,10 @@ int main(int argc, char *argv[]) delete K_hat_carom; delete M_hat; delete K_hat; - delete b_hat_carom; delete u_init_hat_carom; delete b_hat; delete u_init_hat; delete u_hat; - delete u_final_carom; } // 12. Save the final solution in parallel. This output can be viewed later diff --git a/examples/prom/dg_advection_local_rom_matrix_interp.cpp b/examples/prom/dg_advection_local_rom_matrix_interp.cpp index 4958cb49d..5b38c900e 100644 --- a/examples/prom/dg_advection_local_rom_matrix_interp.cpp +++ b/examples/prom/dg_advection_local_rom_matrix_interp.cpp @@ -690,12 +690,12 @@ int main(int argc, char *argv[]) bool update_right_SV = false; bool isIncremental = false; const std::string basisName = "basis_" + std::to_string(f_factor); - const CAROM::Matrix* spatialbasis; + std::shared_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; - CAROM::Matrix *M_hat_carom, *K_hat_carom; + std::shared_ptr K_hat_carom, M_hat_carom; DenseMatrix *M_hat, *K_hat; std::shared_ptr b_hat_carom, u_init_hat_carom; Vector *b_hat, *u_init_hat; @@ -723,11 +723,11 @@ int main(int argc, char *argv[]) CAROM::BasisReader reader(basisName); if (rdim != -1) { - spatialbasis = reader.getSpatialBasis(rdim); + spatialbasis.reset(reader.getSpatialBasis(rdim)); } else { - spatialbasis = reader.getSpatialBasis(ef); + spatialbasis.reset(reader.getSpatialBasis(ef)); } numRowRB = spatialbasis->numRows(); numColumnRB = spatialbasis->numColumns(); @@ -750,7 +750,7 @@ int main(int argc, char *argv[]) HypreParMatrix &M_mat = *M.As(); HypreParMatrix &K_mat = *K.As(); - M_hat_carom = new CAROM::Matrix(numRowRB, numColumnRB, false); + M_hat_carom.reset(new CAROM::Matrix(numRowRB, numColumnRB, false)); ComputeCtAB(M_mat, *spatialbasis, *spatialbasis, *M_hat_carom); if (interp_prep) M_hat_carom->write("M_hat_" + std::to_string(f_factor)); @@ -759,7 +759,7 @@ int main(int argc, char *argv[]) M_hat->Set(1, M_hat_carom->getData()); M_hat->Transpose(); - K_hat_carom = new CAROM::Matrix(numRowRB, numColumnRB, false); + K_hat_carom.reset(new CAROM::Matrix(numRowRB, numColumnRB, false)); ComputeCtAB(K_mat, *spatialbasis, *spatialbasis, *K_hat_carom); if (interp_prep) K_hat_carom->write("K_hat_" + std::to_string(f_factor)); @@ -770,7 +770,7 @@ int main(int argc, char *argv[]) Vector b_vec = *B; CAROM::Vector b_carom(b_vec.GetData(), b_vec.Size(), true); - b_hat_carom.reset(spatialbasis->transposeMult(&b_carom)); + b_hat_carom = spatialbasis->transposeMult(b_carom); if (interp_prep) b_hat_carom->write("b_hat_" + std::to_string(f_factor)); b_hat = new Vector(b_hat_carom->getData(), b_hat_carom->dim()); @@ -804,11 +804,11 @@ int main(int argc, char *argv[]) fin.close(); std::vector parameter_points; - std::vector bases; - std::vector K_hats; - std::vector M_hats; - std::vector b_hats; - std::vector u_init_hats; + std::vector> bases; + std::vector> K_hats; + std::vector> M_hats; + std::vector> b_hats; + std::vector> u_init_hats; for(auto it = frequencies.begin(); it != frequencies.end(); it++) { CAROM::Vector* point = new CAROM::Vector(1, false); @@ -819,24 +819,25 @@ int main(int argc, char *argv[]) CAROM::BasisReader reader(parametricBasisName); MFEM_VERIFY(rdim != -1, "rdim must be used for interpolation."); - CAROM::Matrix* parametricSpatialBasis = reader.getSpatialBasis(rdim); + std::shared_ptr parametricSpatialBasis(reader.getSpatialBasis( + rdim)); numRowRB = parametricSpatialBasis->numRows(); numColumnRB = parametricSpatialBasis->numColumns(); bases.push_back(parametricSpatialBasis); - CAROM::Matrix* parametricMhat = new CAROM::Matrix(); + std::shared_ptr parametricMhat(new CAROM::Matrix()); parametricMhat->read("M_hat_" + std::to_string(*it)); M_hats.push_back(parametricMhat); - CAROM::Matrix* parametricKhat = new CAROM::Matrix(); + std::shared_ptr parametricKhat(new CAROM::Matrix()); parametricKhat->read("K_hat_" + std::to_string(*it)); K_hats.push_back(parametricKhat); - CAROM::Vector* parametricbhat = new CAROM::Vector(); + std::shared_ptr parametricbhat(new CAROM::Vector()); parametricbhat->read("b_hat_" + std::to_string(*it)); b_hats.push_back(parametricbhat); - CAROM::Vector* parametricuinithat = new CAROM::Vector(); + std::shared_ptr parametricuinithat(new CAROM::Vector()); parametricuinithat->read("u_init_hat_" + std::to_string(*it)); u_init_hats.push_back(parametricuinithat); } @@ -847,8 +848,8 @@ int main(int argc, char *argv[]) curr_point->item(0) = f_factor; int ref_point = getClosestPoint(parameter_points, curr_point); - std::vector rotation_matrices = obtainRotationMatrices( - parameter_points, bases, ref_point); + std::vector> rotation_matrices = + obtainRotationMatrices(parameter_points, bases, ref_point); CAROM::MatrixInterpolator basis_interpolator(parameter_points, rotation_matrices, bases, ref_point, "B", rbf_type, interp_method, @@ -988,7 +989,8 @@ int main(int argc, char *argv[]) if (online) { CAROM::Vector u_hat_final_carom(u_in->GetData(), u_in->Size(), false); - CAROM::Vector* u_final_carom = spatialbasis->mult(u_hat_final_carom); + std::unique_ptr u_final_carom = spatialbasis->mult( + u_hat_final_carom); Vector u_final(u_final_carom->getData(), u_final_carom->dim()); u_final += u_init; @@ -1007,15 +1009,11 @@ int main(int argc, char *argv[]) if (myid == 0) std::cout << "Relative l2 error of ROM solution " << diffNorm / fomNorm << std::endl; - delete spatialbasis; - delete M_hat_carom; - delete K_hat_carom; delete M_hat; delete K_hat; delete b_hat; delete u_init_hat; delete u_in; - delete u_final_carom; } // 12. Save the final solution in parallel. This output can be viewed later diff --git a/examples/prom/elliptic_eigenproblem_global_rom.cpp b/examples/prom/elliptic_eigenproblem_global_rom.cpp index 73b6388b0..ce48db220 100644 --- a/examples/prom/elliptic_eigenproblem_global_rom.cpp +++ b/examples/prom/elliptic_eigenproblem_global_rom.cpp @@ -548,10 +548,9 @@ int main(int argc, char *argv[]) tmp.GetRow(i, reduced_eigenvector); CAROM::Vector reduced_eigenvector_carom(reduced_eigenvector.GetData(), reduced_eigenvector.Size(), false, false); - CAROM::Vector *eigenvector_carom = spatialbasis->mult( - reduced_eigenvector_carom); + std::unique_ptr eigenvector_carom = spatialbasis->mult( + reduced_eigenvector_carom); eigenvectors.SetRow(i, eigenvector_carom->getData()); - delete eigenvector_carom; } delete spatialbasis; diff --git a/examples/prom/grad_div_global_rom.cpp b/examples/prom/grad_div_global_rom.cpp index ea9fc777e..0d4413701 100644 --- a/examples/prom/grad_div_global_rom.cpp +++ b/examples/prom/grad_div_global_rom.cpp @@ -383,7 +383,8 @@ int main(int argc, char *argv[]) CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -395,7 +396,6 @@ int main(int argc, char *argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/linear_elasticity_global_rom.cpp b/examples/prom/linear_elasticity_global_rom.cpp index cc404e0c3..5a214f239 100644 --- a/examples/prom/linear_elasticity_global_rom.cpp +++ b/examples/prom/linear_elasticity_global_rom.cpp @@ -392,7 +392,8 @@ int main(int argc, char* argv[]) CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -405,7 +406,6 @@ int main(int argc, char* argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/maxwell_global_rom.cpp b/examples/prom/maxwell_global_rom.cpp index 69d462583..2135866c4 100644 --- a/examples/prom/maxwell_global_rom.cpp +++ b/examples/prom/maxwell_global_rom.cpp @@ -374,7 +374,8 @@ int main(int argc, char *argv[]) CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -386,7 +387,6 @@ int main(int argc, char *argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/maxwell_local_rom_greedy.cpp b/examples/prom/maxwell_local_rom_greedy.cpp index 9c5b973ea..6ddb8fbab 100644 --- a/examples/prom/maxwell_local_rom_greedy.cpp +++ b/examples/prom/maxwell_local_rom_greedy.cpp @@ -496,7 +496,8 @@ int main(int argc, char *argv[]) CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -508,7 +509,6 @@ int main(int argc, char *argv[]) // 24. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 25. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/mixed_nonlinear_diffusion.cpp b/examples/prom/mixed_nonlinear_diffusion.cpp index 236e0ca2f..72322d5bc 100644 --- a/examples/prom/mixed_nonlinear_diffusion.cpp +++ b/examples/prom/mixed_nonlinear_diffusion.cpp @@ -308,7 +308,7 @@ class RomOperator : public TimeDependentOperator const CAROM::Matrix *Ssinv; mutable CAROM::Vector zS; mutable CAROM::Vector zT; - const CAROM::Matrix *S; + const std::shared_ptr S; mutable DenseMatrix J; @@ -353,7 +353,7 @@ class RomOperator : public TimeDependentOperator protected: CAROM::Matrix* BR; CAROM::Matrix* CR; - const CAROM::Matrix* U_R; + const std::shared_ptr U_R; Vector y0; Vector dydt_prev; NonlinearDiffusionOperator *fom; @@ -363,11 +363,11 @@ class RomOperator : public TimeDependentOperator RomOperator(NonlinearDiffusionOperator *fom_, NonlinearDiffusionOperator *fomSp_, const int rrdim_, const int rwdim_, const int nldim_, - CAROM::SampleMeshManager *smm_, - const CAROM::Matrix* V_R_, const CAROM::Matrix* U_R_, const CAROM::Matrix* V_W_, - const CAROM::Matrix *Bsinv, + CAROM::SampleMeshManager *smm_, std::shared_ptr V_R_, + std::shared_ptr U_R_, + std::shared_ptr V_W_, const CAROM::Matrix *Bsinv, const double newton_rel_tol, const double newton_abs_tol, const int newton_iter, - const CAROM::Matrix* S_, const CAROM::Matrix *Ssinv_, + std::shared_ptr S_, const CAROM::Matrix *Ssinv_, const int myid, const bool hyperreduce_source_, const bool oversampling_, const bool use_eqp, CAROM::Vector *eqpSol, CAROM::Vector *eqpSol_S, const IntegrationRule *ir_eqp_); @@ -411,21 +411,6 @@ void BroadcastUndistributedRomVector(CAROM::Vector* v) delete [] d; } -// TODO: move this to the library? -CAROM::Matrix* GetFirstColumns(const int N, const CAROM::Matrix* A) -{ - CAROM::Matrix* S = new CAROM::Matrix(A->numRows(), std::min(N, A->numColumns()), - A->distributed()); - for (int i=0; inumRows(); ++i) - { - for (int j=0; jnumColumns(); ++j) - (*S)(i,j) = (*A)(i,j); - } - - // delete A; // TODO: find a good solution for this. - return S; -} - // TODO: move this to the library? void MergeBasis(const int dimFOM, const int nparam, const int max_num_snapshots, std::string name) @@ -855,10 +840,10 @@ int main(int argc, char *argv[]) RomOperator *romop = 0; const CAROM::Matrix* B_librom = 0; - const CAROM::Matrix* BR_librom = 0; - const CAROM::Matrix* FR_librom = 0; - const CAROM::Matrix* BW_librom = 0; - const CAROM::Matrix* S_librom = 0; + std::shared_ptr BR_librom; + std::shared_ptr FR_librom; + std::shared_ptr BW_librom; + std::shared_ptr S_librom; int nsamp_R = -1; int nsamp_S = -1; @@ -871,12 +856,14 @@ int main(int argc, char *argv[]) if (online) { CAROM::BasisReader readerR("basisR"); - BR_librom = readerR.getSpatialBasis(); + BR_librom.reset(readerR.getSpatialBasis()); if (rrdim == -1) rrdim = BR_librom->numColumns(); else - BR_librom = GetFirstColumns(rrdim, - BR_librom); // TODO: reduce rrdim if too large + { + // TODO: reduce rrdim if too large + BR_librom = BR_librom->getFirstNColumns(rrdim); + } MFEM_VERIFY(BR_librom->numRows() == N1, ""); @@ -884,11 +871,11 @@ int main(int argc, char *argv[]) printf("reduced R dim = %d\n",rrdim); CAROM::BasisReader readerW("basisW"); - BW_librom = readerW.getSpatialBasis(); + BW_librom.reset(readerW.getSpatialBasis()); if (rwdim == -1) rwdim = BW_librom->numColumns(); else - BW_librom = GetFirstColumns(rwdim, BW_librom); + BW_librom = BW_librom->getFirstNColumns(rwdim); MFEM_VERIFY(BW_librom->numRows() == N2, ""); @@ -906,7 +893,7 @@ int main(int argc, char *argv[]) */ CAROM::BasisReader readerFR("basisFR"); - FR_librom = readerFR.getSpatialBasis(); + FR_librom.reset(readerFR.getSpatialBasis()); if (nldim == -1) { @@ -916,7 +903,7 @@ int main(int argc, char *argv[]) MFEM_VERIFY(FR_librom->numRows() == N1 && FR_librom->numColumns() >= nldim, ""); if (FR_librom->numColumns() > nldim) - FR_librom = GetFirstColumns(nldim, FR_librom); + FR_librom = FR_librom->getFirstNColumns(nldim); if (myid == 0) printf("reduced FR dim = %d\n",nldim); @@ -994,7 +981,7 @@ int main(int argc, char *argv[]) if (hyperreduce_source) { readerS = new CAROM::BasisReader("basisS"); - S_librom = readerS->getSpatialBasis(); + S_librom.reset(readerS->getSpatialBasis()); if (nsdim == -1) { @@ -1004,7 +991,7 @@ int main(int argc, char *argv[]) MFEM_VERIFY(S_librom->numColumns() >= nsdim, ""); if (S_librom->numColumns() > nsdim) - S_librom = GetFirstColumns(nsdim, S_librom); + S_librom = S_librom->getFirstNColumns(nsdim); if (myid == 0) printf("reduced S dim = %d\n",nsdim); @@ -1022,7 +1009,6 @@ int main(int argc, char *argv[]) Ssinv = new CAROM::Matrix(nsamp_S, nsdim, false); sample_dofs_S.resize(nsamp_S); - hr.ComputeSamples(S_librom, nsdim, sample_dofs_S, @@ -1696,15 +1682,20 @@ NonlinearDiffusionOperator::~NonlinearDiffusionOperator() } RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, - NonlinearDiffusionOperator *fomSp_, const int rrdim_, const int rwdim_, - const int nldim_, CAROM::SampleMeshManager *smm_, - const CAROM::Matrix* V_R_, const CAROM::Matrix* U_R_, const CAROM::Matrix* V_W_, + NonlinearDiffusionOperator *fomSp_, const int rrdim_, + const int rwdim_, const int nldim_, + CAROM::SampleMeshManager *smm_, + std::shared_ptr V_R_, + std::shared_ptr U_R_, + std::shared_ptr V_W_, const CAROM::Matrix *Bsinv, - const double newton_rel_tol, const double newton_abs_tol, const int newton_iter, - const CAROM::Matrix* S_, const CAROM::Matrix *Ssinv_, + const double newton_rel_tol, + const double newton_abs_tol, const int newton_iter, + std::shared_ptr S_, const CAROM::Matrix *Ssinv_, const int myid, const bool hyperreduce_source_, const bool oversampling_, const bool use_eqp, - CAROM::Vector *eqpSol, CAROM::Vector *eqpSol_S, const IntegrationRule *ir_eqp_) + CAROM::Vector *eqpSol, CAROM::Vector *eqpSol_S, + const IntegrationRule *ir_eqp_) : TimeDependentOperator(rrdim_ + rwdim_, 0.0), newton_solver(), fom(fom_), fomSp(fomSp_), BR(NULL), rrdim(rrdim_), rwdim(rwdim_), nldim(nldim_), diff --git a/examples/prom/mixed_nonlinear_diffusion_eqp.hpp b/examples/prom/mixed_nonlinear_diffusion_eqp.hpp index 4bc0940f5..fe1c9b605 100644 --- a/examples/prom/mixed_nonlinear_diffusion_eqp.hpp +++ b/examples/prom/mixed_nonlinear_diffusion_eqp.hpp @@ -791,7 +791,7 @@ void SolveNNLS(const int rank, const double nnls_tol, const int maxNNLSnnz, void SetupEQP_snapshots(const IntegrationRule *ir0, const int rank, ParFiniteElementSpace *fespace_R, ParFiniteElementSpace *fespace_W, - const int nsets, const CAROM::Matrix* BR, + const int nsets, const std::shared_ptr BR, const CAROM::Matrix* BR_snapshots, const CAROM::Matrix* BW_snapshots, const bool precondition, const double nnls_tol, @@ -883,7 +883,8 @@ void SetupEQP_snapshots(const IntegrationRule *ir0, const int rank, if (precondition) { // Preconditioning is done by (V^T M(p_i) V)^{-1} (of size NB x NB). - PreconditionNNLS(fespace_R, new VectorFEMassIntegrator(a_coeff), BR, i, Gt); + PreconditionNNLS(fespace_R, new VectorFEMassIntegrator(a_coeff), BR.get(), i, + Gt); } } // Loop (i) over snapshots @@ -904,7 +905,7 @@ void SetupEQP_snapshots(const IntegrationRule *ir0, const int rank, // Compute EQP solution from constraints on source snapshots. void SetupEQP_S_snapshots(const IntegrationRule *ir0, const int rank, ParFiniteElementSpace *fespace_W, - const CAROM::Matrix* BW, + const std::shared_ptr BW, const CAROM::Matrix* BS_snapshots, const bool precondition, const double nnls_tol, const int maxNNLSnnz, @@ -956,7 +957,7 @@ void SetupEQP_S_snapshots(const IntegrationRule *ir0, const int rank, if (precondition) { // Preconditioning is done by (V^T M V)^{-1} (of size NB x NB). - PreconditionNNLS(fespace_W, new MassIntegrator(), BW, -1, Gt); + PreconditionNNLS(fespace_W, new MassIntegrator(), BW.get(), -1, Gt); } Array const& w_el = ir0->GetWeights(); diff --git a/examples/prom/nonlinear_elasticity_global_rom.cpp b/examples/prom/nonlinear_elasticity_global_rom.cpp index f645c3558..d0178b33e 100644 --- a/examples/prom/nonlinear_elasticity_global_rom.cpp +++ b/examples/prom/nonlinear_elasticity_global_rom.cpp @@ -230,7 +230,7 @@ class RomOperator : public TimeDependentOperator CAROM::Matrix *M_hat; CAROM::Matrix *M_hat_inv; - const CAROM::Matrix *U_H; + const std::shared_ptr U_H; HyperelasticOperator *fomSp; @@ -243,8 +243,10 @@ class RomOperator : public TimeDependentOperator RomOperator(HyperelasticOperator *fom_, HyperelasticOperator *fomSp_, const int rvdim_, const int rxdim_, const int hdim_, CAROM::SampleMeshManager *smm_, const Vector *v0_, - const Vector *x0_, const Vector v0_fom_, const CAROM::Matrix *V_v_, - const CAROM::Matrix *V_x_, const CAROM::Matrix *U_H_, + const Vector *x0_, const Vector v0_fom_, + const std::shared_ptr V_v_, + const std::shared_ptr V_x_, + const std::shared_ptr U_H_, const CAROM::Matrix *Hsinv_, const int myid, const bool oversampling_, const bool hyperreduce_, const bool x_base_only_, const bool use_eqp, CAROM::Vector *eqpSol, @@ -291,21 +293,6 @@ void visualize(ostream &out, ParMesh *mesh, ParGridFunction *deformed_nodes, ParGridFunction *field, const char *field_name = NULL, bool init_vis = false); -// TODO: move this to the library? -CAROM::Matrix *GetFirstColumns(const int N, const CAROM::Matrix *A) -{ - CAROM::Matrix *S = new CAROM::Matrix(A->numRows(), std::min(N, A->numColumns()), - A->distributed()); - for (int i = 0; i < S->numRows(); ++i) - { - for (int j = 0; j < S->numColumns(); ++j) - (*S)(i, j) = (*A)(i, j); - } - - // delete A; // TODO: find a good solution for this. - return S; -} - // TODO: move this to the library? void MergeBasis(const int dimFOM, const int nparam, const int max_num_snapshots, std::string name) @@ -803,9 +790,9 @@ int main(int argc, char *argv[]) RomOperator *romop = 0; - const CAROM::Matrix *BV_librom = 0; - const CAROM::Matrix *BX_librom = 0; - const CAROM::Matrix *H_librom = 0; + std::shared_ptr BV_librom; + std::shared_ptr BX_librom; + std::shared_ptr H_librom; const CAROM::Matrix *Hsinv = 0; int nsamp_H = -1; @@ -837,13 +824,12 @@ int main(int argc, char *argv[]) readerV = new CAROM::BasisReader("basisV"); } - BV_librom = readerV->getSpatialBasis(); + BV_librom.reset(readerV->getSpatialBasis()); if (rvdim == -1) // Change rvdim rvdim = BV_librom->numColumns(); else - BV_librom = GetFirstColumns(rvdim, - BV_librom); + BV_librom = BV_librom->getFirstNColumns(rvdim); MFEM_VERIFY(BV_librom->numRows() == true_size, ""); @@ -851,13 +837,12 @@ int main(int argc, char *argv[]) printf("reduced V dim = %d\n", rvdim); CAROM::BasisReader readerX("basisX"); - BX_librom = readerX.getSpatialBasis(); + BX_librom.reset(readerX.getSpatialBasis()); if (rxdim == -1) // Change rxdim rxdim = BX_librom->numColumns(); else - BX_librom = GetFirstColumns(rxdim, - BX_librom); + BX_librom = BX_librom->getFirstNColumns(rxdim); MFEM_VERIFY(BX_librom->numRows() == true_size, ""); @@ -866,7 +851,7 @@ int main(int argc, char *argv[]) // Hyper reduce H CAROM::BasisReader readerH("basisH"); - H_librom = readerH.getSpatialBasis(); + H_librom.reset(readerH.getSpatialBasis()); // Compute sample points if (hdim == -1) @@ -877,7 +862,7 @@ int main(int argc, char *argv[]) MFEM_VERIFY(H_librom->numColumns() >= hdim, ""); if (H_librom->numColumns() > hdim) - H_librom = GetFirstColumns(hdim, H_librom); + H_librom = H_librom->getFirstNColumns(hdim); if (myid == 0) printf("reduced H dim = %d\n", hdim); @@ -905,7 +890,7 @@ int main(int argc, char *argv[]) { // EQP setup eqpSol = new CAROM::Vector(ir0->GetNPoints() * fespace.GetNE(), true); - SetupEQP_snapshots(ir0, myid, &fespace, nsets, BV_librom, + SetupEQP_snapshots(ir0, myid, &fespace, nsets, BV_librom.get(), GetSnapshotMatrix(fespace.GetTrueVSize(), nsets, max_num_snapshots, "X"), vx0.GetBlock(0), preconditionNNLS, tolNNLS, maxNNLSnnz, model, *eqpSol, window_ids, snap_step); @@ -1401,10 +1386,6 @@ int main(int argc, char *argv[]) delete pmesh; delete romop; delete soper; - - delete BV_librom; - delete BX_librom; - delete H_librom; delete Hsinv; delete smm; delete eqpSol; @@ -1595,8 +1576,10 @@ void InitialVelocityIC2(const Vector &x, Vector &v) RomOperator::RomOperator(HyperelasticOperator *fom_, HyperelasticOperator *fomSp_, const int rvdim_, const int rxdim_, const int hdim_, CAROM::SampleMeshManager *smm_, const Vector *v0_, - const Vector *x0_, const Vector v0_fom_, const CAROM::Matrix *V_v_, - const CAROM::Matrix *V_x_, const CAROM::Matrix *U_H_, + const Vector *x0_, const Vector v0_fom_, + const std::shared_ptr V_v_, + const std::shared_ptr V_x_, + const std::shared_ptr U_H_, const CAROM::Matrix *Hsinv_, const int myid, const bool oversampling_, const bool hyperreduce_, const bool x_base_only_, const bool use_eqp, CAROM::Vector *eqpSol, const IntegrationRule *ir_eqp_, NeoHookeanModel *model_) @@ -1653,7 +1636,7 @@ RomOperator::RomOperator(HyperelasticOperator *fom_, ComputeCtAB(fom->Smat, V_v, V_v, *S_hat); // Apply S_hat to the initial velocity and store fom->Smat.Mult(v0_fom, *S_hat_v0_temp); - V_v.transposeMult(*S_hat_v0_temp_librom, S_hat_v0); + V_v.transposeMult(*S_hat_v0_temp_librom, *S_hat_v0); // Create M_hat ComputeCtAB(*(fom->Mmat), V_v, V_v, *M_hat); @@ -1679,7 +1662,7 @@ RomOperator::RomOperator(HyperelasticOperator *fom_, V_xTV_v_sp = new CAROM::Matrix(rxdim, rvdim, false); V_xTv_0_sp = new CAROM::Vector(spdim / 2, false); V_x_sp->transposeMult(*V_v_sp, *V_xTV_v_sp); - V_x_sp->transposeMult(*v0_librom, V_xTv_0_sp); + V_x_sp->transposeMult(*v0_librom, *V_xTv_0_sp); // This is for saving the recreated predictions psp_librom = new CAROM::Vector(spdim, false); @@ -1720,8 +1703,8 @@ RomOperator::RomOperator(HyperelasticOperator *fom_, v0_fom_librom = new CAROM::Vector(v0_fom.GetData(), v0_fom.Size(), true, false); V_xTV_v = new CAROM::Matrix(rxdim, rvdim, false); V_xTv_0 = new CAROM::Vector(fdim / 2, false); - V_x.transposeMult(V_v, V_xTV_v); - V_x.transposeMult(*v0_fom_librom, V_xTv_0); + V_x.transposeMult(V_v, *V_xTV_v); + V_x.transposeMult(*v0_fom_librom, *V_xTv_0); Vx_librom_temp = new CAROM::Vector(fdim / 2, true); Vx_temp = new Vector(&((*Vx_librom_temp)(0)), fdim / 2); } @@ -1885,7 +1868,7 @@ void RomOperator::Mult_Hyperreduced(const Vector &vx, Vector &dvx_dt) const } // Multiply by V_v^T * U_H - V_vTU_H.mult(zX, z_librom); + V_vTU_H.mult(zX, *z_librom); } if (fomSp->viscosity != 0.0) @@ -1926,7 +1909,7 @@ void RomOperator::Mult_FullOrder(const Vector &vx, Vector &dvx_dt) const // Apply H to x to get z fom->H->Mult(*pfom_x, *zfom_x); - V_v.transposeMult(*zfom_x_librom, z_librom); + V_v.transposeMult(*zfom_x_librom, *z_librom); if (fom->viscosity != 0.0) { diff --git a/examples/prom/poisson_global_rom.cpp b/examples/prom/poisson_global_rom.cpp index f417539ce..af43f2982 100644 --- a/examples/prom/poisson_global_rom.cpp +++ b/examples/prom/poisson_global_rom.cpp @@ -370,7 +370,8 @@ int main(int argc, char *argv[]) CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -382,7 +383,6 @@ int main(int argc, char *argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/poisson_local_rom_greedy.cpp b/examples/prom/poisson_local_rom_greedy.cpp index 46398dd8c..f3aa8b7d3 100644 --- a/examples/prom/poisson_local_rom_greedy.cpp +++ b/examples/prom/poisson_local_rom_greedy.cpp @@ -480,7 +480,8 @@ int main(int argc, char *argv[]) CAROM::Vector B_carom(B.GetData(), B.Size(), true, false); CAROM::Vector X_carom(X.GetData(), X.Size(), true, false); - CAROM::Vector *reducedRHS = spatialbasis->transposeMult(&B_carom); + std::unique_ptr reducedRHS = spatialbasis->transposeMult( + B_carom); CAROM::Vector reducedSol(numColumnRB, false); assembleTimer.Stop(); @@ -492,7 +493,6 @@ int main(int argc, char *argv[]) // 24. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); delete spatialbasis; - delete reducedRHS; } // 25. Recover the parallel grid function corresponding to X. This is the diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index ad025b3b0..bbc15ae2f 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -102,8 +102,9 @@ DMD::DMD(std::string base_file_name) load(base_file_name); } -DMD::DMD(std::vector> eigs, Matrix* phi_real, - Matrix* phi_imaginary, int k, +DMD::DMD(std::vector> eigs, + std::shared_ptr phi_real, + std::shared_ptr phi_imaginary, int k, double dt, double t_offset, Vector* state_offset) { // Get the rank of this process, and the number of processors. @@ -134,12 +135,6 @@ DMD::~DMD() delete sampled_time; } delete d_state_offset; - delete d_basis; - delete d_A_tilde; - delete d_phi_real; - delete d_phi_imaginary; - delete d_phi_real_squared_inverse; - delete d_phi_imaginary_squared_inverse; } void DMD::setOffset(Vector* offset_vector, int order) @@ -254,23 +249,20 @@ DMD::computePhi(struct DMDInternal dmd_internal_obj) // Calculate phi if (d_alt_output_basis) { - Matrix* f_snapshots_out_mult_d_basis_right = - dmd_internal_obj.snapshots_out->mult(dmd_internal_obj.basis_right); - Matrix* f_snapshots_out_mult_d_basis_right_mult_d_S_inv = - f_snapshots_out_mult_d_basis_right->mult(dmd_internal_obj.S_inv); + std::unique_ptr f_snapshots_out_mult_d_basis_right = + dmd_internal_obj.snapshots_out->mult(*dmd_internal_obj.basis_right); + std::unique_ptr f_snapshots_out_mult_d_basis_right_mult_d_S_inv = + f_snapshots_out_mult_d_basis_right->mult(*dmd_internal_obj.S_inv); d_phi_real = f_snapshots_out_mult_d_basis_right_mult_d_S_inv->mult( - dmd_internal_obj.eigenpair->ev_real); + *dmd_internal_obj.eigenpair->ev_real); d_phi_imaginary = f_snapshots_out_mult_d_basis_right_mult_d_S_inv->mult( - dmd_internal_obj.eigenpair->ev_imaginary); - - delete f_snapshots_out_mult_d_basis_right; - delete f_snapshots_out_mult_d_basis_right_mult_d_S_inv; + *dmd_internal_obj.eigenpair->ev_imaginary); } else { - d_phi_real = dmd_internal_obj.basis->mult(dmd_internal_obj.eigenpair->ev_real); + d_phi_real = dmd_internal_obj.basis->mult(*dmd_internal_obj.eigenpair->ev_real); d_phi_imaginary = dmd_internal_obj.basis->mult( - dmd_internal_obj.eigenpair->ev_imaginary); + *dmd_internal_obj.eigenpair->ev_imaginary); } } @@ -364,7 +356,8 @@ DMD::constructDMD(const Matrix* f_snapshots, d_num_singular_vectors << "." << std::endl; // Allocate the appropriate matrices and gather their elements. - d_basis = new Matrix(f_snapshots->numRows(), d_k, f_snapshots->distributed()); + d_basis.reset(new Matrix(f_snapshots->numRows(), d_k, + f_snapshots->distributed())); Matrix* d_S_inv = new Matrix(d_k, d_k, false); Matrix* d_basis_right = new Matrix(f_snapshots_in->numColumns(), d_k, false); @@ -389,7 +382,7 @@ DMD::constructDMD(const Matrix* f_snapshots, d_S_inv->item(i, i) = 1 / d_factorizer->S[static_cast(i)]; } - Matrix* Q = NULL; + std::unique_ptr Q; // If W0 is not null, we need to ensure it is in the basis of W. if (W0 != NULL) @@ -470,10 +463,9 @@ DMD::constructDMD(const Matrix* f_snapshots, d_basis_new->orthogonalize(); // Calculate Q = W* x W_new; - Q = d_basis->transposeMult(d_basis_new); + Q = d_basis->transposeMult(*d_basis_new); - delete d_basis; - d_basis = d_basis_new; + d_basis.reset(d_basis_new); d_k = d_basis_new->numColumns(); if (d_rank == 0) std::cout << "After adding W0, now using " << d_k << @@ -481,28 +473,28 @@ DMD::constructDMD(const Matrix* f_snapshots, } // Calculate A_tilde = U_transpose * f_snapshots_out * V * inv(S) - Matrix* d_basis_mult_f_snapshots_out = d_basis->transposeMult(f_snapshots_out); - Matrix* d_basis_mult_f_snapshots_out_mult_d_basis_right = - d_basis_mult_f_snapshots_out->mult(d_basis_right); + std::unique_ptr d_basis_mult_f_snapshots_out = d_basis->transposeMult( + *f_snapshots_out); + std::unique_ptr d_basis_mult_f_snapshots_out_mult_d_basis_right = + d_basis_mult_f_snapshots_out->mult(*d_basis_right); if (Q == NULL) { - d_A_tilde = d_basis_mult_f_snapshots_out_mult_d_basis_right->mult(d_S_inv); + d_A_tilde = d_basis_mult_f_snapshots_out_mult_d_basis_right->mult(*d_S_inv); } else { - Matrix* d_basis_mult_f_snapshots_out_mult_d_basis_right_mult_d_S_inv = - d_basis_mult_f_snapshots_out_mult_d_basis_right->mult(d_S_inv); + std::unique_ptr + d_basis_mult_f_snapshots_out_mult_d_basis_right_mult_d_S_inv = + d_basis_mult_f_snapshots_out_mult_d_basis_right->mult(*d_S_inv); d_A_tilde = d_basis_mult_f_snapshots_out_mult_d_basis_right_mult_d_S_inv->mult( - Q); - delete Q; - delete d_basis_mult_f_snapshots_out_mult_d_basis_right_mult_d_S_inv; + *Q); } // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(d_A_tilde); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(d_A_tilde.get()); d_eigs = eigenpair.eigs; - struct DMDInternal dmd_internal = {f_snapshots_in, f_snapshots_out, d_basis, d_basis_right, d_S_inv, &eigenpair}; + struct DMDInternal dmd_internal = {f_snapshots_in, f_snapshots_out, d_basis.get(), d_basis_right, d_S_inv, &eigenpair}; computePhi(dmd_internal); Vector* init = new Vector(f_snapshots_in->numRows(), true); @@ -518,8 +510,6 @@ DMD::constructDMD(const Matrix* f_snapshots, delete d_basis_right; delete d_S_inv; - delete d_basis_mult_f_snapshots_out; - delete d_basis_mult_f_snapshots_out_mult_d_basis_right; delete f_snapshots_in; delete f_snapshots_out; delete eigenpair.ev_real; @@ -532,31 +522,33 @@ DMD::constructDMD(const Matrix* f_snapshots, void DMD::projectInitialCondition(const Vector* init, double t_offset) { - Matrix* d_phi_real_squared = d_phi_real->transposeMult(d_phi_real); - Matrix* d_phi_real_squared_2 = d_phi_imaginary->transposeMult(d_phi_imaginary); - *d_phi_real_squared += *d_phi_real_squared_2; - - Matrix* d_phi_imaginary_squared = d_phi_real->transposeMult(d_phi_imaginary); - Matrix* d_phi_imaginary_squared_2 = d_phi_imaginary->transposeMult(d_phi_real); - *d_phi_imaginary_squared -= *d_phi_imaginary_squared_2; - - const int dprs_row = d_phi_real_squared->numRows(); - const int dprs_col = d_phi_real_squared->numColumns(); + d_phi_real_squared_inverse = d_phi_real->transposeMult(*d_phi_real); + std::unique_ptr d_phi_real_squared_2 = d_phi_imaginary->transposeMult( + *d_phi_imaginary); + *d_phi_real_squared_inverse += *d_phi_real_squared_2; + + d_phi_imaginary_squared_inverse = d_phi_real->transposeMult(*d_phi_imaginary); + std::unique_ptr d_phi_imaginary_squared_2 = + d_phi_imaginary->transposeMult(*d_phi_real); + *d_phi_imaginary_squared_inverse -= *d_phi_imaginary_squared_2; + + const int dprs_row = d_phi_real_squared_inverse->numRows(); + const int dprs_col = d_phi_real_squared_inverse->numColumns(); double* inverse_input = new double[dprs_row * dprs_col * 2]; - for (int i = 0; i < d_phi_real_squared->numRows(); i++) + for (int i = 0; i < d_phi_real_squared_inverse->numRows(); i++) { int k = 0; - for (int j = 0; j < d_phi_real_squared->numColumns() * 2; j++) + for (int j = 0; j < d_phi_real_squared_inverse->numColumns() * 2; j++) { if (j % 2 == 0) { - inverse_input[d_phi_real_squared->numColumns() * 2 * i + j] = - d_phi_real_squared->item(i, k); + inverse_input[d_phi_real_squared_inverse->numColumns() * 2 * i + j] = + d_phi_real_squared_inverse->item(i, k); } else { - inverse_input[d_phi_imaginary_squared->numColumns() * 2 * i + j] = - d_phi_imaginary_squared->item(i, k); + inverse_input[d_phi_imaginary_squared_inverse->numColumns() * 2 * i + j] = + d_phi_imaginary_squared_inverse->item(i, k); k++; } } @@ -565,7 +557,7 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) // Call lapack routines to do the inversion. // Set up some stuff the lapack routines need. int info; - int mtx_size = d_phi_real_squared->numColumns(); + int mtx_size = d_phi_real_squared_inverse->numColumns(); int lwork = mtx_size*mtx_size*std::max(10,d_num_procs); int* ipiv = new int [mtx_size]; double* work = new double [lwork]; @@ -574,9 +566,6 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) zgetrf(&mtx_size, &mtx_size, inverse_input, &mtx_size, ipiv, &info); zgetri(&mtx_size, inverse_input, &mtx_size, ipiv, work, &lwork, &info); - d_phi_real_squared_inverse = d_phi_real_squared; - d_phi_imaginary_squared_inverse = d_phi_imaginary_squared; - for (int i = 0; i < d_phi_real_squared_inverse->numRows(); i++) { int k = 0; @@ -596,30 +585,22 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) } } - Vector* rhs_real = d_phi_real->transposeMult(init); - Vector* rhs_imaginary = d_phi_imaginary->transposeMult(init); + std::unique_ptr rhs_real = d_phi_real->transposeMult(*init); + std::unique_ptr rhs_imaginary = d_phi_imaginary->transposeMult(*init); - Vector* d_projected_init_real_1 = d_phi_real_squared_inverse->mult(*rhs_real); - Vector* d_projected_init_real_2 = d_phi_imaginary_squared_inverse->mult( - *rhs_imaginary); + std::unique_ptr d_projected_init_real_1 = + d_phi_real_squared_inverse->mult(*rhs_real); + std::unique_ptr d_projected_init_real_2 = + d_phi_imaginary_squared_inverse->mult(*rhs_imaginary); d_projected_init_real = d_projected_init_real_1->plus(*d_projected_init_real_2); - Vector* d_projected_init_imaginary_1 = d_phi_real_squared_inverse->mult( - *rhs_imaginary); - Vector* d_projected_init_imaginary_2 = d_phi_imaginary_squared_inverse->mult( - *rhs_real); + std::unique_ptr d_projected_init_imaginary_1 = + d_phi_real_squared_inverse->mult(*rhs_imaginary); + std::unique_ptr d_projected_init_imaginary_2 = + d_phi_imaginary_squared_inverse->mult(*rhs_real); d_projected_init_imaginary = d_projected_init_imaginary_2->minus( *d_projected_init_imaginary_1); - delete d_phi_real_squared_2; - delete d_projected_init_real_1; - delete d_projected_init_real_2; - delete d_phi_imaginary_squared_2; - delete d_projected_init_imaginary_1; - delete d_projected_init_imaginary_2; - delete rhs_real; - delete rhs_imaginary; - delete [] inverse_input; delete [] ipiv; delete [] work; @@ -642,25 +623,21 @@ DMD::predict(double t, int deg) t -= d_t_offset; - std::pair d_phi_pair = phiMultEigs(t, deg); - Matrix* d_phi_mult_eigs_real = d_phi_pair.first; - Matrix* d_phi_mult_eigs_imaginary = d_phi_pair.second; + std::pair, std::shared_ptr> d_phi_pair = + phiMultEigs(t, deg); + std::shared_ptr d_phi_mult_eigs_real = d_phi_pair.first; + std::shared_ptr d_phi_mult_eigs_imaginary = d_phi_pair.second; + + std::unique_ptr d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( + *d_projected_init_real); - Vector* d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( - *d_projected_init_real); + std::unique_ptr d_predicted_state_real_2 = + d_phi_mult_eigs_imaginary->mult(*d_projected_init_imaginary); - Vector* d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( - *d_projected_init_imaginary); std::shared_ptr d_predicted_state_real = - d_predicted_state_real_1->minus( - *d_predicted_state_real_2); + d_predicted_state_real_1->minus(*d_predicted_state_real_2); addOffset(*d_predicted_state_real, t, deg); - delete d_phi_mult_eigs_real; - delete d_phi_mult_eigs_imaginary; - delete d_predicted_state_real_1; - delete d_predicted_state_real_2; - return d_predicted_state_real; } @@ -679,8 +656,8 @@ DMD::computeEigExp(std::complex eig, double t) return std::pow(eig, t / d_dt); } -std::pair -DMD::phiMultEigs(double t, int deg) +std::pair,std::shared_ptr> + DMD::phiMultEigs(double t, int deg) { Matrix* d_eigs_exp_real = new Matrix(d_k, d_k, false); Matrix* d_eigs_exp_imaginary = new Matrix(d_k, d_k, false); @@ -696,20 +673,23 @@ DMD::phiMultEigs(double t, int deg) d_eigs_exp_imaginary->item(i, i) = std::imag(eig_exp); } - Matrix* d_phi_mult_eigs_real = d_phi_real->mult(d_eigs_exp_real); - Matrix* d_phi_mult_eigs_real_2 = d_phi_imaginary->mult(d_eigs_exp_imaginary); + std::shared_ptr d_phi_mult_eigs_real = d_phi_real->mult( + *d_eigs_exp_real); + std::unique_ptr d_phi_mult_eigs_real_2 = d_phi_imaginary->mult( + *d_eigs_exp_imaginary); *d_phi_mult_eigs_real -= *d_phi_mult_eigs_real_2; - Matrix* d_phi_mult_eigs_imaginary = d_phi_real->mult(d_eigs_exp_imaginary); - Matrix* d_phi_mult_eigs_imaginary_2 = d_phi_imaginary->mult(d_eigs_exp_real); + std::shared_ptr d_phi_mult_eigs_imaginary = d_phi_real->mult( + *d_eigs_exp_imaginary); + std::unique_ptr d_phi_mult_eigs_imaginary_2 = d_phi_imaginary->mult( + *d_eigs_exp_real); *d_phi_mult_eigs_imaginary += *d_phi_mult_eigs_imaginary_2; delete d_eigs_exp_real; delete d_eigs_exp_imaginary; - delete d_phi_mult_eigs_real_2; - delete d_phi_mult_eigs_imaginary_2; - return std::pair(d_phi_mult_eigs_real, - d_phi_mult_eigs_imaginary); + return std::pair,std::shared_ptr> + (d_phi_mult_eigs_real, + d_phi_mult_eigs_imaginary); } double @@ -791,27 +771,27 @@ DMD::load(std::string base_file_name) database.close(); full_file_name = base_file_name + "_basis"; - d_basis = new Matrix(); + d_basis.reset(new Matrix()); d_basis->read(full_file_name); full_file_name = base_file_name + "_A_tilde"; - d_A_tilde = new Matrix(); + d_A_tilde.reset(new Matrix()); d_A_tilde->read(full_file_name); full_file_name = base_file_name + "_phi_real"; - d_phi_real = new Matrix(); + d_phi_real.reset(new Matrix()); d_phi_real->read(full_file_name); full_file_name = base_file_name + "_phi_imaginary"; - d_phi_imaginary = new Matrix(); + d_phi_imaginary.reset(new Matrix()); d_phi_imaginary->read(full_file_name); full_file_name = base_file_name + "_phi_real_squared_inverse"; - d_phi_real_squared_inverse = new Matrix(); + d_phi_real_squared_inverse.reset(new Matrix()); d_phi_real_squared_inverse->read(full_file_name); full_file_name = base_file_name + "_phi_imaginary_squared_inverse"; - d_phi_imaginary_squared_inverse = new Matrix(); + d_phi_imaginary_squared_inverse.reset(new Matrix()); d_phi_imaginary_squared_inverse->read(full_file_name); full_file_name = base_file_name + "_projected_init_real"; diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index e573b54f5..3ff6d7cb7 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -266,8 +266,8 @@ class DMD * @param[in] t_offset d_t_offset * @param[in] state_offset d_state_offset */ - DMD(std::vector> eigs, Matrix* phi_real, - Matrix* phi_imaginary, int k, + DMD(std::vector> eigs, std::shared_ptr phi_real, + std::shared_ptr phi_imaginary, int k, double dt, double t_offset, Vector* state_offset); /** @@ -290,7 +290,8 @@ class DMD /** * @brief Internal function to multiply d_phi with the eigenvalues. */ - std::pair phiMultEigs(double t, int deg = 0); + std::pair,std::shared_ptr> phiMultEigs( + double t, int deg = 0); /** * @brief Construct the DMD object. @@ -401,7 +402,7 @@ class DMD /** * @brief The left singular vector basis. */ - Matrix* d_basis = NULL; + std::shared_ptr d_basis; /** * @brief Whether to use the alternative basis for output, i.e. phi = U^(+)*V*Omega^(-1)*X. @@ -411,27 +412,27 @@ class DMD /** * @brief A_tilde */ - Matrix* d_A_tilde = NULL; + std::shared_ptr d_A_tilde; /** * @brief The real part of d_phi. */ - Matrix* d_phi_real = NULL; + std::shared_ptr d_phi_real; /** * @brief The imaginary part of d_phi. */ - Matrix* d_phi_imaginary = NULL; + std::shared_ptr d_phi_imaginary; /** * @brief The real part of d_phi_squared_inverse. */ - Matrix* d_phi_real_squared_inverse = NULL; + std::unique_ptr d_phi_real_squared_inverse; /** * @brief The imaginary part of d_phi_squared_inverse. */ - Matrix* d_phi_imaginary_squared_inverse = NULL; + std::unique_ptr d_phi_imaginary_squared_inverse; /** * @brief The real part of the projected initial condition. @@ -441,7 +442,7 @@ class DMD /** * @brief The imaginary part of the projected initial condition. */ - std::shared_ptr d_projected_init_imaginary = NULL; + std::shared_ptr d_projected_init_imaginary; /** * @brief A vector holding the complex eigenvalues of the eigenmodes. diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index 09097e415..7e4f2199c 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -105,8 +105,9 @@ DMDc::DMDc(std::string base_file_name) load(base_file_name); } -DMDc::DMDc(std::vector> eigs, Matrix* phi_real, - Matrix* phi_imaginary, Matrix* B_tilde, int k, +DMDc::DMDc(std::vector> eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, std::shared_ptr B_tilde, int k, double dt, double t_offset, Vector* state_offset, Matrix* basis) { // Get the rank of this process, and the number of processors. @@ -128,7 +129,7 @@ DMDc::DMDc(std::vector> eigs, Matrix* phi_real, d_k = k; d_dt = dt; d_t_offset = t_offset; - d_basis = basis; + d_basis.reset(basis); setOffset(state_offset); } @@ -143,13 +144,6 @@ DMDc::~DMDc() delete sampled_time; } delete d_state_offset; - delete d_basis; - delete d_A_tilde; - delete d_B_tilde; - delete d_phi_real; - delete d_phi_imaginary; - delete d_phi_real_squared_inverse; - delete d_phi_imaginary_squared_inverse; } void DMDc::setOffset(Vector* offset_vector) @@ -278,9 +272,8 @@ DMDc::computeDMDcSnapshotPair(const Matrix* snapshots, const Matrix* controls, } else { - Matrix* Bf = B->mult(controls); + std::unique_ptr Bf = B->mult(*controls); *f_snapshots_out -= *Bf; - delete Bf; } } @@ -403,13 +396,6 @@ DMDc::constructDMDc(const Matrix* f_snapshots, d_S_inv->item(i, i) = 1 / d_factorizer_in->S[static_cast(i)]; } - // Make sure the basis is freed since we are setting it with DMDc class instead - // of manually setting the basis when interpolating - if (d_basis) - { - delete d_basis; - } - if (B == NULL) { // SVD on outputs @@ -490,8 +476,8 @@ DMDc::constructDMDc(const Matrix* f_snapshots, d_num_singular_vectors << " for output." << std::endl; // Allocate the appropriate matrices and gather their elements. - d_basis = new Matrix(f_snapshots_out->numRows(), d_k, - f_snapshots_out->distributed()); + d_basis.reset(new Matrix(f_snapshots_out->numRows(), d_k, + f_snapshots_out->distributed())); for (int d_rank = 0; d_rank < d_num_procs; ++d_rank) { // V is computed in the transposed order so no reordering necessary. gather_block(&d_basis->item(0, 0), d_factorizer_out->V, @@ -503,18 +489,20 @@ DMDc::constructDMDc(const Matrix* f_snapshots, } else { - d_basis = d_basis_in; + d_basis.reset(d_basis_in); d_k = d_k_in; } delete[] row_offset; // Calculate A_tilde and B_tilde - Matrix* d_basis_mult_f_snapshots_out = d_basis->transposeMult(f_snapshots_out); - Matrix* d_basis_mult_f_snapshots_out_mult_d_basis_right = - d_basis_mult_f_snapshots_out->mult(d_basis_right); - Matrix* d_A_tilde_orig = d_basis_mult_f_snapshots_out_mult_d_basis_right->mult( - d_S_inv); + std::unique_ptr d_basis_mult_f_snapshots_out = d_basis->transposeMult( + *f_snapshots_out); + std::unique_ptr d_basis_mult_f_snapshots_out_mult_d_basis_right = + d_basis_mult_f_snapshots_out->mult(*d_basis_right); + std::shared_ptr d_A_tilde_orig = + d_basis_mult_f_snapshots_out_mult_d_basis_right->mult( + *d_S_inv); if (B == NULL) { @@ -535,28 +523,25 @@ DMDc::constructDMDc(const Matrix* f_snapshots, j); } } - Matrix* d_basis_state_rot = d_basis_in_state->transposeMult(d_basis); - d_A_tilde = d_A_tilde_orig->mult(d_basis_state_rot); - d_B_tilde = d_A_tilde_orig->mult(d_basis_in_control_transpose); + std::unique_ptr d_basis_state_rot = d_basis_in_state->transposeMult( + *d_basis); + d_A_tilde = d_A_tilde_orig->mult(*d_basis_state_rot); + d_B_tilde = d_A_tilde_orig->mult(*d_basis_in_control_transpose); delete d_basis_in_state; delete d_basis_in_control_transpose; - delete d_basis_state_rot; } else { d_A_tilde = d_A_tilde_orig; - d_B_tilde = d_basis->transposeMult(B); + d_B_tilde = d_basis->transposeMult(*B); } // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(d_A_tilde); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(d_A_tilde.get()); d_eigs = eigenpair.eigs; - //struct DMDInternal dmd_internal = {f_snapshots_in, f_snapshots_out, d_basis, d_basis_right, d_S_inv, &eigenpair}; - //computePhi(dmd_internal); - - d_phi_real = d_basis->mult(eigenpair.ev_real); - d_phi_imaginary = d_basis->mult(eigenpair.ev_imaginary); + d_phi_real = d_basis->mult(*eigenpair.ev_real); + d_phi_imaginary = d_basis->mult(*eigenpair.ev_imaginary); Vector* init = new Vector(d_basis->numRows(), true); for (int i = 0; i < init->dim(); i++) @@ -571,9 +556,6 @@ DMDc::constructDMDc(const Matrix* f_snapshots, delete d_basis_right; delete d_S_inv; - delete d_basis_mult_f_snapshots_out; - delete d_basis_mult_f_snapshots_out_mult_d_basis_right; - delete d_A_tilde_orig; delete f_snapshots_in; delete f_snapshots_out; delete eigenpair.ev_real; @@ -586,17 +568,18 @@ DMDc::constructDMDc(const Matrix* f_snapshots, void DMDc::project(const Vector* init, const Matrix* controls, double t_offset) { - Matrix* d_phi_real_squared = d_phi_real->transposeMult(d_phi_real); - Matrix* d_phi_real_squared_2 = d_phi_imaginary->transposeMult(d_phi_imaginary); + std::shared_ptr d_phi_real_squared = d_phi_real->transposeMult( + *d_phi_real); + std::unique_ptr d_phi_real_squared_2 = d_phi_imaginary->transposeMult( + *d_phi_imaginary); *d_phi_real_squared += *d_phi_real_squared_2; - Matrix* d_phi_imaginary_squared = d_phi_real->transposeMult(d_phi_imaginary); - Matrix* d_phi_imaginary_squared_2 = d_phi_imaginary->transposeMult(d_phi_real); + std::shared_ptr d_phi_imaginary_squared = d_phi_real->transposeMult( + *d_phi_imaginary); + std::unique_ptr d_phi_imaginary_squared_2 = + d_phi_imaginary->transposeMult(*d_phi_real); *d_phi_imaginary_squared -= *d_phi_imaginary_squared_2; - delete d_phi_real_squared_2; - delete d_phi_imaginary_squared_2; - const int dprs_row = d_phi_real_squared->numRows(); const int dprs_col = d_phi_real_squared->numColumns(); double* inverse_input = new double[dprs_row * dprs_col * 2]; @@ -654,50 +637,40 @@ DMDc::project(const Vector* init, const Matrix* controls, double t_offset) } // Initial condition - Vector* init_real = d_phi_real->transposeMult(init); - Vector* init_imaginary = d_phi_imaginary->transposeMult(init); + std::unique_ptr init_real = d_phi_real->transposeMult(*init); + std::unique_ptr init_imaginary = d_phi_imaginary->transposeMult(*init); - Vector* d_projected_init_real_1 = d_phi_real_squared_inverse->mult(*init_real); - Vector* d_projected_init_real_2 = d_phi_imaginary_squared_inverse->mult( - *init_imaginary); + std::unique_ptr d_projected_init_real_1 = + d_phi_real_squared_inverse->mult(*init_real); + std::unique_ptr d_projected_init_real_2 = + d_phi_imaginary_squared_inverse->mult(*init_imaginary); d_projected_init_real = d_projected_init_real_1->plus(*d_projected_init_real_2); - Vector* d_projected_init_imaginary_1 = d_phi_real_squared_inverse->mult( - *init_imaginary); - Vector* d_projected_init_imaginary_2 = d_phi_imaginary_squared_inverse->mult( - *init_real); + std::unique_ptr d_projected_init_imaginary_1 = + d_phi_real_squared_inverse->mult(*init_imaginary); + std::unique_ptr d_projected_init_imaginary_2 = + d_phi_imaginary_squared_inverse->mult(*init_real); d_projected_init_imaginary = d_projected_init_imaginary_2->minus( *d_projected_init_imaginary_1); - delete init_real; - delete init_imaginary; - delete d_projected_init_real_1; - delete d_projected_init_real_2; - delete d_projected_init_imaginary_1; - delete d_projected_init_imaginary_2; - // Controls - Matrix* B_tilde_f = d_B_tilde->mult(controls); - Matrix* UBf = d_basis->mult(B_tilde_f); - Matrix* controls_real = d_phi_real->transposeMult(UBf); - Matrix* controls_imaginary = d_phi_imaginary->transposeMult(UBf); - - d_projected_controls_real = d_phi_real_squared_inverse->mult(controls_real); - Matrix* d_projected_controls_real_2 = d_phi_imaginary_squared_inverse->mult( - controls_imaginary); + std::unique_ptr B_tilde_f = d_B_tilde->mult(*controls); + std::unique_ptr UBf = d_basis->mult(*B_tilde_f); + std::unique_ptr controls_real = d_phi_real->transposeMult(*UBf); + std::unique_ptr controls_imaginary = d_phi_imaginary->transposeMult( + *UBf); + + d_projected_controls_real = d_phi_real_squared_inverse->mult(*controls_real); + std::unique_ptr d_projected_controls_real_2 = + d_phi_imaginary_squared_inverse->mult(*controls_imaginary); *d_projected_controls_real += *d_projected_controls_real_2; d_projected_controls_imaginary = d_phi_imaginary_squared_inverse->mult( - controls_real); - Matrix* d_projected_controls_imaginary_2 = d_phi_real_squared_inverse->mult( - controls_imaginary); + *controls_real); + std::unique_ptr d_projected_controls_imaginary_2 = + d_phi_real_squared_inverse->mult(*controls_imaginary); *d_projected_controls_imaginary -= *d_projected_controls_imaginary_2; - delete controls_real; - delete controls_imaginary; - delete d_projected_controls_real_2; - delete d_projected_controls_imaginary_2; - delete [] inverse_input; delete [] ipiv; delete [] work; @@ -723,30 +696,26 @@ DMDc::predict(double t) int n = round(t / d_dt); //int n = min(round(t / d_dt), d_projected_controls_real->numColumns()); - std::pair d_phi_pair = phiMultEigs(t); - Matrix* d_phi_mult_eigs_real = d_phi_pair.first; - Matrix* d_phi_mult_eigs_imaginary = d_phi_pair.second; - - Vector* d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( - *d_projected_init_real); + std::pair,std::shared_ptr> d_phi_pair = + phiMultEigs(t); + std::shared_ptr d_phi_mult_eigs_real = d_phi_pair.first; + std::shared_ptr d_phi_mult_eigs_imaginary = d_phi_pair.second; - Vector* d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult( - *d_projected_init_imaginary); + std::unique_ptr d_predicted_state_real_1 = d_phi_mult_eigs_real->mult( + *d_projected_init_real); + std::unique_ptr d_predicted_state_real_2 = + d_phi_mult_eigs_imaginary->mult(*d_projected_init_imaginary); std::unique_ptr d_predicted_state_real = d_predicted_state_real_1->minus(*d_predicted_state_real_2); addOffset(*d_predicted_state_real); - delete d_phi_mult_eigs_real; - delete d_phi_mult_eigs_imaginary; - delete d_predicted_state_real_1; - delete d_predicted_state_real_2; - Vector* f_control_real = new Vector(d_basis->numRows(), false); Vector* f_control_imaginary = new Vector(d_basis->numRows(), false); for (int k = 0; k < n; k++) { t -= d_dt; - std::pair d_phi_pair = phiMultEigs(t); + std::pair, std::shared_ptr> d_phi_pair = + phiMultEigs(t); d_phi_mult_eigs_real = d_phi_pair.first; d_phi_mult_eigs_imaginary = d_phi_pair.second; @@ -758,11 +727,6 @@ DMDc::predict(double t) *f_control_imaginary); *d_predicted_state_real += *d_predicted_state_real_1; *d_predicted_state_real -= *d_predicted_state_real_2; - - delete d_phi_mult_eigs_real; - delete d_phi_mult_eigs_imaginary; - delete d_predicted_state_real_1; - delete d_predicted_state_real_2; } delete f_control_real; @@ -784,8 +748,8 @@ DMDc::computeEigExp(std::complex eig, double t) return std::pow(eig, t / d_dt); } -std::pair -DMDc::phiMultEigs(double t) +std::pair,std::shared_ptr> + DMDc::phiMultEigs(double t) { Matrix* d_eigs_exp_real = new Matrix(d_k, d_k, false); Matrix* d_eigs_exp_imaginary = new Matrix(d_k, d_k, false); @@ -797,20 +761,23 @@ DMDc::phiMultEigs(double t) d_eigs_exp_imaginary->item(i, i) = std::imag(eig_exp); } - Matrix* d_phi_mult_eigs_real = d_phi_real->mult(d_eigs_exp_real); - Matrix* d_phi_mult_eigs_real_2 = d_phi_imaginary->mult(d_eigs_exp_imaginary); + std::shared_ptr d_phi_mult_eigs_real = d_phi_real->mult( + *d_eigs_exp_real); + std::unique_ptr d_phi_mult_eigs_real_2 = d_phi_imaginary->mult( + *d_eigs_exp_imaginary); *d_phi_mult_eigs_real -= *d_phi_mult_eigs_real_2; - Matrix* d_phi_mult_eigs_imaginary = d_phi_real->mult(d_eigs_exp_imaginary); - Matrix* d_phi_mult_eigs_imaginary_2 = d_phi_imaginary->mult(d_eigs_exp_real); + std::shared_ptr d_phi_mult_eigs_imaginary = d_phi_real->mult( + *d_eigs_exp_imaginary); + std::unique_ptr d_phi_mult_eigs_imaginary_2 = d_phi_imaginary->mult( + *d_eigs_exp_real); *d_phi_mult_eigs_imaginary += *d_phi_mult_eigs_imaginary_2; delete d_eigs_exp_real; delete d_eigs_exp_imaginary; - delete d_phi_mult_eigs_real_2; - delete d_phi_mult_eigs_imaginary_2; - return std::pair(d_phi_mult_eigs_real, - d_phi_mult_eigs_imaginary); + return std::pair,std::shared_ptr> + (d_phi_mult_eigs_real, + d_phi_mult_eigs_imaginary); } double @@ -891,31 +858,31 @@ DMDc::load(std::string base_file_name) database.close(); full_file_name = base_file_name + "_basis"; - d_basis = new Matrix(); + d_basis.reset(new Matrix()); d_basis->read(full_file_name); full_file_name = base_file_name + "_A_tilde"; - d_A_tilde = new Matrix(); + d_A_tilde.reset(new Matrix()); d_A_tilde->read(full_file_name); full_file_name = base_file_name + "_B_tilde"; - d_B_tilde = new Matrix(); + d_B_tilde.reset(new Matrix()); d_B_tilde->read(full_file_name); full_file_name = base_file_name + "_phi_real"; - d_phi_real = new Matrix(); + d_phi_real.reset(new Matrix()); d_phi_real->read(full_file_name); full_file_name = base_file_name + "_phi_imaginary"; - d_phi_imaginary = new Matrix(); + d_phi_imaginary.reset(new Matrix()); d_phi_imaginary->read(full_file_name); full_file_name = base_file_name + "_phi_real_squared_inverse"; - d_phi_real_squared_inverse = new Matrix(); + d_phi_real_squared_inverse.reset(new Matrix()); d_phi_real_squared_inverse->read(full_file_name); full_file_name = base_file_name + "_phi_imaginary_squared_inverse"; - d_phi_imaginary_squared_inverse = new Matrix(); + d_phi_imaginary_squared_inverse.reset(new Matrix()); d_phi_imaginary_squared_inverse->read(full_file_name); full_file_name = base_file_name + "_projected_init_real"; diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index 6dc604256..b7f0c9e92 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -212,8 +212,8 @@ class DMDc friend void getParametricDMDc(DMDc*& parametric_dmdc, std::vector& parameter_points, std::vector& dmdcs, - std::vector controls, - Matrix*& controls_interpolated, + std::vector> controls, + std::shared_ptr & controls_interpolated, Vector* desired_point, std::string rbf, std::string interp_method, @@ -242,8 +242,8 @@ class DMDc * @param[in] state_offset d_state_offset * @param[in] basis d_basis, set by DMDc class for offline stages. When interpolating a new DMDc, we enter the interpolated basis explicitly */ - DMDc(std::vector> eigs, Matrix* phi_real, - Matrix* phi_imaginary, Matrix* B_tilde, int k, + DMDc(std::vector> eigs, std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, std::shared_ptr B_tilde, int k, double dt, double t_offset, Vector* state_offset, Matrix* basis = nullptr); /** @@ -266,7 +266,8 @@ class DMDc /** * @brief Internal function to multiply d_phi with the eigenvalues. */ - std::pair phiMultEigs(double t); + std::pair,std::shared_ptr> + phiMultEigs(double t); /** * @brief Construct the DMDc object. @@ -381,37 +382,37 @@ class DMDc /** * @brief The left singular vector basis. */ - Matrix* d_basis = NULL; + std::shared_ptr d_basis; /** * @brief A_tilde */ - Matrix* d_A_tilde = NULL; + std::shared_ptr d_A_tilde; /** * @brief B_tilde */ - Matrix* d_B_tilde = NULL; + std::shared_ptr d_B_tilde; /** * @brief The real part of d_phi. */ - Matrix* d_phi_real = NULL; + std::shared_ptr d_phi_real; /** * @brief The imaginary part of d_phi. */ - Matrix* d_phi_imaginary = NULL; + std::shared_ptr d_phi_imaginary; /** * @brief The real part of d_phi_squared_inverse. */ - Matrix* d_phi_real_squared_inverse = NULL; + std::shared_ptr d_phi_real_squared_inverse; /** * @brief The imaginary part of d_phi_squared_inverse. */ - Matrix* d_phi_imaginary_squared_inverse = NULL; + std::shared_ptr d_phi_imaginary_squared_inverse; /** * @brief The real part of the projected initial condition. @@ -426,12 +427,12 @@ class DMDc /** * @brief The real part of the projected controls. */ - Matrix* d_projected_controls_real = NULL; + std::unique_ptr d_projected_controls_real; /** * @brief The imaginary part of the projected controls. */ - Matrix* d_projected_controls_imaginary = NULL; + std::unique_ptr d_projected_controls_imaginary; /** * @brief A vector holding the complex eigenvalues of the eigenmodes. diff --git a/lib/algo/NonuniformDMD.cpp b/lib/algo/NonuniformDMD.cpp index 72b25b276..3a611cea1 100644 --- a/lib/algo/NonuniformDMD.cpp +++ b/lib/algo/NonuniformDMD.cpp @@ -39,8 +39,8 @@ NonuniformDMD::NonuniformDMD(std::string base_file_name) : DMD(base_file_name) } NonuniformDMD::NonuniformDMD(std::vector> eigs, - Matrix* phi_real, - Matrix* phi_imaginary, int k, + std::shared_ptr phi_real, + std::shared_ptr phi_imaginary, int k, double dt, double t_offset, Vector* state_offset, Vector* derivative_offset) : DMD(eigs, phi_real, phi_imaginary, k, @@ -103,9 +103,9 @@ NonuniformDMD::computeDMDSnapshotPair(const Matrix* snapshots) void NonuniformDMD::computePhi(struct DMDInternal dmd_internal_obj) { - d_phi_real = dmd_internal_obj.basis->mult(dmd_internal_obj.eigenpair->ev_real); + d_phi_real = dmd_internal_obj.basis->mult(*dmd_internal_obj.eigenpair->ev_real); d_phi_imaginary = dmd_internal_obj.basis->mult( - dmd_internal_obj.eigenpair->ev_imaginary); + *dmd_internal_obj.eigenpair->ev_imaginary); } std::complex diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index bd56532c9..0d0316538 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -127,8 +127,9 @@ class NonuniformDMD : public DMD * @param[in] state_offset d_state_offset * @param[in] derivative_offset d_derivative_offset */ - NonuniformDMD(std::vector> eigs, Matrix* phi_real, - Matrix* phi_imaginary, int k, + NonuniformDMD(std::vector> eigs, + std::shared_ptr phi_real, + std::shared_ptr phi_imaginary, int k, double dt, double t_offset, Vector* state_offset, Vector* derivative_offset); diff --git a/lib/algo/ParametricDMD.h b/lib/algo/ParametricDMD.h index dee8a98f3..f91a0e384 100644 --- a/lib/algo/ParametricDMD.h +++ b/lib/algo/ParametricDMD.h @@ -75,8 +75,8 @@ void getParametricDMD(T*& parametric_dmd, MPI_Comm_rank(MPI_COMM_WORLD, &rank); - std::vector bases; - std::vector A_tildes; + std::vector> bases; + std::vector> A_tildes; for (int i = 0; i < dmds.size(); i++) { bases.push_back(dmds[i]->d_basis); @@ -84,39 +84,34 @@ void getParametricDMD(T*& parametric_dmd, } int ref_point = getClosestPoint(parameter_points, desired_point); - std::vector rotation_matrices = obtainRotationMatrices( - parameter_points, - bases, ref_point); + std::vector> rotation_matrices = + obtainRotationMatrices(parameter_points, bases, ref_point); CAROM::MatrixInterpolator basis_interpolator(parameter_points, rotation_matrices, bases, ref_point, "B", rbf, interp_method, closest_rbf_val); - CAROM::Matrix* W = basis_interpolator.interpolate(desired_point, - reorthogonalize_W); + std::shared_ptr W = basis_interpolator.interpolate(desired_point, + reorthogonalize_W); CAROM::MatrixInterpolator A_tilde_interpolator(parameter_points, rotation_matrices, A_tildes, ref_point, "R", rbf, interp_method, closest_rbf_val); - CAROM::Matrix* A_tilde = A_tilde_interpolator.interpolate(desired_point); + std::shared_ptr A_tilde = A_tilde_interpolator.interpolate( + desired_point); // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(A_tilde); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(A_tilde.get()); std::vector> eigs = eigenpair.eigs; // Calculate phi (phi = W * eigenvectors) - CAROM::Matrix* phi_real = W->mult(eigenpair.ev_real); - CAROM::Matrix* phi_imaginary = W->mult(eigenpair.ev_imaginary); + std::shared_ptr phi_real = W->mult(*eigenpair.ev_real); + std::shared_ptr phi_imaginary = W->mult(*eigenpair.ev_imaginary); parametric_dmd = new T(eigs, phi_real, phi_imaginary, dmds[0]->d_k, dmds[0]->d_dt, dmds[0]->d_t_offset, dmds[0]->d_state_offset); - delete W; - delete A_tilde; delete eigenpair.ev_real; delete eigenpair.ev_imaginary; - - for (auto m : rotation_matrices) - delete m; } /** diff --git a/lib/algo/ParametricDMDc.h b/lib/algo/ParametricDMDc.h index 78639a351..d8b1c1a9f 100644 --- a/lib/algo/ParametricDMDc.h +++ b/lib/algo/ParametricDMDc.h @@ -56,8 +56,8 @@ template void getParametricDMDc(T*& parametric_dmdc, std::vector& parameter_points, std::vector& dmdcs, - std::vector controls, - Matrix*& controls_interpolated, + std::vector> controls, + std::shared_ptr & controls_interpolated, Vector* desired_point, std::string rbf = "G", std::string interp_method = "LS", @@ -81,9 +81,10 @@ void getParametricDMDc(T*& parametric_dmdc, MPI_Comm_rank(MPI_COMM_WORLD, &rank); - std::vector bases; - std::vector A_tildes; - std::vector B_tildes; + std::vector> bases; + std::vector> A_tildes; + std::vector> B_tildes; + for (int i = 0; i < dmdcs.size(); i++) { bases.push_back(dmdcs[i]->d_basis); @@ -92,24 +93,25 @@ void getParametricDMDc(T*& parametric_dmdc, } int ref_point = getClosestPoint(parameter_points, desired_point); - std::vector rotation_matrices = obtainRotationMatrices( - parameter_points, - bases, ref_point); + std::vector> rotation_matrices = + obtainRotationMatrices(parameter_points, bases, ref_point); CAROM::MatrixInterpolator basis_interpolator(parameter_points, rotation_matrices, bases, ref_point, "B", rbf, interp_method, closest_rbf_val); - CAROM::Matrix* W = basis_interpolator.interpolate(desired_point, - reorthogonalize_W); + std::shared_ptr W = basis_interpolator.interpolate(desired_point, + reorthogonalize_W); CAROM::MatrixInterpolator A_tilde_interpolator(parameter_points, rotation_matrices, A_tildes, ref_point, "R", rbf, interp_method, closest_rbf_val); - CAROM::Matrix* A_tilde = A_tilde_interpolator.interpolate(desired_point); + std::shared_ptr A_tilde = A_tilde_interpolator.interpolate( + desired_point); CAROM::MatrixInterpolator B_tilde_interpolator(parameter_points, rotation_matrices, B_tildes, ref_point, "R", rbf, interp_method, closest_rbf_val); - CAROM::Matrix* B_tilde = B_tilde_interpolator.interpolate(desired_point); + std::shared_ptr B_tilde = B_tilde_interpolator.interpolate( + desired_point); CAROM::MatrixInterpolator control_interpolator(parameter_points, rotation_matrices, controls, ref_point, "R", rbf, interp_method, @@ -118,24 +120,19 @@ void getParametricDMDc(T*& parametric_dmdc, controls_interpolated = control_interpolator.interpolate(desired_point); // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(A_tilde); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(A_tilde.get()); std::vector> eigs = eigenpair.eigs; // Calculate phi (phi = W * eigenvectors) - CAROM::Matrix* phi_real = W->mult(eigenpair.ev_real); - CAROM::Matrix* phi_imaginary = W->mult(eigenpair.ev_imaginary); + std::shared_ptr phi_real = W->mult(*eigenpair.ev_real); + std::shared_ptr phi_imaginary = W->mult(*eigenpair.ev_imaginary); parametric_dmdc = new T(eigs, phi_real, phi_imaginary, B_tilde, dmdcs[0]->d_k,dmdcs[0]->d_dt, - dmdcs[0]->d_t_offset, dmdcs[0]->d_state_offset, W); + dmdcs[0]->d_t_offset, dmdcs[0]->d_state_offset, W.get()); - delete A_tilde; delete eigenpair.ev_real; delete eigenpair.ev_imaginary; - - for (auto m : rotation_matrices) - delete m; - } /** @@ -164,8 +161,8 @@ template void getParametricDMDc(T*& parametric_dmdc, std::vector& parameter_points, std::vector& dmdc_paths, - std::vector controls, - Matrix*& controls_interpolated, + std::vector> controls, + std::shared_ptr & controls_interpolated, Vector* desired_point, std::string rbf = "G", std::string interp_method = "LS", diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index bc010f052..877aed94a 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -118,10 +118,10 @@ class SnapshotDMD : public DMD * @param[in] state_offset d_state_offset * @param[in] derivative_offset d_derivative_offset */ - SnapshotDMD(std::vector> eigs, Matrix* phi_real, - Matrix* phi_imaginary, int k, - double dt, double t_offset, - Vector* state_offset) : + SnapshotDMD(std::vector> eigs, + std::shared_ptr phi_real, + std::shared_ptr phi_imaginary, int k, double dt, + double t_offset, Vector* state_offset) : DMD(eigs, phi_real, phi_imaginary, k, dt, t_offset, state_offset) {} private: diff --git a/lib/algo/manifold_interp/Interpolator.cpp b/lib/algo/manifold_interp/Interpolator.cpp index 77ffe7668..3b0ad3267 100644 --- a/lib/algo/manifold_interp/Interpolator.cpp +++ b/lib/algo/manifold_interp/Interpolator.cpp @@ -29,8 +29,8 @@ using namespace std; namespace CAROM { -Interpolator::Interpolator(std::vector parameter_points, - std::vector rotation_matrices, +Interpolator::Interpolator(std::vector & parameter_points, + std::vector> & rotation_matrices, int ref_point, std::string rbf, std::string interp_method, @@ -67,9 +67,9 @@ Interpolator::~Interpolator() delete d_lambda_T; } -std::vector obtainRBFToTrainingPoints(std::vector - parameter_points, - std::string interp_method, std::string rbf, double epsilon, Vector* point) +std::vector obtainRBFToTrainingPoints( + std::vector & parameter_points, + std::string interp_method, std::string rbf, double epsilon, Vector* point) { std::vector rbfs; if (interp_method == "LS") @@ -173,7 +173,7 @@ double obtainRBF(std::string rbf, double epsilon, Vector* point1, return res; } -double convertClosestRBFToEpsilon(std::vector parameter_points, +double convertClosestRBFToEpsilon(std::vector & parameter_points, std::string rbf, double closest_rbf_val) { double closest_point_dist = INT_MAX; @@ -216,10 +216,10 @@ double convertClosestRBFToEpsilon(std::vector parameter_points, return epsilon; } -std::vector obtainRotationMatrices(std::vector - parameter_points, - std::vector bases, - int ref_point) +std::vector> obtainRotationMatrices( + std::vector & parameter_points, + std::vector> & bases, + int ref_point) { // Get the rank of this process, and the number of processors. int mpi_init; @@ -233,7 +233,7 @@ std::vector obtainRotationMatrices(std::vector MPI_Comm_rank(MPI_COMM_WORLD, &rank); MPI_Comm_size(MPI_COMM_WORLD, &num_procs); - std::vector rotation_matrices; + std::vector> rotation_matrices; // Obtain the rotation matrices to rotate the bases into // the same generalized coordinate space. @@ -247,8 +247,8 @@ std::vector obtainRotationMatrices(std::vector // since the ref point doesn't need to be rotated. if (i == ref_point) { - Matrix* identity_matrix = new Matrix(bases[i]->numColumns(), - bases[i]->numColumns(), false); + std::shared_ptr identity_matrix(new Matrix(bases[i]->numColumns(), + bases[i]->numColumns(), false)); for (int j = 0; j < identity_matrix->numColumns(); j++) { identity_matrix->item(j, j) = 1.0; } @@ -256,7 +256,8 @@ std::vector obtainRotationMatrices(std::vector continue; } - Matrix* basis_mult_basis = bases[i]->transposeMult(bases[ref_point]); + std::unique_ptr basis_mult_basis = bases[i]->transposeMult( + *bases[ref_point]); Matrix* basis = new Matrix(basis_mult_basis->numRows(), basis_mult_basis->numColumns(), false); Matrix* basis_right = new Matrix(basis_mult_basis->numColumns(), @@ -268,7 +269,7 @@ std::vector obtainRotationMatrices(std::vector if (rank == 0) { Vector* sv = new Vector(basis_mult_basis->numColumns(), false); - SerialSVD(basis_mult_basis, basis_right, sv, basis); + SerialSVD(basis_mult_basis.get(), basis_right, sv, basis); delete sv; } @@ -280,9 +281,8 @@ std::vector obtainRotationMatrices(std::vector MPI_COMM_WORLD); // Obtain the rotation matrix. - Matrix* rotation_matrix = basis->mult(basis_right); + std::shared_ptr rotation_matrix = basis->mult(*basis_right); - delete basis_mult_basis; delete basis; delete basis_right; rotation_matrices.push_back(rotation_matrix); diff --git a/lib/algo/manifold_interp/Interpolator.h b/lib/algo/manifold_interp/Interpolator.h index 11df9fac8..88711ad61 100644 --- a/lib/algo/manifold_interp/Interpolator.h +++ b/lib/algo/manifold_interp/Interpolator.h @@ -15,6 +15,7 @@ #include #include +#include namespace CAROM { @@ -50,8 +51,8 @@ class Interpolator * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ - Interpolator(std::vector parameter_points, - std::vector rotation_matrices, + Interpolator(std::vector & parameter_points, + std::vector> & rotation_matrices, int ref_point, std::string rbf, std::string interp_method, @@ -102,7 +103,7 @@ class Interpolator /** * @brief The reduced bases with compatible coordinates. */ - std::vector d_rotation_matrices; + std::vector> d_rotation_matrices; /** * @brief The RHS of the linear solve in tangential space. @@ -144,9 +145,9 @@ class Interpolator influence. * @param[in] point The unsampled parameter point. */ -std::vector obtainRBFToTrainingPoints(std::vector - parameter_points, - std::string interp_method, std::string rbf, double epsilon, Vector* point); +std::vector obtainRBFToTrainingPoints( + std::vector & parameter_points, + std::string interp_method, std::string rbf, double epsilon, Vector* point); /** * @brief Compute the sum of the RBF weights. @@ -175,7 +176,7 @@ double obtainRBF(std::string rbf, double epsilon, Vector* point1, * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ -double convertClosestRBFToEpsilon(std::vector parameter_points, +double convertClosestRBFToEpsilon(std::vector & parameter_points, std::string rbf, double closest_rbf_val); /** @@ -188,10 +189,10 @@ double convertClosestRBFToEpsilon(std::vector parameter_points, * @param[in] ref_point The index within the vector of parameter points * to the reference point */ -std::vector obtainRotationMatrices(std::vector - parameter_points, - std::vector bases, - int ref_point); +std::vector> obtainRotationMatrices( + std::vector & parameter_points, + std::vector> & bases, + int ref_point); } diff --git a/lib/algo/manifold_interp/MatrixInterpolator.cpp b/lib/algo/manifold_interp/MatrixInterpolator.cpp index a0606344a..9f55bbd61 100644 --- a/lib/algo/manifold_interp/MatrixInterpolator.cpp +++ b/lib/algo/manifold_interp/MatrixInterpolator.cpp @@ -37,9 +37,9 @@ using namespace std; namespace CAROM { -MatrixInterpolator::MatrixInterpolator(std::vector parameter_points, - std::vector rotation_matrices, - std::vector reduced_matrices, +MatrixInterpolator::MatrixInterpolator(std::vector & parameter_points, + std::vector> & rotation_matrices, + std::vector> & reduced_matrices, int ref_point, std::string matrix_type, std::string rbf, @@ -64,61 +64,41 @@ MatrixInterpolator::MatrixInterpolator(std::vector parameter_points, if (i == d_ref_point) { d_rotated_reduced_matrices.push_back(reduced_matrices[i]); - d_rotated_reduced_matrices_owned.push_back(false); } else { if (reduced_matrices[i]->numRows() == rotation_matrices[i]->numRows() && reduced_matrices[i]->numColumns() == rotation_matrices[i]->numRows()) { - Matrix* Q_tA = rotation_matrices[i]->transposeMult(reduced_matrices[i]); - Matrix* Q_tAQ = Q_tA->mult(rotation_matrices[i]); - delete Q_tA; + std::unique_ptr Q_tA = rotation_matrices[i]->transposeMult( + *reduced_matrices[i]); + std::shared_ptr Q_tAQ = Q_tA->mult(*rotation_matrices[i]); d_rotated_reduced_matrices.push_back(Q_tAQ); - d_rotated_reduced_matrices_owned.push_back(true); } else if (reduced_matrices[i]->numRows() == rotation_matrices[i]->numRows()) { - Matrix* Q_tA = rotation_matrices[i]->transposeMult(reduced_matrices[i]); + std::shared_ptr Q_tA = rotation_matrices[i]->transposeMult( + *reduced_matrices[i]); d_rotated_reduced_matrices.push_back(Q_tA); - d_rotated_reduced_matrices_owned.push_back(true); } else if (reduced_matrices[i]->numColumns() == rotation_matrices[i]->numRows()) { - Matrix* AQ = reduced_matrices[i]->mult(rotation_matrices[i]); + std::shared_ptr AQ = reduced_matrices[i]->mult(*rotation_matrices[i]); d_rotated_reduced_matrices.push_back(AQ); - d_rotated_reduced_matrices_owned.push_back(true); } else { d_rotated_reduced_matrices.push_back(reduced_matrices[i]); - d_rotated_reduced_matrices_owned.push_back(false); } } } } -MatrixInterpolator::~MatrixInterpolator() +std::shared_ptr MatrixInterpolator::interpolate(Vector* point, + bool orthogonalize) { - CAROM_VERIFY(d_rotated_reduced_matrices.size() == - d_rotated_reduced_matrices_owned.size()); - - for (int i=0; i interpolated_matrix; if (d_matrix_type == "SPD") { interpolated_matrix = interpolateSPDMatrix(point); @@ -235,41 +215,40 @@ Matrix* MatrixInterpolator::obtainLogInterpolatedMatrix( return log_interpolated_matrix; } -Matrix* MatrixInterpolator::interpolateSPDMatrix(Vector* point) +std::shared_ptr MatrixInterpolator::interpolateSPDMatrix(Vector* point) { if (d_gammas.size() == 0) { // Diagonalize X to work towards obtaining X^-1/2 EigenPair ref_reduced_matrix_eigenpair = SymmetricRightEigenSolve( - d_rotated_reduced_matrices[d_ref_point]); + d_rotated_reduced_matrices[d_ref_point].get()); Matrix* ref_reduced_matrix_ev = ref_reduced_matrix_eigenpair.ev; - Matrix* ref_reduced_matrix_ev_inv = NULL; Matrix* ref_reduced_matrix_sqrt_eigs = new Matrix( ref_reduced_matrix_eigenpair.eigs.size(), ref_reduced_matrix_eigenpair.eigs.size(), false); for (int i = 0; i < ref_reduced_matrix_eigenpair.eigs.size(); i++) { - ref_reduced_matrix_sqrt_eigs->item(i, - i) = std::sqrt(ref_reduced_matrix_eigenpair.eigs[i]); + ref_reduced_matrix_sqrt_eigs->item(i, i) = + std::sqrt(ref_reduced_matrix_eigenpair.eigs[i]); } + Matrix ref_reduced_matrix_ev_inv(*ref_reduced_matrix_ev); ref_reduced_matrix_ev->inverse(ref_reduced_matrix_ev_inv); // Obtain X^1/2 - Matrix* ref_reduced_matrix_ev_mult_sqrt_eig = ref_reduced_matrix_ev->mult( - ref_reduced_matrix_sqrt_eigs); + std::unique_ptr ref_reduced_matrix_ev_mult_sqrt_eig = + ref_reduced_matrix_ev->mult(*ref_reduced_matrix_sqrt_eigs); d_x_half_power = ref_reduced_matrix_ev_mult_sqrt_eig->mult( ref_reduced_matrix_ev_inv); - Matrix* x_half_power_inv = NULL; + + Matrix x_half_power_inv(*d_x_half_power); // Obtain X^-1/2 d_x_half_power->inverse(x_half_power_inv); delete ref_reduced_matrix_ev; - delete ref_reduced_matrix_ev_inv; delete ref_reduced_matrix_sqrt_eigs; - delete ref_reduced_matrix_ev_mult_sqrt_eig; // Obtain gammas for all points in the database. for (int i = 0; i < d_parameter_points.size(); i++) @@ -277,19 +256,19 @@ Matrix* MatrixInterpolator::interpolateSPDMatrix(Vector* point) // For the ref point, gamma is the zero matrix if (i == d_ref_point) { - Matrix* gamma = new Matrix(x_half_power_inv->numRows(), - x_half_power_inv->numColumns(), x_half_power_inv->distributed()); + std::shared_ptr gamma(new Matrix(x_half_power_inv.numRows(), + x_half_power_inv.numColumns(), + x_half_power_inv.distributed())); d_gammas.push_back(gamma); } else { - Matrix* x_half_power_inv_mult_y = x_half_power_inv->mult( - d_rotated_reduced_matrices[i]); + std::unique_ptr x_half_power_inv_mult_y = x_half_power_inv.mult( + *d_rotated_reduced_matrices[i]); // Obtain X^-1/2*Y*X^-1/2 - Matrix* x_half_power_inv_mult_y_mult_x_half_power_inv = + std::unique_ptr x_half_power_inv_mult_y_mult_x_half_power_inv = x_half_power_inv_mult_y->mult(x_half_power_inv); - delete x_half_power_inv_mult_y; // Diagonalize X^-1/2*Y*X^-1/2 to obtain the log of this matrix. // Diagonalize YX^-1 to obtain log of this matrix. @@ -298,10 +277,8 @@ Matrix* MatrixInterpolator::interpolateSPDMatrix(Vector* point) // of M and V are the eigenvectors of M. // 2. log M = V(log M')V^-1 EigenPair log_eigenpair = SymmetricRightEigenSolve( - x_half_power_inv_mult_y_mult_x_half_power_inv); - delete x_half_power_inv_mult_y_mult_x_half_power_inv; + x_half_power_inv_mult_y_mult_x_half_power_inv.get()); Matrix* log_ev = log_eigenpair.ev; - Matrix* log_ev_inv = NULL; Matrix* log_eigs = new Matrix(log_eigenpair.eigs.size(), log_eigenpair.eigs.size(), false); @@ -318,22 +295,19 @@ Matrix* MatrixInterpolator::interpolateSPDMatrix(Vector* point) } // Invert matrix. + Matrix log_ev_inv(*log_ev); log_ev->inverse(log_ev_inv); // Perform log mapping. - Matrix* log_ev_mult_log_eig = log_ev->mult(log_eigs); - Matrix* gamma = log_ev_mult_log_eig->mult(log_ev_inv); + std::unique_ptr log_ev_mult_log_eig = log_ev->mult(*log_eigs); + std::shared_ptr gamma = log_ev_mult_log_eig->mult(log_ev_inv); d_gammas.push_back(gamma); delete log_ev; - delete log_ev_inv; delete log_eigs; - delete log_ev_mult_log_eig; } } - delete x_half_power_inv; - // Obtain lambda for the P interpolation matrix obtainLambda(); } @@ -356,7 +330,6 @@ Matrix* MatrixInterpolator::interpolateSPDMatrix(Vector* point) delete log_interpolated_matrix; Matrix* exp_ev = exp_eigenpair.ev; - Matrix* exp_ev_inv = NULL; Matrix* exp_eigs = new Matrix(exp_eigenpair.eigs.size(), exp_eigenpair.eigs.size(), false); @@ -365,32 +338,33 @@ Matrix* MatrixInterpolator::interpolateSPDMatrix(Vector* point) exp_eigs->item(i, i) = std::exp(exp_eigenpair.eigs[i]); } + Matrix exp_ev_inv(*exp_ev); exp_ev->inverse(exp_ev_inv); - Matrix* exp_ev_mult_exp_eig = exp_ev->mult(exp_eigs); + std::unique_ptr exp_ev_mult_exp_eig = exp_ev->mult(*exp_eigs); // Exponentiate gamma - Matrix* exp_gamma = exp_ev_mult_exp_eig->mult(exp_ev_inv); + std::unique_ptr exp_gamma = exp_ev_mult_exp_eig->mult(exp_ev_inv); delete exp_ev; - delete exp_ev_inv; delete exp_eigs; - delete exp_ev_mult_exp_eig; // Obtain exp mapping by doing X^1/2*exp(gamma)*X^1/2 - Matrix* x_half_power_mult_exp_gamma = d_x_half_power->mult(exp_gamma); - Matrix* interpolated_matrix = x_half_power_mult_exp_gamma->mult(d_x_half_power); + std::unique_ptr x_half_power_mult_exp_gamma = d_x_half_power->mult( + *exp_gamma); + std::shared_ptr interpolated_matrix = x_half_power_mult_exp_gamma->mult( + *d_x_half_power); - delete x_half_power_mult_exp_gamma; return interpolated_matrix; } -Matrix* MatrixInterpolator::interpolateNonSingularMatrix(Vector* point) +std::shared_ptr MatrixInterpolator::interpolateNonSingularMatrix( + Vector* point) { if (d_gammas.size() == 0) { // Invert X - Matrix* ref_matrix_inv = NULL; + Matrix ref_matrix_inv(*d_rotated_reduced_matrices[d_ref_point]); d_rotated_reduced_matrices[d_ref_point]->inverse(ref_matrix_inv); for (int i = 0; i < d_parameter_points.size(); i++) @@ -398,24 +372,22 @@ Matrix* MatrixInterpolator::interpolateNonSingularMatrix(Vector* point) // For ref_point, gamma is the zero matrix if (i == d_ref_point) { - Matrix* gamma = new Matrix(ref_matrix_inv->numRows(), - ref_matrix_inv->numColumns(), ref_matrix_inv->distributed()); + std::shared_ptr gamma(new Matrix(ref_matrix_inv.numRows(), + ref_matrix_inv.numColumns(), ref_matrix_inv.distributed())); d_gammas.push_back(gamma); } else { - Matrix* y_mult_ref_matrix_inv = d_rotated_reduced_matrices[i]->mult( - ref_matrix_inv); + std::unique_ptr y_mult_ref_matrix_inv = + d_rotated_reduced_matrices[i]->mult(ref_matrix_inv); // Diagonalize YX^-1 to obtain log of this matrix. // Following https://en.wikipedia.org/wiki/Logarithm_of_a_matrix // 1. Diagonalize M to obtain M' = V^-1*M*V. M' are the eigenvalues // of M and V are the eigenvectors of M. // 2. log M = V(log M')V^-1 - EigenPair log_eigenpair = SymmetricRightEigenSolve(y_mult_ref_matrix_inv); - delete y_mult_ref_matrix_inv; + EigenPair log_eigenpair = SymmetricRightEigenSolve(y_mult_ref_matrix_inv.get()); Matrix* log_ev = log_eigenpair.ev; - Matrix* log_ev_inv = NULL; Matrix* log_eigs = new Matrix(log_eigenpair.eigs.size(), log_eigenpair.eigs.size(), false); @@ -431,22 +403,19 @@ Matrix* MatrixInterpolator::interpolateNonSingularMatrix(Vector* point) log_eigs->item(i, i) = std::log(log_eigenpair.eigs[i]); } + Matrix log_ev_inv(log_ev->numRows(), log_ev->numColumns(), false); log_ev->inverse(log_ev_inv); // Perform log mapping. - Matrix* log_ev_mult_log_eig = log_ev->mult(log_eigs); - Matrix* gamma = log_ev_mult_log_eig->mult(log_ev_inv); + std::unique_ptr log_ev_mult_log_eig = log_ev->mult(*log_eigs); + std::shared_ptr gamma = log_ev_mult_log_eig->mult(log_ev_inv); d_gammas.push_back(gamma); delete log_ev; - delete log_ev_inv; delete log_eigs; - delete log_ev_mult_log_eig; } } - delete ref_matrix_inv; - // Obtain lambda for the P interpolation matrix obtainLambda(); } @@ -477,28 +446,26 @@ Matrix* MatrixInterpolator::interpolateNonSingularMatrix(Vector* point) } // Invert matrix. - exp_ev->inverse(exp_ev_inv); + exp_ev->inverse(*exp_ev_inv); // Perform log mapping. - Matrix* exp_ev_mult_exp_eig = exp_ev->mult(exp_eigs); + std::unique_ptr exp_ev_mult_exp_eig = exp_ev->mult(*exp_eigs); // Exponentiate gamma - Matrix* exp_gamma = exp_ev_mult_exp_eig->mult(exp_ev_inv); + std::unique_ptr exp_gamma = exp_ev_mult_exp_eig->mult(*exp_ev_inv); delete exp_ev; delete exp_ev_inv; delete exp_eigs; - delete exp_ev_mult_exp_eig; // Obtain exp mapping by doing exp(gamma)*X - Matrix* interpolated_matrix = exp_gamma->mult( - d_rotated_reduced_matrices[d_ref_point]); - delete exp_gamma; + std::shared_ptr interpolated_matrix = exp_gamma->mult( + *d_rotated_reduced_matrices[d_ref_point]); return interpolated_matrix; } -Matrix* MatrixInterpolator::interpolateMatrix(Vector* point) +std::shared_ptr MatrixInterpolator::interpolateMatrix(Vector* point) { if (d_gammas.size() == 0) { @@ -507,15 +474,16 @@ Matrix* MatrixInterpolator::interpolateMatrix(Vector* point) // For ref point, gamma is the zero matrix. if (i == d_ref_point) { - Matrix* gamma = new Matrix(d_rotated_reduced_matrices[d_ref_point]->numRows(), - d_rotated_reduced_matrices[d_ref_point]->numColumns(), - d_rotated_reduced_matrices[d_ref_point]->distributed()); + std::shared_ptr gamma(new Matrix( + d_rotated_reduced_matrices[d_ref_point]->numRows(), + d_rotated_reduced_matrices[d_ref_point]->numColumns(), + d_rotated_reduced_matrices[d_ref_point]->distributed())); d_gammas.push_back(gamma); } else { // Gamma is Y - X - Matrix* gamma = new Matrix(*d_rotated_reduced_matrices[i]); + std::shared_ptr gamma(new Matrix(*d_rotated_reduced_matrices[i])); *gamma -= *d_rotated_reduced_matrices[d_ref_point]; d_gammas.push_back(gamma); } @@ -530,7 +498,7 @@ Matrix* MatrixInterpolator::interpolateMatrix(Vector* point) d_rbf, d_epsilon, point); // Interpolate gammas to get gamma for new point - Matrix* interpolated_matrix = obtainLogInterpolatedMatrix(rbf); + std::shared_ptr interpolated_matrix(obtainLogInterpolatedMatrix(rbf)); // The exp mapping is X + the interpolated gamma *interpolated_matrix += *d_rotated_reduced_matrices[d_ref_point]; diff --git a/lib/algo/manifold_interp/MatrixInterpolator.h b/lib/algo/manifold_interp/MatrixInterpolator.h index 9ad284dbd..a89382d23 100644 --- a/lib/algo/manifold_interp/MatrixInterpolator.h +++ b/lib/algo/manifold_interp/MatrixInterpolator.h @@ -59,24 +59,22 @@ class MatrixInterpolator : public Interpolator * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ - MatrixInterpolator(std::vector parameter_points, - std::vector rotation_matrices, - std::vector reduced_matrices, + MatrixInterpolator(std::vector & parameter_points, + std::vector> & rotation_matrices, + std::vector> & reduced_matrices, int ref_point, std::string matrix_type, std::string rbf = "G", std::string interp_method = "LS", double closest_rbf_val = 0.9); - ~MatrixInterpolator(); - /** * @brief Obtain the interpolated reduced matrix of the unsampled parameter point. * * @param[in] point The unsampled parameter point. * @param[in] orthogonalize Whether to orthogonalize the resulting interpolated matrix. */ - Matrix* interpolate(Vector* point, bool orthogonalize = false); + std::shared_ptr interpolate(Vector* point, bool orthogonalize = false); private: @@ -118,7 +116,7 @@ class MatrixInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - Matrix* interpolateSPDMatrix(Vector* point); + std::shared_ptr interpolateSPDMatrix(Vector* point); /** * @brief Obtain the interpolated non-singular reduced matrix for the @@ -126,7 +124,7 @@ class MatrixInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - Matrix* interpolateNonSingularMatrix(Vector* point); + std::shared_ptr interpolateNonSingularMatrix(Vector* point); /** * @brief Obtain the interpolated reduced matrix for the @@ -134,7 +132,7 @@ class MatrixInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - Matrix* interpolateMatrix(Vector* point); + std::shared_ptr interpolateMatrix(Vector* point); /** * @brief The matrix type/manifold @@ -144,19 +142,17 @@ class MatrixInterpolator : public Interpolator /** * @brief The reduced matrices with compatible coordinates. */ - std::vector d_rotated_reduced_matrices; - - std::vector d_rotated_reduced_matrices_owned; + std::vector> d_rotated_reduced_matrices; /** * @brief The reduced elements in tangential space. */ - std::vector d_gammas; + std::vector> d_gammas; /** * @brief The reduced matrix of the reference point to the half power. */ - Matrix* d_x_half_power = nullptr; + std::shared_ptr d_x_half_power; }; } diff --git a/lib/algo/manifold_interp/VectorInterpolator.cpp b/lib/algo/manifold_interp/VectorInterpolator.cpp index 3b984cb64..335b5db16 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.cpp +++ b/lib/algo/manifold_interp/VectorInterpolator.cpp @@ -38,9 +38,9 @@ using namespace std; namespace CAROM { -VectorInterpolator::VectorInterpolator(std::vector parameter_points, - std::vector rotation_matrices, - std::vector reduced_vectors, +VectorInterpolator::VectorInterpolator(std::vector & parameter_points, + std::vector> & rotation_matrices, + std::vector> & reduced_vectors, int ref_point, std::string rbf, std::string interp_method, @@ -59,29 +59,12 @@ VectorInterpolator::VectorInterpolator(std::vector parameter_points, { // The ref_point does not need to be rotated if (i == d_ref_point) - { d_rotated_reduced_vectors.push_back(reduced_vectors[i]); - d_rotated_reduced_vectors_owned.push_back(false); - } else { - Vector* Q_tA = rotation_matrices[i]->transposeMult(reduced_vectors[i]); + std::shared_ptr Q_tA = rotation_matrices[i]->transposeMult( + *reduced_vectors[i]); d_rotated_reduced_vectors.push_back(Q_tA); - d_rotated_reduced_vectors_owned.push_back(true); - } - } -} - -VectorInterpolator::~VectorInterpolator() -{ - CAROM_VERIFY(d_rotated_reduced_vectors.size() == - d_rotated_reduced_vectors_owned.size()); - - for (int i = 0; i < d_rotated_reduced_vectors.size(); i++) - { - if (d_rotated_reduced_vectors_owned[i]) - { - delete d_rotated_reduced_vectors[i]; } } } diff --git a/lib/algo/manifold_interp/VectorInterpolator.h b/lib/algo/manifold_interp/VectorInterpolator.h index f00c1223f..93aaee77f 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.h +++ b/lib/algo/manifold_interp/VectorInterpolator.h @@ -54,16 +54,14 @@ class VectorInterpolator : public Interpolator * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ - VectorInterpolator(std::vector parameter_points, - std::vector rotation_matrices, - std::vector reduced_vectors, + VectorInterpolator(std::vector & parameter_points, + std::vector> & rotation_matrices, + std::vector> & reduced_vectors, int ref_point, std::string rbf = "G", std::string interp_method = "LS", double closest_rbf_val = 0.9); - ~VectorInterpolator(); - /** * @brief Obtain the interpolated reduced vector of the unsampled parameter point. * @@ -109,9 +107,7 @@ class VectorInterpolator : public Interpolator /** * @brief The reduced vectors with compatible coordinates. */ - std::vector d_rotated_reduced_vectors; - - std::vector d_rotated_reduced_vectors_owned; + std::vector> d_rotated_reduced_vectors; /** * @brief The reduced elements in tangential space. diff --git a/lib/hyperreduction/Hyperreduction.cpp b/lib/hyperreduction/Hyperreduction.cpp index b98934e63..8b7461c92 100644 --- a/lib/hyperreduction/Hyperreduction.cpp +++ b/lib/hyperreduction/Hyperreduction.cpp @@ -27,7 +27,7 @@ Hyperreduction::Hyperreduction(const char* sampling_type) samplingType = iter->second; } -void Hyperreduction::ComputeSamples(const Matrix* f_basis, +void Hyperreduction::ComputeSamples(const std::shared_ptr f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, @@ -42,7 +42,7 @@ void Hyperreduction::ComputeSamples(const Matrix* f_basis, { case deim: CAROM_VERIFY(num_samples_req == f_basis->numColumns()); - DEIM(f_basis, + DEIM(f_basis.get(), num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, @@ -50,7 +50,7 @@ void Hyperreduction::ComputeSamples(const Matrix* f_basis, myid, num_procs); return; case gnat: - GNAT(f_basis, + GNAT(f_basis.get(), num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, @@ -60,7 +60,7 @@ void Hyperreduction::ComputeSamples(const Matrix* f_basis, init_samples); return; case qdeim: - QDEIM(f_basis, + QDEIM(f_basis.get(), num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/Hyperreduction.h b/lib/hyperreduction/Hyperreduction.h index 2fb8a2947..315e59a5f 100644 --- a/lib/hyperreduction/Hyperreduction.h +++ b/lib/hyperreduction/Hyperreduction.h @@ -18,6 +18,7 @@ #include #include +#include namespace CAROM { @@ -54,7 +55,7 @@ class Hyperreduction samplingType = stype; } - void ComputeSamples(const Matrix* f_basis, + void ComputeSamples(const std::shared_ptr f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/QDEIM.cpp b/lib/hyperreduction/QDEIM.cpp index 486a95410..7e2527b87 100644 --- a/lib/hyperreduction/QDEIM.cpp +++ b/lib/hyperreduction/QDEIM.cpp @@ -246,7 +246,7 @@ QDEIM(const Matrix* f_basis, MPI_Bcast(V.getData(), n*n, MPI_DOUBLE, 0, MPI_COMM_WORLD); // Set Ubt = U * V = (V' * U')' - Matrix *Ubt = f_basis->mult(V); // distributed + std::unique_ptr Ubt = f_basis->mult(V); // distributed CAROM_VERIFY(Ubt->distributed() && Ubt->numRows() == f_basis->numRows() && Ubt->numColumns() == n); @@ -334,8 +334,6 @@ QDEIM(const Matrix* f_basis, MPI_Recv(sampled_row_data.data() + (s*numCol), numCol, MPI_DOUBLE, owner, tagSendRecv, MPI_COMM_WORLD, &status); } - - delete Ubt; } // loop s over samples // Subtract row_offset to convert f_sampled_row from global to local indices. diff --git a/lib/hyperreduction/S_OPT.cpp b/lib/hyperreduction/S_OPT.cpp index 6460bbeae..932ca5207 100644 --- a/lib/hyperreduction/S_OPT.cpp +++ b/lib/hyperreduction/S_OPT.cpp @@ -27,7 +27,7 @@ using namespace std; namespace CAROM { void -S_OPT(const Matrix* f_basis, +S_OPT(const std::shared_ptr f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, @@ -99,7 +99,7 @@ S_OPT(const Matrix* f_basis, // If num_basis_vectors is less than the number of columns of the basis, // we need to truncate the basis. - const Matrix* f_basis_truncated = NULL; + std::shared_ptr f_basis_truncated; if (num_basis_vectors < f_basis->numColumns()) { f_basis_truncated = f_basis->getFirstNColumns(num_basis_vectors); @@ -109,13 +109,11 @@ S_OPT(const Matrix* f_basis, f_basis_truncated = f_basis; } - const Matrix* Vo = NULL; - std::unique_ptr f_basis_truncated_Q; + std::shared_ptr Vo; // Use the QR factorization of the input matrix, if requested if (qr_factorize) { - f_basis_truncated_Q = f_basis_truncated->qr_factorize(); - Vo = f_basis_truncated_Q.get(); + Vo = f_basis_truncated->qr_factorize(); } else { @@ -238,7 +236,7 @@ S_OPT(const Matrix* f_basis, V1_last_col.item(j, 0) = V1.item(j, i - 1); } - Matrix* atA0 = V1_last_col.transposeMult(A0); + std::unique_ptr atA0 = V1_last_col.transposeMult(A0); tt.setSize(num_rows, i - 1); tt1.setSize(num_rows, i - 1); @@ -251,7 +249,7 @@ S_OPT(const Matrix* f_basis, } } - Matrix* lhs = A0.transposeMult(A0); + std::unique_ptr lhs = A0.transposeMult(A0); lhs->inverse(); Matrix* rhs = NULL; if (myid == 0) @@ -281,8 +279,7 @@ S_OPT(const Matrix* f_basis, } } - Matrix* ls_res = rhs->mult(lhs); - delete lhs; + std::unique_ptr ls_res = rhs->mult(*lhs); delete rhs; Matrix* c_T = NULL; @@ -296,7 +293,7 @@ S_OPT(const Matrix* f_basis, c_T = new Matrix(ls_res->getData(), ls_res->numRows(), ls_res->numColumns(), f_basis->distributed(), true); } - Matrix* Vo_first_i_columns = Vo->getFirstNColumns(i - 1); + std::unique_ptr Vo_first_i_columns = Vo->getFirstNColumns(i - 1); Vector* b = new Vector(num_rows, f_basis->distributed()); for (int j = 0; j < Vo_first_i_columns->numRows(); j++) @@ -309,8 +306,6 @@ S_OPT(const Matrix* f_basis, b->item(j) = tmp; } - delete Vo_first_i_columns; - for (int j = 0; j < num_rows; j++) { for (int zz = 0; zz < i - 1; zz++) @@ -328,8 +323,6 @@ S_OPT(const Matrix* f_basis, } } - delete atA0; - Vector* g3 = new Vector(num_rows, f_basis->distributed()); for (int j = 0; j < c_T->numRows(); j++) { @@ -372,8 +365,6 @@ S_OPT(const Matrix* f_basis, } } - delete ls_res; - for (int j = 0; j < A->dim(); j++) { double tmp = 0.0; @@ -413,15 +404,12 @@ S_OPT(const Matrix* f_basis, } else { - Matrix* curr_V1 = new Matrix(V1.getData(), num_samples_obtained, - num_basis_vectors, false, true); - Matrix* lhs = curr_V1->transposeMult(curr_V1); + Matrix curr_V1(V1.getData(), num_samples_obtained, + num_basis_vectors, false, true); + std::unique_ptr lhs = curr_V1.transposeMult(curr_V1); lhs->inverse(); - delete curr_V1; - - Matrix* ls_res = Vo->mult(lhs); - delete lhs; + std::unique_ptr ls_res = Vo->mult(*lhs); nV.setSize(num_basis_vectors); for (int j = 0; j < num_basis_vectors; j++) @@ -451,8 +439,6 @@ S_OPT(const Matrix* f_basis, } A->item(j) = std::log(1 + tmp) - noM->item(j); } - - delete ls_res; } f_bv_max_local.row_val = -DBL_MAX; @@ -520,11 +506,6 @@ S_OPT(const Matrix* f_basis, // Free the MPI_Datatype and MPI_Op. MPI_Type_free(&MaxRowType); MPI_Op_free(&RowInfoOp); - - if (num_basis_vectors < f_basis->numColumns()) - { - delete f_basis_truncated; - } } } diff --git a/lib/hyperreduction/S_OPT.h b/lib/hyperreduction/S_OPT.h index e82094d22..e2268e00a 100644 --- a/lib/hyperreduction/S_OPT.h +++ b/lib/hyperreduction/S_OPT.h @@ -46,7 +46,7 @@ class Matrix; * computation of a QR factorization will be performed. */ void -S_OPT(const Matrix* f_basis, +S_OPT(const std::shared_ptr f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/linalg/BasisGenerator.cpp b/lib/linalg/BasisGenerator.cpp index acb10c26e..100e5b834 100644 --- a/lib/linalg/BasisGenerator.cpp +++ b/lib/linalg/BasisGenerator.cpp @@ -224,29 +224,25 @@ BasisGenerator::computeNextSampleTime( const Matrix* basis = getSpatialBasis(); // Compute l = basis' * u - Vector* l = basis->transposeMult(u_vec); + Vector l(basis->numColumns(), false); + basis->transposeMult(u_vec, l); // basisl = basis * l - Vector* basisl = basis->mult(*l); + Vector basisl(basis->numRows(), true); + basis->mult(l, basisl); // Compute u - basisl. - std::unique_ptr eta = u_vec.minus(*basisl); - - delete l; - delete basisl; + std::unique_ptr eta = u_vec.minus(basisl); // Compute l = basis' * rhs Vector rhs_vec(rhs_in, dim, true); - l = basis->transposeMult(rhs_vec); + basis->transposeMult(rhs_vec, l); // basisl = basis * l - basisl = basis->mult(*l); + basis->mult(l, basisl); // Compute rhs - basisl. - std::unique_ptr eta_dot = rhs_vec.minus(*basisl); - - delete l; - delete basisl; + std::unique_ptr eta_dot = rhs_vec.minus(basisl); // Compute the l-inf norm of eta + d_dt*eta_dot. double global_norm; diff --git a/lib/linalg/BasisReader.h b/lib/linalg/BasisReader.h index fee556e8f..323d811b6 100644 --- a/lib/linalg/BasisReader.h +++ b/lib/linalg/BasisReader.h @@ -90,7 +90,7 @@ class BasisReader { * @pre start_col <= end_col <= numColumns() * * @param[in] start_col The starting column desired. - * @param[in] end_col The starting column desired. + * @param[in] end_col The final column desired. * * @return The spatial basis vectors for the requested time. */ @@ -148,7 +148,7 @@ class BasisReader { * @pre start_col <= end_col <= numColumns() * * @param[in] start_col The starting column desired. - * @param[in] end_col The starting column desired. + * @param[in] end_col The final column desired. * * @return The temporal basis vectors for the requested time. */ @@ -252,7 +252,7 @@ class BasisReader { * @pre start_col <= end_col <= numColumns() * * @param[in] start_col The starting column desired. - * @param[in] end_col The starting column desired. + * @param[in] end_col The final column desired. * * @return The snapshot matrix for the requested time. */ diff --git a/lib/linalg/Matrix.cpp b/lib/linalg/Matrix.cpp index 21dcd55e2..576569fa6 100644 --- a/lib/linalg/Matrix.cpp +++ b/lib/linalg/Matrix.cpp @@ -252,42 +252,14 @@ Matrix::operator = ( return *this; } -Matrix* +std::unique_ptr Matrix::getFirstNColumns(int n) const { CAROM_VERIFY(n > 0 && n <= d_num_cols); - Matrix* first_n_columns = NULL; - getFirstNColumns(n, first_n_columns); - return first_n_columns; -} - -void -Matrix::getFirstNColumns( - int n, - Matrix*& result) const -{ - CAROM_VERIFY(result == 0 || result->distributed() == distributed()); - CAROM_VERIFY(n > 0 && n <= d_num_cols); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) - { - result = new Matrix(d_num_rows, n, d_distributed); - } - else - { - result->setSize(d_num_rows, n); - } - - for (int i = 0; i < d_num_rows; i++) - { - for (int j = 0; j < n; j++) - { - result->item(i, j) = item(i, j); - } - } + Matrix* first_n_columns = new Matrix(d_num_rows, n, d_distributed); + getFirstNColumns(n, *first_n_columns); + return std::unique_ptr(first_n_columns); } void @@ -310,36 +282,6 @@ Matrix::getFirstNColumns( } } -void -Matrix::mult( - const Matrix& other, - Matrix*& result) const -{ - CAROM_VERIFY(result == 0 || result->distributed() == distributed()); - CAROM_VERIFY(!other.distributed()); - CAROM_VERIFY(numColumns() == other.numRows()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Matrix(d_num_rows, other.d_num_cols, d_distributed); - } - else { - result->setSize(d_num_rows, other.d_num_cols); - } - - // Do the multiplication. - for (int this_row = 0; this_row < d_num_rows; ++this_row) { - for (int other_col = 0; other_col < other.d_num_cols; ++other_col) { - double result_val = 0.0; - for (int entry = 0; entry < d_num_cols; ++entry) { - result_val += item(this_row, entry)*other.item(entry, other_col); - } - result->item(this_row, other_col) = result_val; - } - } -} - void Matrix::mult( const Matrix& other, @@ -364,34 +306,6 @@ Matrix::mult( } } -void -Matrix::mult( - const Vector& other, - Vector*& result) const -{ - CAROM_VERIFY(result == 0 || result->distributed() == distributed()); - CAROM_VERIFY(!other.distributed()); - CAROM_VERIFY(numColumns() == other.dim()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_num_rows, d_distributed); - } - else { - result->setSize(d_num_rows); - } - - // Do the multiplication. - for (int this_row = 0; this_row < d_num_rows; ++this_row) { - double result_val = 0.0; - for (int entry = 0; entry < d_num_cols; ++entry) { - result_val += item(this_row, entry)*other.item(entry); - } - result->item(this_row) = result_val; - } -} - void Matrix::mult( const Vector& other, @@ -447,34 +361,6 @@ Matrix::pointwise_mult( } } -void -Matrix::elementwise_mult( - const Matrix& other, - Matrix*& result) const -{ - CAROM_VERIFY(result == 0 || result->distributed() == distributed()); - CAROM_VERIFY(distributed() == other.distributed()); - CAROM_VERIFY(numRows() == other.numRows()); - CAROM_VERIFY(numColumns() == other.numColumns()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Matrix(d_num_rows, d_num_cols, d_distributed); - } - else { - result->setSize(d_num_rows, d_num_cols); - } - - // Do the element-wise multiplication. - for (int this_row = 0; this_row < d_num_rows; ++this_row) { - for (int other_col = 0; other_col < d_num_cols; ++other_col) { - result->item(this_row, other_col) = item(this_row, - other_col) * other.item(this_row, other_col); - } - } -} - void Matrix::elementwise_mult( const Matrix& other, @@ -497,28 +383,6 @@ Matrix::elementwise_mult( } } -void -Matrix::elementwise_square( - Matrix*& result) const -{ - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Matrix(d_num_rows, d_num_cols, d_distributed); - } - else { - result->setSize(d_num_rows, d_num_cols); - } - - // Do the pointwise square. - for (int this_row = 0; this_row < d_num_rows; ++this_row) { - for (int this_col = 0; this_col < d_num_cols; ++this_col) { - result->item(this_row, this_col) = item(this_row, this_col) * item(this_row, - this_col); - } - } -} - void Matrix::elementwise_square( Matrix& result) const @@ -529,8 +393,8 @@ Matrix::elementwise_square( // Do the pointwise square. for (int this_row = 0; this_row < d_num_rows; ++this_row) { for (int this_col = 0; this_col < d_num_cols; ++this_col) { - result.item(this_row, this_col) = item(this_row, this_col) * item(this_row, - this_col); + const double a = item(this_row, this_col); + result.item(this_row, this_col) = a * a; } } } @@ -555,45 +419,6 @@ Matrix::multPlus( } } -void -Matrix::transposeMult( - const Matrix& other, - Matrix*& result) const -{ - CAROM_VERIFY(result == 0 || !result->distributed()); - CAROM_VERIFY(distributed() == other.distributed()); - CAROM_VERIFY(numRows() == other.numRows()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Matrix(d_num_cols, other.d_num_cols, false); - } - else { - result->setSize(d_num_cols, other.d_num_cols); - } - - // Do the multiplication. - for (int this_col = 0; this_col < d_num_cols; ++this_col) { - for (int other_col = 0; other_col < other.d_num_cols; ++other_col) { - double result_val = 0.0; - for (int entry = 0; entry < d_num_rows; ++entry) { - result_val += item(entry, this_col)*other.item(entry, other_col); - } - result->item(this_col, other_col) = result_val; - } - } - if (d_distributed && d_num_procs > 1) { - int new_mat_size = d_num_cols*other.d_num_cols; - MPI_Allreduce(MPI_IN_PLACE, - &result->item(0, 0), - new_mat_size, - MPI_DOUBLE, - MPI_SUM, - MPI_COMM_WORLD); - } -} - void Matrix::transposeMult( const Matrix& other, @@ -627,42 +452,6 @@ Matrix::transposeMult( } } -void -Matrix::transposeMult( - const Vector& other, - Vector*& result) const -{ - CAROM_VERIFY(result == 0 || !result->distributed()); - CAROM_VERIFY(distributed() == other.distributed()); - CAROM_VERIFY(numRows() == other.dim()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Vector(d_num_cols, false); - } - else { - result->setSize(d_num_cols); - } - - // Do the multiplication. - for (int this_col = 0; this_col < d_num_cols; ++this_col) { - double result_val = 0.0; - for (int entry = 0; entry < d_num_rows; ++entry) { - result_val += item(entry, this_col)*other.item(entry); - } - result->item(this_col) = result_val; - } - if (d_distributed && d_num_procs > 1) { - MPI_Allreduce(MPI_IN_PLACE, - &result->item(0), - d_num_cols, - MPI_DOUBLE, - MPI_SUM, - MPI_COMM_WORLD); - } -} - void Matrix::transposeMult( const Vector& other, @@ -694,21 +483,6 @@ Matrix::transposeMult( } } -void -Matrix::getColumn(int column, - Vector*& result) const -{ - if (result == 0) { - if (d_distributed) { - result = new Vector(d_num_rows, true); - } - else { - result = new Vector(d_num_rows, false); - } - } - getColumn(column, *result); -} - void Matrix::getColumn(int column, Vector& result) const @@ -719,61 +493,6 @@ Matrix::getColumn(int column, } } -void -Matrix::inverse( - Matrix*& result) const -{ - CAROM_VERIFY(result == 0 || - (!result->distributed() && - result->numRows() == numRows() && - result->numColumns() == numColumns())); - CAROM_VERIFY(!distributed()); - CAROM_VERIFY(numRows() == numColumns()); - - // If the result has not been allocated then do so. Otherwise size it - // correctly. - if (result == 0) { - result = new Matrix(d_num_rows, d_num_cols, false); - } - else { - result->setSize(d_num_rows, d_num_cols); - } - - // Call lapack routines to do the inversion. - // Set up some stuff the lapack routines need. - int info; - int mtx_size = d_num_rows; - int lwork = mtx_size*mtx_size; - int* ipiv = new int [mtx_size]; - double* work = new double [lwork]; - // To use lapack we need a column major representation of this which is - // essentially the transform of this. Use result for this representation. - for (int row = 0; row < mtx_size; ++row) { - for (int col = 0; col < mtx_size; ++col) { - result->item(col, row) = item(row, col); - } - } - // Now call lapack to do the inversion. - dgetrf(&mtx_size, &mtx_size, result->d_mat, &mtx_size, ipiv, &info); - CAROM_VERIFY(info == 0); - - dgetri(&mtx_size, result->d_mat, &mtx_size, ipiv, work, &lwork, &info); - CAROM_VERIFY(info == 0); - - // Result now has the inverse in a column major representation. Put it - // into row major order. - for (int row = 0; row < mtx_size; ++row) { - for (int col = row+1; col < mtx_size; ++col) { - double tmp = result->item(row, col); - result->item(row, col) = result->item(col, row); - result->item(col, row) = tmp; - } - } - - delete [] ipiv; - delete [] work; -} - void Matrix::inverse( Matrix& result) const @@ -890,7 +609,7 @@ void Matrix::transposePseudoinverse() } else { - Matrix *AtA = this->transposeMult(this); + std::unique_ptr AtA = this->transposeMult(*this); // Directly invert AtA, which is a bad idea if AtA is not small. AtA->inverse(); @@ -909,8 +628,6 @@ void Matrix::transposePseudoinverse() for (int j=0; jitem(i,j) = res.item(j); } - - delete AtA; } } @@ -2459,11 +2176,12 @@ struct SerialSVDDecomposition SerialSVD(Matrix* A) // Compute the product A^T * B, where A is represented by the space-time // product of As and At, and likewise for B. -Matrix* SpaceTimeProduct(const CAROM::Matrix* As, const CAROM::Matrix* At, - const CAROM::Matrix* Bs, const CAROM::Matrix* Bt, - const std::vector *tscale, - const bool At0at0, const bool Bt0at0, const bool lagB, - const bool skip0) +std::unique_ptr SpaceTimeProduct(const CAROM::Matrix* As, + const CAROM::Matrix* At, + const CAROM::Matrix* Bs, const CAROM::Matrix* Bt, + const std::vector *tscale, + const bool At0at0, const bool Bt0at0, const bool lagB, + const bool skip0) { // TODO: implement reduction in parallel for the spatial matrices CAROM_VERIFY(As->distributed() && Bs->distributed()); @@ -2517,7 +2235,7 @@ Matrix* SpaceTimeProduct(const CAROM::Matrix* As, const CAROM::Matrix* At, } } - return p; + return std::unique_ptr(p); } } // end namespace CAROM diff --git a/lib/linalg/Matrix.h b/lib/linalg/Matrix.h index 7bcb092b8..7cc448765 100644 --- a/lib/linalg/Matrix.h +++ b/lib/linalg/Matrix.h @@ -232,24 +232,9 @@ class Matrix * * @return The truncated Matrix. */ - Matrix* + std::unique_ptr getFirstNColumns(int n) const; - /** - * @brief Get the first N columns of a matrix. - * - * @pre result.distributed() == distributed() - * @pre 0 < n < numColumns() - * - * @param[in] n The number of columns to return. - * - * @param[out] result The truncated Matrix. - */ - void - getFirstNColumns( - int n, - Matrix*& result) const; - /** * @brief Get the first N columns of a matrix. * @@ -266,8 +251,7 @@ class Matrix Matrix& result) const; /** - * @brief Multiplies this Matrix with other and returns the product, - * reference version. + * @brief Multiplies this Matrix with other and returns the product. * * Supports multiplication of two undistributed matrices returning an * undistributed Matrix, and multiplication of a distributed Matrix with @@ -280,68 +264,22 @@ class Matrix * * @return The product Matrix. */ - Matrix* + std::unique_ptr mult( const Matrix& other) const { - Matrix* result = 0; - mult(other, result); - return result; - } - - /** - * @brief Multiplies this Matrix with other and returns the product, - * pointer version. - * - * Supports multiplication of two undistributed matrices returning an - * undistributed Matrix, and multiplication of a distributed Matrix with - * an undistributed Matrix returning a distributed Matrix. - * - * @pre other != 0 - * @pre !other->distributed() - * @pre numColumns() == other->numRows() - * - * @param[in] other The Matrix to multiply with this. - * - * @return The product Matrix. - */ - Matrix* - mult( - const Matrix* other) const - { - CAROM_VERIFY(other != 0); - return mult(*other); + Matrix* result = new Matrix(d_num_rows, other.d_num_cols, d_distributed); + mult(other, *result); + return std::unique_ptr(result); } /** * @brief Multiplies this Matrix with other and fills result with the - * answer. + * product. * * Supports multiplication of two undistributed matrices resulting in an * undistributed Matrix, and multiplication of a distributed Matrix with - * an undistributed Matrix resulting in a distributed Matrix. If result - * has not been allocated it will be, otherwise it will be sized - * accordingly. - * - * @pre result == 0 || result->distributed() == distributed() - * @pre !other.distributed() - * @pre numColumns() == other.numRows() - * - * @param[in] other The Matrix to multiply with this. - * @param[out] result The product Matrix. - */ - void - mult( - const Matrix& other, - Matrix*& result) const; - - /** - * @brief Multiplies this Matrix with other and fills result with the - * answer. - * - * Supports multiplication of two undistributed matrices resulting in an - * undistributed Matrix, and multiplication of a distributed Matrix with - * an undistributed Matrix resulting in a distributed Matrix. Result + * an undistributed Matrix resulting in a distributed Matrix. Result * will be sized accordingly. * * @pre result.distributed() == distributed() @@ -357,8 +295,7 @@ class Matrix Matrix& result) const; /** - * @brief Multiplies this Matrix with other and returns the product, - * reference version. + * @brief Multiplies this Matrix with other and returns the product. * * Supports multiplication of an undistributed Matrix and Vector * returning an undistributed Vector, and multiplication of a distributed @@ -371,40 +308,18 @@ class Matrix * * @return The product Vector. */ - Vector* + std::unique_ptr mult( const Vector& other) const { - Vector* result = 0; - mult(other, result); - return result; + Vector* result = new Vector(d_num_rows, d_distributed); + mult(other, *result); + return std::unique_ptr(result); } /** * @brief Multiplies this Matrix with other and fills result with the - * answer. - * - * Supports multiplication of an undistributed Matrix and Vector - * resulting in an undistributed Vector, and multiplication of a - * distributed Matrix and an undistributed Vector resulting in a - * distributed Vector. If result has not been allocated it will be, - * otherwise it will be sized accordingly. - * - * @pre result == 0 || result->distributed() == distributed() - * @pre !other.distributed() - * @pre numColumns() == other.dim() - * - * @param[in] other The Vector to multiply with this. - * @param[out] result The product Vector. - */ - void - mult( - const Vector& other, - Vector*& result) const; - - /** - * @brief Multiplies this Matrix with other and fills result with the - * answer. + * product. * * Supports multiplication of an undistributed Matrix and Vector * resulting in an undistributed Vector, and multiplication of a @@ -480,56 +395,18 @@ class Matrix * * @return The product Matrix. */ - Matrix* + std::unique_ptr elementwise_mult( const Matrix& other) const { - Matrix* result = 0; - elementwise_mult(other, result); - return result; - } - - /** - * @brief Multiplies two matrices element-wise and returns the product, - * pointer version. - * - * @pre other != 0 - * @pre distributed() == other.distributed() - * @pre numRows() == other.numRows() - * @pre numColumns() == other.numColumns() - * - * @param[in] other The Matrix to multiply with this. - * - * @return The product Matrix. - */ - Matrix* - elementwise_mult( - const Matrix* other) const - { - CAROM_VERIFY(other != 0); - return elementwise_mult(*other); + Matrix *result = new Matrix(d_num_rows, d_num_cols, d_distributed); + elementwise_mult(other, *result); + return std::unique_ptr(result); } /** * @brief Multiplies two matrices element-wise and fills result with the - * answer. - * - * @pre result == 0 || result->distributed() == distributed() - * @pre distributed() == other.distributed() - * @pre numRows() == other.numRows() - * @pre numColumns() == other.numColumns() - * - * @param[in] other The Matrix to multiply with this. - * @param[out] result The product Matrix. - */ - void - elementwise_mult( - const Matrix& other, - Matrix*& result) const; - - /** - * @brief Multiplies two matrices element-wise and fills result with the - * answer. + * product. * * @pre result == 0 || result->distributed() == distributed() * @pre distributed() == other.distributed() @@ -549,24 +426,14 @@ class Matrix * * @return The product Matrix. */ - Matrix* + std::unique_ptr elementwise_square() const { - Matrix* result = 0; - elementwise_square(result); - return result; + Matrix *result = new Matrix(d_num_rows, d_num_cols, d_distributed); + elementwise_square(*result); + return std::unique_ptr(result); } - /** - * @brief Square every element in the matrix. - * - * @pre result == 0 || result->distributed() == distributed() - * @param[out] result The product Matrix. - */ - void - elementwise_square( - Matrix*& result) const; - /** * @brief Square every element in the matrix. * @@ -602,7 +469,7 @@ class Matrix /** * @brief Multiplies the transpose of this Matrix with other and returns - * the product, reference version. + * the product. * * Supports multiplication of two undistributed matrices returning an * undistributed Matrix or two distributed matrices returning an @@ -615,63 +482,18 @@ class Matrix * * @return The product Matrix. */ - Matrix* + std::unique_ptr transposeMult( const Matrix& other) const { - Matrix* result = 0; - transposeMult(other, result); - return result; + Matrix* result = new Matrix(d_num_cols, other.d_num_cols, false); + transposeMult(other, *result); + return std::unique_ptr(result); } - /** - * @brief Multiplies the transpose of this Matrix with other and returns - * the product, pointer version. - * - * Supports multiplication of two undistributed matrices returning an - * undistributed Matrix or two distributed matrices returning an - * undistributed Matrix. - * - * @pre other != 0 - * @pre distributed() == other->distributed() - * @pre numRows() == other->numRows() - * - * @param[in] other The Matrix to multiply with this. - * - * @return The product Matrix. - */ - Matrix* - transposeMult( - const Matrix* other) const - { - CAROM_VERIFY(other != 0); - return transposeMult(*other); - } - - /** - * @brief Multiplies the transpose of this Matrix with other and fills - * result with the answer. - * - * Supports multiplication of two undistributed matrices or two - * distributed matrices resulting in an undistributed Matrix. If result - * has not been allocated it will be, otherwise it will be sized - * accordingly. - * - * @pre result == 0 || !result->distributed() - * @pre distributed() == other.distributed() - * @pre numRows() == other.numRows() - * - * @param[in] other The Matrix to multiply with this. - * @param[out] result The product Matrix. - */ - void - transposeMult( - const Matrix& other, - Matrix*& result) const; - /** * @brief Multiplies the transpose of this Matrix with other and fills - * result with the answer. + * result with the product. * * Supports multiplication of two undistributed matrices or two * distributed matrices resulting in an undistributed Matrix. Result @@ -691,7 +513,7 @@ class Matrix /** * @brief Multiplies the transpose of this Matrix with other and returns - * the product, reference version. + * the product. * * Supports multiplication of an undistributed Matrix and an * undistributed Vector or a distributed Matrix and a distributed Vector @@ -704,67 +526,22 @@ class Matrix * * @return The product Vector. */ - Vector* + std::unique_ptr transposeMult( const Vector& other) const { - Vector* result = 0; - transposeMult(other, result); - return result; - } - - /** - * @brief Multiplies the transpose of this Matrix with other and returns - * the product, pointer version. - * - * Supports multiplication of an undistributed Matrix and an - * undistributed Vector or a distributed Matrix and a distributed Vector - * returning an undistributed Vector. - * - * @pre other != 0 - * @pre distributed() == other->distributed() - * @pre numRows() == other->dim(); - * - * @param[in] other The Vector to multiply with this. - * - * @return The product Vector. - */ - Vector* - transposeMult( - const Vector* other) const - { - CAROM_VERIFY(other != 0); - return transposeMult(*other); + Vector* result = new Vector(d_num_cols, false); + transposeMult(other, *result); + return std::unique_ptr(result); } /** * @brief Multiplies the transpose of this Matrix with other and fills - * result with the answer. + * result with the product. * * Supports multiplication of an undistributed Matrix and an * undistributed Vector or a distributed Matrix and a distributed Vector - * resulting in an undistributed Vector. If result has not been allocated - * it will be, otherwise it will be sized accordingly. - * - * @pre result == 0 || !result->distributed() - * @pre distributed() == other.distributed() - * @pre numRows() == other.dim(); - * - * @param[in] other The Vector to multiply with this. - * @param[out] result The product Vector. - */ - void - transposeMult( - const Vector& other, - Vector*& result) const; - - /** - * @brief Multiplies the transpose of this Matrix with other and fills - * result with the answer. - * - * Supports multiplication of an undistributed Matrix and an - * undistributed Vector or a distributed Matrix and a distributed Vector - * resulting in an undistributed Vector. Result will be sized + * resulting in an undistributed Vector. Result will be sized * accordingly. * * @pre !result.distributed() @@ -787,44 +564,26 @@ class Matrix * * @return The inverse of this. */ - Matrix* + std::unique_ptr inverse() const { - Matrix* result = 0; - inverse(result); - return result; + Matrix* result = new Matrix(d_num_rows, d_num_cols, false); + inverse(*result); + return std::unique_ptr(result); } /** - * @brief Computes and returns the inverse of this. - * - * If result has not been allocated it will be, otherwise it will be - * sized accordingly. - * - * @pre result == 0 || (!result->distributed() && - * result->numRows() == numRows() && - * result->numColumns() == numColumns()) - * @pre !distributed() - * @pre numRows() == numColumns() - * - * @param[out] result The inverse of this. - */ - void - inverse( - Matrix*& result) const; - - /** - * @brief Computes and returns the inverse of this. - * - * Result will be sized accordingly. - * - * @pre !result.distributed() && result.numRows() == numRows() && - * result.numColumns() == numColumns() - * @pre !distributed() - * @pre numRows() == numColumns() - * - * @param[out] result The inverse of this. - */ + * @brief Computes and returns the inverse of this. + * + * Result will be sized accordingly. + * + * @pre !result.distributed() && result.numRows() == numRows() && + * result.numColumns() == numColumns() + * @pre !distributed() + * @pre numRows() == numColumns() + * + * @param[out] result The inverse of this. + */ void inverse( Matrix& result) const; @@ -839,27 +598,18 @@ class Matrix inverse(); /** - * @brief Returns a column of the matrix (not owned by Matrix). + * @brief Returns a deep copy of a column of the matrix. * * @return A column of the matrix (not owned by Matrix). */ - Vector* + std::unique_ptr getColumn(int column) const { - Vector* result = 0; - getColumn(column, result); - return result; + Vector* result = new Vector(d_num_rows, true); + getColumn(column, *result); + return std::unique_ptr(result); } - /** - * @brief Returns a column of the matrix (not owned by Matrix). - * - * @return A column of the matrix (not owned by Matrix). - */ - void - getColumn(int column, - Vector*& result) const; - /** * @brief Returns a column of the matrix (not owned by Matrix). * @@ -1452,11 +1202,12 @@ struct EigenPair SymmetricRightEigenSolve(Matrix* A); */ struct ComplexEigenPair NonSymmetricRightEigenSolve(Matrix* A); -Matrix* SpaceTimeProduct(const CAROM::Matrix* As, const CAROM::Matrix* At, - const CAROM::Matrix* Bs, const CAROM::Matrix* Bt, - const std::vector *tscale=NULL, - const bool At0at0=false, const bool Bt0at0=false, - const bool lagB=false, const bool skip0=false); +std::unique_ptr SpaceTimeProduct(const CAROM::Matrix* As, + const CAROM::Matrix* At, const CAROM::Matrix* Bs, + const CAROM::Matrix* Bt, + const std::vector *tscale=NULL, + const bool At0at0=false, const bool Bt0at0=false, + const bool lagB=false, const bool skip0=false); } #endif diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index cfd505440..cbb19c54a 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -98,7 +98,7 @@ IncrementalSVD::IncrementalSVD( d_state_database->getInteger("U_num_rows", num_rows); int num_cols; d_state_database->getInteger("U_num_cols", num_cols); - d_U = new Matrix(num_rows, num_cols, true); + d_U.reset(new Matrix(num_rows, num_cols, true)); d_state_database->getDoubleArray("U", &d_U->item(0, 0), num_rows*num_cols); @@ -252,14 +252,14 @@ const Matrix* IncrementalSVD::getSpatialBasis() { CAROM_ASSERT(d_basis != 0); - return d_basis; + return d_basis.get(); } const Matrix* IncrementalSVD::getTemporalBasis() { CAROM_ASSERT(d_basis != 0); - return d_basis_right; + return d_basis_right.get(); } const Vector* @@ -285,15 +285,17 @@ IncrementalSVD::buildIncrementalSVD( // l = basis' * u Vector u_vec(u, d_dim, true); - Vector* l = d_basis->transposeMult(u_vec); + Vector l(d_basis->numColumns(), false); + d_basis->transposeMult(u_vec, l); // basisl = basis * l - Vector* basisl = d_basis->mult(*l); + Vector basisl(d_basis->numRows(), true); + d_basis->mult(l, basisl); // Computing as k = sqrt(u.u - 2.0*l.l + basisl.basisl) // results in catastrophic cancellation, and must be avoided. // Instead we compute as k = sqrt((u-basisl).(u-basisl)). - std::unique_ptr e_proj = u_vec.minus(*basisl); + std::unique_ptr e_proj = u_vec.minus(basisl); double k = e_proj->inner_product(*e_proj); if (k <= 0) { @@ -333,8 +335,7 @@ IncrementalSVD::buildIncrementalSVD( // Create Q. double* Q; - constructQ(Q, l, k); - delete l; + constructQ(Q, &l, k); // Now get the singular value decomposition of Q. Matrix* A; @@ -362,7 +363,7 @@ IncrementalSVD::buildIncrementalSVD( // This sample is not linearly dependent. // Compute j - std::unique_ptr j = u_vec.minus(*basisl); + std::unique_ptr j = u_vec.minus(basisl); for (int i = 0; i < d_dim; ++i) { j->item(i) /= k; } @@ -371,7 +372,6 @@ IncrementalSVD::buildIncrementalSVD( // deleted upon return. addNewSample(j.get(), A, W, sigma); } - delete basisl; delete A; delete W; @@ -379,7 +379,6 @@ IncrementalSVD::buildIncrementalSVD( computeBasis(); } else { - delete basisl; delete A; delete W; delete sigma; diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index bab939f20..b58a03740 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -27,7 +27,6 @@ IncrementalSVDBrand::IncrementalSVDBrand( IncrementalSVD( options, basis_file_name), - d_Up(0), d_singular_value_tol(options.singular_value_tol) { CAROM_VERIFY(options.singular_value_tol >= 0); @@ -43,7 +42,7 @@ IncrementalSVDBrand::IncrementalSVDBrand( d_state_database->getInteger("Up_num_rows", num_rows); int num_cols; d_state_database->getInteger("Up_num_cols", num_cols); - d_Up = new Matrix(num_rows, num_cols, true); + d_Up.reset(new Matrix(num_rows, num_cols, true)); d_state_database->getDoubleArray("Up", &d_Up->item(0, 0), num_rows*num_cols); @@ -79,11 +78,6 @@ IncrementalSVDBrand::~IncrementalSVDBrand() &d_Up->item(0, 0), num_rows*num_cols); } - - // Delete data members. - if (d_Up) { - delete d_Up; - } } const Matrix* @@ -92,7 +86,7 @@ IncrementalSVDBrand::getSpatialBasis() updateSpatialBasis(); // WARNING: this is costly CAROM_ASSERT(d_basis != 0); - return d_basis; + return d_basis.get(); } const Matrix* @@ -101,7 +95,7 @@ IncrementalSVDBrand::getTemporalBasis() updateTemporalBasis(); CAROM_ASSERT(d_basis_right != 0); - return d_basis_right; + return d_basis_right.get(); } void @@ -117,11 +111,11 @@ IncrementalSVDBrand::buildInitialSVD( d_S->item(0) = norm_u; // Build d_Up for this new time interval. - d_Up = new Matrix(1, 1, false); + d_Up.reset(new Matrix(1, 1, false)); d_Up->item(0, 0) = 1.0; // Build d_U for this new time interval. - d_U = new Matrix(d_dim, 1, true); + d_U.reset(new Matrix(d_dim, 1, true)); for (int i = 0; i < d_dim; ++i) { d_U->item(i, 0) = u[i]/norm_u; } @@ -149,16 +143,14 @@ IncrementalSVDBrand::buildIncrementalSVD( Vector u_vec(u, d_dim, true); Vector e_proj(u, d_dim, true); - Vector *tmp = d_U->transposeMult(e_proj); - Vector *tmp2 = d_U->mult(*tmp); - e_proj -= *tmp2; // Gram-Schmidt - delete tmp2; - delete tmp; - tmp = d_U->transposeMult(e_proj); - tmp2 = d_U->mult(*tmp); - e_proj -= *tmp2; // Re-orthogonalization - delete tmp2; - delete tmp; + Vector tmp(d_U->numColumns(), false); + Vector tmp2(d_U->numRows(), true); + d_U->transposeMult(e_proj, tmp); + d_U->mult(tmp, tmp2); + e_proj -= tmp2; // Gram-Schmidt + d_U->transposeMult(e_proj, tmp); + d_U->mult(tmp, tmp2); + e_proj -= tmp2; // Re-orthogonalization double k = e_proj.inner_product(e_proj); if (k <= 0) { @@ -198,12 +190,10 @@ IncrementalSVDBrand::buildIncrementalSVD( // Create Q. double* Q; - Vector* U_mult_u = new Vector(d_U->transposeMult(u_vec)->getData(), - d_num_samples, - false); - Vector* l = d_Up->transposeMult(U_mult_u); - constructQ(Q, l, k); - delete U_mult_u, l; + Vector U_mult_u(d_U->transposeMult(u_vec)->getData(), d_num_samples, false); + Vector l(d_Up->numColumns(), false); + d_Up->transposeMult(U_mult_u, l); + constructQ(Q, &l, k); // Now get the singular value decomposition of Q. Matrix* A; @@ -255,7 +245,7 @@ IncrementalSVDBrand::buildIncrementalSVD( void IncrementalSVDBrand::updateSpatialBasis() { - d_basis = d_U->mult(d_Up); + d_basis = d_U->mult(*d_Up); // remove the smallest singular value if it is smaller than d_singular_value_tol if ( (d_singular_value_tol != 0.0) && @@ -274,24 +264,21 @@ IncrementalSVDBrand::updateSpatialBasis() d_basis_new->item(row, col) = d_basis->item(row,col); } } - delete d_basis; - d_basis = d_basis_new; + d_basis.reset(d_basis_new); } // Reorthogonalize if necessary. // (not likely to be called anymore but left for safety) - if (fabs(checkOrthogonality(d_basis)) > + if (fabs(checkOrthogonality(d_basis.get())) > std::numeric_limits::epsilon()*static_cast(d_num_samples)) { d_basis->orthogonalize(); } - } void IncrementalSVDBrand::updateTemporalBasis() { - delete d_basis_right; - d_basis_right = new Matrix(*d_W); + d_basis_right.reset(new Matrix(*d_W)); // remove the smallest singular value if it is smaller than d_singular_value_tol if ( (d_singular_value_tol != 0.0) && @@ -310,17 +297,15 @@ IncrementalSVDBrand::updateTemporalBasis() d_basis_right_new->item(row, col) = d_basis_right->item(row,col); } } - delete d_basis_right; - d_basis_right = d_basis_right_new; + d_basis_right.reset(d_basis_right_new); } // Reorthogonalize if necessary. // (not likely to be called anymore but left for safety) - if (fabs(checkOrthogonality(d_basis_right)) > + if (fabs(checkOrthogonality(d_basis_right.get())) > std::numeric_limits::epsilon()*d_num_samples) { d_basis_right->orthogonalize(); } - } void @@ -374,9 +359,9 @@ IncrementalSVDBrand::addLinearlyDependentSample( } // Multiply d_Up and Amod and put result into d_Up. - Matrix* Up_times_Amod = d_Up->mult(Amod); - delete d_Up; - d_Up = Up_times_Amod; + Matrix *Up_times_Amod = new Matrix(d_Up->numRows(), Amod.numColumns(), false); + d_Up->mult(Amod, *Up_times_Amod); + d_Up.reset(Up_times_Amod); Matrix* new_d_W; if (d_update_right_SV) { @@ -424,8 +409,7 @@ IncrementalSVDBrand::addNewSample( } newU->item(row, d_num_samples) = j->item(row); } - delete d_U; - d_U = newU; + d_U.reset(newU); Matrix* new_d_W; if (d_update_right_SV) { @@ -469,8 +453,7 @@ IncrementalSVDBrand::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { new_d_Up->item(d_num_samples, col) = A->item(d_num_samples, col); } - delete d_Up; - d_Up = new_d_Up; + d_Up.reset(new_d_Up); // d_S = sigma. delete d_S; @@ -492,11 +475,11 @@ IncrementalSVDBrand::addNewSample( else { max_U_dim = d_total_dim; } - if (fabs(checkOrthogonality(d_Up)) > + if (fabs(checkOrthogonality(d_Up.get())) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_Up->orthogonalize(); } - if (fabs(checkOrthogonality(d_U)) > + if (fabs(checkOrthogonality(d_U.get())) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_U->orthogonalize(); // Will not be called, but just in case } diff --git a/lib/linalg/svd/IncrementalSVDBrand.h b/lib/linalg/svd/IncrementalSVDBrand.h index 6b7e54482..db1b18ec7 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.h +++ b/lib/linalg/svd/IncrementalSVDBrand.h @@ -173,7 +173,7 @@ class IncrementalSVDBrand : public IncrementalSVD * @brief The matrix U'. U' is not distributed and the entire matrix * exists on each processor. */ - Matrix* d_Up; + std::unique_ptr d_Up; /** * @brief The tolerance value used to remove small singular values. diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp index 6fa22442d..67a9ec1b2 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp @@ -27,7 +27,6 @@ IncrementalSVDFastUpdate::IncrementalSVDFastUpdate( IncrementalSVD( options, basis_file_name), - d_Up(0), d_singular_value_tol(options.singular_value_tol) { CAROM_VERIFY(options.singular_value_tol >= 0); @@ -43,7 +42,7 @@ IncrementalSVDFastUpdate::IncrementalSVDFastUpdate( d_state_database->getInteger("Up_num_rows", num_rows); int num_cols; d_state_database->getInteger("Up_num_cols", num_cols); - d_Up = new Matrix(num_rows, num_cols, true); + d_Up.reset(new Matrix(num_rows, num_cols, true)); d_state_database->getDoubleArray("Up", &d_Up->item(0, 0), num_rows*num_cols); @@ -79,11 +78,6 @@ IncrementalSVDFastUpdate::~IncrementalSVDFastUpdate() &d_Up->item(0, 0), num_rows*num_cols); } - - // Delete data members. - if (d_Up) { - delete d_Up; - } } void @@ -99,11 +93,11 @@ IncrementalSVDFastUpdate::buildInitialSVD( d_S->item(0) = norm_u; // Build d_Up for this new time interval. - d_Up = new Matrix(1, 1, false); + d_Up.reset(new Matrix(1, 1, false)); d_Up->item(0, 0) = 1.0; // Build d_U for this new time interval. - d_U = new Matrix(d_dim, 1, true); + d_U.reset(new Matrix(d_dim, 1, true)); for (int i = 0; i < d_dim; ++i) { d_U->item(i, 0) = u[i]/norm_u; } @@ -126,11 +120,10 @@ IncrementalSVDFastUpdate::buildInitialSVD( void IncrementalSVDFastUpdate::computeBasis() { - d_basis = d_U->mult(d_Up); + d_basis = d_U->mult(*d_Up); if(d_update_right_SV) { - delete d_basis_right; - d_basis_right = new Matrix(*d_W); + d_basis_right.reset(new Matrix(*d_W)); } if(d_rank == 0) { @@ -156,8 +149,7 @@ IncrementalSVDFastUpdate::computeBasis() d_basis_new->item(row, col) = d_basis->item(row,col); } } - delete d_basis; - d_basis = d_basis_new; + d_basis.reset(d_basis_new); if (d_update_right_SV) { @@ -168,20 +160,19 @@ IncrementalSVDFastUpdate::computeBasis() d_basis_right_new->item(row, col) = d_basis_right->item(row,col); } } - delete d_basis_right; - d_basis_right = d_basis_right_new; + d_basis_right.reset(d_basis_right_new); } --d_num_samples; } // Reorthogonalize if necessary. - if (fabs(checkOrthogonality(d_basis)) > + if (fabs(checkOrthogonality(d_basis.get())) > std::numeric_limits::epsilon()*static_cast(d_num_samples)) { d_basis->orthogonalize(); } if(d_update_right_SV) { - if (fabs(checkOrthogonality(d_basis_right)) > + if (fabs(checkOrthogonality(d_basis_right.get())) > std::numeric_limits::epsilon()*d_num_samples) { d_basis_right->orthogonalize(); } @@ -212,9 +203,9 @@ IncrementalSVDFastUpdate::addLinearlyDependentSample( } // Multiply d_Up and Amod and put result into d_Up. - Matrix* Up_times_Amod = d_Up->mult(Amod); - delete d_Up; - d_Up = Up_times_Amod; + Matrix *Up_times_Amod = new Matrix(d_Up->numRows(), Amod.numColumns(), false); + d_Up->mult(Amod, *Up_times_Amod); + d_Up.reset(Up_times_Amod); Matrix* new_d_W; if (d_update_right_SV) { @@ -262,8 +253,7 @@ IncrementalSVDFastUpdate::addNewSample( } newU->item(row, d_num_samples) = j->item(row); } - delete d_U; - d_U = newU; + d_U.reset(newU); Matrix* new_d_W; if (d_update_right_SV) { @@ -307,8 +297,7 @@ IncrementalSVDFastUpdate::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { new_d_Up->item(d_num_samples, col) = A->item(d_num_samples, col); } - delete d_Up; - d_Up = new_d_Up; + d_Up.reset(new_d_Up); // d_S = sigma. delete d_S; diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.h b/lib/linalg/svd/IncrementalSVDFastUpdate.h index 6d7e1f41c..a7d336b0f 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.h +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.h @@ -129,7 +129,7 @@ class IncrementalSVDFastUpdate : public IncrementalSVD * @brief The matrix U'. U' is not distributed and the entire matrix * exists on each processor. */ - Matrix* d_Up; + std::unique_ptr d_Up; /** * @brief The tolerance value used to remove small singular values. diff --git a/lib/linalg/svd/IncrementalSVDStandard.cpp b/lib/linalg/svd/IncrementalSVDStandard.cpp index d063d0a8f..68a3ce07e 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.cpp +++ b/lib/linalg/svd/IncrementalSVDStandard.cpp @@ -72,7 +72,7 @@ IncrementalSVDStandard::buildInitialSVD( d_S->item(0) = norm_u; // Build d_U for this new time interval. - d_U = new Matrix(d_dim, 1, true); + d_U.reset(new Matrix(d_dim, 1, true)); for (int i = 0; i < d_dim; ++i) { d_U->item(i, 0) = u[i]/norm_u; } @@ -94,13 +94,11 @@ void IncrementalSVDStandard::computeBasis() { /* Invalidate existing cached basis and update cached basis */ - delete d_basis; - d_basis = new Matrix(*d_U); + d_basis.reset(new Matrix(*d_U)); if (d_update_right_SV) { - delete d_basis_right; - d_basis_right = new Matrix(*d_W); + d_basis_right.reset(new Matrix(*d_W)); } } @@ -127,9 +125,9 @@ IncrementalSVDStandard::addLinearlyDependentSample( } // Multiply d_U and Amod and put result into d_U. - Matrix* U_times_Amod = d_U->mult(Amod); - delete d_U; - d_U = U_times_Amod; + Matrix *U_times_Amod = new Matrix(d_U->numRows(), Amod.numColumns(), false); + d_U->mult(Amod, *U_times_Amod); + d_U.reset(U_times_Amod); // Chop a column off of W to form Wmod. Matrix* new_d_W; @@ -160,7 +158,7 @@ IncrementalSVDStandard::addLinearlyDependentSample( else { max_U_dim = d_total_dim; } - if (fabs(checkOrthogonality(d_U)) > + if (fabs(checkOrthogonality(d_U.get())) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_U->orthogonalize(); } @@ -181,8 +179,7 @@ IncrementalSVDStandard::addNewSample( } tmp.item(row, d_num_samples) = j->item(row); } - delete d_U; - d_U = tmp.mult(A); + tmp.mult(*A, *d_U); Matrix* new_d_W; if (d_update_right_SV) { @@ -222,7 +219,7 @@ IncrementalSVDStandard::addNewSample( else { max_U_dim = d_total_dim; } - if (fabs(checkOrthogonality(d_U)) > + if (fabs(checkOrthogonality(d_U.get())) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_U->orthogonalize(); } diff --git a/lib/linalg/svd/RandomizedSVD.cpp b/lib/linalg/svd/RandomizedSVD.cpp index 5232e5ed2..e541d3a69 100644 --- a/lib/linalg/svd/RandomizedSVD.cpp +++ b/lib/linalg/svd/RandomizedSVD.cpp @@ -100,14 +100,13 @@ RandomizedSVD::computeSVD() } // Project snapshot matrix onto random subspace - Matrix* rand_proj = snapshot_matrix->mult(rand_mat); + std::unique_ptr rand_proj = snapshot_matrix->mult(*rand_mat); int rand_proj_rows = rand_proj->numRows(); - delete rand_mat; std::unique_ptr Q = rand_proj->qr_factorize(); // Project d_samples onto Q - Matrix* svd_input_mat = Q->transposeMult(snapshot_matrix); + std::unique_ptr svd_input_mat = Q->transposeMult(*snapshot_matrix); int svd_input_mat_distributed_rows = svd_input_mat->numDistributedRows(); SLPK_Matrix svd_input; @@ -117,7 +116,6 @@ RandomizedSVD::computeSVD() scatter_block(&svd_input, 1, 1, svd_input_mat->getData(), svd_input_mat->numColumns(), svd_input_mat->numDistributedRows(),0); - delete svd_input_mat; delete snapshot_matrix; // This block does the actual ScaLAPACK call to do the factorization. @@ -156,8 +154,8 @@ RandomizedSVD::computeSVD() memset(&d_S->item(0), 0, nc*sizeof(double)); } - d_basis = new Matrix(svd_input_mat_distributed_rows, ncolumns, false); - d_basis_right = new Matrix(d_subspace_dim, ncolumns, false); + d_basis.reset(new Matrix(svd_input_mat_distributed_rows, ncolumns, false)); + d_basis_right.reset(new Matrix(d_subspace_dim, ncolumns, false)); // Since the input to the SVD was transposed, U and V are switched. for (int rank = 0; rank < d_num_procs; ++rank) { // V is computed in the transposed order so no reordering necessary. @@ -175,14 +173,13 @@ RandomizedSVD::computeSVD() d_S->item(i) = d_factorizer->S[static_cast(i)]; // Lift solution back to higher dimension - Matrix* d_new_basis = Q->mult(d_basis); - delete d_basis; - d_basis = d_new_basis; + Matrix* d_new_basis = new Matrix(Q->numRows(), d_basis->numColumns(), + Q->distributed()); + Q->mult(*d_basis, *d_new_basis); + d_basis.reset(d_new_basis); if (num_rows <= num_cols) { - Matrix* temp = d_basis; - d_basis = d_basis_right; - d_basis_right = temp; + d_basis.swap(d_basis_right); int local_rows = -1; if (d_basis->numRows() == d_total_dim) diff --git a/lib/linalg/svd/SVD.cpp b/lib/linalg/svd/SVD.cpp index fe6547625..c67110ee4 100644 --- a/lib/linalg/svd/SVD.cpp +++ b/lib/linalg/svd/SVD.cpp @@ -20,9 +20,6 @@ SVD::SVD( d_dim(options.dim), d_num_samples(0), d_max_num_samples(options.max_num_samples), - d_basis(NULL), - d_basis_right(NULL), - d_U(NULL), d_W(NULL), d_S(NULL), d_snapshots(NULL), @@ -34,10 +31,7 @@ SVD::SVD( SVD::~SVD() { - delete d_basis; - delete d_U; delete d_S; - delete d_basis_right; delete d_W; delete d_snapshots; } diff --git a/lib/linalg/svd/SVD.h b/lib/linalg/svd/SVD.h index c8fcddc70..f63ec5eca 100644 --- a/lib/linalg/svd/SVD.h +++ b/lib/linalg/svd/SVD.h @@ -166,7 +166,7 @@ class SVD * The basis vectors are large and each process owns all of the basis * vectors. */ - Matrix* d_basis; + std::unique_ptr d_basis; /** * @brief The globalized right basis vectors for the current time interval. @@ -174,7 +174,7 @@ class SVD * Depending on the SVD algorithm, it may be distributed across all * processors or each processor may own all of U. */ - Matrix* d_basis_right; + std::unique_ptr d_basis_right; /** * @brief The matrix U which is large. @@ -182,7 +182,7 @@ class SVD * Depending on the SVD algorithm, d_U may be distributed across all * processors or each processor may own all of U. */ - Matrix* d_U; + std::unique_ptr d_U; /** * @brief The matrix U which is large. diff --git a/lib/linalg/svd/StaticSVD.cpp b/lib/linalg/svd/StaticSVD.cpp index a926a2e1a..c0f04b848 100644 --- a/lib/linalg/svd/StaticSVD.cpp +++ b/lib/linalg/svd/StaticSVD.cpp @@ -143,23 +143,13 @@ StaticSVD::getSpatialBasis() // If this basis is for the last time interval then it may not be up to date // so recompute it. if (!isBasisCurrent()) { - delete d_basis; - d_basis = nullptr; - delete d_basis_right; - d_basis_right = nullptr; - delete d_U; - d_U = nullptr; - delete d_S; - d_S = nullptr; - delete d_W; - d_W = nullptr; computeSVD(); } else { CAROM_ASSERT(d_basis != 0); } CAROM_ASSERT(isBasisCurrent()); - return d_basis; + return d_basis.get(); } const Matrix* @@ -168,23 +158,13 @@ StaticSVD::getTemporalBasis() // If this basis is for the last time interval then it may not be up to date // so recompute it. if (!isBasisCurrent()) { - delete d_basis; - d_basis = nullptr; - delete d_basis_right; - d_basis_right = nullptr; - delete d_U; - d_U = nullptr; - delete d_S; - d_S = nullptr; - delete d_W; - d_W = nullptr; computeSVD(); } else { CAROM_ASSERT(d_basis_right != 0); } CAROM_ASSERT(isBasisCurrent()); - return d_basis_right; + return d_basis_right.get(); } const Vector* @@ -193,12 +173,6 @@ StaticSVD::getSingularValues() // If these singular values are for the last time interval then they may not // be up to date so recompute them. if (!isBasisCurrent()) { - delete d_basis; - d_basis = nullptr; - delete d_basis_right; - d_basis = nullptr; - delete d_U; - d_U = nullptr; delete d_S; d_S = nullptr; delete d_W; @@ -314,8 +288,8 @@ StaticSVD::computeSVD() memset(&d_S->item(0), 0, nc*sizeof(double)); } - d_basis = new Matrix(d_dim, ncolumns, true); - d_basis_right = new Matrix(d_num_samples, ncolumns, false); + d_basis.reset(new Matrix(d_dim, ncolumns, true)); + d_basis_right.reset(new Matrix(d_num_samples, ncolumns, false)); for (int rank = 0; rank < d_num_procs; ++rank) { if (transpose) { // V is computed in the transposed order so no reordering necessary. diff --git a/unit_tests/test_IncrementalSVD.cpp b/unit_tests/test_IncrementalSVD.cpp index 2ca19d1c0..5368b6f36 100644 --- a/unit_tests/test_IncrementalSVD.cpp +++ b/unit_tests/test_IncrementalSVD.cpp @@ -49,7 +49,7 @@ class FakeIncrementalSVD : public CAROM::IncrementalSVD int dim = options.dim; /* Construct a fake d_U, d_S, d_basis */ - d_basis = new CAROM::Matrix(dim, dim, false); + d_basis.reset(new CAROM::Matrix(dim, dim, false)); d_S = new CAROM::Vector(dim, false); /* Use the identity matrix as a fake basis and fake singular values */ diff --git a/unit_tests/test_Matrix.cpp b/unit_tests/test_Matrix.cpp index 7ee71c623..0cf4f4707 100644 --- a/unit_tests/test_Matrix.cpp +++ b/unit_tests/test_Matrix.cpp @@ -327,7 +327,7 @@ TEST(MatrixSerialTest, Test_get_first_n_columns) 11.0, 12.0, 13.0, 14.0, 15.0 }; CAROM::Matrix matrix(d_mat, 4, 4, false); - CAROM::Matrix* truncated_matrix = matrix.getFirstNColumns(2); + std::unique_ptr truncated_matrix = matrix.getFirstNColumns(2); EXPECT_EQ(truncated_matrix->numRows(), 4); EXPECT_EQ(truncated_matrix->numColumns(), 2); @@ -814,7 +814,7 @@ TEST(MatrixSerialTest, Test_Matrix_orthogonalize_last7) EXPECT_TRUE(norm2 < abs_error) << norm2 << " > " << abs_error; } -TEST(MatrixSerialTest, Test_pMatrix_mult_reference) +TEST(MatrixSerialTest, Test_pMatrix_mult) { /** * Build matrix [ 1.0 0.0] @@ -824,50 +824,20 @@ TEST(MatrixSerialTest, Test_pMatrix_mult_reference) double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; const CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); CAROM::Matrix asymmetric_matrix2(asymmetric, 2, 2, false, true); - CAROM::Matrix *result = NULL; /** * [ 1.0 0.0] * [ 1.0 0.0] = [1.0 0.0] * [ 1.0 1.0] [ 1.0 1.0] [2.0 1.0] * */ - result = asymmetric_matrix.mult(asymmetric_matrix2); + std::unique_ptr result = asymmetric_matrix.mult( + asymmetric_matrix2); EXPECT_EQ(result->numRows(), 2); EXPECT_EQ(result->numColumns(), 2); EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); EXPECT_DOUBLE_EQ(result->item(0, 1), 0.0); EXPECT_DOUBLE_EQ(result->item(1, 0), 2.0); EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - - delete result; -} - -TEST(MatrixSerialTest, Test_pMatrix_mult_pointer) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - const CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - CAROM::Matrix asymmetric_matrix2(asymmetric, 2, 2, false, true); - CAROM::Matrix *result = NULL; - - /** - * [ 1.0 0.0] * [ 1.0 0.0] = [1.0 0.0] - * [ 1.0 1.0] [ 1.0 1.0] [2.0 1.0] - * - */ - result = asymmetric_matrix.mult(&asymmetric_matrix2); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 0.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 2.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - - delete result; } TEST(MatrixSerialTest, Test_void_mult_output_reference) @@ -906,25 +876,23 @@ TEST(MatrixSerialTest, Test_void_mult_output_pointer) double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; const CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); CAROM::Matrix asymmetric_matrix2(asymmetric, 2, 2, false, true); - CAROM::Matrix *result = new CAROM::Matrix(2, 2, false); /** * [ 1.0 0.0] * [ 1.0 0.0] = [1.0 0.0] * [ 1.0 1.0] [ 1.0 1.0] [2.0 1.0] * */ - asymmetric_matrix.mult(asymmetric_matrix2, result); + std::unique_ptr result = asymmetric_matrix.mult( + asymmetric_matrix2); EXPECT_EQ(result->numRows(), 2); EXPECT_EQ(result->numColumns(), 2); EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); EXPECT_DOUBLE_EQ(result->item(0, 1), 0.0); EXPECT_DOUBLE_EQ(result->item(1, 0), 2.0); EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - - delete result; } -TEST(MatrixSerialTest, Test_pMatrix_transpose_mult_output_reference) +TEST(MatrixSerialTest, Test_pMatrix_transpose_mult_output) { /** * Build matrix [ 1.0 0.0] @@ -951,16 +919,14 @@ TEST(MatrixSerialTest, Test_pMatrix_transpose_mult_output_reference) * [ 1.0 1.0] [ 0.0 1.0] [0.0 1.0] * */ - CAROM::Matrix *result = NULL; - result = asymmetric_matrix.transposeMult(identity_matrix); + std::unique_ptr result = asymmetric_matrix.transposeMult( + identity_matrix); EXPECT_EQ(result->numRows(), 2); EXPECT_EQ(result->numColumns(), 2); EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); EXPECT_DOUBLE_EQ(result->item(0, 1), 1.0); EXPECT_DOUBLE_EQ(result->item(1, 0), 0.0); EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; - result = NULL; /** * [ 1.0 0.0]^T * [ 1.0 0.0] = [1.0 0.0] @@ -974,8 +940,6 @@ TEST(MatrixSerialTest, Test_pMatrix_transpose_mult_output_reference) EXPECT_DOUBLE_EQ(result->item(0, 1), 0.0); EXPECT_DOUBLE_EQ(result->item(1, 0), 1.0); EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; - result = NULL; /** * [ 1.0 0.0]^T * [ 1.0 0.0] = [2.0 1.0] @@ -989,78 +953,9 @@ TEST(MatrixSerialTest, Test_pMatrix_transpose_mult_output_reference) EXPECT_DOUBLE_EQ(result->item(0, 1), 1.0); EXPECT_DOUBLE_EQ(result->item(1, 0), 1.0); EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; -} - -TEST(MatrixSerialTest, Test_pMatrix_transpose_mult_output_pointer) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - const CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - - /** - * Build identity matrix [ 1.0 0.0] - * [ 0.0 1.0] - * - */ - double identity[4] = {1.0, 0.0, 0.0, 1.0}; - const CAROM::Matrix identity_matrix(identity, 2, 2, false, true); - EXPECT_DOUBLE_EQ(identity_matrix.item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(identity_matrix.item(0, 1), 0.0); - EXPECT_DOUBLE_EQ(identity_matrix.item(1, 0), 0.0); - EXPECT_DOUBLE_EQ(identity_matrix.item(1, 1), 1.0); - - /** - * [ 1.0 0.0]^T * [ 1.0 0.0] = [1.0 1.0] - * [ 1.0 1.0] [ 0.0 1.0] [0.0 1.0] - * - */ - CAROM::Matrix *result = NULL; - result = asymmetric_matrix.transposeMult(&identity_matrix); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 0.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; - result = NULL; - - /** - * [ 1.0 0.0]^T * [ 1.0 0.0] = [1.0 0.0] - * [ 0.0 1.0] [ 1.0 1.0] [1.0 1.0] - * - */ - result = identity_matrix.transposeMult(&asymmetric_matrix); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 0.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; - result = NULL; - - /** - * [ 1.0 0.0]^T * [ 1.0 0.0] = [2.0 1.0] - * [ 1.0 1.0] [ 1.0 1.0] [1.0 1.0] - * - */ - result = asymmetric_matrix.transposeMult(&asymmetric_matrix); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 2.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; } -TEST(MatrixSerialTest, Test_void_transpose_mult_reference) +TEST(MatrixSerialTest, Test_void_transpose_mult) { /** * Build matrix [ 1.0 0.0] @@ -1117,74 +1012,6 @@ TEST(MatrixSerialTest, Test_void_transpose_mult_reference) EXPECT_DOUBLE_EQ(result.item(1, 1), 1.0); } -TEST(MatrixSerialTest, Test_void_transpose_mult_pointer) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - const CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - - /** - * Build identity matrix [ 1.0 0.0] - * [ 0.0 1.0] - * - */ - double identity[4] = {1.0, 0.0, 0.0, 1.0}; - const CAROM::Matrix identity_matrix(identity, 2, 2, false, true); - EXPECT_DOUBLE_EQ(identity_matrix.item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(identity_matrix.item(0, 1), 0.0); - EXPECT_DOUBLE_EQ(identity_matrix.item(1, 0), 0.0); - EXPECT_DOUBLE_EQ(identity_matrix.item(1, 1), 1.0); - - /** - * [ 1.0 0.0]^T * [ 1.0 0.0] = [1.0 1.0] - * [ 1.0 1.0] [ 0.0 1.0] [0.0 1.0] - * - */ - CAROM::Matrix *result = NULL; - asymmetric_matrix.transposeMult(identity_matrix, result); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 0.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; - result = NULL; - - /** - * [ 1.0 0.0]^T * [ 1.0 0.0] = [1.0 0.0] - * [ 0.0 1.0] [ 1.0 1.0] [1.0 1.0] - * - */ - identity_matrix.transposeMult(asymmetric_matrix, result); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 0.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; - result = NULL; - - /** - * [ 1.0 0.0]^T * [ 1.0 0.0] = [2.0 1.0] - * [ 1.0 1.0] [ 1.0 1.0] [1.0 1.0] - * - */ - asymmetric_matrix.transposeMult(asymmetric_matrix, result); - EXPECT_EQ(result->numRows(), 2); - EXPECT_EQ(result->numColumns(), 2); - EXPECT_DOUBLE_EQ(result->item(0, 0), 2.0); - EXPECT_DOUBLE_EQ(result->item(0, 1), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 0), 1.0); - EXPECT_DOUBLE_EQ(result->item(1, 1), 1.0); - delete result; -} - TEST(MatrixSerialTest, Test_void_inverse_reference) { /** @@ -1203,33 +1030,6 @@ TEST(MatrixSerialTest, Test_void_inverse_reference) EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse.item(1, 1), 1.0); } -TEST(MatrixSerialTest, Test_void_inverse_pointer_reference) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - - /** - * [ 1.0 0.0] ^ (-1) = [ 1.0 0.0] - * [ 1.0 1.0] [-1.0 1.0] - * - */ - CAROM::Matrix *asymmetric_matrix_inverse = NULL; - asymmetric_matrix_inverse = new CAROM::Matrix(2, 2, false); - asymmetric_matrix.inverse(asymmetric_matrix_inverse); - - EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(0, 0), 1.0); - EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(0, 1), 0.0); - EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(1, 0), -1.0); - EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(1, 1), 1.0); - - delete asymmetric_matrix_inverse; -} - TEST(MatrixSerialTest, Test_void_inverse_in_place) { /** @@ -1268,8 +1068,8 @@ TEST(MatrixSerialTest, Test_pMatrix_inverse) * [ 1.0 1.0] [-1.0 1.0] * */ - CAROM::Matrix* asymmetric_matrix_inverse = NULL; - asymmetric_matrix_inverse = asymmetric_matrix.inverse(); + std::unique_ptr asymmetric_matrix_inverse = + asymmetric_matrix.inverse(); EXPECT_EQ(asymmetric_matrix_inverse->numRows(), 2); EXPECT_EQ(asymmetric_matrix_inverse->numColumns(), 2); @@ -1277,8 +1077,6 @@ TEST(MatrixSerialTest, Test_pMatrix_inverse) EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(0, 1), 0.0); EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(1, 0), -1.0); EXPECT_DOUBLE_EQ(asymmetric_matrix_inverse->item(1, 1), 1.0); - - delete asymmetric_matrix_inverse; } /* Use second difference matrix as one fake Matrix for testing */ @@ -1506,37 +1304,6 @@ TEST(MatrixSerialTest, Test_qrcp_pivots_transpose) * * void transposeMult(const Vector&, Vector&) const * */ -TEST(MatrixSerialTest, Test_mult_Vector_reference) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - - /** - * Build vector [ 2.0] - * [ 4.0] - */ - double v_data[2] = {2.0, 4.0}; - CAROM::Vector v(v_data, 2, false, true); - - /** - * [ 1.0 0.0] [ 2.0] = [ 2.0] - * [ 1.0 1.0] [ 4.0] [ 6.0] - * - */ - CAROM::Vector *w; - w = asymmetric_matrix.mult(v); - EXPECT_FALSE(w->distributed()); - EXPECT_EQ(w->dim(), 2); - EXPECT_DOUBLE_EQ((*w)(0), 2.0); - EXPECT_DOUBLE_EQ((*w)(1), 6.0); - delete w; -} - TEST(MatrixSerialTest, Test_mult_Vector_pointer) { /** @@ -1547,38 +1314,6 @@ TEST(MatrixSerialTest, Test_mult_Vector_pointer) double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - /** - * Build vector [ 2.0] - * [ 4.0] - */ - double v_data[2] = {2.0, 4.0}; - CAROM::Vector *v = new CAROM::Vector(v_data, 2, false, true); - - /** - * [ 1.0 0.0] [ 2.0] = [ 2.0] - * [ 1.0 1.0] [ 4.0] [ 6.0] - * - */ - CAROM::Vector *w; - w = asymmetric_matrix.mult(*v); - EXPECT_FALSE(w->distributed()); - EXPECT_EQ(w->dim(), 2); - EXPECT_DOUBLE_EQ((*w)(0), 2.0); - EXPECT_DOUBLE_EQ((*w)(1), 6.0); - delete w; - delete v; -} - -TEST(MatrixSerialTest, Test_mult_Vector_Vector_pointer) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - /** * Build vector [ 2.0] * [ 4.0] @@ -1591,16 +1326,14 @@ TEST(MatrixSerialTest, Test_mult_Vector_Vector_pointer) * [ 1.0 1.0] [ 4.0] [ 6.0] * */ - CAROM::Vector *w = NULL; - asymmetric_matrix.mult(v, w); + std::unique_ptr w = asymmetric_matrix.mult(v); EXPECT_FALSE(w->distributed()); EXPECT_EQ(w->dim(), 2); EXPECT_DOUBLE_EQ((*w)(0), 2.0); EXPECT_DOUBLE_EQ((*w)(1), 6.0); - delete w; } -TEST(MatrixSerialTest, Test_mult_Vector_Vector_reference) +TEST(MatrixSerialTest, Test_mult_Vector_reference) { /** * Build matrix [ 1.0 0.0] @@ -1665,7 +1398,7 @@ TEST(MatrixSerialTest, Test_multPlus) } -TEST(MatrixSerialTest, Test_transposeMult_Vector_reference) +TEST(MatrixSerialTest, Test_transposeMult_Vector_pointer) { /** * Build matrix [ 1.0 0.0] @@ -1687,79 +1420,14 @@ TEST(MatrixSerialTest, Test_transposeMult_Vector_reference) * [ 1.0 1.0] [ 4.0] [ 4.0] * */ - CAROM::Vector *w; - w = asymmetric_matrix.transposeMult(v); + std::unique_ptr w = asymmetric_matrix.transposeMult(v); EXPECT_FALSE(w->distributed()); EXPECT_EQ(w->dim(), 2); EXPECT_DOUBLE_EQ((*w)(0), 6.0); EXPECT_DOUBLE_EQ((*w)(1), 4.0); - delete w; } -TEST(MatrixSerialTest, Test_transposeMult_Vector_pointer) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - - /** - * Build vector [ 2.0] - * [ 4.0] - */ - double v_data[2] = {2.0, 4.0}; - CAROM::Vector *v = new CAROM::Vector(v_data, 2, false, true); - - /** - * [ 1.0 0.0]^{T} [ 2.0] = [ 6.0] - * [ 1.0 1.0] [ 4.0] [ 4.0] - * - */ - CAROM::Vector *w; - w = asymmetric_matrix.transposeMult(v); - EXPECT_FALSE(w->distributed()); - EXPECT_EQ(w->dim(), 2); - EXPECT_DOUBLE_EQ((*w)(0), 6.0); - EXPECT_DOUBLE_EQ((*w)(1), 4.0); - delete w; - delete v; -} - -TEST(MatrixSerialTest, Test_transposeMult_Vector_Vector_pointer) -{ - /** - * Build matrix [ 1.0 0.0] - * [ 1.0 1.0] - * - */ - double asymmetric[4] = {1.0, 0.0, 1.0, 1.0}; - CAROM::Matrix asymmetric_matrix(asymmetric, 2, 2, false, true); - - /** - * Build vector [ 2.0] - * [ 4.0] - */ - double v_data[2] = {2.0, 4.0}; - CAROM::Vector v(v_data, 2, false, true); - - /** - * [ 1.0 0.0]^{T} [ 2.0] = [ 6.0] - * [ 1.0 1.0] [ 4.0] [ 4.0] - * - */ - CAROM::Vector *w = NULL; - asymmetric_matrix.transposeMult(v, w); - EXPECT_FALSE(w->distributed()); - EXPECT_EQ(w->dim(), 2); - EXPECT_DOUBLE_EQ((*w)(0), 6.0); - EXPECT_DOUBLE_EQ((*w)(1), 4.0); - delete w; -} - -TEST(MatrixSerialTest, Test_transposeMult_Vector_Vector_reference) +TEST(MatrixSerialTest, Test_transposeMult_Vector_reference) { /** * Build matrix [ 1.0 0.0] diff --git a/unit_tests/test_QR.cpp b/unit_tests/test_QR.cpp index ec52b5d67..e3d94d488 100644 --- a/unit_tests/test_QR.cpp +++ b/unit_tests/test_QR.cpp @@ -77,7 +77,7 @@ TEST(QRfactorizeTest, Test_QR) // Verify that the columns of Q are orthonormal. { - CAROM::Matrix *id = exactQ.transposeMult(exactQ); + std::unique_ptr id = exactQ.transposeMult(exactQ); EXPECT_EQ(id->numRows(), num_columns); EXPECT_EQ(id->numColumns(), num_columns); @@ -92,11 +92,9 @@ TEST(QRfactorizeTest, Test_QR) } EXPECT_NEAR(maxError, 0.0, 1.0e-15); - - delete id; } - CAROM::Matrix *A = exactQ.mult(exactR); // Compute A = QR + std::unique_ptr A = exactQ.mult(exactR); // Compute A = QR // Factorize A std::vector> QRfactors; @@ -104,8 +102,6 @@ TEST(QRfactorizeTest, Test_QR) std::unique_ptr & Q = QRfactors[0]; std::unique_ptr & R = QRfactors[1]; - delete A; - EXPECT_EQ(Q->numRows(), loc_num_rows); EXPECT_EQ(Q->numColumns(), num_columns); diff --git a/unit_tests/test_S_OPT.cpp b/unit_tests/test_S_OPT.cpp index 9cae320dd..c5adec70b 100644 --- a/unit_tests/test_S_OPT.cpp +++ b/unit_tests/test_S_OPT.cpp @@ -110,7 +110,8 @@ TEST(S_OPTSerialTest, Test_S_OPT) } } - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, true); + std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, + num_cols, true)); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); @@ -225,7 +226,8 @@ TEST(S_OPTSerialTest, Test_S_OPT_less_basis_vectors) } } - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, true); + std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, + num_cols, true)); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); @@ -341,7 +343,8 @@ TEST(S_OPTSerialTest, Test_S_OPT_init_vector) } } - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, true); + std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, + num_cols, true)); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); @@ -500,7 +503,8 @@ TEST(S_OPTSerialTest, Test_S_OPT_QR) } } - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, true); + std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, + num_cols, true)); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); From 9b9086068717cbb9e3716d20d74e2a4bdd6b0e2d Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 31 Jul 2024 18:50:09 -0700 Subject: [PATCH 06/19] Fixed DMDc. --- examples/dmd/heat_conduction_dmdc.cpp | 7 +------ examples/dmd/parametric_dmdc_heat_conduction.cpp | 10 +--------- examples/dmd/parametric_heat_conduction.cpp | 2 +- lib/algo/DMD.cpp | 4 ++-- lib/algo/DMD.h | 2 +- lib/algo/DMDc.cpp | 4 +++- lib/algo/DMDc.h | 2 +- lib/linalg/svd/IncrementalSVD.cpp | 10 ++++------ lib/linalg/svd/IncrementalSVD.h | 2 +- lib/linalg/svd/IncrementalSVDBrand.cpp | 10 +++++----- lib/linalg/svd/IncrementalSVDFastUpdate.cpp | 4 ++-- lib/linalg/svd/IncrementalSVDStandard.cpp | 6 +++--- 12 files changed, 25 insertions(+), 38 deletions(-) diff --git a/examples/dmd/heat_conduction_dmdc.cpp b/examples/dmd/heat_conduction_dmdc.cpp index 91347c89a..910b68215 100644 --- a/examples/dmd/heat_conduction_dmdc.cpp +++ b/examples/dmd/heat_conduction_dmdc.cpp @@ -540,7 +540,7 @@ int main(int argc, char *argv[]) std::cout << "Predicting temperature using DMDc" << std::endl; } - CAROM::Vector* result_u = dmd_u->predict(ts[0]); + std::unique_ptr result_u = dmd_u->predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); @@ -553,8 +553,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.Save(); } - delete result_u; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -568,8 +566,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_u; } } } @@ -602,7 +598,6 @@ int main(int argc, char *argv[]) // 16. Free the used memory. delete ode_solver; delete pmesh; - delete result_u; MPI_Finalize(); diff --git a/examples/dmd/parametric_dmdc_heat_conduction.cpp b/examples/dmd/parametric_dmdc_heat_conduction.cpp index 10841be6a..ea53059ca 100644 --- a/examples/dmd/parametric_dmdc_heat_conduction.cpp +++ b/examples/dmd/parametric_dmdc_heat_conduction.cpp @@ -838,7 +838,7 @@ int main(int argc, char *argv[]) std::cout << "Predicting temperature using DMDc" << std::endl; } - CAROM::Vector* result_u = dmd_u->predict(ts[0]); + std::unique_ptr result_u = dmd_u->predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); @@ -855,8 +855,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.Save(); } - delete result_u; - if (visit) { for (int i = 1; i < ts.size(); i++) @@ -870,8 +868,6 @@ int main(int argc, char *argv[]) dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); dmd_visit_dc.Save(); - - delete result_u; } } } @@ -900,11 +896,7 @@ int main(int argc, char *argv[]) printf("Elapsed time for predicting DMDc: %e second\n", dmd_prediction_timer.RealTime()); } - - delete result_u; - } - } // 16. Free the used memory. diff --git a/examples/dmd/parametric_heat_conduction.cpp b/examples/dmd/parametric_heat_conduction.cpp index 2c5ff2412..9e0dc0a03 100644 --- a/examples/dmd/parametric_heat_conduction.cpp +++ b/examples/dmd/parametric_heat_conduction.cpp @@ -796,7 +796,7 @@ int main(int argc, char *argv[]) std::cout << "Predicting temperature using DMD at: " << ts[0] << std::endl; } - std::shared_ptr result_u = dmd_u->predict(ts[0]); + std::unique_ptr result_u = dmd_u->predict(ts[0]); Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index bbc15ae2f..49a97fc57 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -614,7 +614,7 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) d_init_projected = true; } -std::shared_ptr +std::unique_ptr DMD::predict(double t, int deg) { CAROM_VERIFY(d_trained); @@ -634,7 +634,7 @@ DMD::predict(double t, int deg) std::unique_ptr d_predicted_state_real_2 = d_phi_mult_eigs_imaginary->mult(*d_projected_init_imaginary); - std::shared_ptr d_predicted_state_real = + std::unique_ptr d_predicted_state_real = d_predicted_state_real_1->minus(*d_predicted_state_real_2); addOffset(*d_predicted_state_real, t, deg); diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index 3ff6d7cb7..f423e1791 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -151,7 +151,7 @@ class DMD * @param[in] t The time of the output state * @param[in] deg The derivative degree of the output state */ - std::shared_ptr predict(double t, int deg = 0); + std::unique_ptr predict(double t, int deg = 0); /** * @brief Get the time offset contained within d_t_offset. diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index 7e4f2199c..2c07db638 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -684,7 +684,7 @@ DMDc::project(const Vector* init, const Matrix* controls, double t_offset) d_init_projected = true; } -Vector* +std::unique_ptr DMDc::predict(double t) { CAROM_VERIFY(d_trained); @@ -731,6 +731,8 @@ DMDc::predict(double t) delete f_control_real; delete f_control_imaginary; + + return d_predicted_state_real; } void diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index b7f0c9e92..f532c0bea 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -120,7 +120,7 @@ class DMDc * * @param[in] t The time of the output state */ - Vector* predict(double t); + std::unique_ptr predict(double t); /** * @brief Get the time offset contained within d_t_offset. diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index cbb19c54a..9d07fe6eb 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -506,19 +506,17 @@ IncrementalSVD::svd( double IncrementalSVD::checkOrthogonality( - const Matrix* m) + const Matrix & m) { - CAROM_ASSERT(m != 0); - double result = 0.0; if (d_num_samples > 1) { int last_col = d_num_samples-1; double tmp = 0.0; - int num_rows = m->numRows(); + int num_rows = m.numRows(); for (int i = 0; i < num_rows; ++i) { - tmp += m->item(i, 0) * m->item(i, last_col); + tmp += m.item(i, 0) * m.item(i, last_col); } - if (m->distributed() && d_size > 1) { + if (m.distributed() && d_size > 1) { MPI_Allreduce(&tmp, &result, 1, MPI_DOUBLE, MPI_SUM, MPI_COMM_WORLD); } else { diff --git a/lib/linalg/svd/IncrementalSVD.h b/lib/linalg/svd/IncrementalSVD.h index 5b293e45a..ca770a926 100644 --- a/lib/linalg/svd/IncrementalSVD.h +++ b/lib/linalg/svd/IncrementalSVD.h @@ -233,7 +233,7 @@ class IncrementalSVD : public SVD */ double checkOrthogonality( - const Matrix* m); + const Matrix & m); /** * @brief Tolerance to determine whether or not a sample is linearly diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index b58a03740..ada56b14e 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -269,7 +269,7 @@ IncrementalSVDBrand::updateSpatialBasis() // Reorthogonalize if necessary. // (not likely to be called anymore but left for safety) - if (fabs(checkOrthogonality(d_basis.get())) > + if (fabs(checkOrthogonality(*d_basis)) > std::numeric_limits::epsilon()*static_cast(d_num_samples)) { d_basis->orthogonalize(); } @@ -302,7 +302,7 @@ IncrementalSVDBrand::updateTemporalBasis() // Reorthogonalize if necessary. // (not likely to be called anymore but left for safety) - if (fabs(checkOrthogonality(d_basis_right.get())) > + if (fabs(checkOrthogonality(*d_basis_right)) > std::numeric_limits::epsilon()*d_num_samples) { d_basis_right->orthogonalize(); } @@ -475,18 +475,18 @@ IncrementalSVDBrand::addNewSample( else { max_U_dim = d_total_dim; } - if (fabs(checkOrthogonality(d_Up.get())) > + if (fabs(checkOrthogonality(*d_Up)) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_Up->orthogonalize(); } - if (fabs(checkOrthogonality(d_U.get())) > + if (fabs(checkOrthogonality(*d_U)) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_U->orthogonalize(); // Will not be called, but just in case } if(d_update_right_SV) { - if (fabs(checkOrthogonality(d_W)) > + if (fabs(checkOrthogonality(*d_W)) > std::numeric_limits::epsilon()*d_num_samples) { d_W->orthogonalize(); } diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp index 67a9ec1b2..e46178577 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp @@ -166,13 +166,13 @@ IncrementalSVDFastUpdate::computeBasis() } // Reorthogonalize if necessary. - if (fabs(checkOrthogonality(d_basis.get())) > + if (fabs(checkOrthogonality(*d_basis)) > std::numeric_limits::epsilon()*static_cast(d_num_samples)) { d_basis->orthogonalize(); } if(d_update_right_SV) { - if (fabs(checkOrthogonality(d_basis_right.get())) > + if (fabs(checkOrthogonality(*d_basis_right)) > std::numeric_limits::epsilon()*d_num_samples) { d_basis_right->orthogonalize(); } diff --git a/lib/linalg/svd/IncrementalSVDStandard.cpp b/lib/linalg/svd/IncrementalSVDStandard.cpp index 68a3ce07e..c01209697 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.cpp +++ b/lib/linalg/svd/IncrementalSVDStandard.cpp @@ -158,7 +158,7 @@ IncrementalSVDStandard::addLinearlyDependentSample( else { max_U_dim = d_total_dim; } - if (fabs(checkOrthogonality(d_U.get())) > + if (fabs(checkOrthogonality(*d_U)) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_U->orthogonalize(); } @@ -219,12 +219,12 @@ IncrementalSVDStandard::addNewSample( else { max_U_dim = d_total_dim; } - if (fabs(checkOrthogonality(d_U.get())) > + if (fabs(checkOrthogonality(*d_U)) > std::numeric_limits::epsilon()*static_cast(max_U_dim)) { d_U->orthogonalize(); } if (d_update_right_SV) { - if (fabs(checkOrthogonality(d_W)) > + if (fabs(checkOrthogonality(*d_W)) > std::numeric_limits::epsilon()*d_num_samples) { d_W->orthogonalize(); } From ffa9e5aa62c738cd3cd3257d89f374ae8e9757b6 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 31 Jul 2024 20:51:51 -0700 Subject: [PATCH 07/19] Elimination of raw pointers in BasisReader, BasisGenerator, and SVD classes. --- examples/misc/combine_samples.cpp | 5 +- .../prom/de_parametric_maxwell_greedy.cpp | 3 +- examples/prom/dg_advection_global_rom.cpp | 3 +- .../dg_advection_local_rom_matrix_interp.cpp | 8 +-- .../prom/elliptic_eigenproblem_global_rom.cpp | 8 +-- examples/prom/grad_div_global_rom.cpp | 3 +- .../prom/linear_elasticity_global_rom.cpp | 3 +- examples/prom/maxwell_global_rom.cpp | 3 +- examples/prom/maxwell_local_rom_greedy.cpp | 3 +- examples/prom/mixed_nonlinear_diffusion.cpp | 8 +-- .../prom/nonlinear_elasticity_global_rom.cpp | 12 ++--- examples/prom/poisson_global_rom.cpp | 3 +- examples/prom/poisson_local_rom_greedy.cpp | 3 +- lib/linalg/BasisGenerator.cpp | 25 ++++----- lib/linalg/BasisGenerator.h | 8 +-- lib/linalg/BasisReader.cpp | 51 +++++++++---------- lib/linalg/BasisReader.h | 27 +++++----- lib/linalg/BasisWriter.cpp | 12 ++--- lib/linalg/svd/IncrementalSVD.cpp | 16 +++--- lib/linalg/svd/IncrementalSVD.h | 20 +++----- lib/linalg/svd/IncrementalSVDBrand.cpp | 15 +++--- lib/linalg/svd/IncrementalSVDBrand.h | 10 ++-- lib/linalg/svd/IncrementalSVDFastUpdate.cpp | 5 +- lib/linalg/svd/IncrementalSVDFastUpdate.h | 6 +-- lib/linalg/svd/IncrementalSVDStandard.cpp | 5 +- lib/linalg/svd/IncrementalSVDStandard.h | 6 +-- lib/linalg/svd/RandomizedSVD.cpp | 2 +- lib/linalg/svd/SVD.cpp | 2 - lib/linalg/svd/SVD.h | 18 +++---- lib/linalg/svd/StaticSVD.cpp | 18 +++---- lib/linalg/svd/StaticSVD.h | 20 +++----- regression_tests/basisComparator.cpp | 13 ++--- unit_tests/random_test.cpp | 13 ++--- unit_tests/test_HDFDatabase.cpp | 41 ++++++++------- unit_tests/test_IncrementalSVD.cpp | 6 +-- unit_tests/test_IncrementalSVDBrand.cpp | 6 +-- unit_tests/test_RandomizedSVD.cpp | 24 ++++----- unit_tests/test_StaticSVD.cpp | 12 ++--- unit_tests/test_basis_conversion.cpp | 10 ++-- 39 files changed, 206 insertions(+), 250 deletions(-) mode change 100755 => 100644 regression_tests/basisComparator.cpp diff --git a/examples/misc/combine_samples.cpp b/examples/misc/combine_samples.cpp index 22429a29c..cfffc54e0 100644 --- a/examples/misc/combine_samples.cpp +++ b/examples/misc/combine_samples.cpp @@ -159,8 +159,9 @@ int main(int argc, char* argv[]) else { /*-- load data from hdf5 file to find the mean and subtract it --*/ if (rank==0) std::cout << "Reading snapshots" << std::endl; - CAROM::Matrix* snapshots = (CAROM::Matrix*) - static_basis_generator->getSnapshotMatrix(); + + CAROM::Matrix *snapshots = (CAROM::Matrix*) + static_basis_generator->getSnapshotMatrix().get(); int num_rows = snapshots->numRows(); int num_cols = snapshots->numColumns(); diff --git a/examples/prom/de_parametric_maxwell_greedy.cpp b/examples/prom/de_parametric_maxwell_greedy.cpp index abe4d769b..a27cff4d2 100644 --- a/examples/prom/de_parametric_maxwell_greedy.cpp +++ b/examples/prom/de_parametric_maxwell_greedy.cpp @@ -212,7 +212,7 @@ double simulation() loadBasisName += "_greedy"; } - const CAROM::Matrix* spatialbasis; + std::unique_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; @@ -358,7 +358,6 @@ double simulation() // 24. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 25. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/dg_advection_global_rom.cpp b/examples/prom/dg_advection_global_rom.cpp index 11680f2f1..c4ffbe6a7 100644 --- a/examples/prom/dg_advection_global_rom.cpp +++ b/examples/prom/dg_advection_global_rom.cpp @@ -668,7 +668,7 @@ int main(int argc, char *argv[]) bool isIncremental = false; const std::string basisName = "basis"; const std::string basisFileName = basisName + std::to_string(id); - const CAROM::Matrix* spatialbasis; + std::unique_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; @@ -913,7 +913,6 @@ int main(int argc, char *argv[]) if (myid == 0) std::cout << "Relative l2 error of ROM solution " << diffNorm / fomNorm << std::endl; - delete spatialbasis; delete M_hat_carom; delete K_hat_carom; delete M_hat; diff --git a/examples/prom/dg_advection_local_rom_matrix_interp.cpp b/examples/prom/dg_advection_local_rom_matrix_interp.cpp index 5b38c900e..0536677f7 100644 --- a/examples/prom/dg_advection_local_rom_matrix_interp.cpp +++ b/examples/prom/dg_advection_local_rom_matrix_interp.cpp @@ -722,13 +722,9 @@ int main(int argc, char *argv[]) { CAROM::BasisReader reader(basisName); if (rdim != -1) - { - spatialbasis.reset(reader.getSpatialBasis(rdim)); - } + spatialbasis = reader.getSpatialBasis(rdim); else - { - spatialbasis.reset(reader.getSpatialBasis(ef)); - } + spatialbasis = reader.getSpatialBasis(ef); numRowRB = spatialbasis->numRows(); numColumnRB = spatialbasis->numColumns(); if (myid == 0) printf("spatial basis dimension is %d x %d\n", numRowRB, diff --git a/examples/prom/elliptic_eigenproblem_global_rom.cpp b/examples/prom/elliptic_eigenproblem_global_rom.cpp index ce48db220..c2fc17d16 100644 --- a/examples/prom/elliptic_eigenproblem_global_rom.cpp +++ b/examples/prom/elliptic_eigenproblem_global_rom.cpp @@ -495,15 +495,11 @@ int main(int argc, char *argv[]) CAROM::BasisReader reader(basis_filename); Vector eigenvalues_rom; - const CAROM::Matrix *spatialbasis; + std::unique_ptr spatialbasis; if (rdim != -1) - { spatialbasis = reader.getSpatialBasis(rdim); - } else - { spatialbasis = reader.getSpatialBasis(ef); - } const int numRowRB = spatialbasis->numRows(); const int numColumnRB = spatialbasis->numColumns(); @@ -553,8 +549,6 @@ int main(int argc, char *argv[]) eigenvectors.SetRow(i, eigenvector_carom->getData()); } - delete spatialbasis; - delete A_mat; delete M_mat; } diff --git a/examples/prom/grad_div_global_rom.cpp b/examples/prom/grad_div_global_rom.cpp index 0d4413701..df784c0fc 100644 --- a/examples/prom/grad_div_global_rom.cpp +++ b/examples/prom/grad_div_global_rom.cpp @@ -370,7 +370,7 @@ int main(int argc, char *argv[]) // 20. read the reduced basis assembleTimer.Start(); CAROM::BasisReader reader(basisName); - const CAROM::Matrix* spatialbasis = reader.getSpatialBasis(); + std::unique_ptr spatialbasis = reader.getSpatialBasis(); const int numRowRB = spatialbasis->numRows(); const int numColumnRB = spatialbasis->numColumns(); if (myid == 0) printf("spatial basis dimension is %d x %d\n", numRowRB, @@ -395,7 +395,6 @@ int main(int argc, char *argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/linear_elasticity_global_rom.cpp b/examples/prom/linear_elasticity_global_rom.cpp index 5a214f239..3532551c9 100644 --- a/examples/prom/linear_elasticity_global_rom.cpp +++ b/examples/prom/linear_elasticity_global_rom.cpp @@ -379,7 +379,7 @@ int main(int argc, char* argv[]) // 20. read the reduced basis assembleTimer.Start(); CAROM::BasisReader reader(basisName); - const CAROM::Matrix* spatialbasis = reader.getSpatialBasis(); + std::unique_ptr spatialbasis = reader.getSpatialBasis(); numRowRB = spatialbasis->numRows(); numColumnRB = spatialbasis->numColumns(); printf("On rank %d, spatial basis dimension is %d x %d\n", myid, @@ -405,7 +405,6 @@ int main(int argc, char* argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/maxwell_global_rom.cpp b/examples/prom/maxwell_global_rom.cpp index 2135866c4..bd434dd3c 100644 --- a/examples/prom/maxwell_global_rom.cpp +++ b/examples/prom/maxwell_global_rom.cpp @@ -220,7 +220,7 @@ int main(int argc, char *argv[]) bool isIncremental = false; const std::string basisName = "basis"; const std::string basisFileName = basisName + std::to_string(id); - const CAROM::Matrix* spatialbasis; + std::unique_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; @@ -386,7 +386,6 @@ int main(int argc, char *argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/maxwell_local_rom_greedy.cpp b/examples/prom/maxwell_local_rom_greedy.cpp index 6ddb8fbab..10527d147 100644 --- a/examples/prom/maxwell_local_rom_greedy.cpp +++ b/examples/prom/maxwell_local_rom_greedy.cpp @@ -365,7 +365,7 @@ int main(int argc, char *argv[]) loadBasisName += "_greedy"; } - const CAROM::Matrix* spatialbasis; + std::unique_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; @@ -508,7 +508,6 @@ int main(int argc, char *argv[]) // 24. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 25. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/mixed_nonlinear_diffusion.cpp b/examples/prom/mixed_nonlinear_diffusion.cpp index 72322d5bc..80456a057 100644 --- a/examples/prom/mixed_nonlinear_diffusion.cpp +++ b/examples/prom/mixed_nonlinear_diffusion.cpp @@ -856,7 +856,7 @@ int main(int argc, char *argv[]) if (online) { CAROM::BasisReader readerR("basisR"); - BR_librom.reset(readerR.getSpatialBasis()); + BR_librom = readerR.getSpatialBasis(); if (rrdim == -1) rrdim = BR_librom->numColumns(); else @@ -871,7 +871,7 @@ int main(int argc, char *argv[]) printf("reduced R dim = %d\n",rrdim); CAROM::BasisReader readerW("basisW"); - BW_librom.reset(readerW.getSpatialBasis()); + BW_librom = readerW.getSpatialBasis(); if (rwdim == -1) rwdim = BW_librom->numColumns(); else @@ -893,7 +893,7 @@ int main(int argc, char *argv[]) */ CAROM::BasisReader readerFR("basisFR"); - FR_librom.reset(readerFR.getSpatialBasis()); + FR_librom = readerFR.getSpatialBasis(); if (nldim == -1) { @@ -981,7 +981,7 @@ int main(int argc, char *argv[]) if (hyperreduce_source) { readerS = new CAROM::BasisReader("basisS"); - S_librom.reset(readerS->getSpatialBasis()); + S_librom = readerS->getSpatialBasis(); if (nsdim == -1) { diff --git a/examples/prom/nonlinear_elasticity_global_rom.cpp b/examples/prom/nonlinear_elasticity_global_rom.cpp index d0178b33e..059077bd9 100644 --- a/examples/prom/nonlinear_elasticity_global_rom.cpp +++ b/examples/prom/nonlinear_elasticity_global_rom.cpp @@ -815,16 +815,14 @@ int main(int argc, char *argv[]) if (x_base_only) { - readerV = new - CAROM::BasisReader("basisX"); // The basis for v uses the x basis instead. + // The basis for v uses the x basis instead. + readerV = new CAROM::BasisReader("basisX"); rvdim = rxdim; } else - { readerV = new CAROM::BasisReader("basisV"); - } - BV_librom.reset(readerV->getSpatialBasis()); + BV_librom = readerV->getSpatialBasis(); if (rvdim == -1) // Change rvdim rvdim = BV_librom->numColumns(); @@ -837,7 +835,7 @@ int main(int argc, char *argv[]) printf("reduced V dim = %d\n", rvdim); CAROM::BasisReader readerX("basisX"); - BX_librom.reset(readerX.getSpatialBasis()); + BX_librom = readerX.getSpatialBasis(); if (rxdim == -1) // Change rxdim rxdim = BX_librom->numColumns(); @@ -851,7 +849,7 @@ int main(int argc, char *argv[]) // Hyper reduce H CAROM::BasisReader readerH("basisH"); - H_librom.reset(readerH.getSpatialBasis()); + H_librom = readerH.getSpatialBasis(); // Compute sample points if (hdim == -1) diff --git a/examples/prom/poisson_global_rom.cpp b/examples/prom/poisson_global_rom.cpp index af43f2982..11054e5ed 100644 --- a/examples/prom/poisson_global_rom.cpp +++ b/examples/prom/poisson_global_rom.cpp @@ -229,7 +229,7 @@ int main(int argc, char *argv[]) bool isIncremental = false; const std::string basisName = "basis"; const std::string basisFileName = basisName + std::to_string(id); - const CAROM::Matrix* spatialbasis; + std::unique_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; @@ -382,7 +382,6 @@ int main(int argc, char *argv[]) // 23. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 24. Recover the parallel grid function corresponding to X. This is the diff --git a/examples/prom/poisson_local_rom_greedy.cpp b/examples/prom/poisson_local_rom_greedy.cpp index f3aa8b7d3..110deac71 100644 --- a/examples/prom/poisson_local_rom_greedy.cpp +++ b/examples/prom/poisson_local_rom_greedy.cpp @@ -367,7 +367,7 @@ int main(int argc, char *argv[]) loadBasisName += "_greedy"; } - const CAROM::Matrix* spatialbasis; + std::unique_ptr spatialbasis; CAROM::Options* options; CAROM::BasisGenerator *generator; int numRowRB, numColumnRB; @@ -492,7 +492,6 @@ int main(int argc, char *argv[]) // 24. reconstruct FOM state spatialbasis->mult(reducedSol, X_carom); - delete spatialbasis; } // 25. Recover the parallel grid function corresponding to X. This is the diff --git a/lib/linalg/BasisGenerator.cpp b/lib/linalg/BasisGenerator.cpp index 100e5b834..29c5946ae 100644 --- a/lib/linalg/BasisGenerator.cpp +++ b/lib/linalg/BasisGenerator.cpp @@ -71,20 +71,17 @@ BasisGenerator::BasisGenerator( if (options.fast_update_brand) { d_svd.reset( new IncrementalSVDBrand( - options, - basis_file_name)); + options, basis_file_name)); } else if (options.fast_update) { d_svd.reset( new IncrementalSVDFastUpdate( - options, - basis_file_name)); + options, basis_file_name)); } else { d_svd.reset( new IncrementalSVDStandard( - options, - basis_file_name)); + options, basis_file_name)); } // Get the number of processors. @@ -100,14 +97,10 @@ BasisGenerator::BasisGenerator( else { if (options.randomized) { - d_svd.reset( - new RandomizedSVD( - options)); + d_svd.reset(new RandomizedSVD(options)); } else { - d_svd.reset( - new StaticSVD( - options)); + d_svd.reset(new StaticSVD(options)); } } } @@ -159,8 +152,8 @@ BasisGenerator::loadSampleRange(const std::string& base_file_name, if (d_basis_reader) delete d_basis_reader; d_basis_reader = new BasisReader(base_file_name, db_format, d_dim); - const Matrix* mat; - const Vector* singular_vals; + std::unique_ptr mat; + std::unique_ptr singular_vals; if (kind == "basis") { mat = d_basis_reader->getSpatialBasis(); @@ -221,7 +214,7 @@ BasisGenerator::computeNextSampleTime( } // Get the current basis vectors. - const Matrix* basis = getSpatialBasis(); + std::shared_ptr basis = getSpatialBasis(); // Compute l = basis' * u Vector l(basis->numColumns(), false); @@ -309,7 +302,7 @@ BasisGenerator::finalSummary( const int first_sv) { const int rom_dim = getSpatialBasis()->numColumns(); - const Vector* sing_vals = getSingularValues(); + std::shared_ptr sing_vals = getSingularValues(); CAROM_VERIFY(rom_dim <= sing_vals->dim()); diff --git a/lib/linalg/BasisGenerator.h b/lib/linalg/BasisGenerator.h index 87604447e..792c14044 100644 --- a/lib/linalg/BasisGenerator.h +++ b/lib/linalg/BasisGenerator.h @@ -196,7 +196,7 @@ class BasisGenerator * * @return The basis vectors for the current time interval. */ - const Matrix* + std::shared_ptr getSpatialBasis() { return d_svd->getSpatialBasis(); @@ -208,7 +208,7 @@ class BasisGenerator * * @return The temporal basis vectors for the current time interval. */ - const Matrix* + std::shared_ptr getTemporalBasis() { return d_svd->getTemporalBasis(); @@ -220,7 +220,7 @@ class BasisGenerator * * @return The singular values for the current time interval. */ - const Vector* + std::shared_ptr getSingularValues() { return d_svd->getSingularValues(); @@ -231,7 +231,7 @@ class BasisGenerator * * @return The snapshot matrix for the current time interval. */ - const Matrix* + std::shared_ptr getSnapshotMatrix() { return d_svd->getSnapshotMatrix(); diff --git a/lib/linalg/BasisReader.cpp b/lib/linalg/BasisReader.cpp index b6e26eed8..37d9cd591 100644 --- a/lib/linalg/BasisReader.cpp +++ b/lib/linalg/BasisReader.cpp @@ -72,7 +72,7 @@ BasisReader::~BasisReader() delete d_database; } -Matrix* +std::unique_ptr BasisReader::getSpatialBasis() { int num_rows = getDim("basis"); @@ -84,17 +84,17 @@ BasisReader::getSpatialBasis() &spatial_basis_vectors->item(0, 0), num_rows*num_cols, true); - return spatial_basis_vectors; + return std::unique_ptr(spatial_basis_vectors); } -Matrix* +std::unique_ptr BasisReader::getSpatialBasis( int n) { return getSpatialBasis(1, n); } -Matrix* +std::unique_ptr BasisReader::getSpatialBasis( int start_col, int end_col) @@ -116,14 +116,14 @@ BasisReader::getSpatialBasis( num_cols_to_read, num_cols, true); - return spatial_basis_vectors; + return std::unique_ptr(spatial_basis_vectors); } -Matrix* +std::unique_ptr BasisReader::getSpatialBasis( double ef) { - Vector* sv = getSingularValues(); + std::unique_ptr sv = getSingularValues(); double total_energy = 0.0; double energy = 0.0; for (int i = 0; i < sv->dim(); i++) @@ -142,11 +142,10 @@ BasisReader::getSpatialBasis( } } - delete sv; return getSpatialBasis(num_used_singular_values); } -Matrix* +std::unique_ptr BasisReader::getTemporalBasis() { int num_rows = getDim("temporal_basis"); @@ -158,17 +157,17 @@ BasisReader::getTemporalBasis() d_database->getDoubleArray(tmp, &temporal_basis_vectors->item(0, 0), num_rows*num_cols); - return temporal_basis_vectors; + return std::unique_ptr(temporal_basis_vectors); } -Matrix* +std::unique_ptr BasisReader::getTemporalBasis( int n) { return getTemporalBasis(1, n); } -Matrix* +std::unique_ptr BasisReader::getTemporalBasis( int start_col, int end_col) @@ -189,14 +188,14 @@ BasisReader::getTemporalBasis( start_col - 1, num_cols_to_read, num_cols); - return temporal_basis_vectors; + return std::unique_ptr(temporal_basis_vectors); } -Matrix* +std::unique_ptr BasisReader::getTemporalBasis( double ef) { - Vector* sv = getSingularValues(); + std::unique_ptr sv = getSingularValues(); double total_energy = 0.0; double energy = 0.0; for (int i = 0; i < sv->dim(); i++) @@ -215,11 +214,10 @@ BasisReader::getTemporalBasis( } } - delete sv; return getTemporalBasis(num_used_singular_values); } -Vector* +std::unique_ptr BasisReader::getSingularValues() { char tmp[100]; @@ -232,14 +230,14 @@ BasisReader::getSingularValues() d_database->getDoubleArray(tmp, &singular_values->item(0), size); - return singular_values; + return std::unique_ptr(singular_values); } -Vector* +std::unique_ptr BasisReader::getSingularValues( double ef) { - Vector* sv = getSingularValues(); + std::unique_ptr sv = getSingularValues(); double total_energy = 0.0; double energy = 0.0; for (int i = 0; i < sv->dim(); i++) @@ -265,8 +263,7 @@ BasisReader::getSingularValues( truncated_singular_values->item(i) = sv->item(i); } - delete sv; - return truncated_singular_values; + return std::unique_ptr(truncated_singular_values); } int @@ -320,7 +317,7 @@ BasisReader::getNumSamples( return num_cols; } -Matrix* +std::unique_ptr BasisReader::getSnapshotMatrix() { int num_rows = getDim("snapshot"); @@ -333,17 +330,17 @@ BasisReader::getSnapshotMatrix() &snapshots->item(0, 0), num_rows*num_cols, true); - return snapshots; + return std::unique_ptr(snapshots); } -Matrix* +std::unique_ptr BasisReader::getSnapshotMatrix( int n) { return getSnapshotMatrix(1, n); } -Matrix* +std::unique_ptr BasisReader::getSnapshotMatrix( int start_col, int end_col) @@ -365,6 +362,6 @@ BasisReader::getSnapshotMatrix( num_cols_to_read, num_cols, true); - return snapshots; + return std::unique_ptr(snapshots); } } diff --git a/lib/linalg/BasisReader.h b/lib/linalg/BasisReader.h index 323d811b6..3488196dd 100644 --- a/lib/linalg/BasisReader.h +++ b/lib/linalg/BasisReader.h @@ -17,6 +17,7 @@ #include "utils/Database.h" #include #include +#include namespace CAROM { @@ -63,7 +64,7 @@ class BasisReader { * * @return The spatial basis vectors. */ - Matrix* + std::unique_ptr getSpatialBasis(); /** @@ -77,7 +78,7 @@ class BasisReader { * * @return The spatial basis vectors for the requested time. */ - Matrix* + std::unique_ptr getSpatialBasis( int n); @@ -94,7 +95,7 @@ class BasisReader { * * @return The spatial basis vectors for the requested time. */ - Matrix* + std::unique_ptr getSpatialBasis( int start_col, int end_col); @@ -110,7 +111,7 @@ class BasisReader { * * @return The spatial basis vectors for the requested time. */ - Matrix* + std::unique_ptr getSpatialBasis( double ef); @@ -121,7 +122,7 @@ class BasisReader { * * @return The temporal basis vectors for the requested time. */ - Matrix* + std::unique_ptr getTemporalBasis(); /** @@ -135,7 +136,7 @@ class BasisReader { * * @return The temporal basis vectors for the requested time. */ - Matrix* + std::unique_ptr getTemporalBasis( int n); @@ -152,7 +153,7 @@ class BasisReader { * * @return The temporal basis vectors for the requested time. */ - Matrix* + std::unique_ptr getTemporalBasis( int start_col, int end_col); @@ -168,7 +169,7 @@ class BasisReader { * * @return The temporal basis vectors for the requested time. */ - Matrix* + std::unique_ptr getTemporalBasis( double ef); @@ -178,7 +179,7 @@ class BasisReader { * * @return The temporal basis vectors for the requested time. */ - Vector* + std::unique_ptr getSingularValues(); /** @@ -192,7 +193,7 @@ class BasisReader { * * @return The temporal basis vectors for the requested time. */ - Vector* + std::unique_ptr getSingularValues( double ef); @@ -227,7 +228,7 @@ class BasisReader { * * @return The snapshot matrix for the requested time. */ - Matrix* + std::unique_ptr getSnapshotMatrix(); /** @@ -240,7 +241,7 @@ class BasisReader { * * @return The snapshot matrix for the requested time. */ - Matrix* + std::unique_ptr getSnapshotMatrix( int n); @@ -256,7 +257,7 @@ class BasisReader { * * @return The snapshot matrix for the requested time. */ - Matrix* + std::unique_ptr getSnapshotMatrix( int start_col, int end_col); diff --git a/lib/linalg/BasisWriter.cpp b/lib/linalg/BasisWriter.cpp index 1257006b8..5d28246f7 100644 --- a/lib/linalg/BasisWriter.cpp +++ b/lib/linalg/BasisWriter.cpp @@ -80,7 +80,7 @@ BasisWriter::writeBasis(const std::string& kind) if (kind == "basis") { d_database->create(full_file_name, MPI_COMM_WORLD); - const Matrix* basis = d_basis_generator->getSpatialBasis(); + std::shared_ptr basis = d_basis_generator->getSpatialBasis(); /* spatial basis is always distributed */ CAROM_VERIFY(basis->distributed()); int num_rows = basis->numRows(); @@ -95,8 +95,8 @@ BasisWriter::writeBasis(const std::string& kind) sprintf(tmp, "spatial_basis"); d_database->putDoubleArray(tmp, &basis->item(0, 0), num_rows*num_cols, true); - if(d_basis_generator->updateRightSV()) { - const Matrix* tbasis = d_basis_generator->getTemporalBasis(); + if (d_basis_generator->updateRightSV()) { + std::shared_ptr tbasis = d_basis_generator->getTemporalBasis(); /* temporal basis is always not distributed */ CAROM_VERIFY(!tbasis->distributed()); num_rows = tbasis->numRows(); @@ -109,7 +109,7 @@ BasisWriter::writeBasis(const std::string& kind) d_database->putDoubleArray(tmp, &tbasis->item(0, 0), num_rows*num_cols); } - const Vector* sv = d_basis_generator->getSingularValues(); + std::shared_ptr sv = d_basis_generator->getSingularValues(); /* singular values are always not distributed */ CAROM_VERIFY(!sv->distributed()); int sv_dim = sv->dim(); @@ -124,7 +124,8 @@ BasisWriter::writeBasis(const std::string& kind) if (kind == "snapshot") { d_snap_database->create(snap_file_name, MPI_COMM_WORLD); - const Matrix* snapshots = d_basis_generator->getSnapshotMatrix(); + std::shared_ptr snapshots = + d_basis_generator->getSnapshotMatrix(); /* snapshot matrix is always distributed */ CAROM_VERIFY(snapshots->distributed()); int num_rows = snapshots->numRows(); // d_dim @@ -142,7 +143,6 @@ BasisWriter::writeBasis(const std::string& kind) d_snap_database->close(); } - } } diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index 9d07fe6eb..fdccabc83 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -116,7 +116,7 @@ IncrementalSVD::IncrementalSVD( // Read d_S. int num_dim; d_state_database->getInteger("S_num_dim", num_dim); - d_S = new Vector(num_dim, false); + d_S.reset(new Vector(num_dim, false)); d_state_database->getDoubleArray("S", &d_S->item(0), num_dim); @@ -194,7 +194,7 @@ IncrementalSVD::takeSample( } if (d_debug_algorithm) { - const Matrix* basis = getSpatialBasis(); + std::shared_ptr basis = getSpatialBasis(); if (d_rank == 0) { // Print d_S. for (int col = 0; col < d_num_samples; ++col) { @@ -248,28 +248,28 @@ IncrementalSVD::takeSample( return result; } -const Matrix* +std::shared_ptr IncrementalSVD::getSpatialBasis() { CAROM_ASSERT(d_basis != 0); - return d_basis.get(); + return d_basis; } -const Matrix* +std::shared_ptr IncrementalSVD::getTemporalBasis() { CAROM_ASSERT(d_basis != 0); - return d_basis_right.get(); + return d_basis_right; } -const Vector* +std::shared_ptr IncrementalSVD::getSingularValues() { CAROM_ASSERT(d_S != 0); return d_S; } -const Matrix* +std::shared_ptr IncrementalSVD::getSnapshotMatrix() { std::cout << "Getting snapshot matrix for incremental SVD not implemented" << diff --git a/lib/linalg/svd/IncrementalSVD.h b/lib/linalg/svd/IncrementalSVD.h index ca770a926..a37f5f03c 100644 --- a/lib/linalg/svd/IncrementalSVD.h +++ b/lib/linalg/svd/IncrementalSVD.h @@ -70,9 +70,8 @@ class IncrementalSVD : public SVD * * @return The basis vectors for the current time interval. */ - virtual - const Matrix* - getSpatialBasis(); + std::shared_ptr + getSpatialBasis() override; /** * @brief Returns the temporal basis vectors for the current time interval @@ -80,27 +79,24 @@ class IncrementalSVD : public SVD * * @return The temporal basis vectors for the current time interval. */ - virtual - const Matrix* - getTemporalBasis(); + std::shared_ptr + getTemporalBasis() override; /** * @brief Returns the singular values for the current time interval. * * @return The singular values for the current time interval. */ - virtual - const Vector* - getSingularValues(); + std::shared_ptr + getSingularValues() override; /** * @brief Returns the snapshot matrix for the current time interval. * * @return The snapshot matrix for the current time interval. */ - virtual - const Matrix* - getSnapshotMatrix(); + std::shared_ptr + getSnapshotMatrix() override; protected: /** diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index ada56b14e..511285014 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -80,22 +80,22 @@ IncrementalSVDBrand::~IncrementalSVDBrand() } } -const Matrix* +std::shared_ptr IncrementalSVDBrand::getSpatialBasis() { updateSpatialBasis(); // WARNING: this is costly - CAROM_ASSERT(d_basis != 0); - return d_basis.get(); + CAROM_ASSERT(d_basis != nullptr); + return d_basis; } -const Matrix* +std::shared_ptr IncrementalSVDBrand::getTemporalBasis() { updateTemporalBasis(); CAROM_ASSERT(d_basis_right != 0); - return d_basis_right.get(); + return d_basis_right; } void @@ -105,7 +105,7 @@ IncrementalSVDBrand::buildInitialSVD( CAROM_VERIFY(u != 0); // Build d_S for this new time interval. - d_S = new Vector(1, false); + d_S.reset(new Vector(1, false)); Vector u_vec(u, d_dim, true); double norm_u = u_vec.norm(); d_S->item(0) = norm_u; @@ -456,9 +456,8 @@ IncrementalSVDBrand::addNewSample( d_Up.reset(new_d_Up); // d_S = sigma. - delete d_S; int num_dim = std::min(sigma->numRows(), sigma->numColumns()); - d_S = new Vector(num_dim, false); + d_S.reset(new Vector(num_dim, false)); for (int i = 0; i < num_dim; i++) { d_S->item(i) = sigma->item(i,i); } diff --git a/lib/linalg/svd/IncrementalSVDBrand.h b/lib/linalg/svd/IncrementalSVDBrand.h index db1b18ec7..4e7d374cf 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.h +++ b/lib/linalg/svd/IncrementalSVDBrand.h @@ -38,7 +38,7 @@ class IncrementalSVDBrand : public IncrementalSVD * * @return The basis vectors for the current time interval. */ - const Matrix* + std::shared_ptr getSpatialBasis() override; /** @@ -47,7 +47,7 @@ class IncrementalSVDBrand : public IncrementalSVD * * @return The temporal basis vectors for the current time interval. */ - const Matrix* + std::shared_ptr getTemporalBasis() override; private: @@ -95,10 +95,9 @@ class IncrementalSVDBrand : public IncrementalSVD * @param[in] u The first state. * @param[in] time The simulation time for the first state. */ - virtual void buildInitialSVD( - double* u); + double* u) override; /** * @brief Adds the new sampled the state vector, u, to the system. @@ -129,9 +128,8 @@ class IncrementalSVDBrand : public IncrementalSVD /** * @brief Computes the current basis vectors. */ - virtual void - computeBasis(); + computeBasis() override; /** * @brief Add a linearly dependent sample to the SVD. diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp index e46178577..4bac72750 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp @@ -87,7 +87,7 @@ IncrementalSVDFastUpdate::buildInitialSVD( CAROM_VERIFY(u != 0); // Build d_S for this new time interval. - d_S = new Vector(1, false); + d_S.reset(new Vector(1, false)); Vector u_vec(u, d_dim, true); double norm_u = u_vec.norm(); d_S->item(0) = norm_u; @@ -300,9 +300,8 @@ IncrementalSVDFastUpdate::addNewSample( d_Up.reset(new_d_Up); // d_S = sigma. - delete d_S; int num_dim = std::min(sigma->numRows(), sigma->numColumns()); - d_S = new Vector(num_dim, false); + d_S.reset(new Vector(num_dim, false)); for (int i = 0; i < num_dim; i++) { d_S->item(i) = sigma->item(i,i); } diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.h b/lib/linalg/svd/IncrementalSVDFastUpdate.h index a7d336b0f..90e53bfd3 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.h +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.h @@ -77,17 +77,15 @@ class IncrementalSVDFastUpdate : public IncrementalSVD * @param[in] u The first state. * @param[in] time The simulation time for the first state. */ - virtual void buildInitialSVD( - double* u); + double* u) override; /** * @brief Computes the current basis vectors. */ - virtual void - computeBasis(); + computeBasis() override; /** * @brief Add a linearly dependent sample to the SVD. diff --git a/lib/linalg/svd/IncrementalSVDStandard.cpp b/lib/linalg/svd/IncrementalSVDStandard.cpp index c01209697..82f125085 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.cpp +++ b/lib/linalg/svd/IncrementalSVDStandard.cpp @@ -66,7 +66,7 @@ IncrementalSVDStandard::buildInitialSVD( CAROM_VERIFY(u != 0); // Build d_S for this new time interval. - d_S = new Vector(1, false); + d_S.reset(new Vector(1, false)); Vector u_vec(u, d_dim, true); double norm_u = u_vec.norm(); d_S->item(0) = norm_u; @@ -200,9 +200,8 @@ IncrementalSVDStandard::addNewSample( d_W = new_d_W; } - delete d_S; int num_dim = std::min(sigma->numRows(), sigma->numColumns()); - d_S = new Vector(num_dim, false); + d_S.reset(new Vector(num_dim, false)); for (int i = 0; i < num_dim; i++) { d_S->item(i) = sigma->item(i,i); } diff --git a/lib/linalg/svd/IncrementalSVDStandard.h b/lib/linalg/svd/IncrementalSVDStandard.h index ac10b1ee9..e9cfef4fd 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.h +++ b/lib/linalg/svd/IncrementalSVDStandard.h @@ -76,17 +76,15 @@ class IncrementalSVDStandard : public IncrementalSVD * @param[in] u The first state. * @param[in] time The simulation time for the first state. */ - virtual void buildInitialSVD( - double* u); + double* u) override; /** * @brief Computes the current basis vectors. */ - virtual void - computeBasis(); + computeBasis() override; /** * @brief Add a linearly dependent sample to the SVD. diff --git a/lib/linalg/svd/RandomizedSVD.cpp b/lib/linalg/svd/RandomizedSVD.cpp index e541d3a69..f8420d86c 100644 --- a/lib/linalg/svd/RandomizedSVD.cpp +++ b/lib/linalg/svd/RandomizedSVD.cpp @@ -147,7 +147,7 @@ RandomizedSVD::computeSVD() ncolumns = std::min(ncolumns, d_subspace_dim); // Allocate the appropriate matrices and gather their elements. - d_S = new Vector(ncolumns, false); + d_S.reset(new Vector(ncolumns, false)); { CAROM_VERIFY(ncolumns >= 0); unsigned nc = static_cast(ncolumns); diff --git a/lib/linalg/svd/SVD.cpp b/lib/linalg/svd/SVD.cpp index c67110ee4..514063867 100644 --- a/lib/linalg/svd/SVD.cpp +++ b/lib/linalg/svd/SVD.cpp @@ -31,9 +31,7 @@ SVD::SVD( SVD::~SVD() { - delete d_S; delete d_W; - delete d_snapshots; } } diff --git a/lib/linalg/svd/SVD.h b/lib/linalg/svd/SVD.h index f63ec5eca..3153bc514 100644 --- a/lib/linalg/svd/SVD.h +++ b/lib/linalg/svd/SVD.h @@ -77,7 +77,7 @@ class SVD * @return The basis vectors for the current time interval. */ virtual - const Matrix* + std::shared_ptr getSpatialBasis() = 0; /** @@ -86,7 +86,7 @@ class SVD * @return The temporal basis vectors for the current time interval. */ virtual - const Matrix* + std::shared_ptr getTemporalBasis() = 0; /** @@ -95,7 +95,7 @@ class SVD * @return The singular values for the current time interval. */ virtual - const Vector* + std::shared_ptr getSingularValues() = 0; /** @@ -104,7 +104,7 @@ class SVD * @return The singular values for the current time interval. */ virtual - const Matrix* + std::shared_ptr getSnapshotMatrix() = 0; /** @@ -166,7 +166,7 @@ class SVD * The basis vectors are large and each process owns all of the basis * vectors. */ - std::unique_ptr d_basis; + std::shared_ptr d_basis; /** * @brief The globalized right basis vectors for the current time interval. @@ -174,7 +174,7 @@ class SVD * Depending on the SVD algorithm, it may be distributed across all * processors or each processor may own all of U. */ - std::unique_ptr d_basis_right; + std::shared_ptr d_basis_right; /** * @brief The matrix U which is large. @@ -182,7 +182,7 @@ class SVD * Depending on the SVD algorithm, d_U may be distributed across all * processors or each processor may own all of U. */ - std::unique_ptr d_U; + std::shared_ptr d_U; /** * @brief The matrix U which is large. @@ -198,7 +198,7 @@ class SVD * For all SVD algorithms, S is not distributed and the entire vector * exists on each processor. */ - Vector* d_S; + std::shared_ptr d_S; /** * @brief The globalized snapshot vectors for the current time interval. @@ -206,7 +206,7 @@ class SVD * The snapshot vectors are large and each process owns all of the snapshot * vectors. */ - Matrix* d_snapshots; + std::shared_ptr d_snapshots; /** * @brief Flag to indicate if results of algorithm should be printed for diff --git a/lib/linalg/svd/StaticSVD.cpp b/lib/linalg/svd/StaticSVD.cpp index c0f04b848..b0a370195 100644 --- a/lib/linalg/svd/StaticSVD.cpp +++ b/lib/linalg/svd/StaticSVD.cpp @@ -137,7 +137,7 @@ StaticSVD::takeSample( return true; } -const Matrix* +std::shared_ptr StaticSVD::getSpatialBasis() { // If this basis is for the last time interval then it may not be up to date @@ -149,10 +149,10 @@ StaticSVD::getSpatialBasis() CAROM_ASSERT(d_basis != 0); } CAROM_ASSERT(isBasisCurrent()); - return d_basis.get(); + return d_basis; } -const Matrix* +std::shared_ptr StaticSVD::getTemporalBasis() { // If this basis is for the last time interval then it may not be up to date @@ -164,16 +164,15 @@ StaticSVD::getTemporalBasis() CAROM_ASSERT(d_basis_right != 0); } CAROM_ASSERT(isBasisCurrent()); - return d_basis_right.get(); + return d_basis_right; } -const Vector* +std::shared_ptr StaticSVD::getSingularValues() { // If these singular values are for the last time interval then they may not // be up to date so recompute them. if (!isBasisCurrent()) { - delete d_S; d_S = nullptr; delete d_W; d_W = nullptr; @@ -186,15 +185,14 @@ StaticSVD::getSingularValues() return d_S; } -const Matrix* +std::shared_ptr StaticSVD::getSnapshotMatrix() { if ((!d_preserve_snapshot) && (isBasisCurrent()) && (d_basis != 0)) CAROM_ERROR("StaticSVD: snapshot matrix is modified after computeSVD." " To preserve the snapshots, set Options::static_svd_preserve_snapshot to be true!\n"); - if (d_snapshots) delete d_snapshots; - d_snapshots = new Matrix(d_dim, d_num_samples, true); + d_snapshots.reset(new Matrix(d_dim, d_num_samples, true)); for (int rank = 0; rank < d_num_procs; ++rank) { int nrows = d_dims[static_cast(rank)]; @@ -281,7 +279,7 @@ StaticSVD::computeSVD() CAROM_VERIFY(ncolumns >= 0); // Allocate the appropriate matrices and gather their elements. - d_S = new Vector(ncolumns, false); + d_S.reset(new Vector(ncolumns, false)); { CAROM_VERIFY(ncolumns >= 0); unsigned nc = static_cast(ncolumns); diff --git a/lib/linalg/svd/StaticSVD.h b/lib/linalg/svd/StaticSVD.h index 9dd331a30..ebdab51fb 100644 --- a/lib/linalg/svd/StaticSVD.h +++ b/lib/linalg/svd/StaticSVD.h @@ -61,9 +61,8 @@ class StaticSVD : public SVD * * @return The basis vectors for the current time interval. */ - virtual - const Matrix* - getSpatialBasis(); + std::shared_ptr + getSpatialBasis() override; /** * @brief Returns the temporal basis vectors for the current time interval as @@ -73,9 +72,8 @@ class StaticSVD : public SVD * * @return The temporal basis vectors for the current time interval. */ - virtual - const Matrix* - getTemporalBasis(); + std::shared_ptr + getTemporalBasis() override; /** * @brief Returns the singular values for the current time interval. @@ -84,18 +82,16 @@ class StaticSVD : public SVD * * @return The singular values for the current time interval. */ - virtual - const Vector* - getSingularValues(); + std::shared_ptr + getSingularValues() override; /** * @brief Returns the snapshot matrix for the current time interval. * * @return The snapshot matrix for the current time interval. */ - virtual - const Matrix* - getSnapshotMatrix(); + std::shared_ptr + getSnapshotMatrix() override; protected: diff --git a/regression_tests/basisComparator.cpp b/regression_tests/basisComparator.cpp old mode 100755 new mode 100644 index 9ae74a840..2b79cebad --- a/regression_tests/basisComparator.cpp +++ b/regression_tests/basisComparator.cpp @@ -36,14 +36,15 @@ void compareBasis(string &baselineFile, string &targetFile, double errorBound, vector reducedDiffVecNormL2; CAROM::BasisReader baselineReader(baselineFile); - CAROM::Matrix *baselineBasis = - (CAROM::Matrix*) baselineReader.getSpatialBasis(); - CAROM::Vector *baselineSV = - (CAROM::Vector*) baselineReader.getSingularValues(); + std::unique_ptr baselineBasis = + baselineReader.getSpatialBasis(); + std::unique_ptr baselineSV = + baselineReader.getSingularValues(); CAROM::BasisReader targetReader(targetFile); - CAROM::Matrix *targetBasis = (CAROM::Matrix*) targetReader.getSpatialBasis(); + std::unique_ptr targetBasis = + targetReader.getSpatialBasis(); CAROM::BasisReader diffReader(baselineFile); - CAROM::Matrix *diffBasis = (CAROM::Matrix*) diffReader.getSpatialBasis(); + CAROM::Matrix* diffBasis = diffReader.getSpatialBasis().get(); // Get basis dimensions int baselineNumRows = baselineBasis->numRows(); diff --git a/unit_tests/random_test.cpp b/unit_tests/random_test.cpp index 3d03bdcb0..187b020aa 100644 --- a/unit_tests/random_test.cpp +++ b/unit_tests/random_test.cpp @@ -210,15 +210,17 @@ main( static_basis_generator.endSamples(); // Get the basis vectors from the 2 different algorithms. - const CAROM::Matrix* inc_basis = inc_basis_generator.getSpatialBasis(); - const CAROM::Matrix* static_basis = static_basis_generator.getSpatialBasis(); + std::shared_ptr inc_basis = + inc_basis_generator.getSpatialBasis(); + std::shared_ptr static_basis = + static_basis_generator.getSpatialBasis(); // Compute the product of the transpose of the static basis and the - // incremental basis. This should be a unitary matrix. + // incremental basis. This should be a unitary matrix. // We use a special version of transposeMult as the static basis is not - // distributed. In the context of this test routine we "know" how the + // distributed. In the context of this test routine we "know" how the // incremental basis is distributed so we can do the multiplication. - CAROM::Matrix* test = transposeMult(static_basis, inc_basis); + CAROM::Matrix *test = transposeMult(static_basis.get(), inc_basis.get()); if (rank == 0) { for (int row = 0; row < test->numRows(); ++row) { for (int col = 0; col < test->numColumns(); ++col) { @@ -227,7 +229,6 @@ main( printf("\n"); } } - delete test; } // Clean up. diff --git a/unit_tests/test_HDFDatabase.cpp b/unit_tests/test_HDFDatabase.cpp index 68fc5222b..587681370 100644 --- a/unit_tests/test_HDFDatabase.cpp +++ b/unit_tests/test_HDFDatabase.cpp @@ -587,13 +587,14 @@ TEST(BasisGeneratorIO, HDFDatabase) } sampler.writeSnapshot(); - const CAROM::Matrix *snapshot = sampler.getSnapshotMatrix(); + std::shared_ptr snapshot = sampler.getSnapshotMatrix(); sampler.endSamples(); - const CAROM::Matrix *spatial_basis = sampler.getSpatialBasis(); + std::shared_ptr spatial_basis = sampler.getSpatialBasis(); CAROM::BasisReader basis_reader("test_basis"); - const CAROM::Matrix *spatial_basis1 = basis_reader.getSpatialBasis(); + std::unique_ptr spatial_basis1 = + basis_reader.getSpatialBasis(); EXPECT_EQ(spatial_basis->numRows(), spatial_basis1->numRows()); EXPECT_EQ(spatial_basis->numColumns(), spatial_basis1->numColumns()); @@ -602,7 +603,8 @@ TEST(BasisGeneratorIO, HDFDatabase) EXPECT_NEAR((*spatial_basis)(i, j), (*spatial_basis1)(i, j), threshold); CAROM::BasisReader snapshot_reader("test_basis_snapshot"); - const CAROM::Matrix *snapshot1 = snapshot_reader.getSnapshotMatrix(); + std::unique_ptr snapshot1 = + snapshot_reader.getSnapshotMatrix(); EXPECT_EQ(snapshot->numRows(), snapshot1->numRows()); EXPECT_EQ(snapshot->numColumns(), snapshot1->numColumns()); @@ -641,10 +643,11 @@ TEST(BasisGeneratorIO, Base_MPIO_combination) sampler.loadSamples(base_name + "_snapshot", "snapshot", 1e9, CAROM::Database::formats::HDF5); sampler.writeSnapshot(); - const CAROM::Matrix *snapshot = sampler.getSnapshotMatrix(); + std::shared_ptr snapshot = sampler.getSnapshotMatrix(); CAROM::BasisReader snapshot_reader("test_basis_snapshot"); - const CAROM::Matrix *snapshot1 = snapshot_reader.getSnapshotMatrix(); + std::unique_ptr snapshot1 = + snapshot_reader.getSnapshotMatrix(); EXPECT_EQ(snapshot->numRows(), snapshot1->numRows()); EXPECT_EQ(snapshot->numColumns(), snapshot1->numColumns()); @@ -653,10 +656,11 @@ TEST(BasisGeneratorIO, Base_MPIO_combination) EXPECT_NEAR((*snapshot)(i, j), (*snapshot1)(i, j), threshold); sampler.endSamples(); - const CAROM::Matrix *spatial_basis = sampler.getSpatialBasis(); + std::shared_ptr spatial_basis = sampler.getSpatialBasis(); CAROM::BasisReader basis_reader("test_basis"); - const CAROM::Matrix *spatial_basis1 = basis_reader.getSpatialBasis(); + std::shared_ptr spatial_basis1 = + basis_reader.getSpatialBasis(); EXPECT_EQ(spatial_basis->numRows(), spatial_basis1->numRows()); EXPECT_EQ(spatial_basis->numColumns(), spatial_basis1->numColumns()); @@ -694,10 +698,11 @@ TEST(BasisGeneratorIO, MPIO_Base_combination) sampler.loadSamples(mpio_name + "_snapshot", "snapshot", 1e9, CAROM::Database::formats::HDF5_MPIO); - const CAROM::Matrix *snapshot = sampler.getSnapshotMatrix(); + std::shared_ptr snapshot = sampler.getSnapshotMatrix(); CAROM::BasisReader snapshot_reader("test_basis_snapshot"); - const CAROM::Matrix *snapshot1 = snapshot_reader.getSnapshotMatrix(); + std::unique_ptr snapshot1 = + snapshot_reader.getSnapshotMatrix(); EXPECT_EQ(snapshot->numRows(), snapshot1->numRows()); EXPECT_EQ(snapshot->numColumns(), snapshot1->numColumns()); @@ -706,10 +711,11 @@ TEST(BasisGeneratorIO, MPIO_Base_combination) EXPECT_NEAR((*snapshot)(i, j), (*snapshot1)(i, j), threshold); sampler.endSamples(); - const CAROM::Matrix *spatial_basis = sampler.getSpatialBasis(); + std::shared_ptr spatial_basis = sampler.getSpatialBasis(); CAROM::BasisReader basis_reader("test_basis"); - const CAROM::Matrix *spatial_basis1 = basis_reader.getSpatialBasis(); + std::unique_ptr spatial_basis1 = + basis_reader.getSpatialBasis(); EXPECT_EQ(spatial_basis->numRows(), spatial_basis1->numRows()); EXPECT_EQ(spatial_basis->numColumns(), spatial_basis1->numColumns()); @@ -740,12 +746,14 @@ TEST(BasisReaderIO, partial_getSpatialBasis) std::string mpio_name = "test_mpio"; CAROM::BasisReader basis_reader("test_basis"); - const CAROM::Matrix *spatial_basis = basis_reader.getSpatialBasis(); + std::unique_ptr spatial_basis = + basis_reader.getSpatialBasis(); CAROM::BasisReader basis_reader1("test_mpio", CAROM::Database::formats::HDF5_MPIO, nrow_local); - const CAROM::Matrix *spatial_basis1 = basis_reader1.getSpatialBasis(); + std::unique_ptr spatial_basis1 = + basis_reader1.getSpatialBasis(); EXPECT_EQ(spatial_basis->numRows(), spatial_basis1->numRows()); EXPECT_EQ(spatial_basis->numColumns(), spatial_basis1->numColumns()); @@ -753,8 +761,6 @@ TEST(BasisReaderIO, partial_getSpatialBasis) for (int j = 0; j < spatial_basis->numColumns(); j++) EXPECT_NEAR((*spatial_basis)(i, j), (*spatial_basis1)(i, j), threshold); - delete spatial_basis; - delete spatial_basis1; const int col1 = 3, col2 = 7; spatial_basis = basis_reader.getSpatialBasis(col1, col2); spatial_basis1 = basis_reader1.getSpatialBasis(col1, col2); @@ -764,9 +770,6 @@ TEST(BasisReaderIO, partial_getSpatialBasis) for (int i = 0; i < spatial_basis->numRows(); i++) for (int j = 0; j < spatial_basis->numColumns(); j++) EXPECT_NEAR((*spatial_basis)(i, j), (*spatial_basis1)(i, j), threshold); - - delete spatial_basis; - delete spatial_basis1; } TEST(BasisGeneratorIO, Scaling_test) diff --git a/unit_tests/test_IncrementalSVD.cpp b/unit_tests/test_IncrementalSVD.cpp index 5368b6f36..3c8214d99 100644 --- a/unit_tests/test_IncrementalSVD.cpp +++ b/unit_tests/test_IncrementalSVD.cpp @@ -50,7 +50,7 @@ class FakeIncrementalSVD : public CAROM::IncrementalSVD /* Construct a fake d_U, d_S, d_basis */ d_basis.reset(new CAROM::Matrix(dim, dim, false)); - d_S = new CAROM::Vector(dim, false); + d_S.reset(new CAROM::Vector(dim, false)); /* Use the identity matrix as a fake basis and fake singular values */ for (int i = 0; i < dim; i++) @@ -108,7 +108,7 @@ TEST(IncrementalSVDSerialTest, Test_getBasis) incremental_svd_options, "irrelevant.txt"); - const CAROM::Matrix *B = svd.getSpatialBasis(); + std::shared_ptr B = svd.getSpatialBasis(); for (int i = 0; i < svd.getDim(); i++) { for (int j = 0; j < i; j++) @@ -130,7 +130,7 @@ TEST(IncrementalSVDSerialTest, Test_getSingularValues) incremental_svd_options, "irrelevant.txt"); - const CAROM::Vector *S = svd.getSingularValues(); + std::shared_ptr S = svd.getSingularValues(); for (int i = 0; i < svd.getDim(); i++) { EXPECT_DOUBLE_EQ(S->item(i), 1); diff --git a/unit_tests/test_IncrementalSVDBrand.cpp b/unit_tests/test_IncrementalSVDBrand.cpp index 5e1402a63..bb41bd8fe 100644 --- a/unit_tests/test_IncrementalSVDBrand.cpp +++ b/unit_tests/test_IncrementalSVDBrand.cpp @@ -100,9 +100,9 @@ TEST(IncrementalSVDBrandTest, Test_IncrementalSVDBrand) sampler.takeSample(&sample2[row_offset[d_rank]]); sampler.takeSample(&sample3[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); EXPECT_EQ(d_basis->numRows(), d_num_rows); EXPECT_EQ(d_basis->numColumns(), 3); diff --git a/unit_tests/test_RandomizedSVD.cpp b/unit_tests/test_RandomizedSVD.cpp index 1679392f0..e920b873f 100644 --- a/unit_tests/test_RandomizedSVD.cpp +++ b/unit_tests/test_RandomizedSVD.cpp @@ -78,9 +78,9 @@ TEST(RandomizedSVDTest, Test_RandomizedSVD) sampler.takeSample(&sample2[row_offset[d_rank]]); sampler.takeSample(&sample3[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); EXPECT_EQ(d_basis->numRows(), d_num_rows); EXPECT_EQ(d_basis->numColumns(), 3); @@ -160,9 +160,9 @@ TEST(RandomizedSVDTest, Test_RandomizedSVDTransposed) sampler.takeSample(&sample4[row_offset[d_rank]]); sampler.takeSample(&sample5[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); EXPECT_EQ(d_basis_right->numRows(), num_samples); EXPECT_EQ(d_basis_right->numColumns(), 3); @@ -236,9 +236,9 @@ TEST(RandomizedSVDTest, Test_RandomizedSVDSmallerSubspace) sampler.takeSample(&sample2[row_offset[d_rank]]); sampler.takeSample(&sample3[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); EXPECT_EQ(d_basis->numRows(), d_num_rows); EXPECT_EQ(d_basis->numColumns(), 2); @@ -317,9 +317,9 @@ TEST(RandomizedSVDTest, Test_RandomizedSVDTransposedSmallerSubspace) sampler.takeSample(&sample4[row_offset[d_rank]]); sampler.takeSample(&sample5[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); d_num_rows = CAROM::split_dimension(reduced_rows, MPI_COMM_WORLD); int reduced_rows_check = CAROM::get_global_offsets(d_num_rows, row_offset, diff --git a/unit_tests/test_StaticSVD.cpp b/unit_tests/test_StaticSVD.cpp index 63a599198..906c5b260 100644 --- a/unit_tests/test_StaticSVD.cpp +++ b/unit_tests/test_StaticSVD.cpp @@ -294,9 +294,9 @@ TEST(StaticSVDTest, Test_StaticSVDClass) sampler.takeSample(&sample2[row_offset[d_rank]]); sampler.takeSample(&sample3[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); EXPECT_EQ(d_basis->numRows(), d_num_rows); EXPECT_EQ(d_basis->numColumns(), 3); @@ -376,9 +376,9 @@ TEST(StaticSVDTest, Test_StaticSVDTranspose) sampler.takeSample(&sample4[row_offset[d_rank]]); sampler.takeSample(&sample5[row_offset[d_rank]]); - const CAROM::Matrix* d_basis = sampler.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = sampler.getTemporalBasis(); - const CAROM::Vector* sv = sampler.getSingularValues(); + std::shared_ptr d_basis = sampler.getSpatialBasis(); + std::shared_ptr d_basis_right = sampler.getTemporalBasis(); + std::shared_ptr sv = sampler.getSingularValues(); EXPECT_EQ(d_basis_right->numRows(), num_total_cols); EXPECT_EQ(d_basis_right->numColumns(), 3); diff --git a/unit_tests/test_basis_conversion.cpp b/unit_tests/test_basis_conversion.cpp index 2a4285398..d71c1cd5e 100644 --- a/unit_tests/test_basis_conversion.cpp +++ b/unit_tests/test_basis_conversion.cpp @@ -75,10 +75,10 @@ TEST(StaticSVDTest, Test_StaticSVDClass) CAROM::BasisReader basis("test_basis"); CAROM::BasisReader snapshot("test_basis_snapshot"); - const CAROM::Matrix* d_snapshot = snapshot.getSnapshotMatrix(); - const CAROM::Matrix* d_basis = basis.getSpatialBasis(); - const CAROM::Matrix* d_basis_right = basis.getTemporalBasis(); - const CAROM::Vector* sv = basis.getSingularValues(); + std::unique_ptr d_snapshot = snapshot.getSnapshotMatrix(); + std::unique_ptr d_basis = basis.getSpatialBasis(); + std::unique_ptr d_basis_right = basis.getTemporalBasis(); + std::unique_ptr sv = basis.getSingularValues(); EXPECT_EQ(d_basis->numRows(), d_num_rows); EXPECT_EQ(d_basis->numColumns(), 3); @@ -121,4 +121,4 @@ int main() << "libROM with Google Test support." << std::endl; } -#endif // #endif CAROM_HAS_GTEST \ No newline at end of file +#endif // #endif CAROM_HAS_GTEST From 93e53c1d6ef1cb4f041792a4ec4e709d6d7c74da Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Tue, 20 Aug 2024 19:39:49 -0700 Subject: [PATCH 08/19] Eliminated more raw pointers in DMD classes. Added more const correctness. --- examples/dmd/de_dg_advection_greedy.cpp | 36 +++--- .../de_parametric_heat_conduction_greedy.cpp | 47 ++++---- examples/dmd/local_dw_csv.cpp | 3 +- examples/dmd/local_tw_csv.cpp | 3 +- .../dmd/parametric_dmdc_heat_conduction.cpp | 30 ++--- examples/dmd/parametric_dw_csv.cpp | 27 ++--- examples/dmd/parametric_heat_conduction.cpp | 23 ++-- examples/dmd/parametric_tw_csv.cpp | 11 +- .../dg_advection_local_rom_matrix_interp.cpp | 12 +- lib/algo/AdaptiveDMD.cpp | 50 ++++---- lib/algo/AdaptiveDMD.h | 2 +- lib/algo/DMD.cpp | 68 +++++------ lib/algo/DMD.h | 16 +-- lib/algo/DMDc.cpp | 110 ++++++++---------- lib/algo/DMDc.h | 36 +++--- lib/algo/NonuniformDMD.cpp | 22 ++-- lib/algo/NonuniformDMD.h | 2 +- lib/algo/ParametricDMD.h | 13 +-- lib/algo/ParametricDMDc.h | 10 +- lib/algo/SnapshotDMD.cpp | 17 +-- lib/algo/manifold_interp/Interpolator.cpp | 67 ++++++----- lib/algo/manifold_interp/Interpolator.h | 26 +++-- .../manifold_interp/MatrixInterpolator.cpp | 17 +-- lib/algo/manifold_interp/MatrixInterpolator.h | 15 +-- .../manifold_interp/PCHIPInterpolator.cpp | 41 ++++--- lib/algo/manifold_interp/PCHIPInterpolator.h | 8 +- .../manifold_interp/VectorInterpolator.cpp | 30 ++--- lib/algo/manifold_interp/VectorInterpolator.h | 17 ++- lib/linalg/Vector.cpp | 20 ++-- lib/linalg/Vector.h | 12 +- unit_tests/test_HDFDatabase.cpp | 8 +- unit_tests/test_PCHIPInterpolator.cpp | 4 +- 32 files changed, 392 insertions(+), 411 deletions(-) diff --git a/examples/dmd/de_dg_advection_greedy.cpp b/examples/dmd/de_dg_advection_greedy.cpp index 0f57b95bf..677720fc8 100644 --- a/examples/dmd/de_dg_advection_greedy.cpp +++ b/examples/dmd/de_dg_advection_greedy.cpp @@ -597,7 +597,7 @@ double simulation() std::fstream fin(io_dir + "/parameters.txt", std::ios_base::in); double curr_param; std::vector dmd_paths; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { @@ -605,14 +605,14 @@ double simulation() // INPUT / OUTPUT potential issue dmd_paths.push_back(io_dir + "/" + to_string(curr_f_factor)); - CAROM::Vector* param_vector = new CAROM::Vector(1, false); - param_vector->item(0) = curr_f_factor; + CAROM::Vector param_vector(1, false); + param_vector(0) = curr_f_factor; param_vectors.push_back(param_vector); } fin.close(); - CAROM::Vector* desired_param = new CAROM::Vector(1, false); - desired_param->item(0) = f_factor; + CAROM::Vector desired_param(1, false); + desired_param(0) = f_factor; dmd_training_timer.Start(); @@ -623,7 +623,6 @@ double simulation() dmd_training_timer.Stop(); - delete desired_param; // Compare the DMD solution to the FOM Solution if (true_solution_u == NULL) @@ -697,29 +696,26 @@ double simulation() std::fstream fin(io_dir+"/parameters.txt", std::ios_base::in); double curr_param; std::vector dmd_paths; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { double curr_f_factor = curr_param; dmd_paths.push_back(io_dir + "/" + to_string(curr_f_factor)); - CAROM::Vector* param_vector = new CAROM::Vector(1, false); - param_vector->item(0) = curr_f_factor; + CAROM::Vector param_vector(1, false); + param_vector(0) = curr_f_factor; param_vectors.push_back(param_vector); } fin.close(); if (dmd_paths.size() > 1) { - - CAROM::Vector* desired_param = new CAROM::Vector(1, false); - desired_param->item(0) = f_factor; + CAROM::Vector desired_param(1, false); + desired_param(0) = f_factor; dmd_training_timer.Start(); CAROM::getParametricDMD(dmd_U, param_vectors, dmd_paths, desired_param, "G", "LS", closest_rbf_val); - - delete desired_param; } else { @@ -854,21 +850,21 @@ double simulation() std::fstream fin(io_dir+"/parameters.txt", std::ios_base::in); double curr_param; std::vector dmd_paths; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { double curr_f_factor = curr_param; dmd_paths.push_back(io_dir + "/" + to_string(curr_f_factor)); - CAROM::Vector* param_vector = new CAROM::Vector(1, false); - param_vector->item(0) = curr_f_factor; + CAROM::Vector param_vector(1, false); + param_vector(0) = curr_f_factor; param_vectors.push_back(param_vector); } fin.close(); - CAROM::Vector* desired_param = new CAROM::Vector(1, false); - desired_param->item(0) = f_factor; + CAROM::Vector desired_param(1, false); + desired_param(0) = f_factor; dmd_training_timer.Start(); @@ -877,9 +873,7 @@ double simulation() dmd_U->projectInitialCondition(init); - dmd_training_timer.Stop(); - delete desired_param; } if (offline || calc_err_indicator) diff --git a/examples/dmd/de_parametric_heat_conduction_greedy.cpp b/examples/dmd/de_parametric_heat_conduction_greedy.cpp index 68db41fad..21dd8ca88 100644 --- a/examples/dmd/de_parametric_heat_conduction_greedy.cpp +++ b/examples/dmd/de_parametric_heat_conduction_greedy.cpp @@ -414,7 +414,7 @@ double simulation() std::fstream fin("parameters.txt", std::ios_base::in); double curr_param; std::vector dmd_paths; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { @@ -429,29 +429,27 @@ double simulation() dmd_paths.push_back(to_string(curr_radius) + "_" + to_string(curr_alpha) + "_" + to_string(curr_cx) + "_" + to_string(curr_cy)); - CAROM::Vector* param_vector = new CAROM::Vector(4, false); - param_vector->item(0) = curr_radius; - param_vector->item(1) = curr_alpha; - param_vector->item(2) = curr_cx; - param_vector->item(3) = curr_cy; + CAROM::Vector param_vector(4, false); + param_vector(0) = curr_radius; + param_vector(1) = curr_alpha; + param_vector(2) = curr_cx; + param_vector(3) = curr_cy; param_vectors.push_back(param_vector); } fin.close(); if (dmd_paths.size() > 1) { - CAROM::Vector* desired_param = new CAROM::Vector(4, false); - desired_param->item(0) = radius; - desired_param->item(1) = alpha; - desired_param->item(2) = cx; - desired_param->item(3) = cy; + CAROM::Vector desired_param(4, false); + desired_param(0) = radius; + desired_param(1) = alpha; + desired_param(2) = cx; + desired_param(3) = cy; dmd_training_timer.Start(); CAROM::getParametricDMD(dmd_u, param_vectors, dmd_paths, desired_param, "G", "LS", closest_rbf_val); - - delete desired_param; } else { @@ -581,7 +579,7 @@ double simulation() std::fstream fin("parameters.txt", std::ios_base::in); double curr_param; std::vector dmd_paths; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { @@ -596,20 +594,20 @@ double simulation() dmd_paths.push_back(to_string(curr_radius) + "_" + to_string(curr_alpha) + "_" + to_string(curr_cx) + "_" + to_string(curr_cy)); - CAROM::Vector* param_vector = new CAROM::Vector(4, false); - param_vector->item(0) = curr_radius; - param_vector->item(1) = curr_alpha; - param_vector->item(2) = curr_cx; - param_vector->item(3) = curr_cy; + CAROM::Vector param_vector(4, false); + param_vector(0) = curr_radius; + param_vector(1) = curr_alpha; + param_vector(2) = curr_cx; + param_vector(3) = curr_cy; param_vectors.push_back(param_vector); } fin.close(); - CAROM::Vector* desired_param = new CAROM::Vector(4, false); - desired_param->item(0) = radius; - desired_param->item(1) = alpha; - desired_param->item(2) = cx; - desired_param->item(3) = cy; + CAROM::Vector desired_param(4, false); + desired_param(0) = radius; + desired_param(1) = alpha; + desired_param(2) = cx; + desired_param(3) = cy; dmd_training_timer.Start(); @@ -619,7 +617,6 @@ double simulation() dmd_u->projectInitialCondition(init); dmd_training_timer.Stop(); - delete desired_param; } if (offline || de || calc_err_indicator) diff --git a/examples/dmd/local_dw_csv.cpp b/examples/dmd/local_dw_csv.cpp index ba9afc30f..807084842 100644 --- a/examples/dmd/local_dw_csv.cpp +++ b/examples/dmd/local_dw_csv.cpp @@ -569,7 +569,8 @@ int main(int argc, char *argv[]) double t_init = dmd[window]->getTimeOffset(); dtc = admd->getTrueDt(); - const CAROM::Matrix* f_snapshots = admd->getInterpolatedSnapshots(); + std::unique_ptr f_snapshots = + admd->getInterpolatedSnapshots(); if (myid == 0) { cout << "Verifying Adaptive DMD model #" << window << diff --git a/examples/dmd/local_tw_csv.cpp b/examples/dmd/local_tw_csv.cpp index c11ed9bb2..c14878fa4 100644 --- a/examples/dmd/local_tw_csv.cpp +++ b/examples/dmd/local_tw_csv.cpp @@ -603,7 +603,8 @@ int main(int argc, char *argv[]) double t_init = dmd[window]->getTimeOffset(); dtc = admd->getTrueDt(); - const CAROM::Matrix* f_snapshots = admd->getInterpolatedSnapshots(); + std::unique_ptr f_snapshots = + admd->getInterpolatedSnapshots(); if (myid == 0) { cout << "Verifying Adaptive DMD model #" << window << diff --git a/examples/dmd/parametric_dmdc_heat_conduction.cpp b/examples/dmd/parametric_dmdc_heat_conduction.cpp index ea53059ca..459ba61fa 100644 --- a/examples/dmd/parametric_dmdc_heat_conduction.cpp +++ b/examples/dmd/parametric_dmdc_heat_conduction.cpp @@ -771,7 +771,7 @@ int main(int argc, char *argv[]) double curr_param; std::vector dmdc_paths; std::vector> controls; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { @@ -792,37 +792,31 @@ int main(int argc, char *argv[]) curr_amp_out) + "_control"); controls.push_back(curr_control); - CAROM::Vector* param_vector = new CAROM::Vector(4, false); - param_vector->item(0) = curr_alpha; - param_vector->item(1) = curr_kappa; - param_vector->item(2) = curr_amp_in; - param_vector->item(3) = curr_amp_out; + CAROM::Vector param_vector(4, false); + param_vector(0) = curr_alpha; + param_vector(1) = curr_kappa; + param_vector(2) = curr_amp_in; + param_vector(3) = curr_amp_out; param_vectors.push_back(param_vector); } fin.close(); - CAROM::Vector* desired_param = new CAROM::Vector(4, false); - desired_param->item(0) = alpha; - desired_param->item(1) = kappa; - desired_param->item(2) = amp_in; - desired_param->item(3) = amp_out; + CAROM::Vector desired_param(4, false); + desired_param(0) = alpha; + desired_param(1) = kappa; + desired_param(2) = amp_in; + desired_param(3) = amp_out; dmd_training_timer.Start(); - std::shared_ptr controls_interpolated(new CAROM::Matrix()); CAROM::getParametricDMDc(dmd_u, param_vectors, dmdc_paths, controls, controls_interpolated, desired_param, "G", "LS", closest_rbf_val); - dmd_u->project(init,controls_interpolated.get()); - + dmd_u->project(*init, *controls_interpolated); dmd_training_timer.Stop(); - - delete desired_param; - for (auto m : param_vectors) - delete m; } if (predict) diff --git a/examples/dmd/parametric_dw_csv.cpp b/examples/dmd/parametric_dw_csv.cpp index 21c993a40..c33982dff 100644 --- a/examples/dmd/parametric_dw_csv.cpp +++ b/examples/dmd/parametric_dw_csv.cpp @@ -54,9 +54,9 @@ using namespace std; using namespace mfem; void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector>& training_twep, - CAROM::Vector* desired_point, + const CAROM::Vector & desired_point, std::string rbf, double closest_rbf_val); @@ -263,7 +263,7 @@ int main(int argc, char *argv[]) } vector training_par_list, testing_par_list; // DATASET info - vector training_par_vectors, + vector training_par_vectors, testing_par_vectors; // DATASET param vector par_dir_list; // DATASET name vector num_train_snap; // DATASET size @@ -293,7 +293,7 @@ int main(int argc, char *argv[]) } dpar = par_info.size() - 1; - CAROM::Vector* curr_par = new CAROM::Vector(dpar, false); + CAROM::Vector curr_par(dpar, false); if (idx_dataset == 0) { @@ -337,7 +337,7 @@ int main(int argc, char *argv[]) for (int par_order = 0; par_order < dpar; ++par_order) { - curr_par->item(par_order) = stod(par_info[par_order+1]); + curr_par(par_order) = stod(par_info[par_order+1]); } training_par_vectors.push_back(curr_par); } @@ -620,10 +620,10 @@ int main(int argc, char *argv[]) string par_dir = par_info[0]; par_dir_list.push_back(par_dir); - CAROM::Vector* curr_par = new CAROM::Vector(dpar, false); + CAROM::Vector curr_par(dpar, false); for (int par_order = 0; par_order < dpar; ++par_order) { - curr_par->item(par_order) = stod(par_info[par_order+1]); + curr_par(par_order) = stod(par_info[par_order+1]); } testing_par_vectors.push_back(curr_par); @@ -647,8 +647,7 @@ int main(int argc, char *argv[]) cout << "Interpolating DMD model #" << window << endl; } CAROM::getParametricDMD(dmd[idx_dataset][window], training_par_vectors, - dmd_paths, - curr_par, + dmd_paths, curr_par, string(rbf), string(interp_method), pdmd_closest_rbf_val); } // escape for-loop over window } // escape for-loop over idx_dataset @@ -667,7 +666,7 @@ int main(int argc, char *argv[]) for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) { string par_dir = par_dir_list[idx_dataset]; - CAROM::Vector* curr_par = testing_par_vectors[idx_dataset]; + const CAROM::Vector& curr_par = testing_par_vectors[idx_dataset]; if (myid == 0) { @@ -895,7 +894,6 @@ int main(int argc, char *argv[]) delete[] sample; for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) { - delete testing_par_vectors[idx_dataset]; for (int window = 0; window < numWindows; ++window) { delete dmd[idx_dataset][window]; @@ -906,9 +904,9 @@ int main(int argc, char *argv[]) } void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector>& training_twep, - CAROM::Vector* desired_point, + const CAROM::Vector & desired_point, std::string rbf = "G", double closest_rbf_val = 0.9) { @@ -920,7 +918,6 @@ void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, std::vector rbf_val = obtainRBFToTrainingPoints(parameter_points, "IDW", rbf, epsilon, desired_point); - CAROM::Matrix* f_T = NULL; - + CAROM::Matrix f_T; testing_twep = obtainInterpolatedVector(training_twep, f_T, "IDW", rbf_val); } diff --git a/examples/dmd/parametric_heat_conduction.cpp b/examples/dmd/parametric_heat_conduction.cpp index 9e0dc0a03..9a3aa75e4 100644 --- a/examples/dmd/parametric_heat_conduction.cpp +++ b/examples/dmd/parametric_heat_conduction.cpp @@ -742,7 +742,7 @@ int main(int argc, char *argv[]) std::fstream fin("parameters.txt", std::ios_base::in); double curr_param; std::vector dmd_paths; - std::vector param_vectors; + std::vector param_vectors; while (fin >> curr_param) { @@ -757,20 +757,20 @@ int main(int argc, char *argv[]) dmd_paths.push_back(outputPath + "/" + to_string(curr_radius) + "_" + to_string(curr_alpha) + "_" + to_string(curr_cx) + "_" + to_string(curr_cy)); - CAROM::Vector* param_vector = new CAROM::Vector(4, false); - param_vector->item(0) = curr_radius; - param_vector->item(1) = curr_alpha; - param_vector->item(2) = curr_cx; - param_vector->item(3) = curr_cy; + CAROM::Vector param_vector(4, false); + param_vector(0) = curr_radius; + param_vector(1) = curr_alpha; + param_vector(2) = curr_cx; + param_vector(3) = curr_cy; param_vectors.push_back(param_vector); } fin.close(); - CAROM::Vector* desired_param = new CAROM::Vector(4, false); - desired_param->item(0) = radius; - desired_param->item(1) = alpha; - desired_param->item(2) = cx; - desired_param->item(3) = cy; + CAROM::Vector desired_param(4, false); + desired_param(0) = radius; + desired_param(1) = alpha; + desired_param(2) = cx; + desired_param(3) = cy; dmd_training_timer.Start(); @@ -780,7 +780,6 @@ int main(int argc, char *argv[]) dmd_u->projectInitialCondition(init); dmd_training_timer.Stop(); - delete desired_param; } if (predict) diff --git a/examples/dmd/parametric_tw_csv.cpp b/examples/dmd/parametric_tw_csv.cpp index babcf8987..1d6e299c1 100644 --- a/examples/dmd/parametric_tw_csv.cpp +++ b/examples/dmd/parametric_tw_csv.cpp @@ -329,7 +329,7 @@ int main(int argc, char *argv[]) vector training_par_list, testing_par_list; // DATASET info vector par_dir_list; // DATASET name - vector par_vectors; // DATASET param + vector par_vectors; // DATASET param vector indicator_init, indicator_last; // DATASET indicator range @@ -354,7 +354,7 @@ int main(int argc, char *argv[]) } dpar = par_info.size() - 1; - CAROM::Vector* curr_par = new CAROM::Vector(dpar, false); + CAROM::Vector curr_par(dpar, false); if (idx_dataset == 0) { @@ -439,7 +439,7 @@ int main(int argc, char *argv[]) for (int par_order = 0; par_order < dpar; ++par_order) { - curr_par->item(par_order) = stod(par_info[par_order+1]); + curr_par(par_order) = stod(par_info[par_order+1]); } par_vectors.push_back(curr_par); @@ -818,7 +818,7 @@ int main(int argc, char *argv[]) numWindows); } // escape if-statement of offline - CAROM::Vector* curr_par = new CAROM::Vector(dpar, false); + CAROM::Vector curr_par(dpar, false); if (online) { @@ -888,7 +888,7 @@ int main(int argc, char *argv[]) for (int par_order = 0; par_order < dpar; ++par_order) { - curr_par->item(par_order) = stod(par_info[par_order+1]); + curr_par(par_order) = stod(par_info[par_order+1]); } vector tvec(num_snap_orig); @@ -1262,7 +1262,6 @@ int main(int argc, char *argv[]) } delete[] sample; - delete curr_par; for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) { for (int window = 0; window < numWindows; ++window) diff --git a/examples/prom/dg_advection_local_rom_matrix_interp.cpp b/examples/prom/dg_advection_local_rom_matrix_interp.cpp index 0536677f7..878bce8bc 100644 --- a/examples/prom/dg_advection_local_rom_matrix_interp.cpp +++ b/examples/prom/dg_advection_local_rom_matrix_interp.cpp @@ -799,7 +799,7 @@ int main(int argc, char *argv[]) } fin.close(); - std::vector parameter_points; + std::vector parameter_points; std::vector> bases; std::vector> K_hats; std::vector> M_hats; @@ -807,8 +807,8 @@ int main(int argc, char *argv[]) std::vector> u_init_hats; for(auto it = frequencies.begin(); it != frequencies.end(); it++) { - CAROM::Vector* point = new CAROM::Vector(1, false); - point->item(0) = *it; + CAROM::Vector point(1, false); + point(0) = *it; parameter_points.push_back(point); std::string parametricBasisName = "basis_" + std::to_string(*it); @@ -840,10 +840,10 @@ int main(int argc, char *argv[]) if (myid == 0) printf("spatial basis dimension is %d x %d\n", numRowRB, numColumnRB); - CAROM::Vector* curr_point = new CAROM::Vector(1, false); - curr_point->item(0) = f_factor; + CAROM::Vector curr_point(1, false); + curr_point(0) = f_factor; - int ref_point = getClosestPoint(parameter_points, curr_point); + const int ref_point = getClosestPoint(parameter_points, curr_point); std::vector> rotation_matrices = obtainRotationMatrices(parameter_points, bases, ref_point); diff --git a/lib/algo/AdaptiveDMD.cpp b/lib/algo/AdaptiveDMD.cpp index 7619ca1b7..4609f1583 100644 --- a/lib/algo/AdaptiveDMD.cpp +++ b/lib/algo/AdaptiveDMD.cpp @@ -39,25 +39,21 @@ AdaptiveDMD::AdaptiveDMD(int dim, double desired_dt, std::string rbf, void AdaptiveDMD::train(double energy_fraction, const Matrix* W0, double linearity_tol) { - const Matrix* f_snapshots = getInterpolatedSnapshots(); + std::unique_ptr f_snapshots = getInterpolatedSnapshots(); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(energy_fraction > 0 && energy_fraction <= 1); d_energy_fraction = energy_fraction; - constructDMD(f_snapshots, d_rank, d_num_procs, W0, linearity_tol); - - delete f_snapshots; + constructDMD(*f_snapshots, d_rank, d_num_procs, W0, linearity_tol); } void AdaptiveDMD::train(int k, const Matrix* W0, double linearity_tol) { - const Matrix* f_snapshots = getInterpolatedSnapshots(); + std::unique_ptr f_snapshots = getInterpolatedSnapshots(); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(k > 0 && k <= f_snapshots->numColumns() - 1); d_energy_fraction = -1.0; d_k = k; - constructDMD(f_snapshots, d_rank, d_num_procs, W0, linearity_tol); - - delete f_snapshots; + constructDMD(*f_snapshots, d_rank, d_num_procs, W0, linearity_tol); } void AdaptiveDMD::interpolateSnapshots() @@ -76,21 +72,21 @@ void AdaptiveDMD::interpolateSnapshots() std::vector d_sampled_dts; for (int i = 1; i < d_sampled_times.size(); i++) { - d_sampled_dts.push_back(d_sampled_times[i]->item(0) - d_sampled_times[i - - 1]->item(0)); + d_sampled_dts.push_back(d_sampled_times[i] - d_sampled_times[i - 1]); } auto m = d_sampled_dts.begin() + d_sampled_dts.size() / 2; std::nth_element(d_sampled_dts.begin(), m, d_sampled_dts.end()); - if (d_rank == 0) std::cout << - "Setting desired dt to the median dt between the samples: " << - d_sampled_dts[d_sampled_dts.size() / 2] << std::endl; + if (d_rank == 0) + std::cout << "Setting desired dt to the median dt between the samples: " + << d_sampled_dts[d_sampled_dts.size() / 2] << std::endl; + d_dt = d_sampled_dts[d_sampled_dts.size() / 2]; } - CAROM_VERIFY(d_sampled_times.back()->item(0) > d_dt); + CAROM_VERIFY(d_sampled_times.back() > d_dt); // Find the nearest dt that evenly divides the snapshots. - int num_time_steps = std::round(d_sampled_times.back()->item(0) / d_dt); + int num_time_steps = std::round(d_sampled_times.back() / d_dt); if (automate_dt && num_time_steps < d_sampled_times.size()) { num_time_steps = d_sampled_times.size(); @@ -98,7 +94,7 @@ void AdaptiveDMD::interpolateSnapshots() "There will be less interpolated snapshots than FOM snapshots. dt will be decreased." << std::endl; } - double new_dt = d_sampled_times.back()->item(0) / num_time_steps; + const double new_dt = d_sampled_times.back() / num_time_steps; if (new_dt != d_dt) { d_dt = new_dt; @@ -108,12 +104,15 @@ void AdaptiveDMD::interpolateSnapshots() // Solve the linear system if required. Matrix* f_T = NULL; - double epsilon = convertClosestRBFToEpsilon(d_sampled_times, d_rbf, + std::unique_ptr> sampled_times = scalarsToVectors( + d_sampled_times); + double epsilon = convertClosestRBFToEpsilon(*sampled_times, d_rbf, d_closest_rbf_val); + if (d_interp_method == "LS") { - f_T = solveLinearSystem(d_sampled_times, d_snapshots, d_interp_method, d_rbf, - epsilon); + f_T = solveLinearSystem(*sampled_times, d_snapshots, d_interp_method, + d_rbf, epsilon); } // Create interpolated snapshots using d_dt as the desired dt. @@ -122,19 +121,18 @@ void AdaptiveDMD::interpolateSnapshots() double curr_time = i * d_dt; if (d_rank == 0) std::cout << "Creating new interpolated sample at: " << d_t_offset + curr_time << std::endl; - CAROM::Vector* point = new Vector(&curr_time, 1, false); + Vector point(&curr_time, 1, false); // Obtain distances from database points to new point - std::vector rbf = obtainRBFToTrainingPoints(d_sampled_times, - d_interp_method, d_rbf, epsilon, point); + std::vector rbf = obtainRBFToTrainingPoints( + *scalarsToVectors(d_sampled_times), + d_interp_method, d_rbf, epsilon, point); // Obtain the interpolated snapshot. CAROM::Vector* curr_interpolated_snapshot = obtainInterpolatedVector( - d_snapshots, f_T, d_interp_method, rbf); + d_snapshots, *f_T, d_interp_method, rbf); d_interp_snapshots.push_back(std::shared_ptr (curr_interpolated_snapshot)); - - delete point; } if (d_rank == 0) std::cout << "Number of interpolated snapshots is: " << @@ -146,7 +144,7 @@ double AdaptiveDMD::getTrueDt() const return d_dt; } -const Matrix* AdaptiveDMD::getInterpolatedSnapshots() +std::unique_ptr AdaptiveDMD::getInterpolatedSnapshots() { if (d_interp_snapshots.size() == 0) interpolateSnapshots(); return createSnapshotMatrix(d_interp_snapshots); diff --git a/lib/algo/AdaptiveDMD.h b/lib/algo/AdaptiveDMD.h index b7166a476..85668a5df 100644 --- a/lib/algo/AdaptiveDMD.h +++ b/lib/algo/AdaptiveDMD.h @@ -89,7 +89,7 @@ class AdaptiveDMD : public DMD /** * @brief Get the interpolated snapshot matrix contained within d_interp_snapshots. */ - const Matrix* getInterpolatedSnapshots(); + std::unique_ptr getInterpolatedSnapshots(); private: diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index 49a97fc57..26270de82 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -130,10 +130,6 @@ DMD::DMD(std::vector> eigs, DMD::~DMD() { - for (auto sampled_time : d_sampled_times) - { - delete sampled_time; - } delete d_state_offset; } @@ -163,10 +159,10 @@ void DMD::takeSample(double* u_in, double t) } // Erase any snapshots taken at the same or later time - while (!d_sampled_times.empty() && d_sampled_times.back()->item(0) >= t) + while (!d_sampled_times.empty() && d_sampled_times.back() >= t) { if (d_rank == 0) std::cout << "Removing existing snapshot at time: " << - d_t_offset + d_sampled_times.back()->item(0) << std::endl; + d_t_offset + d_sampled_times.back() << std::endl; d_snapshots.pop_back(); d_sampled_times.pop_back(); } @@ -178,60 +174,54 @@ void DMD::takeSample(double* u_in, double t) } else { - CAROM_VERIFY(d_sampled_times.back()->item(0) < t); + CAROM_VERIFY(d_sampled_times.back() < t); } d_snapshots.push_back(std::shared_ptr(sample)); - - Vector* sampled_time = new Vector(&t, 1, false); - d_sampled_times.push_back(sampled_time); + d_sampled_times.push_back(t); } void DMD::train(double energy_fraction, const Matrix* W0, double linearity_tol) { - const Matrix* f_snapshots = getSnapshotMatrix(); + std::unique_ptr f_snapshots = getSnapshotMatrix(); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(energy_fraction > 0 && energy_fraction <= 1); d_energy_fraction = energy_fraction; - constructDMD(f_snapshots, d_rank, d_num_procs, W0, linearity_tol); - - delete f_snapshots; + constructDMD(*f_snapshots, d_rank, d_num_procs, W0, linearity_tol); } void DMD::train(int k, const Matrix* W0, double linearity_tol) { - const Matrix* f_snapshots = getSnapshotMatrix(); + std::unique_ptr f_snapshots = getSnapshotMatrix(); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(k > 0 && k <= f_snapshots->numColumns() - 1); d_energy_fraction = -1.0; d_k = k; - constructDMD(f_snapshots, d_rank, d_num_procs, W0, linearity_tol); - - delete f_snapshots; + constructDMD(*f_snapshots, d_rank, d_num_procs, W0, linearity_tol); } std::pair -DMD::computeDMDSnapshotPair(const Matrix* snapshots) +DMD::computeDMDSnapshotPair(const Matrix & snapshots) { - CAROM_VERIFY(snapshots->numColumns() > 1); + CAROM_VERIFY(snapshots.numColumns() > 1); // TODO: Making two copies of the snapshot matrix has a lot of overhead. // We need to figure out a way to do submatrix multiplication and to // reimplement this algorithm using one snapshot matrix. - Matrix* f_snapshots_in = new Matrix(snapshots->numRows(), - snapshots->numColumns() - 1, snapshots->distributed()); - Matrix* f_snapshots_out = new Matrix(snapshots->numRows(), - snapshots->numColumns() - 1, snapshots->distributed()); + Matrix* f_snapshots_in = new Matrix(snapshots.numRows(), + snapshots.numColumns() - 1, snapshots.distributed()); + Matrix* f_snapshots_out = new Matrix(snapshots.numRows(), + snapshots.numColumns() - 1, snapshots.distributed()); // Break up snapshots into snapshots_in and snapshots_out // snapshots_in = all columns of snapshots except last // snapshots_out = all columns of snapshots except first - for (int i = 0; i < snapshots->numRows(); i++) + for (int i = 0; i < snapshots.numRows(); i++) { - for (int j = 0; j < snapshots->numColumns() - 1; j++) + for (int j = 0; j < snapshots.numColumns() - 1; j++) { - f_snapshots_in->item(i, j) = snapshots->item(i, j); - f_snapshots_out->item(i, j) = snapshots->item(i, j + 1); + f_snapshots_in->item(i, j) = snapshots(i, j); + f_snapshots_out->item(i, j) = snapshots(i, j + 1); if (d_state_offset) { f_snapshots_in->item(i, j) -= d_state_offset->item(i); @@ -267,7 +257,7 @@ DMD::computePhi(struct DMDInternal dmd_internal_obj) } void -DMD::constructDMD(const Matrix* f_snapshots, +DMD::constructDMD(const Matrix & f_snapshots, int d_rank, int d_num_procs, const Matrix* W0, @@ -356,8 +346,8 @@ DMD::constructDMD(const Matrix* f_snapshots, d_num_singular_vectors << "." << std::endl; // Allocate the appropriate matrices and gather their elements. - d_basis.reset(new Matrix(f_snapshots->numRows(), d_k, - f_snapshots->distributed())); + d_basis.reset(new Matrix(f_snapshots.numRows(), d_k, + f_snapshots.distributed())); Matrix* d_S_inv = new Matrix(d_k, d_k, false); Matrix* d_basis_right = new Matrix(f_snapshots_in->numColumns(), d_k, false); @@ -392,7 +382,7 @@ DMD::constructDMD(const Matrix* f_snapshots, std::vector lin_independent_cols_W; // Copy W0 and orthogonalize. - Matrix* d_basis_init = new Matrix(f_snapshots->numRows(), W0->numColumns(), + Matrix* d_basis_init = new Matrix(f_snapshots.numRows(), W0->numColumns(), true); for (int i = 0; i < d_basis_init->numRows(); i++) { @@ -403,14 +393,14 @@ DMD::constructDMD(const Matrix* f_snapshots, } d_basis_init->orthogonalize(); - Vector W_col(f_snapshots->numRows(), f_snapshots->distributed()); + Vector W_col(f_snapshots.numRows(), f_snapshots.distributed()); Vector l(W0->numColumns(), true); - Vector W0l(f_snapshots->numRows(), f_snapshots->distributed()); + Vector W0l(f_snapshots.numRows(), f_snapshots.distributed()); // Find which columns of d_basis are linearly independent from W0 for (int j = 0; j < d_basis->numColumns(); j++) { // l = W0' * u - for (int i = 0; i < f_snapshots->numRows(); i++) + for (int i = 0; i < f_snapshots.numRows(); i++) { W_col.item(i) = d_basis->item(i, j); } @@ -444,7 +434,7 @@ DMD::constructDMD(const Matrix* f_snapshots, delete d_basis_init; // Add the linearly independent columns of W to W0. Call this new basis W_new. - Matrix* d_basis_new = new Matrix(f_snapshots->numRows(), + Matrix* d_basis_new = new Matrix(f_snapshots.numRows(), W0->numColumns() + lin_independent_cols_W.size(), true); for (int i = 0; i < d_basis_new->numRows(); i++) { @@ -698,13 +688,13 @@ DMD::getTimeOffset() const return d_t_offset; } -const Matrix* +std::unique_ptr DMD::getSnapshotMatrix() { return createSnapshotMatrix(d_snapshots); } -const Matrix* +std::unique_ptr DMD::createSnapshotMatrix(const std::vector> & snapshots) { @@ -727,7 +717,7 @@ DMD::createSnapshotMatrix(const std::vector> & } } - return snapshot_mat; + return std::unique_ptr(snapshot_mat); } void diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index f423e1791..30cd4a1f9 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -176,7 +176,7 @@ class DMD /** * @brief Get the snapshot matrix contained within d_snapshots. */ - const Matrix* getSnapshotMatrix(); + std::unique_ptr getSnapshotMatrix(); /** * @brief Load the object state from a file. @@ -237,9 +237,9 @@ class DMD * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ friend void getParametricDMD(DMD*& parametric_dmd, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmds, - Vector* desired_point, + const Vector & desired_point, std::string rbf, std::string interp_method, double closest_rbf_val, @@ -296,7 +296,7 @@ class DMD /** * @brief Construct the DMD object. */ - void constructDMD(const Matrix* f_snapshots, + void constructDMD(const Matrix & f_snapshots, int rank, int num_procs, const Matrix* W0, @@ -306,7 +306,7 @@ class DMD * @brief Returns a pair of pointers to the minus and plus snapshot matrices */ virtual std::pair computeDMDSnapshotPair( - const Matrix* snapshots); + const Matrix & snapshots); /** * @brief Compute phi. @@ -326,8 +326,8 @@ class DMD /** * @brief Get the snapshot matrix contained within d_snapshots. */ - const Matrix* createSnapshotMatrix(const std::vector> & - snapshots); + std::unique_ptr + createSnapshotMatrix(const std::vector> & snapshots); /** * @brief The rank of the process this object belongs to. @@ -362,7 +362,7 @@ class DMD /** * @brief The stored times of each sample. */ - std::vector d_sampled_times; + std::vector d_sampled_times; /** * @brief State offset in snapshot. diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index 2c07db638..5d4755ffd 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -105,10 +105,11 @@ DMDc::DMDc(std::string base_file_name) load(base_file_name); } -DMDc::DMDc(std::vector> eigs, +DMDc::DMDc(std::vector> & eigs, std::shared_ptr & phi_real, - std::shared_ptr & phi_imaginary, std::shared_ptr B_tilde, int k, - double dt, double t_offset, Vector* state_offset, Matrix* basis) + std::shared_ptr & phi_imaginary, + std::shared_ptr B_tilde, int k, double dt, double t_offset, + Vector* state_offset, std::shared_ptr & basis) { // Get the rank of this process, and the number of processors. int mpi_init; @@ -129,7 +130,7 @@ DMDc::DMDc(std::vector> eigs, d_k = k; d_dt = dt; d_t_offset = t_offset; - d_basis.reset(basis); + d_basis = basis; setOffset(state_offset); } @@ -139,10 +140,6 @@ DMDc::~DMDc() { delete snapshot; } - for (auto sampled_time : d_sampled_times) - { - delete sampled_time; - } delete d_state_offset; } @@ -169,10 +166,10 @@ void DMDc::takeSample(double* u_in, double t, double* f_in, bool last_step) } // Erase any snapshots taken at the same or later time - while (!d_sampled_times.empty() && d_sampled_times.back()->item(0) >= t) + while (!d_sampled_times.empty() && d_sampled_times.back() >= t) { if (d_rank == 0) std::cout << "Removing existing snapshot at time: " << - d_t_offset + d_sampled_times.back()->item(0) << std::endl; + d_t_offset + d_sampled_times.back() << std::endl; Vector* last_snapshot = d_snapshots.back(); delete last_snapshot; d_snapshots.pop_back(); @@ -187,7 +184,7 @@ void DMDc::takeSample(double* u_in, double t, double* f_in, bool last_step) } else { - CAROM_VERIFY(d_sampled_times.back()->item(0) < t); + CAROM_VERIFY(d_sampled_times.back() < t); } d_snapshots.push_back(sample); @@ -197,62 +194,57 @@ void DMDc::takeSample(double* u_in, double t, double* f_in, bool last_step) d_controls.push_back(control); } - Vector* sampled_time = new Vector(&t, 1, false); - d_sampled_times.push_back(sampled_time); + d_sampled_times.push_back(t); } void DMDc::train(double energy_fraction, const Matrix* B) { - const Matrix* f_snapshots = getSnapshotMatrix(); - const Matrix* f_controls = createSnapshotMatrix(d_controls); + std::unique_ptr f_snapshots = getSnapshotMatrix(); + std::unique_ptr f_controls = createSnapshotMatrix(d_controls); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(f_controls->numColumns() == f_snapshots->numColumns() - 1); CAROM_VERIFY(energy_fraction > 0 && energy_fraction <= 1); d_energy_fraction = energy_fraction; - constructDMDc(f_snapshots, f_controls, d_rank, d_num_procs, B); - - delete f_snapshots; + constructDMDc(*f_snapshots, *f_controls, d_rank, d_num_procs, B); } void DMDc::train(int k, const Matrix* B) { - const Matrix* f_snapshots = getSnapshotMatrix(); - const Matrix* f_controls = createSnapshotMatrix(d_controls); + std::unique_ptr f_snapshots = getSnapshotMatrix(); + std::unique_ptr f_controls = createSnapshotMatrix(d_controls); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(f_controls->numColumns() == f_snapshots->numColumns() - 1); CAROM_VERIFY(k > 0 && k <= f_snapshots->numColumns() - 1); d_energy_fraction = -1.0; d_k = k; - constructDMDc(f_snapshots, f_controls, d_rank, d_num_procs, B); - - delete f_snapshots; + constructDMDc(*f_snapshots, *f_controls, d_rank, d_num_procs, B); } std::pair -DMDc::computeDMDcSnapshotPair(const Matrix* snapshots, const Matrix* controls, +DMDc::computeDMDcSnapshotPair(const Matrix & snapshots, const Matrix & controls, const Matrix* B) { - CAROM_VERIFY(snapshots->numColumns() > 1); - CAROM_VERIFY(controls->numColumns() == snapshots->numColumns()-1); + CAROM_VERIFY(snapshots.numColumns() > 1); + CAROM_VERIFY(controls.numColumns() == snapshots.numColumns() - 1); // TODO: Making two copies of the snapshot matrix has a lot of overhead. // We need to figure out a way to do submatrix multiplication and to // reimplement this algorithm using one snapshot matrix. - int input_control_dim = (B == NULL) ? controls->numRows() : 0; - Matrix* f_snapshots_in = new Matrix(snapshots->numRows() + input_control_dim, - snapshots->numColumns() - 1, snapshots->distributed()); - Matrix* f_snapshots_out = new Matrix(snapshots->numRows(), - snapshots->numColumns() - 1, snapshots->distributed()); + int input_control_dim = (B == NULL) ? controls.numRows() : 0; + Matrix* f_snapshots_in = new Matrix(snapshots.numRows() + input_control_dim, + snapshots.numColumns() - 1, snapshots.distributed()); + Matrix* f_snapshots_out = new Matrix(snapshots.numRows(), + snapshots.numColumns() - 1, snapshots.distributed()); // Break up snapshots into snapshots_in and snapshots_out // snapshots_in = all columns of snapshots except last // snapshots_out = all columns of snapshots except first - for (int i = 0; i < snapshots->numRows(); i++) + for (int i = 0; i < snapshots.numRows(); i++) { - for (int j = 0; j < snapshots->numColumns() - 1; j++) + for (int j = 0; j < snapshots.numColumns() - 1; j++) { - f_snapshots_in->item(i, j) = snapshots->item(i, j); - f_snapshots_out->item(i, j) = snapshots->item(i, j + 1); + f_snapshots_in->item(i, j) = snapshots(i, j); + f_snapshots_out->item(i, j) = snapshots(i, j + 1); if (d_state_offset) { f_snapshots_in->item(i, j) -= d_state_offset->item(i); @@ -261,18 +253,18 @@ DMDc::computeDMDcSnapshotPair(const Matrix* snapshots, const Matrix* controls, } } - for (int i = 0; i < controls->numRows(); i++) + for (int i = 0; i < controls.numRows(); i++) { if (B == NULL) { - for (int j = 0; j < snapshots->numColumns() - 1; j++) + for (int j = 0; j < snapshots.numColumns() - 1; j++) { - f_snapshots_in->item(snapshots->numRows() + i, j) = controls->item(i, j); + f_snapshots_in->item(snapshots.numRows() + i, j) = controls.item(i, j); } } else { - std::unique_ptr Bf = B->mult(*controls); + std::unique_ptr Bf = B->mult(controls); *f_snapshots_out -= *Bf; } } @@ -281,8 +273,8 @@ DMDc::computeDMDcSnapshotPair(const Matrix* snapshots, const Matrix* controls, } void -DMDc::constructDMDc(const Matrix* f_snapshots, - const Matrix* f_controls, +DMDc::constructDMDc(const Matrix & f_snapshots, + const Matrix & f_controls, int d_rank, int d_num_procs, const Matrix* B) @@ -506,21 +498,20 @@ DMDc::constructDMDc(const Matrix* f_snapshots, if (B == NULL) { - Matrix* d_basis_in_state = new Matrix(f_snapshots->numRows(), - d_k_in, f_snapshots->distributed()); - Matrix* d_basis_in_control_transpose = new Matrix(d_k_in, f_controls->numRows(), + Matrix* d_basis_in_state = new Matrix(f_snapshots.numRows(), + d_k_in, f_snapshots.distributed()); + Matrix* d_basis_in_control_transpose = new Matrix(d_k_in, f_controls.numRows(), false); for (int j = 0; j < d_k_in; j++) { - for (int i = 0; i < f_snapshots->numRows(); i++) + for (int i = 0; i < f_snapshots.numRows(); i++) { d_basis_in_state->item(i, j) = d_basis_in->item(i, j); } - for (int i = 0; i < f_controls->numRows(); i++) + for (int i = 0; i < f_controls.numRows(); i++) { - d_basis_in_control_transpose->item(j, - i) = d_basis_in->item(f_snapshots->numRows() + i, - j); + d_basis_in_control_transpose->item(j, i) = + d_basis_in->item(f_snapshots.numRows() + i, j); } } std::unique_ptr d_basis_state_rot = d_basis_in_state->transposeMult( @@ -543,10 +534,10 @@ DMDc::constructDMDc(const Matrix* f_snapshots, d_phi_real = d_basis->mult(*eigenpair.ev_real); d_phi_imaginary = d_basis->mult(*eigenpair.ev_imaginary); - Vector* init = new Vector(d_basis->numRows(), true); - for (int i = 0; i < init->dim(); i++) + Vector init(d_basis->numRows(), true); + for (int i = 0; i < init.dim(); i++) { - init->item(i) = f_snapshots_in->item(i, 0); + init(i) = f_snapshots_in->item(i, 0); } // Calculate the projection initial_condition onto column space of d_basis. @@ -560,13 +551,12 @@ DMDc::constructDMDc(const Matrix* f_snapshots, delete f_snapshots_out; delete eigenpair.ev_real; delete eigenpair.ev_imaginary; - delete init; release_context(&svd_input); } void -DMDc::project(const Vector* init, const Matrix* controls, double t_offset) +DMDc::project(const Vector & init, const Matrix & controls, double t_offset) { std::shared_ptr d_phi_real_squared = d_phi_real->transposeMult( *d_phi_real); @@ -637,8 +627,8 @@ DMDc::project(const Vector* init, const Matrix* controls, double t_offset) } // Initial condition - std::unique_ptr init_real = d_phi_real->transposeMult(*init); - std::unique_ptr init_imaginary = d_phi_imaginary->transposeMult(*init); + std::unique_ptr init_real = d_phi_real->transposeMult(init); + std::unique_ptr init_imaginary = d_phi_imaginary->transposeMult(init); std::unique_ptr d_projected_init_real_1 = d_phi_real_squared_inverse->mult(*init_real); @@ -654,7 +644,7 @@ DMDc::project(const Vector* init, const Matrix* controls, double t_offset) *d_projected_init_imaginary_1); // Controls - std::unique_ptr B_tilde_f = d_B_tilde->mult(*controls); + std::unique_ptr B_tilde_f = d_B_tilde->mult(controls); std::unique_ptr UBf = d_basis->mult(*B_tilde_f); std::unique_ptr controls_real = d_phi_real->transposeMult(*UBf); std::unique_ptr controls_imaginary = d_phi_imaginary->transposeMult( @@ -788,13 +778,13 @@ DMDc::getTimeOffset() const return d_t_offset; } -const Matrix* +std::unique_ptr DMDc::getSnapshotMatrix() { return createSnapshotMatrix(d_snapshots); } -const Matrix* +std::unique_ptr DMDc::createSnapshotMatrix(std::vector snapshots) { CAROM_VERIFY(snapshots.size() > 0); @@ -816,7 +806,7 @@ DMDc::createSnapshotMatrix(std::vector snapshots) } } - return snapshot_mat; + return std::unique_ptr(snapshot_mat); } void diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index f532c0bea..2f1b36e7e 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -111,7 +111,7 @@ class DMDc * @param[in] controls The controls. * @param[in] t_offset The initial time offset. */ - void project(const Vector* init, const Matrix* controls, + void project(const Vector & init, const Matrix & controls, double t_offset = -1.0); /** @@ -145,7 +145,7 @@ class DMDc /** * @brief Get the snapshot matrix contained within d_snapshots. */ - const Matrix* getSnapshotMatrix(); + std::unique_ptr getSnapshotMatrix(); /** * @brief Load the object state from a file. @@ -210,11 +210,11 @@ class DMDc * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ friend void getParametricDMDc(DMDc*& parametric_dmdc, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmdcs, std::vector> controls, std::shared_ptr & controls_interpolated, - Vector* desired_point, + const Vector & desired_point, std::string rbf, std::string interp_method, double closest_rbf_val, @@ -240,15 +240,20 @@ class DMDc * @param[in] dt d_dt * @param[in] t_offset d_t_offset * @param[in] state_offset d_state_offset - * @param[in] basis d_basis, set by DMDc class for offline stages. When interpolating a new DMDc, we enter the interpolated basis explicitly + * @param[in] basis d_basis, set by DMDc class for offline stages. When + * interpolating a new DMDc, we enter the interpolated basis + * explicitly. */ - DMDc(std::vector> eigs, std::shared_ptr & phi_real, - std::shared_ptr & phi_imaginary, std::shared_ptr B_tilde, int k, - double dt, double t_offset, Vector* state_offset, Matrix* basis = nullptr); + DMDc(std::vector> & eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, + std::shared_ptr B_tilde, + int k, double dt, double t_offset, Vector* state_offset, + std::shared_ptr & basis); /** - * @brief Unimplemented default constructor. - */ + * @brief Unimplemented default constructor. + */ DMDc(); /** @@ -272,8 +277,8 @@ class DMDc /** * @brief Construct the DMDc object. */ - void constructDMDc(const Matrix* f_snapshots, - const Matrix* f_controls, + void constructDMDc(const Matrix & f_snapshots, + const Matrix & f_controls, int rank, int num_procs, const Matrix* B); @@ -282,7 +287,7 @@ class DMDc * @brief Returns a pair of pointers to the minus and plus snapshot matrices */ virtual std::pair computeDMDcSnapshotPair( - const Matrix* snapshots, const Matrix* controls, const Matrix* B); + const Matrix & snapshots, const Matrix & controls, const Matrix* B); /** * @brief Compute the appropriate exponential function when predicting the solution. @@ -297,7 +302,8 @@ class DMDc /** * @brief Get the snapshot matrix contained within d_snapshots. */ - const Matrix* createSnapshotMatrix(std::vector snapshots); + std::unique_ptr createSnapshotMatrix(std::vector + snapshots); /** * @brief The rank of the process this object belongs to. @@ -342,7 +348,7 @@ class DMDc /** * @brief The stored times of each sample. */ - std::vector d_sampled_times; + std::vector d_sampled_times; /** * @brief State offset in snapshot. diff --git a/lib/algo/NonuniformDMD.cpp b/lib/algo/NonuniformDMD.cpp index 3a611cea1..499bc93fc 100644 --- a/lib/algo/NonuniformDMD.cpp +++ b/lib/algo/NonuniformDMD.cpp @@ -68,29 +68,29 @@ void NonuniformDMD::setOffset(Vector* offset_vector, int order) } std::pair -NonuniformDMD::computeDMDSnapshotPair(const Matrix* snapshots) +NonuniformDMD::computeDMDSnapshotPair(const Matrix & snapshots) { - CAROM_VERIFY(snapshots->numColumns() > 1); + CAROM_VERIFY(snapshots.numColumns() > 1); // TODO: Making two copies of the snapshot matrix has a lot of overhead. // We need to figure out a way to do submatrix multiplication and to // reimplement this algorithm using one snapshot matrix. - Matrix* f_snapshots_in = new Matrix(snapshots->numRows(), - snapshots->numColumns() - 1, snapshots->distributed()); - Matrix* f_snapshots_out = new Matrix(snapshots->numRows(), - snapshots->numColumns() - 1, snapshots->distributed()); + Matrix* f_snapshots_in = new Matrix(snapshots.numRows(), + snapshots.numColumns() - 1, snapshots.distributed()); + Matrix* f_snapshots_out = new Matrix(snapshots.numRows(), + snapshots.numColumns() - 1, snapshots.distributed()); // Break up snapshots into snapshots_in and snapshots_out // snapshots_in = all columns of snapshots except last // snapshots_out = finite difference of all columns of snapshots - for (int i = 0; i < snapshots->numRows(); i++) + for (int i = 0; i < snapshots.numRows(); i++) { - for (int j = 0; j < snapshots->numColumns() - 1; j++) + for (int j = 0; j < snapshots.numColumns() - 1; j++) { - f_snapshots_in->item(i, j) = snapshots->item(i, j); + f_snapshots_in->item(i, j) = snapshots(i, j); f_snapshots_out->item(i, j) = - (snapshots->item(i, j + 1) - snapshots->item(i,j)) / - (d_sampled_times[j + 1]->item(0) - d_sampled_times[j]->item(0)); + (snapshots.item(i, j + 1) - snapshots(i,j)) / + (d_sampled_times[j + 1] - d_sampled_times[j]); if (d_state_offset) f_snapshots_in->item(i, j) -= d_state_offset->item(i); if (d_derivative_offset) f_snapshots_out->item(i, j) -= d_derivative_offset->item(i); diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index 0d0316538..7d09c98b9 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -156,7 +156,7 @@ class NonuniformDMD : public DMD /** * @brief Returns a pair of pointers to the state and derivative snapshot matrices */ - std::pair computeDMDSnapshotPair(const Matrix* snapshots) + std::pair computeDMDSnapshotPair(const Matrix & snapshots) override; /** diff --git a/lib/algo/ParametricDMD.h b/lib/algo/ParametricDMD.h index f91a0e384..87f4c0fe0 100644 --- a/lib/algo/ParametricDMD.h +++ b/lib/algo/ParametricDMD.h @@ -50,9 +50,9 @@ namespace CAROM { */ template void getParametricDMD(T*& parametric_dmd, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmds, - Vector* desired_point, + const Vector & desired_point, std::string rbf = "G", std::string interp_method = "LS", double closest_rbf_val = 0.9, @@ -83,7 +83,7 @@ void getParametricDMD(T*& parametric_dmd, A_tildes.push_back(dmds[i]->d_A_tilde); } - int ref_point = getClosestPoint(parameter_points, desired_point); + const int ref_point = getClosestPoint(parameter_points, desired_point); std::vector> rotation_matrices = obtainRotationMatrices(parameter_points, bases, ref_point); @@ -134,9 +134,9 @@ void getParametricDMD(T*& parametric_dmd, */ template void getParametricDMD(T*& parametric_dmd, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmd_paths, - Vector* desired_point, + const Vector & desired_point, std::string rbf = "G", std::string interp_method = "LS", double closest_rbf_val = 0.9, @@ -150,8 +150,7 @@ void getParametricDMD(T*& parametric_dmd, } getParametricDMD(parametric_dmd, parameter_points, dmds, desired_point, - rbf, interp_method, closest_rbf_val, - reorthogonalize_W); + rbf, interp_method, closest_rbf_val, reorthogonalize_W); for (int i = 0; i < dmds.size(); i++) { delete dmds[i]; diff --git a/lib/algo/ParametricDMDc.h b/lib/algo/ParametricDMDc.h index d8b1c1a9f..ebe07f8b9 100644 --- a/lib/algo/ParametricDMDc.h +++ b/lib/algo/ParametricDMDc.h @@ -54,11 +54,11 @@ namespace CAROM { */ template void getParametricDMDc(T*& parametric_dmdc, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmdcs, std::vector> controls, std::shared_ptr & controls_interpolated, - Vector* desired_point, + const Vector & desired_point, std::string rbf = "G", std::string interp_method = "LS", double closest_rbf_val = 0.9, @@ -129,7 +129,7 @@ void getParametricDMDc(T*& parametric_dmdc, parametric_dmdc = new T(eigs, phi_real, phi_imaginary, B_tilde, dmdcs[0]->d_k,dmdcs[0]->d_dt, - dmdcs[0]->d_t_offset, dmdcs[0]->d_state_offset, W.get()); + dmdcs[0]->d_t_offset, dmdcs[0]->d_state_offset, W); delete eigenpair.ev_real; delete eigenpair.ev_imaginary; @@ -159,11 +159,11 @@ void getParametricDMDc(T*& parametric_dmdc, */ template void getParametricDMDc(T*& parametric_dmdc, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmdc_paths, std::vector> controls, std::shared_ptr & controls_interpolated, - Vector* desired_point, + const Vector & desired_point, std::string rbf = "G", std::string interp_method = "LS", double closest_rbf_val = 0.9, diff --git a/lib/algo/SnapshotDMD.cpp b/lib/algo/SnapshotDMD.cpp index b3915061d..045037e0e 100644 --- a/lib/algo/SnapshotDMD.cpp +++ b/lib/algo/SnapshotDMD.cpp @@ -32,14 +32,12 @@ void SnapshotDMD::train(int k, const Matrix* W0, double linearity_tol) interpolateToNSnapshots(k + 1); } - const Matrix* f_snapshots = getSnapshotMatrix(); + std::unique_ptr f_snapshots = getSnapshotMatrix(); CAROM_VERIFY(f_snapshots->numColumns() > 1); CAROM_VERIFY(k > 0 && k <= f_snapshots->numColumns() - 1); d_energy_fraction = -1.0; d_k = k; - constructDMD(f_snapshots, d_rank, d_num_procs, W0, linearity_tol); - - delete f_snapshots; + constructDMD(*f_snapshots, d_rank, d_num_procs, W0, linearity_tol); } void SnapshotDMD::train(double energy_fraction, const Matrix* W0, @@ -52,12 +50,15 @@ void SnapshotDMD::interpolateToNSnapshots(int n) { PCHIPInterpolator* interp = new PCHIPInterpolator(); std::vector> new_snapshots; - std::vector new_times; + std::vector new_times; - interp->interpolate(d_sampled_times,d_snapshots,n,new_times,new_snapshots); + std::unique_ptr> times = scalarsToVectors(d_sampled_times); + interp->interpolate(*times.get(), d_snapshots, n, + new_times, new_snapshots); d_snapshots = new_snapshots; - d_sampled_times = new_times; - d_dt = d_sampled_times[2]->getData()[0]-d_sampled_times[1]->getData()[0]; + d_sampled_times.resize(new_times.size()); + for (int i=0; i & parameter_points, - std::vector> & rotation_matrices, +Interpolator::Interpolator(const std::vector & parameter_points, + const std::vector> & rotation_matrices, int ref_point, std::string rbf, std::string interp_method, @@ -68,8 +68,9 @@ Interpolator::~Interpolator() } std::vector obtainRBFToTrainingPoints( - std::vector & parameter_points, - std::string interp_method, std::string rbf, double epsilon, Vector* point) + const std::vector & parameter_points, + const std::string & interp_method, const std::string & rbf, double epsilon, + const Vector & point) { std::vector rbfs; if (interp_method == "LS") @@ -115,8 +116,8 @@ std::vector obtainRBFToTrainingPoints( } Vector numerator_vec, denomenator_vec; - point->minus(*parameter_points[j], numerator_vec); - parameter_points[i]->minus(*parameter_points[j], denomenator_vec); + point.minus(parameter_points[j], numerator_vec); + parameter_points[i].minus(parameter_points[j], denomenator_vec); double numerator = numerator_vec.norm(); double denomenator = denomenator_vec.norm(); @@ -146,11 +147,11 @@ double rbfWeightedSum(std::vector& rbf) return sum; } -double obtainRBF(std::string rbf, double epsilon, Vector* point1, - Vector* point2) +double obtainRBF(std::string rbf, double epsilon, const Vector & point1, + const Vector & point2) { Vector diff; - point1->minus(*point2, diff); + point1.minus(point2, diff); double eps_norm_squared = epsilon * epsilon * diff.norm2(); double res = 0.0; @@ -173,8 +174,8 @@ double obtainRBF(std::string rbf, double epsilon, Vector* point1, return res; } -double convertClosestRBFToEpsilon(std::vector & parameter_points, - std::string rbf, double closest_rbf_val) +double convertClosestRBFToEpsilon(const std::vector & parameter_points, + const std::string & rbf, double closest_rbf_val) { double closest_point_dist = INT_MAX; double epsilon; @@ -188,7 +189,7 @@ double convertClosestRBFToEpsilon(std::vector & parameter_points, } Vector diff; - parameter_points[i]->minus(*parameter_points[j], diff); + parameter_points[i].minus(parameter_points[j], diff); double dist = diff.norm2(); if (dist < closest_point_dist) { @@ -217,8 +218,8 @@ double convertClosestRBFToEpsilon(std::vector & parameter_points, } std::vector> obtainRotationMatrices( - std::vector & parameter_points, - std::vector> & bases, + const std::vector & parameter_points, + const std::vector> & bases, int ref_point) { // Get the rank of this process, and the number of processors. @@ -258,37 +259,45 @@ std::vector> obtainRotationMatrices( std::unique_ptr basis_mult_basis = bases[i]->transposeMult( *bases[ref_point]); - Matrix* basis = new Matrix(basis_mult_basis->numRows(), - basis_mult_basis->numColumns(), false); - Matrix* basis_right = new Matrix(basis_mult_basis->numColumns(), - basis_mult_basis->numColumns(), false); + Matrix basis(basis_mult_basis->numRows(), + basis_mult_basis->numColumns(), false); + Matrix basis_right(basis_mult_basis->numColumns(), + basis_mult_basis->numColumns(), false); // We need to compute the SVD of basis_mult_basis. Since it is // undistributed due to the transposeMult, let's use lapack's serial SVD // on rank 0 only. if (rank == 0) { - Vector* sv = new Vector(basis_mult_basis->numColumns(), false); - SerialSVD(basis_mult_basis.get(), basis_right, sv, basis); - delete sv; + Vector sv(basis_mult_basis->numColumns(), false); + SerialSVD(basis_mult_basis.get(), &basis_right, &sv, &basis); } // Broadcast U and V which are computed only on root. - MPI_Bcast(basis->getData(), basis->numRows() * basis->numColumns(), MPI_DOUBLE, + MPI_Bcast(basis.getData(), basis.numRows() * basis.numColumns(), MPI_DOUBLE, 0, MPI_COMM_WORLD); - MPI_Bcast(basis_right->getData(), - basis_right->numRows() * basis_right->numColumns(), MPI_DOUBLE, 0, + MPI_Bcast(basis_right.getData(), + basis_right.numRows() * basis_right.numColumns(), MPI_DOUBLE, 0, MPI_COMM_WORLD); // Obtain the rotation matrix. - std::shared_ptr rotation_matrix = basis->mult(*basis_right); - - delete basis; - delete basis_right; - rotation_matrices.push_back(rotation_matrix); + rotation_matrices.push_back(basis.mult(basis_right)); } return rotation_matrices; } +std::unique_ptr> + scalarsToVectors(const std::vector & s) +{ + std::vector *v = new std::vector(s.size()); + for (int i=0; i>(v); +} + } diff --git a/lib/algo/manifold_interp/Interpolator.h b/lib/algo/manifold_interp/Interpolator.h index 88711ad61..988f5d521 100644 --- a/lib/algo/manifold_interp/Interpolator.h +++ b/lib/algo/manifold_interp/Interpolator.h @@ -51,8 +51,8 @@ class Interpolator * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ - Interpolator(std::vector & parameter_points, - std::vector> & rotation_matrices, + Interpolator(const std::vector & parameter_points, + const std::vector> & rotation_matrices, int ref_point, std::string rbf, std::string interp_method, @@ -98,7 +98,7 @@ class Interpolator /** * @brief The sampled parameter points. */ - std::vector d_parameter_points; + std::vector d_parameter_points; /** * @brief The reduced bases with compatible coordinates. @@ -146,8 +146,9 @@ class Interpolator * @param[in] point The unsampled parameter point. */ std::vector obtainRBFToTrainingPoints( - std::vector & parameter_points, - std::string interp_method, std::string rbf, double epsilon, Vector* point); + const std::vector & parameter_points, + const std::string & interp_method, const std::string & rbf, double epsilon, + const Vector & point); /** * @brief Compute the sum of the RBF weights. @@ -165,8 +166,8 @@ double rbfWeightedSum(std::vector& rbf); * @param[in] point1 The first point. * @param[in] point2 The second point. */ -double obtainRBF(std::string rbf, double epsilon, Vector* point1, - Vector* point2); +double obtainRBF(std::string rbf, double epsilon, const Vector & point1, + const Vector & point2); /** * @brief Convert closest RBF value to an epsilon value. @@ -176,8 +177,8 @@ double obtainRBF(std::string rbf, double epsilon, Vector* point1, * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ -double convertClosestRBFToEpsilon(std::vector & parameter_points, - std::string rbf, double closest_rbf_val); +double convertClosestRBFToEpsilon(const std::vector & parameter_points, + const std::string & rbf, double closest_rbf_val); /** * @brief Obtain the rotation matrices for all the parameter points using @@ -190,10 +191,11 @@ double convertClosestRBFToEpsilon(std::vector & parameter_points, * to the reference point */ std::vector> obtainRotationMatrices( - std::vector & parameter_points, - std::vector> & bases, + const std::vector & parameter_points, + const std::vector> & bases, int ref_point); +std::unique_ptr> + scalarsToVectors(const std::vector & s); } - #endif diff --git a/lib/algo/manifold_interp/MatrixInterpolator.cpp b/lib/algo/manifold_interp/MatrixInterpolator.cpp index 9f55bbd61..5db9be9e6 100644 --- a/lib/algo/manifold_interp/MatrixInterpolator.cpp +++ b/lib/algo/manifold_interp/MatrixInterpolator.cpp @@ -37,9 +37,10 @@ using namespace std; namespace CAROM { -MatrixInterpolator::MatrixInterpolator(std::vector & parameter_points, - std::vector> & rotation_matrices, - std::vector> & reduced_matrices, +MatrixInterpolator::MatrixInterpolator(const std::vector & + parameter_points, + const std::vector> & rotation_matrices, + const std::vector> & reduced_matrices, int ref_point, std::string matrix_type, std::string rbf, @@ -95,7 +96,7 @@ MatrixInterpolator::MatrixInterpolator(std::vector & parameter_points, } } -std::shared_ptr MatrixInterpolator::interpolate(Vector* point, +std::shared_ptr MatrixInterpolator::interpolate(const Vector & point, bool orthogonalize) { std::shared_ptr interpolated_matrix; @@ -215,7 +216,8 @@ Matrix* MatrixInterpolator::obtainLogInterpolatedMatrix( return log_interpolated_matrix; } -std::shared_ptr MatrixInterpolator::interpolateSPDMatrix(Vector* point) +std::shared_ptr MatrixInterpolator::interpolateSPDMatrix( + const Vector & point) { if (d_gammas.size() == 0) { @@ -359,7 +361,7 @@ std::shared_ptr MatrixInterpolator::interpolateSPDMatrix(Vector* point) } std::shared_ptr MatrixInterpolator::interpolateNonSingularMatrix( - Vector* point) + const Vector & point) { if (d_gammas.size() == 0) { @@ -465,7 +467,8 @@ std::shared_ptr MatrixInterpolator::interpolateNonSingularMatrix( return interpolated_matrix; } -std::shared_ptr MatrixInterpolator::interpolateMatrix(Vector* point) +std::shared_ptr MatrixInterpolator::interpolateMatrix( + const Vector & point) { if (d_gammas.size() == 0) { diff --git a/lib/algo/manifold_interp/MatrixInterpolator.h b/lib/algo/manifold_interp/MatrixInterpolator.h index a89382d23..b883fd368 100644 --- a/lib/algo/manifold_interp/MatrixInterpolator.h +++ b/lib/algo/manifold_interp/MatrixInterpolator.h @@ -59,9 +59,9 @@ class MatrixInterpolator : public Interpolator * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ - MatrixInterpolator(std::vector & parameter_points, - std::vector> & rotation_matrices, - std::vector> & reduced_matrices, + MatrixInterpolator(const std::vector & parameter_points, + const std::vector> & rotation_matrices, + const std::vector> & reduced_matrices, int ref_point, std::string matrix_type, std::string rbf = "G", @@ -74,7 +74,8 @@ class MatrixInterpolator : public Interpolator * @param[in] point The unsampled parameter point. * @param[in] orthogonalize Whether to orthogonalize the resulting interpolated matrix. */ - std::shared_ptr interpolate(Vector* point, bool orthogonalize = false); + std::shared_ptr interpolate(const Vector & point, + bool orthogonalize = false); private: @@ -116,7 +117,7 @@ class MatrixInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - std::shared_ptr interpolateSPDMatrix(Vector* point); + std::shared_ptr interpolateSPDMatrix(const Vector & point); /** * @brief Obtain the interpolated non-singular reduced matrix for the @@ -124,7 +125,7 @@ class MatrixInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - std::shared_ptr interpolateNonSingularMatrix(Vector* point); + std::shared_ptr interpolateNonSingularMatrix(const Vector & point); /** * @brief Obtain the interpolated reduced matrix for the @@ -132,7 +133,7 @@ class MatrixInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - std::shared_ptr interpolateMatrix(Vector* point); + std::shared_ptr interpolateMatrix(const Vector & point); /** * @brief The matrix type/manifold diff --git a/lib/algo/manifold_interp/PCHIPInterpolator.cpp b/lib/algo/manifold_interp/PCHIPInterpolator.cpp index 8dc07f81d..b3a16c537 100644 --- a/lib/algo/manifold_interp/PCHIPInterpolator.cpp +++ b/lib/algo/manifold_interp/PCHIPInterpolator.cpp @@ -32,24 +32,23 @@ using namespace std; namespace CAROM { -void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, +void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, std::vector>& snapshots, - std::vector& output_ts, + std::vector& output_ts, std::vector>& output_snapshots) { CAROM_VERIFY(snapshot_ts.size() == snapshots.size()); CAROM_VERIFY(snapshot_ts.size() > 2); CAROM_VERIFY(output_ts.size() > 1); CAROM_VERIFY(output_snapshots.size() == 0); - CAROM_VERIFY(snapshot_ts[0]->getData()[0] - FLT_EPSILON <= - output_ts[0]->getData()[0] && - output_ts[output_ts.size()-1]->getData()[0] <= snapshot_ts[snapshot_ts.size() - -1]->getData()[0] + FLT_EPSILON); + CAROM_VERIFY(snapshot_ts[0](0) - FLT_EPSILON <= output_ts[0](0) && + output_ts[output_ts.size()-1](0) <= + snapshot_ts[snapshot_ts.size()-1](0) + FLT_EPSILON); for(int i = 1; i < snapshot_ts.size(); ++i) { CAROM_VERIFY(snapshots[i-1]->dim() == snapshots[i]->dim()); - CAROM_VERIFY(snapshot_ts[i-1]->getData()[0] < snapshot_ts[i]->getData()[0]); - CAROM_VERIFY(output_ts[i-1]->getData()[0] < output_ts[i]->getData()[0]); + CAROM_VERIFY(snapshot_ts[i-1](0) < snapshot_ts[i](0)); + CAROM_VERIFY(output_ts[i-1](0) < output_ts[i](0)); } int n_out = output_ts.size(); @@ -69,14 +68,14 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, std::vector h,d,delta,t_in,y_in; for(int j = 0; j < n_snap-1; ++j) { - h_temp = snapshot_ts[j+1]->getData()[0] - snapshot_ts[j]->getData()[0]; + h_temp = snapshot_ts[j+1](0) - snapshot_ts[j](0); h.push_back(h_temp); delta_temp = (snapshots[j+1]->getData()[i] - snapshots[j]->getData()[i])/h_temp; delta.push_back(delta_temp); - t_in.push_back(snapshot_ts[j]->getData()[0]); + t_in.push_back(snapshot_ts[j](0)); y_in.push_back(snapshots[j]->getData()[i]); } - t_in.push_back(snapshot_ts[n_snap-1]->getData()[0]); + t_in.push_back(snapshot_ts[n_snap-1](0)); y_in.push_back(snapshots[n_snap-1]->getData()[i]); double d_temp = ((2*h[0] + h[1])*delta[0] - h[0]*delta[1])/(h[0]+h[1]); @@ -94,9 +93,9 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, { d_temp = computeDerivative(delta[j],delta[j+1],h[j],h[j+1]); d.push_back(d_temp); - while(output_ts[counter]->getData()[0] <= t_in[j+1]) + while(output_ts[counter](0) <= t_in[j+1]) { - t = output_ts[counter]->getData()[0]; + t = output_ts[counter](0); output_snapshots[counter]->getData()[i] = y_in[j]*computeH1(t,t_in[j], t_in[j+1]) + y_in[j+1]*computeH2(t,t_in[j],t_in[j+1]) + @@ -120,9 +119,9 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, d.push_back(d_temp); while(counter < n_out - && output_ts[counter]->getData()[0] <= t_in[n_snap-1] + FLT_EPSILON ) + && output_ts[counter](0) <= t_in[n_snap-1] + FLT_EPSILON ) { - t = output_ts[counter]->getData()[0]; + t = output_ts[counter](0); output_snapshots[counter]->getData()[i] = y_in[n_snap-2]*computeH1(t, t_in[n_snap-2],t_in[n_snap-1]) + y_in[n_snap-1]*computeH2(t,t_in[n_snap-2],t_in[n_snap-1]) + @@ -134,10 +133,10 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, } } -void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, +void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, std::vector>& snapshots, int n_out, - std::vector& output_ts, + std::vector& output_ts, std::vector>& output_snapshots) { CAROM_VERIFY(snapshot_ts.size() == snapshots.size()); @@ -148,15 +147,15 @@ void PCHIPInterpolator::interpolate(std::vector& snapshot_ts, int n_snap = snapshots.size(); int n_dim = snapshots[0]->dim(); - double t_min = snapshot_ts[0]->getData()[0]; - double t_max = snapshot_ts[n_snap-1]->getData()[0]; + double t_min = snapshot_ts[0](0); + double t_max = snapshot_ts[n_snap-1](0); double dt = (t_max-t_min)/(n_out-1); output_ts.clear(); for(int i = 0; i < n_out; ++i) { - Vector* temp_t = new Vector(1, false); - temp_t->getData()[0] = t_min + i*dt; + Vector temp_t(1, false); + temp_t(0) = t_min + i*dt; output_ts.push_back(temp_t); } interpolate(snapshot_ts,snapshots,output_ts, output_snapshots); diff --git a/lib/algo/manifold_interp/PCHIPInterpolator.h b/lib/algo/manifold_interp/PCHIPInterpolator.h index e0415d207..90831bf2e 100644 --- a/lib/algo/manifold_interp/PCHIPInterpolator.h +++ b/lib/algo/manifold_interp/PCHIPInterpolator.h @@ -38,9 +38,9 @@ class PCHIPInterpolator * @param[out] output_snapshots snapshots at output_ts interpolated * from snapshot_ts */ - void interpolate(std::vector& snapshot_ts, + void interpolate(std::vector& snapshot_ts, std::vector>& snapshots, - std::vector& output_ts, + std::vector& output_ts, std::vector>& output_snapshots); /** @@ -56,10 +56,10 @@ class PCHIPInterpolator * @param[out] output_snapshots snapshots at output_ts interpolated * from snapshot_ts */ - void interpolate(std::vector& snapshot_ts, + void interpolate(std::vector& snapshot_ts, std::vector>& snapshots, int n_out, - std::vector& output_ts, + std::vector& output_ts, std::vector>& output_snapshots); private: diff --git a/lib/algo/manifold_interp/VectorInterpolator.cpp b/lib/algo/manifold_interp/VectorInterpolator.cpp index 335b5db16..210d1a58b 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.cpp +++ b/lib/algo/manifold_interp/VectorInterpolator.cpp @@ -38,9 +38,10 @@ using namespace std; namespace CAROM { -VectorInterpolator::VectorInterpolator(std::vector & parameter_points, - std::vector> & rotation_matrices, - std::vector> & reduced_vectors, +VectorInterpolator::VectorInterpolator(const std::vector & + parameter_points, + const std::vector> & rotation_matrices, + const std::vector> & reduced_vectors, int ref_point, std::string rbf, std::string interp_method, @@ -73,18 +74,18 @@ void VectorInterpolator::obtainLambda() { if (d_interp_method == "LS") { - d_lambda_T = solveLinearSystem(d_parameter_points, d_gammas, d_interp_method, - d_rbf, d_epsilon); + d_lambda_T = solveLinearSystem(d_parameter_points, d_gammas, + d_interp_method, d_rbf, d_epsilon); } } Vector* VectorInterpolator::obtainLogInterpolatedVector( std::vector& rbf) { - return obtainInterpolatedVector(d_gammas, d_lambda_T, d_interp_method, rbf); + return obtainInterpolatedVector(d_gammas, *d_lambda_T, d_interp_method, rbf); } -std::shared_ptr VectorInterpolator::interpolate(Vector* point) +std::shared_ptr VectorInterpolator::interpolate(const Vector & point) { if (d_gammas.size() == 0) { @@ -127,18 +128,18 @@ std::shared_ptr VectorInterpolator::interpolate(Vector* point) } Vector* obtainInterpolatedVector(const std::vector> & - data, Matrix* f_T, + data, const Matrix & f_T, std::string interp_method, std::vector& rbf) { Vector* interpolated_vector = new Vector(data[0]->dim(), data[0]->distributed()); if (interp_method == "LS") { - for (int i = 0; i < f_T->numRows(); i++) + for (int i = 0; i < f_T.numRows(); i++) { for (int j = 0; j < rbf.size(); j++) { - interpolated_vector->getData()[i] += f_T->item(i, j) * rbf[j]; + interpolated_vector->getData()[i] += f_T(i, j) * rbf[j]; } } } @@ -168,10 +169,10 @@ Vector* obtainInterpolatedVector(const std::vector> & return interpolated_vector; } -Matrix* solveLinearSystem(const std::vector & parameter_points, +Matrix* solveLinearSystem(const std::vector & parameter_points, const std::vector> & data, - std::string interp_method, - std::string rbf, double & epsilon) + const std::string & interp_method, + const std::string & rbf, double epsilon) { int mpi_init, rank; MPI_Initialized(&mpi_init); @@ -201,7 +202,8 @@ Matrix* solveLinearSystem(const std::vector & parameter_points, B->item(i, i) = 1.0; for (int j = i + 1; j < B->numColumns(); j++) { - double res = obtainRBF(rbf, epsilon, parameter_points[i], parameter_points[j]); + double res = obtainRBF(rbf, epsilon, parameter_points[i], + parameter_points[j]); B->item(i, j) = res; B->item(j, i) = res; } diff --git a/lib/algo/manifold_interp/VectorInterpolator.h b/lib/algo/manifold_interp/VectorInterpolator.h index 93aaee77f..2eefb368b 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.h +++ b/lib/algo/manifold_interp/VectorInterpolator.h @@ -54,9 +54,9 @@ class VectorInterpolator : public Interpolator * @param[in] closest_rbf_val The RBF parameter determines the width of influence. * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 */ - VectorInterpolator(std::vector & parameter_points, - std::vector> & rotation_matrices, - std::vector> & reduced_vectors, + VectorInterpolator(const std::vector & parameter_points, + const std::vector> & rotation_matrices, + const std::vector> & reduced_vectors, int ref_point, std::string rbf = "G", std::string interp_method = "LS", @@ -67,7 +67,7 @@ class VectorInterpolator : public Interpolator * * @param[in] point The unsampled parameter point. */ - std::shared_ptr interpolate(Vector* point); + std::shared_ptr interpolate(const Vector & point); private: @@ -117,13 +117,12 @@ class VectorInterpolator : public Interpolator Vector* obtainInterpolatedVector(const std::vector> & data, - Matrix* f_T, std::string interp_method, + const Matrix & f_T, std::string interp_method, std::vector& rbf); - -Matrix* solveLinearSystem(const std::vector & parameter_points, +Matrix* solveLinearSystem(const std::vector & parameter_points, const std::vector> & data, - std::string interp_method, - std::string rbf, double & epsilon); + const std::string & interp_method, + const std::string & rbf, double epsilon); } #endif diff --git a/lib/linalg/Vector.cpp b/lib/linalg/Vector.cpp index 21f3e58fe..bfba1dadc 100644 --- a/lib/linalg/Vector.cpp +++ b/lib/linalg/Vector.cpp @@ -449,7 +449,7 @@ double Vector::localMin(int nmax) return v; } -int getCenterPoint(std::vector& points, +int getCenterPoint(const std::vector& points, bool use_centroid) { int center_point; @@ -505,10 +505,10 @@ int getCenterPoint(std::vector& points, return center_point; } -int getCenterPoint(std::vector& points, +int getCenterPoint(const std::vector& points, bool use_centroid) { - std::vector temp_points; + std::vector temp_points; for (int i = 0; i < points.size(); i++) { temp_points.push_back(&points[i]); @@ -516,14 +516,14 @@ int getCenterPoint(std::vector& points, return getCenterPoint(temp_points, use_centroid); } -int getClosestPoint(std::vector& points, - Vector* test_point) +int getClosestPoint(const std::vector& points, + const Vector & test_point) { int closest_point = 0; double closest_dist_to_test_point = INT_MAX; for (int i = 0; i < points.size(); i++) { Vector diff; - test_point->minus(*points[i], diff); + test_point.minus(*points[i], diff); double dist = diff.norm(); if (dist < closest_dist_to_test_point) { @@ -535,15 +535,15 @@ int getClosestPoint(std::vector& points, return closest_point; } -int getClosestPoint(std::vector& points, - Vector test_point) +int getClosestPoint(const std::vector& points, + const Vector & test_point) { - std::vector temp_points; + std::vector temp_points; for (int i = 0; i < points.size(); i++) { temp_points.push_back(&points[i]); } - return getClosestPoint(temp_points, &test_point); + return getClosestPoint(temp_points, test_point); } } diff --git a/lib/linalg/Vector.h b/lib/linalg/Vector.h index 0361aa491..3f9322770 100644 --- a/lib/linalg/Vector.h +++ b/lib/linalg/Vector.h @@ -615,29 +615,29 @@ class Vector * @brief Get center point of a group of points. */ -int getCenterPoint(std::vector& points, +int getCenterPoint(const std::vector& points, bool use_centroid); /** * @brief Get center point of a group of points. */ -int getCenterPoint(std::vector& points, +int getCenterPoint(const std::vector& points, bool use_centroid); /** * @brief Get closest point to a test point among a group of points. */ -int getClosestPoint(std::vector& points, - Vector* test_point); +int getClosestPoint(const std::vector& points, + const Vector & test_point); /** * @brief Get closest point to a test point among a group of points. */ -int getClosestPoint(std::vector& points, - Vector test_point); +int getClosestPoint(const std::vector& points, + const Vector & test_point); } #endif diff --git a/unit_tests/test_HDFDatabase.cpp b/unit_tests/test_HDFDatabase.cpp index 587681370..1f4ae74dd 100644 --- a/unit_tests/test_HDFDatabase.cpp +++ b/unit_tests/test_HDFDatabase.cpp @@ -823,7 +823,7 @@ TEST(BasisGeneratorIO, Scaling_test) auto stop = steady_clock::now(); auto duration = duration_cast(stop-start); if (rank == 0) - printf("Base writeSnapshot- duration: %dms\n", duration.count()); + printf("Base writeSnapshot- duration: %dms\n", (int) duration.count()); MPI_Barrier(MPI_COMM_WORLD); start = steady_clock::now(); @@ -832,7 +832,7 @@ TEST(BasisGeneratorIO, Scaling_test) stop = steady_clock::now(); duration = duration_cast(stop-start); if (rank == 0) - printf("MPIO writeSnapshot- duration: %dms\n", duration.count()); + printf("MPIO writeSnapshot- duration: %dms\n", (int) duration.count()); MPI_Barrier(MPI_COMM_WORLD); start = steady_clock::now(); @@ -841,7 +841,7 @@ TEST(BasisGeneratorIO, Scaling_test) stop = steady_clock::now(); duration = duration_cast(stop-start); if (rank == 0) - printf("Base endSamples- duration: %dms\n", duration.count()); + printf("Base endSamples- duration: %dms\n", (int) duration.count()); MPI_Barrier(MPI_COMM_WORLD); start = steady_clock::now(); @@ -850,7 +850,7 @@ TEST(BasisGeneratorIO, Scaling_test) stop = steady_clock::now(); duration = duration_cast(stop-start); if (rank == 0) - printf("MPIO endSamples- duration: %dms\n", duration.count()); + printf("MPIO endSamples- duration: %dms\n", (int) duration.count()); } int main(int argc, char* argv[]) diff --git a/unit_tests/test_PCHIPInterpolator.cpp b/unit_tests/test_PCHIPInterpolator.cpp index c9dcf547c..58d1213b1 100644 --- a/unit_tests/test_PCHIPInterpolator.cpp +++ b/unit_tests/test_PCHIPInterpolator.cpp @@ -63,8 +63,8 @@ TEST(InterpolationTest,test_accuracy) std::vector> snapshots; std::vector> out_snapshots; std::vector reference_snapshots; - std::vector times; - std::vector out_times; + std::vector times; + std::vector out_times; for(int i = 0; i < t.size(); ++i) { CAROM::Vector* temp_t = new CAROM::Vector(1, false); From b14987367dd09dc6e02c711dc4fec73b8befcc80 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Tue, 20 Aug 2024 20:27:17 -0700 Subject: [PATCH 09/19] Fix merge. --- lib/algo/NonuniformDMD.h | 2 +- lib/algo/SnapshotDMD.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index 7d09c98b9..62da1dfc7 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -107,7 +107,7 @@ class NonuniformDMD : public DMD * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ friend void getParametricDMD(NonuniformDMD*& parametric_dmd, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmds, Vector* desired_point, std::string rbf, diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index 877aed94a..b229f5be8 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -98,7 +98,7 @@ class SnapshotDMD : public DMD * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ friend void getParametricDMD(SnapshotDMD*& parametric_dmd, - std::vector& parameter_points, + const std::vector& parameter_points, std::vector& dmds, Vector* desired_point, std::string rbf, From 49dd7bd4a1f5556acee62ba98a680de09e42e56c Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 21 Aug 2024 09:30:26 -0700 Subject: [PATCH 10/19] Minor fix --- lib/algo/NonuniformDMD.h | 2 +- lib/algo/SnapshotDMD.h | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index 62da1dfc7..58859236f 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -109,7 +109,7 @@ class NonuniformDMD : public DMD friend void getParametricDMD(NonuniformDMD*& parametric_dmd, const std::vector& parameter_points, std::vector& dmds, - Vector* desired_point, + const Vector & desired_point, std::string rbf, std::string interp_method, double closest_rbf_val, diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index b229f5be8..b428edb93 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -100,7 +100,7 @@ class SnapshotDMD : public DMD friend void getParametricDMD(SnapshotDMD*& parametric_dmd, const std::vector& parameter_points, std::vector& dmds, - Vector* desired_point, + const Vector & desired_point, std::string rbf, std::string interp_method, double closest_rbf_val, From 04bc30b6a472e2dbb94af621909cfb9bdb1d2265 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 21 Aug 2024 09:47:26 -0700 Subject: [PATCH 11/19] Fixed a test. --- unit_tests/test_PCHIPInterpolator.cpp | 44 +++++++++++++-------------- 1 file changed, 21 insertions(+), 23 deletions(-) diff --git a/unit_tests/test_PCHIPInterpolator.cpp b/unit_tests/test_PCHIPInterpolator.cpp index 58d1213b1..67b96c777 100644 --- a/unit_tests/test_PCHIPInterpolator.cpp +++ b/unit_tests/test_PCHIPInterpolator.cpp @@ -62,45 +62,44 @@ TEST(InterpolationTest,test_accuracy) std::vector> snapshots; std::vector> out_snapshots; - std::vector reference_snapshots; - std::vector times; - std::vector out_times; + std::vector reference_snapshots; + std::vector times; + std::vector out_times; for(int i = 0; i < t.size(); ++i) { - CAROM::Vector* temp_t = new CAROM::Vector(1, false); - temp_t->item(0) = t[i]; + CAROM::Vector temp_t(1, false); + temp_t(0) = t[i]; times.push_back(temp_t); - CAROM::Vector* temp_y = new CAROM::Vector(2,false); - temp_y->item(0) = y[i]; - temp_y->item(1) = y2[i]; + CAROM::Vector *temp_y = new CAROM::Vector(2,false); + (*temp_y)(0) = y[i]; + (*temp_y)(1) = y2[i]; snapshots.push_back(std::shared_ptr(temp_y)); } for(int i = 0; i < tq.size(); ++i) { - CAROM::Vector* temp_t = new CAROM::Vector(1, false); - temp_t->item(0) = tq[i]; + CAROM::Vector temp_t(1, false); + temp_t(0) = tq[i]; out_times.push_back(temp_t); - CAROM::Vector* temp_y = new CAROM::Vector(2,false); - temp_y->item(0) = yq1[i]; - temp_y->item(1) = yq2[i]; + CAROM::Vector temp_y(2,false); + temp_y(0) = yq1[i]; + temp_y(1) = yq2[i]; reference_snapshots.push_back(temp_y); } - CAROM::PCHIPInterpolator* interp = new CAROM::PCHIPInterpolator(); + CAROM::PCHIPInterpolator interp; - interp->interpolate(times,snapshots,out_times,out_snapshots); + interp.interpolate(times,snapshots,out_times,out_snapshots); for(int i = 0; i < out_snapshots.size(); ++i) { - if( abs(reference_snapshots[i]->item(0)-out_snapshots[i]->item( - 0)) > 10.*FLT_EPSILON) + if (abs(reference_snapshots[i](0)-(*out_snapshots[i])(0)) > 10.*FLT_EPSILON) { SUCCESS = false; break; } - else if(abs(reference_snapshots[i]->item(1)-out_snapshots[i]->item( - 1)) > 10.*FLT_EPSILON) + else if (abs(reference_snapshots[i](1)-(*out_snapshots[i])( + 1)) > 10.*FLT_EPSILON) { SUCCESS = false; break; @@ -110,18 +109,17 @@ TEST(InterpolationTest,test_accuracy) out_snapshots.clear(); out_times.clear(); - interp->interpolate(times,snapshots,26,out_times,out_snapshots); + interp.interpolate(times,snapshots,26,out_times,out_snapshots); for(int i = 0; i < out_snapshots.size(); ++i) { - if( abs(reference_snapshots[i]->item(0)-out_snapshots[i]->item( + if( abs(reference_snapshots[i](0)-(*out_snapshots[i])( 0)) > 10.*FLT_EPSILON) { SUCCESS = false; break; } - else if(abs(reference_snapshots[i]->item(1)-out_snapshots[i]->item( - 1)) > 10.*FLT_EPSILON) + else if(abs(reference_snapshots[i](1)-(*out_snapshots[i])(1)) > 10.*FLT_EPSILON) { SUCCESS = false; break; From b9816f95c6a207a8793dac7b06508ba04ecb7294 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Mon, 26 Aug 2024 11:55:29 -0700 Subject: [PATCH 12/19] Eliminated raw pointers in hyperreduction interface. Changed offsets to use smart pointers in DMD classes. --- examples/dmd/de_dg_advection_greedy.cpp | 12 +- .../de_parametric_heat_conduction_greedy.cpp | 4 +- examples/dmd/local_dw_csv.cpp | 4 +- examples/dmd/parametric_dw_csv.cpp | 4 +- examples/dmd/parametric_heat_conduction.cpp | 2 +- examples/dmd/parametric_tw_csv.cpp | 4 +- examples/dmd/wave_equation.cpp | 2 +- lib/algo/AdaptiveDMD.cpp | 6 +- lib/algo/AdaptiveDMD.h | 5 +- lib/algo/DMD.cpp | 37 +++-- lib/algo/DMD.h | 20 +-- lib/algo/NonuniformDMD.cpp | 30 ++-- lib/algo/NonuniformDMD.h | 26 ++-- lib/algo/SnapshotDMD.h | 5 +- lib/hyperreduction/DEIM.cpp | 28 ++-- lib/hyperreduction/DEIM.h | 2 +- lib/hyperreduction/GNAT.cpp | 32 ++--- lib/hyperreduction/GNAT.h | 2 +- lib/hyperreduction/Hyperreduction.cpp | 8 +- lib/hyperreduction/QDEIM.cpp | 44 +++--- lib/hyperreduction/QDEIM.h | 2 +- lib/hyperreduction/S_OPT.cpp | 129 ++++++++---------- lib/hyperreduction/S_OPT.h | 2 +- 23 files changed, 192 insertions(+), 218 deletions(-) diff --git a/examples/dmd/de_dg_advection_greedy.cpp b/examples/dmd/de_dg_advection_greedy.cpp index 677720fc8..32ae28880 100644 --- a/examples/dmd/de_dg_advection_greedy.cpp +++ b/examples/dmd/de_dg_advection_greedy.cpp @@ -619,8 +619,7 @@ double simulation() CAROM::getParametricDMD(dmd_U, param_vectors, dmd_paths, desired_param, "G", "LS", closest_rbf_val); - dmd_U->projectInitialCondition(init); - + dmd_U->projectInitialCondition(*init); dmd_training_timer.Stop(); @@ -722,7 +721,7 @@ double simulation() dmd_U = new CAROM::DMD(dmd_paths[0]); } - dmd_U->projectInitialCondition(init); + dmd_U->projectInitialCondition(*init); dmd_training_timer.Stop(); @@ -871,7 +870,7 @@ double simulation() CAROM::getParametricDMD(dmd_U, param_vectors, dmd_paths, desired_param, "G", "LS", closest_rbf_val); - dmd_U->projectInitialCondition(init); + dmd_U->projectInitialCondition(*init); dmd_training_timer.Stop(); } @@ -927,9 +926,8 @@ double simulation() if (myid == 0) { - std::cout << "Rel. diff. of DMD temp. (u) at t_final at f_factor " << f_factor - << ": " - << rel_diff << std::endl; + std::cout << "Rel. diff. of DMD temp. (u) at t_final at f_factor " + << f_factor << ": " << rel_diff << std::endl; } if (myid == 0) diff --git a/examples/dmd/de_parametric_heat_conduction_greedy.cpp b/examples/dmd/de_parametric_heat_conduction_greedy.cpp index 21dd8ca88..8d2eeabbd 100644 --- a/examples/dmd/de_parametric_heat_conduction_greedy.cpp +++ b/examples/dmd/de_parametric_heat_conduction_greedy.cpp @@ -456,7 +456,7 @@ double simulation() dmd_u = new CAROM::DMD(dmd_paths[0]); } - dmd_u->projectInitialCondition(init); + dmd_u->projectInitialCondition(*init); dmd_training_timer.Stop(); @@ -614,7 +614,7 @@ double simulation() CAROM::getParametricDMD(dmd_u, param_vectors, dmd_paths, desired_param, "G", "LS", closest_rbf_val); - dmd_u->projectInitialCondition(init); + dmd_u->projectInitialCondition(*init); dmd_training_timer.Stop(); } diff --git a/examples/dmd/local_dw_csv.cpp b/examples/dmd/local_dw_csv.cpp index 807084842..01714c137 100644 --- a/examples/dmd/local_dw_csv.cpp +++ b/examples/dmd/local_dw_csv.cpp @@ -702,7 +702,7 @@ int main(int argc, char *argv[]) { init_cond->item(i) = sample[i]; } - dmd[curr_window]->projectInitialCondition(init_cond.get(), tval); + dmd[curr_window]->projectInitialCondition(*init_cond, tval); dmd_preprocess_timer.Stop(); } else @@ -792,7 +792,7 @@ int main(int argc, char *argv[]) } init_cond = dmd[curr_window]->predict(t_offset); - dmd[curr_window+1]->projectInitialCondition(init_cond.get(), t_offset); + dmd[curr_window+1]->projectInitialCondition(*init_cond, t_offset); curr_window += 1; result = dmd[curr_window]->predict(tval); diff --git a/examples/dmd/parametric_dw_csv.cpp b/examples/dmd/parametric_dw_csv.cpp index c33982dff..854a5ec51 100644 --- a/examples/dmd/parametric_dw_csv.cpp +++ b/examples/dmd/parametric_dw_csv.cpp @@ -747,7 +747,7 @@ int main(int argc, char *argv[]) { init_cond->item(i) = sample[i]; } - dmd[idx_dataset][curr_window]->projectInitialCondition(init_cond.get(), tval); + dmd[idx_dataset][curr_window]->projectInitialCondition(*init_cond, tval); dmd_preprocess_timer.Stop(); } else @@ -806,7 +806,7 @@ int main(int argc, char *argv[]) } init_cond = dmd[idx_dataset][curr_window]->predict(t_offset); - dmd[idx_dataset][curr_window+1]->projectInitialCondition(init_cond.get(), + dmd[idx_dataset][curr_window+1]->projectInitialCondition(*init_cond, t_offset); curr_window += 1; diff --git a/examples/dmd/parametric_heat_conduction.cpp b/examples/dmd/parametric_heat_conduction.cpp index 9a3aa75e4..7424afe2f 100644 --- a/examples/dmd/parametric_heat_conduction.cpp +++ b/examples/dmd/parametric_heat_conduction.cpp @@ -777,7 +777,7 @@ int main(int argc, char *argv[]) CAROM::getParametricDMD(dmd_u, param_vectors, dmd_paths, desired_param, "G", "LS", closest_rbf_val); - dmd_u->projectInitialCondition(init); + dmd_u->projectInitialCondition(*init); dmd_training_timer.Stop(); } diff --git a/examples/dmd/parametric_tw_csv.cpp b/examples/dmd/parametric_tw_csv.cpp index 8dc33063e..80f724da5 100644 --- a/examples/dmd/parametric_tw_csv.cpp +++ b/examples/dmd/parametric_tw_csv.cpp @@ -784,7 +784,7 @@ int main(int argc, char *argv[]) } std::shared_ptr init_cond = dmd[idx_dataset][window-1]->predict( indicator_val[window]); - dmd[idx_dataset][window]->projectInitialCondition(init_cond.get()); + dmd[idx_dataset][window]->projectInitialCondition(*init_cond); } // Make a directory for this window, only on the first parameter. @@ -1012,7 +1012,7 @@ int main(int argc, char *argv[]) { init_cond = dmd[idx_dataset][window-1]->predict(indicator_val[window]); } - dmd[idx_dataset][window]->projectInitialCondition(init_cond.get()); + dmd[idx_dataset][window]->projectInitialCondition(*init_cond); const double norm_init_cond = init_cond->norm(); if (myid == 0) diff --git a/examples/dmd/wave_equation.cpp b/examples/dmd/wave_equation.cpp index a05bf9205..fe925e89a 100644 --- a/examples/dmd/wave_equation.cpp +++ b/examples/dmd/wave_equation.cpp @@ -630,7 +630,7 @@ int main(int argc, char *argv[]) { result_u = dmd_u[curr_window]->predict(ts[i]); cout << "Projecting solution for new window at " << ts[i] << endl; - dmd_u[curr_window+1]->projectInitialCondition(result_u.get(), ts[i]); + dmd_u[curr_window+1]->projectInitialCondition(*result_u, ts[i]); } delete dmd_u[curr_window]; curr_window++; diff --git a/lib/algo/AdaptiveDMD.cpp b/lib/algo/AdaptiveDMD.cpp index 4609f1583..22b5cf95b 100644 --- a/lib/algo/AdaptiveDMD.cpp +++ b/lib/algo/AdaptiveDMD.cpp @@ -20,10 +20,8 @@ namespace CAROM { AdaptiveDMD::AdaptiveDMD(int dim, double desired_dt, std::string rbf, - std::string interp_method, - double closest_rbf_val, - bool alt_output_basis, - Vector* state_offset) : + std::string interp_method, double closest_rbf_val, + bool alt_output_basis, std::shared_ptr state_offset) : DMD(dim, alt_output_basis, state_offset) { CAROM_VERIFY(rbf == "G" || rbf == "IQ" || rbf == "IMQ"); diff --git a/lib/algo/AdaptiveDMD.h b/lib/algo/AdaptiveDMD.h index 85668a5df..a74fb383f 100644 --- a/lib/algo/AdaptiveDMD.h +++ b/lib/algo/AdaptiveDMD.h @@ -54,10 +54,9 @@ class AdaptiveDMD : public DMD * @param[in] state_offset The state offset. */ AdaptiveDMD(int dim, double desired_dt = -1.0, std::string rbf = "G", - std::string interp_method = "LS", - double closest_rbf_val = 0.9, + std::string interp_method = "LS", double closest_rbf_val = 0.9, bool alt_output_basis = false, - Vector* state_offset = NULL); + std::shared_ptr state_offset = nullptr); /** * @brief Destroy the AdaptiveDMD object diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index 26270de82..fd0d1546c 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -43,7 +43,7 @@ extern "C" { namespace CAROM { -DMD::DMD(int dim, bool alt_output_basis, Vector* state_offset) +DMD::DMD(int dim, bool alt_output_basis, std::shared_ptr state_offset) { CAROM_VERIFY(dim > 0); @@ -63,7 +63,8 @@ DMD::DMD(int dim, bool alt_output_basis, Vector* state_offset) setOffset(state_offset, 0); } -DMD::DMD(int dim, double dt, bool alt_output_basis, Vector* state_offset) +DMD::DMD(int dim, double dt, bool alt_output_basis, + std::shared_ptr state_offset) { CAROM_VERIFY(dim > 0); CAROM_VERIFY(dt > 0.0); @@ -102,10 +103,10 @@ DMD::DMD(std::string base_file_name) load(base_file_name); } -DMD::DMD(std::vector> eigs, - std::shared_ptr phi_real, - std::shared_ptr phi_imaginary, int k, - double dt, double t_offset, Vector* state_offset) +DMD::DMD(std::vector> & eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, int k, + double dt, double t_offset, std::shared_ptr & state_offset) { // Get the rank of this process, and the number of processors. int mpi_init; @@ -128,12 +129,7 @@ DMD::DMD(std::vector> eigs, setOffset(state_offset, 0); } -DMD::~DMD() -{ - delete d_state_offset; -} - -void DMD::setOffset(Vector* offset_vector, int order) +void DMD::setOffset(std::shared_ptr & offset_vector, int order) { if (order == 0) { @@ -487,10 +483,10 @@ DMD::constructDMD(const Matrix & f_snapshots, struct DMDInternal dmd_internal = {f_snapshots_in, f_snapshots_out, d_basis.get(), d_basis_right, d_S_inv, &eigenpair}; computePhi(dmd_internal); - Vector* init = new Vector(f_snapshots_in->numRows(), true); - for (int i = 0; i < init->dim(); i++) + Vector init(f_snapshots_in->numRows(), true); + for (int i = 0; i < init.dim(); i++) { - init->item(i) = f_snapshots_in->item(i, 0); + init(i) = f_snapshots_in->item(i, 0); } // Calculate pinv(d_phi) * initial_condition. @@ -504,13 +500,12 @@ DMD::constructDMD(const Matrix & f_snapshots, delete f_snapshots_out; delete eigenpair.ev_real; delete eigenpair.ev_imaginary; - delete init; release_context(&svd_input); } void -DMD::projectInitialCondition(const Vector* init, double t_offset) +DMD::projectInitialCondition(const Vector & init, double t_offset) { d_phi_real_squared_inverse = d_phi_real->transposeMult(*d_phi_real); std::unique_ptr d_phi_real_squared_2 = d_phi_imaginary->transposeMult( @@ -575,8 +570,8 @@ DMD::projectInitialCondition(const Vector* init, double t_offset) } } - std::unique_ptr rhs_real = d_phi_real->transposeMult(*init); - std::unique_ptr rhs_imaginary = d_phi_imaginary->transposeMult(*init); + std::unique_ptr rhs_real = d_phi_real->transposeMult(init); + std::unique_ptr rhs_imaginary = d_phi_imaginary->transposeMult(init); std::unique_ptr d_projected_init_real_1 = d_phi_real_squared_inverse->mult(*rhs_real); @@ -795,7 +790,7 @@ DMD::load(std::string base_file_name) full_file_name = base_file_name + "_state_offset"; if (Utilities::file_exist(full_file_name + ".000000")) { - d_state_offset = new Vector(); + d_state_offset.reset(new Vector()); d_state_offset->read(full_file_name); } @@ -885,7 +880,7 @@ DMD::save(std::string base_file_name) full_file_name = base_file_name + "_projected_init_imaginary"; d_projected_init_imaginary->write(full_file_name); - if (d_state_offset != NULL) + if (d_state_offset != nullptr) { full_file_name = base_file_name + "_state_offset"; d_state_offset->write(full_file_name); diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index 30cd4a1f9..e164a0f0d 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -81,7 +81,7 @@ class DMD * @param[in] state_offset The state offset. */ DMD(int dim, double dt, bool alt_output_basis = false, - Vector* state_offset = NULL); + std::shared_ptr state_offset = nullptr); /** * @brief Constructor. DMD from saved models. @@ -94,12 +94,12 @@ class DMD /** * @brief Destroy the DMD object */ - virtual ~DMD(); + virtual ~DMD() { }; /** * @brief Set the offset of a certain order. */ - virtual void setOffset(Vector* offset_vector, int order); + virtual void setOffset(std::shared_ptr & offset_vector, int order); /** * @brief Sample the new state, u_in. Any samples in d_snapshots @@ -142,7 +142,7 @@ class DMD * @param[in] init The initial condition. * @param[in] t_offset The initial time offset. */ - void projectInitialCondition(const Vector* init, double t_offset = -1.0); + void projectInitialCondition(const Vector & init, double t_offset = -1.0); /** * @brief Predict state given a time. Uses the projected initial condition of the @@ -253,7 +253,8 @@ class DMD * output, i.e. phi = U^(+)*V*Omega^(-1)*X. * @param[in] state_offset The state offset. */ - DMD(int dim, bool alt_output_basis = false, Vector* state_offset = NULL); + DMD(int dim, bool alt_output_basis = false, + std::shared_ptr state_offset = nullptr); /** * @brief Constructor. Specified from DMD components. @@ -266,9 +267,10 @@ class DMD * @param[in] t_offset d_t_offset * @param[in] state_offset d_state_offset */ - DMD(std::vector> eigs, std::shared_ptr phi_real, - std::shared_ptr phi_imaginary, int k, - double dt, double t_offset, Vector* state_offset); + DMD(std::vector> & eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, int k, double dt, + double t_offset, std::shared_ptr & state_offset); /** * @brief Unimplemented default constructor. @@ -367,7 +369,7 @@ class DMD /** * @brief State offset in snapshot. */ - Vector* d_state_offset = NULL; + std::shared_ptr d_state_offset; /** * @brief Whether the DMD has been trained or not. diff --git a/lib/algo/NonuniformDMD.cpp b/lib/algo/NonuniformDMD.cpp index 499bc93fc..3ad46d03f 100644 --- a/lib/algo/NonuniformDMD.cpp +++ b/lib/algo/NonuniformDMD.cpp @@ -16,13 +16,12 @@ namespace CAROM { -NonuniformDMD::NonuniformDMD(int dim, - bool alt_output_basis, - Vector* state_offset, - Vector* derivative_offset) : +NonuniformDMD::NonuniformDMD(int dim, std::shared_ptr state_offset, + std::shared_ptr derivative_offset, + bool alt_output_basis) : DMD(dim, alt_output_basis, state_offset) { - // stateOffset is set by DMD::setOffset in the constructor + // state_offset is set by DMD::setOffset in the constructor setOffset(derivative_offset, 1); } @@ -33,16 +32,17 @@ NonuniformDMD::NonuniformDMD(std::string base_file_name) : DMD(base_file_name) std::string full_file_name = base_file_name + "_derivative_offset"; if (Utilities::file_exist(full_file_name + ".000000")) { - d_derivative_offset = new Vector(); + d_derivative_offset.reset(new Vector()); d_derivative_offset->read(full_file_name); } } -NonuniformDMD::NonuniformDMD(std::vector> eigs, - std::shared_ptr phi_real, - std::shared_ptr phi_imaginary, int k, +NonuniformDMD::NonuniformDMD(std::vector> & eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, int k, double dt, double t_offset, - Vector* state_offset, Vector* derivative_offset) : + std::shared_ptr & state_offset, + std::shared_ptr & derivative_offset) : DMD(eigs, phi_real, phi_imaginary, k, dt, t_offset, state_offset) { @@ -50,12 +50,8 @@ NonuniformDMD::NonuniformDMD(std::vector> eigs, setOffset(derivative_offset, 1); } -NonuniformDMD::~NonuniformDMD() -{ - delete d_derivative_offset; -} - -void NonuniformDMD::setOffset(Vector* offset_vector, int order) +void NonuniformDMD::setOffset(std::shared_ptr & offset_vector, + int order) { if (order == 0) { @@ -143,7 +139,7 @@ NonuniformDMD::load(std::string base_file_name) std::string full_file_name = base_file_name + "_derivative_offset"; if (Utilities::file_exist(full_file_name + ".000000")) { - d_derivative_offset = new Vector(); + d_derivative_offset.reset(new Vector()); d_derivative_offset->read(full_file_name); } diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index 58859236f..096064cbc 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -46,10 +46,9 @@ class NonuniformDMD : public DMD * @param[in] state_offset The state offset. * @param[in] derivative_offset The derivative offset. */ - NonuniformDMD(int dim, - bool alt_output_basis = false, - Vector* state_offset = NULL, - Vector* derivative_offset = NULL); + NonuniformDMD(int dim, std::shared_ptr state_offset = nullptr, + std::shared_ptr derivative_offset = nullptr, + bool alt_output_basis = false); /** * @brief Constructor. @@ -59,15 +58,10 @@ class NonuniformDMD : public DMD */ NonuniformDMD(std::string base_file_name); - /** - * @brief Destroy the NonuniformDMD object - */ - ~NonuniformDMD(); - /** * @brief Set the offset of a certain order. */ - void setOffset(Vector* offset_vector, int order) override; + void setOffset(std::shared_ptr & offset_vector, int order) override; /** * @brief Load the object state to a file. @@ -127,11 +121,12 @@ class NonuniformDMD : public DMD * @param[in] state_offset d_state_offset * @param[in] derivative_offset d_derivative_offset */ - NonuniformDMD(std::vector> eigs, - std::shared_ptr phi_real, - std::shared_ptr phi_imaginary, int k, + NonuniformDMD(std::vector> & eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, int k, double dt, double t_offset, - Vector* state_offset, Vector* derivative_offset); + std::shared_ptr & state_offset, + std::shared_ptr & derivative_offset); private: @@ -177,8 +172,7 @@ class NonuniformDMD : public DMD /** * @brief Derivative offset in snapshot. */ - Vector* d_derivative_offset = NULL; - + std::shared_ptr d_derivative_offset; }; } diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index b428edb93..0c2c82aa0 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -22,7 +22,8 @@ class SnapshotDMD : public DMD * @param[in] state_offset The state offset. */ SnapshotDMD(int dim, double dt, bool alt_output_basis = false, - Vector* state_offset = NULL) : DMD(dim,dt,alt_output_basis,state_offset) {} + std::shared_ptr state_offset = nullptr) : + DMD(dim, dt, alt_output_basis, state_offset) {} /** * @brief Constructor. DMD from saved models. Inherited directly @@ -121,7 +122,7 @@ class SnapshotDMD : public DMD SnapshotDMD(std::vector> eigs, std::shared_ptr phi_real, std::shared_ptr phi_imaginary, int k, double dt, - double t_offset, Vector* state_offset) : + double t_offset, std::shared_ptr & state_offset) : DMD(eigs, phi_real, phi_imaginary, k, dt, t_offset, state_offset) {} private: diff --git a/lib/hyperreduction/DEIM.cpp b/lib/hyperreduction/DEIM.cpp index 21e6231c9..c738a8686 100644 --- a/lib/hyperreduction/DEIM.cpp +++ b/lib/hyperreduction/DEIM.cpp @@ -26,7 +26,7 @@ using namespace std; namespace CAROM { void -DEIM(const Matrix* f_basis, +DEIM(const Matrix & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, @@ -79,14 +79,14 @@ DEIM(const Matrix* f_basis, // Get the number of basis vectors and the size of each basis vector. CAROM_VERIFY(0 < num_f_basis_vectors_used - && num_f_basis_vectors_used <= f_basis->numColumns()); + && num_f_basis_vectors_used <= f_basis.numColumns()); int num_basis_vectors = - std::min(num_f_basis_vectors_used, f_basis->numColumns()); + std::min(num_f_basis_vectors_used, f_basis.numColumns()); CAROM_VERIFY(num_basis_vectors == f_sampled_row.size()); CAROM_VERIFY(num_basis_vectors == f_basis_sampled_inv.numRows() && num_basis_vectors == f_basis_sampled_inv.numColumns()); CAROM_VERIFY(!f_basis_sampled_inv.distributed()); - int basis_size = f_basis->numRows(); + int basis_size = f_basis.numRows(); // The small matrix inverted by the algorithm. We'll allocate the largest // matrix we'll need and set its size at each step in the algorithm. @@ -107,7 +107,7 @@ DEIM(const Matrix* f_basis, f_bv_max_local.row_val = -1.0; f_bv_max_local.proc = myid; for (int i = 0; i < basis_size; ++i) { - double f_bv_val = fabs(f_basis->item(i, 0)); + double f_bv_val = fabs(f_basis(i, 0)); if (f_bv_val > f_bv_max_local.row_val) { f_bv_max_local.row_val = f_bv_val; f_bv_max_local.row = i; @@ -119,14 +119,14 @@ DEIM(const Matrix* f_basis, // Now get the first sampled row of the basis of the RHS. if (f_bv_max_global.proc == myid) { for (int j = 0; j < num_basis_vectors; ++j) { - c[j] = f_basis->item(f_bv_max_global.row, j); + c[j] = f_basis(f_bv_max_global.row, j); } } MPI_Bcast(c, num_basis_vectors, MPI_DOUBLE, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the first sampled row of the basis of the RHS to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - tmp_fs.item(0, j) = c[j]; + tmp_fs(0, j) = c[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = 0; @@ -139,7 +139,7 @@ DEIM(const Matrix* f_basis, M.setSize(i, i); for (int row = 0; row < i; ++row) { for (int col = 0; col < i; ++col) { - M.item(row, col) = tmp_fs.item(row, col); + M(row, col) = tmp_fs(row, col); } } @@ -151,7 +151,7 @@ DEIM(const Matrix* f_basis, for (int minv_row = 0; minv_row < i; ++minv_row) { double tmp = 0.0; for (int minv_col = 0; minv_col < i; ++minv_col) { - tmp += M.item(minv_row, minv_col)*tmp_fs.item(minv_col, i); + tmp += M(minv_row, minv_col)*tmp_fs(minv_col, i); } c[minv_row] = tmp; } @@ -165,9 +165,9 @@ DEIM(const Matrix* f_basis, for (int F_row = 0; F_row < basis_size; ++F_row) { double tmp = 0.0; for (int F_col = 0; F_col < i; ++F_col) { - tmp += f_basis->item(F_row, F_col)*c[F_col]; + tmp += f_basis(F_row, F_col)*c[F_col]; } - double r_val = fabs(f_basis->item(F_row, i) - tmp); + double r_val = fabs(f_basis(F_row, i) - tmp); if (r_val > f_bv_max_local.row_val) { f_bv_max_local.row_val = r_val; f_bv_max_local.row = F_row; @@ -179,14 +179,14 @@ DEIM(const Matrix* f_basis, // Now get the next sampled row of the basis of f. if (f_bv_max_global.proc == myid) { for (int j = 0; j < num_basis_vectors; ++j) { - c[j] = f_basis->item(f_bv_max_global.row, j); + c[j] = f_basis(f_bv_max_global.row, j); } } MPI_Bcast(c, num_basis_vectors, MPI_DOUBLE, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the ith sampled row of the basis of the RHS to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - tmp_fs.item(i, j) = c[j]; + tmp_fs(i, j) = c[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = i; @@ -206,7 +206,7 @@ DEIM(const Matrix* f_basis, f_sampled_row[idx] = this_f_row; int tmp_fs_row = this_proc_f_row_to_tmp_fs_row[this_f_row]; for (int col = 0; col < num_f_basis_cols; ++col) { - f_basis_sampled_inv.item(idx, col) = tmp_fs.item(tmp_fs_row, col); + f_basis_sampled_inv(idx, col) = tmp_fs(tmp_fs_row, col); } ++idx; } diff --git a/lib/hyperreduction/DEIM.h b/lib/hyperreduction/DEIM.h index b8b14425b..849511b9b 100644 --- a/lib/hyperreduction/DEIM.h +++ b/lib/hyperreduction/DEIM.h @@ -41,7 +41,7 @@ class Matrix; * @param[in] num_procs The total number of processes. */ void -DEIM(const Matrix* f_basis, +DEIM(const Matrix & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/GNAT.cpp b/lib/hyperreduction/GNAT.cpp index f304fb21d..e3901d32b 100644 --- a/lib/hyperreduction/GNAT.cpp +++ b/lib/hyperreduction/GNAT.cpp @@ -24,7 +24,7 @@ namespace CAROM { -void GNAT(const Matrix* f_basis, +void GNAT(const Matrix & f_basis, const int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, @@ -81,18 +81,18 @@ void GNAT(const Matrix* f_basis, // Get the number of basis vectors and the size of each basis vector. CAROM_VERIFY(0 < num_f_basis_vectors_used - && num_f_basis_vectors_used <= f_basis->numColumns()); + && num_f_basis_vectors_used <= f_basis.numColumns()); const int num_basis_vectors = - std::min(num_f_basis_vectors_used, f_basis->numColumns()); + std::min(num_f_basis_vectors_used, f_basis.numColumns()); const int num_samples = num_samples_req > 0 ? num_samples_req : num_basis_vectors; CAROM_VERIFY(num_basis_vectors <= num_samples - && num_samples <= f_basis->numDistributedRows()); + && num_samples <= f_basis.numDistributedRows()); CAROM_VERIFY(num_samples == f_sampled_row.size()); CAROM_VERIFY(num_samples == f_basis_sampled_inv.numRows() && num_basis_vectors == f_basis_sampled_inv.numColumns()); CAROM_VERIFY(!f_basis_sampled_inv.distributed()); - const int basis_size = f_basis->numRows(); + const int basis_size = f_basis.numRows(); const int ns_mod_nr = num_samples % num_basis_vectors; int ns = 0; @@ -162,7 +162,7 @@ void GNAT(const Matrix* f_basis, std::set::const_iterator found = proc_sampled_f_row[myid].find(i); if (found == proc_sampled_f_row[myid].end()) // not found { - double f_bv_val = fabs(f_basis->item(i, 0)); + double f_bv_val = fabs(f_basis(i, 0)); if (f_bv_val > f_bv_max_local.row_val) { f_bv_max_local.row_val = f_bv_val; f_bv_max_local.row = i; @@ -177,14 +177,14 @@ void GNAT(const Matrix* f_basis, // Now get the first sampled row of the basis of the RHS. if (f_bv_max_global.proc == myid) { for (int j = 0; j < num_basis_vectors; ++j) { - sampled_row[j] = f_basis->item(f_bv_max_global.row, j); + sampled_row[j] = f_basis(f_bv_max_global.row, j); } } MPI_Bcast(sampled_row, num_basis_vectors, MPI_DOUBLE, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the first sampled row of the basis of the RHS to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - tmp_fs.item(k, j) = sampled_row[j]; + tmp_fs(k, j) = sampled_row[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = k; @@ -202,7 +202,7 @@ void GNAT(const Matrix* f_basis, M.setSize(ns, i); for (int row = 0; row < ns; ++row) { for (int col = 0; col < i; ++col) { - M.item(row, col) = tmp_fs.item(row, col); + M(row, col) = tmp_fs(row, col); } } @@ -216,12 +216,12 @@ void GNAT(const Matrix* f_basis, for (int minv_col = 0; minv_col < ns; ++minv_col) { if (ns == i) { - tmp += M.item(minv_row, minv_col)*tmp_fs.item(minv_col, i); + tmp += M(minv_row, minv_col)*tmp_fs(minv_col, i); } else { // Transposing M^+, which is stored as its transpose. - tmp += M.item(minv_col, minv_row)*tmp_fs.item(minv_col, i); + tmp += M(minv_col, minv_row)*tmp_fs(minv_col, i); } } c[minv_row] = tmp; @@ -256,9 +256,9 @@ void GNAT(const Matrix* f_basis, { double tmp = 0.0; for (int F_col = 0; F_col < i; ++F_col) { - tmp += f_basis->item(F_row, F_col)*c[F_col]; + tmp += f_basis(F_row, F_col)*c[F_col]; } - const double r_val = fabs(f_basis->item(F_row, i) - tmp); + const double r_val = fabs(f_basis(F_row, i) - tmp); if (r_val > f_bv_max_local.row_val) { f_bv_max_local.row_val = r_val; @@ -274,14 +274,14 @@ void GNAT(const Matrix* f_basis, // Now get the next sampled row of the basis of f. if (f_bv_max_global.proc == myid) { for (int j = 0; j < num_basis_vectors; ++j) { - sampled_row[j] = f_basis->item(f_bv_max_global.row, j); + sampled_row[j] = f_basis(f_bv_max_global.row, j); } } MPI_Bcast(sampled_row, num_basis_vectors, MPI_DOUBLE, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the ith sampled row of the basis of the RHS to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - tmp_fs.item(ns+k, j) = sampled_row[j]; + tmp_fs(ns+k, j) = sampled_row[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = ns+k; @@ -306,7 +306,7 @@ void GNAT(const Matrix* f_basis, f_sampled_row[idx] = this_f_row; int tmp_fs_row = this_proc_f_row_to_tmp_fs_row[this_f_row]; for (int col = 0; col < num_f_basis_cols; ++col) { - f_basis_sampled_inv.item(idx, col) = tmp_fs.item(tmp_fs_row, col); + f_basis_sampled_inv(idx, col) = tmp_fs(tmp_fs_row, col); } ++idx; } diff --git a/lib/hyperreduction/GNAT.h b/lib/hyperreduction/GNAT.h index bfbd60e2e..7d7788671 100644 --- a/lib/hyperreduction/GNAT.h +++ b/lib/hyperreduction/GNAT.h @@ -45,7 +45,7 @@ class Matrix; * @param[in] init_samples Samples to initialize the GNAT algorithm. */ void -GNAT(const Matrix* f_basis, +GNAT(const Matrix & f_basis, const int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/Hyperreduction.cpp b/lib/hyperreduction/Hyperreduction.cpp index 8b7461c92..55b4c0e16 100644 --- a/lib/hyperreduction/Hyperreduction.cpp +++ b/lib/hyperreduction/Hyperreduction.cpp @@ -42,7 +42,7 @@ void Hyperreduction::ComputeSamples(const std::shared_ptr f_basis, { case deim: CAROM_VERIFY(num_samples_req == f_basis->numColumns()); - DEIM(f_basis.get(), + DEIM(*f_basis, num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, @@ -50,7 +50,7 @@ void Hyperreduction::ComputeSamples(const std::shared_ptr f_basis, myid, num_procs); return; case gnat: - GNAT(f_basis.get(), + GNAT(*f_basis, num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, @@ -60,7 +60,7 @@ void Hyperreduction::ComputeSamples(const std::shared_ptr f_basis, init_samples); return; case qdeim: - QDEIM(f_basis.get(), + QDEIM(*f_basis, num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, @@ -69,7 +69,7 @@ void Hyperreduction::ComputeSamples(const std::shared_ptr f_basis, num_samples_req); return; case sopt: - S_OPT(f_basis, + S_OPT(*f_basis, num_f_basis_vectors_used, f_sampled_row, f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/QDEIM.cpp b/lib/hyperreduction/QDEIM.cpp index 7e2527b87..6f05c33b7 100644 --- a/lib/hyperreduction/QDEIM.cpp +++ b/lib/hyperreduction/QDEIM.cpp @@ -22,7 +22,7 @@ namespace CAROM { void -QDEIM(const Matrix* f_basis, +QDEIM(const Matrix & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, @@ -38,31 +38,31 @@ QDEIM(const Matrix* f_basis, // sampled rows of the basis of the RHS. // The QR implementation uses the entire matrix. - CAROM_VERIFY(num_f_basis_vectors_used == f_basis->numColumns()); - CAROM_VERIFY(f_basis->numColumns() <= num_samples_req - && num_samples_req <= f_basis->numDistributedRows()); + CAROM_VERIFY(num_f_basis_vectors_used == f_basis.numColumns()); + CAROM_VERIFY(f_basis.numColumns() <= num_samples_req + && num_samples_req <= f_basis.numDistributedRows()); CAROM_VERIFY(num_samples_req == f_basis_sampled_inv.numRows() - && f_basis->numColumns() == f_basis_sampled_inv.numColumns()); + && f_basis.numColumns() == f_basis_sampled_inv.numColumns()); CAROM_VERIFY(num_samples_req == f_sampled_row.size()); CAROM_VERIFY(!f_basis_sampled_inv.distributed()); // QR will determine (numCol) pivots, which will define the first (numCol) samples. - const int numCol = f_basis->numColumns(); + const int numCol = f_basis.numColumns(); const int num_samples_req_QR = numCol; std::vector sampled_row_data; if (myid == 0) sampled_row_data.resize(num_samples_req * numCol); std::vector f_sampled_row_owner((myid == 0 - && f_basis->distributed()) ? num_samples_req : 0); + && f_basis.distributed()) ? num_samples_req : 0); // QDEIM computes selection/interpolation indices by taking a // column-pivoted QR-decomposition of the transpose of its input matrix. - f_basis->qrcp_pivots_transpose(f_sampled_row.data(), - f_sampled_row_owner.data(), - num_samples_req_QR); + f_basis.qrcp_pivots_transpose(f_sampled_row.data(), + f_sampled_row_owner.data(), + num_samples_req_QR); - if (f_basis->distributed()) + if (f_basis.distributed()) { // Gather the sampled rows to root process in sampled_row_data @@ -129,7 +129,7 @@ QDEIM(const Matrix* f_basis, my_sampled_rows.data(), count, MPI_INT, 0, MPI_COMM_WORLD); std::vector row_offset(num_procs); - row_offset[myid] = f_basis->numRows(); + row_offset[myid] = f_basis.numRows(); CAROM_VERIFY(MPI_Allgather(MPI_IN_PLACE, 1, MPI_INT, row_offset.data(), 1, MPI_INT, MPI_COMM_WORLD) == MPI_SUCCESS); @@ -145,13 +145,13 @@ QDEIM(const Matrix* f_basis, { const int msr = my_sampled_rows[i]; const bool mycond = my_sampled_rows[i] >= row_offset[myid] - && my_sampled_rows[i] < row_offset[myid] + f_basis->numRows(); + && my_sampled_rows[i] < row_offset[myid] + f_basis.numRows(); CAROM_VERIFY(my_sampled_rows[i] >= row_offset[myid] - && my_sampled_rows[i] < row_offset[myid] + f_basis->numRows()); + && my_sampled_rows[i] < row_offset[myid] + f_basis.numRows()); const int row = my_sampled_rows[i] - row_offset[myid]; os = i*numCol; for (int j=0; jitem(row, j); + my_sampled_row_data[os + j] = f_basis(row, j); } if (myid == 0) @@ -167,7 +167,7 @@ QDEIM(const Matrix* f_basis, sampled_row_data.data(), ns.data(), disp.data(), MPI_DOUBLE, 0, MPI_COMM_WORLD); - const int nf = f_basis->numRows(); + const int nf = f_basis.numRows(); std::vector rcnt(num_procs); std::vector rdsp(num_procs); @@ -246,9 +246,9 @@ QDEIM(const Matrix* f_basis, MPI_Bcast(V.getData(), n*n, MPI_DOUBLE, 0, MPI_COMM_WORLD); // Set Ubt = U * V = (V' * U')' - std::unique_ptr Ubt = f_basis->mult(V); // distributed + std::unique_ptr Ubt = f_basis.mult(V); // distributed - CAROM_VERIFY(Ubt->distributed() && Ubt->numRows() == f_basis->numRows() + CAROM_VERIFY(Ubt->distributed() && Ubt->numRows() == f_basis.numRows() && Ubt->numColumns() == n); std::vector r(nf); @@ -324,7 +324,7 @@ QDEIM(const Matrix* f_basis, if (sample > -1) { CAROM_VERIFY(sample >= row_offset[myid]); - MPI_Send(f_basis->getData() + ((sample - row_offset[myid]) * numCol), + MPI_Send(f_basis.getData() + ((sample - row_offset[myid]) * numCol), numCol, MPI_DOUBLE, 0, tagSendRecv, MPI_COMM_WORLD); } @@ -385,7 +385,7 @@ QDEIM(const Matrix* f_basis, for (int j=0; jitem(f_sampled_row[i], j); + f_basis_sampled_inv(i, j) = f_basis(f_sampled_row[i], j); } } f_sampled_rows_per_proc[0] = numCol; } - if (!f_basis->distributed()) + if (!f_basis.distributed()) { // GappyPOD+E not implemented for oversampling if not distributed CAROM_VERIFY(numCol == num_samples_req); diff --git a/lib/hyperreduction/QDEIM.h b/lib/hyperreduction/QDEIM.h index d0b245b6c..c56545a61 100644 --- a/lib/hyperreduction/QDEIM.h +++ b/lib/hyperreduction/QDEIM.h @@ -48,7 +48,7 @@ class Matrix; * @param[in] num_samples_req The minimum number of samples required. */ void -QDEIM(const Matrix* f_basis, +QDEIM(const Matrix & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/S_OPT.cpp b/lib/hyperreduction/S_OPT.cpp index 932ca5207..7bb3a884b 100644 --- a/lib/hyperreduction/S_OPT.cpp +++ b/lib/hyperreduction/S_OPT.cpp @@ -27,7 +27,7 @@ using namespace std; namespace CAROM { void -S_OPT(const std::shared_ptr f_basis, +S_OPT(const Matrix & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, @@ -83,41 +83,37 @@ S_OPT(const std::shared_ptr f_basis, // Get the number of basis vectors and the size of each basis vector. CAROM_VERIFY(0 < num_f_basis_vectors_used - && num_f_basis_vectors_used <= f_basis->numColumns()); + && num_f_basis_vectors_used <= f_basis.numColumns()); const int num_basis_vectors = - std::min(num_f_basis_vectors_used, f_basis->numColumns()); + std::min(num_f_basis_vectors_used, f_basis.numColumns()); const int num_samples = num_samples_req > 0 ? num_samples_req : num_basis_vectors; CAROM_VERIFY(num_basis_vectors <= num_samples - && num_samples <= f_basis->numDistributedRows()); + && num_samples <= f_basis.numDistributedRows()); CAROM_VERIFY(num_samples == f_sampled_row.size()); CAROM_VERIFY(num_samples == f_basis_sampled_inv.numRows() && num_basis_vectors == f_basis_sampled_inv.numColumns()); CAROM_VERIFY(!f_basis_sampled_inv.distributed()); - int num_rows = f_basis->numRows(); + int num_rows = f_basis.numRows(); // If num_basis_vectors is less than the number of columns of the basis, // we need to truncate the basis. - std::shared_ptr f_basis_truncated; - if (num_basis_vectors < f_basis->numColumns()) + std::shared_ptr f_basis_truncated_N; + const Matrix *f_basis_truncated = &f_basis; + if (num_basis_vectors < f_basis.numColumns()) { - f_basis_truncated = f_basis->getFirstNColumns(num_basis_vectors); - } - else - { - f_basis_truncated = f_basis; + f_basis_truncated_N = f_basis.getFirstNColumns(num_basis_vectors); + f_basis_truncated = f_basis_truncated_N.get(); } - std::shared_ptr Vo; + std::shared_ptr Vo_qr; + const Matrix *Vo = f_basis_truncated; // Use the QR factorization of the input matrix, if requested if (qr_factorize) { - Vo = f_basis_truncated->qr_factorize(); - } - else - { - Vo = f_basis_truncated; + Vo_qr = f_basis_truncated->qr_factorize(); + Vo = Vo_qr.get(); } int num_samples_obtained = 0; @@ -164,7 +160,7 @@ S_OPT(const std::shared_ptr f_basis, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the first sampled row of the basis to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - V1.item(num_samples_obtained, j) = c[j]; + V1(num_samples_obtained, j) = c[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = @@ -195,7 +191,7 @@ S_OPT(const std::shared_ptr f_basis, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the first sampled row of the basis to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - V1.item(0, j) = c[j]; + V1(0, j) = c[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = 0; @@ -204,15 +200,15 @@ S_OPT(const std::shared_ptr f_basis, if (num_samples_obtained < num_samples) { - Vector* A = new Vector(num_rows, f_basis->distributed()); - Vector* noM = new Vector(num_rows, f_basis->distributed()); + Vector A(num_rows, f_basis.distributed()); + Vector noM(num_rows, f_basis.distributed()); Matrix A0(num_basis_vectors - 1, num_basis_vectors - 1, false); Matrix V1_last_col(num_basis_vectors - 1, 1, false); - Matrix tt(num_rows, num_basis_vectors - 1, f_basis->distributed()); - Matrix tt1(num_rows, num_basis_vectors - 1, f_basis->distributed()); - Matrix g1(tt.numRows(), tt.numColumns(), f_basis->distributed()); - Matrix GG(tt1.numRows(), tt1.numColumns(), f_basis->distributed()); + Matrix tt(num_rows, num_basis_vectors - 1, f_basis.distributed()); + Matrix tt1(num_rows, num_basis_vectors - 1, f_basis.distributed()); + Matrix g1(tt.numRows(), tt.numColumns(), f_basis.distributed()); + Matrix GG(tt1.numRows(), tt1.numColumns(), f_basis.distributed()); Vector ls_res_first_row(num_basis_vectors - 1, false); Vector nV(num_basis_vectors, false); @@ -231,9 +227,9 @@ S_OPT(const std::shared_ptr f_basis, { for (int k = 0; k < i - 1; k++) { - A0.item(j, k) = V1.item(j, k); + A0(j, k) = V1(j, k); } - V1_last_col.item(j, 0) = V1.item(j, i - 1); + V1_last_col(j, 0) = V1(j, i - 1); } std::unique_ptr atA0 = V1_last_col.transposeMult(A0); @@ -245,7 +241,7 @@ S_OPT(const std::shared_ptr f_basis, { for (int k = 0; k < V1_last_col.numColumns(); k++) { - ata += (V1_last_col.item(j, k) * V1_last_col.item(j, k)); + ata += (V1_last_col(j, k) * V1_last_col(j, k)); } } @@ -254,7 +250,7 @@ S_OPT(const std::shared_ptr f_basis, Matrix* rhs = NULL; if (myid == 0) { - rhs = new Matrix(num_rows + atA0->numRows(), i - 1, f_basis->distributed()); + rhs = new Matrix(num_rows + atA0->numRows(), i - 1, f_basis.distributed()); for (int k = 0; k < rhs->numColumns(); k++) { rhs->item(0, k) = atA0->item(0, k); @@ -269,7 +265,7 @@ S_OPT(const std::shared_ptr f_basis, } else { - rhs = new Matrix(num_rows, i - 1, f_basis->distributed()); + rhs = new Matrix(num_rows, i - 1, f_basis.distributed()); for (int j = 0; j < rhs->numRows(); j++) { for (int k = 0; k < rhs->numColumns(); k++) @@ -286,16 +282,16 @@ S_OPT(const std::shared_ptr f_basis, if (myid == 0) { c_T = new Matrix(ls_res->getData() + ls_res->numColumns(), - ls_res->numRows() - 1, ls_res->numColumns(), f_basis->distributed(), true); + ls_res->numRows() - 1, ls_res->numColumns(), f_basis.distributed(), true); } else { c_T = new Matrix(ls_res->getData(), - ls_res->numRows(), ls_res->numColumns(), f_basis->distributed(), true); + ls_res->numRows(), ls_res->numColumns(), f_basis.distributed(), true); } std::unique_ptr Vo_first_i_columns = Vo->getFirstNColumns(i - 1); - Vector* b = new Vector(num_rows, f_basis->distributed()); + Vector b(num_rows, f_basis.distributed()); for (int j = 0; j < Vo_first_i_columns->numRows(); j++) { double tmp = 1.0; @@ -303,14 +299,14 @@ S_OPT(const std::shared_ptr f_basis, { tmp += (Vo_first_i_columns->item(j, k) * c_T->item(j, k)); } - b->item(j) = tmp; + b(j) = tmp; } for (int j = 0; j < num_rows; j++) { for (int zz = 0; zz < i - 1; zz++) { - tt.item(j, zz) = Vo->item(j, zz) * Vo->item(j, i - 1); + tt(j, zz) = Vo->item(j, zz) * Vo->item(j, i - 1); } } @@ -319,26 +315,26 @@ S_OPT(const std::shared_ptr f_basis, { for (int k = 0; k < g1.numColumns(); k++) { - g1.item(j, k) = atA0->item(0, k) + tt.item(j, k); + g1(j, k) = atA0->item(0, k) + tt(j, k); } } - Vector* g3 = new Vector(num_rows, f_basis->distributed()); + Vector* g3 = new Vector(num_rows, f_basis.distributed()); for (int j = 0; j < c_T->numRows(); j++) { double tmp = 0.0; for (int k = 0; k < c_T->numColumns(); k++) { - tmp += c_T->item(j, k) * g1.item(j, k); + tmp += c_T->item(j, k) * g1(j, k); } - g3->item(j) = tmp / b->item(j); + g3->item(j) = tmp / b(j); } for (int j = 0; j < num_rows; j++) { for (int zz = 0; zz < i - 1; zz++) { - tt1.item(j, zz) = c_T->item(j, zz) * (Vo->item(j, i - 1) - g3->item(j)); + tt1(j, zz) = c_T->item(j, zz) * (Vo->item(j, i - 1) - g3->item(j)); } } @@ -354,53 +350,51 @@ S_OPT(const std::shared_ptr f_basis, MPI_Bcast(c.data(), ls_res->numColumns(), MPI_DOUBLE, 0, MPI_COMM_WORLD); for (int j = 0; j < ls_res->numColumns(); ++j) { - ls_res_first_row.item(j) = c[j]; + ls_res_first_row(j) = c[j]; } GG.setSize(tt1.numRows(), tt1.numColumns()); for (int j = 0; j < GG.numRows(); j++) { for (int k = 0; k < GG.numColumns(); k++) { - GG.item(j, k) = ls_res_first_row.item(k) + tt1.item(j, k); + GG(j, k) = ls_res_first_row(k) + tt1(j, k); } } - for (int j = 0; j < A->dim(); j++) + for (int j = 0; j < A.dim(); j++) { double tmp = 0.0; for (int k = 0; k < g1.numColumns(); k++) { - tmp += g1.item(j, k) * GG.item(j, k); + tmp += g1(j, k) * GG(j, k); } - A->item(j) = std::max(0.0, ata + - (Vo->item(j, i - 1) * Vo->item(j, i - 1)) - tmp); + A(j) = std::max(0.0, ata + + (Vo->item(j, i - 1) * Vo->item(j, i - 1)) - tmp); } nV.setSize(i); for (int j = 0; j < i; j++) { - nV.item(j) = 0.0; + nV(j) = 0.0; for (int k = 0; k < num_samples_obtained; k++) { - nV.item(j) += (V1.item(k, j) * V1.item(k, j)); + nV(j) += (V1(k, j) * V1(k, j)); } } - for (int j = 0; j < noM->dim(); j++) + for (int j = 0; j < noM.dim(); j++) { - noM->item(j) = 0.0; + noM(j) = 0.0; for (int k = 0; k < i; k++) { - noM->item(j) += std::log(nV.item(k) + (Vo->item(j, k) * Vo->item(j, k))); + noM(j) += std::log(nV(k) + (Vo->item(j, k) * Vo->item(j, k))); } } - for (int j = 0; j < A->dim(); j++) + for (int j = 0; j < A.dim(); j++) { - A->item(j) = std::log(fabs(A->item(j))) + std::log(b->item(j)) - noM->item(j); + A(j) = std::log(fabs(A(j))) + std::log(b(j)) - noM(j); } - - delete b; } else { @@ -414,30 +408,30 @@ S_OPT(const std::shared_ptr f_basis, nV.setSize(num_basis_vectors); for (int j = 0; j < num_basis_vectors; j++) { - nV.item(j) = 0.0; + nV(j) = 0.0; for (int k = 0; k < num_samples_obtained; k++) { - nV.item(j) += (V1.item(k, j) * V1.item(k, j)); + nV(j) += (V1(k, j) * V1(k, j)); } } - for (int j = 0; j < noM->dim(); j++) + for (int j = 0; j < noM.dim(); j++) { - noM->item(j) = 0.0; + noM(j) = 0.0; for (int k = 0; k < num_basis_vectors; k++) { - noM->item(j) += std::log(nV.item(k) + (Vo->item(j, k) * Vo->item(j, k))); + noM(j) += std::log(nV(k) + (Vo->item(j, k) * Vo->item(j, k))); } } - for (int j = 0; j < A->dim(); j++) + for (int j = 0; j < A.dim(); j++) { double tmp = 0.0; for (int k = 0; k < Vo->numColumns(); k++) { tmp += Vo->item(j, k) * ls_res->item(j, k); } - A->item(j) = std::log(1 + tmp) - noM->item(j); + A(j) = std::log(1 + tmp) - noM(j); } } @@ -447,7 +441,7 @@ S_OPT(const std::shared_ptr f_basis, if (proc_f_row_to_tmp_fs_row[f_bv_max_local.proc].find(j) == proc_f_row_to_tmp_fs_row[f_bv_max_local.proc].end()) { - double f_bv_val = A->item(j); + double f_bv_val = A(j); if (f_bv_val > f_bv_max_local.row_val) { f_bv_max_local.row_val = f_bv_val; f_bv_max_local.row = j; @@ -466,16 +460,13 @@ S_OPT(const std::shared_ptr f_basis, f_bv_max_global.proc, MPI_COMM_WORLD); // Now add the first sampled row of the basis to tmp_fs. for (int j = 0; j < num_basis_vectors; ++j) { - V1.item(num_samples_obtained, j) = c[j]; + V1(num_samples_obtained, j) = c[j]; } proc_sampled_f_row[f_bv_max_global.proc].insert(f_bv_max_global.row); proc_f_row_to_tmp_fs_row[f_bv_max_global.proc][f_bv_max_global.row] = num_samples_obtained; num_samples_obtained++; } - - delete A; - delete noM; } // Fill f_sampled_row, and f_sampled_rows_per_proc. Unscramble tmp_fs into @@ -492,7 +483,7 @@ S_OPT(const std::shared_ptr f_basis, f_sampled_row[idx] = this_f_row; int tmp_fs_row = this_proc_f_row_to_tmp_fs_row[this_f_row]; for (int col = 0; col < num_f_basis_cols; ++col) { - f_basis_sampled_inv.item(idx, col) = V1.item(tmp_fs_row, col); + f_basis_sampled_inv(idx, col) = V1(tmp_fs_row, col); } ++idx; } diff --git a/lib/hyperreduction/S_OPT.h b/lib/hyperreduction/S_OPT.h index e2268e00a..ab9da8dd7 100644 --- a/lib/hyperreduction/S_OPT.h +++ b/lib/hyperreduction/S_OPT.h @@ -46,7 +46,7 @@ class Matrix; * computation of a QR factorization will be performed. */ void -S_OPT(const std::shared_ptr f_basis, +S_OPT(const Matrix & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, From 23f1b694ba56070a3750d6dd2edcb822edb1a3bf Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Mon, 26 Aug 2024 14:39:07 -0700 Subject: [PATCH 13/19] More removal of raw pointers. --- examples/dmd/de_dg_advection_greedy.cpp | 2 +- .../de_parametric_heat_conduction_greedy.cpp | 2 +- examples/dmd/parametric_dw_csv.cpp | 33 +++++----- .../prom/de_parametric_maxwell_greedy.cpp | 2 +- lib/algo/AdaptiveDMD.cpp | 10 +-- lib/algo/DMD.cpp | 6 +- lib/algo/DMDc.cpp | 13 ++-- lib/algo/DMDc.h | 12 ++-- lib/algo/DifferentialEvolution.h | 2 +- lib/algo/ParametricDMD.h | 2 +- lib/algo/ParametricDMDc.h | 2 +- lib/algo/greedy/GreedyCustomSampler.cpp | 4 +- lib/algo/greedy/GreedyCustomSampler.h | 4 +- lib/algo/greedy/GreedyRandomSampler.cpp | 4 +- lib/algo/greedy/GreedyRandomSampler.h | 4 +- lib/algo/greedy/GreedySampler.cpp | 64 +++++++++---------- lib/algo/greedy/GreedySampler.h | 48 ++++++-------- lib/algo/manifold_interp/Interpolator.cpp | 6 -- lib/algo/manifold_interp/Interpolator.h | 4 +- .../manifold_interp/MatrixInterpolator.cpp | 24 +++---- lib/algo/manifold_interp/MatrixInterpolator.h | 2 +- .../manifold_interp/VectorInterpolator.cpp | 26 ++++---- lib/algo/manifold_interp/VectorInterpolator.h | 19 +++--- lib/linalg/Matrix.cpp | 16 ++--- lib/linalg/Matrix.h | 6 +- unit_tests/test_DEIM.cpp | 6 +- unit_tests/test_GNAT.cpp | 6 +- unit_tests/test_QDEIM.cpp | 4 +- unit_tests/test_S_OPT.cpp | 16 ++--- 29 files changed, 157 insertions(+), 192 deletions(-) diff --git a/examples/dmd/de_dg_advection_greedy.cpp b/examples/dmd/de_dg_advection_greedy.cpp index 32ae28880..0dcb60d98 100644 --- a/examples/dmd/de_dg_advection_greedy.cpp +++ b/examples/dmd/de_dg_advection_greedy.cpp @@ -1057,7 +1057,7 @@ class RelativeDifferenceCostFunction : public CAROM::IOptimizable { } - double EvaluateCost(std::vector inputs) const override + double EvaluateCost(std::vector & inputs) const override { f_factor = inputs[0]; diff --git a/examples/dmd/de_parametric_heat_conduction_greedy.cpp b/examples/dmd/de_parametric_heat_conduction_greedy.cpp index 8d2eeabbd..962dd391e 100644 --- a/examples/dmd/de_parametric_heat_conduction_greedy.cpp +++ b/examples/dmd/de_parametric_heat_conduction_greedy.cpp @@ -822,7 +822,7 @@ class RelativeDifferenceCostFunction : public CAROM::IOptimizable { } - double EvaluateCost(std::vector inputs) const override + double EvaluateCost(std::vector & inputs) const override { radius = inputs[0]; alpha = inputs[1]; diff --git a/examples/dmd/parametric_dw_csv.cpp b/examples/dmd/parametric_dw_csv.cpp index 854a5ec51..73d3171eb 100644 --- a/examples/dmd/parametric_dw_csv.cpp +++ b/examples/dmd/parametric_dw_csv.cpp @@ -53,12 +53,12 @@ using namespace std; using namespace mfem; -void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, - const std::vector& parameter_points, - std::vector>& training_twep, - const CAROM::Vector & desired_point, - std::string rbf, - double closest_rbf_val); +std::unique_ptr getInterpolatedTimeWindows( + const std::vector& parameter_points, + std::vector>& training_twep, + const CAROM::Vector & desired_point, + std::string rbf, + double closest_rbf_val); int main(int argc, char *argv[]) { @@ -702,9 +702,9 @@ int main(int argc, char *argv[]) snap_bound.push_back(snap_list.size()-1); } - CAROM::Vector* twep; - getInterpolatedTimeWindows(twep, training_par_vectors, training_twep, curr_par, - string(rbf), pdmd_closest_rbf_val); // Always use IDW + std::unique_ptr twep = getInterpolatedTimeWindows( + training_par_vectors, training_twep, curr_par, + string(rbf), pdmd_closest_rbf_val); // Always use IDW int min_idx_snap = -1; int max_idx_snap = snap_bound[1]; @@ -873,7 +873,6 @@ int main(int argc, char *argv[]) prediction_time.clear(); prediction_error.clear(); num_tests += (t_final > 0.0) ? 1 : num_snap; - delete twep; } CAROM_VERIFY(num_tests > 0); @@ -903,12 +902,12 @@ int main(int argc, char *argv[]) return 0; } -void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, - const std::vector& parameter_points, - std::vector>& training_twep, - const CAROM::Vector & desired_point, - std::string rbf = "G", - double closest_rbf_val = 0.9) +std::unique_ptr getInterpolatedTimeWindows( + const std::vector& parameter_points, + std::vector>& training_twep, + const CAROM::Vector & desired_point, + std::string rbf = "G", + double closest_rbf_val = 0.9) { CAROM_VERIFY(parameter_points.size() == training_twep.size()); CAROM_VERIFY(training_twep.size() > 1); @@ -919,5 +918,5 @@ void getInterpolatedTimeWindows(CAROM::Vector*& testing_twep, rbf, epsilon, desired_point); CAROM::Matrix f_T; - testing_twep = obtainInterpolatedVector(training_twep, f_T, "IDW", rbf_val); + return obtainInterpolatedVector(training_twep, f_T, "IDW", rbf_val); } diff --git a/examples/prom/de_parametric_maxwell_greedy.cpp b/examples/prom/de_parametric_maxwell_greedy.cpp index a27cff4d2..86a283d88 100644 --- a/examples/prom/de_parametric_maxwell_greedy.cpp +++ b/examples/prom/de_parametric_maxwell_greedy.cpp @@ -569,7 +569,7 @@ class RelativeDifferenceCostFunction : public CAROM::IOptimizable { } - double EvaluateCost(std::vector inputs) const override + double EvaluateCost(std::vector & inputs) const override { freq = inputs[0]; diff --git a/lib/algo/AdaptiveDMD.cpp b/lib/algo/AdaptiveDMD.cpp index 22b5cf95b..7286d045a 100644 --- a/lib/algo/AdaptiveDMD.cpp +++ b/lib/algo/AdaptiveDMD.cpp @@ -101,7 +101,7 @@ void AdaptiveDMD::interpolateSnapshots() } // Solve the linear system if required. - Matrix* f_T = NULL; + std::unique_ptr f_T; std::unique_ptr> sampled_times = scalarsToVectors( d_sampled_times); double epsilon = convertClosestRBFToEpsilon(*sampled_times, d_rbf, @@ -127,10 +127,10 @@ void AdaptiveDMD::interpolateSnapshots() d_interp_method, d_rbf, epsilon, point); // Obtain the interpolated snapshot. - CAROM::Vector* curr_interpolated_snapshot = obtainInterpolatedVector( - d_snapshots, *f_T, d_interp_method, rbf); - d_interp_snapshots.push_back(std::shared_ptr - (curr_interpolated_snapshot)); + std::shared_ptr curr_interpolated_snapshot = + obtainInterpolatedVector( + d_snapshots, *f_T, d_interp_method, rbf); + d_interp_snapshots.push_back(curr_interpolated_snapshot); } if (d_rank == 0) std::cout << "Number of interpolated snapshots is: " << diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index fd0d1546c..568567190 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -230,7 +230,7 @@ DMD::computeDMDSnapshotPair(const Matrix & snapshots) } void -DMD::computePhi(struct DMDInternal dmd_internal_obj) +DMD::computePhi(DMDInternal dmd_internal_obj) { // Calculate phi if (d_alt_output_basis) @@ -477,10 +477,10 @@ DMD::constructDMD(const Matrix & f_snapshots, } // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(d_A_tilde.get()); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(*d_A_tilde); d_eigs = eigenpair.eigs; - struct DMDInternal dmd_internal = {f_snapshots_in, f_snapshots_out, d_basis.get(), d_basis_right, d_S_inv, &eigenpair}; + DMDInternal dmd_internal = {f_snapshots_in, f_snapshots_out, d_basis.get(), d_basis_right, d_S_inv, &eigenpair}; computePhi(dmd_internal); Vector init(f_snapshots_in->numRows(), true); diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index 5d4755ffd..eeff369e1 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -44,7 +44,7 @@ extern "C" { namespace CAROM { -DMDc::DMDc(int dim, int dim_c, Vector* state_offset) +DMDc::DMDc(int dim, int dim_c, std::shared_ptr state_offset) { CAROM_VERIFY(dim > 0); CAROM_VERIFY(dim_c > 0); @@ -65,7 +65,7 @@ DMDc::DMDc(int dim, int dim_c, Vector* state_offset) setOffset(state_offset); } -DMDc::DMDc(int dim, int dim_c, double dt, Vector* state_offset) +DMDc::DMDc(int dim, int dim_c, double dt, std::shared_ptr state_offset) { CAROM_VERIFY(dim > 0); CAROM_VERIFY(dim_c > 0); @@ -109,7 +109,7 @@ DMDc::DMDc(std::vector> & eigs, std::shared_ptr & phi_real, std::shared_ptr & phi_imaginary, std::shared_ptr B_tilde, int k, double dt, double t_offset, - Vector* state_offset, std::shared_ptr & basis) + std::shared_ptr & state_offset, std::shared_ptr & basis) { // Get the rank of this process, and the number of processors. int mpi_init; @@ -140,10 +140,9 @@ DMDc::~DMDc() { delete snapshot; } - delete d_state_offset; } -void DMDc::setOffset(Vector* offset_vector) +void DMDc::setOffset(std::shared_ptr & offset_vector) { d_state_offset = offset_vector; } @@ -528,7 +527,7 @@ DMDc::constructDMDc(const Matrix & f_snapshots, } // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(d_A_tilde.get()); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(*d_A_tilde); d_eigs = eigenpair.eigs; d_phi_real = d_basis->mult(*eigenpair.ev_real); @@ -888,7 +887,7 @@ DMDc::load(std::string base_file_name) full_file_name = base_file_name + "_state_offset"; if (Utilities::file_exist(full_file_name + ".000000")) { - d_state_offset = new Vector(); + d_state_offset.reset(new Vector()); d_state_offset->read(full_file_name); } diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index 2f1b36e7e..7be2bf8f5 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -41,7 +41,8 @@ class DMDc * @param[in] dt The dt between samples. * @param[in] state_offset The state offset. */ - DMDc(int dim, int dim_c, double dt, Vector* state_offset = NULL); + DMDc(int dim, int dim_c, double dt, + std::shared_ptr state_offset = nullptr); /** * @brief Constructor. DMDc from saved models. @@ -59,7 +60,7 @@ class DMDc /** * @brief Set the state offset. */ - virtual void setOffset(Vector* offset_vector); + virtual void setOffset(std::shared_ptr & offset_vector); /** * @brief Sample the new state, u_in. Any samples in d_snapshots @@ -227,7 +228,7 @@ class DMDc * @param[in] dim_c The control dimension. * @param[in] state_offset The state offset. */ - DMDc(int dim, int dim_c, Vector* state_offset = NULL); + DMDc(int dim, int dim_c, std::shared_ptr state_offset = nullptr); /** * @brief Constructor. Specified from DMDc components. @@ -248,7 +249,8 @@ class DMDc std::shared_ptr & phi_real, std::shared_ptr & phi_imaginary, std::shared_ptr B_tilde, - int k, double dt, double t_offset, Vector* state_offset, + int k, double dt, double t_offset, + std::shared_ptr & state_offset, std::shared_ptr & basis); /** @@ -353,7 +355,7 @@ class DMDc /** * @brief State offset in snapshot. */ - Vector* d_state_offset = NULL; + std::shared_ptr d_state_offset; /** * @brief Whether the DMDc has been trained or not. diff --git a/lib/algo/DifferentialEvolution.h b/lib/algo/DifferentialEvolution.h index fe49ce0cd..b93c4883a 100644 --- a/lib/algo/DifferentialEvolution.h +++ b/lib/algo/DifferentialEvolution.h @@ -96,7 +96,7 @@ class IOptimizable /** * @brief Evaluate the cost function with the current set of inputs. */ - virtual double EvaluateCost(std::vector inputs) const = 0; + virtual double EvaluateCost(std::vector & inputs) const = 0; /** * @brief Return the number of parameters. diff --git a/lib/algo/ParametricDMD.h b/lib/algo/ParametricDMD.h index 87f4c0fe0..19095b46b 100644 --- a/lib/algo/ParametricDMD.h +++ b/lib/algo/ParametricDMD.h @@ -99,7 +99,7 @@ void getParametricDMD(T*& parametric_dmd, desired_point); // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(A_tilde.get()); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(*A_tilde); std::vector> eigs = eigenpair.eigs; // Calculate phi (phi = W * eigenvectors) diff --git a/lib/algo/ParametricDMDc.h b/lib/algo/ParametricDMDc.h index ebe07f8b9..3ff2be25b 100644 --- a/lib/algo/ParametricDMDc.h +++ b/lib/algo/ParametricDMDc.h @@ -120,7 +120,7 @@ void getParametricDMDc(T*& parametric_dmdc, controls_interpolated = control_interpolator.interpolate(desired_point); // Calculate the right eigenvalues/eigenvectors of A_tilde - ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(A_tilde.get()); + ComplexEigenPair eigenpair = NonSymmetricRightEigenSolve(*A_tilde); std::vector> eigs = eigenpair.eigs; // Calculate phi (phi = W * eigenvectors) diff --git a/lib/algo/greedy/GreedyCustomSampler.cpp b/lib/algo/greedy/GreedyCustomSampler.cpp index 895d6f880..c2fd252e5 100644 --- a/lib/algo/greedy/GreedyCustomSampler.cpp +++ b/lib/algo/greedy/GreedyCustomSampler.cpp @@ -20,7 +20,7 @@ namespace CAROM { GreedyCustomSampler::GreedyCustomSampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -58,7 +58,7 @@ GreedyCustomSampler::GreedyCustomSampler( } GreedyCustomSampler::GreedyCustomSampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, diff --git a/lib/algo/greedy/GreedyCustomSampler.h b/lib/algo/greedy/GreedyCustomSampler.h index c705976c8..f941683bd 100644 --- a/lib/algo/greedy/GreedyCustomSampler.h +++ b/lib/algo/greedy/GreedyCustomSampler.h @@ -51,7 +51,7 @@ class GreedyCustomSampler : public GreedySampler * debugging purposes. */ GreedyCustomSampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -89,7 +89,7 @@ class GreedyCustomSampler : public GreedySampler * debugging purposes. */ GreedyCustomSampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, diff --git a/lib/algo/greedy/GreedyRandomSampler.cpp b/lib/algo/greedy/GreedyRandomSampler.cpp index 84494e908..2b70fe1f5 100644 --- a/lib/algo/greedy/GreedyRandomSampler.cpp +++ b/lib/algo/greedy/GreedyRandomSampler.cpp @@ -75,8 +75,8 @@ GreedyRandomSampler::GreedyRandomSampler( } GreedyRandomSampler::GreedyRandomSampler( - Vector param_space_min, - Vector param_space_max, + Vector & param_space_min, + Vector & param_space_max, int num_parameter_points, bool check_local_rom, double relative_error_tolerance, diff --git a/lib/algo/greedy/GreedyRandomSampler.h b/lib/algo/greedy/GreedyRandomSampler.h index 92182c18f..e5cd028d0 100644 --- a/lib/algo/greedy/GreedyRandomSampler.h +++ b/lib/algo/greedy/GreedyRandomSampler.h @@ -57,8 +57,8 @@ class GreedyRandomSampler : public GreedySampler * debugging purposes. */ GreedyRandomSampler( - Vector param_space_min, - Vector param_space_max, + Vector & param_space_min, + Vector & param_space_max, int num_parameter_points, bool check_local_rom, double relative_error_tolerance, diff --git a/lib/algo/greedy/GreedySampler.cpp b/lib/algo/greedy/GreedySampler.cpp index d3b8a3e41..18c43a080 100644 --- a/lib/algo/greedy/GreedySampler.cpp +++ b/lib/algo/greedy/GreedySampler.cpp @@ -21,27 +21,16 @@ namespace CAROM { -struct GreedyErrorIndicatorPoint -createGreedyErrorIndicatorPoint(Vector* point, Vector* localROM) +GreedyErrorIndicatorPoint +createGreedyErrorIndicatorPoint(std::shared_ptr point, + std::shared_ptr localROM) { - struct GreedyErrorIndicatorPoint result; - result.point = std::shared_ptr(point); - result.localROM = std::shared_ptr(localROM); - return result; -} - -struct GreedyErrorIndicatorPoint -createGreedyErrorIndicatorPoint(Vector* point, - std::shared_ptr& localROM) -{ - struct GreedyErrorIndicatorPoint result; - result.point = std::shared_ptr(point); - result.localROM = localROM; + GreedyErrorIndicatorPoint result{point, localROM}; return result; } Vector -getNearestPoint(std::vector param_points, Vector point) +getNearestPoint(std::vector & param_points, Vector & point) { int closest_point_index = getNearestPointIndex(param_points, point); @@ -49,7 +38,7 @@ getNearestPoint(std::vector param_points, Vector point) } int -getNearestPointIndex(std::vector param_points, Vector point) +getNearestPointIndex(std::vector & param_points, Vector & point) { double closest_dist_to_points = INT_MAX; @@ -71,7 +60,7 @@ getNearestPointIndex(std::vector param_points, Vector point) } double -getNearestPoint(std::vector param_points, double point) +getNearestPoint(std::vector & param_points, double point) { int closest_point_index = getNearestPointIndex(param_points, point); @@ -79,7 +68,7 @@ getNearestPoint(std::vector param_points, double point) } int -getNearestPointIndex(std::vector param_points, double point) +getNearestPointIndex(std::vector & param_points, double point) { double closest_dist_to_points = INT_MAX; @@ -99,7 +88,7 @@ getNearestPointIndex(std::vector param_points, double point) } GreedySampler::GreedySampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -123,7 +112,7 @@ GreedySampler::GreedySampler( } GreedySampler::GreedySampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -155,8 +144,8 @@ GreedySampler::GreedySampler( } GreedySampler::GreedySampler( - Vector param_space_min, - Vector param_space_max, + Vector & param_space_min, + Vector & param_space_max, int num_parameter_points, bool check_local_rom, double relative_error_tolerance, @@ -592,7 +581,7 @@ GreedySampler::getNextParameterPoint() return std::shared_ptr(result); } -struct GreedyErrorIndicatorPoint +GreedyErrorIndicatorPoint GreedySampler::getNextPointRequiringRelativeError() { if (isComplete()) @@ -605,7 +594,7 @@ GreedySampler::getNextPointRequiringRelativeError() } Vector* result1 = new Vector(d_parameter_points[d_next_point_to_sample]); - Vector* result2 = NULL; + Vector* result2 = nullptr; if (d_parameter_sampled_indices.size() == 1) { @@ -618,10 +607,11 @@ GreedySampler::getNextPointRequiringRelativeError() d_next_point_to_sample, true)]); } - return createGreedyErrorIndicatorPoint(result1, result2); + return createGreedyErrorIndicatorPoint(std::shared_ptr(result1), + std::shared_ptr(result2)); } -struct GreedyErrorIndicatorPoint +GreedyErrorIndicatorPoint GreedySampler::getNextPointRequiringErrorIndicator() { if (isComplete()) @@ -643,7 +633,7 @@ GreedySampler::getNextPointRequiringErrorIndicator() } } -struct GreedyErrorIndicatorPoint +GreedyErrorIndicatorPoint GreedySampler::getNextSubsetPointRequiringErrorIndicator() { if (d_point_requiring_error_indicator_computed) @@ -653,7 +643,8 @@ GreedySampler::getNextSubsetPointRequiringErrorIndicator() Vector* result2 = new Vector( d_parameter_points[getNearestROMIndexToParameterPoint( d_next_point_requiring_error_indicator, false)]); - return createGreedyErrorIndicatorPoint(result1, result2); + return createGreedyErrorIndicatorPoint(std::shared_ptr(result1), + std::shared_ptr(result2)); } if (d_subset_counter == d_subset_size) { @@ -723,7 +714,8 @@ GreedySampler::getNextSubsetPointRequiringErrorIndicator() Vector* result2 = new Vector( d_parameter_points[getNearestROMIndexToParameterPoint( d_next_point_requiring_error_indicator, false)]); - return createGreedyErrorIndicatorPoint(result1, result2); + return createGreedyErrorIndicatorPoint(std::shared_ptr(result1), + std::shared_ptr(result2)); } } else @@ -768,7 +760,7 @@ GreedySampler::getNextSubsetPointRequiringErrorIndicator() return createGreedyErrorIndicatorPoint(nullptr, nullptr); } -struct GreedyErrorIndicatorPoint +GreedyErrorIndicatorPoint GreedySampler::getNextConvergencePointRequiringErrorIndicator() { if (d_point_requiring_error_indicator_computed) @@ -777,7 +769,8 @@ GreedySampler::getNextConvergencePointRequiringErrorIndicator() d_convergence_points[d_next_point_requiring_error_indicator]); std::shared_ptr result2 = getNearestROM( d_convergence_points[d_next_point_requiring_error_indicator]); - return createGreedyErrorIndicatorPoint(result1, result2); + return createGreedyErrorIndicatorPoint(std::shared_ptr(result1), + result2); } if (d_counter == d_convergence_subset_size) { @@ -795,7 +788,8 @@ GreedySampler::getNextConvergencePointRequiringErrorIndicator() d_convergence_points[d_next_point_requiring_error_indicator]); std::shared_ptr result2 = getNearestROM( d_convergence_points[d_next_point_requiring_error_indicator]); - return createGreedyErrorIndicatorPoint(result1, result2); + return createGreedyErrorIndicatorPoint(std::shared_ptr(result1), + result2); } if (d_next_point_requiring_error_indicator == -1) @@ -1237,7 +1231,7 @@ GreedySampler::generateRandomPoints(int num_points) } std::shared_ptr -GreedySampler::getNearestROM(Vector point) +GreedySampler::getNearestROM(Vector & point) { CAROM_VERIFY(point.dim() == d_parameter_points[0].dim()); @@ -1266,7 +1260,7 @@ GreedySampler::getNearestROM(Vector point) } int -GreedySampler::getNearestNonSampledPoint(Vector point) +GreedySampler::getNearestNonSampledPoint(Vector & point) { double closest_dist_to_points = INT_MAX; int closest_point_index = -1; diff --git a/lib/algo/greedy/GreedySampler.h b/lib/algo/greedy/GreedySampler.h index b9f7c2115..9452877a2 100644 --- a/lib/algo/greedy/GreedySampler.h +++ b/lib/algo/greedy/GreedySampler.h @@ -100,7 +100,7 @@ class GreedySampler * debugging purposes. */ GreedySampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -138,7 +138,7 @@ class GreedySampler * debugging purposes. */ GreedySampler( - std::vector parameter_points, + std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -180,8 +180,8 @@ class GreedySampler * debugging purposes. */ GreedySampler( - Vector param_space_min, - Vector param_space_max, + Vector & param_space_min, + Vector & param_space_max, int num_parameter_points, bool check_local_rom, double relative_error_tolerance, @@ -272,7 +272,7 @@ class GreedySampler * @return A struct holding the point and the location of the nearest local * ROM or NULL if no point is required. */ - struct GreedyErrorIndicatorPoint + GreedyErrorIndicatorPoint getNextPointRequiringRelativeError(); /** @@ -282,7 +282,7 @@ class GreedySampler * @return A struct holding the point and the location of the nearest local * ROM or NULL if no point is required. */ - struct GreedyErrorIndicatorPoint + GreedyErrorIndicatorPoint getNextPointRequiringErrorIndicator(); /** @@ -313,7 +313,7 @@ class GreedySampler * the given point or -1 if none exist. */ int - getNearestNonSampledPoint(Vector point); + getNearestNonSampledPoint(Vector & point); /** * @brief Returns the nearest local ROM to the specified parameter point. @@ -323,7 +323,7 @@ class GreedySampler * @return A shared pointer holding the point or NULL if no local ROM exists. */ std::shared_ptr - getNearestROM(Vector point); + getNearestROM(Vector & point); /** * @brief Get the domain of the parameter points. @@ -416,7 +416,7 @@ class GreedySampler * @return A struct holding the point and the location of the nearest local * ROM or NULL if no point is required. */ - struct GreedyErrorIndicatorPoint getNextSubsetPointRequiringErrorIndicator(); + GreedyErrorIndicatorPoint getNextSubsetPointRequiringErrorIndicator(); /** * @brief Get the next convergence point requiring an error indicator. @@ -424,7 +424,7 @@ class GreedySampler * @return A struct holding the point and the location of the nearest local * ROM or NULL if no point is required. */ - struct GreedyErrorIndicatorPoint + GreedyErrorIndicatorPoint getNextConvergencePointRequiringErrorIndicator(); /** @@ -699,23 +699,11 @@ class GreedySampler * @param[in] point The error indicator point. * @param[in] localROM The point of the nearest ROM. * - * @return A struct holding the point and the location of the nearest local - * ROM or NULL if no point is required. + * @return A struct holding @a point and @a localROM. */ -struct GreedyErrorIndicatorPoint createGreedyErrorIndicatorPoint(Vector* point, - Vector* localROM); - -/** - * @brief Create a greedy error indicator point. - * - * @param[in] point The error indicator point. - * @param[in] localROM The point of the nearest ROM. - * - * @return A struct holding the point and the location of the nearest local - * ROM or NULL if no point is required. - */ -struct GreedyErrorIndicatorPoint createGreedyErrorIndicatorPoint(Vector* point, - std::shared_ptr& localROM); +GreedyErrorIndicatorPoint createGreedyErrorIndicatorPoint( + std::shared_ptr point, + std::shared_ptr localROM); /** * @brief Given a vector, find the nearest point in a domain. @@ -725,7 +713,7 @@ struct GreedyErrorIndicatorPoint createGreedyErrorIndicatorPoint(Vector* point, * * @return A vector representing the nearest point in a domain. */ -Vector getNearestPoint(std::vector paramPoints, Vector point); +Vector getNearestPoint(std::vector & paramPoints, Vector & point); /** * @brief Given a double, find the nearest point in a domain. @@ -735,7 +723,7 @@ Vector getNearestPoint(std::vector paramPoints, Vector point); * * @return A double representing the nearest point in a domain. */ -double getNearestPoint(std::vector paramPoints, double point); +double getNearestPoint(std::vector & paramPoints, double point); /** * @brief Given a vector, find the nearest point in a domain. @@ -745,7 +733,7 @@ double getNearestPoint(std::vector paramPoints, double point); * * @return The index of the nearest point in a domain. */ -int getNearestPointIndex(std::vector paramPoints, Vector point); +int getNearestPointIndex(std::vector & paramPoints, Vector & point); /** * @brief Given a double, find the nearest point in a domain. @@ -755,7 +743,7 @@ int getNearestPointIndex(std::vector paramPoints, Vector point); * * @return The index of the nearest point in a domain. */ -int getNearestPointIndex(std::vector paramPoints, double point); +int getNearestPointIndex(std::vector & paramPoints, double point); } #endif diff --git a/lib/algo/manifold_interp/Interpolator.cpp b/lib/algo/manifold_interp/Interpolator.cpp index a361757eb..e97fc38a7 100644 --- a/lib/algo/manifold_interp/Interpolator.cpp +++ b/lib/algo/manifold_interp/Interpolator.cpp @@ -56,17 +56,11 @@ Interpolator::Interpolator(const std::vector & parameter_points, d_parameter_points = parameter_points; d_rotation_matrices = rotation_matrices; d_ref_point = ref_point; - d_lambda_T = NULL; d_rbf = rbf; d_interp_method = interp_method; d_epsilon = convertClosestRBFToEpsilon(parameter_points, rbf, closest_rbf_val); } -Interpolator::~Interpolator() -{ - delete d_lambda_T; -} - std::vector obtainRBFToTrainingPoints( const std::vector & parameter_points, const std::string & interp_method, const std::string & rbf, double epsilon, diff --git a/lib/algo/manifold_interp/Interpolator.h b/lib/algo/manifold_interp/Interpolator.h index 988f5d521..45090ff7a 100644 --- a/lib/algo/manifold_interp/Interpolator.h +++ b/lib/algo/manifold_interp/Interpolator.h @@ -58,8 +58,6 @@ class Interpolator std::string interp_method, double closest_rbf_val = 0.9); - ~Interpolator(); - /** * @brief The rank of the process this object belongs to. */ @@ -108,7 +106,7 @@ class Interpolator /** * @brief The RHS of the linear solve in tangential space. */ - Matrix* d_lambda_T; + std::unique_ptr d_lambda_T; private: diff --git a/lib/algo/manifold_interp/MatrixInterpolator.cpp b/lib/algo/manifold_interp/MatrixInterpolator.cpp index 5db9be9e6..119ea1cf7 100644 --- a/lib/algo/manifold_interp/MatrixInterpolator.cpp +++ b/lib/algo/manifold_interp/MatrixInterpolator.cpp @@ -166,11 +166,11 @@ void MatrixInterpolator::obtainLambda() delete B; - d_lambda_T = f_T; + d_lambda_T = std::unique_ptr(f_T); } } -Matrix* MatrixInterpolator::obtainLogInterpolatedMatrix( +std::unique_ptr MatrixInterpolator::obtainLogInterpolatedMatrix( std::vector& rbf) { Matrix* log_interpolated_matrix = new Matrix( @@ -213,7 +213,7 @@ Matrix* MatrixInterpolator::obtainLogInterpolatedMatrix( } } } - return log_interpolated_matrix; + return std::unique_ptr(log_interpolated_matrix); } std::shared_ptr MatrixInterpolator::interpolateSPDMatrix( @@ -223,7 +223,7 @@ std::shared_ptr MatrixInterpolator::interpolateSPDMatrix( { // Diagonalize X to work towards obtaining X^-1/2 EigenPair ref_reduced_matrix_eigenpair = SymmetricRightEigenSolve( - d_rotated_reduced_matrices[d_ref_point].get()); + *d_rotated_reduced_matrices[d_ref_point]); Matrix* ref_reduced_matrix_ev = ref_reduced_matrix_eigenpair.ev; Matrix* ref_reduced_matrix_sqrt_eigs = new Matrix( @@ -279,7 +279,7 @@ std::shared_ptr MatrixInterpolator::interpolateSPDMatrix( // of M and V are the eigenvectors of M. // 2. log M = V(log M')V^-1 EigenPair log_eigenpair = SymmetricRightEigenSolve( - x_half_power_inv_mult_y_mult_x_half_power_inv.get()); + *x_half_power_inv_mult_y_mult_x_half_power_inv); Matrix* log_ev = log_eigenpair.ev; Matrix* log_eigs = new Matrix(log_eigenpair.eigs.size(), @@ -320,7 +320,8 @@ std::shared_ptr MatrixInterpolator::interpolateSPDMatrix( d_rbf, d_epsilon, point); // Interpolate gammas to get gamma for new point - Matrix* log_interpolated_matrix = obtainLogInterpolatedMatrix(rbf); + std::unique_ptr log_interpolated_matrix = obtainLogInterpolatedMatrix( + rbf); // Diagonalize the new gamma so we can exponentiate it // Diagonalize X to obtain exp(X) of this matrix. @@ -328,8 +329,7 @@ std::shared_ptr MatrixInterpolator::interpolateSPDMatrix( // 1. Diagonalize M to obtain M' = V^-1*M*V. M' are the eigenvalues // of M and V are the eigenvectors of M. // 2. exp M = V(exp M')V^-1 - EigenPair exp_eigenpair = SymmetricRightEigenSolve(log_interpolated_matrix); - delete log_interpolated_matrix; + EigenPair exp_eigenpair = SymmetricRightEigenSolve(*log_interpolated_matrix); Matrix* exp_ev = exp_eigenpair.ev; @@ -388,7 +388,7 @@ std::shared_ptr MatrixInterpolator::interpolateNonSingularMatrix( // 1. Diagonalize M to obtain M' = V^-1*M*V. M' are the eigenvalues // of M and V are the eigenvectors of M. // 2. log M = V(log M')V^-1 - EigenPair log_eigenpair = SymmetricRightEigenSolve(y_mult_ref_matrix_inv.get()); + EigenPair log_eigenpair = SymmetricRightEigenSolve(*y_mult_ref_matrix_inv); Matrix* log_ev = log_eigenpair.ev; Matrix* log_eigs = new Matrix(log_eigenpair.eigs.size(), @@ -427,7 +427,8 @@ std::shared_ptr MatrixInterpolator::interpolateNonSingularMatrix( d_interp_method, d_rbf, d_epsilon, point); // Interpolate gammas to get gamma for new point - Matrix* log_interpolated_matrix = obtainLogInterpolatedMatrix(rbf); + std::unique_ptr log_interpolated_matrix = obtainLogInterpolatedMatrix( + rbf); // Diagonalize the new gamma so we can exponentiate it // Diagonalize X to obtain exp(X) of this matrix. @@ -435,8 +436,7 @@ std::shared_ptr MatrixInterpolator::interpolateNonSingularMatrix( // 1. Diagonalize M to obtain M' = V^-1*M*V. M' are the eigenvalues // of M and V are the eigenvectors of M. // 2. exp M = V(exp M')V^-1 - EigenPair exp_eigenpair = SymmetricRightEigenSolve(log_interpolated_matrix); - delete log_interpolated_matrix; + EigenPair exp_eigenpair = SymmetricRightEigenSolve(*log_interpolated_matrix); Matrix* exp_ev = exp_eigenpair.ev; Matrix* exp_ev_inv = NULL; diff --git a/lib/algo/manifold_interp/MatrixInterpolator.h b/lib/algo/manifold_interp/MatrixInterpolator.h index b883fd368..67a966e5f 100644 --- a/lib/algo/manifold_interp/MatrixInterpolator.h +++ b/lib/algo/manifold_interp/MatrixInterpolator.h @@ -109,7 +109,7 @@ class MatrixInterpolator : public Interpolator * @param[in] rbf The RBF values between the parameter points and * the unsampled parameter point. */ - Matrix* obtainLogInterpolatedMatrix(std::vector& rbf); + std::unique_ptr obtainLogInterpolatedMatrix(std::vector& rbf); /** * @brief Obtain the interpolated SPD reduced matrix for the unsampled diff --git a/lib/algo/manifold_interp/VectorInterpolator.cpp b/lib/algo/manifold_interp/VectorInterpolator.cpp index 210d1a58b..128fcf196 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.cpp +++ b/lib/algo/manifold_interp/VectorInterpolator.cpp @@ -79,7 +79,7 @@ void VectorInterpolator::obtainLambda() } } -Vector* VectorInterpolator::obtainLogInterpolatedVector( +std::unique_ptr VectorInterpolator::obtainLogInterpolatedVector( std::vector& rbf) { return obtainInterpolatedVector(d_gammas, *d_lambda_T, d_interp_method, rbf); @@ -117,19 +117,20 @@ std::shared_ptr VectorInterpolator::interpolate(const Vector & point) d_interp_method, d_rbf, d_epsilon, point); // Interpolate gammas to get gamma for new point - Vector* log_interpolated_vector = obtainLogInterpolatedVector(rbf); + std::unique_ptr log_interpolated_vector = obtainLogInterpolatedVector( + rbf); // The exp mapping is X + the interpolated gamma std::shared_ptr interpolated_vector = d_rotated_reduced_vectors[d_ref_point]->plus( *log_interpolated_vector); - delete log_interpolated_vector; return interpolated_vector; } -Vector* obtainInterpolatedVector(const std::vector> & - data, const Matrix & f_T, - std::string interp_method, std::vector& rbf) +std::unique_ptr obtainInterpolatedVector(const + std::vector> & + data, const Matrix & f_T, + std::string interp_method, std::vector& rbf) { Vector* interpolated_vector = new Vector(data[0]->dim(), data[0]->distributed()); @@ -166,13 +167,14 @@ Vector* obtainInterpolatedVector(const std::vector> & } } - return interpolated_vector; + return std::unique_ptr(interpolated_vector); } -Matrix* solveLinearSystem(const std::vector & parameter_points, - const std::vector> & data, - const std::string & interp_method, - const std::string & rbf, double epsilon) +std::unique_ptr solveLinearSystem( + const std::vector & parameter_points, + const std::vector> & data, + const std::string & interp_method, + const std::string & rbf, double epsilon) { int mpi_init, rank; MPI_Initialized(&mpi_init); @@ -226,7 +228,7 @@ Matrix* solveLinearSystem(const std::vector & parameter_points, delete B; } - return f_T; + return std::unique_ptr(f_T); } } diff --git a/lib/algo/manifold_interp/VectorInterpolator.h b/lib/algo/manifold_interp/VectorInterpolator.h index 2eefb368b..930ffd3ba 100644 --- a/lib/algo/manifold_interp/VectorInterpolator.h +++ b/lib/algo/manifold_interp/VectorInterpolator.h @@ -102,7 +102,7 @@ class VectorInterpolator : public Interpolator * @param[in] rbf The RBF values between the parameter points and * the unsampled parameter point. */ - Vector* obtainLogInterpolatedVector(std::vector& rbf); + std::unique_ptr obtainLogInterpolatedVector(std::vector& rbf); /** * @brief The reduced vectors with compatible coordinates. @@ -115,14 +115,15 @@ class VectorInterpolator : public Interpolator std::vector> d_gammas; }; -Vector* obtainInterpolatedVector(const std::vector> & - data, - const Matrix & f_T, std::string interp_method, - std::vector& rbf); -Matrix* solveLinearSystem(const std::vector & parameter_points, - const std::vector> & data, - const std::string & interp_method, - const std::string & rbf, double epsilon); +std::unique_ptr obtainInterpolatedVector( + const std::vector> & data, + const Matrix & f_T, std::string interp_method, + std::vector& rbf); +std::unique_ptr solveLinearSystem( + const std::vector & parameter_points, + const std::vector> & data, + const std::string & interp_method, + const std::string & rbf, double epsilon); } #endif diff --git a/lib/linalg/Matrix.cpp b/lib/linalg/Matrix.cpp index ffc123396..92674c193 100644 --- a/lib/linalg/Matrix.cpp +++ b/lib/linalg/Matrix.cpp @@ -1980,16 +1980,16 @@ Matrix IdentityMatrixFactory(const Vector &v) return DiagonalMatrixFactory(temporary); } -struct EigenPair SymmetricRightEigenSolve(Matrix* A) +EigenPair SymmetricRightEigenSolve(const Matrix & A) { char jobz = 'V', uplo = 'U'; int info; - int k = A->numColumns(); + int k = A.numColumns(); int lwork = std::max(1, 10*k-1); double* work = new double [lwork]; double* eigs = new double [k]; - Matrix* ev = new Matrix(*A); + Matrix* ev = new Matrix(A); // ev now in a row major representation. Put it // into column major order. @@ -2027,19 +2027,19 @@ struct EigenPair SymmetricRightEigenSolve(Matrix* A) return eigenpair; } -struct ComplexEigenPair NonSymmetricRightEigenSolve(Matrix* A) +ComplexEigenPair NonSymmetricRightEigenSolve(const Matrix & A) { char jobvl = 'N', jobrl = 'V'; int info; - int k = A->numColumns(); + int k = A.numColumns(); int lwork = std::max(k*k, 10*k); double* work = new double [lwork]; double* e_real = new double [k]; double* e_imaginary = new double [k]; double* ev_l = NULL; Matrix* ev_r = new Matrix(k, k, false); - Matrix* A_copy = new Matrix(*A); + Matrix* A_copy = new Matrix(A); // A now in a row major representation. Put it // into column major order. @@ -2161,7 +2161,7 @@ void SerialSVD(Matrix* A, delete A_copy; } -struct SerialSVDDecomposition SerialSVD(Matrix* A) +SerialSVDDecomposition SerialSVD(Matrix* A) { CAROM_VERIFY(!A->distributed()); Matrix* U = NULL; @@ -2170,7 +2170,7 @@ struct SerialSVDDecomposition SerialSVD(Matrix* A) SerialSVD(A, U, S, V); - struct SerialSVDDecomposition decomp; + SerialSVDDecomposition decomp; decomp.U = U; decomp.S = S; decomp.V = V; diff --git a/lib/linalg/Matrix.h b/lib/linalg/Matrix.h index c9c0e2a94..c17be2ce5 100644 --- a/lib/linalg/Matrix.h +++ b/lib/linalg/Matrix.h @@ -1185,7 +1185,7 @@ void SerialSVD(Matrix* A, * and vector contained within the returning struct must be destroyed by * the user. */ -struct SerialSVDDecomposition SerialSVD(Matrix* A); +SerialSVDDecomposition SerialSVD(const Matrix & A); /** * @brief Computes the eigenvectors/eigenvalues of an NxN real symmetric matrix. @@ -1195,7 +1195,7 @@ struct SerialSVDDecomposition SerialSVD(Matrix* A); * @return The eigenvectors and eigenvalues of the eigensolve. The eigenvector matrices * contained within the returning struct must be destroyed by the user. */ -struct EigenPair SymmetricRightEigenSolve(Matrix* A); +EigenPair SymmetricRightEigenSolve(const Matrix & A); /** * @brief Computes the eigenvectors/eigenvalues of an NxN real nonsymmetric matrix. @@ -1205,7 +1205,7 @@ struct EigenPair SymmetricRightEigenSolve(Matrix* A); * @return The eigenvectors and eigenvalues of the eigensolve. The eigenvector matrices * contained within the returning struct must be destroyed by the user. */ -struct ComplexEigenPair NonSymmetricRightEigenSolve(Matrix* A); +ComplexEigenPair NonSymmetricRightEigenSolve(const Matrix & A); std::unique_ptr SpaceTimeProduct(const CAROM::Matrix* As, const CAROM::Matrix* At, const CAROM::Matrix* Bs, diff --git a/unit_tests/test_DEIM.cpp b/unit_tests/test_DEIM.cpp index 751ff2e1b..ee17b4ce2 100644 --- a/unit_tests/test_DEIM.cpp +++ b/unit_tests/test_DEIM.cpp @@ -57,8 +57,7 @@ TEST(DEIMSerialTest, Test_DEIM) int num_cols = 5; int num_rows = 10; - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, - false); + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, false); double* DEIM_res = NULL; std::vector f_sampled_row(num_cols, 0); std::vector f_sampled_row_true_ans{0, 1, 4, 5, 9}; @@ -113,8 +112,7 @@ TEST(DEIMSerialTest, Test_DEIM_decreased_used_basis_vectors) int num_rows = 10; int num_basis_vectors_used = 3; - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, - false); + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, false); double* DEIM_res = NULL; std::vector f_sampled_row(num_basis_vectors_used, 0); std::vector f_sampled_row_true_ans{0, 1, 4}; diff --git a/unit_tests/test_GNAT.cpp b/unit_tests/test_GNAT.cpp index d1524b352..fac45fb72 100644 --- a/unit_tests/test_GNAT.cpp +++ b/unit_tests/test_GNAT.cpp @@ -57,8 +57,7 @@ TEST(GNATSerialTest, Test_GNAT) int num_cols = 5; int num_rows = 10; - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, - false); + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, false); double* GNAT_res = NULL; std::vector f_sampled_row(num_cols, 0); std::vector f_sampled_row_true_ans{0, 1, 4, 5, 9}; @@ -119,8 +118,7 @@ TEST(GNATSerialTest, Test_GNAT_oversampling) int num_rows = 10; int num_samples = 9; - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, - false); + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, false); double* GNAT_res = NULL; std::vector f_sampled_row(num_samples, 0); std::vector f_sampled_row_true_ans{0, 1, 2, 4, 5, 6, 7, 8, 9}; diff --git a/unit_tests/test_QDEIM.cpp b/unit_tests/test_QDEIM.cpp index 9e099855a..468e79007 100644 --- a/unit_tests/test_QDEIM.cpp +++ b/unit_tests/test_QDEIM.cpp @@ -57,7 +57,7 @@ TEST(QDEIMSerialTest, Test_QDEIM) int num_cols = 5; int num_rows = 10; - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, true); + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, true); double* QDEIM_res = NULL; std::vector f_sampled_row(num_cols, 0); std::vector f_sampled_row_true_ans{1, 2, 4, 6, 9}; @@ -118,7 +118,7 @@ TEST(QDEIMSerialTest, Test_QDEIM_gpode_oversampling) int num_rows = 10; int num_samples = 8; - CAROM::Matrix* u = new CAROM::Matrix(orthonormal_mat, num_rows, num_cols, true); + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, true); double* QDEIM_res = NULL; std::vector f_sampled_row(num_samples, 0); std::vector f_sampled_row_true_ans{0, 1, 2, 4, 5, 6, 8, 9}; diff --git a/unit_tests/test_S_OPT.cpp b/unit_tests/test_S_OPT.cpp index c5adec70b..5f1bd68de 100644 --- a/unit_tests/test_S_OPT.cpp +++ b/unit_tests/test_S_OPT.cpp @@ -110,9 +110,7 @@ TEST(S_OPTSerialTest, Test_S_OPT) } } - std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, - num_cols, true)); - + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, true); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); std::vector f_sampled_row_true_ans{0, 19, 21, 48, 49, 50, 72, 79, 90, 97}; @@ -226,9 +224,7 @@ TEST(S_OPTSerialTest, Test_S_OPT_less_basis_vectors) } } - std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, - num_cols, true)); - + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, true); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); std::vector f_sampled_row_true_ans{0, 44, 46, 49, 90}; @@ -343,9 +339,7 @@ TEST(S_OPTSerialTest, Test_S_OPT_init_vector) } } - std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, - num_cols, true)); - + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, true); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); std::vector f_sampled_row_true_ans{0, 44, 46, 49, 90}; @@ -503,9 +497,7 @@ TEST(S_OPTSerialTest, Test_S_OPT_QR) } } - std::shared_ptr u(new CAROM::Matrix(orthonormal_mat, num_rows, - num_cols, true)); - + CAROM::Matrix u(orthonormal_mat, num_rows, num_cols, true); double* S_OPT_res = NULL; std::vector f_sampled_row(num_samples, 0); std::vector f_sampled_row_true_ans{0, 44, 46, 49, 90}; From 84ad4481645adc831cd88cb595c6f183e438bc56 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Mon, 26 Aug 2024 19:14:40 -0700 Subject: [PATCH 14/19] Removal of pointers in svd. --- lib/hyperreduction/STSampling.cpp | 74 ++++++++++----------- lib/hyperreduction/STSampling.h | 6 +- lib/linalg/BasisGenerator.cpp | 2 +- lib/linalg/BasisWriter.cpp | 13 ++-- lib/linalg/BasisWriter.h | 4 +- lib/linalg/Matrix.cpp | 26 ++++---- lib/linalg/Matrix.h | 16 ++--- lib/linalg/Vector.h | 6 +- lib/linalg/svd/IncrementalSVD.cpp | 13 ++-- lib/linalg/svd/IncrementalSVD.h | 26 +++----- lib/linalg/svd/IncrementalSVDBrand.cpp | 49 ++++++-------- lib/linalg/svd/IncrementalSVDBrand.h | 22 ++---- lib/linalg/svd/IncrementalSVDFastUpdate.cpp | 43 +++++------- lib/linalg/svd/IncrementalSVDFastUpdate.h | 22 ++---- lib/linalg/svd/IncrementalSVDStandard.cpp | 37 +++++------ lib/linalg/svd/IncrementalSVDStandard.h | 22 ++---- unit_tests/test_IncrementalSVD.cpp | 14 ++-- 17 files changed, 169 insertions(+), 226 deletions(-) diff --git a/lib/hyperreduction/STSampling.cpp b/lib/hyperreduction/STSampling.cpp index 4f6d25239..5ef106ce9 100644 --- a/lib/hyperreduction/STSampling.cpp +++ b/lib/hyperreduction/STSampling.cpp @@ -30,8 +30,8 @@ namespace CAROM { // In general, there may be multiple temporal basis vectors associated with each // spatial basis vector, but here we assume for now that there is only one, i.e. // column j of s_basis corresponds to column j of t_basis. -void SampleTemporalIndices(const Matrix* s_basis, - const Matrix* t_basis, +void SampleTemporalIndices(const Matrix & s_basis, + const Matrix & t_basis, const int num_f_basis_vectors_used, int* t_samples, const int myid, @@ -39,20 +39,20 @@ void SampleTemporalIndices(const Matrix* s_basis, const int num_samples_req, const bool excludeFinalTime) { - CAROM_VERIFY(!t_basis->distributed()); + CAROM_VERIFY(!t_basis.distributed()); // Get the number of basis vectors and the size of each basis vector. CAROM_VERIFY(0 < num_f_basis_vectors_used - && num_f_basis_vectors_used <= s_basis->numColumns() - && num_f_basis_vectors_used <= t_basis->numColumns()); + && num_f_basis_vectors_used <= s_basis.numColumns() + && num_f_basis_vectors_used <= t_basis.numColumns()); CAROM_VERIFY(num_samples_req > 0); const int num_basis_vectors = - std::min(num_f_basis_vectors_used, s_basis->numColumns()); + std::min(num_f_basis_vectors_used, s_basis.numColumns()); const int num_samples = num_samples_req; const int numExcluded = excludeFinalTime ? 1 : 0; - CAROM_VERIFY(num_samples <= t_basis->numRows() - numExcluded); - const int s_size = s_basis->numRows(); - const int t_size = t_basis->numRows(); + CAROM_VERIFY(num_samples <= t_basis.numRows() - numExcluded); + const int s_size = s_basis.numRows(); + const int t_size = t_basis.numRows(); const int ns_mod_nr = num_samples % num_basis_vectors; int ns = 0; @@ -71,7 +71,7 @@ void SampleTemporalIndices(const Matrix* s_basis, for (int s=0; sitem(s, 0) * t_basis->item(t, 0); + error[t + (s*t_size)] = s_basis.item(s, 0) * t_basis.item(t, 0); } for (int i=0; iitem(s, col) * t_basis->item(t, col); + M.item(row, col) = s_basis.item(s, col) * t_basis.item(t, col); } } @@ -118,7 +118,7 @@ void SampleTemporalIndices(const Matrix* s_basis, for (int s = 0; s < s_size; ++s) { const int row = ti + (s*ns); - const double phi_i_s_t = s_basis->item(s, i) * t_basis->item(t, + const double phi_i_s_t = s_basis.item(s, i) * t_basis.item(t, i); // \phi_i(s,t) for (int col = 0; col < i; ++col) @@ -134,7 +134,7 @@ void SampleTemporalIndices(const Matrix* s_basis, for (int s=0; sitem(s, i) * t_basis->item(t, i); + error[t + (s*t_size)] = s_basis.item(s, i) * t_basis.item(t, i); } // Multiply MZphi by [\phi_0, ..., \phi_{i-1}], subtracting the result from error @@ -143,7 +143,7 @@ void SampleTemporalIndices(const Matrix* s_basis, for (int t=0; titem(s, j) * t_basis->item(t, j); + error[t + (s*t_size)] -= MZphi[j] * s_basis.item(s, j) * t_basis.item(t, j); } } @@ -203,8 +203,8 @@ void SampleTemporalIndices(const Matrix* s_basis, // Temporal basis t_basis is stored in its entirety on each process, of size (number of temporal DOFs) x (number of basis vectors) // In general, there may be multiple temporal basis vectors associated with each spatial basis vector, but here we assume for now // that there is only one, i.e. column j of s_basis corresponds to column j of t_basis. -void SampleSpatialIndices(const Matrix* s_basis, - const Matrix* t_basis, +void SampleSpatialIndices(const Matrix & s_basis, + const Matrix & t_basis, const int num_f_basis_vectors_used, const int num_t_samples, int* t_samples, @@ -260,25 +260,25 @@ void SampleSpatialIndices(const Matrix* s_basis, MPI_Op RowInfoOp; MPI_Op_create((MPI_User_function*)RowInfoMax, true, &RowInfoOp); - //CAROM_VERIFY(!t_basis->distributed()); + //CAROM_VERIFY(!t_basis.distributed()); // Get the number of basis vectors and the size of each basis vector. CAROM_VERIFY(0 < num_f_basis_vectors_used - && num_f_basis_vectors_used <= s_basis->numColumns() - && num_f_basis_vectors_used <= t_basis->numColumns()); + && num_f_basis_vectors_used <= s_basis.numColumns() + && num_f_basis_vectors_used <= t_basis.numColumns()); CAROM_VERIFY(num_samples_req > 0); // TODO: just replace num_samples with num_samples_req const int num_basis_vectors = - std::min(num_f_basis_vectors_used, s_basis->numColumns()); + std::min(num_f_basis_vectors_used, s_basis.numColumns()); //const int num_samples = num_samples_req > 0 ? num_samples_req : num_basis_vectors; const int num_samples = num_samples_req; CAROM_VERIFY(num_basis_vectors <= num_samples - && num_samples <= s_basis->numRows()); + && num_samples <= s_basis.numRows()); CAROM_VERIFY(num_samples == f_basis_sampled.numRows() && num_basis_vectors == f_basis_sampled.numColumns()); CAROM_VERIFY(!f_basis_sampled.distributed()); - const int s_size = s_basis->numRows(); - const int t_size = t_basis->numRows(); + const int s_size = s_basis.numRows(); + const int t_size = t_basis.numRows(); const int ns_mod_nr = num_samples % num_basis_vectors; int ns = 0; @@ -308,7 +308,7 @@ void SampleSpatialIndices(const Matrix* s_basis, for (int s=0; sitem(s, 0) * t_basis->item(t, 0); + error[t + (s*t_size)] = s_basis.item(s, 0) * t_basis.item(t, 0); } for (int i=0; iitem(s, col) * t_basis->item(t, col); + M.item(row, col) = s_basis.item(s, col) * t_basis.item(t, col); } } @@ -350,7 +350,7 @@ void SampleSpatialIndices(const Matrix* s_basis, const int t = t_samples[ti]; const int row = ti + (j*num_t_samples); - M.item(row, k) = tmp_fs.item(j, k) * t_basis->item(t, k); + M.item(row, k) = tmp_fs.item(j, k) * t_basis.item(t, k); } } @@ -374,7 +374,7 @@ void SampleSpatialIndices(const Matrix* s_basis, { const int t = t_samples[ti]; const int row = ti + (si*num_t_samples); - const double phi_i_s_t = s_basis->item(s, i) * t_basis->item(t, i); // \phi_i(s,t) + const double phi_i_s_t = s_basis.item(s, i) * t_basis.item(t, i); // \phi_i(s,t) for (int col = 0; col < i; ++col) { MZphi[col] += M.item(row, col) * phi_i_s_t; @@ -394,7 +394,7 @@ void SampleSpatialIndices(const Matrix* s_basis, const int t = t_samples[ti]; const int row = ti + (j*num_t_samples); - const double phi_i_s_t = s_basis->item(j, i) * t_basis->item(t, + const double phi_i_s_t = s_basis.item(j, i) * t_basis.item(t, i); // \phi_i(s,t) for (int k = 0; k < i; ++k) @@ -406,7 +406,7 @@ void SampleSpatialIndices(const Matrix* s_basis, for (int s=0; sitem(s, i) * t_basis->item(t, i); + error[t + (s*t_size)] = s_basis.item(s, i) * t_basis.item(t, i); } // Multiply MZphi by [\phi_0, ..., \phi_{i-1}], subtracting the result from error @@ -415,7 +415,7 @@ void SampleSpatialIndices(const Matrix* s_basis, for (int t=0; titem(s, j) * t_basis->item(t, j); + error[t + (s*t_size)] -= MZphi[j] * s_basis.item(s, j) * t_basis.item(t, j); } } @@ -467,7 +467,7 @@ void SampleSpatialIndices(const Matrix* s_basis, // Now get the sampled row of the spatial basis. if (f_bv_max_global.proc == myid) { for (int k = 0; k < num_basis_vectors; ++k) { - sampled_row[k] = s_basis->item(f_bv_max_global.row, k); + sampled_row[k] = s_basis.item(f_bv_max_global.row, k); } } MPI_Bcast(sampled_row.data(), num_basis_vectors, MPI_DOUBLE, @@ -510,8 +510,8 @@ void SampleSpatialIndices(const Matrix* s_basis, MPI_Op_free(&RowInfoOp); } -void SpaceTimeSampling(const Matrix* s_basis, - const Matrix* t_basis, +void SpaceTimeSampling(const Matrix & s_basis, + const Matrix & t_basis, const int num_f_basis_vectors_used, std::vector& t_samples, int* f_sampled_row, @@ -528,8 +528,8 @@ void SpaceTimeSampling(const Matrix* s_basis, // This algorithm is sequential greedy sampling of temporal then spatial indices. // TODO: for now, we assume one temporal basis vector for each spatial basis vector. This should be generalized. - CAROM_VERIFY(s_basis->numColumns() == num_f_basis_vectors_used - && t_basis->numColumns() == num_f_basis_vectors_used); + CAROM_VERIFY(s_basis.numColumns() == num_f_basis_vectors_used + && t_basis.numColumns() == num_f_basis_vectors_used); // First, sample temporal indices. CAROM_VERIFY(t_samples.size() == num_t_samples_req); @@ -553,7 +553,7 @@ void SpaceTimeSampling(const Matrix* s_basis, } void GetSampledSpaceTimeBasis(std::vector const& t_samples, - const Matrix* t_basis, + const Matrix& t_basis, Matrix const& s_basis_sampled, Matrix& f_basis_sampled_inv) { @@ -572,7 +572,7 @@ void GetSampledSpaceTimeBasis(std::vector const& t_samples, const int t = t_samples[ti]; for (int j=0; jitem(t, j); + j) * t_basis.item(t, j); } } diff --git a/lib/hyperreduction/STSampling.h b/lib/hyperreduction/STSampling.h index d54ccf0c5..7b7ffee8b 100644 --- a/lib/hyperreduction/STSampling.h +++ b/lib/hyperreduction/STSampling.h @@ -37,8 +37,8 @@ namespace CAROM { * @param[in] excludeFinalTime Whether to exclude the final time index as a temporal sample. */ void -SpaceTimeSampling(const Matrix* s_basis, - const Matrix* t_basis, +SpaceTimeSampling(const Matrix & s_basis, + const Matrix & t_basis, const int num_f_basis_vectors_used, std::vector& t_samples, int* f_sampled_row, @@ -51,7 +51,7 @@ SpaceTimeSampling(const Matrix* s_basis, const bool excludeFinalTime = false); void GetSampledSpaceTimeBasis(std::vector const& t_samples, - const Matrix* t_basis, + const Matrix & t_basis, Matrix const& s_basis_sampled, Matrix& f_basis_sampled_inv); diff --git a/lib/linalg/BasisGenerator.cpp b/lib/linalg/BasisGenerator.cpp index 29c5946ae..6bdb80671 100644 --- a/lib/linalg/BasisGenerator.cpp +++ b/lib/linalg/BasisGenerator.cpp @@ -55,7 +55,7 @@ BasisGenerator::BasisGenerator( } if (!basis_file_name.empty()) { - d_basis_writer = new BasisWriter(this, basis_file_name, file_format); + d_basis_writer = new BasisWriter(*this, basis_file_name, file_format); } d_update_right_SV = options.update_right_SV; if (incremental) diff --git a/lib/linalg/BasisWriter.cpp b/lib/linalg/BasisWriter.cpp index 5d28246f7..4d6d9175d 100644 --- a/lib/linalg/BasisWriter.cpp +++ b/lib/linalg/BasisWriter.cpp @@ -23,7 +23,7 @@ namespace CAROM { BasisWriter::BasisWriter( - BasisGenerator* basis_generator, + BasisGenerator & basis_generator, const std::string& base_file_name, Database::formats db_format) : d_basis_generator(basis_generator), @@ -33,7 +33,6 @@ BasisWriter::BasisWriter( d_database(NULL), d_snap_database(NULL) { - CAROM_ASSERT(basis_generator != 0); CAROM_ASSERT(!base_file_name.empty()); int mpi_init; @@ -80,7 +79,7 @@ BasisWriter::writeBasis(const std::string& kind) if (kind == "basis") { d_database->create(full_file_name, MPI_COMM_WORLD); - std::shared_ptr basis = d_basis_generator->getSpatialBasis(); + std::shared_ptr basis = d_basis_generator.getSpatialBasis(); /* spatial basis is always distributed */ CAROM_VERIFY(basis->distributed()); int num_rows = basis->numRows(); @@ -95,8 +94,8 @@ BasisWriter::writeBasis(const std::string& kind) sprintf(tmp, "spatial_basis"); d_database->putDoubleArray(tmp, &basis->item(0, 0), num_rows*num_cols, true); - if (d_basis_generator->updateRightSV()) { - std::shared_ptr tbasis = d_basis_generator->getTemporalBasis(); + if (d_basis_generator.updateRightSV()) { + std::shared_ptr tbasis = d_basis_generator.getTemporalBasis(); /* temporal basis is always not distributed */ CAROM_VERIFY(!tbasis->distributed()); num_rows = tbasis->numRows(); @@ -109,7 +108,7 @@ BasisWriter::writeBasis(const std::string& kind) d_database->putDoubleArray(tmp, &tbasis->item(0, 0), num_rows*num_cols); } - std::shared_ptr sv = d_basis_generator->getSingularValues(); + std::shared_ptr sv = d_basis_generator.getSingularValues(); /* singular values are always not distributed */ CAROM_VERIFY(!sv->distributed()); int sv_dim = sv->dim(); @@ -125,7 +124,7 @@ BasisWriter::writeBasis(const std::string& kind) d_snap_database->create(snap_file_name, MPI_COMM_WORLD); std::shared_ptr snapshots = - d_basis_generator->getSnapshotMatrix(); + d_basis_generator.getSnapshotMatrix(); /* snapshot matrix is always distributed */ CAROM_VERIFY(snapshots->distributed()); int num_rows = snapshots->numRows(); // d_dim diff --git a/lib/linalg/BasisWriter.h b/lib/linalg/BasisWriter.h index 9684460d3..b9f1580b6 100644 --- a/lib/linalg/BasisWriter.h +++ b/lib/linalg/BasisWriter.h @@ -40,7 +40,7 @@ class BasisWriter { * Database. */ BasisWriter( - BasisGenerator* basis_generator, + BasisGenerator & basis_generator, const std::string& base_file_name, Database::formats db_format = Database::formats::HDF5); @@ -77,7 +77,7 @@ class BasisWriter { /** * @brief Basis generator whose basis vectors are being written. */ - BasisGenerator* d_basis_generator; + BasisGenerator & d_basis_generator; /** * @brief Database to which basis vectors are being written. diff --git a/lib/linalg/Matrix.cpp b/lib/linalg/Matrix.cpp index 92674c193..6db72f818 100644 --- a/lib/linalg/Matrix.cpp +++ b/lib/linalg/Matrix.cpp @@ -2180,30 +2180,30 @@ SerialSVDDecomposition SerialSVD(Matrix* A) // Compute the product A^T * B, where A is represented by the space-time // product of As and At, and likewise for B. -std::unique_ptr SpaceTimeProduct(const CAROM::Matrix* As, - const CAROM::Matrix* At, - const CAROM::Matrix* Bs, const CAROM::Matrix* Bt, +std::unique_ptr SpaceTimeProduct(const CAROM::Matrix & As, + const CAROM::Matrix & At, + const CAROM::Matrix & Bs, const CAROM::Matrix & Bt, const std::vector *tscale, const bool At0at0, const bool Bt0at0, const bool lagB, const bool skip0) { // TODO: implement reduction in parallel for the spatial matrices - CAROM_VERIFY(As->distributed() && Bs->distributed()); + CAROM_VERIFY(As.distributed() && Bs.distributed()); const int AtOS = At0at0 ? 1 : 0; const int BtOS0 = Bt0at0 ? 1 : 0; const int BtOS = BtOS0 + (lagB ? 1 : 0); - const int nrows = As->numColumns(); - const int ncols = Bs->numColumns(); + const int nrows = As.numColumns(); + const int ncols = Bs.numColumns(); - const int nspace = As->numRows(); - const int ntime = At->numRows() + AtOS; + const int nspace = As.numRows(); + const int ntime = At.numRows() + AtOS; - CAROM_VERIFY(nspace == Bs->numRows() && ntime == Bt->numRows() + BtOS0); + CAROM_VERIFY(nspace == Bs.numRows() && ntime == Bt.numRows() + BtOS0); // For now, we assume one time vector for each space vector - CAROM_VERIFY(nrows == At->numColumns() && ncols == Bt->numColumns()); + CAROM_VERIFY(nrows == At.numColumns() && ncols == Bt.numColumns()); //const int k0 = (At0at0 || Bt0at0 || lagB) std::max(AtOS, BtOS) : 0; const int k0AB = std::max(AtOS, BtOS); @@ -2224,13 +2224,13 @@ std::unique_ptr SpaceTimeProduct(const CAROM::Matrix* As, { //const double At_k = (At0at0 && k == 0) ? 0.0 : At->item(k - AtOS,i); //const double Bt_k = (Bt0at0 && k == 0) ? 0.0 : Bt->item(k - BtOS,j); - const double At_k = At->item(k - AtOS,i); - const double Bt_k = Bt->item(k - BtOS,j); + const double At_k = At.item(k - AtOS,i); + const double Bt_k = Bt.item(k - BtOS,j); const double ts = (tscale == NULL) ? 1.0 : (*tscale)[k - 1]; double spij = 0.0; // sum over spatial entries for (int m=0; mitem(m,i) * Bs->item(m,j); + spij += As.item(m,i) * Bs.item(m,j); pij += spij * ts * At_k * Bt_k; } diff --git a/lib/linalg/Matrix.h b/lib/linalg/Matrix.h index c17be2ce5..d6e094f42 100644 --- a/lib/linalg/Matrix.h +++ b/lib/linalg/Matrix.h @@ -743,9 +743,8 @@ class Matrix * @param[in] col The column of the Matrix value requested. */ const double& - item( - int row, - int col) const + item(int row, + int col) const { CAROM_ASSERT((0 <= row) && (row < numRows())); CAROM_ASSERT((0 <= col) && (col < numColumns())); @@ -766,9 +765,8 @@ class Matrix * @param[in] col The column of the Matrix value requested. */ double& - item( - int row, - int col) + item(int row, + int col) { CAROM_ASSERT((0 <= row) && (row < numRows())); CAROM_ASSERT((0 <= col) && (col < numColumns())); @@ -1207,9 +1205,9 @@ EigenPair SymmetricRightEigenSolve(const Matrix & A); */ ComplexEigenPair NonSymmetricRightEigenSolve(const Matrix & A); -std::unique_ptr SpaceTimeProduct(const CAROM::Matrix* As, - const CAROM::Matrix* At, const CAROM::Matrix* Bs, - const CAROM::Matrix* Bt, +std::unique_ptr SpaceTimeProduct(const CAROM::Matrix & As, + const CAROM::Matrix & At, const CAROM::Matrix & Bs, + const CAROM::Matrix & Bt, const std::vector *tscale=NULL, const bool At0at0=false, const bool Bt0at0=false, const bool lagB=false, const bool skip0=false); diff --git a/lib/linalg/Vector.h b/lib/linalg/Vector.h index 3f9322770..bbe25d525 100644 --- a/lib/linalg/Vector.h +++ b/lib/linalg/Vector.h @@ -465,8 +465,7 @@ class Vector * @return The requested component of the Vector on this processor. */ const double& - item( - int i) const + item(int i) const { CAROM_ASSERT((0 <= i) && (i < dim())); return d_vec[i]; @@ -484,8 +483,7 @@ class Vector * @return The requested component of the Vector on this processor. */ double& - item( - int i) + item(int i) { CAROM_ASSERT((0 <= i) && (i < dim())); return d_vec[i]; diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index fdccabc83..365dc28df 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -335,7 +335,7 @@ IncrementalSVD::buildIncrementalSVD( // Create Q. double* Q; - constructQ(Q, &l, k); + constructQ(Q, l, k); // Now get the singular value decomposition of Q. Matrix* A; @@ -356,7 +356,7 @@ IncrementalSVD::buildIncrementalSVD( // This sample is linearly dependent and we are not skipping linearly // dependent samples. if(d_rank == 0) std::cout << "adding linearly dependent sample!\n"; - addLinearlyDependentSample(A, W, sigma); + addLinearlyDependentSample(*A, *W, *sigma); delete sigma; } else if (!linearly_dependent_sample) { @@ -370,7 +370,7 @@ IncrementalSVD::buildIncrementalSVD( // addNewSample will assign sigma to d_S hence it should not be // deleted upon return. - addNewSample(j.get(), A, W, sigma); + addNewSample(*j, *A, *W, *sigma); } delete A; delete W; @@ -389,11 +389,10 @@ IncrementalSVD::buildIncrementalSVD( void IncrementalSVD::constructQ( double*& Q, - const Vector* l, + const Vector & l, double k) { - CAROM_VERIFY(l != 0); - CAROM_VERIFY(l->dim() == numSamples()); + CAROM_VERIFY(l.dim() == numSamples()); // Create Q. Q = new double [(d_num_samples+1)*(d_num_samples+1)]; @@ -413,7 +412,7 @@ IncrementalSVD::constructQ( } q_idx += d_num_samples+1; } - Q[q_idx] = l->item(row); + Q[q_idx] = l.item(row); } q_idx = d_num_samples; for (int col = 0; col < d_num_samples; ++col) { diff --git a/lib/linalg/svd/IncrementalSVD.h b/lib/linalg/svd/IncrementalSVD.h index a37f5f03c..5e4bcb2c6 100644 --- a/lib/linalg/svd/IncrementalSVD.h +++ b/lib/linalg/svd/IncrementalSVD.h @@ -136,7 +136,6 @@ class IncrementalSVD : public SVD /** * @brief Construct the matrix Q whose SVD is needed. * - * @pre l != 0 * @pre l.dim() == numSamples() * * @param[out] Q The matrix to be constructed. [d_S,l; 0,k] @@ -146,7 +145,7 @@ class IncrementalSVD : public SVD void constructQ( double*& Q, - const Vector* l, + const Vector & l, double k); /** @@ -173,9 +172,6 @@ class IncrementalSVD : public SVD /** * @brief Add a linearly dependent sample to the SVD. * - * @pre A != 0 - * @pre sigma != 0 - * * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. * @param[in] sigma The singular values. @@ -183,17 +179,13 @@ class IncrementalSVD : public SVD virtual void addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma) = 0; + const Matrix & A, + const Matrix & W, + const Matrix & sigma) = 0; /** * @brief Add a new, unique sample to the SVD. * - * @pre j != 0 - * @pre A != 0 - * @pre sigma != 0 - * * @param[in] j The new column of d_U. * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. @@ -202,10 +194,10 @@ class IncrementalSVD : public SVD virtual void addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma) = 0; + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma) = 0; /** * @brief The number of samples stored. @@ -221,8 +213,6 @@ class IncrementalSVD : public SVD /** * @brief Computes and returns the orthogonality of m. * - * @pre m != 0 - * * @param[in] m The matrix to check. * * @return The orthogonality of m. diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index 511285014..722df4568 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -193,7 +193,7 @@ IncrementalSVDBrand::buildIncrementalSVD( Vector U_mult_u(d_U->transposeMult(u_vec)->getData(), d_num_samples, false); Vector l(d_Up->numColumns(), false); d_Up->transposeMult(U_mult_u, l); - constructQ(Q, &l, k); + constructQ(Q, l, k); // Now get the singular value decomposition of Q. Matrix* A; @@ -214,7 +214,7 @@ IncrementalSVDBrand::buildIncrementalSVD( // This sample is linearly dependent and we are not skipping linearly // dependent samples. if(d_rank == 0) std::cout << "adding linearly dependent sample!\n"; - addLinearlyDependentSample(A, W, sigma); + addLinearlyDependentSample(*A, *W, *sigma); delete sigma; } else if (!linearly_dependent_sample) { @@ -228,7 +228,7 @@ IncrementalSVDBrand::buildIncrementalSVD( // addNewSample will assign sigma to d_S hence it should not be // deleted upon return. - addNewSample(j, A, W, sigma); + addNewSample(*j, *A, *W, *sigma); delete j; } delete A; @@ -338,22 +338,19 @@ IncrementalSVDBrand::computeBasis() void IncrementalSVDBrand::addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma) + const Matrix & A, + const Matrix & W, + const Matrix & sigma) { - CAROM_VERIFY(A != 0); - CAROM_VERIFY(sigma != 0); - // Chop a row and a column off of A to form Amod. Also form // d_S by chopping a row and a column off of sigma. Matrix Amod(d_num_samples, d_num_samples, false); for (int row = 0; row < d_num_samples; ++row) { for (int col = 0; col < d_num_samples; ++col) { - Amod.item(row, col) = A->item(row, col); + Amod.item(row, col) = A.item(row, col); if (row == col) { - d_S->item(col) = sigma->item(row, col); + d_S->item(col) = sigma.item(row, col); } } } @@ -375,13 +372,13 @@ IncrementalSVDBrand::addLinearlyDependentSample( for (int col = 0; col < d_num_samples; ++col) { double new_d_W_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_W_entry += d_W->item(row, entry)*W->item(entry, col); + new_d_W_entry += d_W->item(row, entry)*W.item(entry, col); } new_d_W->item(row, col) = new_d_W_entry; } } for (int col = 0; col < d_num_samples; ++col) { - new_d_W->item(d_num_rows_of_W, col) = W->item(d_num_samples, col); + new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } delete d_W; d_W = new_d_W; @@ -392,22 +389,18 @@ IncrementalSVDBrand::addLinearlyDependentSample( void IncrementalSVDBrand::addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma) + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma) { - CAROM_VERIFY(j != 0); - CAROM_VERIFY(A != 0); - CAROM_VERIFY(sigma != 0); - // Add j as a new column of d_U. Matrix* newU = new Matrix(d_dim, d_num_samples+1, true); for (int row = 0; row < d_dim; ++row) { for (int col = 0; col < d_num_samples; ++col) { newU->item(row, col) = d_U->item(row, col); } - newU->item(row, d_num_samples) = j->item(row); + newU->item(row, d_num_samples) = j.item(row); } d_U.reset(newU); @@ -423,13 +416,13 @@ IncrementalSVDBrand::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { double new_d_W_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_W_entry += d_W->item(row, entry)*W->item(entry, col); + new_d_W_entry += d_W->item(row, entry)*W.item(entry, col); } new_d_W->item(row, col) = new_d_W_entry; } } for (int col = 0; col < d_num_samples+1; ++col) { - new_d_W->item(d_num_rows_of_W, col) = W->item(d_num_samples, col); + new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } delete d_W; d_W = new_d_W; @@ -445,21 +438,21 @@ IncrementalSVDBrand::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { double new_d_Up_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_Up_entry += d_Up->item(row, entry)*A->item(entry, col); + new_d_Up_entry += d_Up->item(row, entry)*A.item(entry, col); } new_d_Up->item(row, col) = new_d_Up_entry; } } for (int col = 0; col < d_num_samples+1; ++col) { - new_d_Up->item(d_num_samples, col) = A->item(d_num_samples, col); + new_d_Up->item(d_num_samples, col) = A.item(d_num_samples, col); } d_Up.reset(new_d_Up); // d_S = sigma. - int num_dim = std::min(sigma->numRows(), sigma->numColumns()); + int num_dim = std::min(sigma.numRows(), sigma.numColumns()); d_S.reset(new Vector(num_dim, false)); for (int i = 0; i < num_dim; i++) { - d_S->item(i) = sigma->item(i,i); + d_S->item(i) = sigma.item(i,i); } // We now have another sample. diff --git a/lib/linalg/svd/IncrementalSVDBrand.h b/lib/linalg/svd/IncrementalSVDBrand.h index 4e7d374cf..35cdf9f0d 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.h +++ b/lib/linalg/svd/IncrementalSVDBrand.h @@ -134,27 +134,19 @@ class IncrementalSVDBrand : public IncrementalSVD /** * @brief Add a linearly dependent sample to the SVD. * - * @pre A != 0 - * @pre sigma != 0 - * * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. * @param[in] sigma The singular values. */ void addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma); + const Matrix & A, + const Matrix & W, + const Matrix & sigma); /** * @brief Add a new, unique sample to the SVD. * - * @pre j != 0 - * @pre A != 0 - * @pre W != 0 - * @pre sigma != 0 - * * @param[in] j The new column of d_U. * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. @@ -162,10 +154,10 @@ class IncrementalSVDBrand : public IncrementalSVD */ void addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma); + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma); /** * @brief The matrix U'. U' is not distributed and the entire matrix diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp index 4bac72750..c2a663504 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp @@ -182,22 +182,19 @@ IncrementalSVDFastUpdate::computeBasis() void IncrementalSVDFastUpdate::addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma) + const Matrix & A, + const Matrix & W, + const Matrix & sigma) { - CAROM_VERIFY(A != 0); - CAROM_VERIFY(sigma != 0); - // Chop a row and a column off of A to form Amod. Also form // d_S by chopping a row and a column off of sigma. Matrix Amod(d_num_samples, d_num_samples, false); for (int row = 0; row < d_num_samples; ++row) { for (int col = 0; col < d_num_samples; ++col) { - Amod.item(row, col) = A->item(row, col); + Amod.item(row, col) = A.item(row, col); if (row == col) { - d_S->item(col) = sigma->item(row, col); + d_S->item(col) = sigma.item(row, col); } } } @@ -219,13 +216,13 @@ IncrementalSVDFastUpdate::addLinearlyDependentSample( for (int col = 0; col < d_num_samples; ++col) { double new_d_W_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_W_entry += d_W->item(row, entry)*W->item(entry, col); + new_d_W_entry += d_W->item(row, entry)*W.item(entry, col); } new_d_W->item(row, col) = new_d_W_entry; } } for (int col = 0; col < d_num_samples; ++col) { - new_d_W->item(d_num_rows_of_W, col) = W->item(d_num_samples, col); + new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } delete d_W; d_W = new_d_W; @@ -236,22 +233,18 @@ IncrementalSVDFastUpdate::addLinearlyDependentSample( void IncrementalSVDFastUpdate::addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma) + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma) { - CAROM_VERIFY(j != 0); - CAROM_VERIFY(A != 0); - CAROM_VERIFY(sigma != 0); - // Add j as a new column of d_U. Matrix* newU = new Matrix(d_dim, d_num_samples+1, true); for (int row = 0; row < d_dim; ++row) { for (int col = 0; col < d_num_samples; ++col) { newU->item(row, col) = d_U->item(row, col); } - newU->item(row, d_num_samples) = j->item(row); + newU->item(row, d_num_samples) = j.item(row); } d_U.reset(newU); @@ -267,13 +260,13 @@ IncrementalSVDFastUpdate::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { double new_d_W_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_W_entry += d_W->item(row, entry)*W->item(entry, col); + new_d_W_entry += d_W->item(row, entry)*W.item(entry, col); } new_d_W->item(row, col) = new_d_W_entry; } } for (int col = 0; col < d_num_samples+1; ++col) { - new_d_W->item(d_num_rows_of_W, col) = W->item(d_num_samples, col); + new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } delete d_W; d_W = new_d_W; @@ -289,21 +282,21 @@ IncrementalSVDFastUpdate::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { double new_d_Up_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_Up_entry += d_Up->item(row, entry)*A->item(entry, col); + new_d_Up_entry += d_Up->item(row, entry)*A.item(entry, col); } new_d_Up->item(row, col) = new_d_Up_entry; } } for (int col = 0; col < d_num_samples+1; ++col) { - new_d_Up->item(d_num_samples, col) = A->item(d_num_samples, col); + new_d_Up->item(d_num_samples, col) = A.item(d_num_samples, col); } d_Up.reset(new_d_Up); // d_S = sigma. - int num_dim = std::min(sigma->numRows(), sigma->numColumns()); + int num_dim = std::min(sigma.numRows(), sigma.numColumns()); d_S.reset(new Vector(num_dim, false)); for (int i = 0; i < num_dim; i++) { - d_S->item(i) = sigma->item(i,i); + d_S->item(i) = sigma.item(i,i); } // We now have another sample. diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.h b/lib/linalg/svd/IncrementalSVDFastUpdate.h index 90e53bfd3..87aac3955 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.h +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.h @@ -90,27 +90,19 @@ class IncrementalSVDFastUpdate : public IncrementalSVD /** * @brief Add a linearly dependent sample to the SVD. * - * @pre A != 0 - * @pre sigma != 0 - * * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. * @param[in] sigma The singular values. */ void addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma); + const Matrix & A, + const Matrix & W, + const Matrix & sigma); /** * @brief Add a new, unique sample to the SVD. * - * @pre j != 0 - * @pre A != 0 - * @pre W != 0 - * @pre sigma != 0 - * * @param[in] j The new column of d_U. * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. @@ -118,10 +110,10 @@ class IncrementalSVDFastUpdate : public IncrementalSVD */ void addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma); + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma); /** * @brief The matrix U'. U' is not distributed and the entire matrix diff --git a/lib/linalg/svd/IncrementalSVDStandard.cpp b/lib/linalg/svd/IncrementalSVDStandard.cpp index 82f125085..c45de38e6 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.cpp +++ b/lib/linalg/svd/IncrementalSVDStandard.cpp @@ -104,22 +104,19 @@ IncrementalSVDStandard::computeBasis() void IncrementalSVDStandard::addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma) + const Matrix & A, + const Matrix & W, + const Matrix & sigma) { - CAROM_VERIFY(A != 0); - CAROM_VERIFY(sigma != 0); - // Chop a row and a column off of A to form Amod. Also form // d_S by chopping a row and a column off of sigma. Matrix Amod(d_num_samples, d_num_samples, false); for (int row = 0; row < d_num_samples; ++row) { for (int col = 0; col < d_num_samples; ++col) { - Amod.item(row, col) = A->item(row, col); + Amod.item(row, col) = A.item(row, col); if (row == col) { - d_S->item(col) = sigma->item(row, col); + d_S->item(col) = sigma.item(row, col); } } } @@ -137,13 +134,13 @@ IncrementalSVDStandard::addLinearlyDependentSample( for (int col = 0; col < d_num_samples; ++col) { double new_d_W_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_W_entry += d_W->item(row, entry)*W->item(entry, col); + new_d_W_entry += d_W->item(row, entry)*W.item(entry, col); } new_d_W->item(row, col) = new_d_W_entry; } } for (int col = 0; col < d_num_samples; ++col) { - new_d_W->item(d_num_rows_of_W, col) = W->item(d_num_samples, col); + new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } delete d_W; d_W = new_d_W; @@ -166,10 +163,10 @@ IncrementalSVDStandard::addLinearlyDependentSample( void IncrementalSVDStandard::addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma) + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma) { // Add j as a new column of d_U. Then multiply by A to form a new d_U. Matrix tmp(d_dim, d_num_samples+1, true); @@ -177,9 +174,9 @@ IncrementalSVDStandard::addNewSample( for (int col = 0; col < d_num_samples; ++col) { tmp.item(row, col) = d_U->item(row, col); } - tmp.item(row, d_num_samples) = j->item(row); + tmp.item(row, d_num_samples) = j.item(row); } - tmp.mult(*A, *d_U); + tmp.mult(A, *d_U); Matrix* new_d_W; if (d_update_right_SV) { @@ -188,22 +185,22 @@ IncrementalSVDStandard::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { double new_d_W_entry = 0.0; for (int entry = 0; entry < d_num_samples; ++entry) { - new_d_W_entry += d_W->item(row, entry)*W->item(entry, col); + new_d_W_entry += d_W->item(row, entry)*W.item(entry, col); } new_d_W->item(row, col) = new_d_W_entry; } } for (int col = 0; col < d_num_samples+1; ++col) { - new_d_W->item(d_num_rows_of_W, col) = W->item(d_num_samples, col); + new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } delete d_W; d_W = new_d_W; } - int num_dim = std::min(sigma->numRows(), sigma->numColumns()); + int num_dim = std::min(sigma.numRows(), sigma.numColumns()); d_S.reset(new Vector(num_dim, false)); for (int i = 0; i < num_dim; i++) { - d_S->item(i) = sigma->item(i,i); + d_S->item(i) = sigma.item(i,i); } // We now have another sample. diff --git a/lib/linalg/svd/IncrementalSVDStandard.h b/lib/linalg/svd/IncrementalSVDStandard.h index e9cfef4fd..d38613358 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.h +++ b/lib/linalg/svd/IncrementalSVDStandard.h @@ -89,27 +89,19 @@ class IncrementalSVDStandard : public IncrementalSVD /** * @brief Add a linearly dependent sample to the SVD. * - * @pre A != 0 - * @pre sigma != 0 - * * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. * @param[in] sigma The singular values. */ void addLinearlyDependentSample( - const Matrix* A, - const Matrix* W, - const Matrix* sigma); + const Matrix & A, + const Matrix & W, + const Matrix & sigma); /** * @brief Add a new, unique sample to the SVD. * - * @pre j != 0 - * @pre A != 0 - * @pre W != 0 - * @pre sigma != 0 - * * @param[in] j The new column of d_U. * @param[in] A The left singular vectors. * @param[in] W The right singular vectors. @@ -117,10 +109,10 @@ class IncrementalSVDStandard : public IncrementalSVD */ void addNewSample( - const Vector* j, - const Matrix* A, - const Matrix* W, - Matrix* sigma); + const Vector & j, + const Matrix & A, + const Matrix & W, + const Matrix & sigma); }; } diff --git a/unit_tests/test_IncrementalSVD.cpp b/unit_tests/test_IncrementalSVD.cpp index 3c8214d99..0e2d5eeca 100644 --- a/unit_tests/test_IncrementalSVD.cpp +++ b/unit_tests/test_IncrementalSVD.cpp @@ -80,18 +80,18 @@ class FakeIncrementalSVD : public CAROM::IncrementalSVD } void addLinearlyDependentSample - (__attribute__((unused)) const CAROM::Matrix *A, - __attribute__((unused)) const CAROM::Matrix *W, - __attribute__((unused)) const CAROM::Matrix *sigma) + (__attribute__((unused)) const CAROM::Matrix & A, + __attribute__((unused)) const CAROM::Matrix & W, + __attribute__((unused)) const CAROM::Matrix & sigma) { /* Do nothing */ } void addNewSample - (__attribute__((unused)) const CAROM::Vector *j, - __attribute__((unused)) const CAROM::Matrix *A, - __attribute__((unused)) const CAROM::Matrix *W, - __attribute__((unused)) CAROM::Matrix *sigma) + (__attribute__((unused)) const CAROM::Vector & j, + __attribute__((unused)) const CAROM::Matrix & A, + __attribute__((unused)) const CAROM::Matrix & W, + __attribute__((unused)) const CAROM::Matrix & sigma) { /* Do nothing */ } From 284146510cf52b21a9bdfbe21669444a8a3f34f8 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 30 Oct 2024 11:19:53 -0700 Subject: [PATCH 15/19] Fixed memory issues in mixed nonlinear diffusion example. --- examples/prom/mixed_nonlinear_diffusion.cpp | 336 ++++++++---------- .../prom/mixed_nonlinear_diffusion_eqp.hpp | 10 +- 2 files changed, 149 insertions(+), 197 deletions(-) diff --git a/examples/prom/mixed_nonlinear_diffusion.cpp b/examples/prom/mixed_nonlinear_diffusion.cpp index 80456a057..824e5b327 100644 --- a/examples/prom/mixed_nonlinear_diffusion.cpp +++ b/examples/prom/mixed_nonlinear_diffusion.cpp @@ -128,9 +128,6 @@ class NonlinearDiffusionGradientOperator : public Operator private: friend class NonlinearDiffusionOperator; - void SetParameters(Operator *C_solver_, Operator *M_solver_, - Operator *M_prime_, Operator *B_, const double dt_); - Operator *C_solver; Operator *M_solver; Operator *M_prime; @@ -157,18 +154,6 @@ NonlinearDiffusionGradientOperator::NonlinearDiffusionGradientOperator( { } -void NonlinearDiffusionGradientOperator::SetParameters(Operator *C_solver_, - Operator *M_solver_, - Operator *M_prime_, Operator *B_, const double dt_) -{ - C_solver = C_solver_; - M_solver = M_solver_; - M_prime = M_prime_; - B = B_; - - dt = dt_; -} - void NonlinearDiffusionGradientOperator::Mult(const Vector &x, Vector &y) const { // Gradient is I + dt C^{-1} B M(p)^{-1} B^T - dt C^{-1} B M(p)^{-1} M(a'(p)) M(p)^{-1} B^T @@ -210,26 +195,22 @@ class NonlinearDiffusionOperator : public TimeDependentOperator HypreParMatrix *BTmat; mutable HypreParMatrix Mprimemat; - mutable BlockOperator *fullOp; - mutable BlockOperator *fullGradient; - mutable BlockDiagonalPreconditioner *fullPrec; + mutable std::unique_ptr fullOp, fullGradient; + mutable std::unique_ptr fullPrec; Array block_trueOffsets; double current_dt; - mutable CGSolver - *M_solver; // Krylov solver for inverting the R mass matrix M + mutable CGSolver M_solver; // Krylov solver for inverting the R mass matrix M mutable HypreSmoother M_prec; // Preconditioner for the R mass matrix M mutable CGSolver C_solver; // Krylov solver for inverting the W mass matrix C HypreSmoother C_prec; // Preconditioner for the W mass matrix C - GMRESSolver *J_gmres; + std::unique_ptr J_gmres; NewtonSolver newton_solver; - NonlinearDiffusionGradientOperator *gradient; - double linear_solver_rel_tol; Vector p0; @@ -293,22 +274,22 @@ class RomOperator : public TimeDependentOperator double current_dt; bool oversampling; NewtonSolver newton_solver; - GMRESSolver *J_gmres; - CAROM::Matrix *BRsp, *BWsp; - CAROM::Vector *psp_librom, *psp_R_librom, *psp_W_librom; + std::unique_ptr J_gmres; + std::unique_ptr BRsp, BWsp; + std::unique_ptr psp_librom, psp_R_librom, psp_W_librom; Vector *psp; Vector *psp_R; Vector *psp_W; mutable Vector zR; mutable CAROM::Vector zY; mutable CAROM::Vector zN; - const CAROM::Matrix *Vsinv; + const std::shared_ptr Vsinv; // Data for source function - const CAROM::Matrix *Ssinv; + const std::shared_ptr Ssinv; mutable CAROM::Vector zS; mutable CAROM::Vector zT; - const std::shared_ptr S; + const std::shared_ptr S; mutable DenseMatrix J; @@ -321,16 +302,14 @@ class RomOperator : public TimeDependentOperator TransformedCoefficient aprime_coeff; mutable SumCoefficient a_plus_aprime_coeff; - CAROM::Vector *pfom_librom, *pfom_R_librom, *pfom_W_librom; - Vector *pfom; - Vector *pfom_R; - Vector *pfom_W; + std::unique_ptr pfom_librom, pfom_R_librom, pfom_W_librom, + zfomR_librom; + std::unique_ptr pfom, pfom_R, pfom_W; mutable Vector zfomR; mutable Vector zfomW; - CAROM::Vector *zfomR_librom; mutable CAROM::Vector VtzR; - CAROM::SampleMeshManager *smm; + std::shared_ptr smm; void PrintFDJacobian(const Vector &p) const; @@ -351,8 +330,7 @@ class RomOperator : public TimeDependentOperator int rank; protected: - CAROM::Matrix* BR; - CAROM::Matrix* CR; + std::unique_ptr BR, CR; const std::shared_ptr U_R; Vector y0; Vector dydt_prev; @@ -363,14 +341,16 @@ class RomOperator : public TimeDependentOperator RomOperator(NonlinearDiffusionOperator *fom_, NonlinearDiffusionOperator *fomSp_, const int rrdim_, const int rwdim_, const int nldim_, - CAROM::SampleMeshManager *smm_, std::shared_ptr V_R_, - std::shared_ptr U_R_, - std::shared_ptr V_W_, const CAROM::Matrix *Bsinv, + std::shared_ptr & smm_, + std::shared_ptr V_R_, std::shared_ptr U_R_, + std::shared_ptr V_W_, + const std::shared_ptr & Bsinv, const double newton_rel_tol, const double newton_abs_tol, const int newton_iter, - std::shared_ptr S_, const CAROM::Matrix *Ssinv_, + std::shared_ptr S_, + const std::shared_ptr & Ssinv_, const int myid, const bool hyperreduce_source_, const bool oversampling_, - const bool use_eqp, CAROM::Vector *eqpSol, - CAROM::Vector *eqpSol_S, const IntegrationRule *ir_eqp_); + const bool use_eqp, const CAROM::Vector & eqpSol, + const CAROM::Vector & eqpSol_S, const IntegrationRule *ir_eqp_); virtual void Mult(const Vector &y, Vector &dy_dt) const; void Mult_Hyperreduced(const Vector &y, Vector &dy_dt) const; @@ -385,8 +365,6 @@ class RomOperator : public TimeDependentOperator CAROM::Matrix V_W, V_R, VTU_R; CAROM::Matrix VTCS_W; - - virtual ~RomOperator(); }; // TODO: remove this by making online computation serial? @@ -436,9 +414,9 @@ void MergeBasis(const int dimFOM, const int nparam, const int max_num_snapshots, generator.finalSummary(1e-4, cutoff, "mergedSV_" + name); } -// TODO: move this to the library? -const CAROM::Matrix* GetSnapshotMatrix(const int dimFOM, const int nparam, - const int max_num_snapshots, std::string name) +std::shared_ptr +GetSnapshotMatrix(const int dimFOM, const int nparam, + const int max_num_snapshots, std::string name) { MFEM_VERIFY(nparam > 0, "Must specify a positive number of parameter sets"); @@ -455,20 +433,16 @@ const CAROM::Matrix* GetSnapshotMatrix(const int dimFOM, const int nparam, generator.loadSamples(snapshot_filename,"snapshot"); } - // TODO: this deep copy is inefficient, just to get around generator owning the matrix. - CAROM::Matrix *s = new CAROM::Matrix(*generator.getSnapshotMatrix()); - - return s; - //return generator.getSnapshotMatrix(); // BUG: the matrix is deleted when generator goes out of scope. + return generator.getSnapshotMatrix(); } int main(int argc, char *argv[]) { - // 1. Initialize MPI. - int num_procs, myid; - MPI_Init(&argc, &argv); - MPI_Comm_size(MPI_COMM_WORLD, &num_procs); - MPI_Comm_rank(MPI_COMM_WORLD, &myid); + // 1. Initialize MPI and HYPRE. + Mpi::Init(); + const int num_procs = Mpi::WorldSize(); + const int myid = Mpi::WorldRank(); + Hypre::Init(); // 2. Parse command-line options. nonlinear_problem = true; @@ -626,11 +600,11 @@ int main(int argc, char *argv[]) // 6. Define a parallel mesh by a partitioning of the serial mesh. Refine // this mesh further in parallel to increase the resolution. Once the // parallel mesh is defined, the serial mesh can be deleted. - ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); + ParMesh pmesh(MPI_COMM_WORLD, *mesh); delete mesh; for (int lev = 0; lev < par_ref_levels; lev++) { - pmesh->UniformRefinement(); + pmesh.UniformRefinement(); } #ifndef MFEM_USE_GSLIB @@ -646,10 +620,10 @@ int main(int argc, char *argv[]) if (pointwiseSnapshots) { - pmesh->EnsureNodes(); + pmesh.EnsureNodes(); const int dmdDim[3] = {pwx, pwy, pwz}; pws = new CAROM::PointwiseSnapshot(dim, dmdDim); - pws->SetMesh(pmesh); + pws->SetMesh(&pmesh); int snapshotSize = dmdDim[0]; for (int i=1; i wMFEM; + std::unique_ptr w, w_W; const int N1 = R_space.GetTrueVSize(); const int N2 = W_space.GetTrueVSize(); @@ -735,22 +704,20 @@ int main(int argc, char *argv[]) cout << myid << ": Local number of L2 unknowns: " << N2 << endl; cout << myid << ": Local number of RT unknowns: " << N1 << endl; - { - p_librom = new CAROM::Vector(fdim, true); - p.SetDataAndSize(&((*p_librom)(0)), fdim); - p_W_librom = new CAROM::Vector(&((*p_librom)(N1)), N2, true, false); + CAROM::Vector p_librom(fdim, true); + p.SetDataAndSize(&(p_librom(0)), fdim); + CAROM::Vector p_W_librom(&(p_librom(N1)), N2, true, false); - p = 0.0; - p_W = new Vector(p.GetData() + N1, N2); - p_gf.GetTrueDofs(*p_W); + p = 0.0; + Vector p_W(p.GetData() + N1, N2); + p_gf.GetTrueDofs(p_W); - source.SetSize(N2); - } + source.SetSize(N2); // 9. Initialize the diffusion operator and the VisIt visualization. NonlinearDiffusionOperator oper(R_space, W_space, newton_rel_tol, newton_abs_tol, newton_iter, p); // FOM operator - NonlinearDiffusionOperator *soper = 0; // Sample mesh operator + std::unique_ptr soper; // Sample mesh operator if (offline) { @@ -759,7 +726,7 @@ int main(int argc, char *argv[]) sol_name << "nldiff-init" << id_param << "." << setfill('0') << setw(6) << myid; ofstream omesh(mesh_name.str().c_str()); omesh.precision(precision); - pmesh->Print(omesh); + pmesh.Print(omesh); ofstream osol(sol_name.str().c_str()); osol.precision(precision); p_gf.Save(osol); @@ -769,9 +736,9 @@ int main(int argc, char *argv[]) if (visit) { if (offline) - visit_dc = new VisItDataCollection("nldiff-fom", pmesh); + visit_dc = new VisItDataCollection("nldiff-fom", &pmesh); else - visit_dc = new VisItDataCollection("nldiff-rom", pmesh); + visit_dc = new VisItDataCollection("nldiff-rom", &pmesh); visit_dc->RegisterField("temperature", &p_gf); visit_dc->SetCycle(0); @@ -787,7 +754,7 @@ int main(int argc, char *argv[]) sout.open(vishost, visport); sout << "parallel " << num_procs << " " << myid << endl; int good = sout.good(), all_good; - MPI_Allreduce(&good, &all_good, 1, MPI_INT, MPI_MIN, pmesh->GetComm()); + MPI_Allreduce(&good, &all_good, 1, MPI_INT, MPI_MIN, pmesh.GetComm()); if (!all_good) { sout.close(); @@ -802,7 +769,7 @@ int main(int argc, char *argv[]) else { sout.precision(precision); - sout << "solution\n" << *pmesh << p_gf; + sout << "solution\n" << pmesh << p_gf; sout << "pause\n"; sout << flush; if (myid == 0) @@ -839,7 +806,6 @@ int main(int argc, char *argv[]) RomOperator *romop = 0; - const CAROM::Matrix* B_librom = 0; std::shared_ptr BR_librom; std::shared_ptr FR_librom; std::shared_ptr BW_librom; @@ -848,10 +814,8 @@ int main(int argc, char *argv[]) int nsamp_R = -1; int nsamp_S = -1; - CAROM::SampleMeshManager *smm = nullptr; - - CAROM::Vector *eqpSol = nullptr; - CAROM::Vector *eqpSol_S = nullptr; + std::shared_ptr smm; + std::unique_ptr eqpSol, eqpSol_S; if (online) { @@ -912,8 +876,7 @@ int main(int argc, char *argv[]) CAROM::BasisReader *readerS = NULL; ParFiniteElementSpace *sp_R_space, *sp_W_space; - CAROM::Matrix *Bsinv = NULL; - CAROM::Matrix *Ssinv = NULL; + std::shared_ptr Bsinv, Ssinv; const IntegrationRule *ir0 = NULL; if (ir0 == NULL) @@ -929,17 +892,17 @@ int main(int argc, char *argv[]) if (use_eqp) { // EQP setup - eqpSol = new CAROM::Vector(ir0->GetNPoints() * R_space.GetNE(), true); + eqpSol.reset(new CAROM::Vector(ir0->GetNPoints() * R_space.GetNE(), true)); SetupEQP_snapshots(ir0, myid, &R_space, &W_space, nsets, BR_librom, GetSnapshotMatrix(R_space.GetTrueVSize(), nsets, max_num_snapshots, "R"), GetSnapshotMatrix(W_space.GetTrueVSize(), nsets, max_num_snapshots, "W"), preconditionNNLS, tolNNLS, maxNNLSnnz, *eqpSol); - if (writeSampleMesh) WriteMeshEQP(pmesh, myid, ir0->GetNPoints(), *eqpSol); + if (writeSampleMesh) WriteMeshEQP(&pmesh, myid, ir0->GetNPoints(), *eqpSol); if (problem == ANALYTIC) { - eqpSol_S = new CAROM::Vector(ir0->GetNPoints() * W_space.GetNE(), true); + eqpSol_S.reset(new CAROM::Vector(ir0->GetNPoints() * W_space.GetNE(), true)); SetupEQP_S_snapshots(ir0, myid, &W_space, BW_librom, GetSnapshotMatrix(W_space.GetTrueVSize(), nsets, max_num_snapshots, "S"), preconditionNNLS, tolNNLS, maxNNLSnnz, *eqpSol_S); @@ -961,7 +924,7 @@ int main(int argc, char *argv[]) } // Now execute the chosen sampling algorithm to get the sampling information. - Bsinv = new CAROM::Matrix(nsamp_R, nldim, false); + Bsinv.reset(new CAROM::Matrix(nsamp_R, nldim, false)); vector sample_dofs(nsamp_R); // Indices of the sampled rows hr.ComputeSamples(FR_librom, @@ -1006,7 +969,7 @@ int main(int argc, char *argv[]) nsamp_S = nsdim; } - Ssinv = new CAROM::Matrix(nsamp_S, nsdim, false); + Ssinv.reset(new CAROM::Matrix(nsamp_S, nsdim, false)); sample_dofs_S.resize(nsamp_S); hr.ComputeSamples(S_librom, @@ -1028,10 +991,10 @@ int main(int argc, char *argv[]) fespace[1] = &W_space; if (writeSampleMesh) - smm = new CAROM::SampleMeshManager(fespace, "samples", - ir0 ? ir0->GetNPoints() : 1); + smm.reset(new CAROM::SampleMeshManager(fespace, "samples", + ir0 ? ir0->GetNPoints() : 1)); else - smm = new CAROM::SampleMeshManager(fespace); + smm.reset(new CAROM::SampleMeshManager(fespace)); vector sample_dofs_empty; // Potential variable in W space has no sample DOFs. @@ -1064,11 +1027,11 @@ int main(int argc, char *argv[]) } } - w = new CAROM::Vector(rrdim + rwdim, false); - w_W = new CAROM::Vector(rwdim, false); + w.reset(new CAROM::Vector(rrdim + rwdim, false)); + w_W.reset(new CAROM::Vector(rwdim, false)); // Initialize w = B_W^T p. - BW_librom->transposeMult(*p_W_librom, *w_W); + BW_librom->transposeMult(p_W_librom, *w_W); for (int i=0; iGetTrueDofs(*sp_p_W); } - soper = new NonlinearDiffusionOperator(*sp_R_space, *sp_W_space, newton_rel_tol, - newton_abs_tol, newton_iter, sp_p); + soper.reset(new NonlinearDiffusionOperator(*sp_R_space, *sp_W_space, + newton_rel_tol, + newton_abs_tol, newton_iter, sp_p)); } - romop = new RomOperator(&oper, soper, rrdim, rwdim, nldim, smm, + romop = new RomOperator(&oper, soper.get(), rrdim, rwdim, nldim, smm, BR_librom, FR_librom, BW_librom, Bsinv, newton_rel_tol, newton_abs_tol, newton_iter, S_librom, Ssinv, myid, hyperreduce_source, - num_samples_req != -1, use_eqp, eqpSol, eqpSol_S, ir0); + num_samples_req != -1, use_eqp, *eqpSol, *eqpSol_S, ir0); ode_solver.Init(*romop); @@ -1177,8 +1141,8 @@ int main(int argc, char *argv[]) { oper.CopyDpDt_W(dpdt); - basis_generator_W->takeSample(p_W->GetData()); - basis_generator_W->computeNextSampleTime(p_W->GetData(), dpdt.GetData(), t); + basis_generator_W->takeSample(p_W.GetData()); + basis_generator_W->computeNextSampleTime(p_W.GetData(), dpdt.GetData(), t); } } @@ -1239,14 +1203,14 @@ int main(int argc, char *argv[]) { exsol.SetTime(t); - BroadcastUndistributedRomVector(w); + BroadcastUndistributedRomVector(w.get()); for (int i=0; iV_W.mult(*w_W, *p_W_librom); + romop->V_W.mult(*w_W, p_W_librom); - p_gf.SetFromTrueDofs(*p_W); + p_gf.SetFromTrueDofs(p_W); if (last_step) { @@ -1269,7 +1233,7 @@ int main(int argc, char *argv[]) const double fomNorm = sqrt(InnerProduct(MPI_COMM_WORLD, fom_solution, fom_solution)); //const double romNorm = sqrt(InnerProduct(MPI_COMM_WORLD, *p_W, *p_W)); - fom_solution -= *p_W; + fom_solution -= p_W; const double diffNorm = sqrt(InnerProduct(MPI_COMM_WORLD, fom_solution, fom_solution)); if (myid == 0) std::cout << "Relative l2 error of ROM solution " << diffNorm / @@ -1281,7 +1245,7 @@ int main(int argc, char *argv[]) } } else - p_gf.SetFromTrueDofs(*p_W); + p_gf.SetFromTrueDofs(p_W); if (problem == ANALYTIC) { @@ -1297,7 +1261,7 @@ int main(int argc, char *argv[]) if (visualization) { sout << "parallel " << num_procs << " " << myid << "\n"; - sout << "solution\n" << *pmesh << p_gf << flush; + sout << "solution\n" << pmesh << p_gf << flush; } if (visit) @@ -1310,7 +1274,7 @@ int main(int argc, char *argv[]) #ifdef MFEM_USE_GSLIB if (pointwiseSnapshots) { - p_gf.SetFromTrueDofs(*p_W); + p_gf.SetFromTrueDofs(p_W); pws->GetSnapshot(p_gf, pwsnap); ostringstream dmd_filename; @@ -1357,7 +1321,7 @@ int main(int argc, char *argv[]) // W space // TODO: why call computeNextSampleTime if you just do takeSample on every step anyway? - basis_generator_W->takeSample(p_W->GetData()); + basis_generator_W->takeSample(p_W.GetData()); basis_generator_W->writeSnapshot(); oper.GetSource(source); @@ -1371,9 +1335,10 @@ int main(int argc, char *argv[]) delete basis_generator_R; delete basis_generator_FR; delete basis_generator_W; - delete basis_generator_S; } + delete basis_generator_S; + // 11. Save the final solution in parallel. This output can be viewed later // using GLVis: "glvis -np -m nldiff-mesh -g nldiff-final". if (offline) @@ -1391,16 +1356,13 @@ int main(int argc, char *argv[]) fomsol.precision(precision); for (int i = 0; i < N2; ++i) { - fomsol << (*p_W)[i] << std::endl; + fomsol << p_W[i] << std::endl; } } // 12. Free the used memory. - delete pmesh; delete romop; - delete p_W; - #ifdef MFEM_USE_GSLIB delete pws; delete pwsnap_CAROM; @@ -1420,21 +1382,19 @@ NonlinearDiffusionOperator::NonlinearDiffusionOperator(ParFiniteElementSpace const int iter, const Vector &p) : TimeDependentOperator(fR.GetTrueVSize() + fW.GetTrueVSize(), 0.0), fespace_R(fR), fespace_W(fW), M(NULL), C(NULL), Bmat(NULL), BTmat(NULL), + Cmat(NULL), Mprime(NULL), current_dt(0.0), - newton_solver(fW.GetComm()), M_solver(NULL), C_solver(fW.GetComm()), + newton_solver(fW.GetComm()), C_solver(fW.GetComm()), M_solver(fR.GetComm()), zW(fW.GetTrueVSize()), yR(fR.GetTrueVSize()), - zR(fR.GetTrueVSize()), p0(height), dpdt_prev(height), - fullOp(NULL), fullGradient(NULL), fullPrec(NULL) + zR(fR.GetTrueVSize()), p0(height), dpdt_prev(height), Mmat(NULL) { - gradient = new NonlinearDiffusionGradientOperator(fR.GetTrueVSize(), - fW.GetTrueVSize()); - linear_solver_rel_tol = 1.0e-14; C = new ParBilinearForm(&fespace_W); C->AddDomainIntegrator(new MassIntegrator()); C->Assemble(); C->Finalize(); + delete Cmat; Cmat = C->ParallelAssemble(); C_solver.iterative_mode = false; @@ -1471,7 +1431,7 @@ NonlinearDiffusionOperator::NonlinearDiffusionOperator(ParFiniteElementSpace // Set the newton solve parameters //Solver *J_prec = new DSmoother(1); - J_gmres = new GMRESSolver(MPI_COMM_WORLD); + J_gmres.reset(new GMRESSolver(MPI_COMM_WORLD)); J_gmres->SetRelTol(linear_solver_rel_tol); J_gmres->SetAbsTol(0.0); J_gmres->SetMaxIter(1000); @@ -1625,6 +1585,7 @@ void NonlinearDiffusionOperator::SetParameters(const Vector &p) const M->AddDomainIntegrator(new VectorFEMassIntegrator(a_coeff)); M->Assemble(); M->Finalize(); + delete Mmat; Mmat = M->ParallelAssemble(); delete Mprime; @@ -1637,36 +1598,30 @@ void NonlinearDiffusionOperator::SetParameters(const Vector &p) const Mprimemat *= current_dt; - delete M_solver; - M_solver = new CGSolver(fespace_R.GetComm()); - - M_solver->iterative_mode = false; - M_solver->SetRelTol(linear_solver_rel_tol); - M_solver->SetAbsTol(0.0); - M_solver->SetMaxIter(1000); - M_solver->SetPrintLevel(-1); - M_solver->SetPreconditioner(M_prec); + M_solver.iterative_mode = false; + M_solver.SetRelTol(linear_solver_rel_tol); + M_solver.SetAbsTol(0.0); + M_solver.SetMaxIter(1000); + M_solver.SetPrintLevel(-1); + M_solver.SetPreconditioner(M_prec); { - M_solver->SetOperator(Mprimemat); + M_solver.SetOperator(Mprimemat); - delete fullOp; - fullOp = new BlockOperator(block_trueOffsets); + fullOp.reset(new BlockOperator(block_trueOffsets)); fullOp->SetBlock(0, 0, Mmat); fullOp->SetBlock(0, 1, BTmat); fullOp->SetBlock(1, 0, Bmat, -1.0); fullOp->SetBlock(1, 1, Cmat); - delete fullGradient; - fullGradient = new BlockOperator(block_trueOffsets); + fullGradient.reset(new BlockOperator(block_trueOffsets)); fullGradient->SetBlock(0, 0, &Mprimemat); fullGradient->SetBlock(0, 1, BTmat, current_dt); fullGradient->SetBlock(1, 0, Bmat, -current_dt); fullGradient->SetBlock(1, 1, Cmat); - delete fullPrec; - fullPrec = new BlockDiagonalPreconditioner(block_trueOffsets); - fullPrec->SetDiagonalBlock(0, M_solver); + fullPrec.reset(new BlockDiagonalPreconditioner(block_trueOffsets)); + fullPrec->SetDiagonalBlock(0, &M_solver); fullPrec->SetDiagonalBlock(1, &C_solver); J_gmres->SetPreconditioner(*fullPrec); } @@ -1677,35 +1632,36 @@ NonlinearDiffusionOperator::~NonlinearDiffusionOperator() delete M; delete Mprime; delete C; + delete Cmat; + delete Mmat; delete Bmat; - delete J_gmres; + delete BTmat; } RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, NonlinearDiffusionOperator *fomSp_, const int rrdim_, const int rwdim_, const int nldim_, - CAROM::SampleMeshManager *smm_, + std::shared_ptr & smm_, std::shared_ptr V_R_, std::shared_ptr U_R_, std::shared_ptr V_W_, - const CAROM::Matrix *Bsinv, + const std::shared_ptr & Bsinv, const double newton_rel_tol, const double newton_abs_tol, const int newton_iter, - std::shared_ptr S_, const CAROM::Matrix *Ssinv_, + std::shared_ptr S_, + const shared_ptr & Ssinv_, const int myid, const bool hyperreduce_source_, const bool oversampling_, const bool use_eqp, - CAROM::Vector *eqpSol, CAROM::Vector *eqpSol_S, + const CAROM::Vector & eqpSol, const CAROM::Vector & eqpSol_S, const IntegrationRule *ir_eqp_) - : TimeDependentOperator(rrdim_ + rwdim_, 0.0), - newton_solver(), - fom(fom_), fomSp(fomSp_), BR(NULL), rrdim(rrdim_), rwdim(rwdim_), nldim(nldim_), - smm(smm_), + : TimeDependentOperator(rrdim_ + rwdim_, 0.0), newton_solver(), + fom(fom_), fomSp(fomSp_), rrdim(rrdim_), rwdim(rwdim_), nldim(nldim_), + smm(smm_), Vsinv(Bsinv), nsamp_R(smm_ ? smm_->GetNumVarSamples("V") : 0), nsamp_S(hyperreduce_source_ && smm_ ? smm_->GetNumVarSamples("S") : 0), V_R(*V_R_), U_R(U_R_), V_W(*V_W_), VTU_R(rrdim_, nldim_, false), y0(height), dydt_prev(height), zY(nldim, false), - zN(std::max(nsamp_R, 1), false), - Vsinv(Bsinv), J(height), + zN(std::max(nsamp_R, 1), false), J(height), zS(std::max(nsamp_S, 1), false), zT(std::max(nsamp_S, 1), false), Ssinv(Ssinv_), VTCS_W(rwdim, std::max(nsamp_S, 1), false), S(S_), VtzR(rrdim_, false), hyperreduce_source(hyperreduce_source_), @@ -1715,13 +1671,14 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, aprime_coeff(&p_coeff, NonlinearCoefficientDerivative), a_plus_aprime_coeff(a_coeff, aprime_coeff), rank(myid) { + ; dydt_prev = 0.0; if (myid == 0 && !eqp) { zR.SetSize(fomSp_->zR.Size()); - BRsp = new CAROM::Matrix(fomSp->zR.Size(), rrdim, false); - BWsp = new CAROM::Matrix(fomSp->zW.Size(), rwdim, false); + BRsp.reset(new CAROM::Matrix(fomSp->zR.Size(), rrdim, false)); + BWsp.reset(new CAROM::Matrix(fomSp->zW.Size(), rwdim, false)); } V_R.transposeMult(*U_R, VTU_R); @@ -1734,8 +1691,8 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, // Compute BR = V_W^t B V_R and CR = V_W^t C V_W, and store them throughout the simulation. - BR = new CAROM::Matrix(rwdim, rrdim, false); - CR = new CAROM::Matrix(rwdim, rwdim, false); + BR.reset(new CAROM::Matrix(rwdim, rrdim, false)); + CR.reset(new CAROM::Matrix(rwdim, rwdim, false)); ComputeCtAB(*fom->Bmat, V_R, V_W, *BR); ComputeCtAB(*fom->Cmat, V_W, V_W, *CR); @@ -1753,7 +1710,7 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, { const double linear_solver_rel_tol = 1.0e-14; - J_gmres = new GMRESSolver; + J_gmres.reset(new GMRESSolver); J_gmres->SetRelTol(linear_solver_rel_tol); J_gmres->SetAbsTol(0.0); J_gmres->SetMaxIter(1000); @@ -1771,15 +1728,17 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, { const int spdim = fomSp->Height(); - psp_librom = new CAROM::Vector(spdim, false); + psp_librom.reset(new CAROM::Vector(spdim, false)); psp = new Vector(&((*psp_librom)(0)), spdim); // Define sub-vectors of psp. psp_R = new Vector(psp->GetData(), fomSp->zR.Size()); psp_W = new Vector(psp->GetData() + fomSp->zR.Size(), fomSp->zW.Size()); - psp_R_librom = new CAROM::Vector(psp_R->GetData(), psp_R->Size(), false, false); - psp_W_librom = new CAROM::Vector(psp_W->GetData(), psp_W->Size(), false, false); + psp_R_librom.reset(new CAROM::Vector(psp_R->GetData(), psp_R->Size(), false, + false)); + psp_W_librom.reset(new CAROM::Vector(psp_W->GetData(), psp_W->Size(), false, + false)); } } @@ -1790,27 +1749,28 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, { const int fdim = fom->Height(); - pfom_librom = new CAROM::Vector(fdim, false); - pfom = new Vector(&((*pfom_librom)(0)), fdim); + pfom_librom.reset(new CAROM::Vector(fdim, false)); + pfom.reset(new Vector(&((*pfom_librom)(0)), fdim)); // Define sub-vectors of pfom. - pfom_R = new Vector(pfom->GetData(), fom->zR.Size()); - pfom_W = new Vector(pfom->GetData() + fom->zR.Size(), fom->zW.Size()); + pfom_R.reset(new Vector(pfom->GetData(), fom->zR.Size())); + pfom_W.reset(new Vector(pfom->GetData() + fom->zR.Size(), fom->zW.Size())); - pfom_R_librom = new CAROM::Vector(pfom_R->GetData(), pfom_R->Size(), true, - false); - pfom_W_librom = new CAROM::Vector(pfom_W->GetData(), pfom_W->Size(), true, - false); + pfom_R_librom.reset(new CAROM::Vector(pfom_R->GetData(), pfom_R->Size(), + true, false)); + pfom_W_librom.reset(new CAROM::Vector(pfom_W->GetData(), pfom_W->Size(), + true, false)); zfomR.SetSize(fom->zR.Size()); - zfomR_librom = new CAROM::Vector(zfomR.GetData(), zfomR.Size(), false, false); + zfomR_librom.reset(new CAROM::Vector(zfomR.GetData(), zfomR.Size(), false, + false)); zfomW.SetSize(fom->zW.Size()); } else if (eqp) { - pfom_W_librom = new CAROM::Vector(fom->zW.Size(), true); - pfom_W = new Vector(pfom_W_librom->getData(), fom->zW.Size()); + pfom_W_librom.reset(new CAROM::Vector(fom->zW.Size(), true)); + pfom_W.reset(new Vector(pfom_W_librom->getData(), fom->zW.Size())); } if (hyperreduce_source && !eqp) @@ -1821,13 +1781,13 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, std::set elements; const int nqe = ir_eqp->GetWeights().Size(); - for (int i=0; idim(); ++i) + for (int i=0; i 1.0e-12) + if (eqpSol(i) > 1.0e-12) { const int e = i / nqe; // Element index elements.insert(e); - eqp_rw.push_back((*eqpSol)(i)); + eqp_rw.push_back(eqpSol(i)); eqp_qp.push_back(i); } } @@ -1843,13 +1803,13 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, // Setup eqp for the source std::set elements_S; - for (int i=0; idim(); ++i) + for (int i=0; i 1.0e-12) + if (eqpSol_S(i) > 1.0e-12) { const int e = i / nqe; // Element index elements_S.insert(e); - eqp_rw_S.push_back((*eqpSol_S)(i)); + eqp_rw_S.push_back(eqpSol_S(i)); eqp_qp_S.push_back(i); } } @@ -1903,12 +1863,6 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, } } -RomOperator::~RomOperator() -{ - delete BR; - delete CR; -} - void RomOperator::Mult_Hyperreduced(const Vector &dy_dt, Vector &res) const { MFEM_VERIFY(dy_dt.Size() == rrdim + rwdim && res.Size() == rrdim + rwdim, ""); @@ -2129,9 +2083,7 @@ void RomOperator::Mult_FullOrder(const Vector &dy_dt, Vector &res) const void RomOperator::Mult(const Vector &dy_dt, Vector &res) const { if (hyperreduce) - { Mult_Hyperreduced(dy_dt, res); - } else Mult_FullOrder(dy_dt, res); } diff --git a/examples/prom/mixed_nonlinear_diffusion_eqp.hpp b/examples/prom/mixed_nonlinear_diffusion_eqp.hpp index fe1c9b605..85aa663db 100644 --- a/examples/prom/mixed_nonlinear_diffusion_eqp.hpp +++ b/examples/prom/mixed_nonlinear_diffusion_eqp.hpp @@ -791,9 +791,9 @@ void SolveNNLS(const int rank, const double nnls_tol, const int maxNNLSnnz, void SetupEQP_snapshots(const IntegrationRule *ir0, const int rank, ParFiniteElementSpace *fespace_R, ParFiniteElementSpace *fespace_W, - const int nsets, const std::shared_ptr BR, - const CAROM::Matrix* BR_snapshots, - const CAROM::Matrix* BW_snapshots, + const int nsets, const std::shared_ptr & BR, + const std::shared_ptr & BR_snapshots, + const std::shared_ptr & BW_snapshots, const bool precondition, const double nnls_tol, const int maxNNLSnnz, CAROM::Vector & sol) @@ -905,8 +905,8 @@ void SetupEQP_snapshots(const IntegrationRule *ir0, const int rank, // Compute EQP solution from constraints on source snapshots. void SetupEQP_S_snapshots(const IntegrationRule *ir0, const int rank, ParFiniteElementSpace *fespace_W, - const std::shared_ptr BW, - const CAROM::Matrix* BS_snapshots, + const std::shared_ptr & BW, + const std::shared_ptr & BS_snapshots, const bool precondition, const double nnls_tol, const int maxNNLSnnz, CAROM::Vector & sol) From 5032943331f9622f450bf461467bbae0ccc476da Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Thu, 7 Nov 2024 11:54:52 -0800 Subject: [PATCH 16/19] Fixed memory leaks in DMD examples. --- examples/dmd/de_dg_advection_greedy.cpp | 146 ++++++++---------- .../de_parametric_heat_conduction_greedy.cpp | 13 +- .../dmd/parametric_dmdc_heat_conduction.cpp | 45 +++--- examples/dmd/parametric_dw_csv.cpp | 25 +-- examples/dmd/parametric_heat_conduction.cpp | 12 +- examples/dmd/parametric_tw_csv.cpp | 35 ++--- lib/algo/DMD.cpp | 6 + lib/algo/DMD.h | 2 +- lib/algo/DMDc.cpp | 25 ++- lib/algo/DMDc.h | 2 +- lib/algo/NonuniformDMD.h | 6 +- lib/algo/ParametricDMD.h | 10 +- lib/algo/ParametricDMDc.h | 10 +- 13 files changed, 160 insertions(+), 177 deletions(-) diff --git a/examples/dmd/de_dg_advection_greedy.cpp b/examples/dmd/de_dg_advection_greedy.cpp index 0dcb60d98..ce545bede 100644 --- a/examples/dmd/de_dg_advection_greedy.cpp +++ b/examples/dmd/de_dg_advection_greedy.cpp @@ -324,44 +324,44 @@ double simulation() // 6. Define the ODE solver used for time integration. Several explicit // Runge-Kutta methods are available. - ODESolver *ode_solver = NULL; + std::unique_ptr ode_solver; switch (ode_solver_type) { // Explicit methods case 1: - ode_solver = new ForwardEulerSolver; + ode_solver.reset(new ForwardEulerSolver); break; case 2: - ode_solver = new RK2Solver(1.0); + ode_solver.reset(new RK2Solver(1.0)); break; case 3: - ode_solver = new RK3SSPSolver; + ode_solver.reset(new RK3SSPSolver); break; case 4: - ode_solver = new RK4Solver; + ode_solver.reset(new RK4Solver); break; case 6: - ode_solver = new RK6Solver; + ode_solver.reset(new RK6Solver); break; // Implicit (L-stable) methods case 11: - ode_solver = new BackwardEulerSolver; + ode_solver.reset(new BackwardEulerSolver); break; case 12: - ode_solver = new SDIRK23Solver(2); + ode_solver.reset(new SDIRK23Solver(2)); break; case 13: - ode_solver = new SDIRK33Solver; + ode_solver.reset(new SDIRK33Solver); break; // Implicit A-stable methods (not L-stable) case 22: - ode_solver = new ImplicitMidpointSolver; + ode_solver.reset(new ImplicitMidpointSolver); break; case 23: - ode_solver = new SDIRK23Solver; + ode_solver.reset(new SDIRK23Solver); break; case 24: - ode_solver = new SDIRK34Solver; + ode_solver.reset(new SDIRK34Solver); break; default: if (myid == 0) @@ -389,19 +389,19 @@ double simulation() // 8. Define the parallel mesh by a partitioning of the serial mesh. Refine // this mesh further in parallel to increase the resolution. Once the // parallel mesh is defined, the serial mesh can be deleted. - ParMesh *pmesh = new ParMesh(MPI_COMM_WORLD, *mesh); + ParMesh pmesh(MPI_COMM_WORLD, *mesh); delete mesh; for (int lev = 0; lev < par_ref_levels; lev++) { - pmesh->UniformRefinement(); + pmesh.UniformRefinement(); } // 9. Define the parallel discontinuous DG finite element space on the // parallel refined mesh of the given polynomial order. DG_FECollection fec(order, dim, BasisType::GaussLobatto); - ParFiniteElementSpace *fes = new ParFiniteElementSpace(pmesh, &fec); + ParFiniteElementSpace fes(&pmesh, &fec); - HYPRE_BigInt global_vSize = fes->GlobalTrueVSize(); + HYPRE_BigInt global_vSize = fes.GlobalTrueVSize(); if (myid == 0) { cout << "Number of unknowns: " << global_vSize << endl; @@ -414,52 +414,51 @@ double simulation() FunctionCoefficient inflow(inflow_function); FunctionCoefficient u0(u0_function); - ParBilinearForm *m = new ParBilinearForm(fes); - ParBilinearForm *k = new ParBilinearForm(fes); + ParBilinearForm m(&fes); + ParBilinearForm k(&fes); if (pa) { - m->SetAssemblyLevel(AssemblyLevel::PARTIAL); - k->SetAssemblyLevel(AssemblyLevel::PARTIAL); + m.SetAssemblyLevel(AssemblyLevel::PARTIAL); + k.SetAssemblyLevel(AssemblyLevel::PARTIAL); } else if (ea) { - m->SetAssemblyLevel(AssemblyLevel::ELEMENT); - k->SetAssemblyLevel(AssemblyLevel::ELEMENT); + m.SetAssemblyLevel(AssemblyLevel::ELEMENT); + k.SetAssemblyLevel(AssemblyLevel::ELEMENT); } else if (fa) { - m->SetAssemblyLevel(AssemblyLevel::FULL); - k->SetAssemblyLevel(AssemblyLevel::FULL); + m.SetAssemblyLevel(AssemblyLevel::FULL); + k.SetAssemblyLevel(AssemblyLevel::FULL); } - m->AddDomainIntegrator(new MassIntegrator); + m.AddDomainIntegrator(new MassIntegrator); constexpr double alpha = -1.0; - k->AddDomainIntegrator(new ConvectionIntegrator(velocity, alpha)); - k->AddInteriorFaceIntegrator( + k.AddDomainIntegrator(new ConvectionIntegrator(velocity, alpha)); + k.AddInteriorFaceIntegrator( new NonconservativeDGTraceIntegrator(velocity, alpha)); - k->AddBdrFaceIntegrator( + k.AddBdrFaceIntegrator( new NonconservativeDGTraceIntegrator(velocity, alpha)); - ParLinearForm *b = new ParLinearForm(fes); - b->AddBdrFaceIntegrator( + ParLinearForm b(&fes); + b.AddBdrFaceIntegrator( new BoundaryFlowIntegrator(inflow, velocity, alpha)); int skip_zeros = 0; - m->Assemble(); - k->Assemble(skip_zeros); - b->Assemble(); - m->Finalize(); - k->Finalize(skip_zeros); + m.Assemble(); + k.Assemble(skip_zeros); + b.Assemble(); + m.Finalize(); + k.Finalize(skip_zeros); - HypreParVector *B = b->ParallelAssemble(); + std::unique_ptr B(b.ParallelAssemble()); // 12. Define the initial conditions, save the corresponding grid function to // a file and (optionally) save data in the VisIt format and initialize // GLVis visualization. - ParGridFunction *u_gf = new ParGridFunction(fes); - u_gf->ProjectCoefficient(u0); - HypreParVector *U = u_gf->GetTrueDofs(); - + ParGridFunction u_gf(&fes); + u_gf.ProjectCoefficient(u0); + std::unique_ptr U(u_gf.GetTrueDofs()); if (!online) { @@ -470,10 +469,10 @@ double simulation() 6) << myid; ofstream omesh(mesh_name.str().c_str()); omesh.precision(precision); - pmesh->Print(omesh); + pmesh.Print(omesh); ofstream osol(sol_name.str().c_str()); osol.precision(precision); - u_gf->Save(osol); + u_gf.Save(osol); } // Create data collection for solution output: either VisItDataCollection for @@ -484,19 +483,19 @@ double simulation() if (binary) { #ifdef MFEM_USE_SIDRE - dc = new SidreDataCollection("DG_Advection", pmesh); + dc = new SidreDataCollection("DG_Advection", &pmesh); #else MFEM_ABORT("Must build with MFEM_USE_SIDRE=YES for binary output."); #endif } else { - dc = new VisItDataCollection("DG_Advection", pmesh); + dc = new VisItDataCollection("DG_Advection", &pmesh); dc->SetPrecision(precision); // To save the mesh using MFEM's parallel mesh format: // dc->SetFormat(DataCollection::PARALLEL_FORMAT); } - dc->RegisterField("solution", u_gf); + dc->RegisterField("solution", &u_gf); dc->SetCycle(0); dc->SetTime(0.0); dc->Save(); @@ -505,9 +504,9 @@ double simulation() ParaViewDataCollection *pd = NULL; if (paraview) { - pd = new ParaViewDataCollection("DG_Advection", pmesh); + pd = new ParaViewDataCollection("DG_Advection", &pmesh); pd->SetPrefixPath("ParaView"); - pd->RegisterField("solution", u_gf); + pd->RegisterField("solution", &u_gf); pd->SetLevelsOfDetail(order); pd->SetDataFormat(VTKFormat::BINARY); pd->SetHighOrderOutput(true); @@ -527,11 +526,11 @@ double simulation() postfix += "_o" + std::to_string(order); const std::string collection_name = "dg_advection-p-" + postfix + ".bp"; - adios2_dc = new ADIOS2DataCollection(MPI_COMM_WORLD, collection_name, pmesh); + adios2_dc = new ADIOS2DataCollection(MPI_COMM_WORLD, collection_name, &pmesh); // output data substreams are half the number of mpi processes adios2_dc->SetParameter("SubStreams", std::to_string(num_procs/2) ); // adios2_dc->SetLevelsOfDetail(2); - adios2_dc->RegisterField("solution", u_gf); + adios2_dc->RegisterField("solution", &u_gf); adios2_dc->SetCycle(0); adios2_dc->SetTime(0.0); adios2_dc->Save(); @@ -559,7 +558,7 @@ double simulation() { sout << "parallel " << num_procs << " " << myid << "\n"; sout.precision(precision); - sout << "solution\n" << *pmesh << *u_gf; + sout << "solution\n" << pmesh << u_gf; sout << flush; } } @@ -567,7 +566,7 @@ double simulation() // 13. Define the time-dependent evolution operator describing the ODE // right-hand side, and perform time-integration (looping over the time // iterations, ti, with a time-step dt). - FE_Evolution adv(*m, *k, *B, prec_type); + FE_Evolution adv(m, k, *B, prec_type); StopWatch fom_timer, dmd_training_timer, dmd_prediction_timer; @@ -577,17 +576,17 @@ double simulation() vector ts; adv.SetTime(t); ode_solver->Init(adv); - CAROM::Vector* init = NULL; + std::unique_ptr init; CAROM::CSVDatabase csv_db; fom_timer.Stop(); - CAROM::DMD* dmd_U = NULL; + std::unique_ptr dmd_U; - if(de) + if (de) { - u_gf->SetFromTrueDofs(*U); - init = new CAROM::Vector(U->GetData(), U->Size(), true); + u_gf.SetFromTrueDofs(*U); + init.reset(new CAROM::Vector(U->GetData(), U->Size(), true)); ts.push_back(t); @@ -673,7 +672,7 @@ double simulation() { dmd_training_timer.Start(); - dmd_U = new CAROM::DMD(U->Size(), dt); + dmd_U.reset(new CAROM::DMD(U->Size(), dt)); dmd_U->takeSample(U->GetData(), t); ts.push_back(t); if (myid == 0) @@ -687,8 +686,8 @@ double simulation() // 15. If in online mode, save the initial vector. // 15. If in calc_err_indicator mode, load the current DMD database, // and create a parametric DMD object at the current set of parameters. - u_gf->SetFromTrueDofs(*U); - init = new CAROM::Vector(U->GetData(), U->Size(), true); // potential problem + u_gf.SetFromTrueDofs(*U); + init.reset(new CAROM::Vector(U->GetData(), U->Size(), true)); if (calc_err_indicator) { @@ -718,7 +717,7 @@ double simulation() } else { - dmd_U = new CAROM::DMD(dmd_paths[0]); + dmd_U.reset(new CAROM::DMD(dmd_paths[0])); } dmd_U->projectInitialCondition(*init); @@ -739,7 +738,7 @@ double simulation() (*U)[i] = (*carom_tf_u_minus_some)(i); } - u_gf->SetFromTrueDofs(*U); + u_gf.SetFromTrueDofs(*U); } ts.push_back(t); @@ -761,7 +760,7 @@ double simulation() { dmd_training_timer.Start(); - u_gf->SetFromTrueDofs(*U); + u_gf.SetFromTrueDofs(*U); dmd_U->takeSample(U->GetData(),t); if (myid == 0 && ti % vis_steps == 0) @@ -784,12 +783,12 @@ double simulation() // 11. Extract the parallel grid function corresponding to the finite // element approximation U (the local solution on each processor). - *u_gf = *U; + u_gf = *U; if (visualization) { sout << "parallel " << num_procs << " " << myid << "\n"; - sout << "solution\n" << *pmesh << *u_gf << flush; + sout << "solution\n" << pmesh << u_gf << flush; } if (visit) @@ -942,12 +941,11 @@ double simulation() std::shared_ptr result_U = dmd_U->predict(ts[0]); Vector initial_dmd_solution_U(result_U->getData(), result_U->dim()); - u_gf->SetFromTrueDofs(initial_dmd_solution_U); + u_gf.SetFromTrueDofs(initial_dmd_solution_U); - VisItDataCollection dmd_visit_dc("DMD_DG_Advection_Greedy_" - + - to_string(f_factor), pmesh); - dmd_visit_dc.RegisterField("temperature", u_gf); + VisItDataCollection dmd_visit_dc("DMD_DG_Advection_Greedy_" + + to_string(f_factor), &pmesh); + dmd_visit_dc.RegisterField("temperature", &u_gf); if (visit) { dmd_visit_dc.SetCycle(0); @@ -969,7 +967,7 @@ double simulation() Vector dmd_solution_U(result_U->getData(), result_U->dim()); - u_gf->SetFromTrueDofs(dmd_solution_U); + u_gf.SetFromTrueDofs(dmd_solution_U); dmd_visit_dc.SetCycle(i); dmd_visit_dc.SetTime(ts[i]); @@ -1038,14 +1036,6 @@ double simulation() printf("Elapsed time for solving FOM: %e second\n", fom_timer.RealTime()); } - // 24. Free the used memory. - delete ode_solver; - delete pmesh; - if (dmd_U != NULL) - { - delete dmd_U; - } - return rel_diff; } diff --git a/examples/dmd/de_parametric_heat_conduction_greedy.cpp b/examples/dmd/de_parametric_heat_conduction_greedy.cpp index 962dd391e..b0a3aff09 100644 --- a/examples/dmd/de_parametric_heat_conduction_greedy.cpp +++ b/examples/dmd/de_parametric_heat_conduction_greedy.cpp @@ -378,7 +378,7 @@ double simulation() fom_timer.Stop(); - CAROM::DMD* dmd_u = NULL; + std::unique_ptr dmd_u; // 14. If in offline mode, create DMD object and take initial sample. if (offline) @@ -386,7 +386,7 @@ double simulation() dmd_training_timer.Start(); u_gf.SetFromTrueDofs(u); - dmd_u = new CAROM::DMD(u.Size(), dt); + dmd_u.reset(new CAROM::DMD(u.Size(), dt)); dmd_u->takeSample(u.GetData(), t); if (myid == 0) @@ -453,7 +453,7 @@ double simulation() } else { - dmd_u = new CAROM::DMD(dmd_paths[0]); + dmd_u.reset(new CAROM::DMD(dmd_paths[0])); } dmd_u->projectInitialCondition(*init); @@ -728,8 +728,7 @@ double simulation() Vector initial_dmd_solution_u(result_u->getData(), result_u->dim()); u_gf.SetFromTrueDofs(initial_dmd_solution_u); - VisItDataCollection dmd_visit_dc("DMD_DE_Parametric_Heat_Conduction_Greedy_" - + + VisItDataCollection dmd_visit_dc("DMD_DE_Parametric_Heat_Conduction_Greedy_" + to_string(radius) + "_" + to_string(alpha) + "_" + to_string(cx) + "_" + to_string(cy), pmesh); dmd_visit_dc.RegisterField("temperature", &u_gf); @@ -806,10 +805,6 @@ double simulation() // 21. Free the used memory. delete ode_solver; delete pmesh; - if (dmd_u != NULL) - { - delete dmd_u; - } return rel_diff; } diff --git a/examples/dmd/parametric_dmdc_heat_conduction.cpp b/examples/dmd/parametric_dmdc_heat_conduction.cpp index 459ba61fa..a4cf7f66d 100644 --- a/examples/dmd/parametric_dmdc_heat_conduction.cpp +++ b/examples/dmd/parametric_dmdc_heat_conduction.cpp @@ -129,7 +129,7 @@ class ConductionOperator : public TimeDependentOperator double alpha, kappa; // Nonlinear parameters mutable Vector z; // auxiliary vector - HypreParVector *b; // source vector + std::unique_ptr b; // source vector public: ConductionOperator(ParFiniteElementSpace &f, FunctionCoefficient &s, @@ -150,7 +150,8 @@ class ConductionOperator : public TimeDependentOperator }; const CAROM::Matrix* -createControlMatrix(std::vector snapshots) +createControlMatrix(const std::vector> & + snapshots) { CAROM_VERIFY(snapshots.size() > 0); CAROM_VERIFY(snapshots[0]->dim() > 0); @@ -190,11 +191,11 @@ double dt = 1.0e-2; int main(int argc, char *argv[]) { - // 1. Initialize MPI. - int num_procs, myid; - MPI_Init(&argc, &argv); - MPI_Comm_size(MPI_COMM_WORLD, &num_procs); - MPI_Comm_rank(MPI_COMM_WORLD, &myid); + // 1. Initialize MPI and HYPRE. + Mpi::Init(); + const int num_procs = Mpi::WorldSize(); + const int myid = Mpi::WorldRank(); + Hypre::Init(); // 2. Parse command-line options. const char *mesh_file = ""; @@ -527,27 +528,27 @@ int main(int argc, char *argv[]) vector ts; double f[2]; - CAROM::Vector* init = NULL; + std::unique_ptr init; - CAROM::Database *db = NULL; + std::unique_ptr db; if (csvFormat) - db = new CAROM::CSVDatabase(); + db.reset(new CAROM::CSVDatabase()); else - db = new CAROM::HDFDatabase(); + db.reset(new CAROM::HDFDatabase()); vector snap_list; fom_timer.Stop(); - - CAROM::DMDc* dmd_u = NULL; + std::unique_ptr dmd_u; f[0] = Amplitude(t, 0); f[1] = Amplitude(t, 1); int dim_c = 2; // control dim - std::vector d_controls; // vector to store controls - CAROM::Vector* control = new CAROM::Vector(f, dim_c, false); - d_controls.push_back(control); + std::vector> + d_controls; // vector to store controls + d_controls.push_back(std::unique_ptr(new CAROM::Vector(f, dim_c, + false))); if (offline) { @@ -560,7 +561,7 @@ int main(int argc, char *argv[]) std::cout << "t = " << t << std::endl; - dmd_u = new CAROM::DMDc(u.Size(), 2, dt); + dmd_u.reset(new CAROM::DMDc(u.Size(), 2, dt)); dmd_u->takeSample(u.GetData(), t, f, false); dmd_training_timer.Stop(); @@ -569,7 +570,7 @@ int main(int argc, char *argv[]) if (online) { u_gf.SetFromTrueDofs(u); - init = new CAROM::Vector(u.GetData(), u.Size(), true); + init.reset(new CAROM::Vector(u.GetData(), u.Size(), true)); } if (save_dofs && myid == 0) @@ -647,8 +648,8 @@ int main(int argc, char *argv[]) snap_list.push_back(ti); if (!last_step) { - CAROM::Vector* control = new CAROM::Vector(f, dim_c, false); - d_controls.push_back(control); + d_controls.push_back(std::unique_ptr(new CAROM::Vector(f, dim_c, + false))); } if (last_step || (ti % vis_steps) == 0) @@ -757,6 +758,7 @@ int main(int argc, char *argv[]) kappa) + "_" + to_string( amp_in) + "_" + to_string(amp_out) + "_control"; control_mat->write(full_file_name); + delete control_mat; } @@ -896,7 +898,6 @@ int main(int argc, char *argv[]) // 16. Free the used memory. delete ode_solver; delete pmesh; - delete dmd_u; MPI_Finalize(); @@ -976,7 +977,7 @@ void ConductionOperator::SetSourceTime(double t) { src_func.SetTime(t); B->Assemble(); - b = B->ParallelAssemble(); + b.reset(B->ParallelAssemble()); } void ConductionOperator::SetParameters(const Vector &u) diff --git a/examples/dmd/parametric_dw_csv.cpp b/examples/dmd/parametric_dw_csv.cpp index 73d3171eb..db0b3458e 100644 --- a/examples/dmd/parametric_dw_csv.cpp +++ b/examples/dmd/parametric_dw_csv.cpp @@ -355,8 +355,7 @@ int main(int argc, char *argv[]) } StopWatch dmd_training_timer, dmd_preprocess_timer, dmd_prediction_timer; - vector> dmd; - vector dmd_curr_par; + vector>> dmd(npar); double* sample = new double[dim]; if (offline) @@ -371,25 +370,23 @@ int main(int argc, char *argv[]) cout << "Loading samples for " << par_dir << " to train DMD." << endl; } - dmd_curr_par.assign(numWindows, nullptr); + dmd[idx_dataset].resize(numWindows); for (int window = 0; window < numWindows; ++window) { if (ddt > 0.0) { - dmd_curr_par[window] = new CAROM::AdaptiveDMD(dim, ddt, string(rbf), - string(interp_method), admd_closest_rbf_val); + dmd[idx_dataset][window].reset(new CAROM::AdaptiveDMD(dim, ddt, string(rbf), + string(interp_method), admd_closest_rbf_val)); } else if (dtc > 0.0) { - dmd_curr_par[window] = new CAROM::DMD(dim, dtc); + dmd[idx_dataset][window].reset(new CAROM::DMD(dim, dtc)); } else { - dmd_curr_par[window] = new CAROM::NonuniformDMD(dim); + dmd[idx_dataset][window].reset(new CAROM::NonuniformDMD(dim)); } } - dmd.push_back(dmd_curr_par); - dmd_curr_par.clear(); vector snap_list; csv_db.getStringVector(string(list_dir) + "/" + par_dir + ".csv", snap_list, @@ -600,9 +597,6 @@ int main(int argc, char *argv[]) cout << "Loading " << npar << " testing datasets." << endl; } - dmd_curr_par.assign(numWindows, nullptr); - dmd.assign(numWindows, dmd_curr_par); - vector prediction_time, prediction_error; for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) @@ -891,13 +885,6 @@ int main(int argc, char *argv[]) } delete[] sample; - for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) - { - for (int window = 0; window < numWindows; ++window) - { - delete dmd[idx_dataset][window]; - } - } return 0; } diff --git a/examples/dmd/parametric_heat_conduction.cpp b/examples/dmd/parametric_heat_conduction.cpp index 7424afe2f..6b7cae550 100644 --- a/examples/dmd/parametric_heat_conduction.cpp +++ b/examples/dmd/parametric_heat_conduction.cpp @@ -516,7 +516,7 @@ int main(int argc, char *argv[]) ode_solver->Init(oper); double t = 0.0; vector ts; - CAROM::Vector* init = NULL; + std::unique_ptr init; CAROM::Database *db = NULL; if (csvFormat) @@ -528,7 +528,7 @@ int main(int argc, char *argv[]) fom_timer.Stop(); - CAROM::DMD* dmd_u = NULL; + std::unique_ptr dmd_u; if (offline) { @@ -536,7 +536,7 @@ int main(int argc, char *argv[]) // 11. Create DMD object and take initial sample. u_gf.SetFromTrueDofs(u); - dmd_u = new CAROM::DMD(u.Size(), dt); + dmd_u.reset(new CAROM::DMD(u.Size(), dt)); dmd_u->takeSample(u.GetData(), t); if (myid == 0) @@ -549,7 +549,7 @@ int main(int argc, char *argv[]) if (online) { u_gf.SetFromTrueDofs(u); - init = new CAROM::Vector(u.GetData(), u.Size(), true); + init.reset(new CAROM::Vector(u.GetData(), u.Size(), true)); } if (save_dofs && myid == 0) @@ -870,10 +870,6 @@ int main(int argc, char *argv[]) // 16. Free the used memory. delete ode_solver; delete pmesh; - if (offline) - { - delete dmd_u; - } #ifdef MFEM_USE_GSLIB delete pws; diff --git a/examples/dmd/parametric_tw_csv.cpp b/examples/dmd/parametric_tw_csv.cpp index 80f724da5..aaa716b61 100644 --- a/examples/dmd/parametric_tw_csv.cpp +++ b/examples/dmd/parametric_tw_csv.cpp @@ -588,8 +588,7 @@ int main(int argc, char *argv[]) } StopWatch dmd_training_timer, dmd_preprocess_timer, dmd_prediction_timer; - vector> dmd; - vector dmd_curr_par; + vector>> dmd(npar); double* sample = new double[dim]; if (offline) @@ -609,25 +608,23 @@ int main(int argc, char *argv[]) cout << "Loading samples for " << par_dir << " to train DMD." << endl; } - dmd_curr_par.assign(numWindows, nullptr); + dmd[idx_dataset].resize(numWindows); for (int window = 0; window < numWindows; ++window) { if (ddt > 0.0) { - dmd_curr_par[window] = new CAROM::AdaptiveDMD(dim, ddt, string(rbf), - string(interp_method), admd_closest_rbf_val); + dmd[idx_dataset][window].reset(new CAROM::AdaptiveDMD(dim, ddt, string(rbf), + string(interp_method), admd_closest_rbf_val)); } else if (dtc > 0.0) { - dmd_curr_par[window] = new CAROM::DMD(dim, dtc); + dmd[idx_dataset][window].reset(new CAROM::DMD(dim, dtc)); } else { - dmd_curr_par[window] = new CAROM::NonuniformDMD(dim); + dmd[idx_dataset][window].reset(new CAROM::NonuniformDMD(dim)); } } - dmd.push_back(dmd_curr_par); - dmd_curr_par.clear(); int num_snap_orig = 0; if (csvFormat) @@ -823,8 +820,7 @@ int main(int argc, char *argv[]) { for (int window = 0; window < numWindows; ++window) { - delete dmd[idx_dataset][window]; - dmd[idx_dataset][window] = nullptr; + dmd[idx_dataset][window].reset(nullptr); } } } // escape for-loop over idx_dataset @@ -856,14 +852,13 @@ int main(int argc, char *argv[]) cout << "Loading " << npar << " testing datasets." << endl; } - dmd_curr_par.assign(numWindows, nullptr); - dmd.assign(npar, dmd_curr_par); - int num_tests = 0; vector prediction_time, prediction_error; for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) { + dmd[idx_dataset].resize(numWindows); + stringstream par_ss(testing_par_list[idx_dataset]); // testing DATASET vector par_info; string par_entry; @@ -990,7 +985,7 @@ int main(int argc, char *argv[]) { cout << "Loading local DMD model #" << window << endl; } - dmd[idx_dataset][window] = new CAROM::DMD(dmd_paths[0]); + dmd[idx_dataset][window].reset(new CAROM::DMD(dmd_paths[0])); } if (myid == 0) @@ -1032,8 +1027,7 @@ int main(int argc, char *argv[]) << window - 1 << endl; } - delete dmd[idx_dataset][window-1]; - dmd[idx_dataset][window-1] = nullptr; + dmd[idx_dataset][window-1].reset(nullptr); } } // escape for-loop over window @@ -1284,13 +1278,6 @@ int main(int argc, char *argv[]) } delete[] sample; - for (int idx_dataset = 0; idx_dataset < npar; ++idx_dataset) - { - for (int window = 0; window < numWindows; ++window) - { - delete dmd[idx_dataset][window]; - } - } return 0; } diff --git a/lib/algo/DMD.cpp b/lib/algo/DMD.cpp index 568567190..6de8a0074 100644 --- a/lib/algo/DMD.cpp +++ b/lib/algo/DMD.cpp @@ -501,6 +501,12 @@ DMD::constructDMD(const Matrix & f_snapshots, delete eigenpair.ev_real; delete eigenpair.ev_imaginary; + free_matrix_data(d_factorizer->U); + free_matrix_data(d_factorizer->V); + free(d_factorizer->U); + free(d_factorizer->V); + free(d_factorizer->S); + release_context(&svd_input); } diff --git a/lib/algo/DMD.h b/lib/algo/DMD.h index e164a0f0d..b25fe6c87 100644 --- a/lib/algo/DMD.h +++ b/lib/algo/DMD.h @@ -236,7 +236,7 @@ class DMD * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ - friend void getParametricDMD(DMD*& parametric_dmd, + friend void getParametricDMD(std::unique_ptr& parametric_dmd, const std::vector& parameter_points, std::vector& dmds, const Vector & desired_point, diff --git a/lib/algo/DMDc.cpp b/lib/algo/DMDc.cpp index eeff369e1..fcfdffa33 100644 --- a/lib/algo/DMDc.cpp +++ b/lib/algo/DMDc.cpp @@ -140,6 +140,11 @@ DMDc::~DMDc() { delete snapshot; } + + for (auto control : d_controls) + { + delete control; + } } void DMDc::setOffset(std::shared_ptr & offset_vector) @@ -362,8 +367,8 @@ DMDc::constructDMDc(const Matrix & f_snapshots, d_num_singular_vectors << " for input." << std::endl; // Allocate the appropriate matrices and gather their elements. - Matrix* d_basis_in = new Matrix(f_snapshots_in->numRows(), d_k_in, - f_snapshots_in->distributed()); + std::unique_ptr d_basis_in(new Matrix(f_snapshots_in->numRows(), d_k_in, + f_snapshots_in->distributed())); Matrix* d_S_inv = new Matrix(d_k_in, d_k_in, false); Matrix* d_basis_right = new Matrix(f_snapshots_in->numColumns(), d_k_in, false); @@ -477,10 +482,18 @@ DMDc::constructDMDc(const Matrix & f_snapshots, row_offset[static_cast(d_rank)], d_rank); } + + free_matrix_data(d_factorizer_out->U); + free_matrix_data(d_factorizer_out->V); + free(d_factorizer_out->U); + free(d_factorizer_out->V); + free(d_factorizer_out->S); + + release_context(&svd_output); } else { - d_basis.reset(d_basis_in); + d_basis.reset(d_basis_in.release()); d_k = d_k_in; } @@ -551,6 +564,12 @@ DMDc::constructDMDc(const Matrix & f_snapshots, delete eigenpair.ev_real; delete eigenpair.ev_imaginary; + free_matrix_data(d_factorizer_in->U); + free_matrix_data(d_factorizer_in->V); + free(d_factorizer_in->U); + free(d_factorizer_in->V); + free(d_factorizer_in->S); + release_context(&svd_input); } diff --git a/lib/algo/DMDc.h b/lib/algo/DMDc.h index 7be2bf8f5..738a51aa8 100644 --- a/lib/algo/DMDc.h +++ b/lib/algo/DMDc.h @@ -210,7 +210,7 @@ class DMDc * to a value between 0.0 to 1.0 * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ - friend void getParametricDMDc(DMDc*& parametric_dmdc, + friend void getParametricDMDc(std::unique_ptr& parametric_dmdc, const std::vector& parameter_points, std::vector& dmdcs, std::vector> controls, diff --git a/lib/algo/NonuniformDMD.h b/lib/algo/NonuniformDMD.h index 096064cbc..2631a9b75 100644 --- a/lib/algo/NonuniformDMD.h +++ b/lib/algo/NonuniformDMD.h @@ -97,10 +97,12 @@ class NonuniformDMD : public DMD * "IDW" == inverse distance weighting, * "LP" == lagrangian polynomials) * @param[in] closest_rbf_val The RBF parameter determines the width of influence. - * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 + * Set the RBF value of the nearest two parameter points to a value + * between 0.0 to 1.0. * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ - friend void getParametricDMD(NonuniformDMD*& parametric_dmd, + friend void getParametricDMD(std::unique_ptr& + parametric_dmd, const std::vector& parameter_points, std::vector& dmds, const Vector & desired_point, diff --git a/lib/algo/ParametricDMD.h b/lib/algo/ParametricDMD.h index 19095b46b..b38d586d0 100644 --- a/lib/algo/ParametricDMD.h +++ b/lib/algo/ParametricDMD.h @@ -49,7 +49,7 @@ namespace CAROM { * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ template -void getParametricDMD(T*& parametric_dmd, +void getParametricDMD(std::unique_ptr& parametric_dmd, const std::vector& parameter_points, std::vector& dmds, const Vector & desired_point, @@ -106,9 +106,9 @@ void getParametricDMD(T*& parametric_dmd, std::shared_ptr phi_real = W->mult(*eigenpair.ev_real); std::shared_ptr phi_imaginary = W->mult(*eigenpair.ev_imaginary); - parametric_dmd = new T(eigs, phi_real, phi_imaginary, dmds[0]->d_k, - dmds[0]->d_dt, dmds[0]->d_t_offset, - dmds[0]->d_state_offset); + parametric_dmd.reset(new T(eigs, phi_real, phi_imaginary, dmds[0]->d_k, + dmds[0]->d_dt, dmds[0]->d_t_offset, + dmds[0]->d_state_offset)); delete eigenpair.ev_real; delete eigenpair.ev_imaginary; @@ -133,7 +133,7 @@ void getParametricDMD(T*& parametric_dmd, * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ template -void getParametricDMD(T*& parametric_dmd, +void getParametricDMD(std::unique_ptr& parametric_dmd, const std::vector& parameter_points, std::vector& dmd_paths, const Vector & desired_point, diff --git a/lib/algo/ParametricDMDc.h b/lib/algo/ParametricDMDc.h index 3ff2be25b..f8c7d2704 100644 --- a/lib/algo/ParametricDMDc.h +++ b/lib/algo/ParametricDMDc.h @@ -53,7 +53,7 @@ namespace CAROM { * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ template -void getParametricDMDc(T*& parametric_dmdc, +void getParametricDMDc(std::unique_ptr& parametric_dmdc, const std::vector& parameter_points, std::vector& dmdcs, std::vector> controls, @@ -127,9 +127,9 @@ void getParametricDMDc(T*& parametric_dmdc, std::shared_ptr phi_real = W->mult(*eigenpair.ev_real); std::shared_ptr phi_imaginary = W->mult(*eigenpair.ev_imaginary); - parametric_dmdc = new T(eigs, phi_real, phi_imaginary, B_tilde, - dmdcs[0]->d_k,dmdcs[0]->d_dt, - dmdcs[0]->d_t_offset, dmdcs[0]->d_state_offset, W); + parametric_dmdc.reset(new T(eigs, phi_real, phi_imaginary, B_tilde, + dmdcs[0]->d_k,dmdcs[0]->d_dt, + dmdcs[0]->d_t_offset, dmdcs[0]->d_state_offset, W)); delete eigenpair.ev_real; delete eigenpair.ev_imaginary; @@ -158,7 +158,7 @@ void getParametricDMDc(T*& parametric_dmdc, * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ template -void getParametricDMDc(T*& parametric_dmdc, +void getParametricDMDc(std::unique_ptr& parametric_dmdc, const std::vector& parameter_points, std::vector& dmdc_paths, std::vector> controls, From 0bc402d7478fc92ff6fbec0b470cdd18c9e6ed85 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Thu, 7 Nov 2024 13:20:53 -0800 Subject: [PATCH 17/19] Minor fix. --- lib/algo/SnapshotDMD.h | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index 0c2c82aa0..8802f0e91 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -98,7 +98,8 @@ class SnapshotDMD : public DMD * Set the RBF value of the nearest two parameter points to a value between 0.0 to 1.0 * @param[in] reorthogonalize_W Whether to reorthogonalize the interpolated W (basis) matrix. */ - friend void getParametricDMD(SnapshotDMD*& parametric_dmd, + friend void getParametricDMD(std::unique_ptr& + parametric_dmd, const std::vector& parameter_points, std::vector& dmds, const Vector & desired_point, From 3ac1579ce8d3b4d059fe3752d809e1000995d07c Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 20 Nov 2024 10:17:23 -0800 Subject: [PATCH 18/19] Various small fixes. --- .../dmd/parametric_dmdc_heat_conduction.cpp | 6 ++-- examples/prom/mixed_nonlinear_diffusion.cpp | 1 - examples/prom/poisson_local_rom_greedy.cpp | 32 +++++++++---------- lib/algo/SnapshotDMD.h | 6 ++-- lib/algo/greedy/GreedySampler.cpp | 24 +++++++------- lib/algo/greedy/GreedySampler.h | 29 +++++++++-------- lib/hyperreduction/Hyperreduction.cpp | 2 +- lib/hyperreduction/Hyperreduction.h | 2 +- lib/linalg/svd/IncrementalSVD.cpp | 2 +- lib/linalg/svd/IncrementalSVDBrand.cpp | 14 +++----- lib/linalg/svd/IncrementalSVDFastUpdate.cpp | 14 +++----- lib/linalg/svd/IncrementalSVDStandard.cpp | 14 +++----- lib/linalg/svd/SVD.cpp | 5 --- lib/linalg/svd/SVD.h | 7 +--- lib/linalg/svd/StaticSVD.cpp | 5 ++- 15 files changed, 69 insertions(+), 94 deletions(-) diff --git a/examples/dmd/parametric_dmdc_heat_conduction.cpp b/examples/dmd/parametric_dmdc_heat_conduction.cpp index a4cf7f66d..b1692deb7 100644 --- a/examples/dmd/parametric_dmdc_heat_conduction.cpp +++ b/examples/dmd/parametric_dmdc_heat_conduction.cpp @@ -547,8 +547,7 @@ int main(int argc, char *argv[]) int dim_c = 2; // control dim std::vector> d_controls; // vector to store controls - d_controls.push_back(std::unique_ptr(new CAROM::Vector(f, dim_c, - false))); + d_controls.emplace_back(new CAROM::Vector(f, dim_c, false)); if (offline) { @@ -648,8 +647,7 @@ int main(int argc, char *argv[]) snap_list.push_back(ti); if (!last_step) { - d_controls.push_back(std::unique_ptr(new CAROM::Vector(f, dim_c, - false))); + d_controls.emplace_back(new CAROM::Vector(f, dim_c, false)); } if (last_step || (ti % vis_steps) == 0) diff --git a/examples/prom/mixed_nonlinear_diffusion.cpp b/examples/prom/mixed_nonlinear_diffusion.cpp index 824e5b327..6c324972e 100644 --- a/examples/prom/mixed_nonlinear_diffusion.cpp +++ b/examples/prom/mixed_nonlinear_diffusion.cpp @@ -1671,7 +1671,6 @@ RomOperator::RomOperator(NonlinearDiffusionOperator *fom_, aprime_coeff(&p_coeff, NonlinearCoefficientDerivative), a_plus_aprime_coeff(a_coeff, aprime_coeff), rank(myid) { - ; dydt_prev = 0.0; if (myid == 0 && !eqp) diff --git a/examples/prom/poisson_local_rom_greedy.cpp b/examples/prom/poisson_local_rom_greedy.cpp index 110deac71..a64c8b73a 100644 --- a/examples/prom/poisson_local_rom_greedy.cpp +++ b/examples/prom/poisson_local_rom_greedy.cpp @@ -368,18 +368,19 @@ int main(int argc, char *argv[]) } std::unique_ptr spatialbasis; - CAROM::Options* options; - CAROM::BasisGenerator *generator; + std::unique_ptr options; + std::unique_ptr generator; int numRowRB, numColumnRB; StopWatch solveTimer, assembleTimer, mergeTimer; // 12. Set BasisGenerator if offline if (offline) { - options = new CAROM::Options(fespace.GetTrueVSize(), max_num_snapshots, - update_right_SV); + options.reset(new CAROM::Options(fespace.GetTrueVSize(), max_num_snapshots, + update_right_SV)); if (myid == 0) cout << "Saving basis to: " << saveBasisName << endl; - generator = new CAROM::BasisGenerator(*options, isIncremental, saveBasisName); + generator.reset(new CAROM::BasisGenerator(*options, isIncremental, + saveBasisName)); } // 13. Set up the parallel linear form b(.) which corresponds to the @@ -387,10 +388,10 @@ int main(int argc, char *argv[]) // (f,phi_i) where f is given by the function f_exact and phi_i are the // basis functions in the finite element fespace. assembleTimer.Start(); - ParLinearForm *b = new ParLinearForm(&fespace); + ParLinearForm b(&fespace); FunctionCoefficient f(rhs); - b->AddDomainIntegrator(new DomainLFIntegrator(f)); - b->Assemble(); + b.AddDomainIntegrator(new DomainLFIntegrator(f)); + b.Assemble(); // 14. Define the solution vector x as a parallel finite element grid function // corresponding to fespace. Initialize x with initial guess of zero, @@ -419,7 +420,7 @@ int main(int argc, char *argv[]) HypreParMatrix A; Vector B, X; - a.FormLinearSystem(ess_tdof_list, x, *b, A, X, B); + a.FormLinearSystem(ess_tdof_list, x, b, A, X, B); assembleTimer.Stop(); // 17. The offline phase @@ -457,8 +458,6 @@ int main(int argc, char *argv[]) bool addSample = generator->takeSample(X.GetData()); generator->writeSnapshot(); basisIdentifiers.push_back(saveBasisName); - delete generator; - delete options; } } @@ -496,7 +495,7 @@ int main(int argc, char *argv[]) // 25. Recover the parallel grid function corresponding to X. This is the // local finite element solution on each processor. - a.RecoverFEMSolution(X, *b, x); + a.RecoverFEMSolution(X, b, x); // 26. Save the refined mesh and the solution in parallel. This output can // be viewed later using GLVis: "glvis -np -m mesh -g sol". @@ -616,9 +615,10 @@ int main(int argc, char *argv[]) if (calc_rel_error || (offline && basisIdentifiers.size() == 1)) { mergeTimer.Start(); - options = new CAROM::Options(fespace.GetTrueVSize(), max_num_snapshots, - update_right_SV); - generator = new CAROM::BasisGenerator(*options, isIncremental, loadBasisName); + options.reset(new CAROM::Options(fespace.GetTrueVSize(), max_num_snapshots, + update_right_SV)); + generator.reset(new CAROM::BasisGenerator(*options, isIncremental, + loadBasisName)); for (int i = 0; i < basisIdentifiers.size(); ++i) { std::string snapshot_filename = basisIdentifiers[i] + "_snapshot"; @@ -631,8 +631,6 @@ int main(int argc, char *argv[]) printf("Elapsed time for merging and building ROM basis: %e second\n", mergeTimer.RealTime()); } - delete generator; - delete options; } // 31. print timing info diff --git a/lib/algo/SnapshotDMD.h b/lib/algo/SnapshotDMD.h index 8802f0e91..bea1672f7 100644 --- a/lib/algo/SnapshotDMD.h +++ b/lib/algo/SnapshotDMD.h @@ -120,9 +120,9 @@ class SnapshotDMD : public DMD * @param[in] state_offset d_state_offset * @param[in] derivative_offset d_derivative_offset */ - SnapshotDMD(std::vector> eigs, - std::shared_ptr phi_real, - std::shared_ptr phi_imaginary, int k, double dt, + SnapshotDMD(std::vector> & eigs, + std::shared_ptr & phi_real, + std::shared_ptr & phi_imaginary, int k, double dt, double t_offset, std::shared_ptr & state_offset) : DMD(eigs, phi_real, phi_imaginary, k, dt, t_offset, state_offset) {} diff --git a/lib/algo/greedy/GreedySampler.cpp b/lib/algo/greedy/GreedySampler.cpp index 18c43a080..be9579a8e 100644 --- a/lib/algo/greedy/GreedySampler.cpp +++ b/lib/algo/greedy/GreedySampler.cpp @@ -22,15 +22,15 @@ namespace CAROM { GreedyErrorIndicatorPoint -createGreedyErrorIndicatorPoint(std::shared_ptr point, - std::shared_ptr localROM) +createGreedyErrorIndicatorPoint(const std::shared_ptr & point, + const std::shared_ptr & localROM) { GreedyErrorIndicatorPoint result{point, localROM}; return result; } Vector -getNearestPoint(std::vector & param_points, Vector & point) +getNearestPoint(const std::vector & param_points, Vector & point) { int closest_point_index = getNearestPointIndex(param_points, point); @@ -38,7 +38,7 @@ getNearestPoint(std::vector & param_points, Vector & point) } int -getNearestPointIndex(std::vector & param_points, Vector & point) +getNearestPointIndex(const std::vector & param_points, Vector & point) { double closest_dist_to_points = INT_MAX; @@ -68,7 +68,7 @@ getNearestPoint(std::vector & param_points, double point) } int -getNearestPointIndex(std::vector & param_points, double point) +getNearestPointIndex(const std::vector & param_points, double point) { double closest_dist_to_points = INT_MAX; @@ -88,7 +88,7 @@ getNearestPointIndex(std::vector & param_points, double point) } GreedySampler::GreedySampler( - std::vector & parameter_points, + const std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -112,7 +112,7 @@ GreedySampler::GreedySampler( } GreedySampler::GreedySampler( - std::vector & parameter_points, + const std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -144,8 +144,8 @@ GreedySampler::GreedySampler( } GreedySampler::GreedySampler( - Vector & param_space_min, - Vector & param_space_max, + const Vector & param_space_min, + const Vector & param_space_max, int num_parameter_points, bool check_local_rom, double relative_error_tolerance, @@ -1000,7 +1000,7 @@ GreedySampler::setPointErrorIndicator(double error, int vec_size) } void -GreedySampler::printErrorIndicator(Vector errorIndicatorPoint, +GreedySampler::printErrorIndicator(const Vector & errorIndicatorPoint, double proc_errors) { if (d_rank == 0) @@ -1231,7 +1231,7 @@ GreedySampler::generateRandomPoints(int num_points) } std::shared_ptr -GreedySampler::getNearestROM(Vector & point) +GreedySampler::getNearestROM(const Vector & point) { CAROM_VERIFY(point.dim() == d_parameter_points[0].dim()); @@ -1260,7 +1260,7 @@ GreedySampler::getNearestROM(Vector & point) } int -GreedySampler::getNearestNonSampledPoint(Vector & point) +GreedySampler::getNearestNonSampledPoint(const Vector & point) { double closest_dist_to_points = INT_MAX; int closest_point_index = -1; diff --git a/lib/algo/greedy/GreedySampler.h b/lib/algo/greedy/GreedySampler.h index 9452877a2..4e1c7fceb 100644 --- a/lib/algo/greedy/GreedySampler.h +++ b/lib/algo/greedy/GreedySampler.h @@ -100,7 +100,7 @@ class GreedySampler * debugging purposes. */ GreedySampler( - std::vector & parameter_points, + const std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -138,7 +138,7 @@ class GreedySampler * debugging purposes. */ GreedySampler( - std::vector & parameter_points, + const std::vector & parameter_points, bool check_local_rom, double relative_error_tolerance, double alpha, @@ -180,8 +180,8 @@ class GreedySampler * debugging purposes. */ GreedySampler( - Vector & param_space_min, - Vector & param_space_max, + const Vector & param_space_min, + const Vector & param_space_max, int num_parameter_points, bool check_local_rom, double relative_error_tolerance, @@ -313,7 +313,7 @@ class GreedySampler * the given point or -1 if none exist. */ int - getNearestNonSampledPoint(Vector & point); + getNearestNonSampledPoint(const Vector & point); /** * @brief Returns the nearest local ROM to the specified parameter point. @@ -323,7 +323,7 @@ class GreedySampler * @return A shared pointer holding the point or NULL if no local ROM exists. */ std::shared_ptr - getNearestROM(Vector & point); + getNearestROM(const Vector & point); /** * @brief Get the domain of the parameter points. @@ -449,7 +449,8 @@ class GreedySampler * @param[in] proc_errors The error indicator value. * */ - void printErrorIndicator(Vector errorIndicatorPoint, double proc_errors); + void printErrorIndicator(const Vector & errorIndicatorPoint, + double proc_errors); /** * @brief Print that the error indicator was not met. @@ -702,8 +703,8 @@ class GreedySampler * @return A struct holding @a point and @a localROM. */ GreedyErrorIndicatorPoint createGreedyErrorIndicatorPoint( - std::shared_ptr point, - std::shared_ptr localROM); + const std::shared_ptr & point, + const std::shared_ptr & localROM); /** * @brief Given a vector, find the nearest point in a domain. @@ -713,7 +714,8 @@ GreedyErrorIndicatorPoint createGreedyErrorIndicatorPoint( * * @return A vector representing the nearest point in a domain. */ -Vector getNearestPoint(std::vector & paramPoints, Vector & point); +Vector getNearestPoint(const std::vector & paramPoints, + const Vector & point); /** * @brief Given a double, find the nearest point in a domain. @@ -723,7 +725,7 @@ Vector getNearestPoint(std::vector & paramPoints, Vector & point); * * @return A double representing the nearest point in a domain. */ -double getNearestPoint(std::vector & paramPoints, double point); +double getNearestPoint(const std::vector & paramPoints, double point); /** * @brief Given a vector, find the nearest point in a domain. @@ -733,7 +735,8 @@ double getNearestPoint(std::vector & paramPoints, double point); * * @return The index of the nearest point in a domain. */ -int getNearestPointIndex(std::vector & paramPoints, Vector & point); +int getNearestPointIndex(const std::vector & paramPoints, + Vector & point); /** * @brief Given a double, find the nearest point in a domain. @@ -743,7 +746,7 @@ int getNearestPointIndex(std::vector & paramPoints, Vector & point); * * @return The index of the nearest point in a domain. */ -int getNearestPointIndex(std::vector & paramPoints, double point); +int getNearestPointIndex(const std::vector & paramPoints, double point); } #endif diff --git a/lib/hyperreduction/Hyperreduction.cpp b/lib/hyperreduction/Hyperreduction.cpp index 55b4c0e16..cc42a75da 100644 --- a/lib/hyperreduction/Hyperreduction.cpp +++ b/lib/hyperreduction/Hyperreduction.cpp @@ -27,7 +27,7 @@ Hyperreduction::Hyperreduction(const char* sampling_type) samplingType = iter->second; } -void Hyperreduction::ComputeSamples(const std::shared_ptr f_basis, +void Hyperreduction::ComputeSamples(const std::shared_ptr & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/hyperreduction/Hyperreduction.h b/lib/hyperreduction/Hyperreduction.h index 315e59a5f..fefc44ba5 100644 --- a/lib/hyperreduction/Hyperreduction.h +++ b/lib/hyperreduction/Hyperreduction.h @@ -55,7 +55,7 @@ class Hyperreduction samplingType = stype; } - void ComputeSamples(const std::shared_ptr f_basis, + void ComputeSamples(const std::shared_ptr & f_basis, int num_f_basis_vectors_used, std::vector& f_sampled_row, std::vector& f_sampled_rows_per_proc, diff --git a/lib/linalg/svd/IncrementalSVD.cpp b/lib/linalg/svd/IncrementalSVD.cpp index 365dc28df..3b3fd3b1c 100644 --- a/lib/linalg/svd/IncrementalSVD.cpp +++ b/lib/linalg/svd/IncrementalSVD.cpp @@ -107,7 +107,7 @@ IncrementalSVD::IncrementalSVD( // Read d_W. d_state_database->getInteger("W_num_rows", num_rows); d_state_database->getInteger("W_num_cols", num_cols); - d_W = new Matrix(num_rows, num_cols, true); + d_W.reset(new Matrix(num_rows, num_cols, true)); d_state_database->getDoubleArray("W", &d_W->item(0, 0), num_rows*num_cols); diff --git a/lib/linalg/svd/IncrementalSVDBrand.cpp b/lib/linalg/svd/IncrementalSVDBrand.cpp index 722df4568..d64897495 100644 --- a/lib/linalg/svd/IncrementalSVDBrand.cpp +++ b/lib/linalg/svd/IncrementalSVDBrand.cpp @@ -122,7 +122,7 @@ IncrementalSVDBrand::buildInitialSVD( // Build d_W for this new time interval. if (d_update_right_SV) { - d_W = new Matrix(1, 1, false); + d_W.reset(new Matrix(1, 1, false)); d_W->item(0, 0) = 1.0; } @@ -360,14 +360,13 @@ IncrementalSVDBrand::addLinearlyDependentSample( d_Up->mult(Amod, *Up_times_Amod); d_Up.reset(Up_times_Amod); - Matrix* new_d_W; if (d_update_right_SV) { // The new d_W is the product of the current d_W extended by another row // and column and W. The only new value in the extended version of d_W // that is non-zero is the new lower right value and it is 1. We will // construct this product without explicitly forming the extended version of // d_W. - new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples, false); + Matrix *new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples, false); for (int row = 0; row < d_num_rows_of_W; ++row) { for (int col = 0; col < d_num_samples; ++col) { double new_d_W_entry = 0.0; @@ -380,8 +379,7 @@ IncrementalSVDBrand::addLinearlyDependentSample( for (int col = 0; col < d_num_samples; ++col) { new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } - delete d_W; - d_W = new_d_W; + d_W.reset(new_d_W); ++d_num_rows_of_W; } @@ -404,14 +402,13 @@ IncrementalSVDBrand::addNewSample( } d_U.reset(newU); - Matrix* new_d_W; if (d_update_right_SV) { // The new d_W is the product of the current d_W extended by another row // and column and W. The only new value in the extended version of d_W // that is non-zero is the new lower right value and it is 1. We will // construct this product without explicitly forming the extended version of // d_W. - new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples+1, false); + Matrix *new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples+1, false); for (int row = 0; row < d_num_rows_of_W; ++row) { for (int col = 0; col < d_num_samples+1; ++col) { double new_d_W_entry = 0.0; @@ -424,8 +421,7 @@ IncrementalSVDBrand::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } - delete d_W; - d_W = new_d_W; + d_W.reset(new_d_W); } // The new d_Up is the product of the current d_Up extended by another row diff --git a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp index c2a663504..82655586b 100644 --- a/lib/linalg/svd/IncrementalSVDFastUpdate.cpp +++ b/lib/linalg/svd/IncrementalSVDFastUpdate.cpp @@ -104,7 +104,7 @@ IncrementalSVDFastUpdate::buildInitialSVD( // Build d_W for this new time interval. if (d_update_right_SV) { - d_W = new Matrix(1, 1, false); + d_W.reset(new Matrix(1, 1, false)); d_W->item(0, 0) = 1.0; } @@ -204,14 +204,13 @@ IncrementalSVDFastUpdate::addLinearlyDependentSample( d_Up->mult(Amod, *Up_times_Amod); d_Up.reset(Up_times_Amod); - Matrix* new_d_W; if (d_update_right_SV) { // The new d_W is the product of the current d_W extended by another row // and column and W. The only new value in the extended version of d_W // that is non-zero is the new lower right value and it is 1. We will // construct this product without explicitly forming the extended version of // d_W. - new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples, false); + Matrix *new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples, false); for (int row = 0; row < d_num_rows_of_W; ++row) { for (int col = 0; col < d_num_samples; ++col) { double new_d_W_entry = 0.0; @@ -224,8 +223,7 @@ IncrementalSVDFastUpdate::addLinearlyDependentSample( for (int col = 0; col < d_num_samples; ++col) { new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } - delete d_W; - d_W = new_d_W; + d_W.reset(new_d_W); ++d_num_rows_of_W; } @@ -248,14 +246,13 @@ IncrementalSVDFastUpdate::addNewSample( } d_U.reset(newU); - Matrix* new_d_W; if (d_update_right_SV) { // The new d_W is the product of the current d_W extended by another row // and column and W. The only new value in the extended version of d_W // that is non-zero is the new lower right value and it is 1. We will // construct this product without explicitly forming the extended version of // d_W. - new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples+1, false); + Matrix *new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples+1, false); for (int row = 0; row < d_num_rows_of_W; ++row) { for (int col = 0; col < d_num_samples+1; ++col) { double new_d_W_entry = 0.0; @@ -268,8 +265,7 @@ IncrementalSVDFastUpdate::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } - delete d_W; - d_W = new_d_W; + d_W.reset(new_d_W); } // The new d_Up is the product of the current d_Up extended by another row diff --git a/lib/linalg/svd/IncrementalSVDStandard.cpp b/lib/linalg/svd/IncrementalSVDStandard.cpp index c45de38e6..14f7f6421 100644 --- a/lib/linalg/svd/IncrementalSVDStandard.cpp +++ b/lib/linalg/svd/IncrementalSVDStandard.cpp @@ -79,7 +79,7 @@ IncrementalSVDStandard::buildInitialSVD( // Build d_W for this new time interval. if (d_update_right_SV) { - d_W = new Matrix(1, 1, false); + d_W.reset(new Matrix(1, 1, false)); d_W->item(0, 0) = 1.0; } @@ -127,9 +127,8 @@ IncrementalSVDStandard::addLinearlyDependentSample( d_U.reset(U_times_Amod); // Chop a column off of W to form Wmod. - Matrix* new_d_W; if (d_update_right_SV) { - new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples, false); + Matrix *new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples, false); for (int row = 0; row < d_num_rows_of_W; ++row) { for (int col = 0; col < d_num_samples; ++col) { double new_d_W_entry = 0.0; @@ -142,8 +141,7 @@ IncrementalSVDStandard::addLinearlyDependentSample( for (int col = 0; col < d_num_samples; ++col) { new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } - delete d_W; - d_W = new_d_W; + d_W.reset(new_d_W); ++d_num_rows_of_W; } @@ -178,9 +176,8 @@ IncrementalSVDStandard::addNewSample( } tmp.mult(A, *d_U); - Matrix* new_d_W; if (d_update_right_SV) { - new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples+1, false); + Matrix *new_d_W = new Matrix(d_num_rows_of_W+1, d_num_samples+1, false); for (int row = 0; row < d_num_rows_of_W; ++row) { for (int col = 0; col < d_num_samples+1; ++col) { double new_d_W_entry = 0.0; @@ -193,8 +190,7 @@ IncrementalSVDStandard::addNewSample( for (int col = 0; col < d_num_samples+1; ++col) { new_d_W->item(d_num_rows_of_W, col) = W.item(d_num_samples, col); } - delete d_W; - d_W = new_d_W; + d_W.reset(new_d_W); } int num_dim = std::min(sigma.numRows(), sigma.numColumns()); diff --git a/lib/linalg/svd/SVD.cpp b/lib/linalg/svd/SVD.cpp index 514063867..eb1a27eb3 100644 --- a/lib/linalg/svd/SVD.cpp +++ b/lib/linalg/svd/SVD.cpp @@ -29,9 +29,4 @@ SVD::SVD( CAROM_VERIFY(options.max_num_samples > 0); } -SVD::~SVD() -{ - delete d_W; -} - } diff --git a/lib/linalg/svd/SVD.h b/lib/linalg/svd/SVD.h index 3153bc514..7bb06ea81 100644 --- a/lib/linalg/svd/SVD.h +++ b/lib/linalg/svd/SVD.h @@ -38,11 +38,6 @@ class SVD SVD( Options options); - /** - * Destructor. - */ - ~SVD(); - /** * @brief Collect the new sample, u_in at supplied time. * @@ -190,7 +185,7 @@ class SVD * Depending on the SVD algorithm, d_W may be distributed across all * processors or each processor may own all of U. */ - Matrix* d_W; + std::shared_ptr d_W; /** * @brief The vector S which is small. diff --git a/lib/linalg/svd/StaticSVD.cpp b/lib/linalg/svd/StaticSVD.cpp index b0a370195..8844cb107 100644 --- a/lib/linalg/svd/StaticSVD.cpp +++ b/lib/linalg/svd/StaticSVD.cpp @@ -173,9 +173,8 @@ StaticSVD::getSingularValues() // If these singular values are for the last time interval then they may not // be up to date so recompute them. if (!isBasisCurrent()) { - d_S = nullptr; - delete d_W; - d_W = nullptr; + d_S.reset(); + d_W.reset(); computeSVD(); } else { From 80126cd30d502a832536a38ce4ee6033d9a16e54 Mon Sep 17 00:00:00 2001 From: Dylan Copeland Date: Wed, 20 Nov 2024 10:39:22 -0800 Subject: [PATCH 19/19] Minor change. --- lib/linalg/svd/SVD.cpp | 3 --- 1 file changed, 3 deletions(-) diff --git a/lib/linalg/svd/SVD.cpp b/lib/linalg/svd/SVD.cpp index eb1a27eb3..bc4f0e6b7 100644 --- a/lib/linalg/svd/SVD.cpp +++ b/lib/linalg/svd/SVD.cpp @@ -20,9 +20,6 @@ SVD::SVD( d_dim(options.dim), d_num_samples(0), d_max_num_samples(options.max_num_samples), - d_W(NULL), - d_S(NULL), - d_snapshots(NULL), d_debug_algorithm(options.debug_algorithm) { CAROM_VERIFY(options.dim > 0);