[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9 Hints

In this section I’ve included some small hints and advices for the improving of the quality of plots and for the demonstration of some non-trivial features of MathGL library. In contrast to previous examples I showed mostly the idea but not the whole drawing function.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.1 “Compound” graphics

As I noted above, MathGL functions (except the special one, like Clf()) do not erase the previous plotting but just add the new one. It allows one to draw “compound” plots easily. For example, popular Matlab command surfc can be emulated in MathGL by 2 calls:

  Surf(a);
  Cont(a, "_");     // draw contours at bottom

Here a is 2-dimensional data for the plotting, -1 is the value of z-coordinate at which the contour should be plotted (at the bottom in this example). Analogously, one can draw density plot instead of contour lines and so on.

Another nice plot is contour lines plotted directly on the surface:

  Light(true);       // switch on light for the surface
  Surf(a, "BbcyrR"); // select 'jet' colormap for the surface
  Cont(a, "y");      // and yellow color for contours

The possible difficulties arise in black&white case, when the color of the surface can be close to the color of a contour line. In that case I may suggest the following code:

  Light(true);   // switch on light for the surface
  Surf(a, "kw"); // select 'gray' colormap for the surface
  CAxis(-1,0);   // first draw for darker surface colors
  Cont(a, "w");  // white contours
  CAxis(0,1);    // now draw for brighter surface colors
  Cont(a, "k");  // black contours
  CAxis(-1,1);   // return color range to original state

The idea is to divide the color range on 2 parts (dark and bright) and to select the contrasting color for contour lines for each of part.

Similarly, one can plot flow thread over density plot of vector field amplitude (this is another amusing plot from Matlab) and so on. The list of compound graphics can be prolonged but I hope that the general idea is clear.

Just for illustration I put here following sample code:

int sample(mglGraph *gr)
{
  mglData a,b,d;  mgls_prepare2v(&a,&b);  d = a;
  for(int i=0;i<a.nx*a.ny;i++)  d.a[i] = hypot(a.a[i],b.a[i]);
  mglData c;  mgls_prepare3d(&c);
  mglData v(10);  v.Fill(-0.5,1);

  gr->SubPlot(2,2,1,"");  gr->Title("Flow + Dens");
  gr->Flow(a,b,"br"); gr->Dens(d,"BbcyrR"); gr->Box();

  gr->SubPlot(2,2,0); gr->Title("Surf + Cont"); gr->Rotate(50,60);
  gr->Light(true);  gr->Surf(a);  gr->Cont(a,"y");  gr->Box();

  gr->SubPlot(2,2,2); gr->Title("Mesh + Cont"); gr->Rotate(50,60);
  gr->Box();  gr->Mesh(a);  gr->Cont(a,"_");

  gr->SubPlot(2,2,3); gr->Title("Surf3 + ContF3");gr->Rotate(50,60);
  gr->Box();  gr->ContF3(v,c,"z",0);  gr->ContF3(v,c,"x");  gr->ContF3(v,c);
  gr->SetCutBox(mglPoint(0,-1,-1), mglPoint(1,0,1.1));
  gr->ContF3(v,c,"z",c.nz-1); gr->Surf3(-0.5,c);
  return 0;
}
Example of “combined” plots
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.2 Transparency and lighting

Here I want to show how transparency and lighting both and separately change the look of a surface. So, there is code and picture for that:

int sample(mglGraph *gr)
{
  mglData a;  mgls_prepare2d(&a);
  gr->SubPlot(2,2,0); gr->Title("default"); gr->Rotate(50,60);
  gr->Box();  gr->Surf(a);

  gr->SubPlot(2,2,1); gr->Title("light on");  gr->Rotate(50,60);
  gr->Box();  gr->Light(true);  gr->Surf(a);

  gr->SubPlot(2,2,3); gr->Title("alpha on; light on");  gr->Rotate(50,60);
  gr->Box();  gr->Alpha(true);  gr->Surf(a);

  gr->SubPlot(2,2,2); gr->Title("alpha on");  gr->Rotate(50,60);
  gr->Box();  gr->Light(false); gr->Surf(a);
  return 0;
}
Example of transparency and lightings
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.3 Types of transparency

MathGL library has advanced features for setting and handling the surface transparency. The simplest way to add transparency is the using of function alpha. As a result, all further surfaces (and isosurfaces, density plots and so on) become transparent. However, their look can be additionally improved.

The value of transparency can be different from surface to surface. To do it just use SetAlphaDef before the drawing of the surface, or use option alpha (see Command options). If its value is close to 0 then the surface becomes more and more transparent. Contrary, if its value is close to 1 then the surface becomes practically non-transparent.

Also you can change the way how the light goes through overlapped surfaces. The function SetTranspType defines it. By default the usual transparency is used (‘0’) – surfaces below is less visible than the upper ones. A “glass-like” transparency (‘1’) has a different look – each surface just decreases the background light (the surfaces are commutable in this case).

A “neon-like” transparency (‘2’) has more interesting look. In this case a surface is the light source (like a lamp on the dark background) and just adds some intensity to the color. At this, the library sets automatically the black color for the background and changes the default line color to white.

As example I shall show several plots for different types of transparency. The code is the same except the values of SetTranspType function:

int sample(mglGraph *gr)
{
  gr->Alpha(true);  gr->Light(true);
  mglData a;  mgls_prepare2d(&a);
  gr->SetTranspType(0); gr->Clf();
  gr->SubPlot(2,2,0); gr->Rotate(50,60);  gr->Surf(a);  gr->Box();
  gr->SubPlot(2,2,1); gr->Rotate(50,60);  gr->Dens(a);  gr->Box();
  gr->SubPlot(2,2,2); gr->Rotate(50,60);  gr->Cont(a);  gr->Box();
  gr->SubPlot(2,2,3); gr->Rotate(50,60);  gr->Axial(a); gr->Box();
  return 0;
}
Example of SetTranspType(0). Example of SetTranspType(1). Example of SetTranspType(2).
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.4 Axis projection

You can easily make 3D plot and draw its x-,y-,z-projections (like in CAD) by using ternary function with arguments: 4 for Cartesian, 5 for Ternary and 6 for Quaternary coordinates. The sample code is:

int sample(mglGraph *gr)
{
  gr->SetRanges(0,1,0,1,0,1);
  mglData x(50),y(50),z(50),rx(10),ry(10), a(20,30);
  a.Modify("30*x*y*(1-x-y)^2*(x+y<1)");
  x.Modify("0.25*(1+cos(2*pi*x))");
  y.Modify("0.25*(1+sin(2*pi*x))");
  rx.Modify("rnd"); ry.Modify("(1-v)*rnd",rx);
  z.Modify("x");

  gr->Title("Projection sample");
  gr->Ternary(4);
  gr->Rotate(50,60);      gr->Light(true);
  gr->Plot(x,y,z,"r2");   gr->Surf(a,"#");
  gr->Axis(); gr->Grid(); gr->Box();
  gr->Label('x',"X",1);   gr->Label('y',"Y",1);   gr->Label('z',"Z",1);
}
Example of axis projections Example of ternary axis projections
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.5 Adding fog

MathGL can add a fog to the image. Its switching on is rather simple – just use fog function. There is the only feature – fog is applied for whole image. Not to particular subplot. The sample code is:

int sample(mglGraph *gr)
{
  mglData a;  mgls_prepare2d(&a);
  gr->Title("Fog sample");
  gr->Light(true);  gr->Rotate(50,60);  gr->Fog(1); gr->Box();
  gr->Surf(a);
  return 0;
}
Example of Fog().
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.6 Several light sources

In contrast to the most of other programs, MathGL supports several (up to 10) light sources. Moreover, the color each of them can be different: white (this is usual), yellow, red, cyan, green and so on. The use of several light sources may be interesting for the highlighting of some peculiarities of the plot or just to make an amusing picture. Note, each light source can be switched on/off individually. The sample code is:

int sample(mglGraph *gr)
{
  mglData a;  mgls_prepare2d(&a);
  gr->Title("Several light sources");
  gr->Rotate(50,60);  gr->Light(true);
  gr->AddLight(1,mglPoint(0,1,0),'c');
  gr->AddLight(2,mglPoint(1,0,0),'y');
  gr->AddLight(3,mglPoint(0,-1,0),'m');
  gr->Box();  gr->Surf(a,"h");
  return 0;
}
Example of several light sources.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.7 Using primitives

MathGL provide a set of functions for drawing primitives (see Primitives). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.

Primitives in MathGL.

Generally, you can create arbitrary new kind of plot using primitives. For example, MathGL don’t provide any special functions for drawing molecules. However, you can do it using only one type of primitives drop. The sample code is:

int sample(mglGraph *gr)
{
  gr->Alpha(true);  gr->Light(true);

  gr->SubPlot(2,2,0,"");  gr->Title("Methane, CH_4");
  gr->StartGroup("Methane");
  gr->Rotate(60,120);
  gr->Sphere(mglPoint(0,0,0),0.25,"k");
  gr->Drop(mglPoint(0,0,0),mglPoint(0,0,1),0.35,"h",1,2);
  gr->Sphere(mglPoint(0,0,0.7),0.25,"g");
  gr->Drop(mglPoint(0,0,0),mglPoint(-0.94,0,-0.33),0.35,"h",1,2);
  gr->Sphere(mglPoint(-0.66,0,-0.23),0.25,"g");
  gr->Drop(mglPoint(0,0,0),mglPoint(0.47,0.82,-0.33),0.35,"h",1,2);
  gr->Sphere(mglPoint(0.33,0.57,-0.23),0.25,"g");
  gr->Drop(mglPoint(0,0,0),mglPoint(0.47,-0.82,-0.33),0.35,"h",1,2);
  gr->Sphere(mglPoint(0.33,-0.57,-0.23),0.25,"g");
  gr->EndGroup();

  gr->SubPlot(2,2,1,"");  gr->Title("Water, H_{2}O");
  gr->StartGroup("Water");
  gr->Rotate(60,100);
  gr->StartGroup("Water_O");
  gr->Sphere(mglPoint(0,0,0),0.25,"r");
  gr->EndGroup();
  gr->StartGroup("Water_Bond_1");
  gr->Drop(mglPoint(0,0,0),mglPoint(0.3,0.5,0),0.3,"m",1,2);
  gr->EndGroup();
  gr->StartGroup("Water_H_1");
  gr->Sphere(mglPoint(0.3,0.5,0),0.25,"g");
  gr->EndGroup();
  gr->StartGroup("Water_Bond_2");
  gr->Drop(mglPoint(0,0,0),mglPoint(0.3,-0.5,0),0.3,"m",1,2);
  gr->EndGroup();
  gr->StartGroup("Water_H_2");
  gr->Sphere(mglPoint(0.3,-0.5,0),0.25,"g");
  gr->EndGroup();
  gr->EndGroup();

  gr->SubPlot(2,2,2,"");  gr->Title("Oxygen, O_2");
  gr->StartGroup("Oxygen");
  gr->Rotate(60,120);
  gr->Drop(mglPoint(0,0.5,0),mglPoint(0,-0.3,0),0.3,"m",1,2);
  gr->Sphere(mglPoint(0,0.5,0),0.25,"r");
  gr->Drop(mglPoint(0,-0.5,0),mglPoint(0,0.3,0),0.3,"m",1,2);
  gr->Sphere(mglPoint(0,-0.5,0),0.25,"r");
  gr->EndGroup();

  gr->SubPlot(2,2,3,"");  gr->Title("Ammonia, NH_3");
  gr->StartGroup("Ammonia");
  gr->Rotate(60,120);
  gr->Sphere(mglPoint(0,0,0),0.25,"b");
  gr->Drop(mglPoint(0,0,0),mglPoint(0.33,0.57,0),0.32,"n",1,2);
  gr->Sphere(mglPoint(0.33,0.57,0),0.25,"g");
  gr->Drop(mglPoint(0,0,0),mglPoint(0.33,-0.57,0),0.32,"n",1,2);
  gr->Sphere(mglPoint(0.33,-0.57,0),0.25,"g");
  gr->Drop(mglPoint(0,0,0),mglPoint(-0.65,0,0),0.32,"n",1,2);
  gr->Sphere(mglPoint(-0.65,0,0),0.25,"g");
  gr->EndGroup();
  return 0;
}
Example of molecules drawing.

Moreover, some of special plots can be more easily produced by primitives rather than by specialized function. For example, Venn diagram can be produced by Error plot:

int sample(mglGraph *gr)
{
  double xx[3]={-0.3,0,0.3}, yy[3]={0.3,-0.3,0.3}, ee[3]={0.7,0.7,0.7};
  mglData x(3,xx), y(3,yy), e(3,ee);
  gr->Title("Venn-like diagram"); gr->Alpha(true);
  gr->Error(x,y,e,e,"!rgb@#o");
  return 0;
}

You see that you have to specify and fill 3 data arrays. The same picture can be produced by just 3 calls of circle function:

int sample(mglGraph *gr)
{
  gr->Title("Venn-like diagram"); gr->Alpha(true);
  gr->Circle(mglPoint(-0.3,0.3),0.7,"rr@");
  gr->Circle(mglPoint(0,-0.3),0.7,"gg@");
  gr->Circle(mglPoint( 0.3,0.3),0.7,"bb@");
  return 0;
}

Of course, the first variant is more suitable if you need to plot a lot of circles. But for few ones the usage of primitives looks easy.

Example of Venn diagram.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.8 STFA sample

Short-time Fourier Analysis (stfa) is one of informative method for analyzing long rapidly oscillating 1D data arrays. It is used to determine the sinusoidal frequency and phase content of local sections of a signal as it changes over time.

MathGL can find and draw STFA result. Just to show this feature I give following sample. Initial data arrays is 1D arrays with step-like frequency. Exactly this you can see at bottom on the STFA plot. The sample code is:

int sample(mglGraph *gr)
{
  mglData a(2000), b(2000);
  gr->Fill(a,"cos(50*pi*x)*(x<-.5)+cos(100*pi*x)*(x<0)*(x>-.5)+\
  cos(200*pi*x)*(x<.5)*(x>0)+cos(400*pi*x)*(x>.5)");
  gr->SubPlot(1, 2, 0,"<_");  gr->Title("Initial signal");
  gr->Plot(a);
  gr->Axis();
  gr->Label('x', "\\i t");

  gr->SubPlot(1, 2, 1,"<_");  gr->Title("STFA plot");
  gr->STFA(a, b, 64);
  gr->Axis();
  gr->Label('x', "\\i t");
  gr->Label('y', "\\omega", 0);
  return 0;
}
Example of STFA().
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.9 Mapping visualization

Sometime ago I worked with mapping and have a question about its visualization. Let me remember you that mapping is some transformation rule for one set of number to another one. The 1d mapping is just an ordinary function – it takes a number and transforms it to another one. The 2d mapping (which I used) is a pair of functions which take 2 numbers and transform them to another 2 ones. Except general plots (like surfc, surfa) there is a special plot – Arnold diagram. It shows the area which is the result of mapping of some initial area (usually square).

I tried to make such plot in map. It shows the set of points or set of faces, which final position is the result of mapping. At this, the color gives information about their initial position and the height describes Jacobian value of the transformation. Unfortunately, it looks good only for the simplest mapping but for the real multivalent quasi-chaotic mapping it produces a confusion. So, use it if you like :).

