[go: up one dir, main page]

Sparse matrix not zeroed when setting from empty list of triplets

Summary

The documentation for the SparseMatrix.setFromTriplets method says that "The initial contents of *this are destroyed". However, if the provided list of triplets is empty, the contents of the matrix are unchanged. This behavior appears to have changed since Eigen 3.4.0. From doing a git bisect on the example below, I narrowed it down to this commit: 81172cbd.

Environment

  • Operating System : macOS 15.6
  • Architecture : Arm64
  • Eigen Version : master branch at 8a8fbc8f
  • Compiler Version : Apple clang version 17.0.0 (clang-1700.0.13.5)
  • Compile Flags : --std=c++17
  • Vector Extension : N/A?

Minimal Example

#include "Eigen/Sparse"
#include <vector>
#include <iostream>

int main(int argc, char** argv)
{
    Eigen::SparseMatrix<double> M(3, 3);
    std::vector<Eigen::Triplet<double>> triplets1;
    std::vector<Eigen::Triplet<double>> triplets2;
    std::vector<Eigen::Triplet<double>> triplets3;
    triplets1.emplace_back(0, 0, 3.0);
    triplets1.emplace_back(1, 2, 4.0);
    triplets1.emplace_back(2, 1, 6.0);

    triplets3.emplace_back(0, 0, 0.0);
    std::cout << "Initial: sum = " << M.sum() << " (expected 0.0)" << std::endl;
    M.setFromTriplets(triplets1.begin(), triplets1.end());
    std::cout << "From triplets: sum = " << M.sum() << " (expected 13.0)" << std::endl;
    M.setFromTriplets(triplets2.begin(), triplets2.end());
    std::cout << "From empty triplet list: sum = " << M.sum() << " (expected 0.0)" << std::endl;

    M.setFromTriplets(triplets2.begin(), triplets2.end());
    M.setFromTriplets(triplets3.begin(), triplets3.end());
    std::cout << "From triplet zeros: sum = " << M.sum() << " (expected 0.0)" << std::endl;
    return 0;
}

Steps to reproduce

  1. Complile the MWE above
  2. Run it

What is the current bug behavior?

Output of the test program above on the current development version:

Initial: sum = 0 (expected 0.0)
From triplets: sum = 13 (expected 13.0)
From empty triplet list: sum = 13 (expected 0.0)
From triplet zeros: sum = 0 (expected 0.0)

What is the expected correct behavior?

Output of the test program above from Eigen 3.4.0:

Initial: sum = 0 (expected 0.0)
From triplets: sum = 13 (expected 13.0)
From empty triplet list: sum = 0 (expected 0.0)
From triplet zeros: sum = 0 (expected 0.0)