Program Listing for File eigen.h

Return to documentation for file (source/eigen.h)

/*
 * eigen.h Serializers for dense matrices/arrays/vectors from Eigen.
 *
 * References:
 *
 *   [1]
 *
 * Future Improvements:
 *
 *   [1]
 *
 *
 * Author:              Tom Clark  (thclark@github)
 *
 * Copyright (c) 2017-8 T Clark. All Rights Reserved.
 *
 */

#ifndef CPPLOT_EIGEN_H
#define CPPLOT_EIGEN_H

#include <Eigen/Dense>


namespace cpplot {


template<typename Derived>
void to_json(nlohmann::json& j, const Eigen::DenseBase<Derived>& in) {

    // Use the eigen matrix formatting code to stream the matrix to a string.
    // This'll likely be faster than anything I can do here.
    Eigen::IOFormat vector_format(Eigen::FullPrecision, Eigen::DontAlignCols, ", ", ", ", "[", "]");
    Eigen::IOFormat matrix_format(Eigen::FullPrecision, Eigen::DontAlignCols, ", ", ", ", "[", "]", "[", "]");

    // Stream the eigen matrix, vector or array
    std::stringstream value_stream;
    if (in.cols() == 1 && in.rows() > 0) {
        value_stream << in.transpose().format(vector_format);
    } else if (in.rows() == 1) {
        value_stream << in.format(vector_format);
    } else {
        value_stream << in.format(matrix_format);
    }

    // Explicitly add the string as the json object
    // TODO - reparsing this string object is pretty inefficient. Maybe best to write my own after all
    j = nlohmann::json::parse(value_stream.str());

}


} // end namespace

#endif //CPPLOT_EIGEN_H