The sample code for mapping visualization is:

int sample(mglGraph *gr)
{
  mglData a(50, 40), b(50, 40);
  gr->Puts(mglPoint(0, 0), "\\to", ":C", -1.4);
  gr->SetRanges(-1,1,-1,1,-2,2);

  gr->SubPlot(2, 1, 0);
  gr->Fill(a,"x");  gr->Fill(b,"y");
  gr->Puts(mglPoint(0, 1.1), "\\{x, y\\}", ":C", -2);   gr->Box();
  gr->Map(a, b, "brgk");

  gr->SubPlot(2, 1, 1);
  gr->Fill(a,"(x^3+y^3)/2");  gr->Fill(b,"(x-y)/2");
  gr->Puts(mglPoint(0, 1.1), "\\{\\frac{x^3+y^3}{2}, \\frac{x-y}{2}\\}", ":C", -2);
  gr->Box();
  gr->Map(a, b, "brgk");
  return 0;
}
Example of Map().
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.10 Making histogram

Using the hist function(s) for making regular distributions is one of useful fast methods to process and plot irregular data. Hist can be used to find some momentum of set of points by specifying weight function. It is possible to create not only 1D distributions but also 2D and 3D ones. Below I place the simplest sample code which demonstrate hist usage:

int sample(mglGraph *gr)
{
  mglData x(10000), y(10000), z(10000);  gr->Fill(x,"2*rnd-1");
  gr->Fill(y,"2*rnd-1"); gr->Fill(z,"exp(-6*(v^2+w^2))",x,y);
  mglData xx=gr->Hist(x,z), yy=gr->Hist(y,z);	xx.Norm(0,1);
  yy.Norm(0,1);
  gr->MultiPlot(3,3,3,2,2,"");   gr->SetRanges(-1,1,-1,1,0,1);
  gr->Box();  gr->Dots(x,y,z,"wyrRk");
  gr->MultiPlot(3,3,0,2,1,"");   gr->SetRanges(-1,1,0,1);
  gr->Box();  gr->Bars(xx);
  gr->MultiPlot(3,3,5,1,2,"");   gr->SetRanges(0,1,-1,1);
  gr->Box();  gr->Barh(yy);
  gr->SubPlot(3,3,2);
  gr->Puts(mglPoint(0.5,0.5),"Hist and\nMultiPlot\nsample","a",-6);
  return 0;
}
Example of Hist().
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.11 Nonlinear fitting hints

