diff --git a/ifopt_core/src/composite.cc b/ifopt_core/src/composite.cc index 1b8eddd..7f67141 100644 --- a/ifopt_core/src/composite.cc +++ b/ifopt_core/src/composite.cc @@ -1,4 +1,4 @@ -/****************************************************************************** +/****************************************************************************** Copyright (c) 2017, Alexander W Winkler. All rights reserved. Redistribution and use in source and binary forms, with or without @@ -130,16 +130,21 @@ Composite::GetJacobian () const Jacobian jacobian(GetRows(), n_var); int row = 0; + std::vector< Eigen::Triplet > triplet_list; + for (const auto& c : components_) { const Jacobian& jac = c->GetJacobian(); + triplet_list.reserve(triplet_list.size()+jac.nonZeros()); + for (int k=0; k(row+it.row(), it.col(), it.value())); if (!is_cost_) row += c->GetRows(); } + jacobian.setFromTriplets(triplet_list.begin(), triplet_list.end()); return jacobian; } diff --git a/ifopt_core/src/leaves.cc b/ifopt_core/src/leaves.cc index 4b03253..6880113 100644 --- a/ifopt_core/src/leaves.cc +++ b/ifopt_core/src/leaves.cc @@ -1,4 +1,4 @@ -/****************************************************************************** +/****************************************************************************** Copyright (c) 2017, Alexander W Winkler. All rights reserved. Redistribution and use in source and binary forms, with or without @@ -50,20 +50,26 @@ ConstraintSet::GetJacobian () const Jacobian jacobian(GetRows(), variables_->GetRows()); int col = 0; + Jacobian jac; + std::vector< Eigen::Triplet > triplet_list; + for (const auto& vars : variables_->GetComponents()) { int n = vars->GetRows(); - Jacobian jac = Jacobian(GetRows(), n); + jac.resize(GetRows(), n); FillJacobianBlock(vars->GetName(), jac); + // reserve space for the new elements to reduce memory allocation + triplet_list.reserve(triplet_list.size()+jac.nonZeros()); - // insert the derivative in the correct position in the overall Jacobian + // create triplets for the derivative at the correct position in the overall Jacobian for (int k=0; k(it.row(), col+it.col(), it.value())); col += n; } + // transform triplet vector into sparse matrix + jacobian.setFromTriplets(triplet_list.begin(), triplet_list.end()); return jacobian; }