Boost logo

Ublas :

Subject: Re: [ublas] poll: what's your uBLAS I/O usage ?
From: Jesse Perla (jesseperla_at_[hidden])
Date: 2010-05-30 16:26:39


Andrea Arteaga <andyspiros <at> gmail.com> writes:
> If you are interested, I will announce on this mailing list the release, which
will coincide with the end of my bachelor thesis. Then, I will open the project
and every one will be able to contribute to it.

Sounds great. If you are interested in making a more boost/C++ friendly
interface, you might want to convert your interface (or write a simple wrapper
that emulates/integrates with boost serialization:
http://www.boost.org/doc/libs/1_43_0/libs/serialization/doc/index.html

The idea would be that you add a new archive class (matlab_archive?) where
the opening/closing might be handled with RAII. Then you have some kind of
a naming wrapper when adding in different classes. The advantage of this is
that you can easily extend it to support things such as multi_array, etc.

ublas::matrix<double> M(2,2); //fill it
ublas::vector<double> v(2); //fill it

std::ofstream ofs("my.mat");
{
  boost::archive::matlab_binary_archive arch(ofs);
  arch << matlab_named("matrix1", M) << matlab_named("vector1", v);
} //Since the arch goes out of scope, this would call the .close()

/////////////////////////
The implementation of the function matlab_named should be easy enough as it
returns a reference to a wrapper type with the attached name.
e.g. something like the following untested pseudocode

//Specialization for whatever wrapper types you need...
template<typename DenseMatrixType>
struct named_dense_matrix
{
  std::string name_;
  const DenseMatrixType& m_;
  named_dense_matrix(std::string name, const DenseMatrixType& m)
   : name_(name), m_(m){};
};

//Specialization of the matlab_named function
template<typename DenseMatrixType>
named_dense_matrix<DenseMatrixType>
matlab_named(
  const DenseMatrixType& m,
  std::string name,
  boost::enable_if<is_dense_matrix<DenseMatrixType>* dummy = 0)
{
  return named_dense_matrix<DenseMatrixType>(m, name);
}

//(here you would need to get a simple metafunction to test for dense matrices
//I called it is_dense_matrix, but I am sure this could be found in the
//numeric bindings. Or just use partial specialization to implement it)

//The implementation of the serialization routine itself is just
//An operator overload that specializes for the appropriate named
//type wrapper. e.g.
template<typename DenseMatrixType>
boost::archive::matlab_binary_archive&
  operator << (const boost::archive::matlab_binary_archive& arch,
  const named_dense_matrix<DenseMatrixType>& mat)
{
  //Get the underlying archive information
  //Use mat.m_ and mat.name_ for the storage
}

I would be happy to hear what people think about this because I was considering
writing something similar later in the summer and would love to have a critique
of this interface.