Previous: , Up: Basic usage   [Contents][Index]


3.1.8 MathGL and MPI

For using MathGL in MPI program you just need to: (1) plot its own part of data for each running node; (2) collect resulting graphical information in a single program (for example, at node with rank=0); (3) save it. The sample code below demonstrate this for very simple sample of surface drawing.

First you need to initialize MPI

#include <stdio.h>
#include <mgl2/mpi.h>
#include <mpi.h>

int main(int argc, char *argv[])
{
  // initialize MPI
  int rank=0, numproc=1;
  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD,&numproc);
  MPI_Comm_rank(MPI_COMM_WORLD,&rank);
  if(rank==0) printf("Use %d processes.\n", numproc);

Next step is data creation. For simplicity, I create data arrays with the same sizes for all nodes. At this, you have to create mglGraph object too.

  // initialize data similarly for all nodes
  mglData a(128,256);
  mglGraphMPI gr;

Now, data should be filled by numbers. In real case, it should be some kind of calculations. But I just fill it by formula.

  // do the same plot for its own range
  char buf[64];
  sprintf(buf,"xrange %g %g",2.*rank/numproc-1,2.*(rank+1)/numproc-1);
  gr.Fill(a,"sin(2*pi*x)",buf);

It is time to plot the data. Don’t forget to set proper axis range(s) by using parametric form or by using options (as in the sample).

  // plot data in each node
  gr.Clf();   // clear image before making the image
  gr.Rotate(40,60);
  gr.Surf(a,"",buf);

Finally, let send graphical information to node with rank=0.

  // collect information
  if(rank!=0) gr.MPI_Send(0);
  else for(int i=1;i<numproc;i++)  gr.MPI_Recv(i);

Now, node with rank=0 have whole image. It is time to save the image to a file. Also, you can add a kind of annotations here – I draw axis and bounding box in the sample.

  if(rank==0)
  {
    gr.Box();   gr.Axis();   // some post processing
    gr.WritePNG("test.png"); // save result
  }

In my case the program is done, and I finalize MPI. In real program, you can repeat the loop of data calculation and data plotting as many times as you need.

  MPI_Finalize();
  return 0;
}

You can type ‘mpic++ test.cpp -lmgl-mpi -lmgl && mpirun -np 8 ./a.out’ for compilation and running the sample program on 8 nodes. Note, that you have to set enable-mpi=ON at MathGL configure to use this feature.





Previous: , Up: Basic usage   [Contents][Index]