Nonlinear fitting is rather simple. All that you need is the data to fit, the approximation formula and the list of coefficients to fit (better with its initial guess values). Let me demonstrate it on the following simple example. First, let us use sin function with some random noise:

  mglData rnd(100), in(100); //data to be fitted and ideal data
  gr->Fill(rnd,"0.4*rnd+0.1+sin(2*pi*x)");
  gr->Fill(in,"0.3+sin(2*pi*x)");

and plot it to see that data we will fit

  gr->Title("Fitting sample");
  gr->SetRange('y',-2,2); gr->Box();  gr->Plot(rnd, ". ");
  gr->Axis(); gr->Plot(in, "b");
  gr->Puts(mglPoint(0, 2.2), "initial: y = 0.3+sin(2\\pi x)", "b");

The next step is the fitting itself. For that let me specify an initial values ini for coefficients ‘abc’ and do the fitting for approximation formula ‘a+b*sin(c*x)

  mreal ini[3] = {1,1,3};
  mglData Ini(3,ini);
  mglData res = gr->Fit(rnd, "a+b*sin(c*x)", "abc", Ini);

Now display it

  gr->Plot(res, "r");
  gr->Puts(mglPoint(-0.9, -1.3), "fitted:", "r:L");
  gr->PutsFit(mglPoint(0, -1.8), "y = ", "r");

