I am currently using PETSc to solve the transient heat equation (DMeshCreate), but at each time step I need to compute cost functionals, which require the global solution. How can I obtain the global solution from the local solutions?
Additionally, I would like to know how to save this global solution for visualization in ParaView.
When you say you want to compute a cost functional, probably it implies that you have to compute an integral over the whole domain. There is a standard way to do it: compute each integral in each subdomain, and add up all of them. However, doing that you have to introduce a partition of unity in order to avoid taking twice the integral on the overlapping regions.
The typical code lines for that are
//build partition of unity
fespace Vhpart(Th, P0); // P0 elements for partition function
Vhpart part; // Partition function
PartitionCreate(Th, part[], P0); // Create partition using the mesh Th, part[] takes values 0 or 1
real localint = int2d(Th)(part*sol);//integral over the subdomain, without overlapping
real globalint;//global integral (has to be computed)
mpiAllReduce(localint, globalint, mpiCommWorld, mpiSUM);//sum up the local integrals to get the global integral
if (mpirank==0) cout << "The global integral is " << globalint << endl;
About visualization with paraview, you can do as (for example)
It will create several files: sol_nbproc.pvd where nbproc is the number of process, and the files sol_nbproc_…vtu, one for each proc.
The file you have to load with paraview is the master file sol_nbproc.pvd (it will load all the proc files together).