How to extract the coefficients of a dolphin::Function in C++?


134
views
0
4 months ago by
Hi all,

I need something that extracts the coefficients of a dolfin::Function (the coefficients u_i of u=sum(u_i * phi_i)) and allocates them in a std::vector<double>. I need also something that do the same on the contrary. 
I tried to do two functions using the documentation found in internet, and I produced something like:

// from std::vector<double> to dolfin<Function>
void set(std::shared_ptr<Function> func, std::vector<double> val){
      int size=(func->vector())->size();
      la_index ii(0);
      for(int jj=0;jj<size;jj++){
            (func->vector())->setitem(ii,val[jj]);
            ii++;
      }
}

// from dolfin::Function to std::vector<double>
std::vector<double> get(std::shared_ptr<Function> func){
      int size=(func->vector())->size();
      la_index ii(0);
      std::vector<double> res(size);
      for(int jj=0;jj<size;jj++){
            res[jj]=(*(func->vector()))[ii];
            ii++;
      }

return res;
}

Of course I do not have any idea of what this stuff does. It seems to produce something sensible. I did some trials: for example going beyond with the index while extracting the values from Function, in order to have a segmentation fault. But that produced random double values. 
What do you think? Do you have any suggestions? Is the code above right?
Community: FEniCS Project

1 Answer


2
4 months ago by
You first want to extract the vector that underlies the Function:
Function u(V);
auto x = u.vector();

Next, you need to extract components from the vector. If you want them all (for the process):

std::vector<double> values;
x->get_local(values);

The are more function in dolfin::GenericVector for more fine grained access to vector components.

To make sense of the vector entries you will need to use the DofMap. Some functions in dolfin/fem/fem_utils.h might be helpful.

Thanks a lot, this is very useful!
written 4 months ago by Francesco Clerici  
Please login to add an answer/comment or follow this question.

Similar posts:
Search »