NOTE! the fitting results may have strong dependence on initial values for coefficients due to algorithm features. The problem is that in general case there are several local "optimums" for coefficients and the program returns only first found one! There are no guaranties that it will be the best. Try for example to set ini[3] = {0, 0, 0} in the code above.

The full sample code for nonlinear fitting is:

int sample(mglGraph *gr)
{
  mglData rnd(100), in(100);
  gr->Fill(rnd,"0.4*rnd+0.1+sin(2*pi*x)");
  gr->Fill(in,"0.3+sin(2*pi*x)");
  mreal ini[3] = {1,1,3};
  mglData Ini(3,ini);

  mglData res = gr->Fit(rnd, "a+b*sin(c*x)", "abc", Ini);

  gr->Title("Fitting sample");
  gr->SetRange('y',-2,2); gr->Box();  gr->Plot(rnd, ". ");
  gr->Axis();   gr->Plot(res, "r"); gr->Plot(in, "b");
  gr->Puts(mglPoint(-0.9, -1.3), "fitted:", "r:L");
  gr->PutsFit(mglPoint(0, -1.8), "y = ", "r");
  gr->Puts(mglPoint(0, 2.2), "initial: y = 0.3+sin(2\\pi x)", "b");
  return 0;
}
Example of nonlinear fitting.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.12 PDE solving hints

Solving of Partial Differential Equations (PDE, including beam tracing) and ray tracing (or finding particle trajectory) are more or less common task. So, MathGL have several functions for that. There are mglRay() for ray tracing, mglPDE() for PDE solving, mglQO2d() for beam tracing in 2D case (see Global functions). Note, that these functions take “Hamiltonian” or equations as string values. And I don’t plan now to allow one to use user-defined functions. There are 2 reasons: the complexity of corresponding interface; and the basic nature of used methods which are good for samples but may not good for serious scientific calculations.

The ray tracing can be done by mglRay() function. Really ray tracing equation is Hamiltonian equation for 3D space. So, the function can be also used for finding a particle trajectory (i.e. solve Hamiltonian ODE) for 1D, 2D or 3D cases. The function have a set of arguments. First of all, it is Hamiltonian which defined the media (or the equation) you are planning to use. The Hamiltonian is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’, time ‘t’ (for particle dynamics) and momentums ‘p’=p_x, ‘q’=p_y, ‘v’=p_z. Next, you have to define the initial conditions for coordinates and momentums at ‘t’=0 and set the integrations step (default is 0.1) and its duration (default is 10). The Runge-Kutta method of 4-th order is used for integration.

  const char *ham = "p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)";
  mglData r = mglRay(ham, mglPoint(-0.7, -1), mglPoint(0, 0.5), 0.02, 2);

This example calculate the reflection from linear layer (media with Hamiltonian ‘p^2+q^2-x-1’=p_x^2+p_y^2-x-1). This is parabolic curve. The resulting array have 7 columns which contain data for {x,y,z,p,q,v,t}.

The solution of PDE is a bit more complicated. As previous you have to specify the equation as pseudo-differential operator \hat H(x, \nabla) which is called sometime as “Hamiltonian” (for example, in beam tracing). As previously, it is defined by string which may depend on coordinates ‘x’, ‘y’, ‘z’ (but not time!), momentums ‘p’=(d/dx)/i k_0, ‘q’=(d/dy)/i k_0 and field amplitude ‘u’=|u|. The evolutionary coordinate is ‘z’ in all cases. So that, the equation look like du/dz = ik_0 H(x,y,\hat p, \hat q, |u|)[u]. Dependence on field amplitude ‘u’=|u| allows one to solve nonlinear problems too. For example, for nonlinear Shrodinger equation you may set ham="p^2 + q^2 - u^2". Also you may specify imaginary part for wave absorption, like ham = "p^2 + i*x*(x>0)", but only if dependence on variable ‘i’ is linear (i.e. H = Hre+i*Him).

Next step is specifying the initial conditions at ‘z’=Min.z. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified range [Min, Max]. So, the data arrays should have corresponding scales. Finally, you may set the integration step and parameter k0=k_0. Also keep in mind, that internally the 2 times large box is used (for suppressing numerical reflection from boundaries) and the equation should well defined even in this extended range.

Final comment is concerning the possible form of pseudo-differential operator H. At this moment, simplified form of operator H is supported – all “mixed” terms (like ‘x*p’->x*d/dx) are excluded. For example, in 2D case this operator is effectively H = f(p,z) + g(x,z,u). However commutable combinations (like ‘x*q’->x*d/dy) are allowed for 3D case.

So, for example let solve the equation for beam deflected from linear layer and absorbed later. The operator will have the form ‘"p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)"’ that correspond to equation ik_0 \partial_z u + \Delta u + x \cdot u + i (x+z)/2 \cdot u = 0. This is typical equation for Electron Cyclotron (EC) absorption in magnetized plasmas. For initial conditions let me select the beam with plane phase front exp(-48*(x+0.7)^2). The corresponding code looks like this:

int sample(mglGraph *gr)
{
  mglData a,re(128),im(128);
  gr->Fill(re,"exp(-48*(x+0.7)^2)");
  a = gr->PDE("p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)", re, im, 0.01, 30);
  a.Transpose("yxz");
  gr->SubPlot(1,1,0,"<_"); gr->Title("PDE solver");
  gr->SetRange('c',0,1);  gr->Dens(a,"wyrRk");
  gr->Axis(); gr->Label('x', "\\i x");  gr->Label('y', "\\i z");
  gr->FPlot("-x", "k|");
  gr->Puts(mglPoint(0, 0.85), "absorption: (x+z)/2 for x+z>0");
  gr->Puts(mglPoint(0,1.1),"Equation: ik_0\\partial_zu + \\Delta u + x\\cdot u + i \\frac{x+z}{2}\\cdot u = 0");
  return 0;
}
Example of PDE solving.

The last example is example of beam tracing. Beam tracing equation is special kind of PDE equation written in coordinates accompanied to a ray. Generally this is the same parameters and limitation as for PDE solving but the coordinates are defined by the ray and by parameter of grid width w in direction transverse the ray. So, you don’t need to specify the range of coordinates. BUT there is limitation. The accompanied coordinates are well defined only for smooth enough rays, i.e. then the ray curvature K (which is defined as 1/K^2 = (|\ddot r|^2 |\dot r|^2 - (\ddot r, \dot r)^2)/|\dot r|^6) is much large then the grid width: K>>w. So, you may receive incorrect results if this condition will be broken.

You may use following code for obtaining the same solution as in previous example:

int sample(mglGraph *gr)
{
  mglData r, xx, yy, a, im(128), re(128);
  const char *ham = "p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)";
  r = mglRay(ham, mglPoint(-0.7, -1), mglPoint(0, 0.5), 0.02, 2);
  gr->SubPlot(1,1,0,"<_"); gr->Title("Beam and ray tracing");
  gr->Plot(r.SubData(0), r.SubData(1), "k");
  gr->Axis(); gr->Label('x', "\\i x");  gr->Label('y', "\\i z");

  // now start beam tracing
  gr->Fill(re,"exp(-48*x^2)");
  a = mglQO2d(ham, re, im, r, xx, yy, 1, 30);
  gr->SetRange('c',0, 1);
  gr->Dens(xx, yy, a, "wyrRk");
  gr->FPlot("-x", "k|");
  gr->Puts(mglPoint(0, 0.85), "absorption: (x+y)/2 for x+y>0");
  gr->Puts(mglPoint(0.7, -0.05), "central ray");
  return 0;
}
Example of beam tracing.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.13 MGL parser using

Sometimes you may prefer to use MGL scripts in yours code. It is simpler (especially in comparison with C/Fortran interfaces) and provide faster way to plot the data with annotations, labels and so on. Class mglParse (see section mglParse class parse MGL scripts in C++. It have also the corresponding interface for C/Fortran.

The key function here is mglParse::Parse() (or mgl_parse() for C/Fortran) which execute one command per string. At this the detailed information about the possible errors or warnings is passed as function value. Or you may execute the whole script as long string with lines separated by ‘\n’. Functions mglParse::Execute() and mgl_parse_text() perform it. Also you may set the values of parameters ‘$0’...‘$9’ for the script by functions mglParse::AddParam() or mgl_add_param(), allow/disable picture resizing, check “once” status and so on. The usage is rather straight-forward.

The only non-obvious thing is data transition between script and yours program. There are 2 stages: add or find variable; and set data to variable. In C++ you may use functions mglParse::AddVar() and mglParse::FindVar() which return pointer to mglData. In C/Fortran the corresponding functions are mgl_add_var(), mgl_find_var(). This data pointer is valid until next Parse() or Execute() call. Note, you must not delete or free the data obtained from these functions!

So, some simple example at the end. Here I define a data array, create variable, put data into it and plot it. The C++ code looks like this:

int sample(mglGraph *gr)
{
  gr->Title("MGL parser sample");
  mreal a[100];   // let a_i = sin(4*pi*x), x=0...1
  for(int i=0;i<100;i++)a[i]=sin(4*M_PI*i/99);
  mglParse *parser = new mglParse;
  mglData *d = parser->AddVar("dat");
  d->Set(a,100); // set data to variable
  parser->Execute(gr, "plot dat; xrange 0 1\nbox\naxis");
  // you may break script at any line do something
  // and continue after that
  parser->Execute(gr, "xlabel 'x'\nylabel 'y'\nbox");
  // also you may use cycles or conditions in script
  parser->Execute(gr, "for $0 -1 1 0.1\nif $0<0\n"
    "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n"
    "endif\nnext");
  delete parser;
  return 0;
}

The code in C/Fortran looks practically the same:

int sample(HMGL gr)
{
  mgl_title(gr, "MGL parser sample", "", -2);
  double a[100];   // let a_i = sin(4*pi*x), x=0...1
  int i;
  for(i=0;i<100;i++)  a[i]=sin(4*M_PI*i/99);
  HMPR parser = mgl_create_parser();
  HMDT d = mgl_parser_add_var(parser, "dat");
  mgl_data_set_double(d,a,100,1,1);    // set data to variable
  mgl_parse_text(gr, parser, "plot dat; xrange 0 1\nbox\naxis");
  // you may break script at any line do something
  // and continue after that
  mgl_parse_text(gr, parser, "xlabel 'x'\nylabel 'y'");
  // also you may use cycles or conditions in script
  mgl_parse_text(gr, parser, "for $0 -1 1 0.1\nif $0<0\n"
    "line 0 0 -1 $0 'r':else:line 0 0 -1 $0 'g'\n"
    "endif\nnext");
  mgl_write_png(gr, "test.png", "");  // don't forgot to save picture
  return 0;
}
Example of MGL script parsing.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.14 Using options

Command options allow the easy setup of the selected plot by changing global settings only for this plot. Often, options are used for specifying the range of automatic variables (coordinates). However, options allows easily change plot transparency, numbers of line or faces to be drawn, or add legend entries. The sample function for options usage is:

void template(mglGraph *gr)
{
  mglData a(31,41);
  gr->Fill(a,"-pi*x*exp(-(y+1)^2-4*x^2)");

  gr->SubPlot(2,2,0);	gr->Title("Options for coordinates");
  gr->Alpha(true);	gr->Light(true);
  gr->Rotate(40,60);    gr->Box();
  gr->Surf(a,"r","yrange 0 1"); gr->Surf(a,"b","yrange 0 -1");
  if(mini)	return;
  gr->SubPlot(2,2,1);   gr->Title("Option 'meshnum'");
  gr->Rotate(40,60);    gr->Box();
  gr->Mesh(a,"r","yrange 0 1"); gr->Mesh(a,"b","yrange 0 -1; meshnum 5");
  gr->SubPlot(2,2,2);   gr->Title("Option 'alpha'");
  gr->Rotate(40,60);    gr->Box();
  gr->Surf(a,"r","yrange 0 1; alpha 0.7");
  gr->Surf(a,"b","yrange 0 -1; alpha 0.3");
  gr->SubPlot(2,2,3,"<_");  gr->Title("Option 'legend'");
  gr->FPlot("x^3","r","legend 'y = x^3'");
  gr->FPlot("cos(pi*x)","b","legend 'y = cos \\pi x'");
  gr->Box();    gr->Axis(); gr->Legend(2,"");
}
Example of options usage.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.15 “Templates”

As I have noted before, the change of settings will influence only for the further plotting commands. This allows one to create “template” function which will contain settings and primitive drawing for often used plots. Correspondingly one may call this template-function for drawing simplification.

For example, let one has a set of points (experimental or numerical) and wants to compare it with theoretical law (for example, with exponent law \exp(-x/2), x \in [0, 20]). The template-function for this task is:

void template(mglGraph *gr)
{
  mglData  law(100);      // create the law
  law.Modify("exp(-10*x)");
  gr->SetRanges(0,20, 0.0001,1);
  gr->SetFunc(0,"lg(y)",0);
  gr->Plot(law,"r2");
  gr->Puts(mglPoint(10,0.2),"Theoretical law: e^x","r:L");
  gr->Label('x',"x val."); gr->Label('y',"y val.");
  gr->Axis(); gr->Grid("xy","g;"); gr->Box();
}

At this, one will only write a few lines for data drawing:

  template(gr);     // apply settings and default drawing from template
  mglData dat("fname.dat"); // load the data
  // and draw it (suppose that data file have 2 columns)
  gr->Plot(dat.SubData(0),dat.SubData(1),"bx ");

A template-function can also contain settings for font, transparency, lightning, color scheme and so on.

I understand that this is obvious thing for any professional programmer, but I several times receive suggestion about “templates” ... So, I decide to point out it here.


[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.16 Stereo image

One can easily create stereo image in MathGL. Stereo image can be produced by making two subplots with slightly different rotation angles. The corresponding code looks like this:

int sample(mglGraph *gr)
{
  mglData a;  mgls_prepare2d(&a);
  gr->Light(true);

  gr->SubPlot(2,1,0); gr->Rotate(50,60+1);
  gr->Box();  gr->Surf(a);

  gr->SubPlot(2,1,1); gr->Rotate(50,60-1);
  gr->Box();  gr->Surf(a);
  return 0;
}
Example of stereo image.
[ < ] [ > ]   [ << ] [ Up ] [ >> ]         [Top] [Contents] [Index] [ ? ]

2.9.17 Reduce memory usage

By default MathGL save all primitives in memory, rearrange it and only later draw them on bitmaps. Usually, this speed up drawing, but may require a lot of memory for plots which contain a lot of faces (like cloud, dew). You can use quality function for setting to use direct drawing on bitmap and bypassing keeping any primitives in memory. This function also allow you to decrease the quality of the resulting image but increase the speed of the drawing.

The code for lowest memory usage looks like this:

int sample(mglGraph *gr)
{
  gr->SetQuality(6);   // firstly, set to draw directly on bitmap
  for(i=0;i<1000;i++)
    gr->Sphere(mglPoint(mgl_rnd()*2-1,mgl_rnd()*2-1),0.05);
  return 0;
}

[ < ] [ > ]   [ << ] [ Up ] [ >> ]

This document was generated on August 12, 2013 using texi2html 1.82.