Это документация для MathGL (версии 8.0) – библиотеки классов и функций для построения научной графики. Пожалуйста сообщайте о любых ошибках в этом руководстве на mathgl.abalakin@gmail.org. Дополнительную информацию о MathGL можно найти на домашней странице проекта http://mathgl.sourceforge.net/.
Copyright © 2008-2012 Alexey A. Balakin.
Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled “GNU Free Documentation License.”
MathGL это ...
Код для создания качественной научной графики на различных платформах. Код для быстрой обработки и отображения больших массивов данных. Код для работы в графическом и консольном режимах и легкого интегрирования в другие программы. Код с большим обновляемым набором графиков и инструментами обработки данных. Именно такого кода мне не хватало в последние годы при работе на персональных компьютерах и на кластерах. И именно такой код я постарался создать в библиотеке MathGL.
На данный момент (версия 8.0) MathGL это более 50 основных типов графиков для одно-, двух- и трехмерных массивов, возможность экспорта в растровые и векторные (EPS или SVG) файлы, интерфейс для OpenGL и возможность запуска в консольном режиме, функции для обработки данных и даже простейший командный (интерпретируемый) язык MGL для упрощения построения графиков. Кроме того, есть несколько типов прозрачности, гладкое освещение, векторные шрифты, TeX-ие команды в надписях, произвольные криволинейные системы координат и прочие полезные мелочи (см. раздел pictures на домашней странице). Ну, и, естественно, полная переносимость библиотеки и ее свободное распространение под лицензией GPL v.2.0 или более поздней.
Библиотека MathGL позволяет строить широкий класс графиков, включая:
Фактически, я постарался реализовать все известные мне типы научных графиков. Список графиков постоянно пополняется, и если Вам нужен какой-то новый вариант, пишите на e-mail, и в новой версии библиотеки этот график появится.
Я постарался сделать графики максимально красивыми – поверхности могут быть прозрачными и освещены произвольно расположенными источниками света (максимальное их количество 10). Большинство функций рисования имеет два варианта: простой для быстрого построения картинки и более сложный для детальной настройки отображения, включающего в том числе возможность параметрического задания всех массивов. Получившееся изображение можно сохранить в растровом формате PNG, JPEG, GIF, TGA или BMP; в векторном EPS, SVG или TeX формате, или в 3D формате OBJ, OFF, STL, или в PRC формате, который может быть конвертирован U3D.
Все надписи выводятся векторным шрифтом, что обеспечивает их хорошую масштабируемость и переносимость. Текст может содержать команды для большинства ТеХ-их символов, изменения положения (верхний и нижний индексы) и стиля шрифта внутри строки текста (see Стиль текста). Текст меток поворачивается вместе с осями. На график можно вывести описание кривых (легенду) и поместить надпись в произвольную точку экрана или пустить ее вдоль кривой. Поддерживаются произвольные кодировки текста (с помощью стандартной функции setlocale()
) и текст в кодировке UTF-16.
Для представления данных используется специальный класс mglData (see Обработка данных). Помимо безопасного создания и удаления массивов, он включает функции по их обработке (дифференцированию, интегрированию, сглаживанию, интерполяции и т.д.) и чтению текстового файла с автоматическим определением размеров данных. Класс mglData позволяет работать с массивами размерности вплоть до 3 (массивы, зависящие от трех независимых индексов a_{ijk}). Использование массивов с большим числом размерностей нецелесообразно, поскольку я не представляю, как их можно отобразить на экране. Заполнение или изменение значений массива можно выполнить как вручную, так и по формуле, заданной текстовой строкой.
Для быстрого вычисления значения выражения, заданного текстовой строкой (see Текстовые формулы). Он основан на компиляции строки в древоподобную структуру при создании экземпляра класса. На этапе вычисления происходит быстрый обход дерева с выдачей результата для конкретных значений переменных. Помимо изменения значений массива данных, текстовые формулы используются для рисования в произвольной криволинейной системе координат. Набор таких координат ограничивается только фантазией пользователя, а не фиксированным числом (типа полярной, параболической, цилиндрической и т.д.).
Установка библиотеки возможна 4-мя способами.
cmake .
дважды, далее make
и, наконец, с правами суперпользователя make install
. Иногда после компиляции библиотеки может потребоваться обновление списка библиотека в системе – выполните команду ldconfig
с правами суперпользователя.
Есть несколько дополнительных опций, которые по умолчанию отключены. К их числу относятся: enable-fltk, enable-glut, enable-qt4, enable-qt5
для поддержки FLTK, GLUT и/или Qt окон; enable-jpeg, enable-gif, enable-hdf5
для поддержки соответствующих форматов; enable-all
для включения всех возможностей. Для использования типа double
для внутреннего хранения данных используйте опцию enable-double
. Для создания интерфейсов к другим языкам (кроме С/Фортран/MGL) используйте опции enable-python, enable-octave
или enable-all-swig
для всех поддерживаемых языков. Вы можете воспользоваться WYSIWYG утилитой (cmake-gui
) для просмотра и изменения всех опций, или выполнить cmake -D enable-all=on -D enable-all-widgets=on -D enable-all-swig=on .
в командной строке для включения всех опций.
При сборке с помощью MinGW необходимо дополнительно установить опцию сборки -fopenmp
(т.е. CMAKE_EXE_LINKER_FLAGS:STRING='-fopenmp'
и CMAKE_SHARED_LINKER_FLAGS:STRING='-fopenmp'
) если включена поддержка OpenMP (enable-openmp=ON
).
Последнюю версию (которая может быть не стабильна) можно загрузить с sourceforge.net SVN с помощью команды
svn checkout http://svn.code.sf.net/p/mathgl/code/mathgl-2x mathgl-code
ВАЖНО! MathGL использует набор defines, определяемых на этапе конфигурирования библиотеки. Это MGL_SYS_NAN, MGL_HAVE_TYPEOF, MGL_HAVE_PTHREAD, MGL_HAVE_ATTRIBUTE, MGL_HAVE_C99_COMPLEX, MGL_HAVE_RVAL
. Они могут отличаться при использовании бинарников скомпилированных другим компилятором (например при использовании скомпилированных MinGW бинарников в VisualStudio). Я специально устанавливаю их в 0
для компиляторов Borland и Microsoft из соображений совместимости. Кроме того, настройки по умолчанию подходят для компиляторов GNU (gcc, mingw) и clang. Однако, для прочих компиляторов может потребоваться ручная установка defines в 0
в файле include/mgl2/config.h
если вы используете предварительно скомпилированные файлы.
There are 3 steps to prepare the plot in MathGL: (1) prepare data to be plotted, (2) setup plot, (3) plot data. Let me show this on the example of surface plotting.
First we need the data. MathGL use its own class mglData
to handle data arrays (see Обработка данных). This class give ability to handle data arrays by more or less format independent way. So, create it
int main() { mglData dat(30,40); // data to for plotting for(long i=0;i<30;i++) for(long j=0;j<40;j++) dat.a[i+30*j] = 1/(1+(i-15)*(i-15)/225.+(j-20)*(j-20)/400.);
Here I create matrix 30*40 and initialize it by formula. Note, that I use long
type for indexes i, j because data arrays can be really large and long
type will automatically provide proper indexing.
Next step is setup of the plot. The only setup I need is axis rotation and lighting.
mglGraph gr; // class for plot drawing gr.Rotate(50,60); // rotate axis gr.Light(true); // enable lighting
Everything is ready. And surface can be plotted.
gr.Surf(dat); // plot surface
Basically plot is done. But I decide to add yellow (‘y’ color, see Цвета) contour lines on the surface. To do it I can just add:
gr.Cont(dat,"y"); // plot yellow contour lines
This demonstrate one of base MathGL concept (see, Основные принципы) – “new drawing never clears things drawn already”. So, you can just consequently call different plotting functions to obtain “combined” plot. For example, if one need to draw axis then he can just call one more plotting function
gr.Axis(); // draw axis
Now picture is ready and we can save it in a file.
gr.WriteFrame("sample.png"); // save it }
To compile your program, you need to specify the linker option -lmgl
.
This is enough for a compilation of console program or with external (non-MathGL) window library. If you want to use FLTK or Qt windows provided by MathGL then you need to add the option -lmgl-wnd
.
При использовании фортрана необходимо также включить библиотеку -lstdc++
. Кроме того, если библиотека была собрана с опцией enable-double=ON
(по умолчанию в версии 2.1 и более поздних), то все вещественные числа должны быть типа real*8. Это можно включить по умолчанию опцией -fdefault-real-8
.
There are a lot of changes for v.2. Here I denote only main of them.
mglconv, mglview
).
MathGL library provides several tools for parsing MGL scripts. There is tools saving it to bitmap or vectorial images (mglconv
). Tool mglview
show MGL script and allow one to rotate and setup the image. Another feature of mglview
is loading *.mgld files (see ExportMGLD()
) for quick viewing 3d pictures.
Both tools have similar set of arguments. They can be name of script file or options. You can use ‘-’ as script name for using standard input (i.e. pipes). Options are:
Additionally mglconv
have following options:
Also you can create animated GIF file or a set of JPEG files with names ‘frameNNNN.jpg’ (here ‘NNNN’ is frame index). Values of the parameter $0
for making animation can be specified inside the script by comment ##a val
for each value val
(one comment for one value) or by option(s) ‘-A val’. Also you can specify a cycle for animation by comment ##c v1 v2 dv
or by option -C v1:v2:dv
. In the case of found/specified animation parameters, tool will execute script several times – once for each value of $0
.
MathGL also provide another simple tool mgl.cgi
which parse MGL script from CGI request and send back produced PNG file. Usually this program should be placed in /usr/lib/cgi-bin/
. But you need to put this program by yourself due to possible security issues and difference of Apache server settings.
Javascript интерфейс был разработан при поддержке компании DATADVANCE.
В данной главе рассмотрены базовые и продвинутые возможности MathGL, даны советы по использованию и примеры для всех типов графиков. Я рекомендую прочитать вначале первые 2 раздела и посмотреть на раздел Hints. Также рекомендую прочитать Основные принципы и FAQ.
Отмечу, что MathGL v.2.* имеет только пользовательских 2 интерфейса: один для языков подобных C или Fortran (не поддерживающих классы), другой для языков подобных C++/Python/Octave, которые поддерживают классы. При этом все классы являются "оберткой" С-ого интерфейсы, а функции-члены классов – inline вызовами функций С. Поэтому, в большинстве примеров в этой главе я буду приводить только один вариант кода, который после минимальных изменений синтаксиса может быть применен для других языков. Например, код на языке C++
#include <mgl2/mgl.h> int main() { mglGraph gr; gr.FPlot("sin(pi*x)"); gr.WriteFrame("test.png"); }
на Python будет выглядеть как
from mathgl import * gr = mglGraph(); gr.FPlot("sin(pi*x)"); gr.WriteFrame("test.png");
в Octave он будет почти тем же (в новых версиях надо предварительно выполнить mathgl;
)
gr = mglGraph(); gr.FPlot("sin(pi*x)"); gr.WriteFrame("test.png");
в C необходимо будет найти С-ые аналоги функций (из документации) и указать все их аргументы явно
#include <mgl2/mgl_cf.h> int main() { HMGL gr = mgl_create_graph(600,400); mgl_fplot(gr,"sin(pi*x)","",""); mgl_write_frame(gr,"test.png",""); mgl_delete_graph(gr); }
в Fortran помимо этого придется определить функции возвращающие указатели на объекты как функции возвращающие целое
integer gr, mgl_create_graph gr = mgl_create_graph(600,400); call mgl_fplot(gr,'sin(pi*x)','',''); call mgl_write_frame(gr,'test.png',''); call mgl_delete_graph(gr);
и т.д.
Библиотеку MathGL можно использовать несколькими способами, каждый из которых имеет свои достоинства и недостатки:
Положительная сторона состоит в возможности сразу увидеть график и быстро его мышкой поправить (повернуть, приблизить, выключить прозрачность или освещение и т.д.). Однако, в этом случае требуется наличие графической системы (нельзя запускать на удаленной машине), и работать можно только с одним набором данных одновременно.
Достоинства такого подхода: пакетная обработка похожих данных (например, набора расчетных файлов при различных условиях), возможность запуска из консольной программы (включая запуск на удаленном компьютере/сервере/кластере), более быстрая и автоматизированная отрисовка, сохранение графиков для последующего анализа непосредственно во время расчета. К недостаткам подхода можно отнести: использование внешней программы просмотра для построенных графиков, необходимость заранее представить картинку (углы просмотра, освещение и пр.). Я рекомендую вначале использовать графическое окно для выбора оптимальных параметров графика, а потом использовать их для пакетной обработки.
В этом случае программист имеет максимум свободы в выборе графической библиотеки (не только FLTK, Qt или GLUT), в расположении и выборе элементов управления графиком и т.д. Я рекомендую этот вариант для "самодостаточного" приложения.
Вы также можете использовать ряд элементов управления (виджетов), которые позволяют отобразить график, сохранить его в файл в различных форматах или скопировать в буфер обмена, обработать движение/клики мышкой и пр.
Графики MathGL могут быть созданы не только с помощью объектно-ориентированных языков (например, C++ или Python), но и на C или Fortran подобных языках. Использование последних в основном идентичны использованию классов (за исключением различных имен функций). Различие состоит в обязательном предварительном создании (и удалении после использования) объектов типа HMGL (для графики) и/или HMDT (для данных). Пользователи Fortran могут считать эти переменные целочисленными с достаточной разрядностью для используемой операционной системы.
Рассмотрим вышесказанное подробно.
“Интерактивный” способ использования MathGL состоит в создании окна с помощью классов mglQT
, mglFLTK
или mglGLUT
(см. “Оконные” классы) и последующем рисовании в этом окне. Соответствующий код выглядит так:
#include <mgl2/qt.h> int sample(mglGraph *gr) { gr->Rotate(60,40); gr->Box(); return 0; } //----------------------------------------------------- int main(int argc,char **argv) { mglQT gr(sample,"MathGL examples"); return gr.Run(); }
Здесь используется callback функция sample
, выполняющая собственно рисование. Функция main
– точка входа в программу – создает окно (объект gr типа mglQT
) и запускает цикл обработки сообщений (вызов gr.Run()
). Для компиляции достаточно выполнить команду
gcc test.cpp -lmgl-qt5 -lmgl
Вы можете использовать "-lmgl-qt4" вместо "-lmgl-qt5", если установлен Qt4.
Альтернативный способ состоит в использовании класса, производного от mglDraw
с переопределенной функцией Draw()
:
#include <mgl2/qt.h> class Foo : public mglDraw { public: int Draw(mglGraph *gr); }; //----------------------------------------------------- int Foo::Draw(mglGraph *gr) { gr->Rotate(60,40); gr->Box(); return 0; } //----------------------------------------------------- int main(int argc,char **argv) { Foo foo; mglQT gr(&foo,"MathGL examples"); return gr.Run(); }
Или в использовании функций С:
#include <mgl2/mgl_cf.h> int sample(HMGL gr, void *) { mgl_rotate(gr,60,40,0); mgl_box(gr); } int main(int argc,char **argv) { HMGL gr; gr = mgl_create_graph_qt(sample,"MathGL examples",0,0); return mgl_qt_run(); /* generally I should call mgl_delete_graph() here, * but I omit it in main() function. */ }
Похожий код получается и при использовании окон mglFLTK
, mglGLUT
(функция sample()
та же):
#include <mgl2/glut.h> int main(int argc,char **argv) { mglGLUT gr(sample,"MathGL examples"); return 0; }
The rotation, shift, zooming, switching on/off transparency and lighting can be done with help of tool-buttons (for mglWindow
) or by hot-keys: ‘a’, ‘d’, ‘w’, ‘s’ for plot rotation, ‘r’ and ‘f’ switching on/off transparency and lighting. Press ‘x’ for exit (or closing the window).
In this example function sample
rotates axes (Rotate()
, see Матрица преобразования) and draws the bounding box (Box()
). Drawing is placed in separate function since it will be used on demand when window canvas needs to be redrawn.
Another way of using MathGL library is the direct writing of the picture to the file. It is most usable for plot creation during long calculation or for using of small programs (like Matlab or Scilab scripts) for visualizing repetitive sets of data. But the speed of drawing is much higher in comparison with a script language.
The following code produces a bitmap PNG picture:
#include <mgl2/mgl.h> int main(int ,char **) { mglGraph gr; gr.Alpha(true); gr.Light(true); sample(&gr); // The same drawing function. gr.WritePNG("test.png"); // Don't forget to save the result! return 0; }
For compilation, you need only libmgl library not the one with widgets
gcc test.cpp -lmgl
This can be important if you create a console program in computer/cluster where X-server (and widgets) is inaccessible.
The only difference from the previous variant (using windows) is manual switching on the transparency Alpha
and lightning Light
, if you need it. The usage of frames (see Animation) is not advisable since the whole image is prepared each time. If function sample
contains frames then only last one will be saved to the file. In principle, one does not need to separate drawing functions in case of direct file writing in consequence of the single calling of this function for each picture. However, one may use the same drawing procedure to create a plot with changeable parameters, to export in different file types, to emphasize the drawing code and so on. So, in future I will put the drawing in the separate function.
The code for export into other formats (for example, into vector EPS file) looks the same:
#include <mgl2/mgl.h> int main(int ,char **) { mglGraph gr; gr.Light(true); sample(&gr); // The same drawing function. gr.WriteEPS("test.eps"); // Don't forget to save the result! return 0; }
The difference from the previous one is using other function WriteEPS()
for EPS format instead of function WritePNG()
. Also, there is no switching on of the plot transparency Alpha
since EPS format does not support it.
Widget classes (mglWindow
, mglGLUT
) support a delayed drawing, when all plotting functions are called once at the beginning of writing to memory lists. Further program displays the saved lists faster. Resulting redrawing will be faster but it requires sufficient memory. Several lists (frames) can be displayed one after another (by pressing ‘,’, ‘.’) or run as cinema. To switch these feature on one needs to modify function sample
:
int sample(mglGraph *gr) { gr->NewFrame(); // the first frame gr->Rotate(60,40); gr->Box(); gr->EndFrame(); // end of the first frame gr->NewFrame(); // the second frame gr->Box(); gr->Axis("xy"); gr->EndFrame(); // end of the second frame return gr->GetNumFrame(); // returns the frame number }
First, the function creates a frame by calling NewFrame()
for rotated axes and draws the bounding box. The function EndFrame()
must be called after the frame drawing! The second frame contains the bounding box and axes Axis("xy")
in the initial (unrotated) coordinates. Function sample
returns the number of created frames GetNumFrame()
.
Note, that animation can be also done as visualization of running calculations (see Draw and calculate).
Pictures with animation can be saved in file(s) as well. You can: export in animated GIF, or save each frame in separate file (usually JPEG) and convert these files into the movie (for example, by help of ImageMagic). Let me show both methods.
The simplest methods is making animated GIF. There are 3 steps: (1) open GIF file by StartGIF()
function; (2) create the frames by calling NewFrame()
before and EndFrame()
after plotting; (3) close GIF by CloseGIF()
function. So the simplest code for “running” sinusoid will look like this:
#include <mgl2/mgl.h> int main(int ,char **) { mglGraph gr; mglData dat(100); char str[32]; gr.StartGIF("sample.gif"); for(int i=0;i<40;i++) { gr.NewFrame(); // start frame gr.Box(); // some plotting for(int j=0;j<dat.nx;j++) dat.a[j]=sin(M_PI*j/dat.nx+M_PI*0.05*i); gr.Plot(dat,"b"); gr.EndFrame(); // end frame } gr.CloseGIF(); return 0; }
The second way is saving each frame in separate file (usually JPEG) and later make the movie from them. MathGL have special function for saving frames – it is WriteFrame()
. This function save each frame with automatic name ‘frame0001.jpg, frame0002.jpg’ and so on. Here prefix ‘frame’ is defined by PlotId variable of mglGraph
class. So the similar code will look like this:
#include <mgl2/mgl.h> int main(int ,char **) { mglGraph gr; mglData dat(100); char str[32]; for(int i=0;i<40;i++) { gr.NewFrame(); // start frame gr.Box(); // some plotting for(int j=0;j<dat.nx;j++) dat.a[j]=sin(M_PI*j/dat.nx+M_PI*0.05*i); gr.Plot(dat,"b"); gr.EndFrame(); // end frame gr.WriteFrame(); // save frame } return 0; }
Created files can be converted to movie by help of a lot of programs. For example, you can use ImageMagic (command ‘convert frame*.jpg movie.mpg’), MPEG library, GIMP and so on.
Finally, you can use mglconv
tool for doing the same with MGL scripts (see Utilities for parsing MGL).
The last way of MathGL using is the drawing in memory. Class mglGraph
allows one to create a bitmap picture in memory. Further this picture can be displayed in window by some window libraries (like wxWidgets, FLTK, Windows GDI and so on). For example, the code for drawing in wxWidget library looks like:
void MyForm::OnPaint(wxPaintEvent& event) { int w,h,x,y; GetClientSize(&w,&h); // size of the picture mglGraph gr(w,h); gr.Alpha(true); // draws something using MathGL gr.Light(true); sample(&gr,NULL); wxImage img(w,h,gr.GetRGB(),true); ToolBar->GetSize(&x,&y); // gets a height of the toolbar if any wxPaintDC dc(this); // and draws it dc.DrawBitmap(wxBitmap(img),0,y); }
The drawing in other libraries is most the same.
For example, FLTK code will look like
void Fl_MyWidget::draw() { mglGraph gr(w(),h()); gr.Alpha(true); // draws something using MathGL gr.Light(true); sample(&gr,NULL); fl_draw_image(gr.GetRGB(), x(), y(), gr.GetWidth(), gr.GetHeight(), 3); }
Qt code will look like
void MyWidget::paintEvent(QPaintEvent *) { mglGraph gr(w(),h()); gr.Alpha(true); // draws something using MathGL gr.Light(true); gr.Light(0,mglPoint(1,0,-1)); sample(&gr,NULL); // Qt don't support RGB format as is. So, let convert it to BGRN. long w=gr.GetWidth(), h=gr.GetHeight(); unsigned char *buf = new uchar[4*w*h]; gr.GetBGRN(buf, 4*w*h) QPixmap pic = QPixmap::fromImage(QImage(*buf, w, h, QImage::Format_RGB32)); QPainter paint; paint.begin(this); paint.drawPixmap(0,0,pic); paint.end(); delete []buf; }
MathGL can be used to draw plots in parallel with some external calculations. The simplest way for this is the usage of mglDraw class. At this you should enable pthread for widgets by setting enable-pthr-widget=ON
at configure stage (it is set by default).
First, you need to inherit you class from mglDraw
class, define virtual members Draw()
and Calc()
which will draw the plot and proceed calculations. You may want to add the pointer mglWnd *wnd;
to window with plot for interacting with them. Finally, you may add any other data or member functions. The sample class is shown below
class myDraw : public mglDraw { mglPoint pnt; // some variable for changeable data long i; // another variable to be shown mglWnd *wnd; // external window for plotting public: myDraw(mglWnd *w=0) : mglDraw() { wnd=w; } void SetWnd(mglWnd *w) { wnd=w; } int Draw(mglGraph *gr) { gr->Line(mglPoint(),pnt,"Ar2"); char str[16]; snprintf(str,15,"i=%ld",i); gr->Puts(mglPoint(),str); return 0; } void Calc() { for(i=0;;i++) // do calculation { long_calculations();// which can be very long Check(); // check if need pause pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1); if(wnd) wnd->Update(); } } } dr;
There is only one issue here. Sometimes you may want to pause calculations to view result carefully, or save state, or change something. So, you need to provide a mechanism for pausing. Class mglDraw
provide function Check();
which check if toolbutton with pause is pressed and wait until it will be released. This function should be called in a "safety" places, where you can pause the calculation (for example, at the end of time step). Also you may add call exit(0);
at the end of Calc();
function for closing window and exit after finishing calculations.
Finally, you need to create a window itself and run calculations.
int main(int argc,char **argv) { mglFLTK gr(&dr,"Multi-threading test"); // create window dr.SetWnd(&gr); // pass window pointer to yours class dr.Run(); // run calculations gr.Run(); // run event loop for window return 0; }
Note, that you can reach the similar functionality without using mglDraw
class (i.e. even for pure C code).
mglFLTK *gr=NULL; // pointer to window void *calc(void *) // function with calculations { mglPoint pnt; // some data for plot for(long i=0;;i++) // do calculation { long_calculations(); // which can be very long pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1); if(gr) { gr->Clf(); // make new drawing // draw something gr->Line(mglPoint(),pnt,"Ar2"); char str[16]; snprintf(str,15,"i=%ld",i); gr->Puts(mglPoint(),str); // don't forgot to update window gr->Update(); } } } int main(int argc,char **argv) { static pthread_t thr; pthread_create(&thr,0,calc,0); // create separate thread for calculations pthread_detach(thr); // and detach it gr = new mglFLTK; // now create window gr->Run(); // and run event loop return 0; }
This sample is exactly the same as one with mglDraw
class, but it don’t have functionality for pausing calculations. If you need it then you have to create global mutex (like pthread_mutex_t *mutex = pthread_mutex_init(&mutex,NULL);
), set it to window (like gr->SetMutex(mutex);
) and periodically check it at calculations (like pthread_mutex_lock(&mutex); pthread_mutex_unlock(&mutex);
).
Finally, you can put the event-handling loop in separate instead of yours code by using RunThr()
function instead of Run()
one. Unfortunately, such method work well only for FLTK windows and only if pthread support was enabled. Such limitation come from the Qt requirement to be run in the primary thread only. The sample code will be:
int main(int argc,char **argv) { mglFLTK gr("test"); gr.RunThr(); // <-- need MathGL version which use pthread for widgets mglPoint pnt; // some data for(int i=0;i<10;i++) // do calculation { long_calculations();// which can be very long pnt.Set(2*mgl_rnd()-1,2*mgl_rnd()-1); gr.Clf(); // make new drawing gr.Line(mglPoint(),pnt,"Ar2"); char str[10] = "i=0"; str[3] = '0'+i; gr->Puts(mglPoint(),str); gr.Update(); // update window } return 0; // finish calculations and close the window }
MathGL have several interface widgets for different widget libraries. There are QMathGL for Qt, Fl_MathGL for FLTK. These classes provide control which display MathGL graphics. Unfortunately there is no uniform interface for widget classes because all libraries have slightly different set of functions, features and so on. However the usage of MathGL widgets is rather simple. Let me show it on the example of QMathGL.
First of all you have to define the drawing function or inherit a class from mglDraw
class. After it just create a window and setup QMathGL instance as any other Qt widget:
#include <QApplication> #include <QMainWindow> #include <QScrollArea> #include <mgl2/qmathgl.h> int main(int argc,char **argv) { QApplication a(argc,argv); QMainWindow *Wnd = new QMainWindow; Wnd->resize(810,610); // for fill up the QMGL, menu and toolbars Wnd->setWindowTitle("QMathGL sample"); // here I allow one to scroll QMathGL -- the case // then user want to prepare huge picture QScrollArea *scroll = new QScrollArea(Wnd); // Create and setup QMathGL QMathGL *QMGL = new QMathGL(Wnd); //QMGL->setPopup(popup); // if you want to setup popup menu for QMGL QMGL->setDraw(sample); // or use QMGL->setDraw(foo); for instance of class Foo:public mglDraw QMGL->update(); // continue other setup (menu, toolbar and so on) scroll->setWidget(QMGL); Wnd->setCentralWidget(scroll); Wnd->show(); return a.exec(); }
MathGL have possibility to draw resulting plot using OpenGL. This produce resulting plot a bit faster, but with some limitations (especially at use of transparency and lighting). Generally, you need to prepare OpenGL window and call MathGL functions to draw it. There is GLUT interface (see “Оконные” классы) to do it by simple way. Below I show example of OpenGL usage basing on Qt libraries (i.e. by using QGLWidget
widget).
First, one need to define widget class derived from QGLWidget
and implement a few methods: resizeGL()
called after each window resize, paintGL()
for displaying the image on the screen, and initializeGL()
for initializing OpenGL. The header file looks as following.
#ifndef MAINWINDOW_H #define MAINWINDOW_H #include <QGLWidget> #include <mgl2/mgl.h> class MainWindow : public QGLWidget { Q_OBJECT protected: mglGraph *gr; // pointer to MathGL core class void resizeGL(int nWidth, int nHeight); // Method called after each window resize void paintGL(); // Method to display the image on the screen void initializeGL(); // Method to initialize OpenGL public: MainWindow(QWidget *parent = 0); ~MainWindow(); }; #endif // MAINWINDOW_H
The class implementation is rather straightforward. One need to recreate the instance of mglGraph at initializing OpenGL, and ask MathGL to use OpenGL output (set argument 1
in mglGraph constructor). Of course, the mglGraph object should be deleted at destruction. The method resizeGL()
just pass new sizes to OpenGL and update viewport sizes. All plotting functions are located in the method paintGL()
. At this, one need to add 2 calls: gr->Clf()
at beginning for clearing previous OpenGL primitives; and swapBuffers()
for showing output on the screen. The source file looks as following.
#include "qgl_example.h" #include <QApplication> //#include <QtOpenGL> //----------------------------------------------------------------------------- MainWindow::MainWindow(QWidget *parent) : QGLWidget(parent) { gr=0; } //----------------------------------------------------------------------------- MainWindow::~MainWindow() { if(gr) delete gr; } //----------------------------------------------------------------------------- void MainWindow::initializeGL() // recreate instance of MathGL core { if(gr) delete gr; gr = new mglGraph(1); // use '1' for argument to force OpenGL output in MathGL } //----------------------------------------------------------------------------- void MainWindow::resizeGL(int w, int h) // standard resize replace { QGLWidget::resizeGL(w, h); glViewport (0, 0, w, h); } //----------------------------------------------------------------------------- void MainWindow::paintGL() // main drawing function { gr->Clf(); // clear previous OpenGL primitives gr->SubPlot(1,1,0); gr->Rotate(40,60); gr->Light(true); gr->AddLight(0,mglPoint(0,0,10),mglPoint(0,0,-1)); gr->Axis(); gr->Box(); gr->FPlot("sin(pi*x)","i2"); gr->FPlot("cos(pi*x)","|"); gr->FSurf("cos(2*pi*(x^2+y^2))"); gr->Finish(); swapBuffers(); // show output on the screen } //----------------------------------------------------------------------------- int main(int argc, char *argv[]) // create application { mgl_textdomain(argv?argv[0]:NULL,""); QApplication a(argc, argv); MainWindow w; w.show(); return a.exec(); } //-----------------------------------------------------------------------------
Generally SWIG based classes (including the Python one) are the same as C++ classes. However, there are few tips for using MathGL with PyQt. Below I place a very simple python code which demonstrate how MathGL can be used with PyQt. This code is mostly written by Prof. Dr. Heino Falcke. You can just copy it to a file mgl-pyqt-test.py
and execute it from python shell by command execfile("mgl-pyqt-test.py")
from PyQt4 import QtGui,QtCore from mathgl import * import sys app = QtGui.QApplication(sys.argv) qpointf=QtCore.QPointF() class hfQtPlot(QtGui.QWidget): def __init__(self, parent=None): QtGui.QWidget.__init__(self, parent) self.img=(QtGui.QImage()) def setgraph(self,gr): self.buffer='\t' self.buffer=self.buffer.expandtabs(4*gr.GetWidth()*gr.GetHeight()) gr.GetBGRN(self.buffer,len(self.buffer)) self.img=QtGui.QImage(self.buffer, gr.GetWidth(),gr.GetHeight(),QtGui.QImage.Format_ARGB32) self.update() def paintEvent(self, event): paint = QtGui.QPainter() paint.begin(self) paint.drawImage(qpointf,self.img) paint.end() BackgroundColor=[1.0,1.0,1.0] size=100 gr=mglGraph() y=mglData(size) #y.Modify("((0.7*cos(2*pi*(x+.2)*500)+0.3)*(rnd*0.5+0.5)+362.135+10000.)") y.Modify("(cos(2*pi*x*10)+1.1)*1000.*rnd-501") x=mglData(size) x.Modify("x^2"); def plotpanel(gr,x,y,n): gr.SubPlot(2,2,n) gr.SetXRange(x) gr.SetYRange(y) gr.AdjustTicks() gr.Axis() gr.Box() gr.Label("x","x-Axis",1) gr.Label("y","y-Axis",1) gr.ClearLegend() gr.AddLegend("Legend: "+str(n),"k") gr.Legend() gr.Plot(x,y) gr.Clf(BackgroundColor[0],BackgroundColor[1],BackgroundColor[2]) gr.SetPlotFactor(1.5) plotpanel(gr,x,y,0) y.Modify("(cos(2*pi*x*10)+1.1)*1000.*rnd-501") plotpanel(gr,x,y,1) y.Modify("(cos(2*pi*x*10)+1.1)*1000.*rnd-501") plotpanel(gr,x,y,2) y.Modify("(cos(2*pi*x*10)+1.1)*1000.*rnd-501") plotpanel(gr,x,y,3) gr.WritePNG("test.png","Test Plot") qw = hfQtPlot() qw.show() qw.setgraph(gr) qw.raise_()
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.
Now I show several non-obvious features of MathGL: several subplots in a single picture, curvilinear coordinates, text printing and so on. Generally you may miss this section at first reading.
Let me demonstrate possibilities of plot positioning and rotation. MathGL has a set of functions: subplot, inplot, title, aspect and rotate and so on (see Матрица преобразования). The order of their calling is strictly determined. First, one changes the position of plot in image area (functions subplot, inplot and multiplot). Secondly, you can add the title of plot by title function. After that one may rotate the plot (function rotate). Finally, one may change aspects of axes (function aspect). The following code illustrates the aforesaid it:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0); gr->Box(); gr->Puts(mglPoint(-1,1.1),"Just box",":L"); gr->InPlot(0.2,0.5,0.7,1,false); gr->Box(); gr->Puts(mglPoint(0,1.2),"InPlot example"); gr->SubPlot(2,2,1); gr->Title("Rotate only"); gr->Rotate(50,60); gr->Box(); gr->SubPlot(2,2,2); gr->Title("Rotate and Aspect"); gr->Rotate(50,60); gr->Aspect(1,1,2); gr->Box(); gr->SubPlot(2,2,3); gr->Title("Shear"); gr->Box("c"); gr->Shear(0.2,0.1); gr->Box(); return 0; }
Here I used function Puts
for printing the text in arbitrary position of picture (see Вывод текста). Text coordinates and size are connected with axes. However, text coordinates may be everywhere, including the outside the bounding box. I’ll show its features later in Text features.
More complicated sample show how to use most of positioning functions:
int sample(mglGraph *gr) { gr->SubPlot(3,2,0); gr->Title("StickPlot"); gr->StickPlot(3, 0, 20, 30); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->StickPlot(3, 1, 20, 30); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->StickPlot(3, 2, 20, 30); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); gr->SubPlot(3,2,3,""); gr->Title("ColumnPlot"); gr->ColumnPlot(3, 0); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->ColumnPlot(3, 1); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->ColumnPlot(3, 2); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); gr->SubPlot(3,2,4,""); gr->Title("GridPlot"); gr->GridPlot(2, 2, 0); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->GridPlot(2, 2, 1); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->GridPlot(2, 2, 2); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); gr->GridPlot(2, 2, 3); gr->Box("m"); gr->Puts(mglPoint(0),"3","m"); gr->SubPlot(3,2,5,""); gr->Title("InPlot"); gr->Box(); gr->InPlot(0.4, 1, 0.6, 1, true); gr->Box("r"); gr->MultiPlot(3,2,1, 2, 1,""); gr->Title("MultiPlot and ShearPlot"); gr->Box(); gr->ShearPlot(3, 0, 0.2, 0.1); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->ShearPlot(3, 1, 0.2, 0.1); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->ShearPlot(3, 2, 0.2, 0.1); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); return 0; }
MathGL library can draw not only the bounding box but also the axes, grids, labels and so on. The ranges of axes and their origin (the point of intersection) are determined by functions SetRange()
, SetRanges()
, SetOrigin()
(see Масштаб осей координат). Ticks on axis are specified by function SetTicks
, SetTicksVal
, SetTicksTime
(see Метки осей). But usually
Function axis draws axes. Its textual string shows in which directions the axis or axes will be drawn (by default "xyz"
, function draws axes in all directions). Function grid draws grid perpendicularly to specified directions. Example of axes and grid drawing is:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0); gr->Title("Axis origin, Grid"); gr->SetOrigin(0,0); gr->Axis(); gr->Grid(); gr->FPlot("x^3"); gr->SubPlot(2,2,1); gr->Title("2 axis"); gr->SetRanges(-1,1,-1,1); gr->SetOrigin(-1,-1,-1); // first axis gr->Axis(); gr->Label('y',"axis 1",0); gr->FPlot("sin(pi*x)"); gr->SetRanges(0,1,0,1); gr->SetOrigin(1,1,1); // second axis gr->Axis(); gr->Label('y',"axis 2",0); gr->FPlot("cos(pi*x)"); gr->SubPlot(2,2,3); gr->Title("More axis"); gr->SetOrigin(NAN,NAN); gr->SetRange('x',-1,1); gr->Axis(); gr->Label('x',"x",0); gr->Label('y',"y_1",0); gr->FPlot("x^2","k"); gr->SetRanges(-1,1,-1,1); gr->SetOrigin(-1.3,-1); // second axis gr->Axis("y","r"); gr->Label('y',"#r{y_2}",0.2); gr->FPlot("x^3","r"); gr->SubPlot(2,2,2); gr->Title("4 segments, inverted axis"); gr->SetOrigin(0,0); gr->InPlot(0.5,1,0.5,1); gr->SetRanges(0,10,0,2); gr->Axis(); gr->FPlot("sqrt(x/2)"); gr->Label('x',"W",1); gr->Label('y',"U",1); gr->InPlot(0,0.5,0.5,1); gr->SetRanges(1,0,0,2); gr->Axis("x"); gr->FPlot("sqrt(x)+x^3"); gr->Label('x',"\\tau",-1); gr->InPlot(0.5,1,0,0.5); gr->SetRanges(0,10,4,0); gr->Axis("y"); gr->FPlot("x/4"); gr->Label('y',"L",-1); gr->InPlot(0,0.5,0,0.5); gr->SetRanges(1,0,4,0); gr->FPlot("4*x^2"); return 0; }
Note, that MathGL can draw not only single axis (which is default). But also several axis on the plot (see right plots). The idea is that the change of settings does not influence on the already drawn graphics. So, for 2-axes I setup the first axis and draw everything concerning it. Then I setup the second axis and draw things for the second axis. Generally, the similar idea allows one to draw rather complicated plot of 4 axis with different ranges (see bottom left plot).
At this inverted axis can be created by 2 methods. First one is used in this sample – just specify minimal axis value to be large than maximal one. This method work well for 2D axis, but can wrongly place labels in 3D case. Second method is more general and work in 3D case too – just use aspect function with negative arguments. For example, following code will produce exactly the same result for 2D case, but 2nd variant will look better in 3D.
// variant 1 gr->SetRanges(0,10,4,0); gr->Axis(); // variant 2 gr->SetRanges(0,10,0,4); gr->Aspect(1,-1); gr->Axis();
Another MathGL feature is fine ticks tunning. By default (if it is not changed by SetTicks
function), MathGL try to adjust ticks positioning, so that they looks most human readable. At this, MathGL try to extract common factor for too large or too small axis ranges, as well as for too narrow ranges. Last one is non-common notation and can be disabled by SetTuneTicks
function.
Also, one can specify its own ticks with arbitrary labels by help of SetTicksVal
function. Or one can set ticks in time format. In last case MathGL will try to select optimal format for labels with automatic switching between years, months/days, hours/minutes/seconds or microseconds. However, you can specify its own time representation using formats described in http://www.manpagez.com/man/3/strftime/. Most common variants are ‘%X’ for national representation of time, ‘%x’ for national representation of date, ‘%Y’ for year with century.
The sample code, demonstrated ticks feature is
int sample(mglGraph *gr) { gr->SubPlot(3,2,0); gr->Title("Usual axis"); gr->Axis(); gr->SubPlot(3,2,1); gr->Title("Too big/small range"); gr->SetRanges(-1000,1000,0,0.001); gr->Axis(); gr->SubPlot(3,2,3); gr->Title("Too narrow range"); gr->SetRanges(100,100.1,10,10.01); gr->Axis(); gr->SubPlot(3,2,4); gr->Title("Disable ticks tuning"); gr->SetTuneTicks(0); gr->Axis(); gr->SubPlot(3,2,2); gr->Title("Manual ticks"); gr->SetRanges(-M_PI,M_PI, 0, 2); mreal val[]={-M_PI, -M_PI/2, 0, 0.886, M_PI/2, M_PI}; gr->SetTicksVal('x', mglData(6,val), "-\\pi\n-\\pi/2\n0\nx^*\n\\pi/2\n\\pi"); gr->Axis(); gr->Grid(); gr->FPlot("2*cos(x^2)^2", "r2"); gr->SubPlot(3,2,5); gr->Title("Time ticks"); gr->SetRange('x',0,3e5); gr->SetTicksTime('x',0); gr->Axis(); return 0; }
The last sample I want to show in this subsection is Log-axis. From MathGL’s point of view, the log-axis is particular case of general curvilinear coordinates. So, we need first define new coordinates (see also Curvilinear coordinates) by help of SetFunc
or SetCoor
functions. At this one should wary about proper axis range. So the code looks as following:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0,"<_"); gr->Title("Semi-log axis"); gr->SetRanges(0.01,100,-1,1); gr->SetFunc("lg(x)",""); gr->Axis(); gr->Grid("xy","g"); gr->FPlot("sin(1/x)"); gr->Label('x',"x",0); gr->Label('y', "y = sin 1/x",0); gr->SubPlot(2,2,1,"<_"); gr->Title("Log-log axis"); gr->SetRanges(0.01,100,0.1,100); gr->SetFunc("lg(x)","lg(y)"); gr->Axis(); gr->Grid("!","h="); gr->Grid(); gr->FPlot("sqrt(1+x^2)"); gr->Label('x',"x",0); gr->Label('y', "y = \\sqrt{1+x^2}",0); gr->SubPlot(2,2,2,"<_"); gr->Title("Minus-log axis"); gr->SetRanges(-100,-0.01,-100,-0.1); gr->SetFunc("-lg(-x)","-lg(-y)"); gr->Axis(); gr->FPlot("-sqrt(1+x^2)"); gr->Label('x',"x",0); gr->Label('y', "y = -\\sqrt{1+x^2}",0); gr->SubPlot(2,2,3,"<_"); gr->Title("Log-ticks"); gr->SetRanges(0.1,100,0,100); gr->SetFunc("sqrt(x)",""); gr->Axis(); gr->FPlot("x"); gr->Label('x',"x",1); gr->Label('y', "y = x",0); return 0; }
You can see that MathGL automatically switch to log-ticks as we define log-axis formula (in difference from v.1.*). Moreover, it switch to log-ticks for any formula if axis range will be large enough (see right bottom plot). Another interesting feature is that you not necessary define usual log-axis (i.e. when coordinates are positive), but you can define “minus-log” axis when coordinate is negative (see left bottom plot).
As I noted in previous subsection, MathGL support curvilinear coordinates. In difference from other plotting programs and libraries, MathGL uses textual formulas for connection of the old (data) and new (output) coordinates. This allows one to plot in arbitrary coordinates. The following code plots the line y=0, z=0 in Cartesian, polar, parabolic and spiral coordinates:
int sample(mglGraph *gr) { gr->SetOrigin(-1,1,-1); gr->SubPlot(2,2,0); gr->Title("Cartesian"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc("y*sin(pi*x)","y*cos(pi*x)",0); gr->SubPlot(2,2,1); gr->Title("Cylindrical"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc("2*y*x","y*y - x*x",0); gr->SubPlot(2,2,2); gr->Title("Parabolic"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc("y*sin(pi*x)","y*cos(pi*x)","x+z"); gr->SubPlot(2,2,3); gr->Title("Spiral"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc(0,0,0); // set to default Cartesian return 0; }
MathGL handle colorbar as special kind of axis. So, most of functions for axis and ticks setup will work for colorbar too. Colorbars can be in log-scale, and generally as arbitrary function scale; common factor of colorbar labels can be separated; and so on.
But of course, there are differences – colorbars usually located out of bounding box. At this, colorbars can be at subplot boundaries (by default), or at bounding box (if symbol ‘I’ is specified). Colorbars can handle sharp colors. And they can be located at arbitrary position too. The sample code, which demonstrate colorbar features is:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0); gr->Title("Colorbar out of box"); gr->Box(); gr->Colorbar("<"); gr->Colorbar(">"); gr->Colorbar("_"); gr->Colorbar("^"); gr->SubPlot(2,2,1); gr->Title("Colorbar near box"); gr->Box(); gr->Colorbar("<I"); gr->Colorbar(">I"); gr->Colorbar("_I"); gr->Colorbar("^I"); gr->SubPlot(2,2,2); gr->Title("manual colors"); mglData a,v; mgls_prepare2d(&a,0,&v); gr->Box(); gr->ContD(v,a); gr->Colorbar(v,"<"); gr->Colorbar(v,">"); gr->Colorbar(v,"_"); gr->Colorbar(v,"^"); gr->SubPlot(2,2,3); gr->Title(" "); gr->Puts(mglPoint(-0.5,1.55),"Color positions",":C",-2); gr->Colorbar("bwr>",0.25,0); gr->Puts(mglPoint(-0.9,1.2),"Default"); gr->Colorbar("b{w,0.3}r>",0.5,0); gr->Puts(mglPoint(-0.1,1.2),"Manual"); gr->Puts(mglPoint(1,1.55),"log-scale",":C",-2); gr->SetRange('c',0.01,1e3); gr->Colorbar(">",0.75,0); gr->Puts(mglPoint(0.65,1.2),"Normal scale"); gr->SetFunc("","","","lg(c)"); gr->Colorbar(">"); gr->Puts(mglPoint(1.35,1.2),"Log scale"); return 0; }
Box around the plot is rather useful thing because it allows one to: see the plot boundaries, and better estimate points position since box contain another set of ticks. MathGL provide special function for drawing such box – box function. By default, it draw black or white box with ticks (color depend on transparency type, see Types of transparency). However, you can change the color of box, or add drawing of rectangles at rear faces of box. Also you can disable ticks drawing, but I don’t know why anybody will want it. The sample code, which demonstrate box features is:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0); gr->Title("Box (default)"); gr->Rotate(50,60); gr->Box(); gr->SubPlot(2,2,1); gr->Title("colored"); gr->Rotate(50,60); gr->Box("r"); gr->SubPlot(2,2,2); gr->Title("with faces"); gr->Rotate(50,60); gr->Box("@"); gr->SubPlot(2,2,3); gr->Title("both"); gr->Rotate(50,60); gr->Box("@cm"); return 0; }
There are another unusual axis types which are supported by MathGL. These are ternary and quaternary axis. Ternary axis is special axis of 3 coordinates a, b, c which satisfy relation a+b+c=1. Correspondingly, quaternary axis is special axis of 4 coordinates a, b, c, d which satisfy relation a+b+c+d=1.
Generally speaking, only 2 of coordinates (3 for quaternary) are independent. So, MathGL just introduce some special transformation formulas which treat a as ‘x’, b as ‘y’ (and c as ‘z’ for quaternary). As result, all plotting functions (curves, surfaces, contours and so on) work as usual, but in new axis. You should use ternary function for switching to ternary/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->SubPlot(2,2,0); gr->Title("Ordinary axis 3D"); gr->Rotate(50,60); gr->Light(true); gr->Plot(x,y,z,"r2"); gr->Surf(a,"BbcyrR#"); gr->Axis(); gr->Grid(); gr->Box(); gr->Label('x',"B",1); gr->Label('y',"C",1); gr->Label('z',"Z",1); gr->SubPlot(2,2,1); gr->Title("Ternary axis (x+y+t=1)"); gr->Ternary(1); gr->Plot(x,y,"r2"); gr->Plot(rx,ry,"q^ "); gr->Cont(a,"BbcyrR"); gr->Line(mglPoint(0.5,0), mglPoint(0,0.75), "g2"); gr->Axis(); gr->Grid("xyz","B;"); gr->Label('x',"B"); gr->Label('y',"C"); gr->Label('t',"A"); gr->SubPlot(2,2,2); gr->Title("Quaternary axis 3D"); gr->Rotate(50,60); gr->Light(true); gr->Ternary(2); gr->Plot(x,y,z,"r2"); gr->Surf(a,"BbcyrR#"); gr->Axis(); gr->Grid(); gr->Box(); gr->Label('t',"A",1); gr->Label('x',"B",1); gr->Label('y',"C",1); gr->Label('z',"D",1); gr->SubPlot(2,2,3); gr->Title("Ternary axis 3D"); gr->Rotate(50,60); gr->Light(true); gr->Ternary(1); gr->Plot(x,y,z,"r2"); gr->Surf(a,"BbcyrR#"); gr->Axis(); gr->Grid(); gr->Box(); gr->Label('t',"A",1); gr->Label('x',"B",1); gr->Label('y',"C",1); gr->Label('z',"Z",1); return 0; }
MathGL prints text by vector font. There are functions for manual specifying of text position (like Puts
) and for its automatic selection (like Label
, Legend
and so on). MathGL prints text always in specified position even if it lies outside the bounding box. The default size of font is specified by functions SetFontSize* (see Шрифты). However, the actual size of output string depends on subplot size (depends on functions SubPlot
, InPlot
). The switching of the font style (italic, bold, wire and so on) can be done for the whole string (by function parameter) or inside the string. By default MathGL parses TeX-like commands for symbols and indexes (see Стиль текста).
Text can be printed as usual one (from left to right), along some direction (rotated text), or along a curve. Text can be printed on several lines, divided by new line symbol ‘\n’.
Example of MathGL font drawing is:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0,""); gr->Putsw(mglPoint(0,1),L"Text can be in ASCII and in Unicode"); gr->Puts(mglPoint(0,0.6),"It can be \\wire{wire}, \\big{big} or #r{colored}"); gr->Puts(mglPoint(0,0.2),"One can change style in string: " "\\b{bold}, \\i{italic, \\b{both}}"); gr->Puts(mglPoint(0,-0.2),"Easy to \\a{overline} or " "\\u{underline}"); gr->Puts(mglPoint(0,-0.6),"Easy to change indexes ^{up} _{down} @{center}"); gr->Puts(mglPoint(0,-1),"It parse TeX: \\int \\alpha \\cdot " "\\sqrt3{sin(\\pi x)^2 + \\gamma_{i_k}} dx"); gr->SubPlot(2,2,1,""); gr->Puts(mglPoint(0,0.5), "\\sqrt{\\frac{\\alpha^{\\gamma^2}+\\overset 1{\\big\\infty}}{\\sqrt3{2+b}}}", "@", -4); gr->Puts(mglPoint(0,-0.5),"Text can be printed\non several lines"); gr->SubPlot(2,2,2,""); mglData y; mgls_prepare1d(&y); gr->Box(); gr->Plot(y.SubData(-1,0)); gr->Text(y,"This is very very long string drawn along a curve",":k"); gr->Text(y,"Another string drawn under a curve","T:r"); gr->SubPlot(2,2,3,""); gr->Line(mglPoint(-1,-1),mglPoint(1,-1),"rA"); gr->Puts(mglPoint(0,-1),mglPoint(1,-1),"Horizontal"); gr->Line(mglPoint(-1,-1),mglPoint(1,1),"rA"); gr->Puts(mglPoint(0,0),mglPoint(1,1),"At angle","@"); gr->Line(mglPoint(-1,-1),mglPoint(-1,1),"rA"); gr->Puts(mglPoint(-1,0),mglPoint(-1,1),"Vertical"); return 0; }
You can change font faces by loading font files by function loadfont. Note, that this is long-run procedure. Font faces can be downloaded from MathGL website or from here. The sample code is:
int sample(mglGraph *gr) { double h=1.1, d=0.25; gr->LoadFont("STIX"); gr->Puts(mglPoint(0,h), "default font (STIX)"); gr->LoadFont("adventor"); gr->Puts(mglPoint(0,h-d), "adventor font"); gr->LoadFont("bonum"); gr->Puts(mglPoint(0,h-2*d), "bonum font"); gr->LoadFont("chorus"); gr->Puts(mglPoint(0,h-3*d), "chorus font"); gr->LoadFont("cursor"); gr->Puts(mglPoint(0,h-4*d), "cursor font"); gr->LoadFont("heros"); gr->Puts(mglPoint(0,h-5*d), "heros font"); gr->LoadFont("heroscn"); gr->Puts(mglPoint(0,h-6*d), "heroscn font"); gr->LoadFont("pagella"); gr->Puts(mglPoint(0,h-7*d), "pagella font"); gr->LoadFont("schola"); gr->Puts(mglPoint(0,h-8*d), "schola font"); gr->LoadFont("termes"); gr->Puts(mglPoint(0,h-9*d), "termes font"); return 0; }
Legend is one of standard ways to show plot annotations. Basically you need to connect the plot style (line style, marker and color) with some text. In MathGL, you can do it by 2 methods: manually using addlegend function; or use ‘legend’ option (see Опции команд), which will use last plot style. In both cases, legend entries will be added into internal accumulator, which later used for legend drawing itself. clearlegend function allow you to remove all saved legend entries.
There are 2 features. If plot style is empty then text will be printed without indent. If you want to plot the text with indent but without plot sample then you need to use space ‘ ’ as plot style. Such style ‘ ’ will draw a plot sample (line with marker(s)) which is invisible line (i.e. nothing) and print the text with indent as usual one.
Function legend draw legend on the plot. The position of the legend can be selected automatic or manually. You can change the size and style of text labels, as well as setup the plot sample. The sample code demonstrating legend features is:
int sample(mglGraph *gr) { gr->AddLegend("sin(\\pi {x^2})","b"); gr->AddLegend("sin(\\pi x)","g*"); gr->AddLegend("sin(\\pi \\sqrt{x})","rd"); gr->AddLegend("just text"," "); gr->AddLegend("no indent for this",""); gr->SubPlot(2,2,0,""); gr->Title("Legend (default)"); gr->Box(); gr->Legend(); gr->Legend(3,"A#"); gr->Puts(mglPoint(0.75,0.65),"Absolute position","A"); gr->SubPlot(2,2,2,""); gr->Title("coloring"); gr->Box(); gr->Legend(0,"r#"); gr->Legend(1,"Wb#"); gr->Legend(2,"ygr#"); gr->SubPlot(2,2,3,""); gr->Title("manual position"); gr->Box(); gr->Legend(0.5,1); gr->Puts(mglPoint(0.5,0.55),"at x=0.5, y=1","a"); gr->Legend(1,"#-"); gr->Puts(mglPoint(0.75,0.25),"Horizontal legend","a"); return 0; }
The last common thing which I want to show in this section is how one can cut off points from plot. There are 4 mechanism for that.
SetCut
function. As result all points out of bounding box will be omitted.
SetCutBox
function. All points inside this box will be omitted.
SetCutOff
function. All points for which the value of formula is nonzero will be omitted. Note, that this is the slowest variant.
Below I place the code which demonstrate last 3 possibilities:
int sample(mglGraph *gr) { mglData a,c,v(1); mgls_prepare2d(&a); mgls_prepare3d(&c); v.a[0]=0.5; gr->SubPlot(2,2,0); gr->Title("Cut on (default)"); gr->Rotate(50,60); gr->Light(true); gr->Box(); gr->Surf(a,"","zrange -1 0.5"); gr->SubPlot(2,2,1); gr->Title("Cut off"); gr->Rotate(50,60); gr->Box(); gr->Surf(a,"","zrange -1 0.5; cut off"); gr->SubPlot(2,2,2); gr->Title("Cut in box"); gr->Rotate(50,60); gr->SetCutBox(mglPoint(0,-1,-1), mglPoint(1,0,1.1)); gr->Alpha(true); gr->Box(); gr->Surf3(c); gr->SetCutBox(mglPoint(0), mglPoint(0)); // switch it off gr->SubPlot(2,2,3); gr->Title("Cut by formula"); gr->Rotate(50,60); gr->CutOff("(z>(x+0.5*y-1)^2-1) & (z>(x-0.5*y-1)^2-1)"); gr->Box(); gr->Surf3(c); gr->CutOff(""); // switch it off return 0; }
Class mglData
contains all functions for the data handling in MathGL (see Обработка данных). There are several matters why I use class mglData
but not a single array: it does not depend on type of data (mreal or double), sizes of data arrays are kept with data, memory working is simpler and safer.
There are many ways in MathGL how data arrays can be created and filled.
One can put the data in mglData
instance by several ways. Let us do it for sinus function:
mglData
variable
double *a = new double[50]; for(int i=0;i<50;i++) a[i] = sin(M_PI*i/49.); mglData y; y.Set(a,50);
mglData
instance of the desired size and then to work directly with data in this variable
mglData y(50); for(int i=0;i<50;i++) y.a[i] = sin(M_PI*i/49.);
mglData
instance by textual formula with the help of Modify()
function
mglData y(50); y.Modify("sin(pi*x)");
mglData y(50); y.Fill(0,M_PI); y.Modify("sin(u)");
FILE *fp=fopen("sin.dat","wt"); // create file first for(int i=0;i<50;i++) fprintf(fp,"%g\n",sin(M_PI*i/49.)); fclose(fp); mglData y("sin.dat"); // load it
At this you can use textual or HDF files, as well as import values from bitmap image (PNG is supported right now).
FILE *fp-fopen("sin.dat","wt"); // create large file first for(int i=0;i<70;i++) fprintf(fp,"%g\n",sin(M_PI*i/49.)); fclose(fp); mglData y; y.Read("sin.dat",50); // load it
Creation of 2d- and 3d-arrays is mostly the same. But one should keep in mind that class mglData
uses flat data representation. For example, matrix 30*40 is presented as flat (1d-) array with length 30*40=1200 (nx=30, ny=40). The element with indexes {i,j} is a[i+nx*j]. So for 2d array we have:
mglData z(30,40); for(int i=0;i<30;i++) for(int j=0;j<40;j++) z.a[i+30*j] = sin(M_PI*i/29.)*sin(M_PI*j/39.);
or by using Modify()
function
mglData z(30,40); z.Modify("sin(pi*x)*cos(pi*y)");
The only non-obvious thing here is using multidimensional arrays in C/C++, i.e. arrays defined like mreal dat[40][30];
. Since, formally these elements dat[i]
can address the memory in arbitrary place you should use the proper function to convert such arrays to mglData
object. For C++ this is functions like mglData::Set(mreal **dat, int N1, int N2);
. For C this is functions like mgl_data_set_mreal2(HMDT d, const mreal **dat, int N1, int N2);
. At this, you should keep in mind that nx=N2
and ny=N1
after conversion.
Sometimes the data arrays are so large, that one couldn’t’ copy its values to another array (i.e. into mglData). In this case, he can define its own class derived from mglDataA
(see User defined types (mglDataA class)) or can use Link
function.
In last case, MathGL just save the link to an external data array, but not copy it. You should provide the existence of this data array for whole time during which MathGL can use it. Another point is that MathGL will automatically create new array if you’ll try to modify data values by any of mglData
functions. So, you should use only function with const
modifier if you want still using link to the original data array.
Creating the link is rather simple – just the same as using Set
function
double *a = new double[50]; for(int i=0;i<50;i++) a[i] = sin(M_PI*i/49.); mglData y; y.Link(a,50);
MathGL has functions for data processing: differentiating, integrating, smoothing and so on (for more detail, see Обработка данных). Let us consider some examples. The simplest ones are integration and differentiation. The direction in which operation will be performed is specified by textual string, which may contain symbols ‘x’, ‘y’ or ‘z’. For example, the call of Diff("x")
will differentiate data along ‘x’ direction; the call of Integral("xy")
perform the double integration of data along ‘x’ and ‘y’ directions; the call of Diff2("xyz")
will apply 3d Laplace operator to data and so on. Example of this operations on 2d array a=x*y is presented in code:
int sample(mglGraph *gr) { gr->SetRanges(0,1,0,1,0,1); mglData a(30,40); a.Modify("x*y"); gr->SubPlot(2,2,0); gr->Rotate(60,40); gr->Surf(a); gr->Box(); gr->Puts(mglPoint(0.7,1,1.2),"a(x,y)"); gr->SubPlot(2,2,1); gr->Rotate(60,40); a.Diff("x"); gr->Surf(a); gr->Box(); gr->Puts(mglPoint(0.7,1,1.2),"da/dx"); gr->SubPlot(2,2,2); gr->Rotate(60,40); a.Integral("xy"); gr->Surf(a); gr->Box(); gr->Puts(mglPoint(0.7,1,1.2),"\\int da/dx dxdy"); gr->SubPlot(2,2,3); gr->Rotate(60,40); a.Diff2("y"); gr->Surf(a); gr->Box(); gr->Puts(mglPoint(0.7,1,1.2),"\\int {d^2}a/dxdy dx"); return 0; }
Data smoothing (function smooth) is more interesting and important. This function has single argument which define type of smoothing and its direction. Now 3 methods are supported: ‘3’ – linear averaging by 3 points, ‘5’ – linear averaging by 5 points, and default one – quadratic averaging by 5 points.
MathGL also have some amazing functions which is not so important for data processing as useful for data plotting. There are functions for finding envelope (useful for plotting rapidly oscillating data), for data sewing (useful to removing jumps on the phase), for data resizing (interpolation). Let me demonstrate it:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0,""); gr->Title("Envelop sample"); mglData d1(1000); gr->Fill(d1,"exp(-8*x^2)*sin(10*pi*x)"); gr->Axis(); gr->Plot(d1, "b"); d1.Envelop('x'); gr->Plot(d1, "r"); gr->SubPlot(2,2,1,""); gr->Title("Smooth sample"); mglData y0(30),y1,y2,y3; gr->SetRanges(0,1,0,1); gr->Fill(y0, "0.4*sin(pi*x) + 0.3*cos(1.5*pi*x) - 0.4*sin(2*pi*x)+0.5*rnd"); y1=y0; y1.Smooth("x3"); y2=y0; y2.Smooth("x5"); y3=y0; y3.Smooth("x"); gr->Plot(y0,"{m7}:s", "legend 'none'"); //gr->AddLegend("none","k"); gr->Plot(y1,"r", "legend ''3' style'"); gr->Plot(y2,"g", "legend ''5' style'"); gr->Plot(y3,"b", "legend 'default'"); gr->Legend(); gr->Box(); gr->SubPlot(2,2,2); gr->Title("Sew sample"); mglData d2(100, 100); gr->Fill(d2, "mod((y^2-(1-x)^2)/2,0.1)"); gr->Rotate(50, 60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf(d2, "b"); d2.Sew("xy", 0.1); gr->Surf(d2, "r"); gr->SubPlot(2,2,3); gr->Title("Resize sample (interpolation)"); mglData x0(10), v0(10), x1, v1; gr->Fill(x0,"rnd"); gr->Fill(v0,"rnd"); x1 = x0.Resize(100); v1 = v0.Resize(100); gr->Plot(x0,v0,"b+ "); gr->Plot(x1,v1,"r-"); gr->Label(x0,v0,"%n"); return 0; }
Also one can create new data arrays on base of the existing one: extract slice, row or column of data (subdata), summarize along a direction(s) (sum), find distribution of data elements (hist) and so on.
Another interesting feature of MathGL is interpolation and root-finding. There are several functions for linear and cubic spline interpolation (see Интерполяция). Also there is a function evaluate which do interpolation of data array for values of each data element of index data. It look as indirect access to the data elements.
This function have inverse function solve which find array of indexes at which data array is equal to given value (i.e. work as root finding). But solve function have the issue – usually multidimensional data (2d and 3d ones) have an infinite number of indexes which give some value. This is contour lines for 2d data, or isosurface(s) for 3d data. So, solve function will return index only in given direction, assuming that other index(es) are the same as equidistant index(es) of original data. If data have multiple roots then second (and later) branches can be found by consecutive call(s) of solve function. Let me demonstrate this on the following sample.
int sample(mglGraph *gr) { gr->SetRange('z',0,1); mglData x(20,30), y(20,30), z(20,30), xx,yy,zz; gr->Fill(x,"(x+2)/3*cos(pi*y)"); gr->Fill(y,"(x+2)/3*sin(pi*y)"); gr->Fill(z,"exp(-6*x^2-2*sin(pi*y)^2)"); gr->SubPlot(2,1,0); gr->Title("Cartesian space"); gr->Rotate(30,-40); gr->Axis("xyzU"); gr->Box(); gr->Label('x',"x"); gr->Label('y',"y"); gr->SetOrigin(1,1); gr->Grid("xy"); gr->Mesh(x,y,z); // section along 'x' direction mglData u = x.Solve(0.5,'x'); mglData v(u.nx); v.Fill(0,1); xx = x.Evaluate(u,v); yy = y.Evaluate(u,v); zz = z.Evaluate(u,v); gr->Plot(xx,yy,zz,"k2o"); // 1st section along 'y' direction mglData u1 = x.Solve(-0.5,'y'); mglData v1(u1.nx); v1.Fill(0,1); xx = x.Evaluate(v1,u1); yy = y.Evaluate(v1,u1); zz = z.Evaluate(v1,u1); gr->Plot(xx,yy,zz,"b2^"); // 2nd section along 'y' direction mglData u2 = x.Solve(-0.5,'y',u1); xx = x.Evaluate(v1,u2); yy = y.Evaluate(v1,u2); zz = z.Evaluate(v1,u2); gr->Plot(xx,yy,zz,"r2v"); gr->SubPlot(2,1,1); gr->Title("Accompanied space"); gr->SetRanges(0,1,0,1); gr->SetOrigin(0,0); gr->Axis(); gr->Box(); gr->Label('x',"i"); gr->Label('y',"j"); gr->Grid(z,"h"); gr->Plot(u,v,"k2o"); gr->Line(mglPoint(0.4,0.5),mglPoint(0.8,0.5),"kA"); gr->Plot(v1,u1,"b2^"); gr->Line(mglPoint(0.5,0.15),mglPoint(0.5,0.3),"bA"); gr->Plot(v1,u2,"r2v"); gr->Line(mglPoint(0.5,0.7),mglPoint(0.5,0.85),"rA"); }
Let me now show how to plot the data. Next section will give much more examples for all plotting functions. Here I just show some basics. MathGL generally has 2 types of plotting functions. Simple variant requires a single data array for plotting, other data (coordinates) are considered uniformly distributed in axis range. Second variant requires data arrays for all coordinates. It allows one to plot rather complex multivalent curves and surfaces (in case of parametric dependencies). Usually each function have one textual argument for plot style and another textual argument for options (see Опции команд).
Note, that the call of drawing function adds something to picture but does not clear the previous plots (as it does in Matlab). Another difference from Matlab is that all setup (like transparency, lightning, axis borders and so on) must be specified before plotting functions.
Let start for plots for 1D data. Term “1D data” means that data depend on single index (parameter) like curve in parametric form {x(i),y(i),z(i)}, i=1...n. The textual argument allow you specify styles of line and marks (see Стиль линий). If this parameter is NULL
or empty then solid line with color from palette is used (see Палитра и цвета).
Below I shall show the features of 1D plotting on base of plot function. Let us start from sinus plot:
int sample(mglGraph *gr) { mglData y0(50); y0.Modify("sin(pi*(2*x-1))"); gr->SubPlot(2,2,0); gr->Plot(y0); gr->Box();
Style of line is not specified in plot function. So MathGL uses the solid line with first color of palette (this is blue). Next subplot shows array y1 with 2 rows:
gr->SubPlot(2,2,1); mglData y1(50,2); y1.Modify("sin(pi*2*x-pi)"); y1.Modify("cos(pi*2*x-pi)/2",1); gr->Plot(y1); gr->Box();
As previously I did not specify the style of lines. As a result, MathGL again uses solid line with next colors in palette (there are green and red). Now let us plot a circle on the same subplot. The circle is parametric curve x=cos(\pi t), y=sin(\pi t). I will set the color of the circle (dark yellow, ‘Y’) and put marks ‘+’ at point position:
mglData x(50); x.Modify("cos(pi*2*x-pi)"); gr->Plot(x,y0,"Y+");
Note that solid line is used because I did not specify the type of line. The same picture can be achieved by plot and subdata functions. Let us draw ellipse by orange dash line:
gr->Plot(y1.SubData(-1,0),y1.SubData(-1,1),"q|");
Drawing in 3D space is mostly the same. Let us draw spiral with default line style. Now its color is 4-th color from palette (this is cyan):
gr->SubPlot(2,2,2); gr->Rotate(60,40); mglData z(50); z.Modify("2*x-1"); gr->Plot(x,y0,z); gr->Box();
Functions plot and subdata make 3D curve plot but for single array. Use it to put circle marks on the previous plot:
mglData y2(10,3); y2.Modify("cos(pi*(2*x-1+y))"); y2.Modify("2*x-1",2); gr->Plot(y2.SubData(-1,0),y2.SubData(-1,1),y2.SubData(-1,2),"bo ");
Note that line style is empty ‘ ’ here. Usage of other 1D plotting functions looks similar:
gr->SubPlot(2,2,3); gr->Rotate(60,40); gr->Bars(x,y0,z,"r"); gr->Box(); return 0; }
Surfaces surf and other 2D plots (see 2D графики) are drown the same simpler as 1D one. The difference is that the string parameter specifies not the line style but the color scheme of the plot (see Цветовая схема). Here I draw attention on 4 most interesting color schemes. There is gray scheme where color is changed from black to white (string ‘kw’) or from white to black (string ‘wk’). Another scheme is useful for accentuation of negative (by blue color) and positive (by red color) regions on plot (string ‘"BbwrR"’). Last one is the popular “jet” scheme (string ‘"BbcyrR"’).
Now I shall show the example of a surface drawing. At first let us switch lightning on
int sample(mglGraph *gr) { gr->Light(true); gr->Light(0,mglPoint(0,0,1));
and draw the surface, considering coordinates x,y to be uniformly distributed in axis range
mglData a0(50,40); a0.Modify("0.6*sin(2*pi*x)*sin(3*pi*y)+0.4*cos(3*pi*(x*y))"); gr->SubPlot(2,2,0); gr->Rotate(60,40); gr->Surf(a0); gr->Box();
Color scheme was not specified. So previous color scheme is used. In this case it is default color scheme (“jet”) for the first plot. Next example is a sphere. The sphere is parametrically specified surface:
mglData x(50,40),y(50,40),z(50,40); x.Modify("0.8*sin(2*pi*x)*sin(pi*y)"); y.Modify("0.8*cos(2*pi*x)*sin(pi*y)"); z.Modify("0.8*cos(pi*y)"); gr->SubPlot(2,2,1); gr->Rotate(60,40); gr->Surf(x,y,z,"BbwrR");gr->Box();
I set color scheme to "BbwrR"
that corresponds to red top and blue bottom of the sphere.
Surfaces will be plotted for each of slice of the data if nz>1. Next example draws surfaces for data arrays with nz=3:
mglData a1(50,40,3); a1.Modify("0.6*sin(2*pi*x)*sin(3*pi*y)+0.4*cos(3*pi*(x*y))"); a1.Modify("0.6*cos(2*pi*x)*cos(3*pi*y)+0.4*sin(3*pi*(x*y))",1); a1.Modify("0.6*cos(2*pi*x)*cos(3*pi*y)+0.4*cos(3*pi*(x*y))",2); gr->SubPlot(2,2,2); gr->Rotate(60,40); gr->Alpha(true); gr->Surf(a1); gr->Box();
Note, that it may entail a confusion. However, if one will use density plot then the picture will look better:
gr->SubPlot(2,2,3); gr->Rotate(60,40); gr->Dens(a1); gr->Box(); return 0; }
Drawing of other 2D plots is analogous. The only peculiarity is the usage of flag ‘#’. By default this flag switches on the drawing of a grid on plot (grid or mesh for plots in plain or in volume). However, for isosurfaces (including surfaces of rotation axial) this flag switches the face drawing off. Figure becomes wired. The following code gives example of flag ‘#’ using (compare with normal function drawing as in its description):
int sample(mglGraph *gr) { gr->Alpha(true); gr->Light(true); gr->Light(0,mglPoint(0,0,1)); mglData a(30,20); a.Modify("0.6*sin(2*pi*x)*sin(3*pi*y) + 0.4*cos(3*pi*(x*y))"); gr->SubPlot(2,2,0); gr->Rotate(40,60); gr->Surf(a,"BbcyrR#"); gr->Box(); gr->SubPlot(2,2,1); gr->Rotate(40,60); gr->Dens(a,"BbcyrR#"); gr->Box(); gr->SubPlot(2,2,2); gr->Rotate(40,60); gr->Cont(a,"BbcyrR#"); gr->Box(); gr->SubPlot(2,2,3); gr->Rotate(40,60); gr->Axial(a,"BbcyrR#"); gr->Box(); return 0; }
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.
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; }
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; }
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 Опции команд). 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; }
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); }
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); gr->Cont(a,"y"); return 0; }
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; }
Additionally, you can use local light sources and set to use diffuse reflection instead of specular one (by default) or both kinds. Note, I use attachlight command to keep light settings relative to subplot.
int sample(mglGraph *gr) { gr->Light(true); gr->AttachLight(true); gr->SubPlot(2,2,0); gr->Title("Default"); gr->Rotate(50,60); gr->Line(mglPoint(-1,-0.7,1.7),mglPoint(-1,-0.7,0.7),"BA"); gr->Box(); gr->Surf(a); gr->SubPlot(2,2,1); gr->Title("Local"); gr->Rotate(50,60); gr->AddLight(0,mglPoint(1,0,1),mglPoint(-2,-1,-1)); gr->Line(mglPoint(1,0,1),mglPoint(-1,-1,0),"BAO"); gr->Box(); gr->Surf(a); gr->SubPlot(2,2,2); gr->Title("no diffuse"); gr->Rotate(50,60); gr->SetDiffuse(0); gr->Line(mglPoint(1,0,1),mglPoint(-1,-1,0),"BAO"); gr->Box(); gr->Surf(a); gr->SubPlot(2,2,3); gr->Title("diffusive only"); gr->Rotate(50,60); gr->SetDiffuse(0.5); gr->AddLight(0,mglPoint(1,0,1),mglPoint(-2,-1,-1),'w',0); gr->Line(mglPoint(1,0,1),mglPoint(-1,-1,0),"BAO"); gr->Box(); gr->Surf(a); }
MathGL provide a set of functions for drawing primitives (see Рисование примитивов). Primitives are low level object, which used by most of plotting functions. Picture below demonstrate some of commonly used primitives.
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; }
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.
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; }
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; }
There are many functions to get interpolated values of a data array. Basically all of them can be divided by 3 categories:
mglGSpline()
in Глобальные функции);
The usage of first category is rather straightforward and don’t need any special comments.
There is difference in indirect access functions. Function subdata use use step-like interpolation to handle correctly single nan
values in the data array. Contrary, function evaluate use local spline interpolation, which give smoother output but spread nan
values. So, subdata should be used for specific data elements (for example, for given column), and evaluate should be used for distributed elements (i.e. consider data array as some field). Following sample illustrates this difference:
int sample(mglGraph *gr) { gr->SubPlot(1,1,0,""); gr->Title("SubData vs Evaluate"); mglData in(9), arg(99), e, s; gr->Fill(in,"x^3/1.1"); gr->Fill(arg,"4*x+4"); gr->Plot(in,"ko "); gr->Box(); e = in.Evaluate(arg,false); gr->Plot(e,"b.","legend 'Evaluate'"); s = in.SubData(arg); gr->Plot(s,"r.","legend 'SubData'"); gr->Legend(2); }
Example of datagrid usage is done in Making regular data. Here I want to show the peculiarities of refill and gspline functions. Both functions require argument(s) which provide coordinates of the data values, and return rectangular data array which equidistantly distributed in axis range. So, in opposite to evaluate function, refill and gspline can interpolate non-equidistantly distributed data. At this both functions refill and gspline provide continuity of 2nd derivatives along coordinate(s). However, refill is slower but give better (from human point of view) result than global spline gspline due to more advanced algorithm. Following sample illustrates this difference:
int sample(mglGraph *gr) { mglData x(10), y(10), r(100); x.Modify("0.5+rnd"); x.CumSum("x"); x.Norm(-1,1); y.Modify("sin(pi*v)/1.5",x); gr->SubPlot(2,2,0,"<_"); gr->Title("Refill sample"); gr->Axis(); gr->Box(); gr->Plot(x,y,"o "); gr->Refill(r,x,y); // or you can use r.Refill(x,y,-1,1); gr->Plot(r,"r"); gr->FPlot("sin(pi*x)/1.5","B:"); gr->SubPlot(2,2,1,"<_");gr->Title("Global spline"); gr->Axis(); gr->Box(); gr->Plot(x,y,"o "); r.RefillGS(x,y,-1,1); gr->Plot(r,"r"); gr->FPlot("sin(pi*x)/1.5","B:"); gr->Alpha(true); gr->Light(true); mglData z(10,10), xx(10,10), yy(10,10), rr(100,100); y.Modify("0.5+rnd"); y.CumSum("x"); y.Norm(-1,1); for(int i=0;i<10;i++) for(int j=0;j<10;j++) z.a[i+10*j] = sin(M_PI*x.a[i]*y.a[j])/1.5; gr->SubPlot(2,2,2); gr->Title("2d regular"); gr->Rotate(40,60); gr->Axis(); gr->Box(); gr->Mesh(x,y,z,"k"); gr->Refill(rr,x,y,z); gr->Surf(rr); gr->Fill(xx,"(x+1)/2*cos(y*pi/2-1)"); gr->Fill(yy,"(x+1)/2*sin(y*pi/2-1)"); for(int i=0;i<10*10;i++) z.a[i] = sin(M_PI*xx.a[i]*yy.a[i])/1.5; gr->SubPlot(2,2,3); gr->Title("2d non-regular"); gr->Rotate(40,60); gr->Axis(); gr->Box(); gr->Plot(xx,yy,z,"ko "); gr->Refill(rr,xx,yy,z); gr->Surf(rr); }
Sometimes, one have only unregular data, like as data on triangular grids, or experimental results and so on. Such kind of data cannot be used as simple as regular data (like matrices). Only few functions, like dots, can handle unregular data as is.
However, one can use built in triangulation functions for interpolating unregular data points to a regular data grids. There are 2 ways. First way, one can use triangulation function to obtain list of vertexes for triangles. Later this list can be used in functions like triplot or tricont. Second way consist in usage of datagrid function, which fill regular data grid by interpolated values, assuming that coordinates of the data grid is equidistantly distributed in axis range. Note, you can use options (see Опции команд) to change default axis range as well as in other plotting functions.
int sample(mglGraph *gr) { mglData x(100), y(100), z(100); gr->Fill(x,"2*rnd-1"); gr->Fill(y,"2*rnd-1"); gr->Fill(z,"v^2-w^2",x,y); // first way - plot triangular surface for points mglData d = mglTriangulation(x,y); gr->Title("Triangulation"); gr->Rotate(40,60); gr->Box(); gr->Light(true); gr->TriPlot(d,x,y,z); gr->TriPlot(d,x,y,z,"#k"); // second way - make regular data and plot it mglData g(30,30); gr->DataGrid(g,x,y,z); gr->Mesh(g,"m"); }
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; }
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 dat(100), in(100); //data to be fitted and ideal data gr->Fill(dat,"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(dat, "k. "); 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(dat, "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 dat(100), in(100); gr->Fill(dat,"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(dat, "a+b*sin(c*x)", "abc", Ini); gr->Title("Fitting sample"); gr->SetRange('y',-2,2); gr->Box(); gr->Plot(dat, "k. "); 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; }
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 ray for ray tracing, pde for PDE solving, qo2d for beam tracing in 2D case (see Глобальные функции). 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 ray 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)"
or ham = "p^2 + i1*x*(x>0)"
.
Next step is specifying the initial conditions at ‘z’ equal to minimal z-axis value. The function need 2 arrays for real and for imaginary part. Note, that coordinates x,y,z are supposed to be in specified axis range. 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 1/ik_0 * du/dz + d^2 u/dx^2 + d^2 u/dy^2 + x * u + i (x+z)/2 * 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; }
The next 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 = (|r''|^2 |r'|^2 - (r'', r'')^2)/|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; }
Note, the pde is fast enough and suitable for many cases routine. However, there is situations then media have both together: strong spatial dispersion and spatial inhomogeneity. In this, case the pde will produce incorrect result and you need to use advanced PDE solver apde. For example, a wave beam, propagated in plasma, described by Hamiltonian exp(-x^2-p^2), will have different solution for using of simplification and advanced PDE solver:
int sample(mglGraph *gr) { gr->SetRanges(-1,1,0,2,0,2); mglData ar(256), ai(256); gr->Fill(ar,"exp(-2*x^2)"); mglData res1(gr->APDE("exp(-x^2-p^2)",ar,ai,0.01)); res1.Transpose(); gr->SubPlot(1,2,0,"_"); gr->Title("Advanced PDE solver"); gr->SetRanges(0,2,-1,1); gr->SetRange('c',res1); gr->Dens(res1); gr->Axis(); gr->Box(); gr->Label('x',"\\i z"); gr->Label('y',"\\i x"); gr->Puts(mglPoint(-0.5,0.2),"i\\partial_z\\i u = exp(-\\i x^2+\\partial_x^2)[\\i u]","y"); mglData res2(gr->PDE("exp(-x^2-p^2)",ar,ai,0.01)); gr->SubPlot(1,2,1,"_"); gr->Title("Simplified PDE solver"); gr->Dens(res2); gr->Axis(); gr->Box(); gr->Label('x',"\\i z"); gr->Label('y',"\\i x"); gr->Puts(mglPoint(-0.5,0.2),"i\\partial_z\\i u \\approx\\ exp(-\\i x^2)\\i u+exp(\\partial_x^2)[\\i u]","y"); return 0; }
Here I want say a few words of plotting phase plains. Phase plain is name for system of coordinates x, x', i.e. a variable and its time derivative. Plot in phase plain is very useful for qualitative analysis of an ODE, because such plot is rude (it topologically the same for a range of ODE parameters). Most often the phase plain {x, x'} is used (due to its simplicity), that allows one to analyze up to the 2nd order ODE (i.e. x''+f(x,x')=0).
The simplest way to draw phase plain in MathGL is using flow function(s), which automatically select several points and draw flow threads. If the ODE have an integral of motion (like Hamiltonian H(x,x')=const for dissipation-free case) then you can use cont function for plotting isolines (contours). In fact. isolines are the same as flow threads, but without arrows on it. Finally, you can directly solve ODE using ode function and plot its numerical solution.
Let demonstrate this for ODE equation x''-x+3*x^2=0. This is nonlinear oscillator with square nonlinearity. It has integral H=y^2+2*x^3-x^2=Const. Also it have 2 typical stationary points: saddle at {x=0, y=0} and center at {x=1/3, y=0}. Motion at vicinity of center is just simple oscillations, and is stable to small variation of parameters. In opposite, motion around saddle point is non-stable to small variation of parameters, and is very slow. So, calculation around saddle points are more difficult, but more important. Saddle points are responsible for solitons, stochasticity and so on.
So, let draw this phase plain by 3 different methods. First, draw isolines for H=y^2+2*x^3-x^2=Const – this is simplest for ODE without dissipation. Next, draw flow threads – this is straightforward way, but the automatic choice of starting points is not always optimal. Finally, use ode to check the above plots. At this we need to run ode in both direction of time (in future and in the past) to draw whole plain. Alternatively, one can put starting points far from (or at the bounding box as done in flow) the plot, but this is a more complicated. The sample code is:
int sample(mglGraph *gr) { gr->SubPlot(2,2,0,"<_"); gr->Title("Cont"); gr->Box(); gr->Axis(); gr->Label('x',"x"); gr->Label('y',"\\dot{x}"); mglData f(100,100); gr->Fill(f,"y^2+2*x^3-x^2-0.5"); gr->Cont(f); gr->SubPlot(2,2,1,"<_"); gr->Title("Flow"); gr->Box(); gr->Axis(); gr->Label('x',"x"); gr->Label('y',"\\dot{x}"); mglData fx(100,100), fy(100,100); gr->Fill(fx,"x-3*x^2"); gr->Fill(fy,"y"); gr->Flow(fy,fx,"v","value 7"); gr->SubPlot(2,2,2,"<_"); gr->Title("ODE"); gr->Box(); gr->Axis(); gr->Label('x',"x"); gr->Label('y',"\\dot{x}"); for(double x=-1;x<1;x+=0.1) { mglData in(2), r; in.a[0]=x; r = mglODE("y;x-3*x^2","xy",in); gr->Plot(r.SubData(0), r.SubData(1)); r = mglODE("-y;-x+3*x^2","xy",in); gr->Plot(r.SubData(0), r.SubData(1)); } }
There is common task in optics to determine properties of wave pulses or wave beams. MathGL provide special function pulse which return the pulse properties (maximal value, center of mass, width and so on). Its usage is rather simple. Here I just illustrate it on the example of Gaussian pulse, where all parameters are obvious.
void sample(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); gr->Title("Pulse sample"); // first prepare pulse itself mglData a(100); gr->Fill(a,"exp(-6*x^2)"); // get pulse parameters mglData b(a.Pulse('x')); // positions and widths are normalized on the number of points. So, set proper axis scale. gr->SetRanges(0, a.nx-1, 0, 1); gr->Axis(); gr->Plot(a); // draw pulse and axis // now visualize found pulse properties double m = b[0]; // maximal amplitude // approximate position of maximum gr->Line(mglPoint(b[1],0), mglPoint(b[1],m),"r="); // width at half-maximum (so called FWHM) gr->Line(mglPoint(b[1]-b[3]/2,0), mglPoint(b[1]-b[3]/2,m),"m|"); gr->Line(mglPoint(b[1]+b[3]/2,0), mglPoint(b[1]+b[3]/2,m),"m|"); gr->Line(mglPoint(0,m/2), mglPoint(a.nx-1,m/2),"h"); // parabolic approximation near maximum char func[128]; sprintf(func,"%g*(1-((x-%g)/%g)^2)",b[0],b[1],b[2]); gr->FPlot(func,"g"); }
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 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\nline 0 0 -1 $0 'r'\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; }
Опции команд 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,""); }
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.
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; }
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; }
MathGL have possibilities to write textual information into file with variable values. In MGL script you can use save command for that. However, the usual printf();
is simple in C/C++ code. For example, lets create some textual file
FILE *fp=fopen("test.txt","w"); fprintf(fp,"This is test: 0 -> 1 q\n"); fprintf(fp,"This is test: 1 -> -1 q\n"); fprintf(fp,"This is test: 2 -> 0 q\n"); fclose(fp);
It contents look like
This is test: 0 -> 1 q This is test: 1 -> -1 q This is test: 2 -> 0 q
Let assume now that you want to read this values (i.e. [[0,1],[1,-1],[2,0]]) from the file. You can use scanfile for that. The desired values was written using template "This is test: %g -> %g q\n". So, just use
mglData a; a.ScanFile("test.txt","This is test: %g -> %g");
and plot it to for assurance
gr->SetRanges(a.SubData(0), a.SubData(1)); gr->Axis(); gr->Plot(a.SubData(0),a.SubData(1),"o");
Note, I keep only the leading part of template (i.e. "This is test: %g -> %g" instead of "This is test: %g -> %g q\n"), because there is no important for us information after the second number in the line.
Sometimes output plots contain surfaces with a lot of points, and some vector primitives (like axis, text, curves, etc.). Using vector output formats (like EPS or SVG) will produce huge files with possible loss of smoothed lighting. Contrary, the bitmap output may cause the roughness of text and curves. Hopefully, MathGL have a possibility to combine bitmap output for surfaces and vector one for other primitives in the same EPS file, by using rasterize command.
The idea is to prepare part of picture with surfaces or other "heavy" plots and produce the background image from them by help of rasterize command. Next, we draw everything to be saved in vector form (text, curves, axis and etc.). Note, that you need to clear primitives (use clf command) after rasterize if you want to disable duplication of surfaces in output files (like EPS). Note, that some of output formats (like 3D ones, and TeX) don’t support the background bitmap, and use clf for them will cause the loss of part of picture.
The sample code is:
// first draw everything to be in bitmap output gr->FSurf("x^2+y^2", "#", "value 10"); gr->Rasterize(); // set above plots as bitmap background gr->Clf(); // clear primitives, to exclude them from file // now draw everything to be in vector output gr->Axis(); gr->Box(); // and save file gr->WriteFrame("fname.eps");
Проверьте, что точки графика находятся внутри ограничивающего параллелепипеда, при необходимости увеличьте его с помощью функции Axis()
. Проверьте, что размерность массива правильная для выбранного типа графика. Убедитесь, что функция Finish()
была вызвана после построения графика (или график был сохранен в файл). Иногда отражение света от плоских поверхностей (типа, Dens()
) может выглядеть как отсутствие графика.
Многие “новые” графики можно строить, используя уже существующие функции. Например, поверхность вращения кривой относительно оси можно построить, используя специальную функцию Torus()
, а можно построить как параметрически заданную поверхность Surf()
. См. также Hints и Примеры MathGL MathGL. Если же нужного типа графика все равно нет, то пишите мне e-mail и в следующей версии этот график появится.
Нет. Библиотека MathGL самодостаточна и не требует знания сторонних библиотек.
Ядро библиотеки написано на С++. Кроме него, есть интерфейсы для чистого С, фортрана, паскаля, форта и собственный командный язык MGL. Также есть поддержка большого числа интерпретируемых языков (Python, Java, ALLEGROCL, CHICKEN, Lisp, CFFI, C#, Guile, Lua, Modula 3, Mzscheme, Ocaml, Octave, Perl, PHP, Pike, R, Ruby, Tcl). Эти интерфейсы написаны с помощью SWIG (и функции чистого С и классы). Однако на данный момент только интерфейсы для Python и Octave включены в скрипты сборки. Причина в том, что я не знаю других языков, чтобы проверить качество интерфейса :(. Замечу, что большинство прочих языков могут использовать С функции напрямую.
Библиотеку MathGL можно использовать как есть с компилятором gfortran
поскольку он использует по умолчанию AT&T нотацию для внешних функций. Для других компиляторов (например, Visual Fortran) необходимо включить использование AT&T нотации вручную. AT&T нотация требует, чтобы имя функции завершалось символом ‘_’, аргументы функции передавались по указателю и длины строк передавались в конце списка аргументов. Например:
C функция – void mgl_fplot(HMGL graph, const char *fy, const char *stl, int n);
AT&T функция – void mgl_fplot_(uintptr_t *graph, const char *fy, const char *stl, int *n, int ly, int ls);
При использовании фортрана необходимо также включить библиотеку -lstdc++
. Кроме того, если библиотека была собрана с опцией enable-double=ON
(по умолчанию в версии 2.1 и более поздних), то все вещественные числа должны быть типа real*8
. Это можно включить по умолчанию опцией -fdefault-real-8
.
Функции-члены класса в С++ имеют “скрытый” параметр – указатель на экземпляр класса и их прямое использование невозможно. Решением будет определение интерфейсной функции:
int foo_draw(mglGraph *gr, void *par) { ((Foo *)foo)->draw(gr); }
и подстановка именно ее в вызов функции Window()
:
gr->Window(argc,argv,foo_draw,"Title",this);
Можно также наследовать Ваш класс от класса mglDraw
и использовать функцию типа gr->Window(argc, argv, foo, "Title");
.
Стандартный путь состоит в использовании кодировки UTF-8 для вывода текста. Кроме того, все функции вывода текста имеют интерфейс для 8-битных (char *) строк. Однако в последнем случае Вам может потребоваться установить используемую в исходном тексте локаль. Например, для русского языка в кодировке CP1251 можно использовать setlocale(LC_CTYPE, "ru_RU.cp1251");
(под MS Windows имена локали другие – setlocale(LC_CTYPE, "russian_russia.1251")
). Настоятельно не рекомендую использовать константу LC_ALL
, поскольку при этом меняется и формат чисел (в частности, десятичная точка), что может, например, вызвать сложности (неудобство) при написании формул и чтении текстовых файлов. Например, программа ожидает ‘,’ в качестве разделителя целой и дробной части, а пользователь вводит ‘.’.
Есть три основных способа. Во-первых, можно вырезать точку, задав одну из ее координат равной NAN
. Во-вторых, можно воспользоваться функцией SetCutBox()
или CutOff()
для удаления точек из некоторой области (see Обрезание). Наконец, можно сделать эти точки прозрачными (невидимыми) с помощью функций SurfA()
, Surf3A()
(see Парные графики). В последнем случае обеспечивается еще и плавность включения прозрачности.
Начиная с версии 2.0, рекомендуемый к использованию класс mglGraph (заголовочный файл #include <mgl2/mgl.h>
) содержbn только с inline
функции и может использоваться с любым компилятором без перекомпиляции бинарной версии библиотеки. Однако, если Вы планируете использовать низкоуровневые возможности (т.е. классы mglBase, mglCanvas и т.д.), то Вам следует перекомпилировать библиотеку MathGL с использованием Вашего компилятора.
Отмечу, что использование предоставляемых динамических библиотек *.dll требует создания библиотек импорта (import library *.lib). Эта процедура зависит от используемого компилятора – обратитесь к документации по Вашему компилятору. Например для VisualStudio это можно сделать командой lib.exe /DEF:libmgl.def /OUT:libmgl.lib
.
Простейший путь – использование комбинации CMake и MinGW. Также Вам может потребоваться дополнительные библиотеки, такие как GSL, PNG, JPEG и пр. Все они могут быть найдены на http://gnuwin32.sourceforge.net/packages.html. После установки всех компонент, просто запустите конфигуратор CMake и соберите MathGL командой make.
Следует создать отдельный поток для обработки сообщений в окно. Обновление данных в окне можно выполнить вызовом функции Update()
. Подробнее см. Animation.
Большую часть библиотеки написал один человек. Это результат примерно года работы на написание ядра библиотеки и базовых функций (в основном вечерами и по выходным). Процесс усовершенствования продолжается и теперь :). Скрипты сборки в основном написаны Д.Кулагиным, а экспорт в PRC/PDF написан М.Видассовым.
Можно импортировать ее в экземпляр mglData
и построить с помощью функции Dens()
. Например, для черно-белого рисунка можно использовать код: mglData bmp; bmp.Import("fname.png","wk"); gr->Dens(bmp,"wk");
.
Есть специальные классы (виджеты) для этих библиотек: QMathGL для Qt, Fl_MathGL для FLTK и т.д. Если Вы не нашли подходящий класс, то можете создать свой собственный виджет, рисующий растровое изображение из mglCanvas::GetBits().
Используйте функцию WritePRC
(), которая создаст PDF файл если MathGL был собран с enable-pdf=ON.
Используйте функцию WriteTEX
(), которая создаст LaTeX файлы с собственно рисунком ‘fname.tex’, с цветами MathGL ‘mglcolors.tex’ и основной файл ‘mglmain.tex’, который может использоваться для просмотра изображения и/или генерации PDF с помощью команды типа pdflatex mglmain.tex
.
Да, пример JavaScript файла находится в папке texinfo/ исходных текстов. Для его работы необходимо предоставить JSON данные с 3d изображением (можно создать с помощью WriteJSON
() функции). Скрипт позволяет выполнять базовые операции: приближение/удаление, вращение и сдвиг. Примеры использования JavaScript можно найти в http://mathgl.sf.net/json.html.
Во-первых, надо загрузить файлы отсюда или отсюда. Далее, в экземпляре mglGraph загружаем шрифты: gr->LoadFont(fontname,path);
. Здесь fontname – базовое имя шрифта, например ‘STIX’, и path – путь к папке с файлами шрифтов. Вызовите gr->RestoreFont();
для использования шрифта по умолчанию.
Просто используйте отрицательные значения длины меток, например gr->SetTickLen(-0.1);
.
Просто используйте Aspect(NAN,NAN)
для каждого подграфика, или в начале рисования.
Просто используйте код типа Clf("r{A5}");
или подготовьте PNG файл и задайте его в качестве фона рисунка LoadBackground("fname.png");
.
Простейший путь состоит в использовании стилей subplot. Однако, вы должны быть осторожны в изменении стиля subplot если вы планируете добавлять colorbar или вращать график – часть графика может стать невидимой.
Yes. Sometimes you may have huge surface and a small set of curves and/or text on the plot. You can use function rasterize just after making surface plot. This will put all plot to bitmap background. At this later plotting will be in vector format. For example, you can do something like following:
gr->Surf(x, y, z); gr->Rasterize(); // make surface as bitmap gr->Axis(); gr->WriteFrame("fname.eps");
MathGL поддерживает стандарт C99, в котором имя ‘I’ зарезервированно для мнимой единицы. Если Вам все таки нужно это имя для переменной, то поместите
#undef I
сразу после включения заголовочных файлов MathGL.
Вам следует сохранить каждый кадр в файл JPEG с именем типа ‘frame0001.jpg’, ‘frame0002.jpg’, ... Далее используйте ImageMagic для конвертации этих файлов в видео формата MPEG с помощью команды convert frame*.jpg movie.mpg
. См. также MPEG.
Возможности библиотеки MathGL довольно богаты – число только основных типов графиков превышает 50 видов. Кроме того, есть функции для обработки данных, настройки вида графика и пр. и пр. Тем не менее, я старался придерживаться единого стиля в порядке аргументов функций и способе их “настройки”. В основном все ниже сказанное относится к функциям рисования различных графиков.
Всего основных концепций (базисных идей) шесть:
SetQuality(MGL_DRAW_LMEM)
или quality 6
), так и векторные списки примитивов (по умолчанию). Дальнейшая судьба рисунков определяется пользователем: можно сохранить в файл, вывести на экран, создать анимацию/кино, дополнительно отредактировать и т.д. Такой подход обеспечивает высокую переносимость библиотеки – один и тот же программный код создаст в точности одинаковый рисунок на любой операционной системе. Кроме того, при таком подходе рисунки можно создавать непосредственно в консольной программе – графическое окно не нужно!
Кроме основных концепций я хотел бы остановиться на нескольких, как оказалось, нетривиальных моментах – способе указания положения графика, осей координат и строковых параметров линий, поверхностей, текста.
Представление системы координат в MathGL состоит из двух частей. Вначале координаты нормируются в диапазон изменения осей координат (see Настройки осей координат). Если флаг SetCut()
установлен, то точки вне интервала отбрасываются, в противном случае, они проецируются на ограничивающий параллелепипед (см. Обрезание). Кроме того, отбрасываются точки внутри границ, определенных переменными CutMinxCutMax и точки, для которых значение функции CutOff
() не равно нулю. После этого формулы перехода в криволинейную систему координат SetFunc()
применяются к каждой точке. Наконец, точка данных отображается с помощью одной из графических функций.
Диапазон изменения x, y, z-координат задается функциями SetRange()
или ranges. Точка пересечения осей координат задается функцией SetOrigin()
. При этом можно использовать NAN значения для автоматического выбора положения оси.
Кроме привычных осей x, y, z есть еще одна ось – цветовая шкала – ось c. Она используется при окрашивании поверхностей и задает границы изменения функции при окрашивании. Ее границы автоматически устанавливаются равными диапазону z-оси при вызове ranges. Возможно и ручное изменение границ цветового интервала посредством вызова SetRange('c', ...)
. Используйте colorbar для отображения цветовой шкалы.
Вид меток по осям определяется функцией SetTicks()
(see Метки осей). Функция SetTuneTicks включает/выключает выделение общего множителя (большого или малого факторов в диапазоне) для меток осей координат. Наконец, если стандартный вид меток не устраивает пользователя, то их шаблон можно задать явно (можно использовать и ТеХ символы), воспользовавшись функцией SetTickTempl()
. Кроме того, в качестве меток можно вывести произвольный текст использовав функцию SetTicksVal()
.
Base colors are defined by one of symbol ‘wkrgbcymhRGBCYMHWlenupqLENUPQ’.
Символы цвета: ‘k’ – черный, ‘r’ – красный, ‘R’ – темно красный, ‘g’ – зеленый, ‘G’ – темно зеленый, ‘b’ – синий, ‘B’ – темно синий, ‘c’ – голубой, ‘C’ – темно голубой, ‘m’ – пурпурный, ‘M’ – темно пурпурный, ‘y’ – желтый, ‘Y’ – темно желтый (золотой), ‘h’ – серый, ‘H’ – темно серый, ‘w’ – белый, ‘W’ – светло серый, ‘l’ – сине-зеленый, ‘L’ – темно сине-зеленый, ‘e’ – желто-зеленый, ‘E’ – темно желто-зеленый, ‘n’ – небесно-синий, ‘N’ – темно небесно-синий, ‘u’ – сине-фиолетовый, ‘U’ – темно сине-фиолетовый, ‘p’ – фиолетовый, ‘P’ – темно фиолетовый, ‘q’ – оранжевый, ‘Q’ – темно оранжевый (коричневый).
В цветовой схеме можно использовать тональные (“подсвеченные”) цвета. Тональный цвет задается двумя символами в фигурных скобках ‘{cN}’: первый – обычный цвет, второй – его яркость цифрой. Цифра может быть в диапазоне ‘1’...‘9’. При этом ‘5’ соответствует нормальному цвету, ‘1’ – очень темная версия цвета (почти черный), ‘9’ – очень светлая версия цвета (почти белый). Например, цвета могут быть ‘{b2}’ ‘{b7}’ ‘{r7}’ и т.д.
Наконец, можно указать явно RGB или RGBA значения цвета, используя формат ‘{xRRGGBB}’ или ‘{xRRGGBBAA}’ соответственно. Например, ‘{xFF9966}’ даст цвет дыни.
Стиль линии задается строкой, которая может содержать символ цвета (‘wkrgbcymhRGBCYMHWlenupqLENUPQ’), тип пунктира (‘-|;:ji’ или пробел), ширину линии (‘0123456789’) и тип маркера (‘o+xsd.^v’ и модификатор ‘#’). Если пропущен цвет или тип пунктира, то используется значение по умолчанию с последним указанным цветом или значение из палитры (для see 1D графики). По умолчанию палитры содержит следующие цвета: темно серый ‘H’, синий ‘b’, зеленый ‘g’, красный ‘r’, голубой ‘c’, пурпурный ‘m’, yellow ‘y’, серый ‘h’, сине-зеленый ‘l’, небесно-синий ‘n’, оранжевый ‘q’, желто-зеленый ‘e’, сине-фиолетовый ‘u’, фиолетовый ‘p’.
Тип пунктира: пробел – нет линии (для рисования только маркеров), ‘-’ – сплошная линия (■■■■■■■■■■■■■■■■), ‘|’ – длинный пунктир (■■■■■■■■□□□□□□□□), ‘;’ – пунктир (■■■■□□□□■■■■□□□□), ‘=’ – короткий пунктир (■■□□■■□□■■□□■■□□), ‘:’ – точки (■□□□■□□□■□□□■□□□), ‘j’ – пунктир с точками (■■■■■■■□□□□■□□□□), ‘i’ – мелкий пунктир с точками (■■■□□■□□■■■□□■□□), ‘{dNNNN}’ – заданный вручную стиль (для v.2.3 и поздних, например ‘{df090}’ для (■■■■□□□□■□□■□□□□)).
Типы маркеров: ‘o’ – окружность, ‘+’ – крест, ‘x’ – косой крест, ‘s’ – квадрат, ‘d’ - ромб, ‘.’ – точка, ‘^’ – треугольник вверх, ‘v’ – треугольник вниз, ‘<’ – треугольник влево, ‘>’ – треугольник вправо, ‘#*’ – знак Y, ‘#+’ – крест в квадрате, ‘#x’ – косой крест в квадрате, ‘#.’ – точка в окружности. Если в строке присутствует символ ‘#’, то используются символы с заполнением.
Вы можете определить собственные символы (см. addsymbol) для рисования маркеров при использовании стиля ‘&’. В частности, ‘&*’, ‘&o’, ‘&+’, ‘&x’, ‘&s’, ‘&d’, ‘&.’, ‘&^’, ‘&v’, ‘&<’, ‘&>’ нарисует определенный пользователем символ с именем ‘*o+xsd.^v<>’ соответственно; и
‘&#o’, ‘&#+’, ‘&#x’, ‘&#s’, ‘&#d’, ‘&#.’, ‘&#^’, ‘&#v’, ‘&#<’, ‘&#>’ нарисует определенный пользователем символ с именем ‘YOPXSDCTVLR’ соответственно. Замечу, что будет нарисован только контур определенного пользователем символа если задан отрицательный размер маркера (см. marksize или опцию size
в Опции команд).
На конце и в начале линии можно выводить специальный символ (стрелку), если в строке указать один из символов: ‘A’ – стрелка наружу, ‘V’ – стрелка внутрь, ‘I’ – поперечная черта, ‘K’ – стрелка с чертой, ‘T’ – треугольник, ‘S’ – квадрат, ‘D’ – ромб, ‘O’ – круг, ‘X’ – косой крест, ‘_’ – нет стрелки (по умолчанию). При этом действует следующее правило: первый символ определяет стрелку на конце линии, второй символ – стрелку в начале линии. Например, ‘r-A’ – красная сплошная линия со стрелкой на конце, ‘b|AI’ – синий пунктир со стрелкой на конце и чертой вначале, ‘_O’ – линия с текущим стилем и кружком вначале. Эти стили действуют и при построении графиков (например, 1D графики).
Цветовая схема используется для определения цвета поверхностей, линий уровня и пр. Цветовая схема задается строкой s, которая содержит символы цвета (see Стиль линий) или символы ‘#:|’. Символ ‘#’ переключает рисование поверхности на сетчатое (для трехмерных поверхностей) или включает рисование сетки на поверхности. Символ ‘|’ отключает интерполяцию цвета в цветовой схеме. Это может быть полезно для “резких” цветов, например, при рисовании матриц. Если в строке встречается символ ‘:’, то он принудительно заканчивает разбор строки для стиля поверхности. После этого символа могут идти описание стиля текста или оси вращения кривой/линий уровня. Цветовая схема может содержать до 32 значений цвета.
При определении цвета по амплитуде (наиболее часто используется) окончательный цвет определяется путем линейной интерполяции массива цветов. Массив цветов формируется из цветов, указанных в строке спецификации. Аргумент – амплитуда, нормированная на диапазон изменения цвета (см. Настройки осей координат). Например, строка из 4 символов ‘bcyr’ соответствует изменению цвета от синего (минимальное значение) через голубой и желтый (промежуточные значения) к красному (максимальное значение). Строка ‘kw’ соответствует изменению цвета от черного (минимальное значение) к белому (максимальное значение). Строка из одного символа (например, ‘g’) соответствует однотонному цвету (в данному случае зеленому).
Специальная двуосная цветовая схема (как в графике map) задается символом ‘%’. В ней второе направление (прозрачность) используется как вторая координата для цвета. При этом можно указать до 4 цветов для углов: {c1,a1}, {c2,a1}, {c1,a2}, {c2,a2}. Здесь диапазоны цвета и прозрачности равны {c1,c2} и {a1,a2}. Если указано меньше 4 цветов, то черный используется для угла {c1,a1}. Если задано только 2 цвета, то их сумма используется для угла {c2,a2}.
Есть несколько полезных цветовых схем. Строка ‘kw’ дает обычную серую (черно-белую) схему, когда большие значения светлее. Строка ‘wk’ представляет обратную серую схему, когда большие значения темнее. Строки ‘kRryw’, ‘kGgw’, ‘kBbcw’ представляют собой хорошо известные схемы hot, summer и winter. Строки ‘BbwrR’ и ‘bBkRr’ позволяют рисовать двухцветные фигуры на белом или черном фоне, когда отрицательные значения показаны синим цветом, а положительные – красным. Строка ‘BbcyrR’ дает цветовую схему, близкую к хорошо известной схеме jet.
Для более точно раскрашивания поверхностей можно изменить равномерное (по умолчанию) положение цветов в цветовой схеме. Формат следующий: ‘{CN,pos}’, ‘{CN,pos}’ или ‘{xRRGGBB,pos}’. Здесь значение pos положения цвета должно быть в диапазоне [0, 1]. Отмечу, что альтернативным механизмом тонкой настройки цветовой схемы может служить использование формул для цветовой координаты (см. Криволинейные координаты).
При определении цвета по положению точки в пространстве (используется в map) окончательный цвет определяется по формуле c=x*c[1] + y*c[2]. Здесь c[1], c[2] – первые три цвета в цветовом массиве; x, y – координаты точки, нормированные в диапазон изменения осей координат.
Дополнительно, MathGL может наложить маску при закраске граней для создания растрового изображения. Тип маски задается одним из символов ‘-+=;oOsS~<>jdD*^’ в цветовой схеме. Маску можно повернуть на произвольный угол командой mask или на один из улов +45, -45 или 90 градусов, используя символы ‘\/I’ соответственно. Примеры масок по умолчанию показаны на рисунке ниже.
Однако, вы можете задать собственную маску (как матрицу 8*8) для любого из этих символов, используя второй аргумент команды mask. Например, маска на правом нижнем подрисунке получается кодом
gr->SetMask('+', "ff00182424f80000"); gr->Dens(a,"3+");
или использовать явное задание маски (для v.2.3 и более поздних)
gr->Dens(a,"3{s00ff00182424f800}");
Стиль текста задается строкой, которая может содержать цвет текста ‘wkrgbcymhRGBCYMHW’ (см. Цвета), а также тип шрифта (‘ribwou’) и/или выравнивания (‘LRC’) после символа ‘:’. Например, ‘r:iCb’ соответствует жирному (‘b’) курсиву (‘i’) с выравниванием по центру (‘C’ красного цвета (‘r’). Начиная с MathGL версии 2.3, вы можете использовать не только один цвет для всего текста, но и задать цветовой градиент для выводимой строки (см. Цветовая схема).
Начертания шрифта: ‘r’ – прямой шрифт, ‘i’ – курсив, ‘b’ – жирный. По умолчанию используется прямой шрифт. Типы выравнивания текста: ‘L’ – по левому краю (по умолчанию), ‘C’ – по центру, ‘R’ – по правому краю, ‘T’ – под текстом, ‘V’ – по центру вертикально. Дополнительные эффекты шрифта: ‘w’ – контурный, ‘o’ – надчеркнутый, ‘u’ – подчеркнутый.
Синтаксический разбор LaTeX-их команд по умолчанию включен. Это команды смены стиля текста (например, \b для жирного текста): \a или \overline – надчеркивание, \b или \textbf – жирный, \i или \textit – курсив, \r или \textrm – прямой (отменяет стили жирного и курсива), \u или \underline – подчеркнутый, \w или \wire – контурный, \big – большего размера, @ – меньшего размера. Нижний и верхний индексы задаются символами ‘_’ и ‘^’. При этом изменение стиля применяется только к следующему символу или к символам в фигурных скобках {}, которые понимаются как единый блок. Например, сравните строки ‘sin (x^{2^3})’ и ‘sin (x^2^3)’. Можно также менять цвет текста внутри строки с помощью команд #? или \color?, где ‘?’ – символ цвета (see Стиль линий). Например, слова ‘Blue’ и ‘red’ будут окрашены в соответствующий цвет в строке ‘#b{Blue} and \colorr{red} text’. Большинство функций понимает символ новой строки ‘\n’ и позволяет выводить много строчный текст. Наконец, можно использовать символы с произвольным UTF кодом с помощью команды \utf0x????
. Например, \utf0x3b1
даст символ
α.
Распознаются также большинство символов TeX и AMSTeX, команды смены стиля текста (\textrm, \textbf, \textit, \textsc, \overline, \underline), акценты (\hat, \tilde, \dot, \ddot, \acute, \check, \grave, \bar, \breve) и корни (\sqrt, \sqrt3, \sqrt4). Полный список содержит около 2000 символов. Отмечу, что первый пробел (пробел, табуляция и пр.) после команды игнорируется, а все остальные пробелы печатаются обычным образом. Например, следующие строки дают одинаковый результат \tilde a: ‘\tilde{a}’; ‘\tilde a’; ‘\tilde{}a’.
В частности, распознаются греческие буквы: α – \alpha, β – \beta, γ – \gamma, δ – \delta, ε – \epsilon, η – \eta, ι – \iota, χ – \chi, κ – \kappa, λ – \lambda, μ – \mu, ν – \nu, o – \o, ω – \omega, ϕ – \phi, π – \pi, ψ – \psi, ρ – \rho, σ – \sigma, θ – \theta, τ – \tau, υ – \upsilon, ξ – \xi, ζ – \zeta, ς – \varsigma, ɛ – \varepsilon, ϑ – \vartheta, φ – \varphi, ϰ – \varkappa; A – \Alpha, B – \Beta, Γ – \Gamma, Δ – \Delta, E – \Epsilon, H – \Eta, I – \Iota, C – \Chi, K – \Kappa, Λ – \Lambda, M – \Mu, N – \Nu, O – \O, Ω – \Omega, Φ – \Phi, Π – \Pi, Ψ – \Psi, R – \Rho, Σ – \Sigma, Θ – \Theta, T – \Tau, Υ – \Upsilon, Ξ – \Xi, Z – \Zeta.Еще примеры наиболее общеупотребительных TeX-их символов: ∠ – \angle, ⋅ – \cdot, ♣ – \clubsuit, ✓ – \checkmark, ∪ – \cup, ∩ – \cap, ♢ – \diamondsuit, ◇ – \diamond, ÷ – \div, ↓ – \downarrow, † – \dag, ‡ – \ddag, ≡ – \equiv, ∃ – \exists, ⌢ – \frown, ♭ – \flat, ≥ – \ge, ≥ – \geq, ≧ – \geqq, ← – \gets, ♡ – \heartsuit, ∞ – \infty, ∫ – \int, \Int, ℑ – \Im, ♢ – \lozenge, ⟨ – \langle, ≤ – \le, ≤ – \leq, ≦ – \leqq, ← – \leftarrow, ∓ – \mp, ∇ – \nabla, ≠ – \ne, ≠ – \neq, ♮ – \natural, ∮ – \oint, ⊙ – \odot, ⊕ – \oplus, ∂ – \partial, ∥ – \parallel, ⊥ –\perp, ± – \pm, ∝ – \propto, ∏ – \prod, ℜ – \Re, → – \rightarrow, ⟩ – \rangle, ♠ – \spadesuit, ~ – \sim, ⌣ – \smile, ⊂ – \subset, ⊃ – \supset, √ – \sqrt or \surd, § – \S, ♯ – \sharp, ∑ – \sum, × – \times, → – \to, ∴ – \therefore, ↑ – \uparrow, ℘ – \wp.
Размер текста может быть задан явно (если size>0) или относительно базового размера шрифта для рисунка |size|*FontSize при size<0. Значение size=0 указывает, что соответствующая строка выводиться не будет. Базовый размер шрифта измеряется во внутренних единицах. Специальные функции SetFontSizePT(), SetFontSizeCM(), SetFontSizeIN()
позволяют задавать его в более “привычных” единицах.
MathGL имеет быстрый парсер текстовых формул (see Вычисление выражений) , понимающий большое число функций и операций. Базовые операции: ‘+’ – сложение, ‘-’ – вычитание, ‘*’ – умножение, ‘/’ – деление, ‘%’ – остаток от деления, ‘^’ – возведение в целосичленную степень. Также есть логические операции: ‘<’ – истина если if x<y, ‘>’ – истина если x>y, ‘=’ – истина если x=y, ‘&’ – истина если x и y оба не равны нулю, ‘|’ – истина если x или y не нуль. Логические операции имеют наинизший приоритет и возвращают 1 если истина или 0 если ложно.
Базовые функции: ‘sqrt(x)’ – квадратный корень из x, ‘pow(x,y)’ – x в степени y, ‘ln(x)’ – натуральный логарифм x, ‘lg(x)’ – десятичный логарифм x, ‘log(a,x)’ – логарифм по основанию a от x, ‘abs(x)’ – модуль x, ‘sign(x)’ – знак x, ‘mod(x,y)’ – остаток от деления x на y, ‘step(x)’ – ступенчатая функция, ‘int(x)’ – целая часть x, ‘rnd’ – случайное число, ‘random(x)’ – матрица случайный чисел размером как x, ‘hypot(x,y)’=sqrt(x^2+y^2) – гипотенуза, ‘cmplx(x,y)’=x+i*y – комплексное число, ‘pi’ – число π = 3.1415926…, inf=∞
Функции для работы с комплексными числами ‘real(x)’, ‘imag(x)’, ‘abs(x)’, ‘arg(x)’, ‘conj(x)’.
Тригонометрические функции: ‘sin(x)’, ‘cos(x)’, ‘tan(x)’ (или ‘tg(x)’). Обратные тригонометрические функции: ‘asin(x)’, ‘acos(x)’, ‘atan(x)’. Гиперболические функции: ‘sinh(x)’ (или ‘sh(x)’), ‘cosh(x)’ (или ‘ch(x)’), ‘tanh(x)’ (или ‘th(x)’). Обратные гиперболические функции: ‘asinh(x)’, ‘acosh(x)’, ‘atanh(x)’.
Специальные функции: ‘gamma(x)’ – гамма функция Γ(x) = ∫0∞ tx-1 exp(-t) dt, ‘gamma_inc(x,y)’ – неполная гамма функция Γ(x,y) = ∫y∞ tx-1 exp(-t) dt, ‘psi(x)’ – дигамма функция ψ(x) = Γ′(x)/Γ(x) для x≠0, ‘ai(x)’ – Эйри функция Ai(x), ‘bi(x)’ – Эйри функция Bi(x), ‘cl(x)’ – функция Клаузена, ‘li2(x)’ (или ‘dilog(x)’) – дилогарифм Li2(x) = -ℜ∫0xds log(1-s)/s, ‘sinc(x)’ – функция sinc(x) = sin(πx)/(πx) для любых x, ‘zeta(x)’ – зета функция Римана ζ(s) = ∑k=1∞k-s для s≠1, ‘eta(x)’ – эта функция η(s) = (1 - 21-s)ζ(s) для произвольного s, ‘lp(l,x)’ – полином Лежандра Pl(x), (|x|≤1, l≥0), ‘w0(x)’, ‘w1(x)’ – функции Ламберта W. Функции W(x) определены как решение уравнения: W exp(W) = x.
Экспоненциальные интегралы: ‘ci(x)’ – cos-интеграл Ci(x) = ∫0xdt cos(t)/t, ‘si(x)’ – sin-интеграл Si(x) = ∫0xdt sin(t)/t, ‘erf(x)’ – функция ошибки erf(x) = (2/√π) ∫0xdt exp(-t2) , ‘ei(x)’ – интеграл Ei(x) = -PV(∫-x∞dt exp(-t)/t) (где PV обозначает главное значение), ‘e1(x)’ – интеграл E1(x) = ℜ∫1∞dt exp(-xt)/t, ‘e2(x)’ – интеграл E2(x) = ℜ∫1∞dt exp(-xt)/t2, ‘ei3(x)’ – интеграл Ei3(x) = ∫0xdt exp(-t3) для x≥0.
Функции Бесселя: ‘j(nu,x)’ – функция Бесселя первого рода, ‘y(nu,x)’ – функция Бесселя второго рода, ‘i(nu,x)’ – модифицированная функция Бесселя первого рода, ‘k(nu,x)’ – модифицированная функция Бесселя второго рода.
Эллиптические интегралы: ‘ee(k)’ – полный эллиптический интеграл E(k) = E(π/2,k), ‘ek(k)’ – полный эллиптический интеграл K(k) = F(π/2,k), ‘e(phi,k)’ – эллиптический интеграл E(φ,k) = ∫0φdt √(1 - k2sin2(t)), ‘f(phi,k)’ – эллиптический интеграл F(φ,k) = ∫0φdt 1/√(1 - k2sin2(t))
Функции Якоби: ‘sn(u,m)’, ‘cn(u,m)’, ‘dn(u,m)’, ‘sc(u,m)’, ‘sd(u,m)’, ‘ns(u,m)’, ‘cs(u,m)’, ‘cd(u,m)’, ‘nc(u,m)’, ‘ds(u,m)’, ‘dc(u,m)’, ‘nd(u,m)’.
Некоторые из функций могут быть недоступны если не была включена поддержка GSL при компиляции библиотеки MathGL.
При разборе формул нет различия между верхним и нижним регистром. Если аргумент лежит вне области определения функции, то возвращается NaN.
MathGL версии 2.5 позволяет использовать пользовательские функции fn1()...fn9() при вычислении формул, определенные после символа(ов) ’\’. Например, "fn1(3)\x^_1" даст "x^3". Кроме того, добавлены функции ’sum’, ’dsum’, ’prod’ для вычисления сумм, сумм с переменным знаком и произведений в формулах. Например, "sum(_i^2,5)" даст "30"=0+1^2+2^2+3^2+4^2, "dsum(_i^2,5)" даст "10"=0-1^2+2^2-3^2+4^2, и "prod(1+_i,5)" даст 5!="120". Вызовы суммирования и произведения можно делать вложенными, используя переменные _i,_j,...,_z. Например, "sum(sum(_j+_i^2,5),5)" даст "200". Кроме того, в аргументах можно использовать и пользовательские функции. Например, "sum(fn1(_i)-fn2(_i),4)\_1^4\_1^3" эквивалентно "sum(_i^4-_i^3,4)" и даст "62".
Опции команд позволяют легко настроить вид отдельного графика не меняя глобальных настроек для все рисунка. Каждая опция отделяется от предыдущей символом ‘;’. Опции работают так, что запоминают текущие настройки рисунка, применяют собственные настройки, выполняют команду и возвращают глобальные настройки обратно. Поэтому использование опций для команд обработки данных или настройки графика бесполезно.
Наиболее часто используемые опции – xrange, yrange, zrange
, устанавливают границы изменения осей координат (и тем самым автоматических массивов). Например, команда Plot(y,"","xrange 0.1 0.9");
или plot y; xrange 0.1 0.9
построит кривую с x-координатой равно распределенной в интервале 0.1 ... 0.9, а не вдоль текущей оси x. См. раздел Using options, для примеров кода и графика.
val
¶Задает величину прозрачности поверхности. Значение должно быть в диапазоне [0, 1]. См. также alphadef
val
¶Задает яркость фонового освещения. Значение должно быть в диапазоне [0, 1]. См. также ambient
val
¶Задает яркость диффузного освещения для поверхности. Значение должно быть в диапазоне [0, 1]. См. также diffuse.
val
¶Задает размер текста, маркеров и стрелок. См. также font, marksize, arrowsize.
Добавляет строку ’txt’ во внутренний массив записей легенды. Стиль линии и маркера аргумента последней вызванной команды построения 1D графики. См. также legend
val
¶Задает значение, которое будет использовано как дополнительный числовой параметр при построении графика.
Библиотека MathGL имеет интерфейсы к ряду языков программирования. Большинство из них основано на С интерфейсе с использованием SWIG. Это Python, Java, Octave, Lisp, C#, Guile, Lua, Modula 3, Ocaml, Perl, PHP, Pike, R, Ruby, и Tcl интерфейсы. Также есть Fortran интерфейс, который имеет схожий набор функций, но слегка различающиеся типы аргументов (целые вместо указателей). Эти функции отмечены как [C function].
Некоторые языки поддерживают классы (подобно C++ или Python). Имена функций для них такие же как в С++ (см. Ядро MathGL и Обработка данных) и отмечены, например, так [Method on mglGraph].
Наконец, специальный командный язык MGL (см. Скрипты MGL) был создан для быстрого доступа к функциям рисования. Соответствующие скрипты могут быть выполнены самостоятельно (с помощью UDAV, mglconv, mglview и т.д.) или из программы на языке C/C++/Python/... (см. mglParse class).
C интерфейс – основа для многих других интерфейсов. Он содержит функции С для всех методов MathGL. В отличие от C++ классов, C функции содержат обязательный(ые) аргумент(ы) типа HMGL (для графики) и/или HCDT/HMDT/HADT (для массивов данных), который указывают на объект для рисования или изменения. Поэтому перед использованием их необходимо создать с помощью функции mgl_create_*()
, и удалить после использования (или в конце программы) с помощью функции mgl_delete_*()
.
Все C функции описаны в заголовочном файле #include <mgl2/mgl_cf.h>
и используют переменные следующих типов:
HMGL
— Указатель на класс mglGraph
(см. Ядро MathGL).
HCDT
— Указатель на класс const mglDataA
(см. Обработка данных) — неизменяемые массивы данных.
HMDT
— Указатель на класс mglData
(см. Обработка данных) — массивы данных с действительными числами.
HADT
— Указатель на класс mglDataC
(см. Обработка данных) — массивы данных с комплексными числами.
HMPR
— Указатель на класс mglParse
(см. mglParse class) — выполнение MGL скриптов.
HMEX
— Указатель на класс mglExpr
(см. Вычисление выражений) — текстовые формулы для действительных чисел.
HMAX
— Указатель на класс mglExprC
(см. Вычисление выражений) — текстовые формулы для комплексных чисел.
Фортрановские функции и подпрограммы имеют такие же имена как функции С. Однако есть отличие. Переменные типов HMGL, HCDT, HMDT, ...
должны быть целыми с достаточной разрядностью (integer*4
для 32-битной операционной системы или integer*8
для 64-битной). Все C функции типа void
— подпрограммы на Фортране и должны вызываться оператором call
. Прочие функции, возвращающие тип HMGL
или HMDT
и т.п. должны быть объявлены в Фортране как возвращающие целое нужной разрядности. Также необходимо иметь в виду, что строки в Фортране отделяются символом '
, а не "
.
MathGL имеет интерфейс на основе классов (объектов с членами-функциями) с использованием библиотеки SWIG. Типичный пример – Python, имя которого использовано в заголовке раздела. В точности те же классы используются и в C++ API. Отмечу, что С++ классы содержат только inline члены-функции, что делает С++ API независимым от компилятора даже для бинарной версии.
Есть 3 основных класса:
mglGraph
– обеспечивает вывод графики (см. Ядро MathGL).
mglData
– обеспечивает обработку данных (см. Обработка данных). Класс имеет возможность прямого доступа к данным с помощью конструкции вида: dat[i]=sth;
или sth=dat[i]
, где используется "плоское" представление данных (т.е., i может быть в диапазоне 0...nx*nx*nz-1). Также можно импортировать массивы NumPy в Python: mgl_dat = mglData(numpy_dat);
.
mglParse
– обеспечивает выполнение скриптов MGL (см. Скрипты MGL).
Для использования в Python достаточно выполнить ‘import mathgl’. Простейший пример имеет вид:
import mathgl a=mathgl.mglGraph() a.Box() a.WritePNG("test.png")
Также можно импортировать все классы из модуля mathgl
и обеспечить более легкий доступ к MathGL:
from mathgl import * a=mglGraph() a.Box() a.WritePNG("test.png")
Это становится более полезным если, например, вы создаете много объектов данных mglData
.
Основным классом MathGL является класс mglGraph, определённый в #include <mgl2/mgl.h>
. Он включает в себя множество функций для построения графиков от 1D, 2D и 3D массивов. Он также содержит функции вывода текста и построения осей координат. Есть возможность построения в произвольной системе координат, которая задается строковыми формулами. Все графические функции используют класс mglData (см. Обработка данных) для хранения массивов данных. Это позволяет легко контролировать размеры, работу с памятью и производить обработку данных. Дополнительная информация о цветах, шрифтах, вычисления формул может быть найдена в Основные принципы и Other classes.
Некоторые возможности MathGL доступны только в новых версиях библиотеки. Для проверки текущей версии MathGL можно использовать следующую функцию.
'ver'
¶mglGraph
: bool
CheckVersion (const char *
ver) static
¶int
mgl_check_version (const char *
ver)
¶Возвращает нулевое значение если версия MathGL подходит для требуемой в ver, т.е. если номер основной версии совпадает и "подверсия" больше или равна указанной в ver.
mglGraph
: mglGraph (int
kind=0
, int
width=600
, int
height=400
)
¶mglGraph
: mglGraph (const mglGraph &
gr)
¶mglGraph
: mglGraph (HMGL
gr)
¶HMGL
mgl_create_graph (int
width, int
height)
¶HMGL
mgl_create_graph_gl ()
¶Создает (или использует созданный) экземпляр класса, производного от mglGraph
(тип HMGL
) с указанными размерами width и height. Параметр kind может иметь следующие значения: ‘0’ – использовать рисование по умолчанию, ‘1’ – использовать рисование в OpenGL.
mglGraph
: ~mglGraph ()
¶HMGL
mgl_delete_graph (HMGL
gr)
¶Удаляет экземпляр класса mglGraph.
mglGraph
: HMGL
Self ()
¶Возвращает указатель на используемый объект типа HMGL
.
HMGL
mgl_default_graph ()
¶Возвращает указатель на экземпляр класса mglGraph. Этот объект используется по умолчанию при создании нового класса с целью сохранения настроек и ускорения инициализации в различных графиках.
Функции и переменные в этой группе влияют на вид всего рисунка. Соответственно они должны располагаться перед вызовом функций непосредственно рисующих графики.
mglGraph
: void
DefaultPlotParam ()
¶void
mgl_set_def_param (HMGL
gr)
¶Устанавливает все настройки по умолчанию и очищает рисунок.
val flag
¶mglGraph
: void
SetFlagAdv (int
val, uint32_t
flag)
¶void
mgl_set_flag (HMGL
gr, int
val, uint32_t
flag)
¶Устанавливает значение бинарного флага flag в val. Список флагов можно найти в define.h. Текущий список флагов:
#define MGL_ENABLE_CUT 0x00000004 ///< Определяет способ рисования точек вне диапазона осей координат #define MGL_ENABLE_RTEXT 0x00000008 ///< Использовать вращение текста #define MGL_AUTO_FACTOR 0x00000010 ///< Разрешить автоматическое масштабирование графика #define MGL_ENABLE_ALPHA 0x00000020 ///< Использовать прозрачность #define MGL_ENABLE_LIGHT 0x00000040 ///< Использовать освещение #define MGL_TICKS_ROTATE 0x00000080 ///< Разрешить вращение меток осей #define MGL_TICKS_SKIP 0x00000100 ///< Разрешить пропуск меток осей #define MGL_DISABLE_SCALE 0x00000200 ///< Временный флаг, запрещающий изменение размеров #define MGL_FINISHED 0x00000400 ///< Флаг готовности окончательной картинки (т.е. mglCanvas::G) #define MGL_USE_GMTIME 0x00000800 ///< Использовать gmtime вместо localtime #define MGL_SHOW_POS 0x00001000 ///< Включить показ координат щелчка мыши #define MGL_CLF_ON_UPD 0x00002000 ///< Очищать график перед Update() #define MGL_NOSUBTICKS 0x00004000 ///< Запретить рисование subticks для bounding box #define MGL_LOCAL_LIGHT 0x00008000 ///< Сохранять источники освещения в каждом inplot #define MGL_VECT_FRAME 0x00010000 ///< Использовать DrwDat для сохранения всех данных в кадрах #define MGL_REDUCEACC 0x00020000 ///< Сокращать точность вывода точек (для уменьшения размера выходных файлов) #define MGL_PREFERVC 0x00040000 ///< Предпочитать цвета вершин вместо текстур если выходной формат поддерживает #define MGL_ONESIDED 0x00080000 ///< Выводить только переднюю сторону поверхностей если выходной формат поддерживает #define MGL_NO_ORIGIN 0x00100000 ///< Не рисовать метки в точке пересечения осей #define MGL_GRAY_MODE 0x00200000 ///< Преобразовать все цвета в оттенки серого #define MGL_FULL_CURV 0x00400000 ///< Запретить пропуск точек на прямолинейных участках #define MGL_NO_SCALE_REL 0x00800000 ///< Запретить изменение размера текста в относительных inplots
void
mgl_bsize (unsigned
bsize)
¶Задает размер буфера под примитивы как (1<<bsize)^2. Т.е. как 10^12 для bsize=20 или 4*10^9 для bsize=16 (по умолчанию). ВАЖНО: можно устанавливать только один раз вначале, до построения графиков. Возвращает текущее значение.
Эти функции и переменные настраивают тип и степень прозрачности поверхностей. Главной является функция alpha, которая включает/выключает прозрачность для всего графика. Функция alphadef устанавливает величину alpha-канала по умолчанию. Наконец, функция transptype задает тип прозрачности. См. раздел Transparency and lighting, для примеров кода и графика.
[val=on]
¶mglGraph
: void
Alpha (bool
enable)
¶void
mgl_set_alpha (HMGL
gr, int
enable)
¶Включает/выключает прозрачность и возвращает свое предыдущее состояние. По умолчанию прозрачность выключена. Функция включает прозрачность для всего рисунка.
val
¶mglGraph
: void
SetAlphaDef (mreal
val)
¶void
mgl_set_alpha_default (HMGL
gr, mreal
alpha)
¶Задает значение прозрачности по умолчанию для всех графиков. Значение по умолчанию 0.5.
val
¶mglGraph
: void
SetTranspType (int
type)
¶void
mgl_set_transp_type (HMGL
gr, int
type)
¶Задает тип прозрачности. Допустимые значения:
SetAlphaDef(0.3)
или меньше в этом случае).
См. раздел Types of transparency, для примеров кода и графика.
Эти функции настраивают освещение графика. Главная функция light включает/выключает освещение графиков построенных после ее вызова (в OpenGL работает сразу для всего рисунка). MathGL поддерживает до 10 независимых источников света. Но в режиме OpenGL можно использовать только первые 8 из них. Положение, цвет, яркость каждого источника света можно задавать по отдельности. По умолчанию включен только первый (с порядковым номером 0
) источник света белого цвета, расположенный сверху. См. раздел Lighting sample, для примеров кода и графика.
[val=on]
¶mglGraph
: bool
Light (bool
enable)
¶void
mgl_set_light (HMGL
gr, int
enable)
¶Включает/выключает освещение графика и возвращает предыдущее состояние. По умолчанию освещение выключено.
num
val
¶mglGraph
: void
Light (int
n, bool
enable)
¶void
mgl_set_light_n (HMGL
gr, int
n, int
enable)
¶Включает/выключает n-ый источник света.
num xdir ydir zdir
['col'='w' br=0.5 ap=0
]
¶num xdir ydir zdir xpos ypos zpos
['col'='w' br=0.5
]
¶mglGraph
: void
AddLight (int
n, mglPoint
d, char
c='w'
, mreal
bright=0.5
, mreal
ap=0
)
¶mglGraph
: void
AddLight (int
n, mglPoint
r, mglPoint
d, char
c='w'
, mreal
bright=0.5
, mreal
ap=0
)
¶void
mgl_add_light (HMGL
gr, int
n, mreal
dx, mreal
dy, mreal
dz)
¶void
mgl_add_light_ext (HMGL
gr, int
n, mreal
dx, mreal
dy, mreal
dz, char
c, mreal
bright, mreal
ap)
¶void
mgl_add_light_loc (HMGL
gr, int
n, mreal
rx, mreal
ry, mreal
rz, mreal
dx, mreal
dy, mreal
dz, char
c, mreal
bright, mreal
ap)
¶Добавляет источник света с номером n в положение p с цветом c и яркостью bright, которая должна быть в диапазоне [0,1]. Если указано положение источника r и оно не NAN, то источник считается локальным, иначе источник полагается бесконечно удалённым (для более быстрого рисования).
val
¶mglGraph
: void
SetDifLight (mreal
bright)
¶void
mgl_set_difbr (HMGL
gr, mreal
bright)
¶Задает яркость диффузного освещения (только для локальных источников света).
val
¶mglGraph
: void
SetAmbient (mreal
bright=0.5
)
¶void
mgl_set_ambbr (HMGL
gr, mreal
bright)
¶Задает яркость рассеянного освещения. Значение должно быть в диапазоне [0,1].
val
¶mglGraph
: void
AttachLight (bool
val)
¶void
mgl_set_attach_light (HMGL
gr, int
val)
¶Задает привязку настроек освещения к inplot/subplot. Отмечу, что OpenGL и некоторые выходные форматы не поддерживают эту возможность.
val [dz=0.25]
¶mglGraph
: void
Fog (mreal
d, mreal
dz=0.25
)
¶void
mgl_set_fog (HMGL
gr, mreal
d, mreal
dz)
¶Имитирует туман на графике. Туман начинается на относительном расстоянии dz от точки обзора и его плотность растет экспоненциально вглубь по закону ~ 1-exp(-d*z). Здесь z – нормализованная на 1 глубина графика. Если d=0
то туман отсутствует. См. раздел Adding fog, для примеров кода и графика.
Эти функции задают величины большинства параметров графика, включая размеры маркеров, стрелок, толщину линий и т.д. Как и любые другие настройки, они подействуют только на графики созданные после изменения настроек.
val
¶mglGraph
: void
SetBarWidth ( mreal
val)
¶void
mgl_set_bar_width (HMGL
gr, mreal
val)
¶Задает относительный размер прямоугольников в bars, barh, boxplot, candle. Значение по умолчанию 0.7
.
val
¶mglGraph
: void
SetMarkSize (mreal
val)
¶void
mgl_set_mark_size (HMGL
gr, mreal
val)
¶Задает размер маркеров для 1D графики. Значение по умолчанию 1
.
val
¶mglGraph
: void
SetArrowSize (mreal
val)
¶void
mgl_set_arrow_size (HMGL
gr, mreal
val)
¶Задает размер стрелок для 1D графики, линий и кривых (см. Рисование примитивов). Значение по умолчанию 1
.
val
¶mglGraph
: void
SetMeshNum (int
val)
¶void
mgl_set_meshnum (HMGL
gr, int
num)
¶Задает ориентировочное число линий в mesh, fall, и число стрелок (штрихов) в vect, dew, и число ячеек в cloud, и число маркеров в plot, tens, step, mark, textmark. По умолчанию (=0) рисуются все линии, стрелки, ячейки и т.д.
val
¶mglGraph
: void
SetFaceNum (int
val)
¶void
mgl_set_facenum (HMGL
gr, int
num)
¶Задает ориентировочное число видимых граней. Может быть использована для ускорения рисования за счет более грубого рисунка. По умолчанию (=0) рисуются все грани.
'id'
¶mglGraph
: void
SetPlotId (const char *
id)
¶void
mgl_set_plotid (HMGL
gr, const char *
id)
¶Задает имя графика для сохранения в файл (например, в окне FLTK).
mglGraph
: const char *
GetPlotId ()
¶const char *
mgl_get_plotid (HMGL
gr)
¶
mgl_get_plotid (long
gr, char *
out, int
len)
¶Возвращает имя графика для сохранения в файл (например, в окне FLTK).
val
¶mglGraph
: void
SetPenDelta (double
val)
¶void
mgl_pen_delta (HMGL
gr, double
val)
¶Изменяет размытие около линий и текста (по умолчанию 1). Для val>1 текст и линии более резкие. Для val<1 текст и линии более размытые.
Эти функции задают условия когда точка будет исключена (вырезана) из рисования. Замечу, что все точки со значением(-ями) NAN по одной из координат или амплитуде автоматически исключаются из рисования. См. раздел Cutting sample, для примеров кода и графика.
val
¶mglGraph
: void
SetCut (bool
val)
¶void
mgl_set_cut (HMGL
gr, int
val)
¶Задает обрезание точек за пределами осей координат. Если true
то такие точки исключаются из рисования (это по умолчанию) иначе они проецируются на ограничивающий прямоугольник.
x1 y1 z1 x2 y2 z2
¶mglGraph
: void
SetCutBox (mglPoint
p1, mglPoint
p1)
¶void
mgl_set_cut_box (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
x2, mreal
y2, mreal
z2)
¶Задает границы параллелепипеда внутри которого точки не рисуются. Если границы одинаковы (переменные равны), то параллелепипеда считается пустым.
'cond'
¶mglGraph
: void
CutOff (const char *
cond)
¶void
mgl_set_cutoff (HMGL
gr, const char *
cond)
¶Задает условие обрезания по формуле cond. Это условие исключает точки из рисования если результат вычисления формулы не равен нулю. Установите аргумент ""
для выключения условия обрезания.
'fnt' [val=6
]
¶Задает стиль и размер шрифта. Вначале используется ‘:rC’ – прямой шрифт с выравниванием по центру. По умолчанию размер подписей оси координат в 1.4 раза больше. См. также см. Стиль текста.
val
¶mglGraph
: void
SetRotatedText (bool
val)
¶void
mgl_set_rotated_text (HMGL
gr, int
val)
¶Включает/выключает вращение меток и подписей осей координат вдоль оси.
val
¶mglGraph
: void
SetScaleText (bool
val)
¶void
mgl_set_scale_text (HMGL
gr, int
val)
¶Включает/выключает масштабирование текста в относительных inplot-ах (в том числе columnplot, gridplot, stickplot, shearplot).
val
¶mglGraph
: void
SetTeXparse (bool
val)
¶void
mgl_set_tex_parse (HMGL
gr, int
val)
¶Включает/выключает распознавание TeX-подобных команд при печати текста.
['name'='']
¶mglGraph
: void
LoadFont (const char *
name, const char *
path=""
)
¶void
mgl_load_font (HMGL
gr, const char *
name, const char *
path)
¶Загружает начертание шрифта из файла path/name. Пустая строка загрузит шрифт по умолчанию.
mglGraph
: void
SetFontDef (const char *
fnt)
¶void
mgl_set_font_def (HMGL
gr, const char *
val)
¶Задает стиль шрифта (см. Вывод текста). По умолчанию используется ‘rC’ – прямой шрифт с выравниванием по центру.
mglGraph
: void
SetFontSize (mreal
val)
¶void
mgl_set_font_size (HMGL
gr, mreal
val)
¶Задает базовый размер шрифта. По умолчанию размер подписей оси координат в 1.4 раза больше.
mglGraph
: void
SetFontSizePT (mreal
cm, int
dpi=72
)
¶Задает размер шрифта в пунктах для заданного DPI (по умолчанию 16 pt для dpi=72).
mglGraph
: inline void
SetFontSizeCM (mreal
cm, int
dpi=72
)
¶Задает размер шрифта в сантиметрах для заданного DPI (по умолчанию 0.56 см = 16 pt).
mglGraph
: inline void
SetFontSizeIN (mreal
cm, int
dpi=72
)
¶Задает размер шрифта в дюймах для заданного DPI (по умолчанию 0.22 in = 16 pt).
mglGraph
: void
CopyFont (mglGraph *
from)
¶void
mgl_copy_font (HMGL
gr, HMGL
gr_from)
¶Копирует начертание шрифта из другого объекта mglGraph
.
mglGraph
: void
RestoreFont ()
¶void
mgl_restore_font (HMGL
gr)
¶Восстанавливает начертание шрифта по умолчанию.
mglGraph
: void
SetDefFont (const char *
name, const char *
path=""
) static
¶void
mgl_def_font (const char *
name, const char *
path)
¶Загружает начертание шрифта по умолчанию (для всех вновь создаваемых HMGL/mglGraph объектов) из файла path/name.
'colors'
¶mglGraph
: void
SetPalette (const char *
colors)
¶void
mgl_set_palette (HMGL
gr, const char *
colors)
¶Задает палитру как последовательность цветов. Значение по умолчанию "Hbgrcmyhlnqeup"
, что соответствует цветам: темно серый ‘H’, синий ‘b’, зелёный ‘g’, красный ‘r’, голубой ‘c’, малиновый ‘m’, жёлтый ‘y’, серый ‘h’, сине-зелёный ‘l’, небесно-голубой ‘n’, оранжевый ‘q’, желто-зелёный ‘e’, сине-фиолетовый ‘u’, фиолетовый ‘p’. Палитра в основном используется в 1D графиках (см. 1D графики) для кривых с неопределённым стилем линии. Внутренний счетчик цвета будет сброшен при любом изменении палитры, включая скрытые (например, функциями box или axis).
mglGraph
: void
SetDefScheme (const char *
sch)
¶void
mgl_set_def_sch (HMGL
gr, const char *
sch)
¶Устанавливает sch в качестве цветовой схемы по умолчанию. Начальное значение "BbcyrR"
.
mglGraph
: void
SetColor (char
id, mreal
r, mreal
g, mreal
b) static
¶void
mgl_set_color (char
id, mreal
r, mreal
g, mreal
b)
¶Задает RGB значения для цвета с заданным id. Изменения действуют глобально для всех последующих использований данного id.
[val=on
]
¶mglGraph
: void
Gray (bool
enable)
¶void
mgl_set_gray (HMGL
gr, int
enable)
¶Включает/выключает вывод графика в оттенках серого.
'id' 'hex' [angle]
¶'id' hex [angle]
¶mglGraph
: void
SetMask (char
id, const char *
hex)
¶mglGraph
: void
SetMask (char
id, uint64_t
hex)
¶void
mgl_set_mask (HMGL
gr, const char *
hex)
¶void
mgl_set_mask_val (HMGL
gr, uint64_t
hex)
¶Задает новую матрицу hex размером 8*8 для маски с заданным id. Изменения действуют глобально для всех последующих использований данного id. Значения по умолчанию (см. Цветовая схема): ‘-’ – 000000FF00000000, ‘+’ – 080808FF08080808, ‘=’ – 0000FF00FF000000, ‘;’ – 0000007700000000, ‘o’ – 0000182424180000, ‘O’ – 0000183C3C180000, ‘s’ – 00003C24243C0000, ‘S’ – 00003C3C3C3C0000, ‘~’ – 0000060990600000, ‘<’ – 0060584658600000, ‘>’ – 00061A621A060000, ‘j’ – 0000005F00000000, ‘d’ – 0008142214080000, ‘D’ – 00081C3E1C080000, ‘*’ – 8142241818244281, ‘^’ – 0000001824420000. Параметр angle позволяет сразу задать и угол поворота маски. ВАЖНО: при экспорте в EPS угол поворота будет приведен к ближайшему кратному 45 градусам.
Задает новую матрицу hex размером 8*8 для маски с заданным id. Изменения действуют глобально для всех последующих использований данного id. Значения по умолчанию (см. Цветовая схема): ‘-’ – линии (0x000000FF00000000
), ‘+’ – клетки (080808FF08080808
), ‘=’ – двойные линии (0000FF00FF000000
), ‘;’ – пунктир (0x0000000F00000000
), ‘o’ – окружкости (0000182424180000
), ‘O’ – круги (0000183C3C180000
), ‘s’ – квадраты (00003C24243C0000
), ‘S’ – закрашенные квадраты (00003C3C3C3C0000
), ‘~’ – волны (0000060990600000
), ‘<’ – треугольники влево (0060584658600000
), ‘>’ – треугольники вправо (00061A621A060000
), ‘j’ пунктир с точками (0000002700000000
), ‘d’ плюсы (0x0008083E08080000
), ‘D’ – стежки (0x0139010010931000
), ‘*’ – точки (0x0000001818000000
), ‘^’ – кирпичи (0x101010FF010101FF
). Параметр angle позволяет сразу задать и угол поворота маски. ВАЖНО: при экспорте в EPS угол поворота будет приведен к ближайшему кратному 45 градусам.
angle
¶mglGraph
: void
SetMaskAngle (int
angle)
¶void
mgl_set_mask_angle (HMGL
gr, int
angle)
¶Задает угол поворота маски в градусах. Отмечу, что символы ‘\’, ‘/’, ‘I’ в цветовой схеме задают угол поворота в 45, -45 и 90 градусов соответственно. ВАЖНО: при экспорте в EPS угол поворота будет приведен к ближайшему кратному 45 градусам.
Обычно вы должны сбросить признак ошибки с помощью SetWarn(0);
перед построением и проверить GetWarnCode()
или Message()
на наличие ошибок после построения. Только последнее предупреждение сохраняется. Замечу, что все предупреждения/ошибки в MathGL не являются критичными – в худшем из вариантов соответствующий график просто не будет построен. По умолчанию, все предупреждения выводятся в stderr
. Этот вывод можно выключить вызовом mgl_suppress_warn(true);
.
mglGraph
: void
SetWarn (int
code, const char *
info=""
)
¶void
mgl_set_warn (HMGL
gr, int
code, const char *
info)
¶Задает код предупреждения. Обычно вызывается только для очистки предупреждений (SetWarn(0);
) или внутри библиотеки. Текст info будет добавлен к предупреждениям как есть при code<0.
mglGraph
: const char *
Message
() ¶const char *
mgl_get_mess
(HMGL
gr)
¶
mgl_get_mess (long
gr, char *
out, int
len)
¶Возвращает текст предупреждений о причине отсутствия графика. Если возвращаемая строка пустая, то сообщений нет.
mglGraph
: int
GetWarn ()
¶int
mgl_get_warn (HMGL
gr)
¶Возвращает код сообщения о причине отсутствия графика. Возможные значения:
mglWarnNone=0
Предупреждений нет
mglWarnDim
Неправильные или несовместимые размеры данных
mglWarnLow
Размеры данных слишком малы
mglWarnNeg
Минимальное значение отрицательно
mglWarnFile
Файл не найден или указаны неправильные размерности
mglWarnMem
Не достаточно памяти
mglWarnZero
Значение данных равно нулю
mglWarnLeg
Нет записей в легенде
mglWarnSlc
Индекс среза вне данных
mglWarnCnt
Число линий уровня меньше или равно нулю
mglWarnOpen
Не могу открыть файл
mglWarnLId
Light: ID вне допустимых значений
mglWarnSize
Setsize: размер(ы) равны нулю или отрицательны
mglWarnFmt
Формат не поддерживается
mglWarnTern
Диапазоны осей несовместимые
mglWarnNull
Указатель равен NULL
mglWarnSpc
Не хватает места для графика
mglScrArg
Неправильные аргументы команды скрипта MGL
mglScrCmd
Неправильная команда в скрипте MGL
mglScrLong
Слишком длинная строка в скрипте MGL
mglScrStr
Одиночная ’ в скрипте MGL
mglScrTemp
Изменяется временная переменная в MGL скрипте
mglGraph
: void
SuppressWarn (bool
state) static
¶void
mgl_suppress_warn (int
state)
¶Выключает вывод предупреждений в stderr
если state не ноль.
mglGraph
: void
SetGlobalWarn (const char *
info) static
¶void
mgl_set_global_warn (const char *
info)
¶Задает предупреждение info, не привязанное к конкретному объекту рисования.
mglGraph
: const char *
GlobalWarn () static
¶const char *
mgl_get_global_warn ()
¶Возвращает предупреждения, не привязанные к конкретному объекту рисования.
mglGraph
: void
ClearGlobalWarn () static
¶void
mgl_clear_global_warn ()
¶Удаляет общие предупреждения.
mglGraph
: void
Stop (bool
stop=true
)
¶void
mgl_ask_stop (HMGL
gr, int
stop)
¶Просит остановить рисование если stop не ноль, иначе сбрасывает флаг остановки.
mglGraph
: bool
NeedStop ()
¶void
mgl_need_stop (HMGL
gr)
¶Возвращает true
если рисование должно быть остановлено. Также запускает обработку всех отложенных событий в GUI. Пользователь должен вызывать эту функцию время от времени внутри долгих вычислений для плавности отклика GUI.
mglGraph
: bool
SetEventFunc (void (*
func)(void *)
, void *
par=NULL
)
¶void
mgl_set_event_func (HMGL
gr, void (*
func)(void *)
, void *
par)
¶Задает функцию, которая будет вызвана для обработки событий в GUI библиотеке.
Эти функции управляет видом и масштабом осей координат. Перед построением для каждой точки выполняются 3 преобразования: сначала определяется возможность рисования точки (см. Обрезание), далее применяются формулы перехода к криволинейным координатам и наконец точка отображается. Отмечу, что MathGL выдает предупреждение если масштабы осей координат лежат вне области определения формул преобразования координат.
v1 v2
[add=off
]
¶v1 v2
[add=off
]
¶v1 v2
[add=off
]
¶v1 v2
[add=off
]
¶mglGraph
: void
SetRange (char
dir, mreal
v1, mreal
v2)
¶mglGraph
: void
AddRange (char
dir, mreal
v1, mreal
v2)
¶void
mgl_set_range_val (HMGL
gr, char
dir, mreal
v1, mreal
v2)
¶void
mgl_add_range_val (HMGL
gr, char
dir, mreal
v1, mreal
v2)
¶Задает диапазон изменения ‘x’-,‘y’-,‘z’-,‘c’-координат. Если одно из значений равно NAN
, то оно игнорируется. Параметр add=on
указывает добавлять новый диапазон к существующему (не заменять его). См. также ranges.
dat [add=off
]
¶dat [add=off
]
¶dat [add=off
]
¶dat [add=off
]
¶mglGraph
: void
SetRange (char
dir, const mglDataA &
dat, bool
add=false
)
¶void
mgl_set_range_dat (HMGL
gr, char
dir, const HCDT
a, int
add)
¶Задает диапазон изменения ‘x’-,‘y’-,‘z’-,‘c’-координат как минимальное и максимальное значение массива dat. Параметр add=on
указывает добавлять новый диапазон к существующему (не заменять его).
x1 x2 y1 y2 [z1=0 z2=0]
¶mglGraph
: void
SetRanges (mglPoint
p1, mglPoint
p2)
¶mglGraph
: void
SetRanges (mreal
x1, mreal
x2, mreal
y1, mreal
y2, mreal
z1=0
, mreal
z2=0
)
¶void
mgl_set_ranges (HMGL
gr, mreal
x1, mreal
x2, mreal
y1, mreal
y2, mreal
z1, mreal
z2)
¶Задает диапазон изменения координат. Если минимальное и максимальное значение координаты равны, то они игнорируются по данному направлению. Также устанавливает размер цветовой шкалы, аналогично команде crange z1 z2
. Начальные диапазоны равны [-1, 1].
xx yy [zz cc=zz]
¶mglGraph
: void
SetRanges (const mglDataA &
xx, const mglDataA &
yy)
¶mglGraph
: void
SetRanges (const mglDataA &
xx, const mglDataA &
yy, const mglDataA &
zz)
¶mglGraph
: void
SetRanges (const mglDataA &
xx, const mglDataA &
yy, const mglDataA &
zz, const mglDataA &
cc)
¶Задает диапазон изменения ‘x’-,‘y’-,‘z’-,‘c’-координат как минимальное и максимальное значение массивов xx, yy, zz, cc соответственно.
mglGraph
: void
SetAutoRanges (mglPoint
p1, mglPoint
p2)
¶mglGraph
: void
SetAutoRanges (double
x1, double
x2, double
y1, double
y2, double
z1=0
, double
z2=0
, double
c1=0
, double
c2=0
)
¶void
mgl_set_auto_ranges (HMGL
gr, double
x1, double
x2, double
y1, double
y2, double
z1, double
z2, double
z1, double
z2)
¶Задает диапазон изменения координат для автоматических переменных. Если минимальное и максимальное значение координаты равны, то они игнорируются по данному направлению.
x0 y0 [z0=nan]
¶mglGraph
: void
SetOrigin (mglPoint
p0)
¶mglGraph
: void
SetOrigin (mreal
x0, mreal
y0, mreal
z0=NAN
)
¶void
mgl_set_origin (HMGL
gr, mreal
x0, mreal
y0, mreal
z0)
¶Задает центр пересечения осей координат. Если одно из значений равно NAN, то MathGL попытается выбрать оптимальное положение осей координат по этому направлению.
x1 x2
¶x1 y1 x2 y2
¶x1 y1 z1 x2 y2 z2
¶x1 y1 z1 c1 x2 y2 z2 c2
¶mglGraph
: void
ZoomAxis (mglPoint
p1, mglPoint
p2)
¶void
mgl_zoom_axis (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
c1, mreal
x2, mreal
y2, mreal
z2, mreal
c2)
¶Дополнительно расширяет диапазон осей координат, задаваемый функциями SetRange
или SetRanges
, в соответствии с формулами min += (max-min)*p1 и max += (max-min)*p1 (или min *= (max/min)^p1 и max *= (max/min)^p1 для "логарифмических" диапазонов, когда inf>max/min>100 или 0<max/min<0.01). Начальные значения [0, 1]. Внимание! эти настройки не могут быть переписаны никакими другими функциями, включая DefaultPlotParam()
.
val
¶mglGraph
: void
SetFastCut (bool
val=true
)
¶Разрешает/запрещает аккуратное и более медленное обрезание примитивов на границах осей координат. В C/Fortran следует использовать mgl_set_flag(gr,val, MGL_FAST_PRIM);
. Включено автоматически для ternary системы координат.
'fx' 'fy' 'fz' ['fa'='']
¶mglGraph
: void
SetFunc (const char *
EqX, const char *
EqY, const char *
EqZ=""
, const char *
EqA=""
)
¶void
mgl_set_func (HMGL
gr, const char *
EqX, const char *
EqY, const char *
EqZ, const char *
EqA)
¶Задает формулы перехода к криволинейным координатам. Каждая строка является математическим выражением, зависящим от старых координат ‘x’, ‘y’, ‘z’ и ‘a’ или ‘c’ для цветовой шкалы. Например, для цилиндрических координат будет SetFunc("x*cos(y)", "x*sin(y)", "z");
. Для удаления формул соответствующий параметр должен быть пустым или NULL
. Использование формул преобразования слегка замедляет программу. Параметр EqA задает аналогичную формулу для цветовой шкалы. See Текстовые формулы.
how
¶mglGraph
: void
SetCoor (int
how)
¶void
mgl_set_coor (HMGL
gr, int
how)
¶Устанавливает одну из предопределенных систем криволинейных координат в зависимости от параметра how:
mglCartesian=0
декартова система (нет преобразования координат, {x,y,z});
mglPolar=1
полярные координаты: {x*cos(y),x*sin(y), z};
mglSpherical=2
сферические координаты: {x*sin(y)*cos(z), x*sin(y)*sin(z), x*cos(y)};
mglParabolic=3
параболические координаты: {x*y, (x*x-y*y)/2, z};
mglParaboloidal=4
Paraboloidal coordinates: {(x*x-y*y)*cos(z)/2, (x*x-y*y)*sin(z)/2, x*y};
mglOblate=5
Oblate coordinates: {cosh(x)*cos(y)*cos(z), cosh(x)*cos(y)*sin(z), sinh(x)*sin(y)};
mglProlate=6
Prolate coordinates: {sinh(x)*sin(y)*cos(z), sinh(x)*sin(y)*sin(z), cosh(x)*cos(y)};
mglElliptic=7
эллиптические координаты: {cosh(x)*cos(y), sinh(x)*sin(y), z};
mglToroidal=8
тороидальные координаты: {sinh(x)*cos(z)/(cosh(x)-cos(y)), sinh(x)*sin(z)/(cosh(x)-cos(y)), sin(y)/(cosh(x)-cos(y))};
mglBispherical=9
бисферические координаты: {sin(y)*cos(z)/(cosh(x)-cos(y)), sin(y)*sin(z)/(cosh(x)-cos(y)), sinh(x)/(cosh(x)-cos(y))};
mglBipolar=10
биполярные координаты: {sinh(x)/(cosh(x)-cos(y)), sin(y)/(cosh(x)-cos(y)), z};
mglLogLog=11
Log-log координаты: {lg(x), lg(y), lg(z)};
mglLogX=12
Log-x координаты: {lg(x), y, z};
mglLogY=13
Log-y координаты: {x, lg(y), z}.
val
¶mglGraph
: void
Ternary (int
tern)
¶void
mgl_set_ternary (HMGL
gr, int
tern)
¶Задает рисование треугольных (Ternary, tern=1
), пирамидальных (Quaternary, tern=2
) осей координат и проекций осей координат (tern=4,5,6
).
Ternary – специальный тип графика для 3 зависимых координат (компонент) a, b, c таких, что a+b+c=1. MathGL использует только 2 независимые координаты a=x и b=y поскольку их достаточно для построения всех графиков. При этом третья координата z является независимым параметром для построения линий уровня, поверхностей и т.д.
Соответственно Quaternary координаты – 4 зависимые координаты a, b, c и d, такие что a+b+c+d=1. MathGL использует только 2 независимые координаты a=x, b=y и d=z поскольку их достаточно для построения всех графиков.
Проекции строятся если к переменной tern добавить число 4
. Так что tern=4
нарисует проекции в декартовых координатах, tern=5
нарисует проекции в треугольных координатах, tern=6
нарисует проекции в пирамидальных координатах. Если добавить 8
вместо 4
, то текст не будет выводиться на проекциях.
Используйте Ternary(0)
для возвращения к привычным координатам. См. раздел Ternary axis, для примеров кода и графика. См. раздел Axis projection, для примеров кода и графика.
['dir'='xyzc']
¶mglGraph
: void
Adjust (const char *
dir="xyzc"
)
¶void
mgl_adjust_ticks (HMGL
gr, const char *
dir)
¶Автоматически задает шаг меток осей, число подметок и начальное положение меток для осей координат dir в виде наиболее удобном для человека. Также задает SetTuneTicks(true)
. Обычно не требуется вызывать эту функцию кроме случая возвращения настроек по умолчанию.
val [sub=0 org=nan 'fact'='']
¶val [sub=0 org=nan 'fact'='']
¶val [sub=0 org=nan 'fact'='']
¶val sub ['fact'='']
¶val sub ['fact'='']
¶val sub ['fact'='']
¶val ['fact'='']
¶mglGraph
: void
SetTicks (char
dir, mreal
d=0
, int
ns=0
, mreal
org=NAN
, const char *
fact=""
)
¶mglGraph
: void
SetTicks (char
dir, mreal
d=0
, int
ns=0
, mreal
org=NAN
, const wchar_t *
fact)
¶void
mgl_set_ticks (HMGL
gr, char
dir, mreal
d, int
ns, mreal
org)
¶void
mgl_set_ticks_fact (HMGL
gr, char
dir, mreal
d, int
ns, mreal
org, const char *
fact)
¶void
mgl_set_ticks_factw (HMGL
gr, char
dir, mreal
d, int
ns, mreal
org, const wchar_t *
fact)
¶Задает шаг меток осей d, число подметок ns и начальное положение меток org для оси вдоль направления dir (используйте ’c’ для меток colorbar). Переменная d задает шаг меток (если положительна) или их число на оси (если отрицательна). Нулевое значение задает автоматическую расстановку меток. Если org=NAN
, то используется значение из переменной Org. Параметр fact задает текст, которые будет напечатан после метки оси (например, "\pi" для d=M_PI).
val1
'lbl1' [val2
'lbl2' ...]
¶val1
'lbl1' [val2
'lbl2' ...]
¶val1
'lbl1' [val2
'lbl2' ...]
¶val1
'lbl1' [val2
'lbl2' ...]
¶vdat 'lbls' [add=off
]
¶vdat 'lbls' [add=off
]
¶vdat 'lbls' [add=off
]
¶vdat 'lbls' [add=off
]
¶mglGraph
: void
SetTicksVal (char
dir, const char *
lbl, bool
add=false
)
¶mglGraph
: void
SetTicksVal (char
dir, const wchar_t *
lbl, bool
add=false
)
¶mglGraph
: void
SetTicksVal (char
dir, const mglDataA &
val, const char *
lbl, bool
add=false
)
¶mglGraph
: void
SetTicksVal (char
dir, const mglDataA &
val, const wchar_t *
lbl, bool
add=false
)
¶void
mgl_set_ticks_str (HMGL
gr, char
dir, const char *
lbl, bool
add)
¶void
mgl_set_ticks_wcs (HMGL
gr, char
dir, const wchar_t *
lbl, bool
add)
¶void
mgl_set_ticks_val (HMGL
gr, char
dir, HCDT
val, const char *
lbl, bool
add)
¶void
mgl_set_ticks_valw (HMGL
gr, char
dir, HCDT
val, const wchar_t *
lbl, bool
add)
¶Задает явное положение val и подписи lbl для меток вдоль оси dir. Если массив val не указан, то используются значения равно распределённые в диапазоне осей координат. Метки разделяются символом ‘\n’. Если в команде MGL задано только одно значение, то метка будет добавлена к существующим меткам. Используйте SetTicks()
для восстановления автоматических меток.
mglGraph
: void
AddTick (char
dir, double
val, const char *
lbl)
¶mglGraph
: void
AddTick (char
dir, double
val, const wchar_t *
lbl)
¶void
mgl_add_tick (HMGL
gr, char
dir, double
val, const char *
lbl)
¶void
mgl_set_tickw (HMGL
gr, char
dir, double
val, const wchar_t *
lbl)
¶Аналогично предыдущему, но добавляет одну метку оси к списку существующих меток.
'templ'
¶'templ'
¶'templ'
¶'templ'
¶mglGraph
: void
SetTickTempl (char
dir, const char *
templ)
¶mglGraph
: void
SetTickTempl (char
dir, const wchar_t *
templ)
¶void
mgl_set_tick_templ (HMGL
gr, const char *
templ)
¶void
mgl_set_tick_templw (HMGL
gr, const wchar_t *
templ)
¶Задает шаблон templ для меток вдоль x-,y-,z-оси или colorbar. Шаблон может содержать и символы TeX. Если templ=""
, то используется шаблон по умолчанию (в простейшем случае ‘%.2g’). Если шаблон начинается с символа ‘&’, то будет использовано целое long
вместо типа double
. Установка шаблона выключает автоматическое улучшение вида меток.
'dir' [dv=0
'tmpl'='']
¶mglGraph
: void
SetTicksTime (char
dir, mreal
val, const char *
templ)
¶void
mgl_set_ticks_time (HMGL
gr, mreal
val, const char *
templ)
¶Задает метки времени с шагом val и шаблоном templ для меток вдоль x-,y-,z-оси или colorbar. Шаблон может содержать и символы TeX. Формат шаблона templ такой же как http://www.manpagez.com/man/3/strftime/. Наиболее употребительные варианты: ‘%X’ для национального представления времени, ‘%x’ для национального представления даты, ‘%Y’ для года с цифрами столетия. Если val=0 и/или templ="", то используется автоматическая расстановка меток и/или выбор шаблона. Вы можете использовать функцию mgl_get_time
() для получения числа секунд с 1970 года до указанной даты/времени. Отмечу, что MS Visual Studio не может обрабатывать даты до 1970.
double
mgl_get_time (const char*
str, const char *
templ)
¶Возвращает число секунд с 1970 года до даты/времени, указанной в строке str. Формат строки задается templ, такой же как http://www.manpagez.com/man/3/strftime/. Наиболее употребительные варианты: ‘%X’ для национального представления времени, ‘%x’ для национального представления даты, ‘%Y’ для года с цифрами столетия. Отмечу, что MS Visual Studio не может обрабатывать даты до 1970.
val
[pos=1.15
]
¶mglGraph
: void
SetTuneTicks (int
tune, mreal
pos=1.15
)
¶void
mgl_tune_ticks (HMGL
gr, int
tune, mreal
pos)
¶Включает/выключает улучшение вида меток осей путем вынесения общего множителя (для маленьких, типа 0.001...0.002, или больших, типа 1000...2000, значений координат) или общей компоненты (для узкого диапазона, типа 0.999...1.000). Также задает положение pos общего множителя на оси: =0 около минимального значения, =1 около максимального значения.
dx [dy=0 dz=0 dc=0]
¶mglGraph
: void
SetTickShift (mglPoint
d)
¶void
mgl_set_tick_shift (HMGL
gr, mreal
dx, mreal
dy, mreal
dz, mreal
dc)
¶Задает значение дополнительного сдвига меток осей координат.
mglGraph
: void
SetTickRotate (bool
val)
¶void
mgl_set_tick_rotate (HMGL
gr, bool
val)
¶Включает/выключает поворот меток если их число или длина меток слишком велики.
mglGraph
: void
SetTickSkip (bool
val)
¶void
mgl_set_tick_skip (HMGL
gr, bool
val)
¶Включает/выключает пропуск меток если их число или длина меток слишком велики.
mglGraph
: void
SetTimeUTC (bool
val)
¶Разрешает/запрещает использование UTC времени в метках осей координат. В C/Fortran следует использовать mgl_set_flag(gr,val, MGL_USE_GMTIME);
.
val
¶mglGraph
: void
SetOriginTick (bool
val=true
)
¶Разрешает/запрещает рисование меток в точке пересечения осей координат. В C/Fortran следует использовать mgl_set_flag(gr,val, MGL_NO_ORIGIN);
.
val
[stt=1
]
¶mglGraph
: void
SetTickLen (mreal
val, mreal
stt=1
)
¶void
mgl_set_tick_len (HMGL
gr, mreal
val, mreal
stt)
¶Задает относительную длину меток осей координат. Значение по умолчанию 0.1
. Параметр stt>0 задает относительную длину подметок, которые в sqrt(1+stt)
раз меньше.
'stl' ['tck'='' 'sub'='']
¶mglGraph
: void
SetAxisStl (const char *
stl="k"
, const char *
tck=0
, const char *
sub=0
)
¶void
mgl_set_axis_stl (HMGL
gr, const char *
stl, const char *
tck, const char *
sub)
¶Задает стиль осей (stl), меток (tck) и подметок (sub) осей координат. Если stl пустая или ноль, то используется стиль по умолчанию (‘k’ или ‘w’ в зависимости от типа прозрачности). Если tck, sub пустая или ноль, то используется стиль осей (т.е. stl).
Эти функции контролируют где и как график будет расположен. Существует определенный порядок вызова этих функций для лучшего вида графика. Вначале должны вызываться функции subplot, multiplot или inplot для указания местоположения вывода. После них – функции вращения rotate, shear и aspect. И наконец любые другие функции для рисования графика. Вместо вращения графика можно вызвать функцию columnplot, gridplot, stickplot, shearplot или относительную inplot для расположения графиков в столбец одного над другим без зазора между осями. См. раздел Subplots, для примеров кода и графика.
nx ny m
['stl'='<>_^' dx=0 dy=0
]
¶mglGraph
: void
SubPlot (int
nx, int
ny, int
m, const char *
stl="<>_^"
, mreal
dx=0
, mreal
dy=0
)
¶void
mgl_subplot (HMGL
gr, int
nx, int
ny, int
m, const char *
stl)
¶void
mgl_subplot_d (HMGL
gr, int
nx, int
ny, int
m, const char *
stl, mreal
dx, mreal
dy)
¶Помещает последующий вывод в m-ую ячейку сетки размером nx*ny от всего рисунка. Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться первой для создания "подграфика". С эстетической точки зрения не рекомендуется вызывать эту функцию с различными (или не кратными) размерами сетки. Дополнительное место для осей/colorbar резервируется только если строка stl содержит:
Ячейка может быть дополнительно сдвинута относительно своего обычного положения на относительный размер dx, dy. Отмечу, что colorbar может находиться за пределами рисунка если выбран пустой стиль ‘’.
nx ny m dx dy
['style'='<>_^' sx sy]
¶mglGraph
: void
MultiPlot (int
nx, int
ny, int
m, int
dx, int
dy, const char *
stl="<>_^"
)
¶void
mgl_multiplot (HMGL
gr, int
nx, int
ny, int
m, int
dx, int
dy, const char *
stl)
¶Помещает последующий вывод в прямоугольник из dx*dy ячеек, начиная с m-ой ячейки, сетки размером nx*ny от всего рисунка. Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться первой для создания "подграфика". Дополнительное место для осей/colorbar резервируется если строка stl содержит:
Область вывода может быть дополнительно сдвинута относительно своего обычного положения на относительный размер sx, sy.
x1 x2 y1 y2 [rel=on]
¶mglGraph
: void
InPlot (mreal
x1, mreal
x2, mreal
y1, mreal
y2, bool
rel=true
)
¶void
mgl_inplot (HMGL
gr, mreal
x1, mreal
x2, mreal
y1, mreal
y2)
¶void
mgl_relplot (HMGL
gr, mreal
x1, mreal
x2, mreal
y1, mreal
y2)
¶Помещает последующий вывод в прямоугольную область [x1, x2]*[y1, y2] (исходный размер [0,1]*[0,1]). Эта функция позволяет поместить график в произвольную область рисунка. Если параметр rel=true
, то используется позиция относительно текущего subplot (или inplot с rel=false
). Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться первой для создания "подграфика".
num ind [d=0]
¶mglGraph
: void
ColumnPlot (int
num, int
ind, mreal
d=0
)
¶void
mgl_columnplot (HMGL
gr, int
num, int
ind)
¶void
mgl_columnplot_d (HMGL
gr, int
num, int
ind, mreal
d)
¶Помещает последующий вывод в ind-ую строку столбца из num строк. Положение столбца выбирается относительно последнего вызова subplot (или inplot с rel=false
). Параметр d задает дополнительный зазор между строк.
nx ny ind [d=0]
¶mglGraph
: void
GridPlot (int
nx, int
ny, int
ind, mreal
d=0
)
¶void
mgl_gridplot (HMGL
gr, int
nx, int
ny, int
ind)
¶void
mgl_gridplot_d (HMGL
gr, int
nx, int
ny, int
ind, mreal
d)
¶Помещает последующий вывод в ind-ую ячейку таблицы nx*ny. Положение ячейки выбирается относительно последнего вызова subplot (или inplot с rel=false
). Параметр d задает дополнительный зазор между ячеек.
num ind tet phi
¶mglGraph
: void
StickPlot (int
num, int
ind, mreal
tet, mreal
phi)
¶void
mgl_stickplot (HMGL
gr, int
num, int
ind, mreal
tet, mreal
phi)
¶Помещает последующий вывод в ind-ую ячейку "бруска" из num ячеек. При этом сам брусок повернут на углы tet, phi. Положение выбирается относительно последнего вызова subplot (или inplot с rel=false
).
num ind sx sy [xd yd]
¶mglGraph
: void
ShearPlot (int
num, int
ind, mreal
sx, mreal
sy, mreal
xd=1
, mreal
yd=0
)
¶void
mgl_shearplot (HMGL
gr, int
num, int
ind, mreal
sx, mreal
sy, mreal
xd, mreal
yd)
¶Помещает последующий вывод в ind-ую ячейку "бруска" из num ячеек. При этом сама ячейка скошена на sx, sy. Направление бруска задается переменными xd и yd. Положение выбирается относительно последнего вызова subplot (или inplot с rel=false
).
'title' ['stl'='' size=-2
]
¶mglGraph
: void
Title (const char *
txt, const char *
stl=""
, mreal
size=-2
)
¶mglGraph
: void
Title (const wchar_t *
txt, const char *
stl=""
, mreal
size=-2
)
¶void
mgl_title (HMGL
gr, const char *
txt, const char *
stl, mreal
size)
¶void
mgl_titlew (HMGL
gr, const wchar_t *
txt, const char *
stl, mreal
size)
¶Выводит заголовок title для текущего "подграфика" шрифтом stl с размером size. Если строка stl содержит ‘#’, то рисуется обрамляющий прямоугольник. Функция сбрасывает матрицу трансформации (повороты и сжатие графика) и должна вызываться сразу после создания "подграфика". Следует отметить, что каждый последующий вызов команды резервирует дополнительное место. Поэтому следует вручную вызвать subplot после rasterize если требуется совместить растровые и векторные куски графика.
tetx tetz [tety=0]
¶mglGraph
: void
Rotate (mreal
TetX, mreal
TetZ, mreal
TetY=0
)
¶void
mgl_rotate (HMGL
gr, mreal
TetX, mreal
TetZ, mreal
TetY)
¶Вращает систему координат относительно осей {x, z, y} последовательно на углы TetX, TetZ, TetY.
tet x y z
¶mglGraph
: void
RotateN (mreal
Tet, mreal
x, mreal
y, mreal
z)
¶void
mgl_rotate_vector (HMGL
gr, mreal Tet
, mreal x
, mreal y
, mreal z
)
¶Вращает систему координат относительно вектора {x, y, z} на угол Tet.
sx sy
¶mglGraph
: void
Shear (mreal
sx, mreal
sy)
¶void
mgl_shear (HMGL
gr, mreal
sx, mreal
sy)
¶Сдвигает (скашивает) систему координат на значения sx, sy.
ax ay [az=1]
¶mglGraph
: void
Aspect (mreal
Ax, mreal
Ay, mreal
Az=1
)
¶void
mgl_aspect (HMGL
gr, mreal
Ax, mreal
Ay, mreal
Az)
¶Устанавливает соотношение размеров осей в отношении Ax:Ay:Az. Для лучшего вида следует вызывать после функции rotate. Если Ax=NAN
, то функция выберет оптимальное соотношение размеров, чтобы шаг по осям x-y был одинаков. При этом, Ay задает фактор пропорциональности шага (обычно 1), или указывает на его автоматический выбор при Ay=NAN
.
mglGraph
: void
Push ()
¶void
mgl_mat_push (HMGL
gr)
¶Помещает матрицу преобразования в стек. Позднее вы можете восстановить текущее состояние с помощью функции Pop().
mglGraph
: void
Pop ()
¶void
mgl_mat_pop (HMGL
gr)
¶Заменяет (восстанавливает) матрицу преобразования на последнюю помещенную в стек матрицу.
mglGraph
: void
SetPlotFactor (mreal
val)
¶void
mgl_set_plotfactor (HMGL
gr, mreal
val)
¶Задает масштаб картинки. Не рекомендуется устанавливать значения меньше 1.5. Это аналог функции Zoom(), но применяется только к конкретному подграфику. Используйте ноль для включения автоматического масштабирования.
Также есть 3 функции, которые управляют перспективой Perspective()
, масштабированием Zoom()
и вращением View()
всего рисунка. Т.е. они действуют как ещё одна матрица трансформации. Они были введены для вращения/приближения графика с помощью мыши. Не рекомендуется вызывать их при рисовании графика.
val
¶mglGraph
: void
Perspective (mreal
a)
¶void
mgl_perspective (HMGL
gr, mreal
a)
¶Добавляет (включает) перспективу для графика. Параметр a = Depth/(Depth+dz) \in [0,1). По умолчанию (a=0
) перспектива отключена.
tetx tetz [tety=0]
¶mglGraph
: void
View (mreal
TetX, mreal
TetZ, mreal
TetY=0
)
¶void
mgl_view (HMGL
gr, mreal
TetX, mreal
TetZ, mreal
TetY)
¶Вращает систему координат относительно осей {x, z, y} последовательно на углы TetX, TetZ, TetY. Вращение происходит независимо от rotate. Внимание! эти настройки не могут быть переписаны функцией DefaultPlotParam()
. Используйте Zoom(0,0,1,1)
для возвращения к виду по умолчанию.
x1 y1 x2 y2
¶mglGraph
: void
Zoom (mreal
x1, mreal
y1, mreal
x2, mreal
y2)
¶void
mgl_set_zoom (HMGL
gr, mreal
x1, mreal
y1, mreal
x2, mreal
y2)
¶Масштабирует весь рисунок. После вызова функции текущий график будет очищен и в дальнейшем рисунок будет содержать только область [x1,x2]*[y1,y2] от исходного рисунка. Координаты x1, x2, y1, y2 меняются в диапазоне от 0 до 1. Внимание! эти настройки не могут быть переписаны никакими другими функциями, включая DefaultPlotParam()
. Используйте Zoom(0,0,1,1)
для возвращения к виду по умолчанию.
Функции в этой группе сохраняют или дают доступ к полученному рисунку. Поэтом обычно они должны вызываться в конце рисования.
w h
¶mglGraph
: void
SetSize (int
width, int
height, bool
clear=true
)
¶void
mgl_set_size (HMGL
gr, int
width, int
height)
¶void
mgl_scale_size (HMGL
gr, int
width, int
height)
¶Изменяет размер картинки в пикселях. Функция должна вызываться перед любыми функциями построения потому что полностью очищает содержимое рисунка при clear=true
. Функция только очищает растровый рисунок и масштабирует примитивы при clear=false
.
factor
¶mglGraph
: void
SetSizeScl (double
factor)
¶void
mgl_set_size_scl (HMGL
gr, double
factor)
¶Задает множитель для высоты и ширины во всех последующих вызовах setsize.
[val
=2]
¶mglGraph
: void
SetQuality (int
val=MGL_DRAW_NORM
)
¶void
mgl_set_quality (HMGL
gr, int
val)
¶Задает качество графика в зависимости от значения val: MGL_DRAW_WIRE=0
– нет рисования граней (наиболее быстрый), MGL_DRAW_FAST=1
– нет интерполяции цвета (быстрый), MGL_DRAW_NORM=2
– высокое качество (нормальный), MGL_DRAW_HIGH=3
– высокое качество с рисованием 3d примитивов (стрелок и маркеров). Если установлен бит MGL_DRAW_LMEM=0x4
, то происходит прямое рисование в растровое изображение (меньше затраты памяти). Если установлен бит MGL_DRAW_DOTS=0x8
, то рисуются точки вместо примитивов (очень быстро).
mglGraph
: int
GetQuality ()
¶void
mgl_get_quality (HMGL
gr)
¶Возвращает качество графика: MGL_DRAW_WIRE=0
– нет рисования граней (наиболее быстрый), MGL_DRAW_FAST=1
– нет интерполяции цвета (быстрый), MGL_DRAW_NORM=2
– высокое качество (нормальный), MGL_DRAW_HIGH=3
– высокое качество с рисованием 3d примитивов (стрелок и маркеров). Если установлен бит MGL_DRAW_LMEM=0x4
, то происходит прямое рисование в растровое изображение (меньше затраты памяти). Если установлен бит MGL_DRAW_DOTS=0x8
, то рисуются точки вместо примитивов (очень быстро).
mglGraph
: void
StartGroup (const char *name)
¶void
mgl_start_group (HMGL
gr, const char *
name)
¶Начинает определение группы. Группа может содержать объекты и другие группы. Они используются для выбора части модели при приближении, изменении прозрачности и т.д.
mglGraph
: void
EndGroup ()
¶void
mgl_end_group (HMGL
gr)
¶Завершает определение группы.
Эти функции экспортируют текущую картинку (кадр) в файл. Имя файла fname должно иметь соответствующее расширение. Параметр descr дает краткое описание картинки. Пока прозрачность поддерживается только для форматов PNG, SVG, OBJ и PRC.
['fname'='']
¶mglGraph
: void
WriteFrame (const char *
fname=""
, const char *
descr=""
)
¶void
mgl_write_frame (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в файл fname с типом, определяемым по расширению. Параметр descr добавляет описание (может быть пустым). Если fname пустой, то используется имя ‘frame####.jpg’, где ‘####’ – текущий номер кадра и имя ‘frame’ определяется переменной plotid.
x1 y1 [x2=-1
y2=-1
]
¶mglGraph
: void
SetBBox (int
x1=0
, int
y1=0
, int
x2=-1
, int
y2=-1
)
¶void
mgl_set_bbox (HMGL
gr, int
x1, int
y1, int
x2, int
y2)
¶Задает область изображения, которая будет сохранена в файл 2D формата. Если x2<0 (y2<0), то исходная ширина (высота) рисунка будет использована. Если x1<0 или y1<0 или x1>=x2|Width или y1>=y2|Height, то обрезания рисунка не будет.
mglGraph
: void
WritePNG (const char *
fname, const char *
descr=""
, int
compr=""
, bool
alpha=true
)
¶void
mgl_write_png (HMGL
gr, const char *
fname, const char *
descr)
¶void
mgl_write_png_solid (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в PNG файл. Параметры функции следующие: fname – имя файла, descr – описание файла, alpha – прозрачность фона. Если при компиляции MathGL не был определен флаг HAVE_PNG, то экспорт в файл не производится.
mglGraph
: void
WriteJPEG (const char *
fname, const char *
descr=""
)
¶void
mgl_write_jpg (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в JPEG файл. Параметры функции следующие: fname – имя файла, descr – описание файла. Если при компиляции MathGL не был определен флаг HAVE_JPEG, то экспорт в файл не производится.
mglGraph
: void
WriteGIF (const char *
fname, const char *
descr=""
)
¶void
mgl_write_gif (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в GIF файл. Параметры функции следующие: fname – имя файла, descr – описание файла. Если при компиляции MathGL не был определен флаг HAVE_GIF, то экспорт в файл не производится.
mglGraph
: void
WriteBMP (const char *
fname, const char *
descr=""
)
¶void
mgl_write_bmp (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в BMP файл. Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
WriteTGA (const char *
fname, const char *
descr=""
)
¶void
mgl_write_tga (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в TGA файл. Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
WriteEPS (const char *
fname, const char *
descr=""
)
¶void
mgl_write_eps (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в EPS файл, используя векторное представление графика. Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла. Если имя файла оканчивается на ‘z’ (например, ‘fname.eps.gz’), то файл автоматически архивируется в формате gzip. Отмечу, что формат EPS не поддерживает интерполяцию цвета, и картинка будет выглядеть как при использовании quality=1.
mglGraph
: void
WriteBPS (const char *
fname, const char *
descr=""
)
¶void
mgl_write_eps (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в EPS файл, используя растровое представление графика. Параметры функции следующие: fname – имя файла, descr – описание файла. Если имя файла оканчивается на ‘z’ (например, ‘fname.eps.gz’), то файл автоматически архивируется в формате gzip.
mglGraph
: void
WriteSVG (const char *
fname, const char *
descr=""
)
¶void
mgl_write_svg (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в SVG файл, используя векторное представление графика. Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла. Если имя файла оканчивается на ‘z’ (например, ‘fname.svgz’), то файл автоматически архивируется в формате gzip. Отмечу, что формат SVG не поддерживает интерполяцию цвета, и картинка будет выглядеть как при использовании quality=1.
mglGraph
: void
WriteTEX (const char *
fname, const char *
descr=""
)
¶void
mgl_write_tex (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в LaTeX файл (пакет Tikz/PGF), используя векторное представление графика. Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла. Отмечу, что сейчас отсутствует изменение размера текста (например, в subplot), что может приводить к неправильному положению надписей.
mglGraph
: void
WritePRC (const char *
fname, const char *
descr=""
, bool
make_pdf=true
)
¶void
mgl_write_prc (HMGL
gr, const char *
fname, const char *
descr, int
make_pdf)
¶Экспортирует текущий кадр в PRC файл, используя векторное представление графика (см. http://en.wikipedia.org/wiki/PRC_%28file_format%29). Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла. Если параметр make_pdf=true
и PDF был выбран при конфигурировании MathGL, то также создается соответствующий PDF файл с 3D изображением.
mglGraph
: void
WriteOBJ (const char *
fname, const char *
descr=""
)
¶void
mgl_write_obj (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в OBJ/MTL файл, используя векторное представление графика (см. OBJ формат). Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
WriteXYZ (const char *
fname, const char *
descr=""
)
¶void
mgl_write_xyz (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в XYZ/XYZL/XYZF файлы, используя векторное представление графика (см. XYZ формат). Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
WriteSTL (const char *
fname, const char *
descr=""
)
¶void
mgl_write_stl (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует текущий кадр в STL файл, используя векторное представление графика (см. STL формат). Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
WriteOFF (const char *
fname, const char *
descr=""
, bool
colored=false
)
¶void
mgl_write_off (HMGL
gr, const char *
fname, const char *
descr, bool
colored)
¶Экспортирует текущий кадр в OFF файл, используя векторное представление графика (см. OFF формат). Вследствие чего не рекомендуется сохранять большие графики (поверхности, а особенно поверхности уровня) из-за большого размера файла. Хотя никаких внутренних ограничений на размер выходного файла нет. Для них лучше использовать растровый формат (например, PNG или JPEG). Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
ShowImage (const char *
viewer, bool
nowait=false
)
¶void
mgl_show_image (const char *
viewer, int
nowait)
¶Отображает текущий кадр используя внешнюю программу просмотра viewer. Функция сохраняет картинку во временный файл и вызывает viewer для его отображения. Если nowait=true
, то функция возвращает управление немедленно – не ждет пока окно просмотра будет закрыто.
mglGraph
: void
WriteJSON (const char *
fname, const char *
descr=""
)
¶void
mgl_write_json (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует точки и примитивы в текстовый файл используя JSON format. В дальнейшем этот файл можно загрузить и просмотреть в JavaScript скрипте. Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
ExportMGLD (const char *
fname, const char *
descr=""
)
¶void
mgl_export_mgld (HMGL
gr, const char *
fname, const char *
descr)
¶Экспортирует точки и примитивы в файл MGLD format. В дальнейшем этот файл можно загрузить и просмотреть с помощью mglview
. Параметры функции следующие: fname – имя файла, descr – описание файла.
mglGraph
: void
ImportMGLD (const char *
fname, bool
add=false
)
¶void
mgl_import_mgld (HMGL
gr, const char *
fname, int
add)
¶Импортирует точки и примитивы из файла в MGLD format. Параметры функции следующие: fname – имя файла, add – флаг добавления или замены существующих точек и примитивов.
Эти функции позволяют создавать несколько картинок одновременно. В большинстве случаев это бесполезно, но для органов управления (см. “Оконные” классы) это позволяет показывать анимацию. Также можно записать несколько кадров в анимированный GIF файл.
mglGraph
: void
NewFrame ()
¶void
mgl_new_frame (HMGL
gr)
¶Создает новый кадр. Функция возвращает номер текущего кадра. В режиме OpenGL функция не должны вызываться в параллельных потоках! – используйте прямое создание списка. Функция EndFrame()
должна быть вызвана после рисования кадра для каждого вызова этой функции.
mglGraph
: void
EndFrame ()
¶void
mgl_end_frame (HMGL
gr)
¶Завершает рисование кадра.
mglGraph
: int
GetNumFrame ()
¶int
mgl_get_num_frame (HMGL
gr)
¶Возвращает число созданных кадров.
mglGraph
: void
GetFrame (int
i)
¶void
mgl_get_frame (HMGL
gr, int
i)
¶Завершает рисование кадра и сохраняет объекты рисования в кадр с номером i, который должен быть в диапазоне [0, GetNumFrame()
-1]. Функция аналогична EndFrame()
, но не добавляет кадр в GIF изображение.
mglGraph
: void
GetFrame (int
i)
¶void
mgl_get_frame (HMGL
gr, int
i)
¶Заменяет объекты рисования на объекты из кадра с номером i. Функция работает если установлен флаг MGL_VECT_FRAME
(по умолчанию).
mglGraph
: void
ShowFrame (int
i)
¶void
mgl_show_frame (HMGL
gr, int
i)
¶Добавляет объекты рисования из кадра с номером i к уже существующим. Функция работает если установлен флаг MGL_VECT_FRAME
(по умолчанию).
mglGraph
: void
DelFrame (int
i)
¶void
mgl_del_frame (HMGL
gr, int
i)
¶Удаляет объекты рисования для кадра с номером i и сдвигает нумерацию всех последующих кадров. Функция работает если установлен флаг MGL_VECT_FRAME
(по умолчанию).
mglGraph
: void
ResetFrames ()
¶void
mgl_reset_frames (HMGL
gr)
¶Сбрасывает счетчик кадров в 0.
mglGraph
: void
ClearFrame (int
i)
¶void
mgl_clear_frame (HMGL
gr, int
i)
¶Очищает текущий список объектов.
mglGraph
: void
StartGIF (const char *
fname, int
ms=100
)
¶void
mgl_start_gif (HMGL
gr, const char *
fname, int
ms)
¶Начинает запись кадров в анимированный GIF файл fname. Параметр ms задает задержку между кадрами в миллисекундах. Вы не должны менять размер рисунка во время создания кино. Используйте CloseGIF() для завершения записи. Эта функция не работает в режиме OpenGL.
mglGraph
: void
CloseGIF ()
¶void
mgl_close_gif (HMGL
gr)
¶Завершает запись анимированного GIF файла.
Эти функции возвращают созданный растровый рисунок, его ширину и высоту. В дальнейшем его можно использовать в любой графической библиотеке (см. также, “Оконные” классы) или сохранить в файл (см. также, Экспорт в файл).
mglGraph
: const unsigned char *
GetRGB ()
¶mglGraph
: void
GetRGB (char *
buf, int
size)
¶mglGraph
: void
GetBGRN (char *
buf, int
size)
¶const unsigned char *
mgl_get_rgb (HMGL
gr)
¶Возвращает растровое изображение в формате RGB для текущего кадра. Формат каждого элемента (пикселя): {red, green, blue}. Число элементов Width*Height. Положение элемента {i,j} есть [3*i + 3*Width*j] (или [4*i + 4*Width*j] для GetBGRN()
). В Python вы должны предоставить буфер buf достаточного размера size, т.е. код должен выглядеть следующим образом (для Python)
from mathgl import * gr = mglGraph(); bits='\t'; bits=bits.expandtabs(4*gr.GetWidth()*gr.GetHeight()); gr.GetBGRN(bits, len(bits));
mglGraph
: const unsigned char *
GetRGBA ()
¶mglGraph
: void
GetRGBA (char *
buf, int
size)
¶const unsigned char *
mgl_get_rgba (HMGL
gr)
¶Возвращает растровое изображение в формате RGBA для текущего кадра. Формат каждого элемента (пикселя): {red, green, blue, alpha}. Число элементов Width*Height. Положение элемента {i,j} есть [4*i + 4*Width*j].
mglGraph
: int
GetWidth ()
¶mglGraph
: int
GetHeight ()
¶int
mgl_get_width (HMGL
gr)
¶int
mgl_get_height (HMGL
gr)
¶Возвращает ширину и высоту изображения.
mglGraph
: mglPoint
CalcXYZ (int
xs, int
ys)
¶void
mgl_calc_xyz (HMGL
gr, int
xs, int
ys, mreal *
x, mreal *
y, mreal *
z)
¶Вычисляет 3D координаты {x,y,z} для экранной точки {xs,ys}. В данный момент игнорируется перспектива графика и формулы перехода в криволинейные координаты. Вычисления производятся для последнего использованного InPlot (см. Матрица преобразования).
mglGraph
: mglPoint
CalcScr (mglPoint
p)
¶void
mgl_calc_scr (HMGL
gr, mreal
x, mreal
y, mreal
z, int *
xs, int *
ys)
¶Вычисляет экранные координаты {xs,ys} для 3D координат {x,y,z}. Вычисления производятся для последнего использованного InPlot (см. Матрица преобразования).
mglGraph
: void
SetObjId (int
id)
¶void
mgl_set_obj_id (HMGL
gr, int
id)
¶Задает числовой идентификатор для объектов или subplot/inplot.
mglGraph
: int
GetObjId (int
xs, int
ys)
¶int
mgl_get_obj_id (HMGL
gr, int
xs, int
ys)
¶Возвращает числовой идентификатор верхнего объекта в точке {xs, ys} рисунка. Следует отметить, что все графики из одной строки MGL скрипта имеют одинаковый идентификатор.
mglGraph
: int
GetSplId (int
xs, int
ys)
¶int
mgl_get_spl_id (HMGL
gr, int
xs, int
ys)
¶Возвращает числовой идентификатор верхнего "подграфика" в точке {xs, ys} рисунка.
mglGraph
: void
Highlight (int
id)
¶void
mgl_highlight (HMGL
gr, int
id)
¶Выделяет объект с заданным id.
mglGraph
: long
IsActive (int
xs, int
ys, int
d=1
)
¶long
mgl_is_active (HMGL
gr, int
xs, int
ys, int
d)
¶Проверяет близка ли точка {xs, ys} к активной точке (т.е. mglBase::Act) с точностью d и возвращает индекс активной точки или -1
если не найдено. Активные точки – специальные точки, которые характеризуют примитивы (например, вершины). Это функция только для опытных пользователей.
mglGraph
: long
SetDrawReg (int
nx=1
, int
ny=1
, int
m=0
)
¶long
mgl_set_draw_reg (HMGL
gr, int
nx, int
ny, int
m)
¶Ограничивает рисование прямоугольной областью m-ой клетки матрицы размером nx*ny (аналогично subplot). Функция может бытб использована для ускорения вывода путем уменьшения выводимых примитивов. Это функция только для опытных пользователей.
Многие функции MathGL используют несколько потоков для ускорения работы (если MathGL была собрана с поддержкой pthread). При этом можно настраивать число используемых потоков.
int
mgl_set_num_thr (int
n)
¶Задает число потоков, которое будет использовано в MathGL. При n<1 число потоков задается как максимальное число процессоров (ядер) в системе. При n=1 не используется распараллеливание.
Другая возможность – комбинирование изображений из разных объектов mglGraph
. Эти методы наиболее подходят для компьютерных кластеров, когда данные настолько велики, что не могут поместиться в памяти отдельного компьютера.
mglGraph
: int
Combine (const mglGraph *
g)
¶int
mgl_combine_gr (HMGL
gr, HMGL
g)
¶Комбинирует (добавляет) рисунок из g с gr, принимая во внимание “высоту” пикселей. Ширина и высота обоих рисунков должна быть одинаковы.
mglGraph
: int
MPI_Send (int
id)
¶int
mgl_mpi_send (HMGL
gr, int
id)
¶Посылает рисунок из компьютера (ноды) id, используя MPI. Ширина и высота обоих рисунков должна быть одинаковы.
mglGraph
: int
MPI_Recv (int
id)
¶int
mgl_mpi_send (HMGL
gr, int
id)
¶Принимает рисунок из компьютера (ноды) id, используя MPI. Ширина и высота обоих рисунков должна быть одинаковы.
These functions change background image.
['col']
¶r g b
¶mglGraph
: void
Clf ()
¶mglGraph
: void
Clf (const char *
col)
¶mglGraph
: void
Clf (char
col)
¶mglGraph
: void
Clf (mreal
r, mreal
g, mreal
b)
¶void
mgl_clf (HMGL
gr)
¶void
mgl_clf_str (HMGL
gr, const char *
col)
¶void
mgl_clf_chr (HMGL
gr, char
col)
¶void
mgl_clf_rgb (HMGL
gr, mreal
r, mreal
g, mreal
b)
¶void
mgl_clf_rgba (HMGL
gr, mreal
r, mreal
g, mreal
b, mreal
a)
¶Очищает рисунок и заполняет фон заданным цветом.
mglGraph
: void
Rasterize ()
¶void
mgl_rasterize (HMGL
gr)
¶Завершает рисование графика и помещает результат в качестве фона. После этого, очищает список примитивов (как clf). Функция полезна для сохранения части графика (например, поверхностей или векторных полей) в растровом виде, а другой части (кривых, осей и пр.) в векторном. Часто требуется вызвать команду subplot после rasterize во избежание выделения дополнительного места или вращения графика.
'fname' [alpha=1
]
¶'fname' 'how' [alpha=1
]
¶mglGraph
: void
LoadBackground (const char *
fname, double
alpha=1
)
¶void
mgl_load_background (HMGL
gr, const char *
fname, double
alpha)
¶mglGraph
: void
LoadBackground (const char *
fname, const char *
how, double
alpha=1
)
¶void
mgl_load_background_ext (HMGL
gr, const char *
fname, const char *
how, double
alpha)
¶Загружает PNG или JPEG файл fname в качестве фона для графика. Параметр alpha задает прозрачность фона вручную. Параметр how может содержать: ‘a’ для заполнения текущего subplot, ‘s’ для растягивания на всю область, ‘c’ для центрирования, ‘m’ для заполнения мозаикой.
[r g b
]
¶mglGraph
: void
FillBackground (const mglColor &
rgb)
¶void
mgl_fill_background (HMGL
gr, double
r, double
g, double
b, double
a)
¶Заполняет фон указанным цветом. Значения должны быть в диапазоне от 0 до 1.
Эти функции рисуют рисуют простые объекты типа линий, точек, сфер, капель, конусов, и т.д.
x y
['col'='r.']
¶x y z
['col'='r.']
¶mglGraph
: void
Ball (mglPoint
p, char
col='r'
)
¶mglGraph
: void
Mark (mglPoint
p, const char *
mark)
¶void
mgl_mark (HMGL
gr, mreal
x, mreal
y, mreal
z, const char *
mark)
¶Рисует маркер (точку по умолчанию) с координатами p={x, y, z} и цветом col.
x y ex ey
['stl'='']
¶x y z ex ey ez
['stl'='']
¶mglGraph
: void
Error (mglPoint
p, mglPoint
e, char
*stl=""
)
¶void
mgl_error_box (HMGL
gr, mreal
px, mreal
py, mreal
pz, mreal
ex, mreal
ey, mreal
ez, char *
stl)
¶Рисует 3d error box в точке p={x, y, z} размером e={ex, ey, ez} и стилем stl. Используйте NAN в компонентах e для уменьшения рисуемых элементов.
x1 y1 x2 y2
['stl'='']
¶x1 y1 z1 x2 y2 z2
['stl'='']
¶mglGraph
: void
Line (mglPoint
p1, mglPoint
p2, char *
stl="B"
, int
num=2
)
¶void
mgl_line (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
x2, mreal
y2, mreal
z2, char *
stl, int
num)
¶Рисует геодезическую линию (декартовых координатах – прямую) из точки p1 в p2 использую стиль линии stl. Параметр num определяет гладкость линии (число точек на линии). Если num=2
, то рисуется прямая даже в криволинейных координатах (см. Криволинейные координаты). Наоборот, для больших значений (например, =100
) рисуется геодезическая линия (окружность в полярных координатах, парабола в параболических и т.д.). Линия рисуется даже если часть ее лежит вне диапазона осей координат.
x1 y1 dx1 dy1 x2 y2 dx2 dy2
['stl'='']
¶x1 y1 z1 dx1 dy1 dz1 x2 y2 z2 dx2 dy2 dz2
['stl'='']
¶mglGraph
: void
Curve (mglPoint
p1, mglPoint
d1, mglPoint
p2, mglPoint
d2, const char *
stl="B"
, int
num=100
)
¶void
mgl_curve (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
dx1, mreal
dy1, mreal
dz1, mreal
x2, mreal
y2, mreal
z2, mreal
dx2, mreal
dy2, mreal
dz2, const char *
stl, int
num)
¶Рисует кривую Безье из точки p1 в p2 используя стиль линии stl. Касательные в точках пропорциональны d1, d2. Параметр num определяет гладкость линии (число точек на линии). Если num=2
, то рисуется прямая даже в криволинейных координатах (см. Криволинейные координаты). Наоборот, для больших значений (например, =100
) рисуется геодезическая линия (окружность в полярных координатах, парабола в параболических и т.д.). Кривая рисуется даже если часть ее лежит вне диапазона осей координат.
x1 y1 x2 y2 x3 y3 x4 y4
['stl'='']
¶x1 y1 z1 x2 y2 z2 x3 y3 z3 x4 y4 z4
['stl'='']
¶mglGraph
: void
Face (mglPoint
p1, mglPoint
p2, mglPoint
p3, mglPoint
p4, const char *
stl="w"
)
¶void
mgl_face (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
x2, mreal
y2, mreal
z2, mreal
x3, mreal
y3, mreal
z3, mreal
x4, mreal
y4, mreal
z4, const char *
stl)
¶Рисует заполненный четырехугольник (грань) с углами в точках p1, p2, p3, p4 и цветом(-ами) stl. При этом цвет может быть один для всей грани, или различным если указаны все 4 цвета. Грань будет нарисована даже если часть ее лежит вне диапазона осей координат. Параметр stl может также содержать параметры маски (см. Цветовая схема).
x1 y1 x2 y2
['stl'='']
¶x1 y1 z1 x2 y2 z2
['stl'='']
¶Рисует закрашенный прямоугольник (грань) с вершинами {x1, y1, z1} и {x2, y2, z2} цветом stl. При этом цвет может быть один для всей грани, или различным для разных вершин если указаны все 4 цвета. Грань будет нарисована даже если часть ее лежит вне диапазона осей координат. Параметр stl может также содержать параметры маски (см. Цветовая схема).
x0 y0 z0 wy wz
['stl'='' d1=0 d2=0
]
¶x0 y0 z0 wx wz
['stl'='' d1=0 d2=0
]
¶x0 y0 z0 wx wy
['stl'='' d1=0 d2=0
]
¶mglGraph
: void
FaceX (mreal
x0, mreal
y0, mreal
z0, mreal
wy, mreal
wz, const char *
stl="w"
, mreal
d1=0
, mreal
d2=0
)
¶mglGraph
: void
FaceY (mreal
x0, mreal
y0, mreal
z0, mreal
wx, mreal
wz, const char *
stl="w"
, mreal
d1=0
, mreal
d2=0
)
¶mglGraph
: void
FaceZ (mreal
x0, mreal
y0, mreal
z0, mreal
wx, mreal
wy, const char *
stl="w"
, mreal
d1=0
, mreal
d2=0
)
¶void
mgl_facex (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
wy, mreal
wz, const char *
stl, mreal
d1, mreal
d2)
¶void
mgl_facey (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
wx, mreal
wz, const char *
stl, mreal
d1, mreal
d2)
¶void
mgl_facez (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
wx, mreal
wy, const char *
stl, mreal
d1, mreal
d2)
¶Рисует закрашенный прямоугольник (грань) перпендикулярно оси [x,y,z] в точке {x0, y0, z0} цветом stl и шириной wx, wy, wz вдоль соответствующего направления. При этом цвет может быть один для всей грани, или различным для разных вершин если указаны все 4 цвета. Параметр stl может также содержать параметры маски (см. Цветовая схема). Параметры d1!=0, d2!=0 задают дополнительный сдвиг последней точки (т.е. рисуют четырехугольник). Грань будет нарисована даже если часть ее лежит вне диапазона осей координат.
x0 y0 r
['col'='r']
¶x0 y0 z0 r
['col'='r']
¶mglGraph
: void
Sphere (mglPoint
p, mreal
r, const char *
stl="r"
)
¶void
mgl_sphere (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
r, const char *
stl)
¶Рисует сферу радиуса r с центром в точке p={x0, y0, z0} цветом stl.
x0 y0 dx dy r
['col'='r' sh=1 asp=1
]
¶x0 y0 z0 dx dy dz r
['col'='r' sh=1 asp=1
]
¶mglGraph
: void
Drop (mglPoint
p, mglPoint
d, mreal
r, const char *
col="r"
, mreal
shift=1
, mreal
ap=1
)
¶void
mgl_drop (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
dx, mreal
dy, mreal
dz, mreal
r, const char *
col, mreal
shift, mreal
ap)
¶Рисует каплю радиуса r в точке p вытянутую вдоль направления d цветом col. Параметр shift определяет степень вытянутости: ‘0’ – сфера, ‘1’ – классическая капля. Параметр ap определяет относительную ширину капли (аналог "эллиптичности" для сферы).
x1 y1 z1 x2 y2 z2 r1
[r2=-1
'stl'='' edge=off
]
¶mglGraph
: void
Cone (mglPoint
p1, mglPoint
p2, mreal
r1, mreal
r2=-1
, const char *
stl="B"
, bool
edge=false
)
¶void
mgl_cone (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
x2, mreal
y2, mreal
z2, mreal
r1, mreal
r2, const char *
stl, int
draw_edge)
¶Рисует трубу (или усеченный конус если edge=false
) между точками p1, p2 с радиусами на концах r1, r2. Если r2<0, то полагается r2=r1. Цвет конуса задается строкой stl. Параметр stl может содержать:
x0 y0 r
['col'='r']
¶x0 y0 z0 r
['col'='r']
¶mglGraph
: void
Circle (mglPoint
p, mreal
r, const char *
stl="r"
)
¶Рисует круг радиуса r с центром в точке p={x0, y0, z0} цветом stl. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными). Параметр col может также содержать параметры маски (см. Цветовая схема).
x1 y1 x2 y2 r
['col'='r']
¶x1 y1 z1 x2 y2 z2 r
['col'='r']
¶mglGraph
: void
Ellipse (mglPoint
p1, mglPoint
p2, mreal
r, const char *
col="r"
)
¶void
mgl_ellipse (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
x2, mreal
y2, mreal
z2, mreal
r, const char *
col)
¶Рисует эллипс радиуса r с фокусами в точках p1, p2 цветом stl. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными). Параметр col может также содержать параметры маски (см. Цветовая схема).
x1 y1 x2 y2 r
['col'='r']
¶x1 y1 z1 x2 y2 z2 r
['col'='r']
¶mglGraph
: void
Rhomb (mglPoint
p1, mglPoint
p2, mreal
r, const char *
col="r"
)
¶void
mgl_rhomb (HMGL
gr, mreal
x1, mreal
y1, mreal
z1, mreal
x2, mreal
y2, mreal
z2, mreal
r, const char *
col)
¶Рисует ромб ширины r с вершинами в точках p1, p2 цветом stl. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными). Если col содержит 3 цвета, то используется градиентная заливка. Параметр col может также содержать параметры маски (см. Цветовая схема).
x0 y0 x1 y1 a
['col'='r']
¶x0 y0 z0 x1 y1 a
['col'='r']
¶x0 y0 z0 xa ya za x1 y1 z1 a
['col'='r']
¶mglGraph
: void
Arc (mglPoint
p0, mglPoint
p1, mreal
a, const char *
col="r"
)
¶mglGraph
: void
Arc (mglPoint
p0, mglPoint
pa, mglPoint
p1, mreal
a, const char *
col="r"
)
¶void
mgl_arc (HMGL
gr, mreal
x0, mreal
y0, mreal
x1, mreal
y1, mreal
a, const char *
col)
¶void
mgl_arc_ext (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
xa, mreal
ya, mreal
za, mreal
x1, mreal
y1, mreal
z1, mreal
a, const char *
col)
¶Рисует дугу вокруг оси pa (по умолчанию вокруг оси z pa={0,0,1}) с центром в p0, начиная с точки p1. Параметр a задает угол дуги в градусах. Строка col задает цвет дуги и тип стрелок на краях.
x0 y0 x1 y1 num
['col'='r']
¶x0 y0 z0 x1 y1 z1 num
['col'='r']
¶mglGraph
: void
Polygon (mglPoint
p0, mglPoint
p1, int
num, const char *
col="r"
)
¶void
mgl_polygon (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, mreal
x1, mreal
y1, mreal
z1, int
num, const char *
col)
¶Рисует правильный num-угольник с центром в p0 с первой вершиной в p1 цветом col. Если col содержит: ‘#’ то рисуется только граница, ‘@’ то рисуется граница (вторым цветом из col или черными). Параметр col может также содержать параметры маски (см. Цветовая схема).
'fname' [smooth=off]
¶mglGraph
: void
Logo (const char *
fname, bool
smooth=false
, const char *
opt=""
)
¶mglGraph
: void
Logo (long
w, long
h, const unsigned char *
rgba, bool
smooth=false
, const char *
opt=""
)
¶void
mgl_logo (HMGL
gr, long
w, long
h, const unsigned char *
rgba, bool
smooth, const char *
opt)
¶void
mgl_logo_file (HMGL
gr, const char *
fname, bool
smooth, const char *
opt)
¶Draw bitmap (logo) along whole axis range, which can be changed by Опции команд. Bitmap can be loaded from file or specified as RGBA values for pixels. Parameter smooth set to draw bitmap without or with color interpolation.
x y
'id' ['fnt'='' size=-1
]
¶x y z
'id' ['fnt'='' size=-1
]
¶mglGraph
: void
Symbol (mglPoint
p, char
id, const char *
fnt=""
, mreal
size=-1
)
¶void
mgl_symbol (HMGL
gr, mreal
x, mreal
y, mreal
z, char
id, const char *
fnt, mreal
size)
¶Рисует определенный пользователем символ с именем id в точке p стилем fnt. Размер задается параметром size (по умолчанию -1
). Строка fnt может содержать цвет (до разделителя ‘:’); стили ‘a’ или ‘A’ для вывода в абсолютной позиции ({x, y} полагаются в диапазоне [0,1]) относительно рисунка (для ‘A’) или subplot/inplot (для ‘a’); и стиль ‘w’ для рисования только контура символа.
x y dx dy
'id' ['fnt'=':L' size=-1
]
¶x y z dx dy dz
'id' ['fnt'=':L' size=-1
]
¶mglGraph
: void
Symbol (mglPoint
p, mglPoint
d, char
id, const char *
fnt=""
, mreal
size=-1
)
¶void
mgl_symbol_dir (HMGL
gr, mreal
x, mreal
y, mreal
z, mreal
dx, mreal
dy, mreal
dz, const char *
text, const char *
fnt, mreal
size)
¶Аналогично предыдущему, но символ рисуется в повернутым в направлении d.
'id' xdat ydat
¶mglGraph
: void
DefineSymbol (char
id, const mglDataA &
xdat, const mglDataA &
ydat)
¶void
mgl_define_symbol (HMGL
gr, HCDT
xdat, HCDT
ydat)
¶Добавляет определенный пользователем символ с именем id и границей {xdat, ydat}. Значения NAN
задают разрыв (скачок) граничной кривой.
Функции для вывода текста позволяют вывести строку текста в произвольном месте рисунка, в произвольном направлении и вдоль произвольной кривой. MathGL позволяет использовать произвольное начертание шрифта и многие ТеХ-ие команды (детальнее см. Стиль текста). Все функции вывода текста имеют варианты для 8-bit строк (char *
) и для Unicode строк (wchar_t *
). В первом случае используется конверсия из текущей локали, т.е. иногда вам требуется явно указать локаль с помощью функции setlocale()
. Аргумент size определяет размер текста: размер шрифта если положителен или относительный размер (=-size*SetFontSize()
) если отрицателен. Начертание шрифта (STIX, arial, courier, times и др.) можно изменить с помощью функции LoadFont(). See Шрифты.
Параметры шрифта задаются строкой, которая может содержать символы цвета ‘wkrgbcymhRGBCYMHW’ (см. Цвета). Также после символа ‘:’ можно указать символы стиля (‘rbiwou’) и/или выравнивания (‘LRCTV’). Стили шрифта: ‘r’ – прямой, ‘i’ – курсив, ‘b’ – жирный, ‘w’ – контурный, ‘o’ – надчеркнутый, ‘u’ – подчеркнутый. По умолчанию используется прямой шрифт. Типы выравнивания: ‘L’ – по левому краю (по умолчанию), ‘C’ – по центру, ‘R’ – по правому краю, ‘T’ – под текстом, ‘V’ – по центру вертикально. Например, строка ‘b:iC’ соответствует курсиву синего цвета с выравниванием по центру. Начиная с MathGL версии 2.3, вы можете задать цветовой градиент для выводимой строки (см. Цветовая схема).
Если строка содержит символы ‘aA’, то текст выводится в абсолютных координатах (полагаются в диапазоне [0,1]). При этом используются координаты относительно рисунка (если указано ‘A’) или относительно последнего subplot/inplot (если указано ‘a’). Если строка содержит символ ‘@’, то вокруг текста рисуется прямоугольник.
См. раздел Text features, для примеров кода и графика.
x y
'text' ['fnt'='' size=-1
]
¶x y z
'text' ['fnt'='' size=-1
]
¶mglGraph
: void
Puts (mglPoint
p, const char *
text, const char *
fnt=":C"
, mreal
size=-1
)
¶mglGraph
: void
Putsw (mglPoint
p, const wchar_t *
text, const char *
fnt=":C"
, mreal
size=-1
)
¶mglGraph
: void
Puts (mreal
x, mreal
y, const char *
text, const char *
fnt=":AC"
, mreal
size=-1
)
¶mglGraph
: void
Putsw (mreal
x, mreal
y, const wchar_t *
text, const char *
fnt=":AC"
, mreal
size=-1
)
¶void
mgl_puts (HMGL
gr, mreal
x, mreal
y, mreal
z, const char *
text, const char *
fnt, mreal
size)
¶void
mgl_putsw (HMGL
gr, mreal
x, mreal
y, mreal
z, const wchar_t *
text, const char *
fnt, mreal
size)
¶Выводит строку text от точки p шрифтом определяемым строкой fnt. Размер шрифта задается параметром size (по умолчанию -1
).
x y dx dy
'text' ['fnt'=':L' size=-1
]
¶x y z dx dy dz
'text' ['fnt'=':L' size=-1
]
¶mglGraph
: void
Puts (mglPoint
p, mglPoint
d, const char *
text, const char *
fnt=':L'
, mreal
size=-1
)
¶mglGraph
: void
Putsw (mglPoint
p, mglPoint
d, const wchar_t *
text, const char *
fnt=':L'
, mreal
size=-1
)
¶void
mgl_puts_dir (HMGL
gr, mreal
x, mreal
y, mreal
z, mreal
dx, mreal
dy, mreal
dz, const char *
text, const char *
fnt, mreal
size)
¶void
mgl_putsw_dir (HMGL
gr, mreal
x, mreal
y, mreal
z, mreal
dx, mreal
dy, mreal
dz, const wchar_t *
text, const char *
fnt, mreal
size)
¶Выводит строку text от точки p вдоль направления d. Параметр fnt задает стиль текста и указывает выводить текст под линией (‘T’) или над ней (‘t’).
x y
'fname' [n=0
'fnt'='' size=-1.4
]
¶x y z
'fname' [n=0
'fnt'='' size=-1.4
]
¶Выводит n-ую строку файла fname от точки {x,y,z} шрифтом fnt и размером size. По умолчанию используются параметры заданные командой font.
ydat 'text' ['fnt'='']
¶xdat ydat 'text' ['fnt'='' size=-1 zval=nan
]
¶xdat ydat zdat 'text' ['fnt'='' size=-1
]
¶mglGraph
: void
Text (const mglDataA &
y, const char *
text, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Text (const mglDataA &
y, const wchar_t *
text, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Text (const mglDataA &
x, const mglDataA &
y, const char *
text, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Text (const mglDataA &
x, const mglDataA &
y, const wchar_t *
text, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Text (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
text, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Text (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const wchar_t *
text, const char *
fnt=""
, const char *
opt=""
)
¶void
mgl_text_y (HMGL
gr, HCDT
y, const char *
text, const char *
fnt, const char *
opt)
¶void
mgl_textw_y (HMGL
gr, HCDT
y, const wchar_t *
text, const char *
fnt, const char *
opt)
¶void
mgl_text_xy (HCDT
x, HCDT
y, const char *
text, const char *
fnt, const char *
opt)
¶void
mgl_textw_xy (HCDT
x, HCDT
y, const wchar_t *
text, const char *
fnt, const char *
opt)
¶void
mgl_text_xyz (HCDT
x, HCDT
y, HCDT
z, const char *
text, const char *
fnt, const char *
opt)
¶void
mgl_textw_xyz (HCDT
x, HCDT
y, HCDT
z, const wchar_t *
text, const char *
fnt, const char *
opt)
¶Выводит строку text вдоль кривой {x[i], y[i], z[i]} шрифтом fnt. Строка fnt может содержать символы: ‘t’ для вывода текста под кривой (по умолчанию), или ‘T’ для вывода текста под кривой. Размеры по 1-ой размерности должны быть одинаковы для всех массивов x.nx=y.nx=z.nx
. Если массив x не указан, то используется "автоматический" массив со значениями в диапазоне осей координат (см. Масштаб осей координат). Если массив z не указан, то используется минимальное значение оси z. Строка opt содержит опции команды (см. Опции команд).
Эти функции рисуют объекты для "измерения" типа осей координат, цветовой таблицы (colorbar), сетку по осям, обрамляющий параллелепипед и подписи по осям координат. См. также см. Настройки осей координат.
['dir'='xyz' 'stl'='']
¶mglGraph
: void
Axis (const char *
dir="xyz"
, const char *
stl=""
, const char *
opt=""
)
¶void
mgl_axis (HMGL
gr, const char *
dir, const char *
stl, const char *
opt)
¶Рисует оси координат и метки на них (см. Настройки осей координат) в направлениях ‘xyz’, указанных строкой dir. Строка dir может содержать:
Стиль меток и оси(ей) задается строкой stl. Опция value
задает угол вращения меток оси. См. раздел Axis and ticks, для примеров кода и графика.
['sch'='']
¶mglGraph
: void
Colorbar (const char *
sch=""
, const char *
opt=""
)
¶void
mgl_colorbar (HMGL
gr, const char *
sch, const char *
opt)
¶Рисует полосу соответствия цвета и числовых значений (colorbar) для цветовой схемы sch (используется текущая для sch=""
) с краю от графика. Строка sch также может содержать:
См. раздел Colorbars, для примеров кода и графика.
vdat ['sch'='']
¶mglGraph
: void
Colorbar (const mglDataA &
v, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_colorbar_val (HMGL
gr, HCDT
v, const char *
sch, const char *
opt)
¶Аналогично предыдущему, но для цветовой схемы без сглаживания с заданными значениями v. См. раздел Sample ‘contd’, для примеров кода и графика.
'sch' x y [w=1 h=1]
¶mglGraph
: void
Colorbar (const char *
sch, mreal
x, mreal
y, mreal
w=1
, mreal
h=1
, const char *
opt=""
)
¶void
mgl_colorbar_ext (HMGL
gr, const char *
sch, mreal
x, mreal
y, mreal
w, mreal
h, const char *
opt)
¶Аналогично первому, но в произвольном месте графика {x, y} (полагаются в диапазоне [0,1]). Параметры w, h задают относительную ширину и высоту colorbar.
vdat 'sch' x y [w=1 h=1]
¶mglGraph
: void
Colorbar (const mglDataA &
v, const char *
sch, mreal
x, mreal
y, mreal
w=1
, mreal
h=1
, const char *
opt=""
)
¶void
mgl_colorbar_val_ext (HMGL
gr, HCDT
v, const char *
sch, mreal
x, mreal
y, mreal
w, mreal
h, const char *
opt)
¶Аналогично предыдущему, но для цветовой схемы sch без сглаживания с заданными значениями v. См. раздел Sample ‘contd’, для примеров кода и графика.
['dir'='xyz' 'pen'='B']
¶mglGraph
: void
Grid (const char *
dir="xyz"
, const char *
pen="B"
, const char *
opt=""
)
¶void
mgl_axis_grid (HMGL
gr, const char *
dir, const char *
pen, const char *
opt)
¶Рисует линии сетки в направлениях перпендикулярным dir. Если dir содержит ‘!’, то линии рисуются также и для координат под-меток. Шаг сетки такой же как у меток осей координат. Стиль линий задается параметром pen (по умолчанию – сплошная темно синяя линия ‘B-’).
['stl'='k' ticks=on
]
¶mglGraph
: void
Box (const char *
col=""
, bool
ticks=true
)
¶void
mgl_box (HMGL
gr)
¶void
mgl_box_str (HMGL
gr, const char *
col, int
ticks)
¶Рисует ограничивающий параллелепипед цветом col. Если col содержит ‘@’, то рисуются закрашенные задние грани. При этом первый цвет используется для граней (по умолчанию светло жёлтый), а последний для рёбер и меток.
'text' [pos=1
]
¶'text' [pos=1
]
¶'text' [pos=1
]
¶'text' [pos=1
]
¶'text' [pos=1
]
¶mglGraph
: void
Label (char
dir, const char *
text, mreal
pos=1
, const char *
opt=""
)
¶mglGraph
: void
Label (char
dir, const wchar_t *
text, mreal
pos=1
, const char *
opt=""
)
¶void
mgl_label (HMGL
gr, char
dir, const char *
text, mreal
pos, const char *
opt)
¶void
mgl_labelw (HMGL
gr, char
dir, const wchar_t *
text, mreal
pos, const char *
opt)
¶Выводит подпись text для оси dir=‘x’,‘y’,‘z’,‘t’,‘c’, где ‘t’ – “тернарная” ось t=1-x-y; ‘c’ – для цвета (следует вызывать после colorbar). Параметр pos задает положение подписи: при pos=0 – по центру оси, при pos>0 – около максимальных значений, при pos<0 – около минимальных значений. Опция value
задает дополнительный сдвиг текста. See Вывод текста.
Эти функции обеспечивают рисование легенды графика (полезно для 1D графики). Запись в легенде состоит из двух строк: одна для стиля линии и маркеров, другая с текстом описания (с включенным разбором TeX-их команд). Можно использовать непосредственно массивы строк, или накопление во внутренние массивы с помощью функции AddLegend() с последующим отображением. Положение легенды можно задать автоматически или вручную. Параметры fnt и size задают стиль и размер шрифта (см. Шрифты). Опция value
задает зазор между примером линии и текстом (по умолчанию 0.1). Опция size
задает размер текста. Если стиль линии пустой, то соответствующий текст печатается без отступа. Строка fnt может содержать:
См. раздел Legend sample, для примеров кода и графика.
[pos=3
'fnt'='#']
¶mglGraph
: void
Legend (int
pos=0x3
, const char *
fnt="#"
, const char *
opt=""
)
¶void
mgl_legend (HMGL
gr, int
pos, const char *
fnt, const char *
opt)
¶Рисует легенду из накопленных записей шрифтом fnt. Параметр pos задает положение легенды: ‘0’ – в нижнем левом углу, ‘1’ – нижнем правом углу, ‘2’ – верхнем левом углу, ‘3’ – верхнем правом углу (по умолчанию). Опция value
задает зазор между примером линии и текстом (по умолчанию 0.1).
x y
['fnt'='#']
¶mglGraph
: void
Legend (mreal
x, mreal
y, const char *
fnt="#"
, const char *
opt=""
)
¶void
mgl_legend_pos (HMGL
gr, mreal
x, mreal
y, const char *
fnt, const char *
opt)
¶Рисует легенду из накопленных записей шрифтом fnt. Положение легенды задается параметрами x, y, которые полагаются нормированными в диапазоне [0,1]. Опция value
задает зазор между примером линии и текстом (по умолчанию 0.1).
'text' 'stl'
¶mglGraph
: void
AddLegend (const char *
text, const char *
style)
¶mglGraph
: void
AddLegend (const wchar_t *
text, const char *
style)
¶void
mgl_add_legend (HMGL
gr, const char *
text, const char *
style)
¶void
mgl_add_legendw (HMGL
gr, const wchar_t *
text, const char *
style)
¶Добавляет описание text кривой со стилем style (см. Стиль линий) во внутренний массив записей легенды.
mglGraph
: void
ClearLegend ()
¶void
mgl_clear_legend (HMGL
gr)
¶Очищает внутренний массив записей легенды.
val
¶mglGraph
: void
SetLegendMarks (int
num)
¶void
mgl_set_legend_marks (HMGL
gr, int
num)
¶Задает число маркеров в легенде. По умолчанию используется 1 маркер.
Эти функции строят графики для одномерных (1D) массивов. Одномерными считаются массивы, зависящие только от одного параметра (индекса) подобно кривой в параметрической форме {x(i),y(i),z(i)}, i=1...n. По умолчанию (если отсутствуют) значения x[i] равно распределены в диапазоне оси х, и z[i] равно минимальному значению оси z. Графики рисуются для каждой строки массива данных если он двумерный. Размер по 1-ой координате должен быть одинаков для всех массивов x.nx=y.nx=z.nx
.
Строка pen задает цвет и стиль линии и маркеров (см. Стиль линий). По умолчанию (pen=""
) рисуется сплошная линия с текущим цветом из палитры (см. Палитра и цвета). Символ ‘!’ в строке задает использование нового цвета из палитры для каждой точки данных (не для всей кривой, как по умолчанию). Строка opt задает опции графика (см. Опции команд).
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Plot (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Plot (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Plot (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_plot (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_plot_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_plot_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют ломанную линию по точкам {x[i], y[i], z[i]}. Если pen содержит ‘a’, то рисуются и сегменты между точками вне диапазона осей координат. Если pen содержит ‘~’, то число сегментов уменьшается для квази-линейных участков. См. также area, step, stem, tube, mark, error, belt, tens, tape, meshnum. См. раздел Sample ‘plot’, для примеров кода и графика.
adat ['stl'='']
¶mglGraph
: void
Radar (const mglDataA &
a, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_radar (HMGL
gr, HCDT
a, const char *
pen, const char *
opt)
¶Функции рисуют radar chart, представляющий собой ломанную с вершинами на радиальных линиях (типа ломанной в полярных координатах). Параметр value
в опциях opt задает дополнительный сдвиг данных (т.е. использование a+value
вместо a). Если pen содержит ‘#’, то рисуется "сетка" (радиальные линии). Если pen содержит ‘a’, то рисуются и сегменты между точками вне диапазона осей координат. См. также plot, meshnum. См. раздел Sample ‘radar’, для примеров кода и графика.
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Step (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Step (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Step (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_step (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_step_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_step_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют ступеньки для точек массива. Если x.nx>y.nx, то массив x задает границы ступенек, а не их конец. См. также plot, stem, tile, boxs, meshnum. См. раздел Sample ‘step’, для примеров кода и графика.
ydat cdat ['stl'='']
¶xdat ydat cdat ['stl'='']
¶xdat ydat zdat cdat ['stl'='']
¶mglGraph
: void
Tens (const mglDataA &
y, const mglDataA &
c, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tens (const mglDataA &
x, const mglDataA &
y, const mglDataA &
c, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tens (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_tens (HMGL
gr, HCDT
y, HCDT
c, const char *
pen, const char *
opt)
¶void
mgl_tens_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
c, const char *
pen, const char *
opt)
¶void
mgl_tens_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
pen, const char *
opt)
¶Функции рисуют ломанную линию по точкам с цветом, определяемым массивом c (типа графика натяжений). Строка pen задает цветовую схему (см. Цветовая схема) и стиль линий и/или маркеров (см. Стиль линий). Если pen содержит ‘a’, то рисуются и сегменты между точками вне диапазона осей координат. Если pen содержит ‘~’, то число сегментов уменьшается для квази-линейных участков. См. также plot, mesh, fall, meshnum. См. раздел Sample ‘tens’, для примеров кода и графика.
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Tape (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tape (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tape (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_tape (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_tape_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_tape_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют ленты, которые вращаются вокруг кривой {x[i], y[i], z[i]} как её нормали. Начальная лента(ы) выбираются в плоскости x-y (для ‘x’ в pen) и/или y-z (для ‘x’ в pen). Параметр pen может также содержать параметры маски (см. Цветовая схема). Ширина лент пропорциональна barwidth, а также может быть изменена опцией value
. См. также plot, flow, barwidth. См. раздел Sample ‘tape’, для примеров кода и графика.
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Area (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Area (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Area (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_area (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_area_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_area_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют ломанную линию между точками и закрашивает её вниз до плоскости осей координат. Градиентная заливка используется если число цветов равно удвоенному число кривых. Если pen содержит ‘#’, то рисуется только каркас. Если pen содержит ‘a’, то рисуются и сегменты между точками вне диапазона осей координат. Параметр pen может также содержать параметры маски (см. Цветовая схема). См. также plot, bars, stem, region. См. раздел Sample ‘area’, для примеров кода и графика.
ydat1 ydat2 ['stl'='']
¶xdat ydat1 ydat2 ['stl'='']
¶xdat1 ydat1 xdat2 ydat2 ['stl'='']
¶xdat1 ydat1 zdat1 xdat2 ydat2 zdat2 ['stl'='']
¶mglGraph
: void
Region (const mglDataA &
y1, const mglDataA &
y2, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Region (const mglDataA &
x, const mglDataA &
y1, const mglDataA &
y2, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Region (const mglDataA &
x1, const mglDataA &
y1, const mglDataA &
x2, const mglDataA &
y2, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Region (const mglDataA &
x1, const mglDataA &
y1, const mglDataA &
z1, const mglDataA &
x2, const mglDataA &
y2, const mglDataA &
z2, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_region (HMGL
gr, HCDT
y1, HCDT
y2, const char *
pen, const char *
opt)
¶void
mgl_region_xy (HMGL
gr, HCDT
x, HCDT
y1, HCDT
y2, const char *
pen, const char *
opt)
¶void
mgl_region_3d (HMGL
gr, HCDT
x1, HCDT
y1, HCDT
z1, HCDT
x2, HCDT
y2, HCDT
z2, const char *
pen, const char *
opt)
¶Функции закрашивают область между 2 кривыми. Градиентная заливка используется если число цветов равно удвоенному число кривых. Если в 2d версии pen содержит ‘i’, то закрашивается только область y1<y<y2, в противном случае будет закрашена и область y2<y<y1. Если pen содержит ‘#’, то рисуется только каркас. Если pen содержит ‘a’, то рисуются и сегменты между точками вне диапазона осей координат. Параметр pen может также содержать параметры маски (см. Цветовая схема). См. также area, bars, stem. См. раздел Sample ‘region’, для примеров кода и графика.
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Stem (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Stem (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Stem (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_stem (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_stem_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_stem_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют вертикальные линии из точек до плоскости осей координат. См. также area, bars, plot, mark. См. раздел Sample ‘stem’, для примеров кода и графика.
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Bars (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Bars (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Bars (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_bars (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_bars_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_bars_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют вертикальные полосы (прямоугольники) из точек до плоскости осей координат. Строка pen может содержать:
Можно использовать разные цвета для положительных и отрицательных значений если число указанных цветов равно удвоенному числу кривых для построения. Если x.nx>y.nx, то массив x задает границы полос, а не их центр. См. также barh, cones, area, stem, chart, barwidth. См. раздел Sample ‘bars’, для примеров кода и графика.
vdat ['stl'='']
¶ydat vdat ['stl'='']
¶mglGraph
: void
Barh (const mglDataA &
v, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Barh (const mglDataA &
y, const mglDataA &
v, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_barh (HMGL
gr, HCDT
v, const char *
pen, const char *
opt)
¶void
mgl_barh_xy (HMGL
gr, HCDT
y, HCDT
v, const char *
pen, const char *
opt)
¶Функции рисуют горизонтальные полосы (прямоугольники) из точек до плоскости осей координат. Строка pen может содержать:
Можно использовать разные цвета для положительных и отрицательных значений если число указанных цветов равно удвоенному числу кривых для построения. Если x.nx>y.nx, то массив x задает границы полос, а не их центр. См. также bars, barwidth. См. раздел Sample ‘barh’, для примеров кода и графика.
ydat ['stl'='']
¶xdat ydat ['stl'='']
¶xdat ydat zdat ['stl'='']
¶mglGraph
: void
Cones (const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Cones (const mglDataA &
x, const mglDataA &
y, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Cones (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_cones (HMGL
gr, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_cones_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
pen, const char *
opt)
¶void
mgl_cones_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют конусы из точек до плоскости осей координат. Если строка pen содержит символ ‘a’, то линии рисуются одна поверх другой. Можно использовать разные цвета для положительных и отрицательных значений если число указанных цветов равно удвоенному числу кривых для построения. Параметр pen может содержать:
См. также bars, cone, barwidth. См. раздел Sample ‘cones’, для примеров кода и графика.
adat ['col'='']
¶mglGraph
: void
Chart (const mglDataA &
a, const char *
col=""
, const char *
opt=""
)
¶void
mgl_chart (HMGL
gr, HCDT
a, const char *
col, const char *
opt)
¶Рисует цветные полосы (пояса) для массива данных a. Число полос равно числу строк a (равно a.ny). Цвет полос поочерёдно меняется из цветов указанных в col или в палитре (см. Палитра и цвета). Пробел в цветах соответствует прозрачному "цвету", т.е. если col содержит пробел(ы), то соответствующая полоса не рисуется. Ширина полосы пропорциональна значению элемента в a. График строится только для массивов не содержащих отрицательных значений. Если строка col содержит ‘#’, то рисуется также чёрная граница полос. Параметр col может также содержать параметры маски (см. Цветовая схема). График выглядит лучше в (после вращения системы координат) и/или в полярной системе координат (становится Pie chart). См. раздел Sample ‘chart’, для примеров кода и графика.
adat ['stl'='']
¶xdat adat ['stl'='']
¶mglGraph
: void
BoxPlot (const mglDataA &
a, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
BoxPlot (const mglDataA &
x, const mglDataA &
a, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_boxplot (HMGL
gr, HCDT
a, const char *
pen, const char *
opt)
¶void
mgl_boxplot_xy (HMGL
gr, HCDT
x, HCDT
a, const char *
pen, const char *
opt)
¶Функции рисуют boxplot (называемый также как box-and-whisker diagram или как "ящик с усами") в точках x[i] на плоскости z = zVal (по умолчанию z равно минимальному значению оси z). Это график, компактно изображающий распределение вероятностей a[i,j] (минимум, нижний квартиль (Q1), медиана (Q2), верхний квартиль (Q3) и максимум) вдоль второго (j-го) направления. Если pen содержит ‘<’, ‘^’ или ‘>’, то полоски будут выровнены влево, вправо или центрированы относительно их координат. См. также plot, error, bars, barwidth. См. раздел Sample ‘boxplot’, для примеров кода и графика.
vdat1 ['stl'='']
¶vdat1 vdat2 ['stl'='']
¶vdat1 ydat1 ydat2 ['stl'='']
¶vdat1 vdat2 ydat1 ydat2 ['stl'='']
¶xdat vdat1 vdat2 ydat1 ydat2 ['stl'='']
¶mglGraph
: void
Candle (const mglDataA &
v1, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Candle (const mglDataA &
v1, const mglDataA &
v2, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Candle (const mglDataA &
v1, const mglDataA &
y1, const mglDataA &
y2, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Candle (const mglDataA &
v1, const mglDataA &
v2, const mglDataA &
y1, const mglDataA &
y2, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Candle (const mglDataA &
x, const mglDataA &
v1, const mglDataA &
v2, const mglDataA &
y1, const mglDataA &
y2, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_candle (HMGL
gr, HCDT
v1, HCDT
y1, HCDT
y2, const char *
pen, const char *
opt)
¶void
mgl_candle_yv (HMGL
gr, HCDT
v1, HCDT
v2, HCDT
y1, HCDT
y2, const char *
pen, const char *
opt)
¶void
mgl_candle_xyv (HMGL
gr, HCDT
x, HCDT
v1, HCDT
v2, HCDT
y1, HCDT
y2, const char *
pen, const char *
opt)
¶Функции рисуют candlestick chart в точках x[i]. Этот график показывает прямоугольником ("свечой") диапазон изменения величины. Прозрачная (белая) свеча соответствует росту величины v1[i]<v2[i], чёрная – уменьшению. "Тени" показывают минимальное y1 и максимальное y2 значения. Если v2 отсутствует, то он определяется как v2[i]=v1[i+1]. Можно использовать разные цвета для растущих и падающих дней если число указанных цветов равно удвоенному числу кривых для построения. Если pen содержит ‘#’, то прозрачная свеча будет использована и при 2-цветной схеме. Параметр pen может также содержать параметры маски (см. Цветовая схема). См. также plot, bars, ohlc, barwidth. См. раздел Sample ‘candle’, для примеров кода и графика.
odat hdat ldat cdat ['stl'='']
¶xdat odat hdat ldat cdat ['stl'='']
¶mglGraph
: void
OHLC (const mglDataA &
o, const mglDataA &
h, const mglDataA &
l, const mglDataA &
c, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
OHLC (const mglDataA &
x, const mglDataA &
o, const mglDataA &
h, const mglDataA &
l, const mglDataA &
c, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_ohlc (HMGL
gr, HCDT
o, HCDT
h, HCDT
l, HCDT
c, const char *
pen, const char *
opt)
¶void
mgl_ohlc_x (HMGL
gr, HCDT
x, HCDT
o, HCDT
h, HCDT
l, HCDT
c, const char *
pen, const char *
opt)
¶Функции рисуют Open-High-Low-Close диаграмму. Этот график содержит вертикальные линии между максимальным h и минимальным l значениями, и горизонтальные линии перед/после вертикальной линии для начального o и конечного c значений процесса (обычно цены). Можно использовать разные цвета для растущих и падающих дней если число указанных цветов равно удвоенному числу кривых для построения. См. также candle, plot, barwidth. См. раздел Sample ‘ohlc’, для примеров кода и графика.
ydat yerr ['stl'='']
¶xdat ydat yerr ['stl'='']
¶xdat ydat xerr yerr ['stl'='']
¶mglGraph
: void
Error (const mglDataA &
y, const mglDataA &
ey, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Error (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ey, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Error (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ex, const mglDataA &
ey, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_error (HMGL
gr, HCDT
y, HCDT
ey, const char *
pen, const char *
opt)
¶void
mgl_error_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ey, const char *
pen, const char *
opt)
¶void
mgl_error_exy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ex, HCDT
ey, const char *
pen, const char *
opt)
¶Функции рисуют размер ошибки {ex[i], ey[i]} в точках {x[i], y[i]} на плоскости z = zVal (по умолчанию z равно минимальному значению оси z). Такой график полезен для отображения ошибки эксперимента, вычислений и пр. Если pen содержит ‘@’, то будут использованы большие полупрозрачные маркеры. См. также plot, mark. См. раздел Sample ‘error’, для примеров кода и графика.
ydat rdat ['stl'='']
¶xdat ydat rdat ['stl'='']
¶xdat ydat zdat rdat ['stl'='']
¶mglGraph
: void
Mark (const mglDataA &
y, const mglDataA &
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Mark (const mglDataA &
x, const mglDataA &
y, const mglDataA &
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Mark (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
r, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_mark_y (HMGL
gr, HCDT
y, HCDT
r, const char *
pen, const char *
opt)
¶void
mgl_mark_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
r, const char *
pen, const char *
opt)
¶void
mgl_mark_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
r, const char *
pen, const char *
opt)
¶Функции рисуют маркеры размером r[i]*marksize (см. Базовые размеры) в точках {x[i], y[i], z[i]}. Для рисования маркеров одинакового размера можно использовать функцию plot с невидимой линией (со стилем содержащим ‘ ’). Для маркеров с размером как у координат можно использовать error со стилем ‘@’. См. также plot, textmark, error, stem, meshnum. См. раздел Sample ‘mark’, для примеров кода и графика.
ydat 'txt' ['stl'='']
¶ydat rdat 'txt' ['stl'='']
¶xdat ydat rdat 'txt' ['stl'='']
¶xdat ydat zdat rdat 'txt' ['stl'='']
¶mglGraph
: void
TextMark (const mglDataA &
y, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
y, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
y, const mglDataA &
r, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
y, const mglDataA &
r, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
x, const mglDataA &
y, const mglDataA &
r, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
x, const mglDataA &
y, const mglDataA &
r, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
r, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
TextMark (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
r, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶void
mgl_textmark (HMGL
gr, HCDT
y, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmarkw (HMGL
gr, HCDT
y, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmark_yr (HMGL
gr, HCDT
y, HCDT
r, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmarkw_yr (HMGL
gr, HCDT
y, HCDT
r, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmark_xyr (HMGL
gr, HCDT
x, HCDT
y, HCDT
r, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmarkw_xyr (HMGL
gr, HCDT
x, HCDT
y, HCDT
r, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmark_xyzr (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
r, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_textmarkw_xyzr (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
r, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶Функции рисуют текст txt как маркер с размером пропорциональным r[i]*marksize в точках {x[i], y[i], z[i]}. См. также plot, mark, stem, meshnum. См. раздел Sample ‘textmark’, для примеров кода и графика.
ydat 'txt' ['stl'='']
¶xdat ydat 'txt' ['stl'='']
¶xdat ydat zdat 'txt' ['stl'='']
¶mglGraph
: void
Label (const mglDataA &
y, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Label (const mglDataA &
y, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Label (const mglDataA &
x, const mglDataA &
y, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Label (const mglDataA &
x, const mglDataA &
y, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Label (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Label (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶void
mgl_label (HMGL
gr, HCDT
y, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_labelw (HMGL
gr, HCDT
y, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶void
mgl_label_xy (HMGL
gr, HCDT
x, HCDT
y, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_labelw_xy (HMGL
gr, HCDT
x, HCDT
y, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶void
mgl_label_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_labelw_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶Функции выводят текстовую строку txt в точках {x[i], y[i], z[i]}. Если строка txt содержит ‘%x’, ‘%y’, ‘%z’ или ‘%n’, то они будут заменены на значения соответствующих координат или на номер точки. Строка fnt может содержать:
См. также plot, mark, textmark, table. См. раздел Sample ‘label’, для примеров кода и графика.
vdat 'txt' ['stl'='#']
¶x y vdat 'txt' ['stl'='#']
¶mglGraph
: void
Table (const mglDataA &
val, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Table (const mglDataA &
val, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Table (mreal
x, mreal
y, const mglDataA &
val, const char *
txt, const char *
fnt=""
, const char *
opt=""
)
¶mglGraph
: void
Table (mreal
x, mreal
y, const mglDataA &
val, const wchar_t *
txt, const char *
fnt=""
, const char *
opt=""
)
¶void
mgl_table (HMGL
gr, mreal
x, mreal
y, HCDT
val, const char *
txt, const char *
fnt, const char *
opt)
¶void
mgl_tablew (HMGL
gr, mreal
x, mreal
y, HCDT
val, const wchar_t *
txt, const char *
fnt, const char *
opt)
¶Рисует таблицу значений массива val с заголовками txt (разделенными символом новой строки ‘\n’) в точке {x, y} (по умолчанию {0,0}) относительно текущего subplot. Строка fnt может содержать:
Опция value
задает ширину таблицы (по умолчанию 1). См. также plot, label. См. раздел Sample ‘table’, для примеров кода и графика.
dats 'ids' ['stl'='']
¶dats rngs 'ids' ['stl'='']
¶mglGraph
: void
Iris (const mglDataA &
dats, const char *
ids, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Iris (const mglDataA &
dats, const wchar_t *
ids, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Iris (const mglDataA &
dats, const mglDataA &
rngs, const char *
ids, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Iris (const mglDataA &
dats, const mglDataA &
rngs, const wchar_t *
ids, const char *
stl=""
, const char *
opt=""
)
¶void
mgl_iris_1 (HMGL
gr, HCDT
dats, const char *
ids, const char *
stl, const char *
opt)
¶void
mgl_irisw_1 (HMGL
gr, HCDT
dats, const wchar_t *
ids, const char *
stl, const char *
opt)
¶void
mgl_iris (HMGL
gr, HCDT
dats, HCDT
rngs, const char *
ids, const char *
stl, const char *
opt)
¶void
mgl_irisw (HMGL
gr, HCDT
dats, HCDT
rngs, const wchar_t *
ids, const char *
stl, const char *
opt)
¶Рисует Ирисы Фишера для определения зависимостей данных dats друг от друга (см. http://en.wikipedia.org/wiki/Iris_flower_data_set). Массив rngs размером 2*dats.nx задает диапазон изменения осей для каждой из колонки. Строка ids содержит имена колонок данных, разделенных символом ‘;’. Опция value
задает размер текста для имен данных. На график можно добавить новый набор данных если указать тот же размер rngs и использовать пустую строку имен ids. См. также plot. См. раздел Sample ‘iris’, для примеров кода и графика.
ydat rdat ['stl'='']
¶ydat rval
['stl'='']
¶xdat ydat rdat ['stl'='']
¶xdat ydat rval
['stl'='']
¶xdat ydat zdat rdat ['stl'='']
¶xdat ydat zdat rval
['stl'='']
¶mglGraph
: void
Tube (const mglDataA &
y, const mglDataA &
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tube (const mglDataA &
y, mreal
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tube (const mglDataA &
x, const mglDataA &
y, const mglDataA &
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tube (const mglDataA &
x, const mglDataA &
y, mreal
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tube (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
r, const char *
pen=""
, const char *
opt=""
)
¶mglGraph
: void
Tube (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, mreal
r, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_tube_r (HMGL
gr, HCDT
y, HCDT
r, const char *
pen, const char *
opt)
¶void
mgl_tube (HMGL
gr, HCDT
y, mreal
r, const char *
pen, const char *
opt)
¶void
mgl_tube_xyr (HMGL
gr, HCDT
x, HCDT
y, HCDT
r, const char *
pen, const char *
opt)
¶void
mgl_tube_xy (HMGL
gr, HCDT
x, HCDT
y, mreal
r, const char *
pen, const char *
opt)
¶void
mgl_tube_xyzr (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
r, const char *
pen, const char *
opt)
¶void
mgl_tube_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, mreal
r, const char *
pen, const char *
opt)
¶Функции рисуют трубу радиуса r[i] вдоль кривой между точками {x[i], y[i], z[i]}. Опция value
число сегментов в поперечном сечении (по умолчанию 25). См. также plot. См. раздел Sample ‘tube’, для примеров кода и графика.
rdat zdat ['stl'='']
¶mglGraph
: void
Torus (const mglDataA &
r, const mglDataA &
z, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_torus (HMGL
gr, HCDT
r, HCDT
z, const char *
pen, const char *
opt)
¶Функции рисуют поверхность вращения кривой {r, z} относительно оси. Если строка pen содержит ‘x’ или ‘z’, то ось вращения будет выбрана в указанном направлении (по умолчанию вдоль оси y). Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также plot, axial. См. раздел Sample ‘torus’, для примеров кода и графика.
x0
ydat ['stl'='']
¶x0
'y(x)' ['stl'='']
¶mglGraph
: void
Lamerey (double
x0, const mglDataA &
y, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Lamerey (double
x0, const char *
y, const char *
stl=""
, const char *
opt=""
)
¶void
mgl_lamerey_dat (HMGL
gr, double
x0, HCDT
y, const char *
stl, const char *
opt)
¶void
mgl_lamerey_str (HMGL
gr, double
x0, const char *
y, const char *
stl, const char *
opt)
¶Функции рисуют диаграмму Ламерея для точечного отображения x_new = y(x_old) начиная с точки x0. Строка stl может содержать стиль линии, символ ‘v’ для стрелок, символ ‘~’ для исключения первого сегмента. Опция value
задает число сегментов для рисования (по умолчанию 20). См. также plot, fplot, bifurcation, pmap. См. раздел Sample ‘lamerey’, для примеров кода и графика.
dx
ydat ['stl'='']
¶dx
'y(x)' ['stl'='']
¶mglGraph
: void
Bifurcation (double
dx, const mglDataA &
y, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Bifurcation (double
dx, const char *
y, const char *
stl=""
, const char *
opt=""
)
¶void
mgl_bifurcation_dat (HMGL
gr, double
dx, HCDT
y, const char *
stl, const char *
opt)
¶void
mgl_bifurcation_str (HMGL
gr, double
dx, const char *
y, const char *
stl, const char *
opt)
¶Функции рисуют бифуркационную диаграмму (диаграмму удвоения периода) для точечного отображения x_new = y(x_old). Параметр dx задает точность по оси x. Строка stl задает цвет. Опция value
задает число учитываемых стационарных точек (по умолчанию 1024). См. также plot, fplot, lamerey. См. раздел Sample ‘bifurcation’, для примеров кода и графика.
ydat sdat ['stl'='']
¶xdat ydat sdat ['stl'='']
¶xdat ydat zdat sdat ['stl'='']
¶mglGraph
: void
Pmap (const mglDataA &
y, const mglDataA &
s, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Pmap (const mglDataA &
x, const mglDataA &
y, const mglDataA &
s, const char *
stl=""
, const char *
opt=""
)
¶mglGraph
: void
Pmap (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
s, const char *
stl=""
, const char *
opt=""
)
¶void
mgl_pmap (HMGL
gr, HMDT
y, HCDT
s, const char *
stl, const char *
opt)
¶void
mgl_pmap_xy (HMGL
gr, HCDT
x, HMDT
y, HCDT
s, const char *
stl, const char *
opt)
¶void
mgl_pmap_xyz (HMGL
gr, HCDT
x, HMDT
y, HCDT
z, HCDT
s, const char *
stl, const char *
opt)
¶Функции рисуют отображение Пуанкаре для кривой {x, y, z} при условии s=0. Проще говоря, рисуются точки пересечения кривой и поверхности. Строка stl задает стиль маркеров. См. также plot, mark, lamerey. См. раздел Sample ‘pmap’, для примеров кода и графика.
Эти функции строят графики для двумерных (2D) массивов. Двумерными считаются массивы, зависящие только от двух параметров (индексов) подобно матрице f(x_i,y_j), i=1...n, j=1...m. По умолчанию (если отсутствуют) значения x, y равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z должны быть одинаковы x.nx=z.nx && y.nx=z.ny
или x.nx=y.nx=z.nx && x.ny=y.ny=z.ny
. Массивы x и y могут быть векторами (не матрицами как z). График строится для каждого z среза данных. Строка sch задает цветовую схему (см. Цветовая схема). Строка opt задает опции графика (см. Опции команд).
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Surf (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_surf_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]}. Если sch содержит ‘#’, то рисуется сетка на поверхности. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также mesh, dens, belt, tile, boxs, surfc, surfa. См. раздел Sample ‘surf’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Mesh (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Mesh (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_mesh (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_mesh_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует сетчатую поверхность, заданную параметрически {x[i,j], y[i,j], z[i,j]}. См. также surf, fall, meshnum, cont, tens. См. раздел Sample ‘mesh’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Fall (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Fall (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_fall (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_fall_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует водопад для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. График удобен для построения нескольких кривых, сдвинутых вглубь друг относительно друга. Если sch содержит ‘x’, то линии рисуются вдоль оси x, иначе (по умолчанию) вдоль оси y. См. также belt, mesh, tens, meshnum. См. раздел Sample ‘fall’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Belt (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Belt (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_belt (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_belt_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует ленточки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. График может использоваться как 3d обобщение графика plot. Если sch содержит ‘x’, то ленточки рисуются вдоль оси x, иначе (по умолчанию) вдоль оси y. См. также fall, surf, beltc, plot, meshnum. См. раздел Sample ‘belt’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Boxs (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Boxs (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_boxs (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_boxs_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует вертикальные ящики для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. См. также surf, dens, tile, step. См. раздел Sample ‘boxs’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶xdat ydat zdat cdat ['sch'='']
¶mglGraph
: void
Tile (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Tile (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Tile (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_tile (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_tile_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_tile_xyc (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶Рисует плитки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} с цветом, заданным массивом c[i,j]. Если строка sch содержит стиль ‘x’ или ‘y’, то плитки будут ориентированы перпендикулярно x- или y-оси. График может использоваться как 3d обобщение step. См. также surf, boxs, step, tiles. См. раздел Sample ‘tile’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Dens (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
, mreal
zVal=NAN
)
¶mglGraph
: void
Dens (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
, mreal
zVal=NAN
)
¶void
mgl_dens (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_dens_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует график плотности для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z равном минимальному значению оси z. Если sch содержит ‘#’, то рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf, cont, contf, boxs, tile, dens[xyz]
. См. раздел Sample ‘dens’, для примеров кода и графика.
vdat zdat ['sch'='']
¶vdat xdat ydat zdat ['sch'='']
¶mglGraph
: void
Cont (const mglDataA &
v, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Cont (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_cont__val (HMGL
gr, HCDT
v, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_cont_xy_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует линии уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. Если sch содержит ‘t’ или ‘T’, то значения v[k] будут выведены вдоль контуров над (или под) кривой. См. также dens, contf, contd, axial, cont[xyz]
. См. раздел Sample ‘cont’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Cont (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Cont (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_cont (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_cont_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7). Если sch содержит ‘.’, то будут строится только контуры по уровням седловых точек.
val
adat xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContGen (mreal
val, const mglDataA &
a, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_cont_gen (HMGL
gr, mreal
val, HCDT
a, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует линии уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при a[i,j]=val. Если sch содержит ‘t’ или ‘T’, то значения v[k] будут выведены вдоль контуров над (или под) кривой.
vdat zdat ['sch'='']
¶vdat xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContF (const mglDataA &
v, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
ContF (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contf_val (HMGL
gr, HCDT
v, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_contf_xy_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует закрашенные линии (контуры) уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. См. также dens, cont, contd, contf[xyz]
. См. раздел Sample ‘contf’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContF (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
ContF (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contf (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_contf_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
v1 v2
adat xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContFGen (mreal
v1, mreal
v2, const mglDataA &
a, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contf_gen (HMGL
gr, mreal
v1, mreal
v2, HCDT
a, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует закрашенные линии (контуры) уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} между a[i,j]=v1 и a[i,j]=v2.
vdat zdat ['sch'='']
¶vdat xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContD (const mglDataA &
v, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
ContD (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contd_val (HMGL
gr, HCDT
v, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_contd_xy_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует закрашенные линии (контуры) уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. Строка sch задает цвета контуров: цвет k-го контура определяется как k-ый цвет строки. См. также dens, cont, contf. См. раздел Sample ‘contd’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContD (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
ContD (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contd (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_contd_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
vdat xdat ydat zdat adat ['sch'='']
¶mglGraph
: void
ContP (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contp_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, const char *
opt)
¶Рисует линии уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. Линии уровня рисуются для a[i,j]=v[k]. Если sch содержит ‘t’ или ‘T’, то значения v[k] будут выведены вдоль контуров над (или под) кривой. Если sch содержит ‘f’, то контуры будут закрашены. См. также cont, contf, surfc, cont[xyz]
.
xdat ydat zdat adat ['sch'='']
¶mglGraph
: void
ContP (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contp (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, const char *
opt)
¶Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
vdat zdat ['sch'='']
¶vdat xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContV (const mglDataA &
v, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
ContV (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contv_val (HMGL
gr, HCDT
v, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_contv_xy_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует вертикальные цилиндры от линий уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z=v[k] или при z равном минимальному значению оси z если sch содержит ‘_’. Линии уровня рисуются для z[i,j]=v[k]. См. также cont, contf. См. раздел Sample ‘contv’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
ContV (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
ContV (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_contv (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_contv_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7).
vdat zdat ['sch'='']
¶vdat xdat ydat zdat ['sch'='']
¶mglGraph
: void
Axial (const mglDataA &
v, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Axial (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_axial_val (HMGL
gr, HCDT
v, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_axial_xy_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует поверхность вращения линии уровня для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]}. Линии уровня рисуются для z[i,j]=v[k]. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. Если строка содержит символы ‘x’ или ‘z’, то ось вращения устанавливается в указанное направление (по умолчанию вдоль ‘y’). См. также cont, contf, torus, surf3. См. раздел Sample ‘axial’, для примеров кода и графика.
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Axial (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
, int
num=3
)
¶mglGraph
: void
Axial (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
, int
num=3
)
¶void
mgl_axial (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_axial_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Как предыдущий с вектором v из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 3).
zdat ['sch'='']
¶xdat ydat zdat ['sch'='']
¶mglGraph
: void
Grid (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Grid (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_grid (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_grid_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует плоскую сету для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} при z равном минимальному значению оси z. См. также dens, cont, contf, grid3, meshnum.
Эти функции строят графики для трехмерных (3D) массивов. Трёхмерными считаются массивы, зависящие от трёх параметров (индексов) подобно матрице f(x_i,y_j,z_k), i=1...n, j=1...m, k=1...l. По умолчанию (если отсутствуют) значения x, y, z равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z должны быть одинаковы x.nx=a.nx && y.nx=a.ny && z.nz=a.nz
или x.nx=y.nx=z.nx=a.nx && x.ny=y.ny=z.ny=a.ny && x.nz=y.nz=z.nz=a.nz
. Массивы x, y и z могут быть векторами (не матрицами как a). Строка sch задает цветовую схему (см. Цветовая схема). Строка opt задает опции графика (см. Опции команд).
adat val
['sch'='']
¶xdat ydat zdat adat val
['sch'='']
¶mglGraph
: void
Surf3 (mreal
val, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3 (mreal
val, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3_val (HMGL
gr, mreal
val, HCDT
a, const char *
sch, const char *
opt)
¶void
mgl_surf3_xyz_val (HMGL
gr, mreal
val, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, const char *
opt)
¶Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. Замечу, что возможно некорректная отрисовка граней вследствие неопределённости построения сечения если поверхность пересекает ячейку данных 2 и более раз. См. также cloud, dens3, surf3c, surf3a, axial. См. раздел Sample ‘surf3’, для примеров кода и графика.
adat ['sch'='']
¶xdat ydat zdat adat ['sch'='']
¶mglGraph
: void
Surf3 (const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3 (HMGL
gr, HCDT
a, const char *
sch, const char *
opt)
¶void
mgl_surf3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, const char *
opt)
¶Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 3).
adat ['sch'='']
¶xdat ydat zdat adat ['sch'='']
¶mglGraph
: void
Cloud (const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Cloud (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_cloud (HMGL
gr, HCDT
a, const char *
sch, const char *
opt)
¶void
mgl_cloud_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, const char *
opt)
¶Рисует облачный график для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). График состоит из кубиков с цветом и прозрачностью пропорциональной значениям a. Результат похож на облако – малые значения прозрачны, а большие нет. Число кубиков зависит от meshnum. Если sch содержит ‘.’, то будет построен график более низкого качества, но с заметно меньшим использованием памяти. Если sch содержит ‘i’, то прозрачность будет инвертирована, т.е. области с более высокими значениями будут более прозрачны, а с более низким – менее прозрачны. См. также surf3, meshnum. См. раздел Sample ‘cloud’, для примеров кода и графика.
adat ['sch'='' sval=-1
]
¶xdat ydat zdat adat ['sch'='' sval=-1
]
¶mglGraph
: void
Dens3 (const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Dens3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_dens3 (HMGL
gr, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_dens3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶Рисует график плотности для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). График рисуется на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Если sch содержит ‘#’, то на срезе рисуется сетка. См. также cont3, contf3, dens, grid3. См. раздел Sample ‘dens3’, для примеров кода и графика.
vdat adat ['sch'='' sval=-1
]
¶vdat xdat ydat zdat adat ['sch'='' sval=-1
]
¶mglGraph
: void
Cont3 (const mglDataA &
v, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Cont3 (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_cont3_val (HMGL
gr, HCDT
v, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_cont3_xyz_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶Рисует линии уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Линии рисуются для значений из массива v на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Если sch содержит ‘#’, то на срезе рисуется сетка. Если sch содержит ‘t’ или ‘T’, то значения v[k] будут выведены вдоль контуров над (или под) кривой. См. также dens3, contf3, cont, grid3. См. раздел Sample ‘cont3’, для примеров кода и графика.
adat ['sch'='' sval=-1
]
¶xdat ydat zdat adat ['sch'='' sval=-1
]
¶mglGraph
: void
Cont3 (const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Cont3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_cont3 (HMGL
gr, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_cont3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶Аналогично предыдущему для num линий уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 7).
vdat adat ['sch'='' sval=-1
]
¶vdat xdat ydat zdat adat ['sch'='' sval=-1
]
¶mglGraph
: void
Contf3 (const mglDataA &
v, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Contf3 (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_contf3_val (HMGL
gr, HCDT
v, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_contf3_xyz_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶Рисует закрашенные линии (контуры) уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Линии рисуются для значений из массива v на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Если sch содержит ‘#’, то на срезе рисуется сетка. См. также dens3, cont3, contf, grid3. См. раздел Sample ‘contf3’, для примеров кода и графика.
adat ['sch'='' sval=-1
]
¶xdat ydat zdat adat ['sch'='' sval=-1
]
¶mglGraph
: void
Contf3 (const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Contf3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_contf3 (HMGL
gr, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_contf3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶Аналогично предыдущему для num закрашенных линий (контуров) уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 7).
adat ['sch'='' sval=-1
]
¶xdat ydat zdat adat ['sch'='' sval=-1
]
¶mglGraph
: void
Grid3 (const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Grid3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_grid3 (HMGL
gr, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_grid3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, mreal
sVal, const char *
opt)
¶Рисует сетку для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). График рисуется на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). См. также cont3, contf3, dens3, grid2, meshnum.
vdat adat bdat ['sch'='']
¶vdat xdat ydat zdat adat bdat ['sch'='']
¶mglGraph
: void
DCont (const mglDataA &
v, const mglDataA &
a, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
DCont (const mglDataA &
v, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_dcont_val (HMGL
gr, HCDT
v, HCDT
a, HCDT
b, const char *
sch, const char *
opt)
¶void
mgl_dcont_xyz_val (HMGL
gr, HCDT
v, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
b, const char *
sch, const char *
opt)
¶Рисует линии пересечений поверхностей постоянного уровня для 3d данных a, b заданных параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]). Поверхности уровня берутся при значениях функции равных элементам массива v. См. также cont, cont3. См. раздел Sample ‘dcont’, для примеров кода и графика.
adat bdat ['sch'='' sval=-1
]
¶xdat ydat zdat adat bdat ['sch'='' sval=-1
]
¶mglGraph
: void
DCont (const mglDataA &
a, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
DCont (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_dcont (HMGL
gr, HCDT
a, HCDT
b, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_HCDT
b, cont_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
b, const char *
sch, const char *
opt)
¶Аналогично предыдущему для num уровней равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 7).
tr g1 g2 adat rval
['sch'='' flag=0 num=3
]
¶mglGraph
: void
Beam (const mglDataA &
tr, const mglDataA &
g1, const mglDataA &
g2, const mglDataA &
a, mreal
r, const char *
stl=""
, int
flag=0
, int
num=3
)
¶mglGraph
: void
Beam (mreal
val, const mglDataA &
tr, const mglDataA &
g1, const mglDataA &
g2, const mglDataA &
a, mreal
r, const char *
stl=""
, int
flag=0
)
¶void
mgl_beam (HMGL
gr, HCDT
tr, HCDT
g1, HCDT
g2, HCDT
a, mreal
r, const char *
stl, int
flag, int
num)
¶void
mgl_beam_val (HMGL
gr, mreal
val, HCDT
tr, HCDT
g1, HCDT
g2, HCDT
a, mreal
r, const char *
stl, int
flag)
¶Рисует поверхность уровня для 3d массива a при постоянном значении a=val. Это специальный тип графика для a заданного в сопровождающей системе координат вдоль кривой tr с ортами g1, g2 и с поперечным размером r. Переменная flag – битовый флаг: ‘0x1’ - рисовать в сопровождающих (не лабораторных) координатах; ‘0x2’ - рисовать проекцию на плоскость \rho-z; ‘0x4’ - рисовать нормированное в каждом сечении поле. Размеры массивов по 1-му индексу tr, g1, g2 должны быть nx>2. Размеры массивов по 2-му индексу tr, g1, g2 и размер по 3-му индексу массива a должны быть одинаковы. См. также surf3.
Эти функции строят графики для двух связанных массивов. Есть несколько основных типов 3D графиков: поверхность и поверхность уровня с окраской по второму массиву (SurfC, Surf3C), поверхность и поверхность уровня с прозрачностью по второму массиву (SurfA, Surf3A), плитки переменного размера (TileS), диаграмма точечного отображения (Map), STFA диаграмма (STFA). По умолчанию (если отсутствуют) значения x, y (и z для Surf3C, Surf3A
) равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z, c должны быть одинаковы x.nx=a.nx && y.nx=a.ny && z.nz=a.nz
или x.nx=y.nx=z.nx=a.nx && x.ny=y.ny=z.ny=a.ny && x.nz=y.nz=z.nz=a.nz
. Массивы x, y (и z для Surf3C, Surf3A
) могут быть векторами (не матрицами как c). Строка sch задает цветовую схему (см. Цветовая схема). Строка opt задает опции графика (см. Опции команд).
zdat cdat ['sch'='']
¶xdat ydat zdat cdat ['sch'='']
¶mglGraph
: void
SurfC (const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
SurfC (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surfc (HMGL
gr, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_surfc_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]} с цветом, заданным массивом c[i,j]. Если sch содержит ‘#’, то на поверхности рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. Размерность массивов z и c должна быть одинакова. График строится для каждого z среза данных. См. также surf, surfa, beltc, surf3c. См. раздел Sample ‘surfc’, для примеров кода и графика.
zdat cdat ['sch'='']
¶xdat ydat zdat cdat ['sch'='']
¶mglGraph
: void
BeltC (const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
BeltC (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_beltc (HMGL
gr, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_beltc_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует ленточки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} с цветом, заданным массивом c[i,j]. График может использоваться как 3d обобщение графика plot. Если sch содержит ‘x’, то ленточки рисуются вдоль оси x, иначе (по умолчанию) вдоль оси y. См. также belt, surfc, meshnum. См. раздел Sample ‘beltc’, для примеров кода и графика.
adat cdat val
['sch'='']
¶xdat ydat zdat adat cdat val
['sch'='']
¶mglGraph
: void
Surf3C (mreal
val, const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3C (mreal
val, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3c_val (HMGL
gr, mreal
val, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_surf3c_xyz_val (HMGL
gr, mreal
val, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Аналогично surf3, но цвет задается массивом c. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf3, surfc, surf3a. См. раздел Sample ‘surf3c’, для примеров кода и графика.
adat cdat ['sch'='']
¶xdat ydat zdat adat cdat ['sch'='']
¶mglGraph
: void
Surf3C (const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3C (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3c (HMGL
gr, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_surf3c_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. Величина num равна значению параметра value
в опциях opt (по умолчанию 3).
zdat cdat ['sch'='']
¶xdat ydat zdat cdat ['sch'='']
¶mglGraph
: void
SurfA (const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
SurfA (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surfa (HMGL
gr, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_surfa_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]} с прозрачностью, заданной массивом c[i,j]. Если sch содержит ‘#’, то на поверхности рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. Размерность массивов z и c должна быть одинакова. График строится для каждого z среза данных. См. также surf, surfc, surf3a. См. раздел Sample ‘surfa’, для примеров кода и графика.
adat cdat val
['sch'='']
¶xdat ydat zdat adat cdat val
['sch'='']
¶mglGraph
: void
Surf3A (mreal
val, const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3A (mreal
val, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3a_val (HMGL
gr, mreal
val, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_surf3a_xyz_val (HMGL
gr, mreal
val, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Аналогично surf3, но прозрачность задается массивом c. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf3, surfc, surf3a. См. раздел Sample ‘surf3a’, для примеров кода и графика.
adat cdat ['sch'='']
¶xdat ydat zdat adat cdat ['sch'='']
¶mglGraph
: void
Surf3A (const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3A (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3a (HMGL
gr, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_surf3a_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
c, const char *
sch, const char *
opt)
¶Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. При этом массив c может быть вектором со значениями прозрачности и num=c.nx. В противном случае величина num равна значению параметра value
в опциях opt (по умолчанию 3).
zdat cdat adat ['sch'='']
¶xdat ydat zdat cdat adat ['sch'='']
¶mglGraph
: void
SurfCA (const mglDataA &
z, const mglDataA &
c, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
SurfCA (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surfca (HMGL
gr, HCDT
z, HCDT
c, HCDT
a, const char *
sch, const char *
opt)
¶void
mgl_surfca_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
c, HCDT
a, const char *
sch, const char *
opt)
¶Рисует параметрически заданную поверхность {x[i,j], y[i,j], z[i,j]} с цветом и прозрачностью, заданными массивами c[i,j] и a[i,j] соответственно. Если sch содержит ‘#’, то на поверхности рисуется сетка. Если sch содержит ‘.’, то рисуется поверхность из точек. Размерность массивов z и c должна быть одинакова. График строится для каждого z среза данных. См. также surf, surfc, surfa, surf3ca. См. раздел Sample ‘surfca’, для примеров кода и графика.
adat cdat bdat val
['sch'='']
¶xdat ydat zdat adat cdat bdat val
['sch'='']
¶mglGraph
: void
Surf3CA (mreal
val, const mglDataA &
a, const mglDataA &
c, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3CA (mreal
val, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
c, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3ca_val (HMGL
gr, mreal
val, HCDT
a, HCDT
c, HCDT
b, const char *
sch, const char *
opt)
¶void
mgl_surf3ca_xyz_val (HMGL
gr, mreal
val, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
c, HCDT
b, const char *
sch, const char *
opt)
¶Рисует поверхность уровня для 3d массива, заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) при a(x,y,z)=val. Аналогично surf3, но цвет и прозрачность задается массивами c и b соответственно. Если sch содержит ‘#’, то рисуется сетчатая поверхность. Если sch содержит ‘.’, то рисуется поверхность из точек. См. также surf3, surfc, surf3a. См. раздел Sample ‘surf3a’, для примеров кода и графика.
adat cdat ['sch'='']
¶xdat ydat zdat adat cdat ['sch'='']
¶mglGraph
: void
Surf3CA (const mglDataA &
a, const mglDataA &
c, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Surf3CA (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
c, const mglDataA &
b, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_surf3ca (HMGL
gr, HCDT
a, HCDT
c, HCDT
b, const char *
sch, const char *
opt)
¶void
mgl_surf3ca_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
c, HCDT
b, const char *
sch, const char *
opt)
¶Аналогично предыдущему для num поверхностей уровня равномерно распределённых в диапазоне изменения цвета. Здесь величина num равна значению параметра value
в опциях opt (по умолчанию 3).
zdat rdat ['sch'='']
¶xdat ydat zdat rdat ['sch'='']
¶xdat ydat zdat rdat cdat ['sch'='']
¶mglGraph
: void
TileS (const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TileS (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
r, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TileS (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
r, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_tiles (HMGL
gr, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_tiles_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
r, const char *
sch, const char *
opt)
¶void
mgl_tiles_xyc (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
r, HCDT
c, const char *
sch, const char *
opt)
¶Рисует плитки для параметрически заданной поверхности {x[i,j], y[i,j], z[i,j]} с цветом, заданным массивом c[i,j]. Аналогично Tile(), но размер плиток задается массивов r. Если строка sch содержит стиль ‘x’ или ‘y’, то плитки будут ориентированы перпендикулярно x- или y-оси. Это создает эффект "прозрачности" при экспорте в файлы EPS. График строится для каждого z среза данных. См. также surfa, tile. См. раздел Sample ‘tiles’, для примеров кода и графика.
udat vdat ['sch'='']
¶xdat ydat udat vdat ['sch'='']
¶mglGraph
: void
Map (const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Map (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_map (HMGL
gr, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶void
mgl_map_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶Рисует точечное отображение для матриц {ax, ay } параметрически зависящих от координат x, y. Исходное положение ячейки задает ее цвет. Высота пропорциональна якобиану J(ax,ay). График является аналогом диаграммы Арнольда ??? Если sch содержит ‘.’, то цветные точки рисуются в узлах матриц (полезно для "запутанного" отображения), иначе рисуются грани. См. раздел Mapping visualization, для примеров кода и графика.
re im dn
['sch'='']
¶xdat ydat re im dn
['sch'='']
¶mglGraph
: void
STFA (const mglDataA &
re, const mglDataA &
im, int
dn, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
STFA (const mglDataA &
x, const mglDataA &
y, const mglDataA &
re, const mglDataA &
im, int
dn, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_stfa (HMGL
gr, HCDT
re, HCDT
im, int
dn, const char *
sch, const char *
opt)
¶void
mgl_stfa_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
re, HCDT
im, int
dn, const char *
sch, const char *
opt)
¶Рисует спектрограмму комплексного массива re+i*im для Фурье размером dn точек в плоскости z равно минимальному значению оси z. Параметр dn – любое чётное число. Например в 1D случае, результатом будет график плотности от массива res[i,j]=|\sum_d^dn exp(I*j*d)*(re[i*dn+d]+I*im[i*dn+d])|/dn размером {int(nx/dn), dn, ny}. Массивы re, im параметрически зависят от координат x, y. Все размеры массивов re и im должны быть одинаковы. Младшие размерности массивов x, y, re должны быть одинаковы. Массивы x и y могут быть векторами (не матрицами как re). См. раздел Sample ‘stfa’, для примеров кода и графика.
Эти функции рисуют графики для 2D и 3D векторных полей. Есть несколько типов графиков: просто векторное поле (Vect), вектора вдоль траектории (Traj), векторное поле каплями (Dew), нити тока (Flow, FlowP), трубки тока (Pipe). По умолчанию (если отсутствуют) значения x, y и z равно распределены в диапазоне осей координат. Младшие размерности массивов x, y, z и ax должны быть одинаковы. Размеры массивов ax, ay и az должны быть одинаковы. Массивы x, y и z могут быть векторами (не матрицами как ax). Строка sch задает цветовую схему (см. Цветовая схема). Строка opt задает опции графика (см. Опции команд).
y1dat y2dat ['sch'='']
¶x1dat y1dat x2dat y2dat ['sch'='']
¶x1dat y1dat z1dat x2dat y2dat z2dat ['sch'='']
¶mglGraph
: void
Lines (const mglDataA &
y1, const mglDataA &
y2, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Lines (const mglDataA &
x1, const mglDataA &
y1, const mglDataA &
x2, const mglDataA &
y2, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Lines (const mglDataA &
x1, const mglDataA &
y1, const mglDataA &
z1, const mglDataA &
x2, const mglDataA &
y2, const mglDataA &
z2, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_lines_xyz (HMGL
gr, HCDT
x1, HCDT
y1, HCDT
z1, HCDT
x2, HCDT
y2, HCDT
z2, const char *
sch, const char *
opt)
¶void
mgl_lines_xy (HMGL
gr, HCDT
x1, HCDT
y1, HCDT
x2, HCDT
y2, const char *
sch, const char *
opt)
¶void
mgl_lines (HMGL
gr, HCDT
y1, HCDT
y2, const char *
sch, const char *
opt)
¶Функция рисует линии между точками {x1, y1, z1} и {x2, y2, z2}. Строка pen задает цвет (см. Стиль линий). По умолчанию (pen=""
) используется текущий цвет из палитры (см. Палитра и цвета). Размер по 1-му индексу должен быть одинаков. График рисуется для каждой строки если один из массивов матрица. См. также plot, traj. См. раздел Sample ‘lines’, для примеров кода и графика.
xdat ydat udat vdat ['sch'='']
¶xdat ydat zdat udat vdat wdat ['sch'='']
¶mglGraph
: void
Traj (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Traj (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_traj_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶void
mgl_traj_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶Рисует вектора {ax, ay, az} вдоль кривой {x, y, z}. Длина векторов пропорциональна \sqrt{ax^2+ay^2+az^2}. Строка pen задает цвет (см. Стиль линий). По умолчанию (pen=""
) используется текущий цвет из палитры (см. Палитра и цвета). Опция value
задает фактор длины векторов (если не нуль) или выбирать длину пропорционально расстоянию между точками кривой (если value=0
). Размер по 1-му индексу должен быть 2 или больше. График рисуется для каждой строки если один из массивов матрица. См. также vect. См. раздел Sample ‘traj’, для примеров кода и графика.
udat vdat ['sch'='']
¶xdat ydat udat vdat ['sch'='']
¶mglGraph
: void
Vect (const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Vect (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_vect_2d (HMGL
gr, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶void
mgl_vect_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶Рисует векторное поле {ax, ay} параметрически зависящее от координат x, y на плоскости при z равном минимальному значению оси z. Длина и цвет векторов пропорциональна \sqrt{ax^2+ay^2}. Число рисуемых векторов зависит от meshnum. Вид стрелок/штрихов может быть изменён символами:
См. также flow, dew. См. раздел Sample ‘vect’, для примеров кода и графика.
udat vdat wdat ['sch'='']
¶xdat ydat zdat udat vdat wdat ['sch'='']
¶mglGraph
: void
Vect (const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Vect (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_vect_3d (HMGL
gr, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶void
mgl_vect_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶Это 3d версия графика. Здесь массивы ax, ay, az должны трёхмерными тензорами и длина вектора пропорциональна \sqrt{ax^2+ay^2+az^2}.
udat vdat wdat ['sch'='' sval]
¶xdat ydat zdat udat vdat wdat ['sch'='' sval]
¶mglGraph
: void
Vect3 (const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Vect3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, mreal
sVal=-1
, const char *
opt=""
)
¶void
mgl_vect3 (HMGL
gr, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, mreal
sVal, const char *
opt)
¶void
mgl_vect3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, mreal
sVal, const char *
opt)
¶Рисует 3D векторное поле {ax, ay, az} параметрически зависящее от координат x, y, z. График рисуется на срезе sVal в направлении {‘x’, ‘y’, ‘z’}, указанном в строке sch (по умолчанию, в напралении ‘y’). Длина и цвет векторов пропорциональна \sqrt{ax^2+ay^2+az^2}. Число рисуемых векторов зависит от meshnum. Вид стрелок/штрихов может быть изменён символами:
См. также vect, flow, dew. См. раздел Sample ‘vect’, для примеров кода и графика.
udat vdat ['sch'='']
¶xdat ydat udat vdat ['sch'='']
¶mglGraph
: void
Dew (const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Dew (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_dew (HMGL
gr, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶void
mgl_dew_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶Рисует капли для векторного поля {ax, ay}, параметрически зависящего от координат x, y при z равном минимальному значению оси z. Замечу, что график требует много памяти и процессорного времени для своего создания! Цвет капель пропорционален \sqrt{ax^2+ay^2}. Число капель определяется meshnum. См. также vect. См. раздел Sample ‘dew’, для примеров кода и графика.
udat vdat ['sch'='']
¶xdat ydat udat vdat ['sch'='']
¶mglGraph
: void
Flow (const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Flow (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_flow_2d (HMGL
gr, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶void
mgl_flow_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶Рисует нити тока для векторного поля {ax, ay}, параметрически зависящего от координат x, y на плоскости при z равном минимальному значению оси z. Число нитей пропорционально значению опции value
(по умолчанию 5). Цвет нитей пропорционален \sqrt{ax^2+ay^2}. Строка sch может содержать
См. также pipe, vect, tape, flow3, barwidth. См. раздел Sample ‘flow’, для примеров кода и графика.
udat vdat wdat ['sch'='']
¶xdat ydat zdat udat vdat wdat ['sch'='']
¶mglGraph
: void
Flow (const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Flow (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_flow_3d (HMGL
gr, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶void
mgl_flow_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶Это 3d версия графика. Здесь массивы должны трёхмерными тензорами и цвет пропорционален \sqrt{ax^2+ay^2+az^2}.
x0 y0
udat vdat ['sch'='']
¶x0 y0
xdat ydat udat vdat ['sch'='']
¶mglGraph
: void
FlowP (mglPoint
p0, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
FlowP (mglPoint
p0, const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_flowp_2d (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶void
mgl_flowp_xy (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, const char *
opt)
¶Аналогично flow, но рисует одну нить из точки p0={x0,y0,z0}. Строка sch также может содержать: ‘>’ или ‘<’ для рисования линии тока только вперед или только назад от заданной точки (по умолчанию, рисует в обе стороны).
x0 y0 z0
udat vdat wdat ['sch'='']
¶x0 y0 z0
xdat ydat zdat udat vdat wdat ['sch'='']
¶mglGraph
: void
FlowP (mglPoint
p0, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
FlowP (mglPoint
p0, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_flowp_3d (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶void
mgl_flowp_xyz (HMGL
gr, mreal
x0, mreal
y0, mreal
z0, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, const char *
opt)
¶Это 3d версия графика.
udat vdat wdat ['sch'='']
¶xdat ydat zdat udat vdat ['sch'='']
¶mglGraph
: void
Flow3 (const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, double
sVal=-1
, const char *
opt=""
)
¶mglGraph
: void
Flow3 (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, double
sVal=-1
, const char *
opt=""
)
¶void
mgl_flow3 (HMGL
gr, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, double
sVal, const char *
opt)
¶void
mgl_flow3_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, double
sVal, const char *
opt)
¶The function draws flow threads for the 3D vector field {ax, ay, az} parametrically depending on coordinates x, y, z. Flow threads starts from given plane. Option value
set the approximate number of threads (default is 5). String sch may contain:
See also flow, pipe, vect. См. раздел Sample ‘flow3’, для примеров кода и графика.
pdat ['sch'='']
¶xdat ydat pdat ['sch'='']
¶xdat ydat zdat pdat ['sch'='']
¶mglGraph
: void
Grad (const mglDataA &
phi, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Grad (const mglDataA &
x, const mglDataA &
y, const mglDataA &
phi, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Grad (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
phi, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_grad (HMGL
gr, HCDT
phi, const char *
sch, const char *
opt)
¶void
mgl_grad_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
phi, const char *
sch, const char *
opt)
¶void
mgl_grad_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
phi, const char *
sch, const char *
opt)
¶Рисует линии градиента скалярного поля phi[i,j] (или phi[i,j,k] в 3d случае) заданного параметрически {x[i,j,k], y[i,j,k], z[i,j,k]}. Число линий пропорционально значению опции value
(по умолчанию 5). См. также dens, cont, flow.
udat vdat ['sch'='' r0=0.05
]
¶xdat ydat udat vdat ['sch'='' r0=0.05
]
¶mglGraph
: void
Pipe (const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, mreal
r0=0.05
, const char *
opt=""
)
¶mglGraph
: void
Pipe (const mglDataA &
x, const mglDataA &
y, const mglDataA &
ax, const mglDataA &
ay, const char *
sch=""
, mreal
r0=0.05
, const char *
opt=""
)
¶void
mgl_pipe_2d (HMGL
gr, HCDT
ax, HCDT
ay, const char *
sch, mreal
r0, const char *
opt)
¶void
mgl_pipe_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
ax, HCDT
ay, const char *
sch, mreal
r0, const char *
opt)
¶Рисует трубки тока для векторного поля {ax, ay}, параметрически зависящего от координат x, y на плоскости при z равном минимальному значению оси z. Число трубок пропорционально значению опции value
. Цвет и радиус трубок пропорционален \sqrt{ax^2+ay^2}. Тёплые цвета соответствуют нормальному току (типа стока). Холодные цвета соответствуют обратному току (типа источника). Параметр r0 задает радиус трубок. При r0<0 радиус трубок обратно пропорционален их амплитуде. См. также flow, vect. См. раздел Sample ‘pipe’, для примеров кода и графика.
udat vdat wdat ['sch'='' r0=0.05
]
¶xdat ydat zdat udat vdat wdat ['sch'='' r0=0.05
]
¶mglGraph
: void
Pipe (const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, mreal
r0=0.05
, const char *
opt=""
)
¶mglGraph
: void
Pipe (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
ax, const mglDataA &
ay, const mglDataA &
az, const char *
sch=""
, mreal
r0=0.05
, const char *
opt=""
)
¶void
mgl_pipe_3d (HMGL
gr, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, mreal
r0, const char *
opt)
¶void
mgl_pipe_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
ax, HCDT
ay, HCDT
az, const char *
sch, mreal
r0, const char *
opt)
¶Это 3d версия графика. Здесь массивы ax, ay, az должны трёхмерными тензорами и цвет пропорционален \sqrt{ax^2+ay^2+az^2}.
Это функции, не относящиеся к какой-то специальной категории. Сюда входят функции построения графиков по текстовым формулам (FPlot и FSurf), рисования поверхностей из треугольников и четырёхугольников (TriPlot, TriCont, QuadPlot), произвольных точек в пространстве (Dots) и реконструкции по ним поверхности (Crust), графики плотности и линии уровня на плоскостях, перпендикулярных осям x, y или z (Dens[XYZ], Cont[XYZ], ContF[XYZ]). Каждый тип графика имеет похожий интерфейс. Есть версия для рисования одного массива с автоматическими координатами и версия для параметрически заданного массива. Параметры цветовой схемы задаются строкой. See Цветовая схема.
dat ['sch'='' sval=nan
]
¶dat ['sch'='' sval=nan
]
¶dat ['sch'='' sval=nan
]
¶mglGraph
: void
DensX (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
DensY (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
DensZ (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶void
mgl_dens_x (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_dens_y (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_dens_z (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶Эти функции рисуют график плотности на x, y или z плоскостях. Если a – 3d массив, то выполняется интерполяция к заданному срезу sVal. Функции полезны для создания проекций 3D массивов на оси координат. См. также ContXYZ, ContFXYZ, dens, Распределение данных. См. раздел Sample ‘dens_xyz’, для примеров кода и графика.
dat ['sch'='' sval=nan
]
¶dat ['sch'='' sval=nan
]
¶dat ['sch'='' sval=nan
]
¶mglGraph
: void
ContX (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContY (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContZ (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶void
mgl_cont_x (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_cont_y (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_cont_z (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶Эти функции рисуют линии уровня на x, y или z плоскостях. Если a – 3d массив, то выполняется интерполяция к заданному срезу sVal. Опция value
задает число контуров. Функции полезны для создания проекций 3D массивов на оси координат. См. также ContFXYZ, DensXYZ, cont, Распределение данных. См. раздел Sample ‘cont_xyz’, для примеров кода и графика.
mglGraph
: void
ContX (const mglDataA &
v, const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContY (const mglDataA &
v, const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContZ (const mglDataA &
v, const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶void
mgl_cont_x_val (HMGL
gr, HCDT
v, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_cont_y_val (HMGL
gr, HCDT
v, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_cont_z_val (HMGL
gr, HCDT
v, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶Аналогично предыдущему с ручным заданием значений для линий уровня.
dat ['sch'='' sval=nan
]
¶dat ['sch'='' sval=nan
]
¶dat ['sch'='' sval=nan
]
¶mglGraph
: void
ContFX (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContFY (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContFZ (const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶void
mgl_contf_x (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_contf_y (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_contf_z (HMGL
gr, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶Эти функции рисуют закрашенные контуры уровня на x, y или z плоскостях. Если a – 3d массив, то выполняется интерполяция к заданному срезу sVal. Опция value
задает число контуров. Функции полезны для создания проекций 3D массивов на оси координат. См. также ContFXYZ, DensXYZ, cont, Распределение данных. См. раздел Sample ‘contf_xyz’, для примеров кода и графика.
mglGraph
: void
ContFX (const mglDataA &
v, const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContFY (const mglDataA &
v, const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶mglGraph
: void
ContFZ (const mglDataA &
v, const mglDataA &
a, const char *
stl=""
, mreal
sVal=NAN
, const char *
opt=""
)
¶void
mgl_contf_x_val (HMGL
gr, HCDT
v, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_contf_y_val (HMGL
gr, HCDT
v, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶void
mgl_contf_z_val (HMGL
gr, HCDT
v, HCDT
a, const char *
stl, mreal
sVal, const char *
opt)
¶Аналогично предыдущему с ручным заданием значений для линий уровня.
'y(x)' ['pen'='']
¶mglGraph
: void
FPlot (const char *
eqY, const char *
pen=""
, const char *
opt=""
)
¶void
mgl_fplot (HMGL
gr, const char *
eqY, const char *
pen, const char *
opt)
¶Рисует функцию ‘eqY(x)’ в плоскости z равно минимальному значению оси z с координатой ‘x’ в диапазоне осей координат. Опция value
задает начальное число точек. См. также plot.
'x(t)' 'y(t)' 'z(t)' ['pen'='']
¶mglGraph
: void
FPlot (const char *
eqX, const char *
eqY, const char *
eqZ, const char *
pen, const char *
opt=""
)
¶void
mgl_fplot_xyz (HMGL
gr, const char *
eqX, const char *
eqY, const char *
eqZ, const char *
pen, const char *
opt)
¶Рисует параметрическую кривую {‘eqX(t)’, ‘eqY(t)’, ‘eqZ(t)’}, где координата ‘t’ меняется в диапазоне [0, 1]. Опция value
задает начальное число точек. См. также plot.
'z(x,y)' ['sch'='']
¶mglGraph
: void
FSurf (const char *
eqZ, const char *
sch=""
, const char *
opt=""
);
¶void
mgl_fsurf (HMGL
gr, const char *
eqZ, const char *
sch, const char *
opt);
¶Рисует поверхность ‘eqY(x,y)’ с координатами ‘x’, ‘y’ в диапазоне xrange, yrange
. Опция value
задает число точек. См. также surf.
'x(u,v)' 'y(u,v)' 'z(u,v)' ['sch'='']
¶mglGraph
: void
FSurf (const char *
eqX, const char *
eqY, const char *
eqZ, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_fsurf_xyz (HMGL
gr, const char *
eqX, const char *
eqY, const char *
eqZ, const char *
sch, const char *
opt)
¶Рисует параметрическую поверхность {‘eqX(u,v)’, ‘eqY(u,v)’, ‘eqZ(u,v)’}, где координаты ‘u’, ‘v’ меняются в диапазоне [0, 1]. Опция value
задает число точек. См. также surf.
idat xdat ydat ['sch'='']
¶idat xdat ydat zdat ['sch'='']
¶idat xdat ydat zdat cdat ['sch'='']
¶mglGraph
: void
TriPlot (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TriPlot (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TriPlot (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_triplot_xy (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, const char *
sch, const char *
opt)
¶void
mgl_triplot_xyz (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_triplot_xyzc (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶Рисует поверхность из треугольников. Вершины треугольников задаются индексами id в массиве точек {x[i], y[i], z[i]}. Строка sch задает цветовую схему. Если строка содержит ‘#’, то рисуется сетчатая поверхность. Размер по 1-му индексу массива id должен быть 3 или больше. Массивы x, y, z должны иметь одинаковые размеры. Массив c задает цвет треугольников (если id.ny=c.nx) или цвет вершин (если x.nx=c.nx). См. также dots, crust, quadplot, triangulation. См. раздел Sample ‘triplot’, для примеров кода и графика.
vdat idat xdat ydat zdat cdat ['sch'='']
¶vdat idat xdat ydat zdat ['sch'='']
¶idat xdat ydat zdat ['sch'='']
¶mglGraph
: void
TriCont (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TriCont (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TriContV (const mglDataA &
v, const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
TriContV (const mglDataA &
v, const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_tricont_xyzc (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_tricont_xyz (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_tricont_xyzcv (HMGL
gr, HCDT
v, HCDT
id, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶void
mgl_tricont_xyzv (HMGL
gr, HCDT
v, HCDT
id, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Рисует линии уровня поверхности из треугольников при z=v[k] (или при z равном минимальному значению оси z если sch содержит ‘_’). Вершины треугольников задаются индексами id в массиве точек {x[i], y[i], z[i]}. Если аргуент v не задан, то используется массив из num элементов равно распределенных в диапазоне изменения цвета. Здесь num равен значению параметра value
в опциях opt (по умолчанию 7). Строка sch задает цветовую схему. Размер по 1-му индексу массива id должен быть 3 или больше. Массивы x, y, z должны иметь одинаковые размеры. Массив c задает цвет треугольников (если id.ny=c.nx) или цвет вершин (если x.nx=c.nx). См. также triplot, cont, triangulation.
idat xdat ydat ['sch'='']
¶idat xdat ydat zdat ['sch'='']
¶idat xdat ydat zdat cdat ['sch'='']
¶mglGraph
: void
QuadPlot (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
QuadPlot (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
QuadPlot (const mglDataA &
id, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_quadplot_xy (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, const char *
sch, const char *
opt)
¶void
mgl_quadplot_xyz (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_quadplot_xyzc (HMGL
gr, HCDT
id, HCDT
x, HCDT
y, HCDT
z, HCDT
c, const char *
sch, const char *
opt)
¶Рисует поверхность из четырёхугольников. Вершины четырёхугольников задаются индексами id в массиве точек {x[i], y[i], z[i]}. Строка sch задает цветовую схему. Если строка содержит ‘#’, то рисуется сетчатая поверхность. Размер по 1-му индексу массива id должен быть 4 или больше. Массивы x, y, z должны иметь одинаковые размеры. Массив c задает цвет четырёхугольников (если id.ny=c.nx) или цвет вершин (если x.nx=c.nx). См. также triplot. См. раздел Sample ‘triplot’, для примеров кода и графика.
xdat ydat zdat ['sch'='']
¶xdat ydat zdat adat ['sch'='']
¶mglGraph
: void
Dots (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Dots (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶mglGraph
: void
Dots (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
c, const mglDataA &
a, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_dots (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶void
mgl_dots_a (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
sch, const char *
opt)
¶void
mgl_dots_ca (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
c, HCDT
a, const char *
sch, const char *
opt)
¶Рисует произвольно расположенные точки {x[i], y[i], z[i]}. Строка sch задает цветовую схему и тип маркеров. Если определёны массивы c, a то они задают цвет и прозрачность точек соответственно. Непрозрачные точки с заданным цветом можно нарисовать с помощью tens, используя стиль ‘ .’. Массивы x, y, z, a должны иметь одинаковые размеры. См. также crust, tens, mark, plot. См. раздел Sample ‘dots’, для примеров кода и графика.
xdat ydat zdat ['sch'='']
¶mglGraph
: void
Crust (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
sch=""
, const char *
opt=""
)
¶void
mgl_crust (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, const char *
sch, const char *
opt)
¶Реконструирует и рисует поверхность по произвольно расположенным точкам {x[i], y[i], z[i]}. Опция value задает радиус ошибки (увеличите для удаления дыр). Строка sch задает цветовую схему. Если строка содержит ‘#’, то рисуется сетчатая поверхность. Массивы x, y, z должны иметь одинаковые размеры. См. также dots, triplot.
Эти функции подбирают параметры функции для наилучшей аппроксимации данных, т.е. минимизируют сумму \sum_i (f(x_i, y_i, z_i) - a_i)^2/s_i^2. При этом аппроксимирующая функция ‘f’ может зависеть от одного аргумента ‘x’ (1D случай), от двух аргументов ‘x,y’ (2D случай) или от трех аргументов ‘x,y,z’ (3D случай). Функция ‘f’ также может зависеть от параметров. Список параметров задается строкой var (например, ‘abcd’). Обычно пользователь должен предоставить начальные значения параметров в переменной ini. Однако, при его отсутствии используются нулевые значения. Параметр print=true
включает вывод найденной формулы в Message (см. Обработка ошибок).
Функции Fit() и FitS() не рисуют полученные массивы. Они заполняют массив fit по формуле ‘f’ с найденными коэффициентами и возвращают \chi^2 ошибку аппроксимации. При этом, координаты ‘x,y,z’ равно распределены в диапазоне осей координат. Число точек в fit определяется опцией value
(по умолчанию mglFitPnts=100). Функции используют библиотеку GSL. См. раздел Nonlinear fitting hints, для примеров кода и графика.
res adat sdat 'func' 'var' [ini=0]
¶res xdat adat sdat 'func' 'var' [ini=0]
¶res xdat ydat adat sdat 'func' 'var' [ini=0]
¶res xdat ydat zdat adat sdat 'func' 'var' [ini=0]
¶mglGraph
: mglData
FitS (const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
x, const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
x, const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
x, const mglDataA &
y, const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
x, const mglDataA &
y, const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
FitS (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const mglDataA &
s, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶HMDT
mgl_fit_ys (HMGL
gr, HCDT
a, HCDT
s, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_xys (HMGL
gr, HCDT
x, HCDT
a, HCDT
s, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_xyzs (HMGL
gr, HCDT
x, HCDT
y, HCDT
a, HCDT
s, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_xyzas (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, HCDT
s, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶"Подгоняют" формулу вдоль x-, y- и z-направлений для 3d массива заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) с весовым множителем s[i,j,k].
res adat 'func' 'var' [ini=0]
¶res xdat adat 'func' 'var' [ini=0]
¶res xdat ydat adat 'func' 'var' [ini=0]
¶res xdat ydat zdat adat 'func' 'var' [ini=0]
¶mglGraph
: mglData
Fit (const mglDataA &
a, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
a, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
x, const mglDataA &
a, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
x, const mglDataA &
a, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
x, const mglDataA &
y, const mglDataA &
a, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
x, const mglDataA &
y, const mglDataA &
a, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
Fit (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶HMDT
mgl_fit_y (HMGL
gr, HCDT
a, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_xy (HMGL
gr, HCDT
x, HCDT
a, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
a, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_xyza (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶"Подгоняют" формулу вдоль x-, y- и z-направлений для 3d массива заданного параметрически a[i,j,k](x[i,j,k], y[i,j,k], z[i,j,k]) с весовым множителем 1.
mglGraph
: mglData
Fit2 (const mglDataA &
a, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
Fit2 (mglData &
fit, const mglDataA &
a, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶mglGraph
: mglData
Fit3 (mglData &
fit, const mglDataA &
a, const char *
func, const char *
var, const char *
opt=""
)
¶mglGraph
: mglData
Fit3 (mglData &
fit, const mglDataA &
a, const char *
func, const char *
var, mglData &
ini, const char *
opt=""
)
¶HMDT
mgl_fit_2 (HMGL
gr, HCDT
a, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶HMDT
mgl_fit_3 (HMGL
gr, HCDT
a, const char *
func, const char *
var, HMDT
ini, const char *
opt)
¶"Подгоняют" формулу вдоль всех направлений для 2d или 3d массива a с s=1 и x, y, z равно распределёнными в диапазоне осей координат.
x y
['pre'='' 'fnt'='' size=-1
]
¶mglGraph
: void
PutsFit (mglPoint
p, const char *
prefix=""
, const char *
font=""
, mreal
size=-1
)
¶void
mgl_puts_fit (HMGL
gr, mreal
x, mreal
y, mreal
z, const char *
prefix, const char *
font, mreal
size)
¶Печатает последнюю подобранную формулу с найденными коэффициентами в точке p0. Строка prefix будет напечатана перед формулой. Все другие параметры такие же как в Вывод текста.
mglGraph
: const char *
GetFit
() ¶const char *
mgl_get_fit (HMGL
gr)
¶
mgl_get_fit (long
gr, char *
out, int
len)
¶Возвращает последнюю подобранную формулу с найденными коэффициентами.
mglGraph
: mreal
GetFitChi ()
¶mreal
mgl_get_fit_chi ()
¶Возвращает величину \chi для последней подобранной формулы.
mglGraph
: mreal
GetFitCovar ()
¶mreal
mgl_get_fit_covar ()
¶Возвращает ковариационную матрицу для последней подобранной формулы.
RES xdat adat
¶RES xdat ydat adat
¶RES xdat ydat zdat adat
¶mglGraph
: mglData
Hist (const mglDataA &
x, const mglDataA &
a, const char *
opt=""
)
¶mglGraph
: mglData
Hist (const mglDataA &
x, const mglDataA &
y, const mglDataA &
a, const char *
opt=""
)
¶mglGraph
: mglData
Hist (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
a, const char *
opt=""
)
¶HMDT
mgl_hist_x (HMGL
gr, HCDT
x, HCDT
a, const char *
opt)
¶HMDT
mgl_hist_xy (HMGL
gr, HCDT
x, HCDT
y, HCDT
a, const char *
opt)
¶HMDT
mgl_hist_xyz (HMGL
gr, HCDT
x, HCDT
y, HCDT
z, HCDT
a, const char *
opt)
¶Создают распределения данных. Они не рисуют данные. Функции могут быть полезны в случае когда данные пользователя определены на случайно расположенных точка (например, после PIC расчетов) и он хочет построить график, требующий регулярных данных (данных на сетках). Диапазон сеток равен диапазону осей координат. Массивы x, y, z определяют положение (координаты) точек. Массив a задает значения данных. Число точек в результате res определяется опцией value
(по умолчанию mglFitPnts=100).
dat 'eq'
¶dat 'eq' vdat
¶dat 'eq' vdat wdat
¶mglGraph
: void
Fill (mglData &
u, const char *
eq, const char *
opt=""
)
¶mglGraph
: void
Fill (mglData &
u, const char *
eq, const mglDataA &
v, const char *
opt=""
)
¶mglGraph
: void
Fill (mglData &
u, const char *
eq, const mglDataA &
v, const mglDataA &
w, const char *
opt=""
)
¶void
mgl_data_fill_eq (HMGL
gr, HMDT
u, const char *
eq, HCDT
v, HCDT
w, const char *
opt)
¶Заполняют значения массива ‘u’ в соответствии с формулой в строке eq. Формула – произвольное выражение, зависящее от переменных ‘x’, ‘y’, ‘z’, ‘u’, ‘v’, ‘w’. Координаты ‘x’, ‘y’, ‘z’ полагаются в диапазоне изменения осей координат. Переменная ‘u’ – значение исходного массива. Переменные ‘v’ и ‘w’ – значения массивов v, w, которые могут быть NULL
(т.е. могут быть опущены).
dat xdat ydat zdat
¶mglGraph
: void
DataGrid (mglData &
u, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
opt=""
)
¶void
mgl_data_grid (HMGL
gr, HMDT
u, HCDT
x, HCDT
y, HCDT
z, const char *
opt)
¶Заполняет значения массива ‘u’ результатом линейной интерполяции по триангулированной поверхности, найденной по произвольно расположенным точкам ‘x’, ‘y’, ‘z’. NAN значение используется для точек сетки вне триангулированной поверхности. См. раздел Making regular data, для примеров кода и графика.
dat xdat vdat [sl=-1]
¶dat xdat ydat vdat [sl=-1]
¶dat xdat ydat zdat vdat
¶mglData
: void
Refill (mglDataA &
dat, const mglDataA &
x, const mglDataA &
v, long
sl=-1
, const char *
opt=""
)
¶mglData
: void
Refill (mglDataA &
dat, const mglDataA &
x, const mglDataA &
y, const mglDataA &
v, long
sl=-1
, const char *
opt=""
)
¶mglData
: void
Refill (mglDataA &
dat, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
v, const char *
opt=""
)
¶void
mgl_data_refill_gr (HMGL
gr, HMDT
a, HCDT
x, HCDT
y, HCDT
z, HCDT
v, long
sl, const char *
opt)
¶Заполняет значениями интерполяции массива v в точках {x, y, z}={X[i], Y[j], Z[k]
} (или {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]
} если x, y, z не 1d массивы), где X,Y,Z
равномерно распределены в диапазоне осей координат и имеют такой же размер как и массив dat. Если параметр sl равен 0 или положительный, то изменятся будет только sl-ый срез.
RES 'ham' ini_re ini_im [dz=0.1 k0=100
]
¶mglGraph
: mglData
PDE (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, mreal
dz=0.1
, mreal
k0=100
, const char *
opt=""
)
¶HMDT
mgl_pde_solve (HMGL
gr, const char *
ham, HCDT
ini_re, HCDT
ini_im, mreal
dz, mreal
k0, const char *
opt)
¶Решает уравнение в частных производных du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные оперторы. Параметры ini_re, ini_im задают действительную и мнимую часть начального распределения поля. Координаты ‘x’, ‘y’, ‘z’ полагаются в диапазоне изменения осей координат. Отмечу, ято в действительности этот диапазон увеличен на 3/2 для уменьшения отражения от границ сетки. Параметр dz задает шаг по эволюционной координате z. Сейчас используется упрощенный вид функции ham – исключены все “смешанные” члены (типа ‘x*p’->x*d/dx). Например, в 2D случае это функция вида ham = f(p,z) + g(x,z,u). Однако, коммутирующие члены (типа ‘x*q’->x*d/dy) разрешены. Переменная ‘u’ используется для амплитуды поля |u|, что позволяет решать нелинейные задачи – например уравнение Шредингера ham="p^2 + q^2 - u^2"
. Вы можете задавать мнимую часть для поглощения волн, например ham = "p^2 + i*x*(x>0)"
, но только для линейной зависимости от переменной ‘i’ (т.е. ham = hre+i*him). См. раздел PDE solving hints, для примеров кода и графика.
Есть целый набор “оконных” классов для создания окон с графикой MathGL: mglWnd
и mglGLUT
для окон целиком, Fl_MathGL
и QMathGL
для виджетов. Все эти классы позволяют пользователю просмотривать, вращать, экспортировать рисунок. Большинство из них (кроме mglGLUT
) имеют панель инструментов для упрощения изменения графика. Все оконные классы имеют схожий набор функций. Ниже приведен список классов с краткими комментариями.
Для рисования можно использовать: указатель NULL
если планируется обновлять график вручную, глобальную функцию типа int draw(
или HMGL
gr, void *
p)int draw(
, или экземпляр класса, производного от mglDraw class. Этот класс определен в mglGraph *
gr)#include <mgl2/wnd.h>
и имеет 2 основных виртуальных метода:
class mglDraw { public: virtual int Draw(mglGraph *) { return 0; }; virtual void Reload() {}; };
Вам следует наследовать свой класс от mglDraw
и определить один или оба метода.
Непосредственно окна можно создать используя один из следующих классов (см. Использование окон MathGL для примеров).
mglFLTK
: mglFLTK (const char *
title="MathGL"
)
¶mglFLTK
: mglFLTK (int
(*draw)(HMGL
gr, void *
p), const char *
title="MathGL"
, void *
par=NULL
, void
(*reload)(HMGL
gr, void *
p)=0)
¶mglFLTK
: mglFLTK (int
(*draw)(mglGraph *
gr), const char *
title="MathGL"
)
¶mglFLTK
: mglFLTK (mglDraw *
draw, const char *
title="MathGL"
)
¶HMGL
mgl_create_graph_fltk (int
(*draw)(HMGL
gr, void *
p), const char *
title, void *
par, void
(*reload)(HMGL
gr, void *
p))
¶Создает FLTK окно для вывода графика. Параметр draw – указатель (имя) функции рисования. Есть возможность создания нескольких кадров вначале (требует больше памяти) и их быстрая анимации в дальнейшем. В этом случае функция draw должна возвращать число кадров или ноль для рисования по запросу. Замечу, что draw может быть равна NULL
для отображения статической (текущей) картинки. Параметр title задает заголовок окна. Параметр par содержит указатель на данные, передаваемые функции рисования draw. FLTK окна обеспечивают быстрое рисование и хорошо поддерживают многопоточность.
mglWnd
: int
RunThr ()
¶int
mgl_fltk_thr ()
¶Запускает цикл обработки сообщений в отдельном потоке. В данный момент работает только для окон FLTK.
mglQT
: mglQT (const char *
title="MathGL"
)
¶mglQT
: mglQT (int
(*draw)(HMGL
gr, void *
p), const char *
title="MathGL"
, void *
par=NULL
, void
(*reload)(HMGL
gr, void *
p)=0)
¶mglQT
: mglQT (int
(*draw)(mglGraph *
gr), const char *
title="MathGL"
)
¶mglQT
: mglQT (mglDraw *
draw, const char *
title="MathGL"
)
¶HMGL
mgl_create_graph_qt (int
(*draw)(HMGL
gr, void *
p), const char *
title, void *
par, void
(*reload)(HMGL
gr, void *
p))
¶Создает Qt окно для вывода графика. Параметр draw – указатель (имя) функции рисования. Есть возможность создания нескольких кадров вначале (требует больше памяти) и их быстрая анимации в дальнейшем. В этом случае функция draw должна возвращать число кадров или ноль для рисования по запросу. Замечу, что draw может быть равна NULL
для отображения статической (текущей) картинки. Параметр title задает заголовок окна. Параметр par содержит указатель на данные, передаваемые функции рисования draw.
mglGLUT
: mglGLUT (const char *
title="MathGL"
)
¶mglGLUT
: mglGLUT (int
(*draw)(HMGL
gr, void *
p), const char *
title="MathGL"
, void *
par=NULL
, void
(*reload)(HMGL
gr, void *
p)=0)
¶mglGLUT
: mglGLUT (int
(*draw)(mglGraph *
gr), const char *
title="MathGL"
)
¶mglGLUT
: mglGLUT (mglDraw *
draw, const char *
title="MathGL"
)
¶HMGL
mgl_create_graph_glut (int
(*draw)(HMGL
gr, void *
p), const char *
title, void *
par, void
(*reload)(HMGL
gr, void *
p))
¶Создает окно для вывода графика. Параметр draw – указатель (имя) функции рисования. Есть возможность создания нескольких кадров вначале (требует больше памяти) и их быстрая анимации в дальнейшем. В этом случае функция draw должна возвращать число кадров или ноль для рисования по запросу. Замечу, что draw может быть равна NULL
для отображения статической (текущей) картинки. Параметр title задает заголовок окна. Параметр par содержит указатель на данные, передаваемые функции рисования draw. Параметр kind может иметь следующие значения: ‘0’ – использовать окно FLTK, ‘1’ – использовать окно Qt.
В окне просмотра можно использовать клавиши: ’a’, ’d’, ’w’, ’s’ для вращения; ’,’, ’.’ для просмотра предыдущего и следующего кадров; ’r’ для переключения прозрачности; ’f’ для переключения оспещенности; ’x’ для закрытия окна.
Следует отметить, что цикл обработки сообщений GLUT можно остановить вызовом функции glutLeaveMainLoop()
.
Это абстрактный класс производный от класса mglGraph (см. Ядро MathGL). Он определен в #include <mgl2/wnd.h>
. Класс содержит методы для создания и управления окном, содержащим графику MathGL. Производные от него классы существует отдельно для каждой библиотеки виджетов: mglQT
в #include <mgl2/qt.h>
, mglFLTK
в #include <mgl2/fltk.h>
.
mglWnd
: int
Run ()
¶int
mgl_qt_run ()
¶int
mgl_fltk_run ()
¶Запускает цикл обработки сообщений. Обычно эта функция должна вызываться в отдельном потоке или последней функцией в main()
.
mglWnd
: void
SetDrawFunc (int
(*draw)(HMGL
gr, void *
p), void *
par=NULL
, void
(*reload)(void *
p)=NULL
)
¶mglWnd
: void
SetDrawFunc (int
(*draw)(mglGraph *
gr))
¶mglWnd
: void
SetDrawFunc (mglDraw *
obj)
¶void
mgl_wnd_set_func (HMGL
gr, int
(*draw)(HMGL
gr, void *
p), void *
par, void
(*reload)(void *
p))
¶Устанавливает функцию, которая будет вызвана при перерисовке (draw) и при повторной загрузке данных (reload), или объект obj класса, производного от mglDraw
.
mglWnd
: void
SetClickFunc (void
(*func)(HMGL
gr, void *
p))
¶void
mgl_set_click_func (void
(*func)(HMGL
gr, void *
p))
¶Устанавливает функцию, которая будет вызвана при щелчке мышью.
mglWnd
: void
SetMutex(pthread_mutex_t *
mutex) ¶void
mgl_wnd_set_mutex(HMGL
gr, pthread_mutex_t *
mutex)
¶Устанавливает внешний mutex для блокировки/разблокировки внешних вычислений с помощью меню или кнопок окна. Функция вызывается автоматически при использовании mglDraw class.
mglWnd
: void
ToggleAlpha ()
¶void
mgl_wnd_toggle_alpha (HMGL
gr)
¶Включает/выключает прозрачность, но не перекрывает ее включение в пользовательской функции рисования.
mglWnd
: void
ToggleLight ()
¶void
mgl_wnd_toggle_light (HMGL
gr)
¶Включает/выключает освещение, но не перекрывает его включение в пользовательской функции рисования.
mglWnd
: void
ToggleRotate ()
¶void
mgl_wnd_toggle_rotate (HMGL
gr)
¶Включает/выключает вращение мышкой. Нажатая левая кнопка используется для вращения, средняя для сдвига, правая для приближения/перспективы.
mglWnd
: void
ToggleZoom ()
¶void
mgl_wnd_toggle_zoom (HMGL
gr)
¶Включает/выключает приближение мышкой. Выделите прямоугольную область и она будет приближена.
mglWnd
: void
ToggleNo ()
¶void
mgl_wnd_toggle_no (HMGL
gr)
¶Выключает вращение и приближение мышкой, а также восстанавливает исходный вид графика.
mglWnd
: void
Update ()
¶void
mgl_wnd_update (HMGL
gr)
¶Обновляет содержимое окна. Функция полезна при ручном обновлении содержимого, пока долгий расчет идет в параллельном потоке.
mglWnd
: void
ReLoad ()
¶void
mgl_wnd_reload (HMGL
gr)
¶Перегружает данные и обновляет рисунок. Функция также обновляет число кадров, которое создает функция рисования.
mglWnd
: void
Adjust ()
¶void
mgl_wnd_adjust (HMGL
gr)
¶Подгоняет размер рисунка под размер окна.
mglWnd
: void
NextFrame ()
¶void
mgl_wnd_next_frame (HMGL
gr)
¶Показывает следующий кадр, если он есть.
mglWnd
: void
PrevFrame ()
¶void
mgl_wnd_prev_frame (HMGL
gr)
¶Показывает предыдущий кадр, если он есть.
mglWnd
: void
Animation ()
¶void
mgl_wnd_animation (HMGL
gr)
¶Запускает/останавливает анимацию кадров.
mglWnd
: void
SetDelay (double
dt)
¶void
mgl_wnd_set_delay (HMGL
gr, double
dt)
¶Задает задержку при анимации в секундах. По умолчанию интервал – 1 секунда.
mglWnd
: double
GetDelay ()
¶double
mgl_wnd_get_delay (HMGL
gr)
¶Возвращает задержку при анимации в секундах.
mglWnd
: void
Setup (bool
clfupd=true
, bool
showpos=false
)
¶void
mgl_setup_window (HMGL
gr, bool
clfupd, bool
showpos)
¶Включает/выключает:
mglWnd
: mglPoint
LastMousePos ()
¶void
mgl_get_last_mouse_pos (HMGL
gr, mreal *
x, mreal *
y, mreal *
z)
¶Возвращает положение щелчка мыши.
mglWnd
: void *
Widget ()
¶void *
mgl_fltk_widget (HMGL
gr)
¶void *
mgl_qt_widget (HMGL
gr)
¶Возвращает указатель на виджет (Класс Fl_MathGL or Класс QMathGL), используемый для рисования.
This class provide base functionality for callback drawing and running calculation in separate thread. It is defined in #include <mgl2/wnd.h>
. You should make inherited class and implement virtual functions if you need it.
mglDraw
: int
Draw (mglGraph *
gr)
¶This is callback drawing function, which will be called when any redrawing is required for the window. There is support of a list of plots (frames). So as one can prepare a set of frames at first and redraw it fast later (but it requires more memory). Function should return positive number of frames for the list or zero if it will plot directly.
mglDraw
: void
Reload ()
¶This is callback function, which will be called if user press menu or toolbutton to reload data.
mglDraw
: void
Click ()
¶This is callback function, which will be called if user click mouse.
mglDraw
: void
Calc ()
¶This is callback function, which will be called if user start calculations in separate thread by calling mglDraw::Run()
function. It should periodically call mglDraw::Check()
function to check if calculations should be paused.
mglDraw
: void
Run ()
¶Runs mglDraw::Calc()
function in separate thread. It also initialize mglDraw::thr
variable and unlock mglDraw::mutex
. Function is present only if FLTK support for widgets was enabled.
mglDraw
: void
Cancel ()
¶Cancels thread with calculations. Function is present only if FLTK support for widgets was enabled.
mglDraw
: void
Pause ()
¶Pauses thread with calculations by locking mglDraw::mutex
. You should call mglDraw::Continue()
to continue calculations. Function is present only if FLTK support for widgets was enabled.
mglDraw
: void
Continue ()
¶Continues calculations by unlocking mglDraw::mutex
. Function is present only if FLTK support for widgets was enabled.
mglDraw
: void
Continue ()
¶Checks if calculations should be paused and pause it. Function is present only if FLTK support for widgets was enabled.
Класс реализует элемент интерфейса FLTK для отображения графики MathGL. Он определен в #include <mgl2/Fl_MathGL.h>
.
Fl_MathGL
: void
set_draw (int
(*draw)(HMGL
gr, void *
p))
¶Fl_MathGL
: void
set_draw (int
(*draw)(mglGraph *
gr))
¶Fl_MathGL
: void
set_draw (mglDraw *
draw)
¶Устанавливает функцию рисования как глобальную функцию или как функцию член класса, производного от mglDraw
. Поддерживается список графиков (кадров), так что можно вначале их нарисовать (требует довольно много памяти), а потом достаточно быстро отображать. Функция должна возвращать положительное число создаваемых кадров или ноль для непосредственного рисования. Параметр par содержит указатель на данные пользователя, передаваемый функции рисования draw.
Fl_MathGL
: mglDraw *
get_class
() ¶Указатель на экземпляр класса mglDraw
или NULL
если отсутствует.
Fl_MathGL
: void
update ()
¶Обновляет (перерисовывает) график.
Fl_MathGL
: void
set_angle (mreal
t, mreal
p)
¶Задает углы для дополнительного вращения графика.
Fl_MathGL
: void
set_flag (int
f)
¶Задает битовые флаги для: 1 - прозрачности, 2 - освещения.
Fl_MathGL
: void
set_state (bool
z, bool
r)
¶Задает флаги обработки движений мыши: z=true
– разрешает приближение выделения, r=true
разрешает вращение/сдвиг/приближение/перспективу.
Fl_MathGL
: void
set_zoom (mreal
X1, mreal
Y1, mreal
X2, mreal
Y2)
¶Задает область приближения.
Fl_MathGL
: void
get_zoom (mreal *
X1, mreal *
Y1, mreal *
X2, mreal *
Y2)
¶Возвращает область приближения.
Fl_MathGL
: void
set_popup (const Fl_Menu_Item *
pmenu, Fl_Widget *
w, void *
v)
¶Задает указатель на всплывающее меню.
Fl_MathGL
: void
set_graph (mglCanvas *
gr)
¶Fl_MathGL
: void
set_graph (mglGraph *
gr)
¶Задает экземпляр класс для рисования вместо встроеного. Fl_MathGL автоматически удалит его при удалении виджета и при новом вызове set_graph()
.
Fl_MathGL
: mglGraph *
get_graph ()
¶Возвращает указатель на объект, строящий графики.
Fl_MathGL
: void
set_show_warn (bool
val)
¶Флаг показа окна с сообщениями после выполнения скрипта.
Fl_MathGL
: void
stop (bool
stop=true
)
¶Запрос на остановку рисования.
Fl_MathGL
: void
set_handle_key (bool
val)
¶Вкл/выкл обработку нажатий клавиш (как в mglview, по умолчанию выкл).
Fl_MathGL
: int
get_last_id ()
¶Вернуть id последнего выделенного объекта.
Fl_MathGL
: bool
running ()
¶Проверяет выполняется ли сейчас скрипт или нет.
Fl_MathGL
: Fl_Valuator *
tet_val ¶Указатель на внешний элемент управления для изменения угла tet.
Fl_MathGL
: Fl_Valuator *
phi_val ¶Указатель на внешний элемент управления для изменения угла phi.
Класс реализует элемент интерфейса Qt для отображения графики MathGL. Он определен в #include <mgl2/qt.h>
.
QMathGL
: void
setDraw (mglDraw *
dr)
¶Задает функцию рисования из класса производного от mglDraw
.
QMathGL
: void
setDraw (int (*
draw)(mglBase *
gr, void *
p)
, void *
par=NULL
)
¶QMathGL
: void
setDraw (int (*
draw)(mglGraph *
gr)
)
¶Задает функцию рисования draw. Поддерживается список графиков (кадров), так что можно вначале их нарисовать (требует довольно много памяти), а потом достаточно быстро отображать. Функция должна возвращать положительное число создаваемых кадров или ноль для непосредственного рисования. Параметр par содержит указатель на данные пользователя, передаваемый функции рисования draw.
QMathGL
: void
setGraph (mglCanvas *
gr)
¶QMathGL
: void
setGraph (mglGraph *
gr)
¶Устанавливает указатель на внешний экземпляр класса для рисования (вместо встроенного). Отмечу, что QMathGL автоматически удалит этот объект при удалении элемента интерфейса или при новом вызове setGraph()
.
QMathGL
: HMGL
getGraph ()
¶Возвращает указатель на объект, строящий графики.
QMathGL
: void
setPopup (QMenu *
p)
¶Задает указатель на всплывающее меню.
QMathGL
: void
setSize (int
w, int
h)
¶Задает размеры элемента управления и картинки.
QMathGL
: double
getRatio ()
¶Возвращает соотношение сторон рисунка.
QMathGL
: int
getPer ()
¶Возвращает величину перспективы в процентах.
QMathGL
: int
getPhi ()
¶Возвращает величину угла Phi в градусах.
QMathGL
: int
getTet ()
¶Возвращает величину угла Theta в градусах.
QMathGL
: bool
getAlpha ()
¶Возвращает состояние переключателя прозрачности.
QMathGL
: bool
getLight ()
¶Возвращает состояние переключателя освещения.
QMathGL
: bool
getZoom ()
¶Возвращает состояние переключателя приближения мышью.
QMathGL
: bool
getRotate ()
¶Возвращает состояние переключателя вращения мышью.
QMathGL
: void
refresh ()
¶Перерисовывает (обновляет) элемент управления без вызова функции рисования.
QMathGL
: void
update ()
¶Обновляет рисунок путем вызова функции рисования.
QMathGL
: void
copy ()
¶Копирует график в буфер обмена.
QMathGL
: void
copyClickCoor ()
¶Копирует координаты щелчка мышью (как текст).
QMathGL
: void
print ()
¶Печатает текущий рисунок.
QMathGL
: void
stop ()
¶Посылает сигнал остановки рисования.
QMathGL
: void
adjust ()
¶Подгоняет размер картинки под размер окна.
QMathGL
: void
nextSlide ()
¶Показывает следующий кадр.
QMathGL
: void
prevSlide ()
¶Показывает предыдущий кадр.
QMathGL
: void
animation (bool
st=true
)
¶Запускает анимацию.
QMathGL
: void
setPer (int
val)
¶Задает величину перспективы.
QMathGL
: void
setPhi (int
val)
¶Задает величину угла Phi.
QMathGL
: void
setTet (int
val)
¶Задает величину угла Theta.
QMathGL
: void
setAlpha (bool
val)
¶Включает/выключает прозрачность.
QMathGL
: void
setLight (bool
val)
¶Включает/выключает освещение.
QMathGL
: void
setGrid (bool
val)
¶Включает/выключает рисование сетки абсолютных координат на графике.
QMathGL
: void
setZoom (bool
val)
¶Включает/выключает приближение мышью.
QMathGL
: void
setRotate (bool
val)
¶Включает/выключает вращение мышью.
QMathGL
: void
zoomIn ()
¶Приблиажет график.
QMathGL
: void
zoomOut ()
¶Отдаляет график.
QMathGL
: void
shiftLeft ()
¶Сдвигает график влево.
QMathGL
: void
shiftRight ()
¶Сдвигает график вправо.
QMathGL
: void
shiftUp ()
¶Сдвигает график вверх.
QMathGL
: void
shiftDown ()
¶Сдвигает график вниз.
QMathGL
: void
restore ()
¶Восстанавливает приближение и поворот графика в значения по умолчанию.
QMathGL
: void
exportPNG (QString
fname=""
)
¶Сохраняет текущий рисунок в PNG файл.
QMathGL
: void
exportPNGs (QString
fname=""
)
¶Сохраняет текущий рисунок в PNG файл без прозрачности.
QMathGL
: void
exportJPG (QString
fname=""
)
¶Сохраняет текущий рисунок в JPEG файл.
QMathGL
: void
exportBPS (QString
fname=""
)
¶Сохраняет текущий рисунок в растровый EPS файл.
QMathGL
: void
exportEPS (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный EPS файл.
QMathGL
: void
exportSVG (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный SVG файл.
QMathGL
: void
exportGIF (QString
fname=""
)
¶Сохраняет текущий рисунок в GIF файл.
QMathGL
: void
exportTEX (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный LaTeX/Tikz файл.
QMathGL
: void
exportTGA (QString
fname=""
)
¶Сохраняет текущий рисунок в TGA файл.
QMathGL
: void
exportXYZ (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный XYZ/XYZL/XYZF файл.
QMathGL
: void
exportOBJ (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный OBJ/MTL файл.
QMathGL
: void
exportSTL (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный STL файл.
QMathGL
: void
exportOFF (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный OFF файл.
QMathGL
: void
setUsePrimitives (bool
use)
¶Разрешает использовать список примитивов для кадров. Это позволяет вращать/масштабировать кадры, но требует значительно больше памяти. По умолчанию разрешено (=true
).
QMathGL
: void
setMGLFont (QString
path)
¶Восстанавливает (path=""
) или загружает файлы шрифтов.
QMathGL
: void
about ()
¶Показывает информацию о программе.
QMathGL
: void
aboutQt ()
¶Показывает информацию о версии Qt.
QMathGL
: void
phiChanged (int
val)
¶Угол Phi изменен.
QMathGL
: void
tetChanged (int
val)
¶Угол Tet изменен.
QMathGL
: void
perChanged (int
val)
¶Перспектива изменена.
QMathGL
: void
alphaChanged (bool
val)
¶Прозрачность изменена.
QMathGL
: void
lightChanged (bool
val)
¶Освещение изменено.
QMathGL
: void
gridChanged (bool
val)
¶Рисование сетки изменено.
QMathGL
: void
zoomChanged (bool
val)
¶Режим приближения мышью изменен.
QMathGL
: void
rotateChanged (bool
val)
¶Режим вращения мышью изменен.
QMathGL
: void
mouseClick (mreal
x, mreal
y, mreal
z)
¶Был щелчок мышью в точке {x,y,z}.
QMathGL
: void
frameChanged (int
val)
¶Требуется новый кадр для отображения.
QMathGL
: void
showWarn (QString
warn)
¶Есть предупреждения.
QMathGL
: void
posChanged (QString
pos)
¶Положение щелчка мышью изменилось.
QMathGL
: void
objChanged (int
id)
¶Изменился id объекта на графике (из-за щелчка мышью).
QMathGL
: void
refreshData ()
¶Данные могли измениться (рисование завершено).
QMathGL
: QString
appName ¶Имя приложения для окон сообщений.
QMathGL
: bool
autoResize ¶Разрешить изменять размер рисунка (по умолчанию false).
Класс реализует элемент интерфейса WX для отображения графики MathGL. Он определен в #include <mgl2/wx.h>
.
wxMathGL
: void
SetDraw (mglDraw *
dr)
¶Задает функцию рисования из класса производного от mglDraw
.
wxMathGL
: void
SetDraw (int (*
draw)(mglBase *
gr, void *
p)
, void *
par=NULL
)
¶wxMathGL
: void
SetDraw (int (*
draw)(mglGraph *
gr)
)
¶Задает функцию рисования draw. Поддерживается список графиков (кадров), так что можно вначале их нарисовать (требует довольно много памяти), а потом достаточно быстро отображать. Функция должна возвращать положительное число создаваемых кадров или ноль для непосредственного рисования. Параметр par содержит указатель на данные пользователя, передаваемый функции рисования draw.
wxMathGL
: void
SetGraph (mglCanvas *
gr)
¶wxMathGL
: void
SetGraph (mglGraph *
gr)
¶Устанавливает указатель на внешний экземпляр класса для рисования (вместо встроенного). Отмечу, что wxMathGL автоматически удалит этот объект при удалении элемента интерфейса или при новом вызове setGraph()
.
wxMathGL
: HMGL
GetGraph ()
¶Возвращает указатель на объект, строящий графики.
wxMathGL
: void
SetPopup (QMenu *
p)
¶Задает указатель на всплывающее меню.
wxMathGL
: void
SetSize (int
w, int
h)
¶Задает размеры элемента управления и картинки.
wxMathGL
: double
GetRatio ()
¶Возвращает соотношение сторон рисунка.
wxMathGL
: int
GetPer ()
¶Возвращает величину перспективы в процентах.
wxMathGL
: int
GetPhi ()
¶Возвращает величину угла Phi в градусах.
wxMathGL
: int
GetTet ()
¶Возвращает величину угла Theta в градусах.
wxMathGL
: bool
GetAlpha ()
¶Возвращает состояние переключателя прозрачности.
wxMathGL
: bool
GetLight ()
¶Возвращает состояние переключателя освещения.
wxMathGL
: bool
GetZoom ()
¶Возвращает состояние переключателя приближения мышью.
wxMathGL
: bool
GetRotate ()
¶Возвращает состояние переключателя вращения мышью.
wxMathGL
: void
Repaint ()
¶Перерисовывает (обновляет) элемент управления без вызова функции рисования.
wxMathGL
: void
Update ()
¶Обновляет рисунок путем вызова функции рисования.
wxMathGL
: void
Copy ()
¶Копирует график в буфер обмена.
wxMathGL
: void
Print ()
¶Печатает текущий рисунок.
wxMathGL
: void
Adjust ()
¶Подгоняет размер картинки под размер окна.
wxMathGL
: void
NextSlide ()
¶Показывает следующий кадр.
wxMathGL
: void
PrevSlide ()
¶Показывает предыдущий кадр.
wxMathGL
: void
Animation (bool
st=true
)
¶Запускает анимацию.
wxMathGL
: void
SetPer (int
val)
¶Задает величину перспективы.
wxMathGL
: void
SetPhi (int
val)
¶Задает величину угла Phi.
wxMathGL
: void
SetTet (int
val)
¶Задает величину угла Theta.
wxMathGL
: void
SetAlpha (bool
val)
¶Включает/выключает прозрачность.
wxMathGL
: void
SetLight (bool
val)
¶Включает/выключает освещение.
wxMathGL
: void
SetZoom (bool
val)
¶Включает/выключает приближение мышью.
wxMathGL
: void
SetRotate (bool
val)
¶Включает/выключает вращение мышью.
wxMathGL
: void
ZoomIn ()
¶Приблиажет график.
wxMathGL
: void
ZoomOut ()
¶Отдаляет график.
wxMathGL
: void
ShiftLeft ()
¶Сдвигает график влево.
wxMathGL
: void
ShiftRight ()
¶Сдвигает график вправо.
wxMathGL
: void
ShiftUp ()
¶Сдвигает график вверх.
wxMathGL
: void
ShiftDown ()
¶Сдвигает график вниз.
wxMathGL
: void
Restore ()
¶Восстанавливает приближение и поворот графика в значения по умолчанию.
wxMathGL
: void
About ()
¶Показывает информацию о программе.
wxMathGL
: void
ExportPNG (QString
fname=""
)
¶Сохраняет текущий рисунок в PNG файл.
wxMathGL
: void
ExportPNGs (QString
fname=""
)
¶Сохраняет текущий рисунок в PNG файл без прозрачности.
wxMathGL
: void
ExportJPG (QString
fname=""
)
¶Сохраняет текущий рисунок в JPEG файл.
wxMathGL
: void
ExportBPS (QString
fname=""
)
¶Сохраняет текущий рисунок в растровый EPS файл.
wxMathGL
: void
ExportEPS (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный EPS файл.
wxMathGL
: void
ExportSVG (QString
fname=""
)
¶Сохраняет текущий рисунок в векторный SVG файл.
В данной главе описываются классы mglData
и mglDataC
для работы с массивами действительных и комплексных данных, определённые в #include <mgl2/data.h>
и #include <mgl2/datac.h>
соответственно. Оба класса являются наследниками абстрактного класса mglDataA
, и могут быть использованы в аргументах всех функций рисования (см. Ядро MathGL). Классы содержат функции для выделения памяти и изменения размера данных, чтения данных из файла, численного дифференцирования, интегрирования, интерполяции и пр., заполнения по текстовой формуле и т.д. Классы позволяют работать с данными размерности не более 3 (как функции от трёх переменных – x,y,z). По умолчанию внутреннее представление данных использует тип mreal (и dual=std::complex<mreal> для mglDataC
), который может быть сконфигурирован как float или double на этапе установки указав опцию --enable-double
(см. Установка MathGL). Тип float удобен в силу меньшего размера занимаемой памяти и, как правило, достаточной для построения графиков точности. Однако, тип double имеет большую точность, что может быть важно, например, для осей с метками времени. Массивы которые могут быть созданы командами MGL отображаются Small Caps шрифтом (например, DAT).
mglData
: mreal *
a ¶mglDataC
: dual *
a ¶Указатель на массив данных. Это одномерный массив. Например, матрица [nx x ny x nz] представляется одномерным массивом длиной nx*ny*nz, где элемент с индексами {i, j, k} находится как a[i+nx*j+nx*ny*k] (индексы отсчитываются от нуля).
mglData
: int
nx ¶mglDataC
: long
nx ¶Размер массива по 1-ой размерности (’x’ размерности).
mglData
: int
ny ¶mglDataC
: long
ny ¶Размер массива по 2-ой размерности (’y’ размерности).
mglData
: int
nz ¶mglDataC
: long
nz ¶Размер массива по 3-ей размерности (’z’ размерности).
mglData
: std::string
id ¶mglDataC
: std::string
id ¶Имена колонки (или среза при nz>1) – один символ на колонку.
mglData
: bool
link ¶mglDataC
: bool
link ¶Флаг использования указателя на внешние данные, включает запрет на удаление массива данных.
mglDataA
: std::wstring
s ¶Имя массива данных, использующееся при разборе MGL скриптов.
mglDataA
: bool
temp ¶Флаг временной переменной, которая может быть удалена в любой момент.
mglDataA
: void (*)(void *)
func ¶Указатель на callback функцию, которая будет вызвана при удлалении данных.
mglDataA
: void *
o ¶Указатель для callback функции.
mglData
: mreal
GetVal (long
i)
¶mglDataC
: mreal
GetVal (long
i)
¶mglData
: void
SetVal (mreal
val, long
i)
¶mglDataC
: void
SetVal (mreal
val, long
i)
¶Присваивает или возвращает значение используя "непрерывную" индексацию без проверки выхода за границы массива. Индекс i должен быть в диапазоне [0, nx*ny*nz-1].
mglDataA
: long
GetNx ()
¶mglDataA
: long
GetNy ()
¶mglDataA
: long
GetNz ()
¶long
mgl_data_get_nx (HCDT
dat)
¶long
mgl_data_get_ny (HCDT
dat)
¶long
mgl_data_get_nz (HCDT
dat)
¶Возвращает размер данных в направлении x, y и z соответственно.
mreal
mgl_data_get_value (HCDT
dat, int
i, int
j, int
k)
¶dual
mgl_datac_get_value (HCDT
dat, int
i, int
j, int
k)
¶mreal *
mgl_data_value (HMDT
dat, int
i, int
j, int
k)
¶dual *
mgl_datac_value (HADT
dat, int
i, int
j, int
k)
¶void
mgl_data_set_value (HMDT
dat, mreal
v, int
i, int
j, int
k)
¶void
mgl_datac_set_value (HADT
dat, dual
v, int
i, int
j, int
k)
¶Присваивает или возвращает значение ячейки данных с проверкой выхода за пределы массива.
const mreal *
mgl_data_data (HCDT
dat)
¶Возвращает указатель на внутренний массив данных.
void
mgl_data_set_func (mglDataA *
dat, void (*
func)(void *)
, void *
par)
¶Задает указатель на callback функцию, которая будет вызвана при удлалении данных.
void
mgl_data_set_name (mglDataA *
dat, const char *
name)
¶void
mgl_data_set_name_w (mglDataA *
dat, const wchar_t *
name)
¶Задает имя массива данных, использующееся при разборе MGL скриптов.
DAT [nx=1
'eq']
¶DAT nx ny
['eq']
¶DAT nx ny nz
['eq']
¶mglData
: mglData (int
mx=1
, int
my=1
, int
mz=1
)
¶mglDataC
: mglDataC (int
mx=1
, int
my=1
, int
mz=1
)
¶HMDT
mgl_create_data ()
¶HMDT
mgl_create_data_size (int
mx, int
my, int
mz)
¶Выделяет память для массива данных и заполняет её нулями. Если указана формула eq, то данные заполняются также как при использовании fill.
DAT dat2 ['eq'='']
¶DAT val
¶mglData
: mglData (const mglData &
dat2)
¶mglData
: mglData (const mglDataA *
dat2)
¶mglData
: mglData (int
size, const mreal *
dat2)
¶mglData
: mglData (int
size, int
cols, const mreal *
dat2)
¶mglData
: mglData (int
size, const double *
dat2)
¶mglData
: mglData (int
size, int
cols, const double *
dat2)
¶mglData
: mglData (const double *
dat2, int
size)
¶mglData
: mglData (const double *
dat2, int
size, int
cols)
¶mglDataC
: mglDataC (const mglDataA &
dat2)
¶mglDataC
: mglDataC (const mglDataA *
dat2)
¶mglDataC
: mglDataC (int
size, const float *
dat2)
¶mglDataC
: mglDataC (int
size, int
cols, const float *
dat2)
¶mglDataC
: mglDataC (int
size, const double *
dat2)
¶mglDataC
: mglDataC (int
size, int
cols, const double *
dat2)
¶mglDataC
: mglDataC (int
size, const dual *
dat2)
¶mglDataC
: mglDataC (int
size, int
cols, const dual *
dat2)
¶Копирует данные из другого экземпляра данных. Если указана формула eq, то данные заполняются также как при использовании fill.
REDAT IMDAT dat2
¶Копирует действительную и мнимую часть данных из комплексного массива данных dat2.
DAT 'name'
¶Копирует данные из другого экземпляра данных с именем name. При этом имя name может быть некорректным с точки зрения MGL (например, взятым из HDF5 файла).
DAT 'fname'
¶mglData
: mglData (const char *
fname)
¶mglDataC
: mglDataC (const char *
fname)
¶HMDT
mgl_create_data_file (const char *
fname)
¶HADT
mgl_create_datac_file (const char *
fname)
¶Читает данные из текстового файла с автоматическим определением размеров массива.
dat
¶'name'
¶mglData
: ~mglData ()
¶void
mgl_delete_data (HMDT
dat)
¶mglDataC
: ~mglDataC ()
¶void
mgl_delete_datac (HADT
dat)
¶Удаляет массив данных из памяти.
DAT [nx=1 ny=1 nz=1
]
¶mglData
: void
Create (int
mx, int
my=1
, int
mz=1
)
¶mglDataC
: void
Create (int
mx, int
my=1
, int
mz=1
)
¶void
mgl_data_create (HMDT
dat, int
mx, int
my, int
mz)
¶void
mgl_datac_create (HADT
dat, int
mx, int
my, int
mz)
¶Создает/пересоздает массив данных указанного размера и заполняет его нулями. Ничего не делает при mx, my, mz отрицательных или равных нулю.
dat mx [my=0 mz=0]
¶mglData
: void
Rearrange (int
mx, int
my=0
, int
mz=0
)
¶mglDataC
: void
Rearrange (int
mx, int
my=0
, int
mz=0
)
¶void
mgl_data_rearrange (HMDT
dat, int
mx, int
my, int
mz)
¶void
mgl_datac_rearrange (HADT
dat, int
mx, int
my, int
mz)
¶Изменяет размерность данных без изменения самого массива данных, так что результирующий массив mx*my*mz < nx*ny*nz. Если один из параметров my или mz ноль, то он будет выбран оптимальным образом. Например, если my=0, то будет my=nx*ny*nz/mx и mz=1.
dat ['dim'='yxz']
¶mglData
: void
Transpose (const char *
dim="yx"
)
¶mglDataC
: void
Transpose (const char *
dim="yx"
)
¶void
mgl_data_transpose (const char *
dim)
¶void
mgl_datac_transpose (HADT
dat, const char *
dim)
¶Транспонирует (меняет порядок размерностей) массив данных. Новый порядок размерностей задается строкой dim. Функция может быть полезна для транспонирования одномерных (или квазиодномерных) массивов после чтения их из файла.
dat n1 [n2=0]
¶mglData
: void
Extend (int
n1, int
n2=0
)
¶mglDataC
: void
Extend (int
n1, int
n2=0
)
¶void
mgl_data_extend (HMDT
dat, int
n1, int
n2)
¶void
mgl_datac_extend (HADT
dat, int
n1, int
n2)
¶Увеличивает размер данных путем вставки (|n1|+1) новых срезов после (для n1>0) или перед (для n1<0) существующими данными. Можно добавить сразу 2 размерности для 1d массива, используя второй параметр n2. Данные в новые срезы будут скопированы из существующих. Например, для n1>0 новый массив будет a_ij^new = a_i^old where j=0...n1. Соответственно, для n1<0 новый массив будет a_ij^new = a_j^old, где i=0...|n1|.
dat rx [ry=1 rz=1 sm=off]
¶mglData
: void
Squeeze (int
rx, int
ry=1
, int
rz=1
, bool
smooth=false
)
¶mglDataC
: void
Squeeze (int
rx, int
ry=1
, int
rz=1
, bool
smooth=false
)
¶void
mgl_data_squeeze (HMDT
dat, int
rx, int
ry, int
rz, int
smooth)
¶void
mgl_datac_squeeze (HADT
dat, int
rx, int
ry, int
rz, int
smooth)
¶Уменьшает размер данных путём удаления элементов с индексами не кратными rx, ry, rz соответственно. Параметр smooth задает использовать сглаживания (т.е. out[i]=\sum_{j=i,i+r} a[j]/r) или нет (т.е. out[i]=a[j*r]).
dat n1 n2
'dir'
¶mglData
: void
Crop (int
n1, int
n2, char
dir='x'
)
¶mglDataC
: void
Crop (int
n1, int
n2, char
dir='x'
)
¶void
mgl_data_crop (HMDT
dat, int
n1, int
n2, char
dir)
¶void
mgl_datac_crop (HADT
dat, int
n1, int
n2, char
dir)
¶Обрезает границы данных при i<n1 и i>n2 (при n2>0) или i>n[xyz]
-n2 (при n2<=0) вдоль направления dir.
dat 'how'
¶mglData
: void
Crop (const char *
how="235x"
)
¶mglDataC
: void
Crop (const char *
how="235x"
)
¶void
mgl_data_crop_opt (HMDT
dat, const char *
how)
¶void
mgl_datac_crop_opt (HADT
dat, const char *
how)
¶Обрезает дальний край данных, чтобы сделать их более оптимальным для быстрого преобразования Фурье. Размер массива будет равен наиболее близким к исходному из 2^n*3^m*5^l. Строка how может содержать: ‘x’, ‘y’, ‘z’ для направлений, и ‘2’, ‘3’, ‘5’ для использования соответствующего основания.
dat 'dir' [pos=off num=0]
¶mglData
: void
Insert (char
dir, int
pos=0
, int
num=1
)
¶mglDataC
: void
Insert (char
dir, int
pos=0
, int
num=1
)
¶void
mgl_data_insert (HMDT
dat, char
dir, int
pos, char
num)
¶void
mgl_datac_insert (HADT
dat, char
dir, int
pos, char
num)
¶Вставляет num срезов вдоль направления dir с позиции pos и заполняет их нулями.
dat 'dir' [pos=off num=0]
¶mglData
: void
Delete (char
dir, int
pos=0
, int
num=1
)
¶mglDataC
: void
Delete (char
dir, int
pos=0
, int
num=1
)
¶void
mgl_data_delete (HMDT
dat, char
dir, int
pos, char
num)
¶void
mgl_datac_delete (HADT
dat, char
dir, int
pos, char
num)
¶Удаляет num срезов вдоль направления dir с позиции pos.
dat idx [idy=-1]
¶mglData
: void
Sort (lond
idx, long
idy=-1
)
¶void
mgl_data_sort (HMDT
dat, lond
idx, long
idy)
¶Сортирует строки (или срезы в 3D случае) по значениям в указанной колонке idx (или ячейках {idx,idy} для 3D случая). Не используйте в многопоточных функциях!
dat idx
¶mglData
: void
Clean (lond
idx)
¶void
mgl_data_clean (HMDT
dat, lond
idx)
¶Удаляет строки в которых значения для заданной колонки idx совпадают со значениями в следующей строке.
dat vdat [v2dat ...]
¶mglData
: void
Join (const mglDataA &
vdat)
¶mglDataC
: void
Join (const mglDataA &
vdat)
¶void
mgl_data_join (HMDT
dat, HCDT
vdat)
¶void
mgl_datac_join (HADT
dat, HCDT
vdat)
¶Объединяет данные из массива vdat с данными массива dat. При этом, функция увеличивает размер массива dat: в z-направлении для массивов с одинаковыми размерами по x и y; в y-направлении для массивов с одинаковыми размерами по x; в x-направлении в остальных случаях.
DAT v1 ...
¶Создает новый массив данных dat и заполняет его числовыми значениями аргументов v1 ...
. Команда может создавать одно- и двухмерные массивы с произвольными значениями. Для создания 2d массива следует использовать разделитель ‘|’, который означает начало новой строки данных. Размер массива данных будет [maximal of row sizes * number of rows]. Например, команда list 1 | 2 3
создаст массив [1 0; 2 3]. Замечу, что максимальное число аргументов равно 1000.
DAT d1 ...
¶Создает новый массив данных dat и заполняет его значениями из массивов d1 .... Команда может создавать двух- и трёхмерные (если аргументы – двумерные массивы) массивы. Меньшая размерность всех массивов в аргументах должна совпадать. В противном случае аргумент (массив) будет пропущен.
mglData
: void
Set (const mreal *
A, int
NX, int
NY=1
, int
NZ=1
)
¶mglData
: void
Set (const double *
A, int
NX, int
NY=1
, int
NZ=1
)
¶void
mgl_data_set_mreal (HMDT
dat, const mreal *
A, int
NX, int
NY, int
NZ)
¶void
mgl_data_set_double (HMDT
dat, const double *
A, int
NX, int
NY, int
NZ)
¶mglDataC
: void
Set (const float *
A, int
NX, int
NY=1
, int
NZ=1
)
¶mglDataC
: void
Set (const double *
A, int
NX, int
NY=1
, int
NZ=1
)
¶mglDataC
: void
Set (const dual *
A, int
NX, int
NY=1
, int
NZ=1
)
¶void
mgl_datac_set_float (HADT
dat, const mreal *
A, int
NX, int
NY, int
NZ)
¶void
mgl_datac_set_double (HADT
dat, const double *
A, int
NX, int
NY, int
NZ)
¶void
mgl_datac_set_complex (HADT
dat, const dual *
A, int
NX, int
NY, int
NZ)
¶Выделяет память и копирует данные из массивов типа mreal*
или double*
, т.е. из массивов определённых как mreal a[NX*NY*NZ];
.
mglData
: void
Set (const mreal **
A, int
N1, int
N2)
¶mglData
: void
Set (const double **
A, int
N1, int
N2)
¶void
mgl_data_set_mreal2 (HMDT
dat, const mreal **
A, int
N1, int
N2)
¶void
mgl_data_set_double2 (HMDT
dat, const double **
A, int
N1, int
N2)
¶Выделяет память и копирует данные из массивов типа mreal**
или double**
с размерностями N1, N2, т.е. из массивов определённых как mreal a[N1][N2];
.
mglData
: void
Set (const mreal ***
A, int
N1, int
N2)
¶mglData
: void
Set (const double ***
A, int
N1, int
N2)
¶void
mgl_data_set_mreal3 (HMDT
dat, const mreal ***
A, int
N1, int
N2)
¶void
mgl_data_set_double3 (HMDT
dat, const double ***
A, int
N1, int
N2)
¶Выделяет память и копирует данные из массивов типа mreal***
или double***
с размерностями N1, N2, N3, т.е. из массивов определённых как mreal a[N1][N2][N3];
.
mglData
: void
Set (gsl_vector *
v)
¶mglDataC
: void
Set (gsl_vector *
v)
¶void
mgl_data_set_vector (HMDT
dat, gsl_vector *
v)
¶void
mgl_datac_set_vector (HADT
dat, gsl_vector *
v)
¶Выделяет память и копирует данные из структуры типа gsl_vector *
.
mglData
: void
Set (gsl_matrix *
m)
¶mglDataC
: void
Set (gsl_matrix *
m)
¶void
mgl_data_set_matrix (HMDT
dat, gsl_matrix *
m)
¶void
mgl_datac_set_matrix (HADT
dat, gsl_matrix *
m)
¶Выделяет память и копирует данные из структуры типа gsl_matrix *
.
mglData
: void
Set (const mglDataA &
from)
¶mglData
: void
Set (HCDT
from)
¶void
mgl_data_set (HMDT
dat, HCDT
from)
¶mglDataC
: void
Set (const mglDataA &
from)
¶mglDataC
: void
Set (HCDT
from)
¶void
mgl_datac_set (HADT
dat, HCDT
from)
¶Выделяет память и копирует данные из другого экземпляра данных from.
mglDataC
: void
Set (const mglDataA &
re, const mglDataA &
im)
¶mglDataC
: void
Set (HCDT
re, HCDT
im)
¶mglDataC
: void
SetAmpl (HCDT
ampl, const mglDataA &
phase)
¶void
mgl_datac_set_ri (HADT
dat, HCDT
re, HCDT
im)
¶void
mgl_datac_set_ap (HADT
dat, HCDT
ampl, HCDT
phase)
¶Выделяет память и копирует данные из экземпляра данных для действительной re и мнимой im частей комплексного массива данных.
mglData
: void
Set (const std::vector<int> &
d)
¶mglDataC
: void
Set (const std::vector<int> &
d)
¶mglData
: void
Set (const std::vector<float> &
d)
¶mglDataC
: void
Set (const std::vector<float> &
d)
¶mglData
: void
Set (const std::vector<double> &
d)
¶mglDataC
: void
Set (const std::vector<double> &
d)
¶mglDataC
: void
Set (const std::vector<dual> &
d)
¶Выделяет память и копирует данные из массива типа std::vector<T>
.
mglData
: void
Set (const char *
str, int
NX, int
NY=1
, int
NZ=1
)
¶void
mgl_data_set_values (const char *
str, int
NX, int
NY, int
NZ)
¶mglDataC
: void
Set (const char *
str, int
NX, int
NY=1
, int
NZ=1
)
¶void
mgl_datac_set_values (const char *
str, int
NX, int
NY, int
NZ)
¶Выделяет память и сканирует массив данных из строки.
mglData
: void
SetList (long
n, ...)
¶Allocate memory and set data from variable argument list of double values. Note, you need to specify decimal point ‘.’ for integer values! For example, the code SetList(2,0.,1.);
is correct, but the code SetList(2,0,1);
is incorrect.
mglData
: void
Set (const arma::vec &
d)
¶mglData
: void
Set (const arma::mat &
d)
¶mglData
: void
Set (const arma::cube &
d)
¶mglDataC
: void
Set (const arma::vec &
d)
¶mglDataC
: void
Set (const arma::cx_vec &
d)
¶mglDataC
: void
Set (const arma::mat &
d)
¶mglDataC
: void
Set (const arma::cx_mat &
d)
¶mglDataC
: void
Set (const arma::cube &
d)
¶mglDataC
: void
Set (const arma::cx_cube &
d)
¶Выделяет память и копирует данные из Armadillo структур.
mglData
: arma::mat
arma_mat (long
k=0)
¶mglData
: arma::cube
arma_cube ()
¶mglData
: arma::cx_mat
arma_mat (long
k=0)
¶mglData
: arma::cx_cube
arma_cube ()
¶Возвращает данные в формате структур Armadillo.
mglData
: void
Link (mglData &
from)
¶mglData
: void
Link (mreal *
A, int
NX, int
NY=1
, int
NZ=1
)
¶void
mgl_data_link (HMDT
dat, const mreal *
A, int
NX, int
NY, int
NZ)
¶mglDataC
: void
Link (mglDataC &
from)
¶mglDataC
: void
Link (dual *
A, int
NX, int
NY=1
, int
NZ=1
)
¶void
mgl_datac_link (HADT
dat, const mreal *
A, int
NX, int
NY, int
NZ)
¶Устанавливает флаг использования внешнего массива данных, которые не будут удалены. Флаг может быть возвращён в исходное состояние и создан новый внутренний массив если использовались функции изменяющие размер данных.
DAT num v1 [v2=nan]
¶Создает новый одномерный массив данных dat размером num, и заполняет его равномерно в диапазоне [v1, v2]. Если v2=nan
, то используется v2=v1.
dat v1 v2 ['dir'='x']
¶mglData
: void
Fill (mreal
v1, mreal
v2, char
dir='x'
)
¶mglDataC
: void
Fill (dual
v1, dual
v2, char
dir='x'
)
¶void
mgl_data_fill (HMDT
dat, mreal
v1, mreal
v2, char
dir)
¶void
mgl_datac_fill (HADT
dat, dual
v1, dual
v2, char
dir)
¶Заполняет значениями равно распределёнными в диапазоне [x1, x2] в направлении dir={‘x’,‘y’,‘z’}.
dat 'eq'[vdat wdat]
¶mglData
: void
Fill (HMGL
gr, const char *
eq, const char *
opt=""
)
¶mglData
: void
Fill (HMGL
gr, const char *
eq, const mglDataA &
vdat, const char *
opt=""
)
¶mglData
: void
Fill (HMGL
gr, const char *
eq, const mglDataA &
vdat, const mglDataA &
wdat, const char *
opt=""
)
¶mglDataC
: void
Fill (HMGL
gr, const char *
eq, const char *
opt=""
)
¶mglDataC
: void
Fill (HMGL
gr, const char *
eq, const mglDataA &
vdat, const char *
opt=""
)
¶mglDataC
: void
Fill (HMGL
gr, const char *
eq, const mglDataA &
vdat, const mglDataA &
wdat, const char *
opt=""
)
¶void
mgl_data_fill_eq (HMGL
gr, HMDT
dat, const char *
eq, HCDT
vdat, HCDT
wdat, const char *
opt)
¶void
mgl_datac_fill_eq (HMGL
gr, HADT
dat, const char *
eq, HCDT
vdat, HCDT
wdat, const char *
opt)
¶Заполняет значениями вычисленными по формуле eq. Формула представляет собой произвольное выражение, зависящее от переменных ‘x’, ‘y’, ‘z’, ‘u’, ‘v’, ‘w’. Координаты ‘x’, ‘y’, ‘z’ полагаются меняющимися в диапазоне Min x Max (в отличие от функции Modify
). Переменные ‘i’, ‘j’, ‘k’ равны значениям соответствующего индекса. При этом, используются нулевые значения для переменных, отвечающих отсутствующим размерностям. Переменная ‘u’ – значения исходного массива, переменные ‘v’, ‘w’ – значения массивов vdat, wdat. Последние могут быть NULL
, т.е. опущены.
dat 'eq' [dim=0
]
¶dat 'eq' vdat [wdat]
¶mglData
: void
Modify (const char *
eq, int
dim=0
)
¶mglData
: void
Modify (const char *
eq, const mglDataA &
v)
¶mglData
: void
Modify (const char *
eq, const mglDataA &
v, const mglDataA &
w)
¶mglDataC
: void
Modify (const char *
eq, int
dim=0
)
¶mglDataC
: void
Modify (const char *
eq, const mglDataA &
v)
¶mglDataC
: void
Modify (const char *
eq, const mglDataA &
v, const mglDataA &
w)
¶void
mgl_data_modify (HMDT
dat, const char *
eq, int
dim)
¶void
mgl_data_modify_vw (HMDT
dat, const char *
eq, HCDT
v, HCDT
w)
¶void
mgl_datac_modify (HADT
dat, const char *
eq, int
dim)
¶void
mgl_datac_modify_vw (HADT
dat, const char *
eq, HCDT
v, HCDT
w)
¶Аналогично предыдущему с координатами ‘x’, ‘y’, ‘z’, меняющимися в диапазоне [0,1]. Переменные ‘i’, ‘j’, ‘k’ равны значениям соответствующего индекса. При этом, используются нулевые значения для переменных, отвечающих отсутствующим размерностям. Если указан dim>0, то изменяются только слои >=dim.
dat 'how'
¶mglData
: void
FillSample (const char *
how)
¶void
mgl_data_fill_sample (HMDT
a, const char *
how)
¶Заполняет массив данных ’x’ или ’k’ значениями для преобразований Ханкеля (’h’) или Фурье (’f’).
dat xdat ydat zdat
¶mglData
: mglData
Grid (HMGL
gr, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const char *
opt=""
)
¶mglData
: mglData
Grid (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, mglPoint
p1, mglPoint
p2)
¶void
mgl_data_grid (HMGL
gr, HMDT
u, HCDT
x, HCDT
y, HCDT
z, const char *
opt)
¶void
mgl_data_grid_xy (HMDT
u, HCDT
x, HCDT
y, HCDT
z, mreal
x1, mreal
x2, mreal
y1, mreal
y2)
¶Заполняет значения массива результатом линейной интерполяции (считая координаты равнораспределенными в диапазоне осей координат или в диапазоне [x1,x2]*[y1,y2]) по триангулированной поверхности, найденной по произвольно расположенным точкам ‘x’, ‘y’, ‘z’. NAN значение используется для точек сетки вне триангулированной поверхности. См. раздел Making regular data, для примеров кода и графика.
dat val [i=all j=all k=all]
¶mglData
: void
Put (mreal
val, int
i=-1
, int
j=-1
, int
k=-1
)
¶mglDataC
: void
Put (dual
val, int
i=-1
, int
j=-1
, int
k=-1
)
¶void
mgl_data_put_val (HMDT
a, mreal
val, int
i, int
j, int
k)
¶void
mgl_datac_put_val (HADT
a, dual
val, int
i, int
j, int
k)
¶Присваивает значения (под-)массива dat[i, j, k] = val. Индексы i, j, k равные ‘-1’ задают значения val для всего диапазона соответствующего направления(ий). Например, Put(val,-1,0,-1);
задает a[i,0,j]=val для i=0...(nx-1), j=0...(nz-1).
dat vdat [i=all j=all k=all
]
¶mglData
: void
Put (const mglDataA &
v, int
i=-1
, int
j=-1
, int
k=-1
)
¶mglDataC
: void
Put (const mglDataA &
v, int
i=-1
, int
j=-1
, int
k=-1
)
¶void
mgl_data_put_dat (HMDT
a, HCDT
v, int
i, int
j, int
k)
¶void
mgl_datac_put_dat (HADT
a, HCDT
v, int
i, int
j, int
k)
¶Копирует значения из массива v в диапазон значений данного массива. Индексы i, j, k равные ‘-1’ задают диапазон изменения значений в соответствующих направление(ях). Младшие размерности массива v должны быть больше выбранного диапазона массива. Например, Put(v,-1,0,-1);
присвоит a[i,0,j]=v.ny>nz ? v.a[i,j] : v.a[i], где i=0...(nx-1), j=0...(nz-1) и условие v.nx>=nx выполнено.
dat xdat vdat [sl=-1]
¶dat xdat ydat vdat [sl=-1]
¶dat xdat ydat zdat vdat
¶mglData
: void
Refill (const mglDataA &
x, const mglDataA &
v, mreal
x1, mreal
x2, long
sl=-1
)
¶mglData
: void
Refill (const mglDataA &
x, const mglDataA &
v, mglPoint
p1, mglPoint
p2, long
sl=-1
)
¶mglData
: void
Refill (const mglDataA &
x, const mglDataA &
y, const mglDataA &
v, mglPoint
p1, mglPoint
p2, long
sl=-1
)
¶mglData
: void
Refill (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
v, mglPoint
p1, mglPoint
p2)
¶mglData
: void
Refill (HMGL
gr, const mglDataA &
x, const mglDataA &
v, long
sl=-1
, const char *
opt=""
)
¶mglData
: void
Refill (HMGL
gr, const mglDataA &
x, const mglDataA &
y, const mglDataA &
v, long
sl=-1
, const char *
opt=""
)
¶mglData
: void
Refill (HMGL
gr, const mglDataA &
x, const mglDataA &
y, const mglDataA &
z, const mglDataA &
v, const char *
opt=""
)
¶void
mgl_data_refill_x (HMDT
a, HCDT
x, HCDT
v, mreal
x1, mreal
x2, long
sl)
¶void
mgl_data_refill_xy (HMDT
a, HCDT
x, HCDT
y, HCDT
v, mreal
x1, mreal
x2, mreal
y1, mreal
y2, long
sl)
¶void
mgl_data_refill_xyz (HMDT
a, HCDT
x, HCDT
y, HCDT
z, HCDT
v, mreal
x1, mreal
x2, mreal
y1, mreal
y2, mreal
z1, mreal
z2)
¶void
mgl_data_refill_gr (HMGL
gr, HMDT
a, HCDT
x, HCDT
y, HCDT
z, HCDT
v, long
sl, const char *
opt)
¶Заполняет значениями интерполяции массива v в точках {x, y, z}={X[i], Y[j], Z[k]
} (или {x, y, z}={X[i,j,k], Y[i,j,k], Z[i,j,k]
} если x, y, z не 1d массивы), где X,Y,Z
равномерно распределены в диапазоне [x1,x2]*[y1,y2]*[z1,z2] и имеют такой же размер как и заполняемый массив. Если параметр sl равен 0 или положительный, то изменятся будет только sl-ый срез.
dat xdat vdat [sl=-1]
¶mglData
: void
RefillGS (const mglDataA &
x, const mglDataA &
v, mreal
x1, mreal
x2, long
sl=-1
)
¶void
mgl_data_refill_gs (HMDT
a, HCDT
x, HCDT
v, mreal
x1, mreal
x2, long
sl)
¶Заполняет значениями глобального кубического сплайна для массива v в точках x=X[i]
, где X
равномерно распределен в диапазоне [x1,x2] и имеет такой же размер как и заполняемый массив. Если параметр sl равен 0 или положительный, то изменятся будет только sl-ый срез.
dat 'ids'
¶mglData
: void
SetColumnId (const char *
ids)
¶void
mgl_data_set_id (const char *
ids)
¶mglDataC
: void
SetColumnId (const char *
ids)
¶void
mgl_datac_set_id (HADT
a, const char *
ids)
¶Задает названия ids для колонок массива данных. Строка должна содержать один символ ’a’...’z’ на колонку. Эти названия используются в функции column.
dat [p=0.5
]
¶mglData
: void
RndBernoulli (mreal
p=0.5)
¶void
mgl_data_rnd_bernoulli (HMDT
dat, mreal
p)
¶mreal
mgl_rnd_bernoulli (mreal
p)
¶Заполняет массив случайными числами с распределением Бернулли вероятности p.
dat n [p=0.5]
¶mglData
: void
RndBinomial (long
n, mreal
p=0.5)
¶void
mgl_data_rnd_binomial (HMDT
dat, long
n, mreal
p)
¶mreal
mgl_rnd_binomial (long
n, mreal
p)
¶Заполняет массив случайными числами с биномиальным распределением в n бросков с вероятностью p.
dat y1 y2 sigma h
¶mglData
: void
RndBrownian (mreal
y1, mreal
y2, mreal
sigma, mreal
h)
¶void
mgl_data_rnd_brownian (HMDT
dat, mreal
y1, mreal
y2, mreal
sigma, mreal
h)
¶Заполняет массив случайным броуновским движением.
dat vdat
¶mglData
: void
RndDiscrete (const mglDataA &
vdat)
¶void
mgl_data_rnd_discrete (HMDT
dat, HCDT
vdat)
¶mreal
mgl_rnd_discrete (HCDT
vdat)
¶Заполняет массив случайными числами с дискретным распределением.
dat [p
]
¶mglData
: void
RndExponential (mreal
p)
¶void
mgl_data_rnd_exponential (HMDT
dat, mreal
p)
¶mreal
mgl_rnd_exponential (mreal
p)
¶Заполняет массив случайными числами с экспоненциальным распределением масштаба p.
dat [mu=0 sigma=1
]
¶mglData
: void
RndGaussian (mreal
mu=0, mreal
sigma=1)
¶void
mgl_data_rnd_gaussian (HMDT
dat, mreal
mu, mreal
sigma)
¶mreal
mgl_rnd_gaussian (mreal
mu, mreal
sigma)
¶Заполняет массив случайными числами с гауссовым распределением со средним mu и масштабом sigma.
dat ['dir'='a']
¶mglData
: void
RndShuffle (char
dir='a')
¶void
mgl_data_rnd_shuffle (HMDT
dat, char
dir)
¶Перемешивает содержимое ячеек (для dir=‘a’) или срезов (для dir=‘xyz’).
dat lo hi
¶mglData
: void
RndUniform (mreal
lo, mreal
hi)
¶void
mgl_data_rnd_uniform (HMDT
dat, mreal
lo, mreal
hi)
¶mreal
mgl_rnd_uniform (mreal
lo, mreal
hi)
¶Заполняет массив случайными числами с равномерным распределением в интервале (lo,hi).
dat lo hi
¶mglData
: void
RndInteger (long
lo, long
hi)
¶void
mgl_data_rnd_integer (HMDT
dat, long
lo, mreal
hi)
¶long
mgl_rnd_integer (long
lo, long
hi)
¶Заполняет массив случайными целыми числами с равномерным распределением в интервале [lo,hi).
DAT 'fname'
¶REDAT IMDAT 'fname'
¶mglData
: bool
Read (const char *
fname)
¶mglDataC
: bool
Read (const char *
fname)
¶int
mgl_data_read (HMDT
dat, const char *
fname)
¶int
mgl_datac_read (HADT
dat, const char *
fname)
¶Читает данные из текстового файла с разделителями символом пробела/табуляции с автоматическим определением размера массива. Двойной перевод строки начинает новый срез данных (по направлению z).
DAT 'fname' mx [my=1 mz=1]
¶REDAT IMDAT 'fname' mx [my=1 mz=1]
¶mglData
: bool
Read (const char *
fname, int
mx, int
my=1
, int
mz=1
)
¶mglDataC
: bool
Read (const char *
fname, int
mx, int
my=1
, int
mz=1
)
¶int
mgl_data_read_dim (HMDT
dat, const char *
fname, int
mx, int
my, int
mz)
¶int
mgl_datac_read_dim (HADT
dat, const char *
fname, int
mx, int
my, int
mz)
¶Читает данные из текстового файла с заданными размерами. Ничего не делается если параметры mx, my или mz равны нулю или отрицательны.
DAT 'fname' [dim=2
]
¶mglData
: bool
ReadMat (const char *
fname, int
dim=2
)
¶mglDataC
: bool
ReadMat (const char *
fname, int
dim=2
)
¶int
mgl_data_read_mat (HMDT
dat, const char *
fname, int
dim)
¶int
mgl_datac_read_mat (HADT
dat, const char *
fname, int
dim)
¶Читает данные из текстового файла с размерами, указанными в первых dim числах файла. При этом переменная dim задает размерность (1d, 2d, 3d) данных.
DAT 'templ' v1 v2 [dv=1 slice=off]
¶mglData
: bool
ReadRange (const char *
templ, mreal
from, mreal
to, mreal
step=1.f
, bool
as_slice=false
)
¶mglDataC
: bool
ReadRange (const char *
templ, mreal
from, mreal
to, mreal
step=1
, bool
as_slice=false
)
¶int
mgl_data_read_range (HMDT
dat, const char *
templ, mreal
from, mreal
to, mreal
step, int
as_slice)
¶int
mgl_datac_read_range (HADT
dat, const char *
templ, mreal
from, mreal
to, mreal
step, int
as_slice)
¶Объединяет данные из нескольких текстовых файлов. Имена файлов определяются вызовом функции sprintf(fname,templ,val);
, где val меняется от from до to с шагом step. Данные загружаются один за другим в один и тот же срез данных (при as_slice=false
) или срез-за-срезом (при as_slice=true
).
DAT 'templ' [slice=off]
¶mglData
: bool
ReadAll (const char *
templ, bool
as_slice=false
)
¶mglDataC
: bool
ReadAll (const char *
templ, bool
as_slice=false
)
¶int
mgl_data_read_all (HMDT
dat, const char *
templ, int
as_slice)
¶int
mgl_datac_read_all (HADT
dat, const char *
templ, int
as_slice)
¶Объединяет данные из нескольких текстовых файлов, чьи имена удовлетворяют шаблону templ (например, templ="t_*.dat"
). Данные загружаются один за другим в один и тот же срез данных (при as_slice=false
) или срез-за-срезом (при as_slice=true
).
DAT 'fname' 'templ'
¶mglData
: bool
ScanFile (const char *
fname, const char *
templ)
¶int
mgl_data_scan_file (HMDT
dat, const char *
fname, const char *
templ)
¶Читает файл fname построчно и каждую строку сканирует на соответствие шаблону templ. Полученные числа (обозначаются как ‘%g’ в шаблоне) сохраняются. См. раздел Scanning file, для примеров кода и графика.
dat 'fname'
¶mglDataA
: void
Save (const char *
fname, int
ns=-1
) const
¶void
mgl_data_save (HCDT
dat, const char *
fname, int
ns)
¶void
mgl_datac_save (HCDT
dat, const char *
fname, int
ns)
¶Сохраняет весь массив данных при ns=-1
или только ns-ый срез в текстовый файл.
val
'fname'
¶Сохраняет значение val в файл fname.
'str' 'fname' ['mode'='a']
¶Сохраняет строку str в файл fname. Для параметра mode=‘a’ происходит добавление строки (по умолчанию): для mode=‘w’ файл будет перезаписан. См. раздел Scanning file, для примеров кода и графика.
DAT 'fname' 'dname'
¶mglData
: void
ReadHDF (const char *
fname, const char *
dname)
¶mglDataC
: void
ReadHDF (const char *
fname, const char *
dname)
¶void
mgl_data_read_hdf (HMDT
dat, const char *
fname, const char *
dname)
¶void
mgl_datac_read_hdf (HADT
dat, const char *
fname, const char *
dname)
¶Читает массив с именем dname из HDF5 или HDF4 файла fname. Функция ничего не делает если библиотека была собрана без поддержки HDF5|HDF4.
dat 'fname' 'dname' [rewrite
=off
]
¶mglDataA
: void
SaveHDF (const char *
fname, const char *
dname, bool
rewrite=false
) const
¶void
mgl_data_save_hdf (HCDT
dat, const char *
fname, const char *
dname, int
rewrite)
¶void
mgl_datac_save_hdf (HCDT
dat, const char *
fname, const char *
dname, int
rewrite)
¶Сохраняет массив под именем dname в HDF5 или HDF4 файл fname. Функция ничего не делает если библиотека была собрана без поддержки HDF5|HDF4.
val
'fname' 'dname' [rewrite
=off
]
¶void
mgl_real_save_hdf (real
val, const char *
fname, const char *
dname, int
rewrite)
¶void
mgl_dual_save_hdf (dual
val, const char *
fname, const char *
dname, int
rewrite)
¶void
mgl_int_save_hdf (long
val, const char *
fname, const char *
dname, int
rewrite)
¶Сохраняет значение val
под именем dname в HDF5 файл fname. Функция ничего не делает если библиотека была собрана без поддержки HDF5.
'fname'
¶mglDataA
: int
DatasHDF (const char *
fname, char *
buf, long
size) static
¶void
mgl_datas_hdf (const char *
fname, char *
buf, long
size)
¶Помещает имена массивов данных в HDF5 файле fname в строку buf разделёнными символом табуляции ’\t’. В версии MGL имена массивов будут выведены как сообщение. Функция ничего не делает если библиотека была собрана без поддержки HDF5.
'fname'
¶mglParse
: void
OpenHDF (const char *
fname)
¶void
mgl_parser_openhdf (HMPR
pr, const char *
fname)
¶Читает все массивы данных из HDF5 файла fname и создает переменные MGL с соответствующими именами. Если имя данных начинается с ‘!’, то будут созданы комплексные массивы.
const char * const *
mgl_datas_hdf_str (HMPR
pr, const char *
fname)
¶Помещает имена данных из HDF файла fname в массив строк (последняя строка ""). Массив строк будет изменен при следующем вызове функции.
DAT 'fname' 'sch' [v1=0 v2=1
]
¶mglData
: void
Import (const char *
fname, const char *
scheme, mreal
v1=0
, mreal v2=1
)
¶void
mgl_data_import (HMDT
dat, const char *
fname, const char *
scheme, mreal
v1, mreal v2)
¶Читает данные из растрового файла. RGB значения пикселов преобразуются в число в диапазоне [v1, v2] используя цветовую схему sch (see Цветовая схема).
dat 'fname' 'sch' [v1=0 v2=0
]
¶mglDataA
: void
Export (const char *
fname, const char *
scheme, mreal
v1=0
, mreal v2=0
, int
ns=-1
) const
¶void
mgl_data_export (HMDT
dat, const char *
fname, const char *
scheme, mreal
v1, mreal v2, int
ns) const
¶Сохраняет данные в растровый файл. Числовые значения, нормированные в диапазон [v1, v2], преобразуются в RGB значения пикселов, используя цветовую схему sch (see Цветовая схема). Если v1>=v2, то значения v1, v2 определяются автоматически как минимальное и максимальное значение данных.
dat 'fname' type
¶mglData
: bool
ReadBin (const char *
fname, int
type)
¶int
mgl_data_read_bin (HMDT
dat, const char *
fname, int
type)
¶Читает данные из файла в бинарном формате. Параметр type задает тип данных в файле: 0 - double, 1 - float, 2 - long double, 3 - long int, 4 - int, 5 - short int, 6 - char. Внимание! Эту функцию не рекомендуется использовать с данными, сохраненными на других компьютерах из-за возможных проблем с бинарным представлением чисел. Предпочтительнее использовать HDF формат, см. readhdf.
RES dat xx [yy=all zz=all]
¶mglData
: mglData
SubData (mreal
xx, mreal
yy=-1
, mreal
zz=-1
) const
¶mglDataC
: mglData
SubData (mreal
xx, mreal
yy=-1
, mreal
zz=-1
) const
¶HMDT
mgl_data_subdata (HCDT
dat, mreal
xx, mreal
yy, mreal
zz)
¶Возвращает в res подмассив массива данных dat с фиксированными значениями индексов с положительными значениями. Например, SubData(-1,2)
выделяет третью строку (индексы начинаются с нуля), SubData(4,-1)
выделяет 5-ую колонку, SubData(-1,-1,3)
выделяет 4-ый срез и т.д. В MGL скриптах обычно используется упрощенная версия dat(xx,yy,zz)
. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat xdat [ydat zdat]
¶mglData
: mglData
SubData (const mglDataA &
xx, const mglDataA &
yy, const mglDataA &
zz) const
¶mglDataC
: mglData
SubData (const mglDataA &
xx, const mglDataA &
yy, const mglDataA &
zz) const
¶HMDT
mgl_data_subdata_ext (HCDT
dat, HCDT
xx, HCDT
yy, HCDT
zz)
¶Возвращает в res подмассив массива данных dat с индексами, заданными в массивах xx, yy, zz (косвенная адресация). Результат будет иметь размерность массивов с индексами. Размеры массивов xx, yy, zz с индексами должна быть одинакова, либо должны быть "скаляром" (т.е. 1*1*1). В MGL скриптах обычно используется упрощенная версия dat(xx,yy,zz)
. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat 'eq'
¶mglData
: mglData
Column (const char *
eq) const
¶mglDataC
: mglData
Column (const char *
eq) const
¶HMDT
mgl_data_column (HCDT
dat, const char *
eq)
¶Возвращает массив данных заполненный по формуле eq, вычисленной для именованных колонок (или срезов). Например, Column("n*w^2/exp(t)");
. Имена колонок должны быть предварительно заданы функцией idset или при чтении файлов данных. В MGL скриптах обычно используется упрощенная версия dat('eq')
. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat mx [my=1 mz=1]
¶mglData
: mglData
Resize (int
mx, int
my=0
, int
mz=0
, mreal
x1=0
, mreal
x2=1
, mreal
y1=0
, mreal
y2=1
, mreal
z1=0
, mreal
z2=1
) const
¶mglDataC
: mglData
Resize (int
mx, int
my=0
, int
mz=0
, mreal
x1=0
, mreal
x2=1
, mreal
y1=0
, mreal
y2=1
, mreal
z1=0
, mreal
z2=1
) const
¶HMDT
mgl_data_resize (HCDT
dat, int
mx, int
my, int
mz)
¶HMDT
mgl_data_resize_box (HCDT
dat, int
mx, int
my, int
mz, mreal
x1, mreal
x2, mreal
y1, mreal
y2, mreal
z1, mreal
z2)
¶Возвращает массив данных размером mx, my, mz со значениями полученными интерполяцией значений из части [x1,x2] x [y1,y2] x [z1,z2] исходного массива. Величины x,y,z полагаются нормированными в диапазоне [0,1]. Если значение mx, my или mz равно 0, то исходный размер используется. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat idat [norm=on
]
¶RES dat idat jdat [norm=on
]
¶RES dat idat jdat kdat [norm=on
]
¶mglData
: mglData
Evaluate (const mglDataA &
idat, bool
norm=true
) const
¶mglData
: mglData
Evaluate (const mglDataA &
idat, const mglDataA &
jdat, bool
norm=true
) const
¶mglData
: mglData
Evaluate (const mglDataA &
idat, const mglDataA &
jdat, const mglDataA &
kdat, bool
norm=true
) const
¶mglDataC
: mglData
Evaluate (const mglDataA &
idat, bool
norm=true
) const
¶mglDataC
: mglData
Evaluate (const mglDataA &
idat, const mglDataA &
jdat, bool
norm=true
) const
¶mglDataC
: mglData
Evaluate (const mglDataA &
idat, const mglDataA &
jdat, const mglDataA &
kdat, bool
norm=true
) const
¶HMDT
mgl_data_evaluate (HCDT
dat, HCDT
idat, HCDT
jdat, HCDT
kdat, int
norm)
¶Возвращает массив данных, полученный в результате интерполяции исходного массива в точках других массивов (например, res[i,j]=dat[idat[i,j],jdat[i,j]]). Размеры массивов idat, jdat, kdat должны совпадать. Координаты в idat, jdat, kdat полагаются нормированными в диапазон [0,1] (при norm=true
) или в диапазоны [0,nx], [0,ny], [0,nz] соответственно. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat ids ['dir'='y' val=nan
]
¶RES dat id
['dir'='y' val=nan
]
¶mglData
: mglData
Section (const mglDataA &
ids, const char *
dir='y'
, mreal
val=NAN
) const
¶mglData
: mglData
Section (long
id, const char *
dir='y'
, mreal
val=NAN
) const
¶mglDataC
: mglData
Section (const mglDataA &
ids, const char *
dir='y'
, mreal
val=NAN
) const
¶mglDataC
: mglData
Section (long
id, const char *
dir='y'
, mreal
val=NAN
) const
¶HMDT
mgl_data_section (HCDT
dat, HCDT
ids, const char *
dir, mreal
val)
¶HMDT
mgl_data_section_val (HCDT
dat, long
id, const char *
dir, mreal
val)
¶HADT
mgl_datac_section (HCDT
dat, HCDT
ids, const char *
dir, mreal
val)
¶HADT
mgl_datac_section_val (HCDT
dat, long
id, const char *
dir, mreal
val)
¶Возвращает массив данных, являющийся id-ой секцией (диапазоном срезов, разделенных значениями val) исходного массива dat. Для id<0 используется обратный порядок (т.e. -1 даст последнюю секцию). Если указано несколько ids, то выходной массив будет результатом последовательного объединения секций.
RES dat val
'dir' [norm=on
]
¶RES dat val
'dir' idat [norm=on
]
¶mglData
: mglData
Solve (mreal
val, char
dir, bool
norm=true
) const
¶mglData
: mglData
Solve (mreal
val, char
dir, const mglDataA &
idat, bool
norm=true
) const
¶HMDT
mgl_data_solve (HCDT
dat, mreal
val, char
dir, HCDT
idat, int
norm)
¶Возвращает массив индексов (корней) вдоль выбранного направления dir в которых значения массива dat равны val. Выходной массив будет иметь размеры массива dat в направлениях поперечных dir. Если предоставлен массив idat, то его значения используются как стартовые при поиске. Это позволяет найти несколько веток с помощью последовательного вызова функции. Индексы полагаются нормированными в диапазон [0,1] (при norm=true
) или в диапазоны [0,nx], [0,ny], [0,nz] соответственно. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов. См. раздел Solve sample, для примеров кода и графика.
RES 'func' ini ['var'='x']
¶RES 'func' ini
['var'='x']
¶mglData
: mglData
Roots (const char *
func, char
var) const
¶HMDT
mgl_data_roots (const char *
func, HCDT
ini, char
var)
¶mreal
mgl_find_root_txt (const char *
func, mreal
ini, char
var)
¶Возвращает массив корней уравнения ’func’=0 для переменной var с начальными положениями ini. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES 'funcs' 'vars' ini
¶mglData
: mglData
MultiRoots (const char *
funcs, const char *
vars) const
¶mglDataC
: mglDataC
MultiRoots (const char *
funcs, const char *
vars) const
¶HMDT
mgl_find_roots_txt (const char *
func, const char *
vars, HCDT
ini)
¶HADT
mgl_find_roots_txt_c (const char *
func, const char *
vars, HCDT
ini)
¶Возвращает массив корней системы уравнений ’funcs’=0 для переменных vars с начальными значениями ini. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat lvl dj [di=0 minlen=0]
¶mglData
: mglData
Detect (mreal
lvl, mreal
dj, mreal
di=0
, mreal
minlen=0
) const
¶HMDT
mgl_data_detect (HCDT
dat, mreal
lvl, mreal
dj, mreal
di, mreal
minlen)
¶Возвращает массив кривых {x,y}, разделенных NAN значениями, для локальных максимумов массива dat как функцию координаты x. Шумы амплитудой меньше lvl игнорируются. Параметр dj (в диапазоне [0,ny]) задает область "притяжения" точек в y-направлении к кривой. Аналогично, di продолжает кривые в x-направлении через разрывы длиной менее di точек. Кривые с минимальной длинной менее minlen игнорируются.
RES dat num v1 v2 [nsub=0]
¶RES dat wdat num v1 v2 [nsub=0]
¶mglData
: mglData
Hist (int
n, mreal
v1=0
, mreal
v2=1
, int
nsub=0
) const
¶mglData
: mglData
Hist (const mglDataA &
w, int
n, mreal
v1=0
, mreal
v2=1
, int
nsub=0
) const
¶mglDataC
: mglData
Hist (int
n, mreal
v1=0
, mreal
v2=1
, int
nsub=0
) const
¶mglDataC
: mglData
Hist (const mglDataA &
w, int
n, mreal
v1=0
, mreal
v2=1
, int
nsub=0
) const
¶HMDT
mgl_data_hist (HCDT
dat, int
n, mreal
v1, mreal
v2, int
nsub)
¶HMDT
mgl_data_hist_w (HCDT
dat, HCDT
w, int
n, mreal
v1, mreal
v2, int
nsub)
¶Возвращает распределение (гистограмму) из n точек от значений массива в диапазоне [v1, v2]. Массив w задает веса элементов (по умолчанию все веса равны 1). Параметр nsub задает число дополнительных точек интерполяции (для сглаживания получившейся гистограммы). Если nsub<0, то используется линейная интерполяция вместо сплайнов. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов. См. также Распределение данных
RES dat 'how' ['dir'='z']
¶mglData
: mglData
Momentum (char
dir, const char *
how) const
¶mglDataC
: mglData
Momentum (char
dir, const char *
how) const
¶HMDT
mgl_data_momentum (HCDT
dat, char
dir, const char *
how)
¶Возвращает момент (1d массив) данных вдоль направления dir. Строка how определяет тип момента. Момент определяется как res_k = \sum_ij how(x_i,y_j,z_k) a_ij/ \sum_ij a_ij если dir=‘z’ и т.д. Координаты ‘x’, ‘y’, ‘z’ – индексы массива в диапазоне [0,1]. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat 'dir'
¶mglData
: mglData
Sum (const char *
dir) const
¶mglDataC
: mglData
Sum (const char *
dir) const
¶HMDT
mgl_data_sum (HCDT
dat, const char *
dir)
¶Возвращает результат суммирования данных вдоль направления(ий) dir. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat 'dir'
¶mglData
: mglData
Max (const char *
dir) const
¶mglDataC
: mglData
Max (const char *
dir) const
¶HMDT
mgl_data_max_dir (HCDT
dat, const char *
dir)
¶Возвращает максимальное значение данных вдоль направления(ий) dir. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat 'dir'
¶mglData
: mglData
Min (const char *
dir) const
¶mglDataC
: mglData
Min (const char *
dir) const
¶HMDT
mgl_data_min_dir (HCDT
dat, const char *
dir)
¶Возвращает минимальное значение данных вдоль направления(ий) dir. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat
¶mglData
: mglData
MinMax () const
¶HMDT
mgl_data_minmax (HCDT
dat)
¶Возвращает положение локальных минимумов и максимумов. Функция возвращает NULL или пустой массив если минимумов и максимумов нет.
RES val
dat
¶mglData
: mglData
Conts (mreal
val) const
¶HMDT
mgl_data_conts (mreal
val, HCDT
dat)
¶Возвращает координаты линий уровня для dat[i,j]=val. Кривые разделяются NAN. Функция возвращает NULL или пустой массив если линий уровня нет.
RES adat bdat
¶mglData
: mglData
Combine (const mglDataA &
a) const
¶mglDataC
: mglData
Combine (const mglDataA &
a) const
¶HMDT
mgl_data_combine (HCDT
dat, HCDT
a)
¶Возвращает прямое произведение массивов (наподобие, res[i,j] = adat[i]*bdat[j] и т.д.). Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES dat
¶mglData
: mglData
Trace () const
¶mglDataC
: mglData
Trace () const
¶HMDT
mgl_data_trace (HCDT
dat)
¶Возвращает массив диагональных элементов a[i,i] (для 2D данных) или a[i,i,i] (для 3D данных) где i=0...nx-1. В 1D случае возвращается сам массив данных. Размеры массива данных должен быть ny,nz >= nx или ny,nz = 1. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
RES adat bdat 'dir'
¶mglData
: mglData
Correl (const mglDataA &
b, const char *
dir) const
¶mglData
: mglData
AutoCorrel (const char *
dir) const
¶mglDataC
: mglDataC
Correl (const mglDataA &
b, const char *
dir) const
¶mglDataC
: mglDataC
AutoCorrel (const char *
dir) const
¶HMDT
mgl_data_correl (HCDT
a, HCDT
b, const char *
dir)
¶HADT
mgl_datac_correl (HCDT
a, HCDT
b, const char *
dir)
¶Возвращает корреляцию массивов a (или this в C++) и b вдоль направлений dir. При вычислении используется преобразование Фурье. Поэтому может потребоваться вызов функций swap и/или norm перед построением. Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов.
mglDataC
: mglData
Real () const
¶HMDT
mgl_datac_real (HCDT
dat)
¶Возвращает массив действительных частей массива данных.
mglDataC
: mglData
Imag () const
¶HMDT
mgl_datac_imag (HCDT
dat)
¶Возвращает массив мнимых частей массива данных.
mglDataC
: mglData
Abs () const
¶HMDT
mgl_datac_abs (HCDT
dat)
¶Возвращает массив абсолютных значений массива данных.
mglDataC
: mglData
Arg () const
¶HMDT
mgl_datac_arg (HCDT
dat)
¶Возвращает массив аргументов массива данных.
RES dat 'dir'
¶mglData
: mglData
Pulse (const char *
dir) const
¶HMDT
mgl_data_pulse (HCDT
dat, const char *
dir)
¶Находит параметры импульса вдоль направления dir: максимальное значение (в колонке 0), его положение (в колонке 1), ширина по параболлической аппроксимации (в колонке 3) и по полувысоте (в колонке 2), энергию около максимума (в колонке 4). NAN значения используются для ширин если максимум расположен вблизи границ массива. Отмечу, что для комплексных массивов есть неопределенность определения параметров. Обычно следует использовать квадрат абсолютного значения амплитуды (т.е. |dat[i]|^2). Поэтому MathGL не включает эту функцию в mglDataC
, хотя формально C функция будет работать и для них, но будет использовать абсолютное значение амплитуды (т.е. |dat[i]|). Функция возвращает NULL или пустой массив если данные не могут быть созданы при данных значениях аргументов. См. также max, min, momentum, sum. См. раздел Pulse properties, для примеров кода и графика.
RES dat 'dir' val
¶mglData
: mglData
First (const char *
dir, mreal
val) const
¶mglDataC
: mglData
First (const char *
dir, mreal
val) const
¶HMDT
mgl_data_first_dir (HCDT
dat, const char *
dir, mreal
val)
¶Возвращает массив положений ячеек со значениями впервые превысившими val. Для комплексных данных используется абсолютное значение. См. также last.
RES dat 'dir' val
¶mglData
: mglData
Last (const char *
dir, mreal
val) const
¶mglDataC
: mglData
Last (const char *
dir, mreal
val) const
¶HMDT
mgl_data_last_dir (HCDT
dat, const char *
dir, mreal
val)
¶Возвращает массив положений ячеек со значениями последний раз превысившими val. Для комплексных данных используется абсолютное значение. См. также first.
HMDT
mgl_formula_calc (const char *
str, long
n, ...)
¶HADT
mgl_formula_calc_c (const char *
str, long
n, ...)
¶Вычисляет формулу str для заданного списка из n массивов данных типа HCDT
. Имена переменных соответствуют именам массивов. Возвращенный массив должен быть удален пользователем по окончании использования. См. также fill.
These functions change the data in some direction like differentiations, integrations and so on. The direction in which the change will applied is specified by the string parameter, which may contain ‘x’, ‘y’ or ‘z’ characters for 1-st, 2-nd and 3-d dimension correspondingly.
dat 'dir'
¶mglData
: void
CumSum (const char *
dir)
¶mglDataC
: void
CumSum (const char *
dir)
¶void
mgl_data_cumsum (HMDT
dat, const char *
dir)
¶void
mgl_datac_cumsum (HADT
dat, const char *
dir)
¶Суммирует с накоплением в выбранном направлении(ях).
dat 'dir'
¶mglData
: void
Integral (const char *
dir)
¶mglDataC
: void
Integral (const char *
dir)
¶void
mgl_data_integral (HMDT
dat, const char *
dir)
¶void
mgl_datac_integral (HADT
dat, const char *
dir)
¶Выполняет интегрирование (методом трапеций) в выбранном направлении(ях).
dat 'dir'
¶mglData
: void
Diff (const char *
dir)
¶mglDataC
: void
Diff (const char *
dir)
¶void
mgl_data_diff (HMDT
dat, const char *
dir)
¶void
mgl_datac_diff (HADT
dat, const char *
dir)
¶Выполняет дифференцирование в выбранном направлении(ях).
dat xdat ydat [zdat]
¶mglData
: void
Diff (const mglDataA &
x)
¶mglData
: void
Diff (const mglDataA &
x, const mglDataA &
y)
¶mglData
: void
Diff (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z)
¶mglDataC
: void
Diff (const mglDataA &
x)
¶mglDataC
: void
Diff (const mglDataA &
x, const mglDataA &
y)
¶mglDataC
: void
Diff (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z)
¶void
mgl_data_diff_par (HMDT
dat, HCDT
x, HCDT
y, HCDT
z)
¶void
mgl_datac_diff_par (HADT
dat, HCDT
x, HCDT
y, HCDT
z)
¶Выполняет дифференцирование данных, параметрически зависящих от координат, в направлении x с y, z=constant. Параметр z может быть опущен, что соответствует 2D случаю. Используются следующие формулы (2D случай): da/dx = (a_j*y_i-a_i*y_j)/(x_j*y_i-x_i*y_j), где a_i=da/di, a_j=da/dj обозначает дифференцирование вдоль 1-ой и 2-ой размерности. Похожие формулы используются и в 3D случае. Порядок аргументов можно менять – например, если данные a(i,j) зависят от координат {x(i,j), y(i,j)}, то обычная производная по ‘x’ будет равна Diff(x,y);
, а обычная производная по ‘y’ будет равна Diff(y,x);
.
dat 'dir'
¶mglData
: void
Diff2 (const char *
dir)
¶mglDataC
: void
Diff2 (const char *
dir)
¶void
mgl_data_diff2 (HMDT
dat, const char *
dir)
¶void
mgl_datac_diff2 (HADT
dat, const char *
dir)
¶Выполняет двойное дифференцирование (как в операторе Лапласа) в выбранном направлении(ях).
dat 'dir'
¶mglData
: void
SinFFT (const char *
dir)
¶void
mgl_data_sinfft (HMDT
dat, const char *
dir)
¶Выполняет синус преобразование в выбранном направлении(ях). Синус преобразование есть \sum a_j \sin(k j) (см. http://en.wikipedia.org/wiki/Discrete_sine_transform#DST-I).
dat 'dir'
¶mglData
: void
CosFFT (const char *
dir)
¶void
mgl_data_cosfft (HMDT
dat, const char *
dir)
¶Выполняет косинус преобразование в выбранном направлении(ях). Синус преобразование есть \sum a_j \cos(k j) (см. http://en.wikipedia.org/wiki/Discrete_cosine_transform#DCT-I).
mglDataC
: void
FFT (const char *
dir)
¶void
mgl_datac_fft (HADT
dat, const char *
dir)
¶Выполняет фурье преобразование в выбранном направлении(ях). Если строка dir содержит ‘i’, то используется обратное преобразование фурье. Фурье преобразование есть \sum a_j \exp(i k j) (см. http://en.wikipedia.org/wiki/Discrete_Fourier_transform).
dat 'dir'
¶mglData
: void
Hankel (const char *
dir)
¶mglDataC
: void
Hankel (const char *
dir)
¶void
mgl_data_hankel (HMDT
dat, const char *
dir)
¶void
mgl_datac_hankel (HADT
dat, const char *
dir)
¶Выполняет преобразование Ханкеля в выбранном направлении(ях). Преобразование Ханкеля есть \sum a_j J_0(k j) (см. http://en.wikipedia.org/wiki/Hankel_transform).
dat 'dir' k
¶mglData
: void
Wavelet (const char *
dir, int
k)
¶void
mgl_data_wavelet (HMDT
dat, const char *
dir, int
k)
¶Выполняет преобразование wavelet в выбранном направлении(ях). Параметр dir задает тип: ‘d’ для daubechies, ‘D’ для центрированного daubechies, ‘h’ для haar, ‘H’ для центрированного haar, ‘b’ для bspline, ‘B’ для центрированного bspline. Если указан символ ‘i’, то выполняется обратное преобразование. Параметр k задает размер преобразования.
dat 'dir'
¶mglData
: void
Swap (const char *
dir)
¶mglDataC
: void
Swap (const char *
dir)
¶void
mgl_data_swap (HMDT
dat, const char *
dir)
¶void
mgl_datac_swap (HADT
dat, const char *
dir)
¶Меняет местами левую и правую части данных в выбранном направлении(ях). Полезно для отображения результата FFT.
dat 'dir' num
¶mglData
: void
Roll (char
dir, num
)
¶mglDataC
: void
Roll (char
dir, num
)
¶void
mgl_data_roll (HMDT
dat, char
dir, num
)
¶void
mgl_datac_roll (HADT
dat, char
dir, num
)
¶Сдвигает данные на num ячеек в выбранном направлении(ях). Соответствует замене индекса на i->(i+num)%nx при dir='x'
.
dat 'dir'
¶mglData
: void
Mirror (const char *
dir)
¶mglDataC
: void
Mirror (const char *
dir)
¶void
mgl_data_mirror (HMDT
dat, const char *
dir)
¶void
mgl_datac_mirror (HADT
dat, const char *
dir)
¶Отражает данные в выбранном направлении(ях). Соответствует замене индекса на i->n-i. Отмечу, что похожего эффекта на графике можно достичь используя опции (see Опции команд), например, surf dat; xrange 1 -1
.
dat ['dir'='xyz' da=2*pi
]
¶mglData
: void
Sew (const char *
dir, mreal
da=2*M_PI
)
¶void
mgl_data_sew (HMDT
dat, const char *
dir, mreal
da)
¶Удаляет скачки данных (например, скачки фазы после обратных тригонометрических функций) с периодом da в выбранном направлении(ях).
data ['dir'='xyz']
¶mglData
: void
Smooth (const char *
dir="xyz"
, mreal
delta=0
)
¶mglDataC
: void
Smooth (const char *
dir="xyz"
, mreal
delta=0
)
¶void
mgl_data_smooth (HMDT
dat, const char *
dir, mreal
delta)
¶void
mgl_datac_smooth (HADT
dat, const char *
dir, mreal
delta)
¶Сглаживает данные в выбранном направлении(ях) dir. Строка dirs задает направления вдоль которых будет производиться сглаживание. Строка dir может содержать:
По умолчанию используется квадратичное усреднение по 5 точкам.
dat ['dir'='x']
¶mglData
: void
Envelop (char
dir='x'
)
¶void
mgl_data_envelop (HMDT
dat, char
dir)
¶Находит огибающую данных в выбранном направлении dir.
dat 'how' q
¶mglDataC
: void
Diffraction (const char *
how, mreal
q)
¶void
mgl_datac_diffr (HADT
dat, const char *
how, mreal
q)
¶Вычисляет один шаг диффракции в конечно-разностной схеме с параметром q=\delta t/\delta x^2 используя метод третьего порядка точности. Параметр how может содержать:
dat v1 v2 [sym=off dim=0]
¶mglData
: void
Norm (mreal
v1=0
, mreal
v2=1
, bool
sym=false
, long
dim=0
)
¶void
mgl_data_norm (HMDT
dat, mreal
v1, mreal
v2, int
sym, long
dim)
¶Нормирует данные в интервал [v1,v2]. Если sym=true
, то используется симметричный интервал [-max(|v1|,|v2|), max(|v1|,|v2|)]. Изменения применяются только к срезам >=dim.
dat v1 v2
['dir'='z' keep=on sym=off
]
¶mglData
: void
NormSl (mreal
v1=0
, mreal
v2=1
, char
dir='z'
, bool
keep=true
, bool
sym=false
)
¶void
mgl_data_norm_slice (HMDT
dat, mreal
v1, mreal
v2, char
dir, int
keep, int
sym)
¶Нормирует данные срез-за-срезом в выбранном направлении dir в интервал [v1,v2]. Если sym=true
, то используется симметричный интервал [-max(|v1|,|v2|), max(|v1|,|v2|)]. Если keep=true
, то максимальное значение k-го среза ограничено величиной
\sqrt{\sum a_ij(k)/\sum a_ij(0)}.
dat 'dir' i [j=0]
¶mglData
: void
Keep (const char *
dir, long
i, long
j=0)
¶mglDataC
: void
Keep (const char *
dir, long
i, long
j=0)
¶void
mgl_data_keep (HMDT
dat, const char *
dir, long
i, long
j)
¶void
mgl_datac_keep (HADT
dat, const char *
dir, long
i, long
j=0)
¶Ограничивает изменение фазы/знака или амплитуды (если dir содержит ‘a’) данных вдоль направления dir фиксируя значение в точке {i,j} начального среза. Функция полезна для удаления общего набега фазы в комплексных данных. См. раздел Sample ‘keep’, для примеров кода и графика.
dat val
¶mglData
: void
Limit (mreal
val)
¶mglDataC
: void
Limit (mreal
val)
¶void
mgl_data_limit (HMDT
dat, mreal
val)
¶void
mgl_datac_limit (HADT
dat, mreal
val)
¶Ограничивает амплитуду данных диапазоном [-val,val]. При этом сохраняется исходный знак (фаза для комплексных чисел). Эквивалентно операции a[i] *= abs(a[i])<val?1.:val/abs(a[i]);
.
dat v1 v2 [sep=on]
¶mglData
: void
Coil (mreal
v1, mreal
v2, bool
sep=true
)
¶void
mgl_data_coil (HMDT
dat, mreal
v1, mreal
v2, int
sep)
¶Проецирует периодические данные на диапазон [v1,v2] (аналогично функции mod()
). Разделяет ветки по значениям равным NAN
если sep=true
.
dat [val=1 step=1]
¶mglData
: void
Dilate (mreal
val=1
, long
step=1
)
¶void
mgl_data_dilate (HMDT
dat, mreal
val, long
step)
¶Возвращает "расширенный" на step ячеек массив из 0 и 1 для данных больших порогового значения val.
dat [val=1 step=1]
¶mglData
: void
Erode (mreal
val=1
, long
step=1
)
¶void
mgl_data_erode (HMDT
dat, mreal
val, long
step)
¶Возвращает "суженный" на step ячеек массив из 0 и 1 для данных больших порогового значения val.
Скрипты MGL могут использовать интерполяцию кубическими сплайнами с помощью команд evaluate или refill. Также можно использовать resize для массива с новыми размерами.
Однако, есть специальные и более быстрые функции при использовании других языков (C/C++/Fortran/Python/...).
mglData
: mreal
Spline (mreal
x, mreal
y=0
, mreal
z=0
) const
¶mglDataC
: dual
Spline (mreal
x, mreal
y=0
, mreal
z=0
) const
¶mreal
mgl_data_spline (HCDT
dat, mreal
x, mreal
y, mreal
z)
¶dual
mgl_datac_spline (HCDT
dat, mreal
x, mreal
y, mreal
z)
¶Интерполирует данные кубическим сплайном в точке x в [0...nx-1], y в [0...ny-1], z в [0...nz-1].
mglData
: mreal
Spline1 (mreal
x, mreal
y=0
, mreal
z=0
) const
¶mglDataC
: dual
Spline1 (mreal
x, mreal
y=0
, mreal
z=0
) const
¶Интерполирует данные кубическим сплайном в точке x, y, z, где координаты полагаются в интервале [0, 1].
mglData
: mreal
Spline (mglPoint
&dif, mreal
x, mreal
y=0
, mreal
z=0
) const
¶mreal
mgl_data_spline_ext (HCDT
dat, mreal
x, mreal
y, mreal
z, mreal *
dx, mreal *
dy, mreal *
dz)
¶dual
mgl_datac_spline_ext (HCDT
dat, mreal
x, mreal
y, mreal
z, dual *
dx, dual *
dy, dual *
dz)
¶Интерполирует данные кубическим сплайном в точке x в [0...nx-1], y в [0...ny-1], z в [0...nz-1]. Значения производных в точке записываются в dif.
mglData
: mreal
Spline1 (mglPoint
&dif, mreal
x, mreal
y=0
, mreal
z=0
) const
¶Интерполирует данные кубическим сплайном в точке x, y, z, где координаты полагаются в интервале [0, 1]. Значения производных в точке записываются в dif.
mglData
: mreal
Linear (mreal
x, mreal
y=0
, mreal
z=0
) const
¶mglDataC
: dual
Linear (mreal
x, mreal
y=0
, mreal
z=0
) const
¶mreal
mgl_data_linear (HCDT
dat, mreal
x, mreal
y, mreal
z)
¶dual
mgl_datac_linear (HCDT
dat, mreal
x, mreal
y, mreal
z)
¶Интерполирует данные линейной функцией в точке x в [0...nx-1], y в [0...ny-1], z в [0...nz-1].
mglData
: mreal
Linear1 (mreal
x, mreal
y=0
, mreal
z=0
) const
¶mglDataC
: dual
Linear1 (mreal
x, mreal
y=0
, mreal
z=0
) const
¶Интерполирует данные линейной функцией в точке x, y, z, где координаты полагаются в интервале [0, 1].
mglData
: mreal
Linear (mglPoint
&dif, mreal
x, mreal
y=0
, mreal
z=0
) const
¶mglDataC
: dual
Linear (mglPoint
&dif, mreal
x, mreal
y=0
, mreal
z=0
) const
¶mreal
mgl_data_linear_ext (HCDT
dat, mreal
x, mreal
y, mreal
z, mreal *
dx, mreal *
dy, mreal *
dz)
¶dual
mgl_datac_linear_ext (HCDT
dat, mreal
x, mreal
y, mreal
z, dual *
dx, dual *
dy, dual *
dz)
¶Интерполирует данные линейной функцией в точке x, y, z, где координаты полагаются в интервале [0, 1]. Значения производных в точке записываются в dif.
mglData
: mreal
Linear1 (mglPoint
&dif, mreal
x, mreal
y=0
, mreal
z=0
) const
¶mglDataC
: dual
Linear1 (mglPoint
&dif, mreal
x, mreal
y=0
, mreal
z=0
) const
¶Интерполирует данные линейной функцией в точке x, y, z, где координаты полагаются в интервале [0, 1]. Значения производных в точке записываются в dif.
В MathGL есть ряд функций для получения свойств массива данных. В MGL скриптах большинство из них реализовано в виде "суффиксов". Суффиксы дают числовое значение некоторой характеристики массива данных. Например, его размер, минимальное и максимальное значение, сумму элементов и т.д. Суффиксы начинаются с точки ‘.’ сразу после массива (без пробелов). Например, a.nx
даст размер массива a вдоль x, b(1).max
даст максимальное значение второй колонки массива b, (c(:,0)^2).sum
даст сумму квадратов в первой строке массива c и т.д.
dat
¶mglDataA
: const char *
PrintInfo () const
¶mglDataA
: void
PrintInfo (FILE *
fp) const
¶const char *
mgl_data_info (HCDT
dat)
¶
mgl_data_info (long
dat, char *
out, int
len)
¶Возвращает строку с информацией о данных (размеры, моменты и пр.) или пишет её в файл. В MGL скрипте печатает её как сообщение.
'txt'
¶Печатает строку txt как сообщение.
val
¶Печатает значение числа val как сообщение.
dat
¶'txt'
¶val
¶Аналогично info, но сразу выводит в stdout.
dat
¶Печатает все значения массива dat как сообщение.
val max
¶mglGraph
: void
Progress (int
val, int
max)
¶void
mgl_progress (int
val, int
max)
¶Отображает прогресс чего-либо как заполненную полоску с относительной длиной val/max. На данный момент работает только в консоли и основанных на FLTK программах, включая mgllab
и mglview
.
(dat)
.nx ¶(dat)
.ny ¶(dat)
.nz ¶mglDataA
: long
GetNx ()
¶mglDataA
: long
GetNy ()
¶mglDataA
: long
GetNz ()
¶long
mgl_data_get_nx (HCDT
dat)
¶long
mgl_data_get_ny (HCDT
dat)
¶long
mgl_data_get_nz (HCDT
dat)
¶Возвращает размер данных в направлении x, y и z соответственно.
(dat)
.max ¶mglDataA
: mreal
Maximal () const
¶mreal
mgl_data_max (HCDT
dat)
¶Возвращает максимальное значение массива данных.
(dat)
.min ¶mglDataA
: mreal
Minimal () const
¶mreal
mgl_data_min (HMDT
dat) const
¶Возвращает минимальное значение массива данных.
mglDataA
: mreal
Minimal (int
&i, int
&j, int
&k) const
¶mreal
mgl_data_min_int (HCDT
dat, int
*i, int
*j, int
*k)
¶Возвращает максимальное значение массива данных и сохраняет его положение в переменные i, j, k.
mglDataA
: mreal
Maximal (int
&i, int
&j, int
&k) const
¶mreal
mgl_data_max_int (HCDT
dat, int
*i, int
*j, int
*k)
¶Возвращает минимальное значение массива данных и сохраняет его положение в переменные i, j, k.
mglDataA
: mreal
Minimal (mreal
&x, mreal
&y, mreal
&z) const
¶mreal
mgl_data_min_real (HCDT
dat, mreal
*x, mreal
*y, mreal
*z)
¶Возвращает максимальное значение массива данных и его приближенное (интерполированное) положение в переменные x, y, z.
(dat)
.mx ¶(dat)
.my ¶(dat)
.mz ¶mglDataA
: mreal
Maximal (mreal
&x, mreal
&y, mreal
&z) const
¶mreal
mgl_data_max_real (HCDT
dat, mreal
*x, mreal
*y, mreal
*z)
¶Возвращает минимальное значение массива данных и его приближенное (интерполированное) положение в переменные x, y, z.
(dat)
.mxf ¶(dat)
.myf ¶(dat)
.mzf ¶(dat)
.mxl ¶(dat)
.myl ¶(dat)
.mzl ¶mglDataA
: long
Maximal (char
dir, long
from) const
¶mglDataA
: long
Maximal (char
dir, long
from, long
&p1, long
&p2) const
¶mreal
mgl_data_max_firstl (HCDT
dat, char
dir, long
from, long
*p1, long
*p2)
¶Возвращает положение первого (последнего при from<0) максимума в направлении dir, начиная с позиции from. Положение остальных координат для максимума сохраняется в p1, p2.
(dat)
.sum ¶(dat)
.ax ¶(dat)
.ay ¶(dat)
.az ¶(dat)
.aa ¶(dat)
.wx ¶(dat)
.wy ¶(dat)
.wz ¶(dat)
.wa ¶(dat)
.sx ¶(dat)
.sy ¶(dat)
.sz ¶(dat)
.sa ¶(dat)
.kx ¶(dat)
.ky ¶(dat)
.kz ¶(dat)
.ka ¶mglDataA
: mreal
Momentum (char
dir, mreal
&a, mreal
&w) const
¶mglDataA
: mreal
Momentum (char
dir, mreal
&m, mreal
&w, mreal
&s, mreal
&k) const
¶mreal
mgl_data_momentum_val (HCDT
dat, char
dir, mreal
*a, mreal
*w, mreal
*s, mreal
*k)
¶Возвращает нулевой момент (энергию, I=\sum a_i) и записывает первый (среднее, m = \sum \xi_i a_i/I), второй (ширину, w^2 = \sum (\xi_i-m)^2 a_i/I), третий (асимметрия, s = \sum (\xi_i-m)^3 a_i/ I w^3) и четвёртый моменты (эксцесс, k = \sum (\xi_i-m)^4 a_i / 3 I w^4)). Здесь \xi – соответствующая координата если dir равно ‘'x'’, ‘'y'’, ‘'z'’. В противном случае среднее, ширина, асимметрия, эксцесс равны m = \sum a_i/N, w^2 = \sum (a_i-m)^2/N и т.д.
(dat)
.fst ¶mglDataA
: mreal
Find (const char *
cond, int
&i, int
&j, int
&k) const
¶mreal
mgl_data_first (HCDT
dat, const char *
cond, int
*i, int
*j, int
*k)
¶Находит положение (после заданного в i, j, k) первого не нулевого значения формулы cond. Функция возвращает найденное значение и записывает его положение в i, j, k.
(dat)
.lst ¶mglDataA
: mreal
Last (const char *
cond, int
&i, int
&j, int
&k) const
¶mreal
mgl_data_last (HCDT
dat, const char *
cond, int
*i, int
*j, int
*k)
¶Находит положение (перед заданного в i, j, k) последнего не нулевого значения формулы cond. Функция возвращает найденное значение и записывает его положение в i, j, k.
mglDataA
: int
Find (const char *
cond, char
dir, int
i=0
, int
j=0
, int
k=0
) const
¶mreal
mgl_data_find (HCDT
dat, const char *
cond, int
i, int
j, int
k)
¶Возвращает положение первого в направлении dir не нулевого значения формулы cond. Поиск начинается с точки {i,j,k}.
mglDataA
: bool
FindAny (const char *
cond) const
¶mreal
mgl_data_find_any (HCDT
dat, const char *
cond)
¶Определяет есть ли хоть одно значение массива, удовлетворяющее условию cond.
(dat)
.a ¶Возвращает первое число массива (для .a
это dat->a[0]
).
DAT dat2 ['eq'='']
¶mglData
: void
operator= (const mglDataA &
d)
¶Копирует данные из другого экземпляра.
dat val
¶mreal
: void
operator= (mreal
val)
¶Устанавливает все значения массива равными val.
dat dat2
¶dat val
¶mglData
: void
operator*= (const mglDataA &
d)
¶mglData
: void
operator*= (mreal
d)
¶void
mgl_data_mul_dat (HMDT
dat, HCDT
d)
¶void
mgl_data_mul_num (HMDT
dat, mreal
d)
¶Поэлементно умножает на массив d или на число val.
dat dat2
¶dat val
¶mglData
: void
operator/= (const mglDataA &
d)
¶mglData
: void
operator/= (mreal
d)
¶void
mgl_data_div_dat (HMDT
dat, HCDT
d)
¶void
mgl_data_div_num (HMDT
dat, mreal
d)
¶Поэлементно делит на массив d или на число val.
dat dat2
¶dat val
¶mglData
: void
operator+= (const mglDataA &
d)
¶mglData
: void
operator+= (mreal
d)
¶void
mgl_data_add_dat (HMDT
dat, HCDT
d)
¶void
mgl_data_add_num (HMDT
dat, mreal
d)
¶Поэлементно прибавляет d или число val.
dat dat2
¶dat val
¶mglData
: void
operator-= (const mglDataA &
d)
¶mglData
: void
operator-= (mreal
d)
¶void
mgl_data_sub_dat (HMDT
dat, HCDT
d)
¶void
mgl_data_sub_num (HMDT
dat, mreal
d)
¶Поэлементно вычитает d или число val.
mglData
operator+ (const mglDataA &
a, const mglDataA &
b)
¶mglData
operator+ (mreal
a, const mglDataA &
b)
¶mglData
operator+ (const mglDataA &
a, mreal
b)
¶Возвращает поэлементную сумму данных.
mglData
operator- (const mglDataA &
a, const mglDataA &
b)
¶mglData
operator- (mreal
a, const mglDataA &
b)
¶mglData
operator- (const mglDataA &
a, mreal
b)
¶Возвращает поэлементную разность данных.
mglData
operator* (const mglDataA &
a, const mglDataA &
b)
¶mglData
operator* (mreal
a, const mglDataA &
b)
¶mglData
operator* (const mglDataA &
a, mreal
b)
¶Возвращает поэлементное произведение данных.
mglData
operator/ (const mglDataA &
a, const mglDataA &
b)
¶mglData
operator/ (const mglDataA &
a, mreal
b)
¶Возвращает поэлементное деление данных.
Эти функции не методы класса mglData
, но они дают дополнительные возможности по обработке данных. Поэтому я поместил их в эту главу.
DAT 'type' real imag
¶mglData
mglTransform (const mglDataA &
real, const mglDataA &
imag, const char *
type)
¶HMDT
mgl_transform (HCDT
real, HCDT
imag, const char *
type)
¶Выполняет интегральное преобразование комплексных данных real, imag в выбранном направлении и возвращает модуль результата. Порядок и тип преобразований задается строкой type: первый символ для x-направления, второй для y-направления, третий для z-направления. Возможные символы: ‘f’ – прямое преобразование Фурье, ‘i’ – обратное преобразование Фурье, ‘s’ – синус преобразование, ‘c’ – косинус преобразование, ‘h’ – преобразование Ханкеля, ‘n’ или ‘ ’ – нет преобразования.
DAT 'type' ampl phase
¶mglData
mglTransformA const mglDataA &
ampl, const mglDataA &
phase, const char *
type)
¶HMDT
mgl_transform_a HCDT
ampl, HCDT
phase, const char *
type)
¶Аналогично предыдущему с заданными амплитудой ampl и фазой phase комплексных чисел.
reDat imDat 'dir'
¶complexDat 'dir'
¶void
mglFourier const mglDataA &
re, const mglDataA &
im, const char *
dir)
¶mglDataC
: void
FFT (const char *
dir)
¶void
mgl_data_fourier HCDT
re, HCDT
im, const char *
dir)
¶void
mgl_datac_fft (HADT
dat, const char *
dir)
¶Выполняет Фурье преобразование для комплексных данных re+i*im в направлениях dir. Результат помещается обратно в массивы re и im. Если dir содержит ‘i’, то выполняется обратное преобразование Фурье.
RES real imag dn
['dir'='x']
¶mglData
mglSTFA (const mglDataA &
real, const mglDataA &
imag, int
dn, char
dir='x'
)
¶HMDT
mgl_data_stfa (HCDT
real, HCDT
imag, int
dn, char
dir)
¶Выполняет оконное преобразование Фурье длиной dn для комплексных данных real, imag и возвращает модуль результата. Например, для dir=‘x’ результат будет иметь размер {int(nx/dn), dn, ny} и будет равен res[i,j,k]=|\sum_d^dn exp(I*j*d)*(real[i*dn+d,k]+I*imag[i*dn+d,k])|/dn.
dat xdat ydat
¶mglData
mglTriangulation (const mglDataA &
x, const mglDataA &
y)
¶void
mgl_triangulation_2d (HCDT
x, HCDT
y)
¶Выполняет триангуляцию Делоне для точек на плоскости и возвращает массив, пригодный для triplot и tricont. См. раздел Making regular data, для примеров кода и графика.
RES ADAT BDAT CDAT DDAT 'how'
¶mglData
mglTridMat (const mglDataA &
A, const mglDataA &
B, const mglDataA &
C, const mglDataA &
D, const char *
how)
¶mglDataC
mglTridMatC (const mglDataA &
A, const mglDataA &
B, const mglDataA &
C, const mglDataA &
D, const char *
how)
¶HMDT
mgl_data_tridmat (HCDT
A, HCDT
B, HCDT
C, HCDT
D, const char*
how)
¶HADT
mgl_datac_tridmat (HCDT
A, HCDT
B, HCDT
C, HCDT
D, const char*
how)
¶Возвращает решение трехдиагональной системы уравнений A[i]*x[i-1]+B[i]*x[i]+C[i]*x[i+1]=D[i]. Строка how может содержать:
Размеры массивов A, B, C должны быть одинаковы. Также их размерности должны совпадать со всеми или с "младшими" размерностями массива D. См. раздел PDE solving hints, для примеров кода и графика.
RES 'ham' ini_re ini_im [dz=0.1 k0=100
]
¶mglData
mglPDE (HMGL
gr, const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, mreal
dz=0.1
, mreal
k0=100
, const char *
opt=""
)
¶mglDataC
mglPDEc (HMGL
gr, const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, mreal
dz=0.1
, mreal
k0=100
, const char *
opt=""
)
¶HMDT
mgl_pde_solve (HMGL
gr, const char *
ham, HCDT
ini_re, HCDT
ini_im, mreal
dz, mreal
k0, const char *
opt)
¶HADT
mgl_pde_solve_c (HMGL
gr, const char *
ham, HCDT
ini_re, HCDT
ini_im, mreal
dz, mreal
k0, const char *
opt)
¶Решает уравнение в частных производных du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Координаты в уравнении и в решении полагаются в диапазоне осей координат. Замечу, что внутри этот диапазон увеличивается в 3/2 раза для уменьшения отражения от границ расчетного интервала. Параметр dz задает шаг по эволюционной координате z. В данный момент использован упрощенный алгоритм, когда все “смешанные” члена (типа ‘x*p’->x*d/dx) исключаются. Например, в 2D случае это функции типа ham = f(p,z) + g(x,z,u). При этом допускаются коммутирующие комбинации (типа ‘x*q’->x*d/dy). Переменная ‘u’ используется для обозначения амплитуды поля |u|. Это позволяет решать нелинейные задачи – например, нелинейное уравнение Шредингера ham='p^2+q^2-u^2'
. Также можно указать мнимую часть для поглощения (типа ham = 'p^2+i*x*(x>0)'
). См. также apde, qo2d, qo3d. См. раздел PDE solving hints, для примеров кода и графика.
RES 'ham' ini_re ini_im [dz=0.1 k0=100
]
¶mglData
mglAPDE (HMGL
gr, const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, mreal
dz=0.1
, mreal
k0=100
, const char *
opt=""
)
¶mglDataC
mglAPDEc (HMGL
gr, const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, mreal
dz=0.1
, mreal
k0=100
, const char *
opt=""
)
¶HMDT
mgl_pde_solve_adv (HMGL
gr, const char *
ham, HCDT
ini_re, HCDT
ini_im, mreal
dz, mreal
k0, const char *
opt)
¶HADT
mgl_pde_solve_adv_c (HMGL
gr, const char *
ham, HCDT
ini_re, HCDT
ini_im, mreal
dz, mreal
k0, const char *
opt)
¶Решает уравнение в частных производных du/dz = i*k0*ham(p,q,x,y,z,|u|)[u], где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Координаты в уравнении и в решении полагаются в диапазоне осей координат. Замечу, что внутри этот диапазон увеличивается в 3/2 раза для уменьшения отражения от границ расчетного интервала. Параметр dz задает шаг по эволюционной координате z. Используется достаточно сложный и медленный алгоритм, способный учесть одновременное влияние пространственной дисперсии и неоднородности среды [см. А.А. Балакин, Е.Д. Господчиков, А.Г. Шалашов, Письма ЖЭТФ 104, 701 (2016)]. Переменная ‘u’ используется для обозначения амплитуды поля |u|. Это позволяет решать нелинейные задачи – например, нелинейное уравнение Шредингера ham='p^2+q^2-u^2'
. Также можно указать мнимую часть для поглощения (типа ham = 'p^2+i*x*(x>0)'
). См. также apde. См. раздел PDE solving hints, для примеров кода и графика.
RES 'ham' x0 y0 z0 p0 q0 v0 [dt=0.1 tmax=10]
¶mglData
mglRay (const char *
ham, mglPoint
r0, mglPoint
p0, mreal
dt=0.1
, mreal
tmax=10
)
¶HMDT
mgl_ray_trace (const char *
ham, mreal
x0, mreal
y0, mreal
z0, mreal
px, mreal
py, mreal
pz, mreal
dt, mreal
tmax)
¶Решает систему геометрооптических уравнений dr/dt = d ham/dp, dp/dt = -d ham/dr. Это гамильтоновы уравнения для траектории частицы в 3D случае. Гамильтониан ham может зависеть от координат ‘x’, ‘y’, ‘z’, импульсов ‘p’=px, ‘q’=py, ‘v’=pz и времени ‘t’: ham = H(x,y,z,p,q,v,t). Начальная точка (при t=0
) задается переменными {x0, y0, z0, p0, q0, v0}. Параметры dt и tmax задают шаг и максимальное время интегрирования. Результат – массив {x,y,z,p,q,v,t} с размером {7 * int(tmax/dt+1) }.
RES 'df' 'var' ini [dt=0.1 tmax=10
]
¶mglData
mglODE (const char *
df, const char *
var, const mglDataA &
ini, mreal
dt=0.1
, mreal
tmax=10
)
¶mglDataC
mglODEc (const char *
df, const char *
var, const mglDataA &
ini, mreal
dt=0.1
, mreal
tmax=10
)
¶HMDT
mgl_ode_solve_str (const char *
df, const char *
var, HCDT
ini, mreal
dt, mreal
tmax)
¶HADT
mgl_ode_solve_str_c (const char *
df, const char *
var, HCDT
ini, mreal
dt, mreal
tmax)
¶HMDT
mgl_ode_solve (void (*
df)(const mreal *x, mreal *dx, void *par)
, int
n, const mreal *
ini, mreal
dt, mreal
tmax)
¶HMDT
mgl_ode_solve_ex (void (*
df)(const mreal *x, mreal *dx, void *par)
, int
n, const mreal *
ini, mreal
dt, mreal
tmax, void (*
bord)(mreal *x, const mreal *xprev, void *par)
)
¶Решает систему обыкновенных дифференциальных уравнений dx/dt = df(x). Функции df могут быть заданны строкой с разделенными ’;’ формулами (аргумент var задает символы для переменных x[i]) или указателем на функцию, которая заполняет dx
по заданным значениям x
. Параметры ini, dt, tmax задают начальные значения, шаг и максимальное время интегрирования. Функция обрывает расчет при появлении значений NAN
или INF
. Результат – массив размером {n * Nt}, где Nt <= int(tmax/dt+1).
Если dt*tmax<0, то включается регуляризация, при которой уравнение заменяется на dx/ds = df(x)/max(|df(x)|) для более аккуратного прохождения областей резкого изменения df и более быстрого расчета в области малых df. Здесь s – новое "время". При этом реальное время определяется уравнением dt/ds=max(|df(x)|). Поэтому для вывода реального времени его следует явно добавить в уравнение, например ‘ode res 'y;-sin(x);1' 'xyt' [3,0] 0.3 -100’. Оно также сохранит точность вблизи стационарных точек (т.е. при малых df в периодическом движении).
RES 'df' 'var' 'brd' ini [dt=0.1 tmax=10
]
¶mglData
mglODEs (const char *
df, const char *
var, char
brd, const mglDataA &
ini, mreal
dt=0.1
, mreal
tmax=10
)
¶mglDataC
mglODEcs (const char *
df, const char *
var, char
brd, const mglDataA &
ini, mreal
dt=0.1
, mreal
tmax=10
)
¶HMDT
mgl_ode_solve_set (const char *
df, const char *
var, char
brd, HCDT
ini, mreal
dt, mreal
tmax)
¶HADT
mgl_ode_solve_set_c (const char *
df, const char *
var, char
brd, HCDT
ini, mreal
dt, mreal
tmax)
¶Решает разностную аппроксимацию уравнений в частных производных как систему обыкновенных дифференциальных уравнений dx/dt = df(x,j). Функции df могут быть заданны строкой с разделенными ’;’ формулами, зависящими от индекса j и текущего времени ‘t’. Аргумент var задает символы для переменных x[i]. Параметр brd задает тип граничных условий по j: ‘0’ или ‘z’ – нулевые, ‘1’ или ‘c’ – постоянные, ‘2’ или ‘l’ – линейные (ноль лапласиана), ‘3’ или ‘s’ – квадратичные, ‘4’ или ‘e’ – экспоненциальные, ‘5’ или ‘g’ – гауссовы. Последние два типа условий применимы только в случае комплексных переменных. Параметры ini, dt, tmax задают начальные значения, шаг и максимальное время интегрирования. Функция обрывает расчет при появлении значений NAN
или INF
. Результат – массив размером {n * Nt}, где Nt <= int(tmax/dt+1). Например, разностная аппроксимация уравнения диффузии с нулевыми граничными условиями находится вызовом: ‘ode res 'u(j+1)-2*u(j)+u(j-1)' 'u' '0' u0’, где ‘u0’ – массив начальных значений.
Если dt*tmax<0, то включается регуляризация, при которой уравнение заменяется на dx/ds = df(x)/max(|df(x)|) для более аккуратного прохождения областей резкого изменения df и более быстрого расчета в области малых df. Здесь s – новое "время". При этом реальное время определяется уравнением dt/ds=max(|df(x)|). Поэтому для вывода реального времени его следует явно добавить в уравнение, например ‘ode res 'y;-sin(x);1' 'xyt' [3,0] 0.3 -100’. Оно также сохранит точность вблизи стационарных точек (т.е. при малых df в периодическом движении).
RES 'ham' ini_re ini_im ray [r=1 k0=100
xx yy]
¶mglData
mglQO2d (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mreal
r=1
, mreal
k0=100
, mglData *
xx=0
, mglData *
yy=0
)
¶mglData
mglQO2d (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mglData &
xx, mglData &
yy, mreal
r=1
, mreal
k0=100
)
¶mglDataC
mglQO2dc (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mreal
r=1
, mreal
k0=100
)
¶mglDataC
mglQO2dc (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mglData &
xx, mglData &
yy, mreal
r=1
, mreal
k0=100
)
¶HMDT
mgl_qo2d_solve (const char *
ham, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy)
¶HADT
mgl_qo2d_solve_c (const char *
ham, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy)
¶HMDT
mgl_qo2d_func (dual (*
ham)(mreal u, mreal x, mreal y, mreal px, mreal py, void *par)
, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy)
¶HADT
mgl_qo2d_func_c (dual (*
ham)(mreal u, mreal x, mreal y, mreal px, mreal py, void *par)
, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy)
¶Решает уравнение в частных производных du/dt = i*k0*ham(p,q,x,y,|u|)[u] в сопровождающей системе координат, где p=-i/k0*d/dx, q=-i/k0*d/dy – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Параметр ray задает опорный луч для сопровождающей системы координат. Можно использовать луч найденный с помощью ray. Опорный луч должен быть достаточно гладкий, чтобы система координат была однозначной и для исключения ошибок интегрирования. Если массивы xx и yy указаны, то в них записываются декартовы координаты для каждой точки найденного решения. См. также pde, qo3d. См. раздел PDE solving hints, для примеров кода и графика.
RES 'ham' ini_re ini_im ray [r=1 k0=100
xx yy zz]
¶mglData
mglQO3d (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mreal
r=1
, mreal
k0=100
)
¶mglData
mglQO3d (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mglData &
xx, mglData &
yy, mglData &
zz, mreal
r=1
, mreal
k0=100
)
¶mglDataC
mglQO3dc (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mreal
r=1
, mreal
k0=100
)
¶mglDataC
mglQO3dc (const char *
ham, const mglDataA &
ini_re, const mglDataA &
ini_im, const mglDataA &
ray, mglData &
xx, mglData &
yy, mglData &
zz, mreal
r=1
, mreal
k0=100
)
¶HMDT
mgl_qo3d_solve (const char *
ham, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy, HMDT
zz)
¶HADT
mgl_qo3d_solve_c (const char *
ham, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy, HMDT
zz)
¶HMDT
mgl_qo3d_func (dual (*
ham)(mreal u, mreal x, mreal y, mreal z, mreal px, mreal py, mreal pz, void *par)
, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy, HMDT
zz)
¶HADT
mgl_qo3d_func_c (dual (*
ham)(mreal u, mreal x, mreal y, mreal z, mreal px, mreal py, mreal pz, void *par)
, HCDT
ini_re, HCDT
ini_im, HCDT
ray, mreal
r, mreal
k0, HMDT
xx, HMDT
yy, HMDT
zz)
¶Решает уравнение в частных производных du/dt = i*k0*ham(p,q,v,x,y,z,|u|)[u] в сопровождающей системе координат, где p=-i/k0*d/dx, q=-i/k0*d/dy, v=-i/k0*d/dz – псевдо-дифференциальные операторы. Параметры ini_re, ini_im задают начальное распределение поля. Параметр ray задает опорный луч для сопровождающей системы координат. Можно использовать луч найденный с помощью ray. Опорный луч должен быть достаточно гладкий, чтобы система координат была однозначной и для исключения ошибок интегрирования. Если массивы xx, yy и zz указаны, то в них записываются декартовы координаты для каждой точки найденного решения. См. также pde, qo2d.
RES xdat ydat [zdat]
¶mglData
mglJacobian (const mglDataA &
x, const mglDataA &
y)
¶mglData
mglJacobian (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z)
¶HMDT
mgl_jacobian_2d (HCDT
x, HCDT
y)
¶HMDT
mgl_jacobian_3d (HCDT
x, HCDT
y, HCDT
z)
¶Вычисляет якобиан преобразования {i,j,k} в {x,y,z}, где координаты {i,j,k} полагаются нормированными в интервал [0,1]. Якобиан находится по формуле det||dr_\alpha/d\xi_\beta||, где r={x,y,z} и \xi={i,j,k}. Все размерности всех массивов должны быть одинаковы. Данные должны быть трехмерными если указаны все 3 массива {x,y,z} или двумерными если только 2 массива {x,y}.
RES xdat ydat [zdat]
¶mglData
mglTriangulation (const mglDataA &
x, const mglDataA &
y)
¶mglData
mglTriangulation (const mglDataA &
x, const mglDataA &
y, const mglDataA &
z)
¶HMDT
mgl_triangulation_2d (HCDT
x, HCDT
y)
¶HMDT
mgl_triangulation_3d (HCDT
x, HCDT
y, HCDT
z)
¶Выполняет триангуляцию для произвольно расположенных точек с координатами {x,y,z} (т.е. находит треугольники, соединяющие точки). Первая размерность всех массивов должна быть одинакова x.nx=y.nx=z.nx
. Получившийся массив можно использовать в triplot или tricont для визуализации реконструированной поверхности. См. раздел Making regular data, для примеров кода и графика.
mglData
mglGSplineInit (const mglDataA &
x, const mglDataA &
y)
¶mglDataC
mglGSplineCInit (const mglDataA &
x, const mglDataA &
y)
¶HMDT
mgl_gspline_init (HCDT
x, HCDT
y)
¶HADT
mgl_gsplinec_init (HCDT
x, HCDT
y)
¶Подготавливает коэффициенты для глобального кубического сплайна.
mreal
mglGSpline (const mglDataA &
coef, mreal
dx, mreal *
d1=0
, mreal *
d2=0
)
¶dual
mglGSplineC (const mglDataA &
coef, mreal
dx, dual *
d1=0
, dual *
d2=0
)
¶mreal
mgl_gspline (HCDT
coef, mreal
dx, mreal *
d1, mreal *
d2)
¶dual
mgl_gsplinec (HCDT
coef, mreal
dx, dual *
d1, dual *
d2)
¶Вычисляет глобальный кубический сплайн (а также 1ую и 2ую производные d1, d2 если они не NULL
), используя коэффициенты coef в точке dx+x0 (здесь x0 – 1ый элемент массива x в функции mglGSpline*Init()
).
RES dat num
[skip=20
]
¶mglData
mglIFS2d (const mglDataA &
dat, long
num, long
skip=20
)
¶HMDT
mgl_data_ifs_2d (HCDT
dat, long
num, long
skip)
¶Находит num точек {x[i]=res[0,i], y[i]=res[1,i]} фрактала с использованием итерационной системы функций (IFS). Матрица dat используется для генерации в соответствии с формулами
x[i+1] = dat[0,i]*x[i] + dat[1,i]*y[i] + dat[4,i]; y[i+1] = dat[2,i]*x[i] + dat[3,i]*y[i] + dat[5,i];
Значение dat[6,i]
– весовой коэффициент для i-ой строки матрицы dat. Первые skip итераций будут опущены. Массив dat должен иметь размер по x больше или равный 7. См. также ifs3d, flame2d. См. раздел Sample ‘ifs2d’, для примеров кода и графика.
RES dat num
[skip=20
]
¶mglData
mglIFS3d (const mglDataA &
dat, long
num, long
skip=20
)
¶HMDT
mgl_data_ifs_3d (HCDT
dat, long
num, long
skip)
¶Находит num точек {x[i]=res[0,i], y[i]=res[1,i], z[i]=res[2,i]} фрактала с использованием итерационной системы функций (IFS). Матрица dat используется для генерации в соответствии с формулами
x[i+1] = dat[0,i]*x[i] + dat[1,i]*y[i] + dat[2,i]*z[i] + dat[9,i]; y[i+1] = dat[3,i]*x[i] + dat[4,i]*y[i] + dat[5,i]*z[i] + dat[10,i]; z[i+1] = dat[6,i]*x[i] + dat[7,i]*y[i] + dat[8,i]*z[i] + dat[11,i];
Значение dat[12,i]
– весовой коэффициент для i-ой строки матрицы dat. Первые skip итераций будут опущены. Массив dat должен иметь размер по x больше или равный 13. См. также ifs2d. См. раздел Sample ‘ifs3d’, для примеров кода и графика.
RES 'fname' 'name' num
[skip=20
]
¶mglData
mglIFSfile (const char *
fname, const char *
name, long
num, long
skip=20
)
¶HMDT
mgl_data_ifs_file (const char *
fname, const char *
name, long
num, long
skip)
¶Считывает параметры фрактала name из файла fname и находит num точек для него. Первые skip итераций будут опущены. См. также ifs2d, ifs3d.
Файл IFS может содержать несколько записей. Каждая запись содержит имя фрактала (‘binary’ в примере ниже) и тело в фигурных скобках {} с параметрами фрактала. Символ ‘;’ начинает комментарий. Если имя содержит ‘(3D)’ или ‘(3d)’, то определен 3d IFS фрактал. Пример содержит два фрактала: ‘binary’ – обычный 2d фрактал, и ‘3dfern (3D)’ – 3d фрактал. См. также ifs2d, ifs3d.
binary { ; comment allowed here ; and here .5 .0 .0 .5 -2.563477 -0.000003 .333333 ; also comment allowed here .5 .0 .0 .5 2.436544 -0.000003 .333333 .0 -.5 .5 .0 4.873085 7.563492 .333333 } 3dfern (3D) { .00 .00 0 .0 .18 .0 0 0.0 0.00 0 0.0 0 .01 .85 .00 0 .0 .85 .1 0 -0.1 0.85 0 1.6 0 .85 .20 -.20 0 .2 .20 .0 0 0.0 0.30 0 0.8 0 .07 -.20 .20 0 .2 .20 .0 0 0.0 0.30 0 0.8 0 .07 }
RES dat func num
[skip=20
]
¶mglData
mglFlame2d (const mglDataA &
dat, const mglDataA &
func, long
num, long
skip=20
)
¶HMDT
mgl_data_flame_2d (HCDT
dat, HCDT
func, long
num, long
skip)
¶Находит num точек {x[i]=res[0,i], y[i]=res[1,i]} фрактала с использованием итерационной системы функций (IFS). Массив func задает идентификатор функции (func[0,i,j]), ее вес (func[0,i,j]) и аргументы (func[2 ... 5,i,j]). Матрица dat используется для преобразования координат для аргументов функции. Результирующее преобразование имеет вид:
xx = dat[0,i]*x[j] + dat[1,j]*y[i] + dat[4,j]; yy = dat[2,i]*x[j] + dat[3,j]*y[i] + dat[5,j]; x[j+1] = sum_i @var{func}[1,i,j]*@var{func}[0,i,j]_x(xx, yy; @var{func}[2,i,j],...,@var{func}[5,i,j]); y[j+1] = sum_i @var{func}[1,i,j]*@var{func}[0,i,j]_y(xx, yy; @var{func}[2,i,j],...,@var{func}[5,i,j]);
Значение dat[6,i]
– весовой коэффициент для i-ой строки матрицы dat. Первые skip итераций будут опущены. Массив dat должен иметь размер по x больше или равный 7.
Доступные идентификаторы функций: mglFlame2d_linear=0, mglFlame2d_sinusoidal, mglFlame2d_spherical, mglFlame2d_swirl, mglFlame2d_horseshoe,
mglFlame2d_polar, mglFlame2d_handkerchief,mglFlame2d_heart, mglFlame2d_disc, mglFlame2d_spiral,
mglFlame2d_hyperbolic, mglFlame2d_diamond, mglFlame2d_ex, mglFlame2d_julia, mglFlame2d_bent,
mglFlame2d_waves, mglFlame2d_fisheye, mglFlame2d_popcorn, mglFlame2d_exponential, mglFlame2d_power,
mglFlame2d_cosine, mglFlame2d_rings, mglFlame2d_fan, mglFlame2d_blob, mglFlame2d_pdj,
mglFlame2d_fan2, mglFlame2d_rings2, mglFlame2d_eyefish, mglFlame2d_bubble, mglFlame2d_cylinder,
mglFlame2d_perspective, mglFlame2d_noise, mglFlame2d_juliaN, mglFlame2d_juliaScope, mglFlame2d_blur,
mglFlame2d_gaussian, mglFlame2d_radialBlur, mglFlame2d_pie, mglFlame2d_ngon, mglFlame2d_curl,
mglFlame2d_rectangles, mglFlame2d_arch, mglFlame2d_tangent, mglFlame2d_square, mglFlame2d_blade,
mglFlame2d_secant, mglFlame2d_rays, mglFlame2d_twintrian, mglFlame2d_cross, mglFlame2d_disc2,
mglFlame2d_supershape, mglFlame2d_flower, mglFlame2d_conic, mglFlame2d_parabola, mglFlame2d_bent2,
mglFlame2d_bipolar, mglFlame2d_boarders, mglFlame2d_butterfly, mglFlame2d_cell, mglFlame2d_cpow,
mglFlame2d_curve, mglFlame2d_edisc, mglFlame2d_elliptic, mglFlame2d_escher, mglFlame2d_foci,
mglFlame2d_lazySusan, mglFlame2d_loonie, mglFlame2d_preBlur, mglFlame2d_modulus, mglFlame2d_oscope,
mglFlame2d_polar2, mglFlame2d_popcorn2, mglFlame2d_scry, mglFlame2d_separation, mglFlame2d_split,
mglFlame2d_splits, mglFlame2d_stripes, mglFlame2d_wedge, mglFlame2d_wedgeJulia, mglFlame2d_wedgeSph,
mglFlame2d_whorl, mglFlame2d_waves2, mglFlame2d_exp, mglFlame2d_log, mglFlame2d_sin,
mglFlame2d_cos, mglFlame2d_tan, mglFlame2d_sec, mglFlame2d_csc, mglFlame2d_cot,
mglFlame2d_sinh, mglFlame2d_cosh, mglFlame2d_tanh, mglFlame2d_sech, mglFlame2d_csch,
mglFlame2d_coth, mglFlame2d_auger, mglFlame2d_flux.
Значение dat[6,i]
– весовой коэффициент для i-ой строки матрицы dat. Первые skip итераций будут опущены. Размеры массивов должны удовлетворять требованиям: dat.nx>=7, func.nx>=2 и func.nz=dat.ny. См. также ifs2d, ifs3d. См. раздел Sample ‘flame2d’, для примеров кода и графика.
В MathGL есть специальные классы mglExpr
и mglExprC
для вычисления формул заданных строкой для действительных и комплексных чисел соответственно. Классы определены в #include <mgl2/data.h>
и #include <mgl2/datac.h>
соответственно. При создании класса происходит разбор формулы в древовидную структуру. А при вычислении только выполняется достаточно быстрый обход по дереву. В данный момент нет различия между верхним и нижним регистром. Если аргумент какой-либо функции лежит вне её области определения, то возвращается NaN. See Текстовые формулы.
mglExpr
:
mglExpr (const char *
expr)
¶mglExprC
:
mglExprC (const char *
expr)
¶HMEX
mgl_create_expr (const char *
expr)
¶HAEX
mgl_create_cexpr (const char *
expr)
¶Разбирает формулу expr и создает древовидную структуру, содержащую последовательность вызова функций и операторов для последующего быстрого вычисления формулы с помощью функций Calc()
и/или CalcD()
.
mglExpr
:
~mglExpr ()
¶mglExprC
:
~mglExprC ()
¶void
mgl_delete_expr (HMEX
ex)
¶void
mgl_delete_cexpr (HAEX
ex)
¶Удаляет объект типа mglExpr
.
mglExpr
: mreal
Eval (mreal
x, mreal
y, mreal
z)
¶mglExprC
: dual
Eval (dual
x, dual
y, dual
z)
¶mreal
mgl_expr_eval (HMEX
ex, mreal
x, mreal
y, mreal
z)
¶dual
mgl_cexpr_eval (HAEX
ex, dual
x, dual
y, dual
z)
¶Вычисляет значение формулы для 'x','r'
=x, 'y','n'
=y, 'z','t'
=z, 'a','u'
=u.
mglExpr
: mreal
Eval (mreal
var[26])
¶mglExprC
: dual
Eval (dual
var[26])
¶mreal
mgl_expr_eval_v (HMEX
ex, mreal *
var)
¶dual
mgl_cexpr_eval_v (HMEX
ex, dual *
var)
¶Вычисляет значение формулы для переменных в массиве var[0,...,’z’-’a’].
mglExpr
: mreal
Diff (char
dir, mreal
x, mreal
y, mreal
z)
¶mreal
mgl_expr_diff (HMEX
ex, char
dir, mreal
x, mreal
y, mreal
z)
¶Вычисляет производную от формулы по переменной dir для 'x','r'
=x, 'y','n'
=y, 'z','t'
=z, 'a','u'
=u.
mglExpr
: mreal
Diff (char
dir, mreal
var[26])
¶mreal
mgl_expr_diff_v (HMEX
ex, char
dir, mreal *
var)
¶Вычисляет производную от формулы по переменной dir для переменных в массиве var[0,...,’z’-’a’].
Раздел описывает специальные классы данных mglDataV
, mglDataF
, mglDataT
и mglDataR
, которые могут заметно ускорить рисование и обработку данных. Классы определены в #include <mgl2/data.h>
. Отмечу, что все функции рисования и обработки данных можно выполнить используя только основные классы mglData
и/или mglDataC
. Также специальные классы доступны только в коде на С++.
mglDataV
представляет переменную со значениями равнораспределенными в заданном интервале.
mglDataV
:
mglDataV (const mglDataV &
d)
¶Конструктор копирования.
mglDataV
:
mglDataV (long
nx=1
, long
ny=1
, long
nz=1
, mreal
v1=0
, mreal
v2=NaN
, char
dir='x'
)
¶Создает переменную "размером" nxxnyxnz, изменяющуюся от v1 до v2 (или постоянную при v2=NaN
) вдоль направления dir.
mglDataV
: void
Create (long
nx=1
, long
ny=1
, long
nz=1
)
¶Задает "размеры" переменной nxxnyxnz.
mglDataV
: void
Fill (mreal
x1, mreal
x2=NaN
, char
dir='x'
)
¶Задает диапазон изменения переменной.
mglDataV
: void
Freq (mreal
dp, char
dir='x'
)
¶Задает переменную для частоты с шагом dp.
mglDataF
представляет функцию, которая будет вызываться вместо обращения к элементам массива (как в классе mglData
).
mglDataF
:
mglDataF (const mglDataF &
d)
¶Конструктор копирования.
mglDataF
:
mglDataF (long
nx=1
, long
ny=1
, long
nz=1
)
¶Создает данные "размером" nxxnyxnz с нулевой функцией.
mglDataF
: void
Create (long
nx=1
, long
ny=1
, long
nz=1
)
¶Задает "размеры" данных nxxnyxnz.
mglDataF
: void
SetRanges (mglPoint
p1, mglPoint
p2)
¶Задает диапазоны изменения внутренних переменных x,y,z.
mglDataF
: void
SetFormula (const char *
func)
¶Задает строку, которая будет разобрана в функцию. Это вариант более чем 10 раз медленнее в сравнении с SetFunc
().
mglDataF
: void
SetFunc (mreal (*
f)(mreal x,mreal y,mreal z,void *p)
, void *
p=NULL
)
¶Задает указатель на функцию, которая будет использована вместо доступа к элементам массива.
mglDataT
представляет именнованную ссылку на столбец в другом массиве данных.
mglDataT
:
mglDataT (const mglDataT &
d)
¶Конструктор копирования.
mglDataT
:
mglDataT (const mglDataA &
d, long
col=0
)
¶Создает ссылку на col-ый столбец данных d.
mglDataT
: void
SetInd (long
col, wchar_t
name)
¶mglDataT
: void
SetInd (long
col, const wchar_t *
name)
¶Задает ссылку на другой столбец того же массива данных.
mglDataR
представляет именнованную ссылку на строку в другом массиве данных.
mglDataR
:
mglDataR (const mglDataR &
d)
¶Конструктор копирования.
mglDataR
:
mglDataR (const mglDataA &
d, long
row=0
)
¶Создает ссылку на row-ую строку данных d.
mglDataR
: void
SetInd (long
row, wchar_t
name)
¶mglDataR
: void
SetInd (long
row, const wchar_t *
name)
¶Задает ссылку на другой столбец того же массива данных.
mglDataW
представляет часоту для FFT в виде массива данных.
mglDataW
:
mglDataW (const mglDataW &
d)
¶Конструктор копирования.
mglDataW
:
mglDataW (long
xx=1
, long
yy=1
, long
zz=1
, double
dp=0
, char
dir='x'
)
¶Задает размеры, направление dir и шаг dp для частоты.
mglDataR
: void
Freq (double
dp, char
dir='x'
)
¶Равномерно распределяет данные с шагом dp в направлении dir.
mglDataS
представляет std::vector в виде массива данных.
mglDataS
: std::vector<mreal>
dat ¶Собственно данные.
mglDataS
:
mglDataS (const mglDataS &
d)
¶Конструктор копирования.
mglDataS
:
mglDataS (const std::vector<mreal> &
d)
¶Копирует данные из d.
mglDataS
:
mglDataS (size_t
s)
¶Выделяет память для s элементов.
mglDataS
: void
reserve (size_t
num)
¶Резервирует место для num элементов.
mglDataS
: void
push_back (double
v)
¶Добавляет значение v к концу массива данных.
MathGL имеет встроенный скриптовый язык MGL для обработки и отображения данных. Скрипты MGL могут быть выполнены независимо (с помощью программ UDAV, mglconv, mglview и др. , см. Utilities for parsing MGL) или с использованием вызовов библиотеки.
Язык MGL достаточно простой. Каждая строка – отдельная команда. Первое слово – имя команды, а все остальные ее аргументы. Команда может иметь до 1000 аргументов (по крайней мере сейчас). Слова разделяются одно от другого пробелом или символом табуляции. Различий между верхним и нижним индексом нет, т.е. переменные a и A идентичны. Символ ‘#’ начинает комментарий – все символы после него игнорируются до конца строки. Исключением является случай, когда ‘#’ входит в строку. Опции команды указываются после символа ‘;’ (see Опции команд). Символ ‘:’ начинает новую команду (подобно переводу строки) если он расположен не внутри скобок или строки.
Если строка содержит ссылки на внешние параметры (‘$0’, ‘$1’ ... ‘$9’) или макроопределения (‘$a’, ‘$b’ ... ‘$z’), то текущие значения параметров/макроопределений подставляются в строку вместо ссылки до выполнением команды. Это позволяет использовать один и тот же скрипт при различных входных параметрах командной строки или вводить макроопределения по ходу исполнения команд скрипта.
Аргументы команды могут быть строками, переменными или числами.
'b'
);
'abf'
).
new x 100 'x':copy !b !exp(1i*x)
создаст массив действительных чисел x и массив комплексных чисел b, который будет равен exp(I*x), где I^2=-1.
В качестве переменной можно использовать также и временные массивы, включающие в себя:
a(1)
или a(1,:)
или a(1,:,:)
– вторая строка массива a, a(:,2)
или a(:,2,:)
– третий столбец, a(:,:,0)
– первый срез и т.д. Также можно выделить часть массива с m-го по n-ый элемент a(m:n,:,:)
или просто a(m:n)
.
a('n*w^2/exp(t)')
), если столбцы данных были именованы командой idset или в файле данных (в строке начинающейся с ##
).
tmp[i,j] = sqrt(dat[i,5,j]+1)
. При этом символ ‘`’ возвращает транспонированный массив: ‘`sqrt(dat(:,5)+1)’ и ‘sqrt(`dat(:,5)+1)’ оба дадут временный массив данных с элементами равными tmp[i,j] = sqrt(dat[j,5,i]+1)
.
Временные массивы не могут стоять в качестве первого аргумента команд, создающих массивы (например, ‘new’, ‘read’, ‘hist’ и т.д.).
nan=#QNAN, inf=бесконечность, rnd=случайное число, pi=3.1415926..., on=1, off=0, all=-1, :=-1
, переменные с суффиксами (see Информационные функции), переменные определенные командой define, значения времени (в формате "hh-mm-ss_DD.MM.YYYY", "hh-mm-ss" или "DD.MM.YYYY") . Также массивы размером 1x1x1 считаются скалярами (например, ‘pi/dat.nx’).
Перед первым использованием все переменные должны быть определены с помощью команд, создающих массивы (new, var, list, copy, read, hist, sum и др., см. Создание и удаление данных, Заполнение данных и Make another data).
Команды могут иметь несколько наборов аргументов (например, plot ydat
и plot xdat ydat
). Все аргументы команды для выбранного набора должны быть указаны, однако часть из них могут иметь значения по умолчанию. Такие аргументы в описании команд будут помещены в квадратные скобки [], например plot ydat ['stl'='' zval=nan]
. При этом запись [arg1 arg2 arg3 ...]
подразумевает [arg1 [arg2 [arg3 ...]]]
, т.е. опускать можно только аргументы с конца, если вы согласны с их значениями по умолчанию. Например, plot ydat '' 1
или plot ydat ''
правильно, а plot ydat 1
не правильно (аргумент 'stl'
пропущен).
Можно предоставить несколько вариантов аргументов комманд при использовании символа ‘?’ для их разделения. Конкретный вариант аргумента, используемый при выполнении команды, задается значением команды variant. При этом будет использован последний вариант, если задано слишком большое значение. По умолчанию используется первый вариант (т.е. как при variant 0
). Например в следующем коде будет сначала нарисован график синим цветом (первый аргумент ‘b’), а затем красным пунктиром – после variant 1
будет использован второй аргумент ‘r|’:
fplot 'x' 'b'?'r' variant 1 fplot 'x^3' 'b'?'r|'
Ниже собраны команды, управляющие порядком выполнения других команд (условия, циклы, подпрограммы), (пере-)определяют аргументы скрипта и пр. Прочие команды могут быть найдены в главах Ядро MathGL и Обработка данных. Отмечу, что некоторые из команд (например, define, ask, call, for, func) должны быть расположены на отдельной строке.
'path'
¶Переходит в папку path.
$N 'question'
¶Задает N-ый аргумент скрипта равным ответу пользователя на вопрос question. Обычно команда показывает диалог с вопросом и полем ввода текста ответа. Здесь N это цифра (0...9) или буква (a...z).
$N smth
¶Задает N-ый аргумент скрипта равным smth. Отмечу, что smth используется как есть (с символами ‘'’ если присутствуют). Выполняется только подстановка других макроопределений $0...$9, $a...$z. Здесь N это цифра (0...9) или буква (a...z).
name smth
¶Определяет константу (скаляр) с именем name
и числовым значением smth
. Позднее она может быть использована как обычное число.
$N smth
¶Задает N-ый аргумент скрипта равным символу с UTF кодом smth. Здесь N это цифра (0...9) или буква (a...z).
$N smth
¶Задает N-ый аргумент скрипта равным числовому значению smth. Здесь N это цифра (0...9) или буква (a...z).
'fname' [ARG1 ARG2 ... ARG9]
¶Переходит к выполнению (вызывает) подпрограммы fname (или внешнего скрипта, если функция не была найдена). Опциональные аргументы передаются в подпрограмму. См. также func.
'fname' [narg=0]
¶Определяет подпрограмму с именем fname и задает число требуемых аргументов. Аргументы будут помещены в параметры скрипта $1, $2, ... $9. Отмечу, что выполнение основной программы будет остановлено при встрече func
– действует аналогично комманде stop. См. также return.
'filename'
¶Загружает дополнительные команды MGL из внешней динамической библиотеки filename. Данная библиотека должна содержать массив с именем mgl_cmd_extra
типа mglCommand
, который содержит описание новых комманд.
val
then CMD
¶Выполняет команду CMD
только если val
не ноль.
val
¶Начинает блок команд, выполняемый если val
не ноль.
dat 'cond'
¶Начинает блок команд, выполняемый если каждый элемент dat удовлетворяет условию cond.
dat 'cond'
¶Начинает блок команд, выполняемый если предыдущий if
или elseif
не был выполнен и каждый элемент dat удовлетворяет условию cond.
val
¶Начинает блок команд, выполняемый если предыдущий if
или elseif
не был выполнен и val
не ноль.
Начинает блок команд, выполняемый если предыдущий if
или elseif
не был выполнен.
Заканчивает определение блока if/elseif/else
.
$N v1 v2 [dv=1]
¶Начинает блок команд, выполняемый в цикле с $N-ым аргументом изменяющимся от v1 до v2 с шагом dv. Здесь N это цифра (0...9) или буква (a...z).
$N dat
¶Начинает блок команд, выполняемый в цикле с $N-ым аргументом пробегающим значения массива dat. Здесь N это цифра (0...9) или буква (a...z).
Заканчивает блок цикла for
.
Начинает бесконечный цикл.
val
¶Переходит к следующей итерации цикла если val не ноль, в противном случае заканчивает цикл.
dat 'cond'
¶Переходит к следующей итерации цикла если dat удовлетворяет условию cond, в противном случае заканчивает цикл.
val
¶Определяет код (между once on
и once off
) который будет выполнен только один раз. Полезно для работы с большими данными в программах типа UDAV.
Останавливает выполнение скрипта.
val
¶Задает вариант аргумента(ов), разделенных символом ‘?’, для всех последующих комманд.
eq1;... var1;... [dt=1
]
¶Выполняет один шаг решения системы обыкновенных дифференциальных уравнений {var1’ = eq1, ... } с временным шагом dt. Здесь переменные ‘var1’, ... – переменные, определенные в MGL скрипте ранее. При решении используется метод Рунге-Кутта 4-го порядка.
There are number of special comments for MGL script, which set some global behavior (like, animation, dialog for parameters and so on). All these special comments starts with double sign ##
. Let consider them.
v1 v2 [dv=1]
’Sets the parameter for animation loop relative to variable $0
. Here v1 and v2 are initial and final values, dv is the increment.
Adds the parameter val to the list of animation relative to variable $0
. You can use it several times (one parameter per line) or combine it with animation loop ##c.
Creates custom dialog for changing plot properties. Each line adds one widget to the dialog. Here $I is id ($0,$1...$9,$a,$b...$z), label is the label of widget, kind is the kind of the widget:
Now, it work in FLTK-based mgllab
and mglview
only.
You can make custom dialog in C/C++ code too by using one of following functions.
mglWnd
: void
MakeDialog (const char *
ids, char const * const *
args, const char *
title)
¶mglWnd
: void
MakeDialog (const std::string &
ids, const std::vector<std::string> &
args, const char *
title)
¶void
mgl_wnd_make_dialog (HMGL
gr, const char *
ids, char const * const *
args, const char *
title)
¶Makes custom dialog for parameters ids of element properties defined by args.
At this you need to provide callback function for setting up properties. You can do it by overloading Param()
function of mglDraw
class or set it manually.
mglDraw
: void
Param (char
id, const char *
val)
¶mglWnd
: void
SetPropFunc (void (*
prop)(char id, const char *val, void *p)
, void *
par=NULL
)
¶void
mgl_wnd_set_prop (void (*
prop)(char id, const char *val, void *p)
, void *
par)
¶Set callback function for properties setup.
There is LaTeX package mgltex
(was made by Diego Sejas Viscarra) which allow one to make figures directly from MGL script located in LaTeX file.
For using this package you need to specify --shell-escape
option for latex/pdflatex or manually run mglconv tool with produced MGL scripts for generation of images. Don’t forgot to run latex/pdflatex second time to insert generated images into the output document. Also you need to run pdflatex third time to update converted from EPS images if you are using vector EPS output (default).
The package may have following options: draft
, final
— the same as in the graphicx package; on
, off
— to activate/deactivate the creation of scripts and graphics; comments
, nocomments
— to make visible/invisible comments contained inside mglcomment
environments; jpg
, jpeg
, png
— to export graphics as JPEG/PNG images; eps
, epsz
— to export to uncompressed/compressed EPS format as primitives; bps
, bpsz
— to export to uncompressed/compressed EPS format as bitmap (doesn’t work with pdflatex); pdf
— to export to 3D PDF; tex
— to export to LaTeX/tikz document.
The package defines the following environments:
It writes its contents to a general script which has the same name as the LaTeX document, but its extension is .mgl. The code in this environment is compiled and the image produced is included. It takes exactly the same optional arguments as the \includegraphics
command, plus an additional argument imgext, which specifies the extension to save the image.
An example of usage of ‘mgl’ environment would be:
\begin{mglfunc}{prepare2d} new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' \end{mglfunc} \begin{figure}[!ht] \centering \begin{mgl}[width=0.85\textwidth,height=7.5cm] fog 0.5 call 'prepare2d' subplot 2 2 0 : title 'Surf plot (default)' : rotate 50 60 : light on : box : surf a subplot 2 2 1 : title '"\#" style; meshnum 10' : rotate 50 60 : box surf a '#'; meshnum 10 subplot 2 2 2 : title 'Mesh plot' : rotate 50 60 : box mesh a new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)' new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)' new z 50 40 '0.8*cos(pi*(y+1)/2)' subplot 2 2 3 : title 'parametric form' : rotate 50 60 : box surf x y z 'BbwrR' \end{mgl} \end{figure}
It adds its contents to the general script, without producing any image.
Is exactly the same as ‘mgl’, but it writes its contents verbatim to its own file, whose name is specified as a mandatory argument.
Is exactly the same as ‘mglcode’, but it doesn’t produce any image, nor accepts optional arguments. It is useful, for example, to create a MGL script, which can later be post processed by another package like "listings".
It writes its contents verbatim to a file, specified as a mandatory argument, and to the LaTeX document, and numerates each line of code.
Exactly the same as ‘mglblock’, but it doesn’t write to a file. This environment doesn’t have arguments.
Is used to define MGL functions. It takes one mandatory argument, which is the name of the function, plus one additional argument, which specifies the number of arguments of the function. The environment needs to contain only the body of the function, since the first and last lines are appended automatically, and the resulting code is written at the end of the general script, after the stop command, which is also written automatically. The warning is produced if 2 or more function with the same name is defined.
Is used to contain multiline comments. This comments will be visible/invisible in the output document, depending on the use of the package options comments
and nocomments
(see above), or the \mglcomments
and \mglnocomments
commands (see bellow).
If many scripts with the same code are to be written, the repetitive code can be written inside this environment only once, then this code will be used automatically every time the ‘\mglplot’ command is used (see below). It takes one optional argument, which is a name to be associated to the corresponding contents of the environment; this name can be passed to the ‘\mglplot’ command to use the corresponding block of code automatically (see below).
The package also defines the following commands:
It takes one mandatory argument, which is MGL instructions separated by the symbol ‘:’ this argument can be more than one line long. It takes the same optional arguments as the ‘mgl’ environment, plus an additional argument setup, which indicates the name associated to a block of code inside a ‘mglsetup’ environment. The code inside the mandatory argument will be appended to the block of code specified, and the resulting code will be written to the general script.
An example of usage of ‘\mglplot’ command would be:
\begin{mglsetup} box '@{W9}' : axis \end{mglsetup} \begin{mglsetup}[2d] box : axis grid 'xy' ';k' \end{mglsetup} \begin{mglsetup}[3d] rotate 50 60 box : axis : grid 'xyz' ';k' \end{mglsetup} \begin{figure}[!ht] \centering \mglplot[scale=0.5]{new a 200 'sin(pi*x)' : plot a '2B'} \end{figure} \begin{figure}[!ht] \centering \mglplot[scale=0.5,setup=2d]{ fplot 'sin(pi*x)' '2B' : fplot 'cos(pi*x^2)' '2R' } \end{figure} \begin{figure}[!ht] \centering \mglplot[setup=3d]{fsurf 'sin(pi*x)+cos(pi*y)'} \end{figure}
This command takes the same optional arguments as the ‘mgl’ environment, and one mandatory argument, which is the name of a MGL script. This command will compile the corresponding script and include the resulting image. It is useful when you have a script outside the LaTeX document, and you want to include the image, but you don’t want to type the script again.
This is like ‘\mglgraphics’ but, instead of creating/including the corresponding image, it writes the contents of the MGL script to the LaTeX document, and numerates the lines.
This command can be used in the preamble of the document to specify a directory where LaTeX will save the MGL scripts and generate the corresponding images. This directory is also where ‘\mglgraphics’ and ‘\mglinclude’ will look for scripts.
Adjust the quality of the MGL graphics produced similarly to quality.
Activate/deactivate the creation of MGL scripts and images. Notice these commands have local behavior in the sense that their effect is from the point they are called on.
Make visible/invisible the contents of the mglcomment
environments. These commands have local effect too.
It just pretty prints the name of the package.
As an additional feature, when an image is not found or cannot be included, instead of issuing an error, mgltex
prints a box with the word ‘MGL image not found’ in the LaTeX document.
Класс разбирает и выполняет скрипты MGL. Он определен в #include <mgl2/mgl.h>
.
Основная функция класса mglParse – Execute()
, выполняющая построчный разбор скрипта. Также есть вспомогательные функции для поиска и создания переменных MGL (объектов, производных от mglDataA
). Эти функции полезны для отображения значений массивов во внешних объектах (например, в отдельном окне) или для предоставления доступа к внутренним массивам. Функция AllowSetSize()
позволяет запретить изменение размера картинки (запрещает команду setsize
). Функция AllowFileIO()
позволяет запретить доступ к файлам на диске.
mglParse
:
mglParse (bool
setsize=false
)
¶mglParse
:
mglParse (HMPR
pr)
¶mglParse
:
mglParse (mglParse &
pr)
¶HMPR
mgl_create_parser ()
¶Создает экземпляр класса mglParse
и устанавливает значение AllowSetSize.
mglParse
:
~mglParse ()
¶void
mgl_delete_parser (HMPR
p)
¶Удаляет экземпляр класса.
mglParse
: HMPR
Self ()
¶Возвращает указатель на используемый объект типа HMPR
.
mglParse
: void
Execute (mglGraph *
gr, const char *
text)
¶mglParse
: void
Execute (mglGraph *
gr, const wchar_t *
text)
¶void
mgl_parse_text (HMGL
gr, HMPR
p, const char *
text)
¶void
mgl_parse_textw (HMGL
gr, HMPR
p, const wchar_t *
text)
¶Выполняет построчно скрипт MGL, содержащийся в text. Строки считаются разделенными символом ‘\n’. Это основная функция класса.
mglParse
: void
Execute (mglGraph *
gr, FILE *
fp, bool
print=false
)
¶void
mgl_parse_file (HMGL
gr, HMPR
p, FILE *
fp, int
print)
¶Аналогично предыдущему, но скрипт читается из файла fp. Если print=true
, то предупреждения и информационные сообщения печатаются в stdout.
mglParse
: int
Parse (mglGraph *
gr, const char *
str, long
pos=0
)
¶mglParse
: int
Parse (mglGraph *
gr, const wchar_t *
str, long
pos=0
)
¶int
mgl_parse_line (HMGL
gr, HMPR
p, const char *
str, int
pos)
¶int
mgl_parse_linew (HMGL
gr, HMPR
p, const wchar_t *
str, int
pos)
¶Выполняет строку str с выводом графики на gr. Возвращает код ошибки: 0 – нет ошибок, 1 – неправильные аргументы, 2 – неизвестная команда, 3 – строка слишком длинная, 4 – нет закрывающей скобки или ‘'’. Аргумент pos задает позицию строки в документе/файле для использования в команде for.
mglParse
: mglData
Calc (const char *
formula)
¶mglParse
: mglData
Calc (const wchar_t *
formula)
¶HMDT
mgl_parser_calc (HMPR
p, const char *
formula)
¶HMDT
mgl_parser_calcw (HMPR
p, const wchar_t *
formula)
¶Разбирает строку formula и возвращает полученный массив. В отличие от AddVar()
или FindVar()
, это обычный массив данных, который следует удалить после использования.
mglParse
: mglDataC
CalcComplex (const char *
formula)
¶mglParse
: mglDataC
CalcComplex (const wchar_t *
formula)
¶HADT
mgl_parser_calc_complex (HMPR
p, const char *
formula)
¶HADT
mgl_parser_calc_complexw (HMPR
p, const wchar_t *
formula)
¶Разбирает строку formula и возвращает полученный массив с комплексными значениями. В отличие от AddVar()
или FindVar()
, это обычный массив данных, который следует удалить после использования.
mglParse
: void
AddParam (int
n, const char *
str)
¶mglParse
: void
AddParam (int
n, const wchar_t *
str)
¶void
mgl_parser_add_param (HMPR
p, int
id, const char *
val)
¶void
mgl_parser_add_paramw (HMPR
p, int
id, const wchar_t *
val)
¶Устанавливает значение n-го параметра строкой str (n=0, 1 ... ’z’-’a’+10). Строка str не должна содержать символ ‘$’.
mglParse
: mglVar *
FindVar (const char *
name)
¶mglParse
: mglVar *
FindVar (const wchar_t *
name)
¶HMDT
mgl_parser_find_var (HMPR
p, const char *
name)
¶HMDT
mgl_parser_find_varw (HMPR
p, const wchar_t *
name)
¶Возвращает указатель на переменную с именем name или NULL
если переменная отсутствует. Используйте эту функцию для добавления внешних массивов в скрипт. Не удаляйте полученный массив!
mglParse
: mglVar *
AddVar (const char *
name)
¶mglParse
: mglVar *
AddVar (const wchar_t *
name)
¶HMDT
mgl_parser_add_var (HMPR
p, const char *
name)
¶HMDT
mgl_parser_add_varw (HMPR
p, const wchar_t *
name)
¶Возвращает указатель на переменную с именем name. Если переменная отсутствует, то она будет создана. Используйте эту функцию для добавления внешних массивов в скрипт. Не удаляйте полученный массив!
mglParse
: void
OpenHDF (const char *
fname)
¶void
mgl_parser_openhdf (HMPR
pr, const char *
fname)
¶Читает все массивы данных из HDF5 файла fname и создает переменные MGL с соответствующими именами. Если имя данных начинается с ‘!’, то будут созданы комплексные массивы.
mglParse
(C++): void
DeleteVar (const char *
name)
¶mglParse
(C++): void
DeleteVar (const wchar_t *
name)
¶void
mgl_parser_del_var (HMPR
p, const char *
name)
¶void
mgl_parser_del_varw (HMPR
p, const wchar_t *
name)
¶Удаляет переменную по имени name.
mglParse
(C++): void
DeleteAll ()
¶void
mgl_parser_del_all (HMPR
p)
¶Удаляет все переменные и сбрасывает список команд к списку по умолчанию в данном классе.
mglParse
: void
RestoreOnce ()
¶void
mgl_parser_restore_once (HMPR
p)
¶Восстанавливает состояние флага Once.
mglParse
: void
AllowSetSize (bool
a)
¶void
mgl_parser_allow_setsize (HMPR
p, int
a)
¶Разрешает/запрещает команду setsize.
mglParse
: void
AllowFileIO (bool
a)
¶void
mgl_parser_allow_file_io (HMPR
p, int
a)
¶Разрешает/запрещает команды чтения файлов.
mglParse
: void
AllowDllCall (bool
a)
¶void
mgl_parser_allow_dll_call (HMPR
p, int
a)
¶Разрешает/запрещает команду load.
mglParse
: void
Stop ()
¶void
mgl_parser_stop (HMPR
p)
¶Посылает сигнал завершения выполнения для следующей команды.
mglParse
: void
SetVariant (int
var=0
)
¶void
mgl_parser_variant (HMPR
p, int
var=0
)
¶Задает вариант аргумента(ов), разделенных символом ‘?’, для всех последующих комманд.
mglParse
: void
StartID (int
id=0
)
¶void
mgl_parser_start_id (HMPR
p, int
id)
¶Задает начальный id (обычно это номер строки) первой строки при последующем выполнении скрипта.
mglParse
: long
GetCmdNum ()
¶long
mgl_parser_cmd_num (HMPR
p)
¶Возвращает число зарегистрированных команд MGL.
mglParse
: const char *
GetCmdName (long
id)
¶const char *
mgl_parser_cmd_name (HMPR
p, long
id)
¶Возвращает имя команды MGL с заданным номером id.
mglParse
: int
CmdType (const char *
name)
¶int
mgl_parser_cmd_type (HMPR
p, const char *
name)
¶Возвращает тип команды MGL с именем name. Типы команд: 0 – не команда, 1 - графики по данным, 2 - прочие графики, 3 - настройка, 4 - обработка данных, 5 - создание данных, 6 - трансформация, 7 - ход выполнения, 8 - 1d графики, 9 - 2d графики, 10 - 3d графики, 11 - двойные графики, 12 - векторные поля, 13 - оси координат, 14 - примитивы, 15 - настройка осей, 16 - текст/легенда, 17 - изменение данных.
mglParse
: const char *
CmdFormat (const char *
name)
¶const char *
mgl_parser_cmd_frmt (HMPR
p, const char *
name)
¶Возвращает формат аргументов команды MGL с именем name.
mglParse
: const char *
CmdDesc (const char *
name)
¶const char *
mgl_parser_cmd_desc (HMPR
p, const char *
name)
¶Возвращает описание команды MGL с именем name.
mglParse
: void
RK_Step (const char *
eqs, const char *
vars, mreal
dt=1
)
¶mglParse
: void
RK_Step (const wchar_t *
eqs, const wchar_t *
vars, mreal
dt=1
)
¶void
mgl_rk_step (HMPR
p, const char *
eqs, const char *
vars, mreal
dt)
¶void
mgl_rk_step_w (HMPR
p, const wchar_t *
eqs, const wchar_t *
vars, mreal
dt)
¶Make one step for ordinary differential equation(s) {var1’ = eq1, ... } with time-step dt. Here strings eqs and vars contain the equations and variable names separated by symbol ‘;’. The variable(s) ‘var1’, ... are the ones, defined in MGL script previously. The Runge-Kutta 4-th order method is used.
UDAV (Universal Data Array Visualizator) is cross-platform program for data arrays visualization based on MathGL library. It support wide spectrum of graphics, simple script language and visual data handling and editing. It has window interface for data viewing, changing and plotting. Also it can execute MGL scripts, setup and rotate graphics and so on. UDAV hot-keys can be found in the appendix Hot-keys for UDAV.
UDAV have main window divided by 2 parts in general case and optional bottom panel(s). Left side contain tabs for MGL script and data arrays. Right side contain tabs with graphics itself, with list of variables and with help on MGL. Bottom side may contain the panel with MGL messages and warnings, and the panel with calculator.
Main window is shown on the figure above. You can see the script (at left) with current line highlighted by light-yellow, and result of its execution at right. Each panel have its own set of toolbuttons.
Editor toolbuttons allow: open and save script from/to file; undo and redo changes; cut, copy and paste selection; find/replace text; show dialogs for command arguments and for plot setup; show calculator at bottom.
Graphics toolbuttons allow: enable/disable additional transparency and lighting; show grid of absolute coordinates; enable mouse rotation; restore image view; refresh graphics (execute the script); stop calculation; copy graphics into clipboard; add primitives (line, curve, box, rhombus, ellipse, mark, text) to the image; change view angles manually. Vertical toolbuttons allow: shift and zoom in/out of image as whole; show next and previous frame of animation, or start animation (if one present).
Graphics panel support plot editing by mouse.
Short command description and list of its arguments are shown at the status-bar, when you move cursor to the new line of code. You can press F1 to see more detailed help on special panel.
Also you can look the current list of variables, its dimensions and its size in the memory (right side of above figure). Toolbuttons allow: create new variable, edit variable, delete variable, preview variable plot and its properties, refresh list of variables. Pressing on any column will sort table according its contents. Double click on a variable will open panel with data cells of the variable, where you can view/edit each cell independently or apply a set of transformations.
Finally, pressing F2 or F4 you can show/hide windows with messages/warnings and with calculator. Double click on a warning in message window will jump to corresponding line in editor. Calculator allow you type expression by keyboard as well as by toolbuttons. It know about all current variables, so you can use them in formulas.
There are a set of dialogs, which allow change/add a command, setup global plot properties, or setup UDAV itself.
One of most interesting dialog (hotkey Meta-C or Win-C) is dialog which help to enter new command or change arguments of existed one. It allows consequently select the category of command, command name in category and appropriate set of command arguments. At this right side show detailed command description. Required argument(s) are denoted by bold text. Strings are placed in apostrophes, like 'txt'
. Buttons below table allow one to call dialogs for changing style of command (if argument 'fmt'
is present in the list of command arguments); to set variable or expression for argument(s); to add options for command. Note, you can click on a cell to enter value, or double-click to call corresponding dialog.
Dialog for changing style can be called independently, but usually is called from New command dialog or by double click on primitive. It contain 3 tabs: one for pen style, one for color scheme, one for text style. You should select appropriate one. Resulting string of style and sample picture are shown at bottom of dialog. Usually it can be called from New command dialog.
Dialog for entering variable allow one to select variable or expression which can be used as argument of a command. Here you can select the variable name; range of indexes in each directions; operation which will be applied (like, summation, finding minimal/maximal values and so on). Usually it can be called from New command dialog.
Dialog for command options allow one to change Опции команд. Usually it can be called from New command dialog.
Another interesting dialog, which help to select and properly setup a subplot, inplot, columnplot, stickplot and similar commands.
There is dialog for setting general plot properties, including tab for setting lighting properties. It can be called by called by hotkey ??? and put setup commands at the beginning of MGL script.
Also you can set or change script parameters (‘$0’ ... ‘$9’, see Основы MGL).
Finally, there is dialog for UDAV settings. It allow one to change most of things in UDAV appearance and working, including colors of keywords and numbers, default font and image size, and so on (see figure above).
There are also a set of dialogs for data handling, but they are too simple and clear. So, I will not put them here.
mglconv
, mglview
.
There are few end-user classes: mglGraph
(see Ядро MathGL), mglWindow
and mglGLUT
(see “Оконные” классы), mglData
(see Обработка данных), mglParse
(see Скрипты MGL). Exactly these classes I recommend to use in most of user programs. All methods in all of these classes are inline and have exact C/Fortran analogue functions. This give compiler independent binary libraries for MathGL.
However, sometimes you may need to extend MathGL by writing yours own plotting functions or handling yours own data structures. In these cases you may need to use low-level API. This chapter describes it.
The internal structure of MathGL is rather complicated. There are C++ classes mglBase
, mglCanvas
, ... for drawing primitives and positioning the plot (blue ones in the figure). There is a layer of C functions, which include interface for most important methods of these classes. Also most of plotting functions are implemented as C functions. After it, there are “inline” front-end classes which are created for user convenience (yellow ones in the figure). Also there are widgets for FLTK and Qt libraries (green ones in the figure).
Below I show how this internal classes can be used.
Basically most of new kinds of plot can be created using just MathGL primitives (see Рисование примитивов). However the usage of mglBase
methods can give you higher speed of drawing and better control of plot settings.
All plotting functions should use a pointer to mglBase
class (or HMGL
type in C functions) due to compatibility issues. Exactly such type of pointers are used in front-end classes (mglGraph, mglWindow
) and in widgets (QMathGL, Fl_MathGL
).
MathGL tries to remember all vertexes and all primitives and plot creation stage, and to use them for making final picture by demand. Basically for making plot, you need to add vertexes by AddPnt()
function, which return index for new vertex, and call one of primitive drawing function (like mark_plot(), arrow_plot(), line_plot(), trig_plot(), quad_plot(), text_plot()
), using vertex indexes as argument(s). AddPnt()
function use 2 mreal numbers for color specification. First one is positioning in textures – integer part is texture index, fractional part is relative coordinate in the texture. Second number is like a transparency of plot (or second coordinate in the 2D texture).
I don’t want to put here detailed description of mglBase
class. It was rather well documented in mgl2/base.h
file. I just show and example of its usage on the base of circle drawing.
First, we should prototype new function circle()
as C function.
#ifdef __cplusplus extern "C" { #endif void circle(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt); #ifdef __cplusplus } #endif
This is done for generating compiler independent binary. Because only C-functions have standard naming mechanism, the same for any compilers.
Now, we create a C++ file and put the code of function. I’ll write it line by line and try to comment all important points.
void circle(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt) {
First, we need to check all input arguments and send warnings if something is wrong. In our case it is negative value of r argument. We just send warning, since it is not critical situation – other plot still can be drawn.
if(r<=0) { gr->SetWarn(mglWarnNeg,"Circle"); return; }
Next step is creating a group. Group keep some general setting for plot (like options) and useful for export in 3d files.
static int cgid=1; gr->StartGroup("Circle",cgid++);
Now let apply options. Options are rather useful things, generally, which allow one easily redefine axis range(s), transparency and other settings (see Опции команд).
gr->SaveState(opt);
I use global setting for determining the number of points in circle approximation. Note, that user can change MeshNum
by options easily.
const int n = gr->MeshNum>1?gr->MeshNum : 41;
Let try to determine plot specific flags. MathGL functions expect that most of flags will be sent in string. In our case it is symbol ‘@’ which set to draw filled circle instead of border only (last will be default). Note, you have to handle NULL
as string pointer.
bool fill = mglchr(stl,'@');
Now, time for coloring. I use palette mechanism because circle have few colors: one for filling and another for border. SetPenPal()
function parse input string and write resulting texture index in pal. Function return the character for marker, which can be specified in string str. Marker will be plotted at the center of circle. I’ll show on next sample how you can use color schemes (smooth colors) too.
long pal=0; char mk=gr->SetPenPal(stl,&pal);
Next step, is determining colors for filling and for border. First one for filling.
mreal c=gr->NextColor(pal), d;
Second one for border. I use black color (call gr->AddTexture('k')
) if second color is not specified.
mreal k=(gr->GetNumPal(pal)>1)?gr->NextColor(pal):gr->AddTexture('k');
If user want draw only border (fill=false
) then I use first color for border.
if(!fill) k=c;
Now we should reserve space for vertexes. This functions need n
for border, n+1
for filling and 1
for marker. So, maximal number of vertexes is 2*n+2
. Note, that such reservation is not required for normal work but can sufficiently speed up the plotting.
gr->Reserve(2*n+2);
We’ve done with setup and ready to start drawing. First, we need to add vertex(es). Let define NAN as normals, since I don’t want handle lighting for this plot,
mglPoint q(NAN,NAN);
and start adding vertexes. First one for central point of filling. I use -1
if I don’t need this point. The arguments of AddPnt()
function is: mglPoint(x,y,z)
– coordinate of vertex, c
– vertex color, q
– normal at vertex, -1
– vertex transparency (-1
for default), 3
bitwise flag which show that coordinates will be scaled (0x1
) and will not be cutted (0x2
).
long n0,n1,n2,m1,m2,i; n0 = fill ? gr->AddPnt(mglPoint(x,y,z),c,q,-1,3):-1;
Similar for marker, but we use different color k.
n2 = mk ? gr->AddPnt(mglPoint(x,y,z),k,q,-1,3):-1;
Draw marker.
if(mk) gr->mark_plot(n2,mk);
Time for drawing circle itself. I use -1
for m1, n1 as sign that primitives shouldn’t be drawn for first point i=0
.
for(i=0,m1=n1=-1;i<n;i++) {
Each function should check Stop
variable and return if it is non-zero. It is done for interrupting drawing for system which don’t support multi-threading.
if(gr->Stop) return;
Let find coordinates of vertex.
mreal t = i*2*M_PI/(n-1.); mglPoint p(x+r*cos(t), y+r*sin(t), z);
Save previous vertex and add next one
n2 = n1; n1 = gr->AddPnt(p,c,q,-1,3);
and copy it for border but with different color. Such copying is much faster than adding new vertex using AddPnt()
.
m2 = m1; m1 = gr->CopyNtoC(n1,k);
Now draw triangle for filling internal part
if(fill) gr->trig_plot(n0,n1,n2);
and draw line for border.
gr->line_plot(m1,m2); }
Drawing is done. Let close group and return.
gr->EndGroup(); }
Another sample I want to show is exactly the same function but with smooth coloring using color scheme. So, I’ll add comments only in the place of difference.
void circle_cs(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt) {
In this case let allow negative radius too. Formally it is not the problem for plotting (formulas the same) and this allow us to handle all color range.
//if(r<=0) { gr->SetWarn(mglWarnNeg,"Circle"); return; } static int cgid=1; gr->StartGroup("CircleCS",cgid++); gr->SaveState(opt); const int n = gr->MeshNum>1?gr->MeshNum : 41; bool fill = mglchr(stl,'@');
Here is main difference. We need to create texture for color scheme specified by user
long ss = gr->AddTexture(stl);
But we need also get marker and color for it (if filling is enabled). Let suppose that marker and color is specified after ‘:’. This is standard delimiter which stop color scheme entering. So, just lets find it and use for setting pen.
const char *pen=0; if(stl) pen = strchr(stl,':'); if(pen) pen++;
The substring is placed in pen and it will be used as line style.
long pal=0; char mk=gr->SetPenPal(pen,&pal);
Next step, is determining colors for filling and for border. First one for filling.
mreal c=gr->GetC(ss,r);
Second one for border.
mreal k=gr->NextColor(pal);
The rest part is the same as in previous function.
if(!fill) k=c; gr->Reserve(2*n+2); mglPoint q(NAN,NAN); long n0,n1,n2,m1,m2,i; n0 = fill ? gr->AddPnt(mglPoint(x,y,z),c,q,-1,3):-1; n2 = mk ? gr->AddPnt(mglPoint(x,y,z),k,q,-1,3):-1; if(mk) gr->mark_plot(n2,mk); for(i=0,m1=n1=-1;i<n;i++) { if(gr->Stop) return; mreal t = i*2*M_PI/(n-1.); mglPoint p(x+r*cos(t), y+r*sin(t), z); n2 = n1; n1 = gr->AddPnt(p,c,q,-1,3); m2 = m1; m1 = gr->CopyNtoC(n1,k); if(fill) gr->trig_plot(n0,n1,n2); gr->line_plot(m1,m2); } gr->EndGroup(); }
The last thing which we can do is derive our own class with new plotting functions. Good idea is to derive it from mglGraph
(if you don’t need extended window), or from mglWindow
(if you need to extend window). So, in our case it will be
class MyGraph : public mglGraph { public: inline void Circle(mglPoint p, mreal r, const char *stl="", const char *opt="") { circle(p.x,p.y,p.z, r, stl, opt); } inline void CircleCS(mglPoint p, mreal r, const char *stl="", const char *opt="") { circle_cs(p.x,p.y,p.z, r, stl, opt); } };
Note, that I use inline
modifier for using the same binary code with different compilers.
So, the complete sample will be
#include <mgl2/mgl.h> //--------------------------------------------------------- #ifdef __cplusplus extern "C" { #endif void circle(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt); void circle_cs(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt); #ifdef __cplusplus } #endif //--------------------------------------------------------- class MyGraph : public mglGraph { public: inline void CircleCF(mglPoint p, mreal r, const char *stl="", const char *opt="") { circle(p.x,p.y,p.z, r, stl, opt); } inline void CircleCS(mglPoint p, mreal r, const char *stl="", const char *opt="") { circle_cs(p.x,p.y,p.z, r, stl, opt); } }; //--------------------------------------------------------- void circle(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt) { if(r<=0) { gr->SetWarn(mglWarnNeg,"Circle"); return; } static int cgid=1; gr->StartGroup("Circle",cgid++); gr->SaveState(opt); const int n = gr->MeshNum>1?gr->MeshNum : 41; bool fill = mglchr(stl,'@'); long pal=0; char mk=gr->SetPenPal(stl,&pal); mreal c=gr->NextColor(pal), d; mreal k=(gr->GetNumPal(pal)>1)?gr->NextColor(pal):gr->AddTexture('k'); if(!fill) k=c; gr->Reserve(2*n+2); mglPoint q(NAN,NAN); long n0,n1,n2,m1,m2,i; n0 = fill ? gr->AddPnt(mglPoint(x,y,z),c,q,-1,3):-1; n2 = mk ? gr->AddPnt(mglPoint(x,y,z),k,q,-1,3):-1; if(mk) gr->mark_plot(n2,mk); for(i=0,m1=n1=-1;i<n;i++) { if(gr->Stop) return; mreal t = i*2*M_PI/(n-1.); mglPoint p(x+r*cos(t), y+r*sin(t), z); n2 = n1; n1 = gr->AddPnt(p,c,q,-1,3); m2 = m1; m1 = gr->CopyNtoC(n1,k); if(fill) gr->trig_plot(n0,n1,n2); gr->line_plot(m1,m2); } gr->EndGroup(); } //--------------------------------------------------------- void circle_cs(HMGL gr, mreal x, mreal y, mreal z, mreal r, const char *stl, const char *opt) { static int cgid=1; gr->StartGroup("CircleCS",cgid++); gr->SaveState(opt); const int n = gr->MeshNum>1?gr->MeshNum : 41; bool fill = mglchr(stl,'@'); long ss = gr->AddTexture(stl); const char *pen=0; if(stl) pen = strchr(stl,':'); if(pen) pen++; long pal=0; char mk=gr->SetPenPal(pen,&pal); mreal c=gr->GetC(ss,r); mreal k=gr->NextColor(pal); if(!fill) k=c; gr->Reserve(2*n+2); mglPoint q(NAN,NAN); long n0,n1,n2,m1,m2,i; n0 = fill ? gr->AddPnt(mglPoint(x,y,z),c,q,-1,3):-1; n2 = mk ? gr->AddPnt(mglPoint(x,y,z),k,q,-1,3):-1; if(mk) gr->mark_plot(n2,mk); for(i=0,m1=n1=-1;i<n;i++) { if(gr->Stop) return; mreal t = i*2*M_PI/(n-1.); mglPoint p(x+r*cos(t), y+r*sin(t), z); n2 = n1; n1 = gr->AddPnt(p,c,q,-1,3); m2 = m1; m1 = gr->CopyNtoC(n1,k); if(fill) gr->trig_plot(n0,n1,n2); gr->line_plot(m1,m2); } gr->EndGroup(); } //--------------------------------------------------------- int main() { MyGraph gr; gr.Box(); // first let draw circles with fixed colors for(int i=0;i<10;i++) gr.CircleCF(mglPoint(2*mgl_rnd()-1, 2*mgl_rnd()-1), mgl_rnd()); // now let draw circles with color scheme for(int i=0;i<10;i++) gr.CircleCS(mglPoint(2*mgl_rnd()-1, 2*mgl_rnd()-1), 2*mgl_rnd()-1); }
mglData
class have abstract predecessor class mglDataA
. Exactly the pointers to mglDataA
instances are used in all plotting functions and some of data processing functions. This was done for taking possibility to define yours own class, which will handle yours own data (for example, complex numbers, or differently organized data). And this new class will be almost the same as mglData
for plotting purposes.
However, the most of data processing functions will be slower as if you used mglData
instance. This is more or less understandable – I don’t know how data in yours particular class will be organized, and couldn’t optimize the these functions generally.
There are few virtual functions which must be provided in derived classes. This functions give:
GetNx
, GetNy
, GetNz
),
v
, dvx
, dvy
, dvz
),
Maximal
, Minimal
) – you can use provided functions (like mgl_data_max
and mgl_data_min
), but yours own realization can be more efficient,
vthr
) – you need this only if you want using MathGL’s data processing functions.
Let me, for example define class mglComplex
which will handle complex number and draw its amplitude or phase, depending on flag use_abs:
#include <complex> #include <mgl2/mgl.h> #define dual std::complex<double> class mglComplex : public mglDataA { public: long nx; ///< number of points in 1st dimensions ('x' dimension) long ny; ///< number of points in 2nd dimensions ('y' dimension) long nz; ///< number of points in 3d dimensions ('z' dimension) dual *a; ///< data array bool use_abs; ///< flag to use abs() or arg() inline mglComplex(long xx=1,long yy=1,long zz=1) { a=0; use_abs=true; Create(xx,yy,zz); } virtual ~mglComplex() { if(a) delete []a; } /// Get sizes inline long GetNx() const { return nx; } inline long GetNy() const { return ny; } inline long GetNz() const { return nz; } /// Create or recreate the array with specified size and fill it by zero inline void Create(long mx,long my=1,long mz=1) { nx=mx; ny=my; nz=mz; if(a) delete []a; a = new dual[nx*ny*nz]; } /// Get maximal value of the data inline mreal Maximal() const { return mgl_data_max(this); } /// Get minimal value of the data inline mreal Minimal() const { return mgl_data_min(this); } protected: inline mreal v(long i,long j=0,long k=0) const { return use_abs ? abs(a[i+nx*(j+ny*k)]) : arg(a[i+nx*(j+ny*k)]); } inline mreal vthr(long i) const { return use_abs ? abs(a[i]) : arg(a[i]); } inline mreal dvx(long i,long j=0,long k=0) const { long i0=i+nx*(j+ny*k); std::complex<double> res=i>0? (i<nx-1? (a[i0+1]-a[i0-1])/2.:a[i0]-a[i0-1]) : a[i0+1]-a[i0]; return use_abs? abs(res) : arg(res); } inline mreal dvy(long i,long j=0,long k=0) const { long i0=i+nx*(j+ny*k); std::complex<double> res=j>0? (j<ny-1? (a[i0+nx]-a[i0-nx])/2.:a[i0]-a[i0-nx]) : a[i0+nx]-a[i0]; return use_abs? abs(res) : arg(res); } inline mreal dvz(long i,long j=0,long k=0) const { long i0=i+nx*(j+ny*k), n=nx*ny; std::complex<double> res=k>0? (k<nz-1? (a[i0+n]-a[i0-n])/2.:a[i0]-a[i0-n]) : a[i0+n]-a[i0]; return use_abs? abs(res) : arg(res); } }; int main() { mglComplex dat(20); for(long i=0;i<20;i++) dat.a[i] = 3*exp(-0.05*(i-10)*(i-10))*dual(cos(M_PI*i*0.3), sin(M_PI*i*0.3)); mglGraph gr; gr.SetRange('y', -M_PI, M_PI); gr.Box(); gr.Plot(dat,"r","legend 'abs'"); dat.use_abs=false; gr.Plot(dat,"b","legend 'arg'"); gr.Legend(); gr.WritePNG("complex.png"); return 0; }
Structure for working with colors. This structure is defined in #include <mgl2/type.h>
.
There are two ways to set the color in MathGL. First one is using of mreal values of red, green and blue channels for precise color definition. The second way is the using of character id. There are a set of characters specifying frequently used colors. Normally capital letter gives more dark color than lowercase one. See Стиль линий.
mglColor
: mreal
r, g, b, a ¶Reg, green and blue component of color.
mglColor
:
mglColor (mreal
R, mreal
G, mreal
B, mreal
A=1
)
¶Constructor sets the color by mreal values of Red, Green, Blue and Alpha channels. These values should be in interval [0,1].
mglColor
:
mglColor (char
c='k'
, mreal
bright=1
)
¶Constructor sets the color from character id. The black color is used by default. Parameter br set additional “lightness” of color.
mglColor
: void
Set (mreal
R, mreal
G, mreal
B, mreal
A=1
)
¶Sets color from values of Red, Green, Blue and Alpha channels. These values should be in interval [0,1].
mglColor
: void
Set (mglColor
c, mreal
bright=1
)
¶Sets color as “lighted” version of color c.
mglColor
: void
Set (char
p, mreal
bright=1
)
¶Sets color from symbolic id.
mglColor
: bool
Valid ()
¶Checks correctness of the color.
mglColor
: mreal
Norm ()
¶Gets maximal of spectral component.
mglColor
: bool
operator== (const mglColor &
c)
¶mglColor
: bool
operator!= (const mglColor &
c)
¶Compare with another color
mglColor
: bool
operator*= (mreal
v)
¶Multiplies color components by number v.
mglColor
: bool
operator+= (const mglColor &
c)
¶Adds color c component by component.
mglColor
: bool
operator-= (const mglColor &
c)
¶Subtracts color c component by component.
mglColor
operator+ (const mglColor &
a, const mglColor &
b)
¶Adds colors by its RGB values.
mglColor
operator- (const mglColor &
a, const mglColor &
b)
¶Subtracts colors by its RGB values.
mglColor
operator* (const mglColor &
a, mreal
b)
¶mglColor
operator* (mreal
a, const mglColor &
b)
¶Multiplies color by number.
mglColor
operator/ (const mglColor &
a, mreal
b)
¶Divide color by number.
mglColor
operator! (const mglColor &
a)
¶Return inverted color.
Structure describes point in space. This structure is defined in #include <mgl2/type.h>
mglPoint
: mreal
x, y, z, c ¶Point coordinates {x,y,z} and one extra value c used for amplitude, transparency and so on. By default all values are zero.
mglPoint
:
mglPoint (mreal
X=0
, mreal
Y=0
, mreal
Z=0
, mreal
C=0
)
¶Constructor sets the color by mreal values of Red, Green, Blue and Alpha channels. These values should be in interval [0,1].
mglPoint
: bool
IsNAN ()
¶Returns true
if point contain NAN values.
mglPoint
: mreal
norm ()
¶Returns the norm \sqrt{x^2+y^2+z^2} of vector.
mglPoint
: void
Normalize ()
¶Normalizes vector to be unit vector.
mglPoint
: mreal
val (int
i)
¶Returns point component: x for i=0, y for i=1, z for i=2, c for i=3.
mglPoint
operator+ (const mglPoint &
a, const mglPoint &
b)
¶Point of summation (summation of vectors).
mglPoint
operator- (const mglPoint &
a, const mglPoint &
b)
¶Point of difference (difference of vectors).
mglPoint
operator* (mreal
a, const mglPoint &
b)
¶mglPoint
operator* (const mglPoint &
a, mreal
b)
¶Multiplies (scale) points by number.
mglPoint
operator/ (const mglPoint &
a, mreal
b)
¶Multiplies (scale) points by number 1/b.
mreal
operator* (const mglPoint &
a, const mglPoint &
b)
¶Scalar product of vectors.
mglPoint
operator/ (const mglPoint &
a, const mglPoint &
b)
¶Return vector of element-by-element product.
mglPoint
operator^ (const mglPoint &
a, const mglPoint &
b)
¶Cross-product of vectors.
mglPoint
operator& (const mglPoint &
a, const mglPoint &
b)
¶The part of a which is perpendicular to vector b.
mglPoint
operator| (const mglPoint &
a, const mglPoint &
b)
¶The part of a which is parallel to vector b.
mglPoint
operator! (const mglPoint &
a)
¶Return vector perpendicular to vector a.
mreal
mgl_norm (const mglPoint &
a)
¶Return the norm sqrt(|a|^2) of vector a.
bool
operator== (const mglPoint &
a, const mglPoint &
b)
¶Return true if points are the same.
bool
operator!= (const mglPoint &
a, const mglPoint &
b)
¶Return true if points are different.
This chapter contain alphabetical list of MGL and C++ samples for most of MathGL graphics and features.
This section contain functions for input data for most of further samples.
MGL code:
func 'prepare1d' new y 50 3 modify y '0.7*sin(2*pi*x)+0.5*cos(3*pi*x)+0.2*sin(pi*x)' modify y 'sin(2*pi*x)' 1 modify y 'cos(2*pi*x)' 2 new x1 50 'x' new x2 50 '0.05-0.03*cos(pi*x)' new y1 50 '0.5-0.3*cos(pi*x)' new y2 50 '-0.3*sin(pi*x)' return func 'prepare2d' new a 50 40 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 50 40 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' return func 'prepare3d' new c 61 50 40 '-2*(x^2+y^2+z^4-z^2)+0.2' new d 61 50 40 '1-2*tanh((x+y)*(x+y))' return func 'prepare2v' new a 20 30 '0.6*sin(pi*(x+1))*sin(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' new b 20 30 '0.6*cos(pi*(x+1))*cos(1.5*pi*(y+1))+0.4*cos(0.75*pi*(x+1)*(y+1))' return func 'prepare3v' define $1 pow(x*x+y*y+(z-0.3)*(z-0.3)+0.03,1.5) define $2 pow(x*x+y*y+(z+0.3)*(z+0.3)+0.03,1.5) new ex 10 10 10 '0.2*x/$1-0.2*x/$2' new ey 10 10 10 '0.2*y/$1-0.2*y/$2' new ez 10 10 10 '0.2*(z-0.3)/$1-0.2*(z+0.3)/$2' return
C++ code:
void mgls_prepare1d(mglData *y, mglData *y1, mglData *y2, mglData *x1, mglData *x2) { long n=50; if(y) y->Create(n,3); if(x1) x1->Create(n); if(x2) x2->Create(n); if(y1) y1->Create(n); if(y2) y2->Create(n); for(long i=0;i<n;i++) { double xx = i/(n-1.); if(y) { y->a[i] = 0.7*sin(2*M_PI*xx) + 0.5*cos(3*M_PI*xx) + 0.2*sin(M_PI*xx); y->a[i+n] = sin(2*M_PI*xx); y->a[i+2*n] = cos(2*M_PI*xx); } if(y1) y1->a[i] = 0.5+0.3*cos(2*M_PI*xx); if(y2) y2->a[i] = 0.3*sin(2*M_PI*xx); if(x1) x1->a[i] = xx*2-1; if(x2) x2->a[i] = 0.05+0.03*cos(2*M_PI*xx); } } //----------------------------------------------------------------------------- void mgls_prepare2d(mglData *a, mglData *b, mglData *v) { long n=50,m=40; if(a) a->Create(n,m); if(b) b->Create(n,m); if(v) { v->Create(9); v->Fill(-1,1); } for(long j=0;j<m;j++) for(long i=0;i<n;i++) { double x = i/(n-1.), y = j/(m-1.); long i0 = i+n*j; if(a) a->a[i0] = 0.6*sin(2*M_PI*x)*sin(3*M_PI*y)+0.4*cos(3*M_PI*x*y); if(b) b->a[i0] = 0.6*cos(2*M_PI*x)*cos(3*M_PI*y)+0.4*cos(3*M_PI*x*y); } } //----------------------------------------------------------------------------- void mgls_prepare3d(mglData *a, mglData *b) { long n=61,m=50,l=40; if(a) a->Create(n,m,l); if(b) b->Create(n,m,l); for(long k=0;k<l;k++) for(long j=0;j<m;j++) for(long i=0;i<n;i++) { double x=2*i/(n-1.)-1, y=2*j/(m-1.)-1, z=2*k/(l-1.)-1; long i0 = i+n*(j+m*k); if(a) a->a[i0] = -2*(x*x + y*y + z*z*z*z - z*z - 0.1); if(b) b->a[i0] = 1-2*tanh((x+y)*(x+y)); } } //----------------------------------------------------------------------------- void mgls_prepare2v(mglData *a, mglData *b) { long n=20,m=30; if(a) a->Create(n,m); if(b) b->Create(n,m); for(long j=0;j<m;j++) for(long i=0;i<n;i++) { double x=i/(n-1.), y=j/(m-1.); long i0 = i+n*j; if(a) a->a[i0] = 0.6*sin(2*M_PI*x)*sin(3*M_PI*y)+0.4*cos(3*M_PI*x*y); if(b) b->a[i0] = 0.6*cos(2*M_PI*x)*cos(3*M_PI*y)+0.4*cos(3*M_PI*x*y); } } //----------------------------------------------------------------------------- void mgls_prepare3v(mglData *ex, mglData *ey, mglData *ez) { long n=10; double z0=0.3; if(!ex || !ey || !ez) return; ex->Create(n,n,n); ey->Create(n,n,n); ez->Create(n,n,n); for(long k=0;k<n;k++) for(long j=0;j<n;j++) for(long i=0;i<n;i++) { double x=2*i/(n-1.)-1, y=2*j/(n-1.)-1, z=2*k/(n-1.)-1; long i0 = i+n*(j+k*n); double r1 = pow(x*x+y*y+(z-z0)*(z-z0)+0.03,1.5); double r2 = pow(x*x+y*y+(z+z0)*(z+z0)+0.03,1.5); ex->a[i0]=0.2*x/r1 - 0.2*x/r2; ey->a[i0]=0.2*y/r1 - 0.2*y/r2; ez->a[i0]=0.2*(z-z0)/r1 - 0.2*(z+z0)/r2; } } //-----------------------------------------------------------------------------
Example of complex ode on basis of 3-wave decay.
MGL code:
define t 50 ode !r '-b*f;a*conj(f);a*conj(b)-0.1*f' 'abf' [1,1e-3,0] 0.1 t ranges 0 t 0 r.max plot r(0) 'b';legend 'a' plot r(1) 'g';legend 'b' plot r(2) 'r';legend 'f' axis:box:legend
C++ code:
void smgl_3wave(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Complex ODE sample"); double t=50; mglData ini; ini.SetList(3, 1., 1e-3, 0.); mglDataC r(mglODEc("-b*f;a*conj(f);a*conj(b)-0.1*f","abf",ini,0.1,t)); gr->SetRanges(0, t, 0, r.Maximal()); gr->Plot(r.SubData(0),"b","legend 'a'"); gr->Plot(r.SubData(1),"g","legend 'b'"); gr->Plot(r.SubData(2),"r","legend 'f'"); gr->Axis(); gr->Box(); gr->Legend(); }
Example of light and alpha (transparency).
MGL code:
call 'prepare2d' subplot 2 2 0:title 'default':rotate 50 60:box surf a subplot 2 2 1:title 'light on':rotate 50 60:box light on:surf a subplot 2 2 3:title 'light on; alpha on':rotate 50 60:box alpha on:surf a subplot 2 2 2:title 'alpha on':rotate 50 60:box light off:surf a
C++ code:
void smgl_alpha(mglGraph *gr) // alpha and lighting { 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); }
Comparison of advanced PDE solver (apde) and ordinary one (pde).
MGL code:
ranges -1 1 0 2 0 2 new ar 256 'exp(-2*(x+0.0)^2)' new ai 256 apde res1 'exp(-x^2-p^2)' ar ai 0.01:transpose res1 pde res2 'exp(-x^2-p^2)' ar ai 0.01 subplot 1 2 0 '_':title 'Advanced PDE solver' ranges 0 2 -1 1:crange res1 dens res1:box axis:xlabel '\i z':ylabel '\i x' text -0.5 0.2 'i\partial_z\i u = exp(-\i x^2+\partial_x^2)[\i u]' 'y' subplot 1 2 1 '_':title 'Simplified PDE solver' dens res2:box axis:xlabel '\i z':ylabel '\i x' text -0.5 0.2 'i\partial_z\i u \approx\ exp(-\i x^2)\i u+exp(\partial_x^2)[\i u]' 'y'
C++ code:
void smgl_apde(mglGraph *gr) { gr->SetRanges(-1,1,0,2,0,2); mglData ar(256), ai(256); gr->Fill(ar,"exp(-2*(x+0.0)^2)"); mglData res1(gr->APDE("exp(-x^2-p^2)",ar,ai,0.01)); res1.Transpose(); mglData res2(gr->PDE("exp(-x^2-p^2)",ar,ai,0.01)); gr->SubPlot(1,2,0,"_"); gr->Title("Advanced PDE solver"); gr->SetRanges(0,2,-1,1); gr->SetRange('c',res1); gr->Dens(res1); gr->Axis(); gr->Box(); gr->Label('x',"\\i z"); gr->Label('y',"\\i x"); gr->Puts(mglPoint(-0.5,0.2),"i\\partial_z\\i u = exp(-\\i x^2+\\partial_x^2)[\\i u]","y"); gr->SubPlot(1,2,1,"_"); gr->Title("Simplified PDE solver"); gr->Dens(res2); gr->Axis(); gr->Box(); gr->Label('x',"\\i z"); gr->Label('y',"\\i x"); gr->Puts(mglPoint(-0.5,0.2),"i\\partial_z\\i u \\approx\\ exp(-\\i x^2)\\i u+exp(\\partial_x^2)[\\i u]","y"); }
Function area fill the area between curve and axis plane. It support gradient filling if 2 colors per curve is specified.
MGL code:
call 'prepare1d' origin 0 0 0 subplot 2 2 0 '':title 'Area plot (default)':box:area y subplot 2 2 1 '':title '2 colors':box:area y 'cbgGyr' subplot 2 2 2 '':title '"!" style':box:area y '!' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 3:title '3d variant':rotate 50 60:box area xc yc z 'r' area xc -yc z 'b#'
C++ code:
void smgl_area(mglGraph *gr) { mglData y; mgls_prepare1d(&y); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Area plot (default)"); } gr->Box(); gr->Area(y); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Title("2 colors"); gr->Box(); gr->Area(y,"cbgGyr"); gr->SubPlot(2,2,2,""); gr->Title("'!' style"); gr->Box(); gr->Area(y,"!"); gr->SubPlot(2,2,3); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); mglData yc(30), xc(30), z(30); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); gr->Area(xc,yc,z,"r"); yc.Modify("-sin(pi*(2*x-1))"); gr->Area(xc,yc,z,"b#"); }
Example of subplot, inplot, rotate, aspect, shear.
MGL code:
subplot 2 2 0:box:text -1 1.1 'Just box' ':L' inplot 0.2 0.5 0.7 1 off:box:text 0 1.2 'InPlot example' subplot 2 2 1:title 'Rotate only':rotate 50 60:box subplot 2 2 2:title 'Rotate and Aspect':rotate 50 60:aspect 1 1 2:box subplot 2 2 3:title 'Shear':box 'c':shear 0.2 0.1:box
C++ code:
void smgl_aspect(mglGraph *gr) // transformation { gr->SubPlot(2,2,0); gr->Box(); gr->Puts(mglPoint(-1,1.1),"Just box",":L"); gr->InPlot(0.2,0.5,0.7,1,false); gr->Box(); gr->Puts(mglPoint(0,1.2),"InPlot example"); gr->SubPlot(2,2,1); gr->Title("Rotate only"); gr->Rotate(50,60); gr->Box(); gr->SubPlot(2,2,2); gr->Title("Rotate and Aspect"); gr->Rotate(50,60); gr->Aspect(1,1,2); gr->Box(); gr->SubPlot(2,2,3); gr->Title("Shear"); gr->Box("c"); gr->Shear(0.2,0.1); gr->Box(); }
Function axial draw surfaces of rotation for contour lines. You can draw wire surfaces (‘#’ style) or ones rotated in other directions (‘x’, ‘z’ styles).
MGL code:
call 'prepare2d' subplot 2 2 0:title 'Axial plot (default)':light on:alpha on:rotate 50 60:box:axial a subplot 2 2 1:title '"x" style;"." style':light on:rotate 50 60:box:axial a 'x.' subplot 2 2 2:title '"z" style':light on:rotate 50 60:box:axial a 'z' subplot 2 2 3:title '"\#" style':light on:rotate 50 60:box:axial a '#'
C++ code:
void smgl_axial(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Axial plot (default)"); } gr->Light(true); gr->Alpha(true); gr->Rotate(50,60); gr->Box(); gr->Axial(a); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'x' style; '.'style"); gr->Rotate(50,60); gr->Box(); gr->Axial(a,"x."); gr->SubPlot(2,2,2); gr->Title("'z' style"); gr->Rotate(50,60); gr->Box(); gr->Axial(a,"z"); gr->SubPlot(2,2,3); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Axial(a,"#"); }
Different forms of axis position.
MGL code:
subplot 2 2 0:title 'Axis origin, Grid':origin 0 0:axis:grid:fplot 'x^3' subplot 2 2 1:title '2 axis':ranges -1 1 -1 1:origin -1 -1:axis:ylabel 'axis_1':fplot 'sin(pi*x)' 'r2' ranges 0 1 0 1:origin 1 1:axis:ylabel 'axis_2':fplot 'cos(pi*x)' subplot 2 2 3:title 'More axis':origin nan nan:xrange -1 1:axis:xlabel 'x' 0:ylabel 'y_1' 0:fplot 'x^2' 'k' yrange -1 1:origin -1.3 -1:axis 'y' 'r':ylabel '#r{y_2}' 0.2:fplot 'x^3' 'r' subplot 2 2 2:title '4 segments, inverted axis':origin 0 0: inplot 0.5 1 0.5 1 on:ranges 0 10 0 2:axis fplot 'sqrt(x/2)':xlabel 'W' 1:ylabel 'U' 1 inplot 0 0.5 0.5 1 on:ranges 1 0 0 2:axis 'x':fplot 'sqrt(x)+x^3':xlabel '\tau' 1 inplot 0.5 1 0 0.5 on:ranges 0 10 4 0:axis 'y':fplot 'x/4':ylabel 'L' -1 inplot 0 0.5 0 0.5 on:ranges 1 0 4 0:fplot '4*x^2'
C++ code:
void smgl_axis(mglGraph *gr) { gr->SubPlot(2,2,0); gr->Title("Axis origin, Grid"); gr->SetOrigin(0,0); gr->Axis(); gr->Grid(); gr->FPlot("x^3"); gr->SubPlot(2,2,1); gr->Title("2 axis"); gr->SetRanges(-1,1,-1,1); gr->SetOrigin(-1,-1,-1); // first axis gr->Axis(); gr->Label('y',"axis 1",0); gr->FPlot("sin(pi*x)","r2"); gr->SetRanges(0,1,0,1); gr->SetOrigin(1,1,1); // second axis gr->Axis(); gr->Label('y',"axis 2",0); gr->FPlot("cos(pi*x)"); gr->SubPlot(2,2,3); gr->Title("More axis"); gr->SetOrigin(NAN,NAN); gr->SetRange('x',-1,1); gr->Axis(); gr->Label('x',"x",0); gr->Label('y',"y_1",0); gr->FPlot("x^2","k"); gr->SetRanges(-1,1,-1,1); gr->SetOrigin(-1.3,-1); // second axis gr->Axis("y","r"); gr->Label('y',"#r{y_2}",0.2); gr->FPlot("x^3","r"); gr->SubPlot(2,2,2); gr->Title("4 segments, inverted axis"); gr->SetOrigin(0,0); gr->InPlot(0.5,1,0.5,1); gr->SetRanges(0,10,0,2); gr->Axis(); gr->FPlot("sqrt(x/2)"); gr->Label('x',"W",1); gr->Label('y',"U",1); gr->InPlot(0,0.5,0.5,1); gr->SetRanges(1,0,0,2); gr->Axis("x"); gr->FPlot("sqrt(x)+x^3"); gr->Label('x',"\\tau",-1); gr->InPlot(0.5,1,0,0.5); gr->SetRanges(0,10,4,0); gr->Axis("y"); gr->FPlot("x/4"); gr->Label('y',"L",-1); gr->InPlot(0,0.5,0,0.5); gr->SetRanges(1,0,4,0); gr->FPlot("4*x^2"); }
Load background from an image file.
MGL code:
define $f udav_new.png #background '$f' 's' subplot 2 2 0 '':box background '$f' 'a' text 0.5 0.1 'Default' 'a' subplot 2 2 1 '':box background '$f' 'ca' text 0.5 0.1 'Centering' 'a' subplot 2 2 2 '':box background '$f' 'ma' text 0.5 0.1 'Mosaic' 'a' subplot 2 2 3 '':box background '$f' 'sa' text 0.5 0.1 'Scaling' 'a'
C++ code:
void smgl_background(mglGraph *gr) { const char *fname = "udav_new.png"; gr->SubPlot(2,2,0,""); gr->Box(); gr->LoadBackground(fname,"a"); gr->Puts(0.5,0.1,"Default","a"); gr->SubPlot(2,2,1,""); gr->Box(); gr->LoadBackground(fname,"ca"); gr->Puts(0.5,0.1,"Centering","a"); gr->SubPlot(2,2,2,""); gr->Box(); gr->LoadBackground(fname,"ma"); gr->Puts(0.5,0.1,"Mosaic","a"); gr->SubPlot(2,2,3,""); gr->Box(); gr->LoadBackground(fname,"sa"); gr->Puts(0.5,0.1,"Scaling","a"); //gr->LoadBackground(fname,"s"); }
Function barh is the similar to bars but draw horizontal bars.
MGL code:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd':origin 0 0 0 subplot 2 2 0 '':title 'Barh plot (default)':box:barh ys subplot 2 2 1 '':title '2 colors':box:barh ys 'cbgGyr' ranges -3 3 -1 1:subplot 2 2 2 '':title '"a" style':box:barh ys 'a' subplot 2 2 3 '': title '"f" style':box:barh ys 'f'
C++ code:
void smgl_barh(mglGraph *gr) { mglData ys(10,3); ys.Modify("0.8*sin(pi*(2*x+y/2))+0.2*rnd"); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Barh plot (default)"); } gr->Box(); gr->Barh(ys); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Title("2 colors"); gr->Box(); gr->Barh(ys,"cbgGyr"); gr->SetRanges(-3,3,-1,1); // increase range since summation can exceed [-1,1] gr->SubPlot(2,2,2,""); gr->Title("'a' style"); gr->Box(); gr->Barh(ys,"a"); gr->SubPlot(2,2,3,""); gr->Title("'f' style"); gr->Box(); gr->Barh(ys,"f"); }
Function bars draw vertical bars. It have a lot of options: bar-above-bar (‘a’ style), fall like (‘f’ style), 2 colors for positive and negative values, wired bars (‘#’ style), 3D variant.
MGL code:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd':origin 0 0 0 subplot 3 2 0 '':title 'Bars plot (default)':box:bars ys subplot 3 2 1 '':title '2 colors':box:bars ys 'cbgGyr' subplot 3 2 4 '':title '"\#" style':box:bars ys '#' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 3 2 5:title '3d variant':rotate 50 60:box:bars xc yc z 'r' ranges -1 1 -3 3:subplot 3 2 2 '':title '"a" style':box:bars ys 'a' subplot 3 2 3 '':title '"f" style':box:bars ys 'f'
C++ code:
void smgl_bars(mglGraph *gr) { mglData ys(10,3); ys.Modify("0.8*sin(pi*(2*x+y/2))+0.2*rnd"); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(3,2,0,""); gr->Title("Bars plot (default)"); } gr->Box(); gr->Bars(ys); if(big==3) return; gr->SubPlot(3,2,1,""); gr->Title("2 colors"); gr->Box(); gr->Bars(ys,"cbgGyr"); gr->SubPlot(3,2,4,""); gr->Title("'\\#' style"); gr->Box(); gr->Bars(ys,"#"); gr->SubPlot(3,2,5); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); mglData yc(30), xc(30), z(30); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); gr->Bars(xc,yc,z,"r"); gr->SetRanges(-1,1,-3,3); // increase range since summation can exceed [-1,1] gr->SubPlot(3,2,2,""); gr->Title("'a' style"); gr->Box(); gr->Bars(ys,"a"); gr->SubPlot(3,2,3,""); gr->Title("'f' style"); gr->Box(); gr->Bars(ys,"f"); }
Function belt draw surface by belts. You can use ‘x’ style for drawing lines in other direction.
MGL code:
call 'prepare2d' title 'Belt plot':rotate 50 60:box:belt a
C++ code:
void smgl_belt(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) gr->Title("Belt plot"); gr->Rotate(50,60); gr->Box(); gr->Belt(a); }
Function beltc draw surface by belts. You can use ‘x’ style for drawing lines in other direction.
MGL code:
call 'prepare2d' title 'BeltC plot':rotate 50 60:box:beltc a b
C++ code:
void smgl_beltc(mglGraph *gr) { mglData a,b; mgls_prepare2d(&a,&b); if(big!=3) gr->Title("BeltC plot"); gr->Rotate(50,60); gr->Box(); gr->BeltC(a,b); }
Function bifurcation draw Bifurcation diagram for multiple stationary points of the map (like logistic map).
MGL code:
subplot 1 1 0 '<_':title 'Bifurcation sample' ranges 0 4 0 1:axis bifurcation 0.005 'x*y*(1-y)' 'r'
C++ code:
void smgl_bifurcation(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Bifurcation sample"); gr->SetRanges(0,4,0,1); gr->Axis(); gr->Bifurcation(0.005,"x*y*(1-y)","r"); }
Different styles of bounding box.
MGL code:
subplot 2 2 0:title 'Box (default)':rotate 50 60:box subplot 2 2 1:title 'colored':rotate 50 60:box 'r' subplot 2 2 2:title 'with faces':rotate 50 60:box '@' subplot 2 2 3:title 'both':rotate 50 60:box '@cm'
C++ code:
void smgl_boxplot(mglGraph *gr) // flow threads and density plot { mglData a(10,7); a.Modify("(2*rnd-1)^3/2"); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("Boxplot plot"); } gr->Box(); gr->BoxPlot(a); }
Function boxplot draw box-and-whisker diagram.
MGL code:
new a 10 7 '(2*rnd-1)^3/2' subplot 1 1 0 '':title 'Boxplot plot':box:boxplot a
C++ code:
void smgl_boxplot(mglGraph *gr) // flow threads and density plot { mglData a(10,7); a.Modify("(2*rnd-1)^3/2"); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("Boxplot plot"); } gr->Box(); gr->BoxPlot(a); }
Function boxs draw surface by boxes. You can use ‘#’ for drawing wire plot.
MGL code:
call 'prepare2d' origin 0 0 0 subplot 2 2 0:title 'Boxs plot (default)':rotate 40 60:light on:box:boxs a subplot 2 2 1:title '"\@" style':rotate 50 60:box:boxs a '@' subplot 2 2 2:title '"\#" style':rotate 50 60:box:boxs a '#' subplot 2 2 3:title 'compare with Tile':rotate 50 60:box:tile a
C++ code:
void smgl_boxs(mglGraph *gr) { mglData a; mgls_prepare2d(&a); gr->SetOrigin(0,0,0); gr->Light(true); if(big!=3) {gr->SubPlot(2,2,0); gr->Title("Boxs plot (default)");} gr->Rotate(40,60); gr->Box(); gr->Boxs(a); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'\\@' style"); gr->Rotate(50,60); gr->Box(); gr->Boxs(a,"@"); gr->SubPlot(2,2,2); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Boxs(a,"#"); gr->SubPlot(2,2,3); gr->Title("compare with Tile"); gr->Rotate(50,60); gr->Box(); gr->Tile(a); }
Function candle draw candlestick chart. This is a combination of a line-chart and a bar-chart, in that each bar represents the range of price movement over a given time interval.
MGL code:
new y 30 'sin(pi*x/2)^2' subplot 1 1 0 '':title 'Candle plot (default)' yrange 0 1:box candle y y/2 (y+1)/2
C++ code:
void smgl_candle(mglGraph *gr) { mglData y(30); gr->Fill(y,"sin(pi*x/2)^2"); mglData y1(30); gr->Fill(y1,"v/2",y); mglData y2(30); gr->Fill(y2,"(1+v)/2",y); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("Candle plot (default)"); } gr->SetRange('y',0,1); gr->Box(); gr->Candle(y,y1,y2); }
Function chart draw colored boxes with width proportional to data values. Use ‘ ’ for empty box. It produce well known pie chart if drawn in polar coordinates.
MGL code:
new ch 7 2 'rnd+0.1':light on subplot 2 2 0:title 'Chart plot (default)':rotate 50 60:box:chart ch subplot 2 2 1:title '"\#" style':rotate 50 60:box:chart ch '#' subplot 2 2 2:title 'Pie chart; " " color':rotate 50 60: axis '(y+1)/2*cos(pi*x)' '(y+1)/2*sin(pi*x)' '':box:chart ch 'bgr cmy#' subplot 2 2 3:title 'Ring chart; " " color':rotate 50 60: axis '(y+2)/3*cos(pi*x)' '(y+2)/3*sin(pi*x)' '':box:chart ch 'bgr cmy#'
C++ code:
void smgl_chart(mglGraph *gr) { mglData ch(7,2); for(int i=0;i<7*2;i++) ch.a[i]=mgl_rnd()+0.1; if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Chart plot (default)"); } gr->Light(true); gr->Rotate(50,60); gr->Box(); gr->Chart(ch); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Chart(ch,"#"); gr->SubPlot(2,2,2); gr->Title("Pie chart; ' ' color"); gr->SetFunc("(y+1)/2*cos(pi*x)","(y+1)/2*sin(pi*x)",""); gr->Rotate(50,60); gr->Box(); gr->Chart(ch,"bgr cmy#"); gr->SubPlot(2,2,3); gr->Title("Ring chart; ' ' color"); gr->SetFunc("(y+2)/3*cos(pi*x)","(y+2)/3*sin(pi*x)",""); gr->Rotate(50,60); gr->Box(); gr->Chart(ch,"bgr cmy#"); }
Function cloud draw cloud-like object which is less transparent for higher data values. Similar plot can be created using many (about 10...20 – surf3a a a;value 10
) isosurfaces surf3a.
MGL code:
call 'prepare3d' subplot 2 2 0:title 'Cloud plot':rotate 50 60:alpha on:box:cloud c 'wyrRk' subplot 2 2 1:title '"i" style':rotate 50 60:box:cloud c 'iwyrRk' subplot 2 2 2:title '"." style':rotate 50 60:box:cloud c '.wyrRk' subplot 2 2 3:title 'meshnum 10':rotate 50 60:box:cloud c 'wyrRk'; meshnum 10
C++ code:
void smgl_cloud(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Cloud plot"); } gr->Rotate(50,60); gr->Alpha(true); gr->Box(); gr->Cloud(c,"wyrRk"); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'i' style"); gr->Rotate(50,60); gr->Box(); gr->Cloud(c,"iwyrRk"); gr->SubPlot(2,2,2); gr->Title("'.' style"); gr->Rotate(50,60); gr->Box(); gr->Cloud(c,".wyrRk"); gr->SubPlot(2,2,3); gr->Title("meshnum 10"); gr->Rotate(50,60); gr->Box(); gr->Cloud(c,"wyrRk","meshnum 10"); }
Example of colorbar position and styles.
MGL code:
call 'prepare2d' new v 9 'x' subplot 2 2 0:title 'Colorbar out of box':box colorbar '<':colorbar '>':colorbar '_':colorbar '^' subplot 2 2 1:title 'Colorbar near box':box colorbar '<I':colorbar '>I':colorbar '_I':colorbar '^I' subplot 2 2 2:title 'manual colors':box:contd v a colorbar v '<':colorbar v '>':colorbar v '_':colorbar v '^' subplot 2 2 3:title '':text -0.5 1.55 'Color positions' ':C' -2 colorbar 'bwr>' 0.25 0:text -0.9 1.2 'Default' colorbar 'b{w,0.3}r>' 0.5 0:text -0.1 1.2 'Manual' crange 0.01 1e3 colorbar '>' 0.75 0:text 0.65 1.2 'Normal scale':colorbar '>':text 1.35 1.2 'Log scale'
C++ code:
void smgl_colorbar(mglGraph *gr) { gr->SubPlot(2,2,0); gr->Title("Colorbar out of box"); gr->Box(); gr->Colorbar("<"); gr->Colorbar(">"); gr->Colorbar("_"); gr->Colorbar("^"); gr->SubPlot(2,2,1); gr->Title("Colorbar near box"); gr->Box(); gr->Colorbar("<I"); gr->Colorbar(">I"); gr->Colorbar("_I"); gr->Colorbar("^I"); gr->SubPlot(2,2,2); gr->Title("manual colors"); mglData a,v; mgls_prepare2d(&a,0,&v); gr->Box(); gr->ContD(v,a); gr->Colorbar(v,"<"); gr->Colorbar(v,">"); gr->Colorbar(v,"_"); gr->Colorbar(v,"^"); gr->SubPlot(2,2,3); gr->Title(" "); gr->Puts(mglPoint(-0.5,1.55),"Color positions",":C",-2); gr->Colorbar("bwr>",0.25,0); gr->Puts(mglPoint(-0.9,1.2),"Default"); gr->Colorbar("b{w,0.3}r>",0.5,0); gr->Puts(mglPoint(-0.1,1.2),"Manual"); gr->Puts(mglPoint(1,1.55),"log-scale",":C",-2); gr->SetRange('c',0.01,1e3); gr->Colorbar(">",0.75,0); gr->Puts(mglPoint(0.65,1.2),"Normal scale"); gr->SetFunc("","","","lg(c)"); gr->Colorbar(">"); gr->Puts(mglPoint(1.35,1.2),"Log scale"); }
Example of several plots in the same axis.
MGL code:
call 'prepare2v' call 'prepare3d' new v 10:fill v -0.5 1:copy d sqrt(a^2+b^2) subplot 2 2 0:title 'Surf + Cont':rotate 50 60:light on:box:surf a:cont a 'y' subplot 2 2 1 '':title 'Flow + Dens':light off:box:flow a b 'br':dens d subplot 2 2 2:title 'Mesh + Cont':rotate 50 60:box:mesh a:cont a '_' subplot 2 2 3:title 'Surf3 + ContF3':rotate 50 60:light on box:contf3 v c 'z' 0:contf3 v c 'x':contf3 v c cut 0 -1 -1 1 0 1.1 contf3 v c 'z' c.nz-1:surf3 c -0.5
C++ code:
void smgl_combined(mglGraph *gr) // flow threads and density plot { 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); 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); }
Function cones is similar to bars but draw cones.
MGL code:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd' light on:origin 0 0 0 subplot 3 2 0:title 'Cones plot':rotate 50 60:box:cones ys subplot 3 2 1:title '2 colors':rotate 50 60:box:cones ys 'cbgGyr' subplot 3 2 2:title '"\#" style':rotate 50 60:box:cones ys '#' subplot 3 2 3:title '"a" style':rotate 50 60:zrange -2 2:box:cones ys 'a' subplot 3 2 4:title '"t" style':rotate 50 60:box:cones ys 't' subplot 3 2 5:title '"4" style':rotate 50 60:box:cones ys '4'
C++ code:
void smgl_cones(mglGraph *gr) { mglData ys(10,3); ys.Modify("0.8*sin(pi*(2*x+y/2))+0.2*rnd"); gr->Light(true); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(3,2,0); gr->Title("Cones plot"); } gr->Rotate(50,60); gr->Box(); gr->Cones(ys); if(big==3) return; gr->SubPlot(3,2,1); gr->Title("2 colors"); gr->Rotate(50,60); gr->Box(); gr->Cones(ys,"cbgGyr"); gr->SubPlot(3,2,2); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Cones(ys,"#"); gr->SubPlot(3,2,3); gr->Title("'a' style"); gr->SetRange('z',-2,2); // increase range since summation can exceed [-1,1] gr->Rotate(50,60); gr->Box(); gr->Cones(ys,"a"); gr->SubPlot(3,2,4); gr->Title("'t' style"); gr->Rotate(50,60); gr->Box(); gr->Cones(ys,"t"); gr->SubPlot(3,2,5); gr->Title("'4' style"); gr->Rotate(50,60); gr->Box(); gr->Cones(ys,"4"); }
Function cont draw contour lines for surface. You can select automatic (default) or manual levels for contours, print contour labels, draw it on the surface (default) or at plane (as Dens
).
MGL code:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 subplot 2 2 0:title 'Cont plot (default)':rotate 50 60:box:cont a subplot 2 2 1:title 'manual levels':rotate 50 60:box:cont v a subplot 2 2 2:title '"\_" and "." styles':rotate 50 60:box:cont a '_':cont a '_.2k' subplot 2 2 3 '':title '"t" style':box:cont a 't'
C++ code:
void smgl_cont3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("Cont3 sample"); gr->Rotate(50,60); gr->Box(); gr->Cont3(c,"x"); gr->Cont3(c); gr->Cont3(c,"z"); }
Function contf3 draw ordinary contour lines but at slices of 3D data.
MGL code:
call 'prepare3d' title 'Cont3 sample':rotate 50 60:box cont3 c 'x':cont3 c:cont3 c 'z'
C++ code:
void smgl_cont3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("Cont3 sample"); gr->Rotate(50,60); gr->Box(); gr->Cont3(c,"x"); gr->Cont3(c); gr->Cont3(c,"z"); }
Functions contz, conty, contx draw contour lines on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
MGL code:
call 'prepare3d' title 'Cont[XYZ] sample':rotate 50 60:box contx {sum c 'x'} '' -1:conty {sum c 'y'} '' 1:contz {sum c 'z'} '' -1
C++ code:
void smgl_cont_xyz(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("Cont[XYZ] sample"); gr->Rotate(50,60); gr->Box(); gr->ContX(c.Sum("x"),"",-1); gr->ContY(c.Sum("y"),"",1); gr->ContZ(c.Sum("z"),"",-1); }
Function contd is similar to contf but with manual contour colors.
MGL code:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 new a1 30 40 3 '0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) + 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)' subplot 2 2 0:title 'ContD plot (default)':rotate 50 60:box:contd a subplot 2 2 1:title 'manual levels':rotate 50 60:box:contd v a subplot 2 2 2:title '"\_" style':rotate 50 60:box:contd a '_' subplot 2 2 3:title 'several slices':rotate 50 60:box:contd a1
C++ code:
void smgl_contd(mglGraph *gr) { mglData a,v(5),a1(30,40,3); mgls_prepare2d(&a); v.a[0]=-0.5; v.a[1]=-0.15; v.a[2]=0; v.a[3]=0.15; v.a[4]=0.5; gr->Fill(a1,"0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) + 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)"); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("ContD plot (default)"); } gr->Rotate(50,60); gr->Box(); gr->ContD(a); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("manual levels"); gr->Rotate(50,60); gr->Box(); gr->ContD(v,a); gr->SubPlot(2,2,2); gr->Title("'\\_' style"); gr->Rotate(50,60); gr->Box(); gr->ContD(a,"_"); gr->SubPlot(2,2,3); gr->Title("several slices"); gr->Rotate(50,60); gr->Box(); gr->ContD(a1); }
Function contf draw filled contours. You can select automatic (default) or manual levels for contours.
MGL code:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 new a1 30 40 3 '0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) + 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)' subplot 2 2 0:title 'ContF plot (default)':rotate 50 60:box:contf a subplot 2 2 1:title 'manual levels':rotate 50 60:box:contf v a subplot 2 2 2:title '"\_" style':rotate 50 60:box:contf a '_' subplot 2 2 3:title 'several slices':rotate 50 60:box:contf a1
C++ code:
void smgl_contf3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("ContF3 sample"); gr->Rotate(50,60); gr->Light(true); gr->Box(); gr->ContF3(c,"x"); gr->ContF3(c); gr->ContF3(c,"z"); gr->Cont3(c,"kx"); gr->Cont3(c,"k"); gr->Cont3(c,"kz"); }
Function contf3 draw ordinary filled contours but at slices of 3D data.
MGL code:
call 'prepare3d' title 'Cont3 sample':rotate 50 60:box:light on contf3 c 'x':contf3 c:contf3 c 'z' cont3 c 'xk':cont3 c 'k':cont3 c 'zk'
C++ code:
void smgl_contf3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("ContF3 sample"); gr->Rotate(50,60); gr->Light(true); gr->Box(); gr->ContF3(c,"x"); gr->ContF3(c); gr->ContF3(c,"z"); gr->Cont3(c,"kx"); gr->Cont3(c,"k"); gr->Cont3(c,"kz"); }
Functions contfz, contfy, contfx, draw filled contours on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
MGL code:
call 'prepare3d' title 'ContF[XYZ] sample':rotate 50 60:box contfx {sum c 'x'} '' -1:contfy {sum c 'y'} '' 1:contfz {sum c 'z'} '' -1
C++ code:
void smgl_contf_xyz(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("ContF[XYZ] sample"); gr->Rotate(50,60); gr->Box(); gr->ContFX(c.Sum("x"),"",-1); gr->ContFY(c.Sum("y"),"",1); gr->ContFZ(c.Sum("z"),"",-1); }
Function conts get contour coordinate as data array.
MGL code:
new a 10 10 'sin(2*pi*x*y)' title 'Conts sample':rotate 40 60:box dens a '#' cont [0,0] a 'r' conts r 0 a plot 2*r(0)-1 2*r(1)-1 1+r(2) '2c'
C++ code:
void smgl_conts(mglGraph *gr) // test conts { mglData a(10,10); gr->Fill(a,"sin(2*pi*x*y)"); mglData v, r=a.Conts(0); if(big!=3) { gr->Title("Conts sample"); } gr->Rotate(40,60); gr->Box(); gr->Dens(a,"#"); gr->Cont(v,a,"r"); mglData x(r.ny),y(r.ny),z(r.ny); for(long i=0;i<x.nx;i++) { x[i]=r[r.nx*i]*2-1; y[i]=r[r.nx*i+1]*2-1; z[i]=1; } gr->Plot(x,y,z,"2c"); }
Function contv draw vertical cylinders (belts) at contour lines.
MGL code:
call 'prepare2d' list v -0.5 -0.15 0 0.15 0.5 subplot 2 2 0:title 'ContV plot (default)':rotate 50 60:box:contv a subplot 2 2 1:title 'manual levels':rotate 50 60:box:contv v a subplot 2 2 2:title '"\_" style':rotate 50 60:box:contv a '_' subplot 2 2 3:title 'ContV and ContF':rotate 50 60:light on:box contv a:contf a:cont a 'k'
C++ code:
void smgl_contv(mglGraph *gr) { mglData a,v(5); mgls_prepare2d(&a); v.a[0]=-0.5; v.a[1]=-0.15; v.a[2]=0; v.a[3]=0.15; v.a[4]=0.5; if(big!=3) { gr->SubPlot(2,2,0); gr->Title("ContV plot (default)"); } gr->Rotate(50,60); gr->Box(); gr->ContV(a); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("manual levels"); gr->Rotate(50,60); gr->Box(); gr->ContV(v,a); gr->SubPlot(2,2,2); gr->Title("'\\_' style"); gr->Rotate(50,60); gr->Box(); gr->ContV(a,"_"); gr->SubPlot(2,2,3); gr->Title("ContV and ContF"); gr->Rotate(50,60); gr->Box(); gr->Light(true); gr->ContV(a); gr->ContF(a); gr->Cont(a,"k"); }
Test of correlation function (correl).
MGL code:
new a 100 'exp(-10*x^2)' new b 100 'exp(-10*(x+0.5)^2)' yrange 0 1 subplot 1 2 0 '_':title 'Input fields' plot a:plot b:box:axis correl r a b 'x' norm r 0 1:swap r 'x' # make it human readable subplot 1 2 1 '_':title 'Correlation of a and b' plot r 'r':axis:box line 0.5 0 0.5 1 'B|'
C++ code:
void smgl_correl(mglGraph *gr) { mglData a(100),b(100); gr->Fill(a,"exp(-10*x^2)"); gr->Fill(b,"exp(-10*(x+0.5)^2)"); gr->SetRange('y',0,1); gr->SubPlot(1,2,0,"_"); gr->Title("Input fields"); gr->Plot(a); gr->Plot(b); gr->Axis(); gr->Box(); mglData r = a.Correl(b,"x"); r.Norm(0,1); r.Swap("x"); // make it human readable gr->SubPlot(1,2,1,"_"); gr->Title("Correlation of a and b"); gr->Plot(r,"r"); gr->Axis(); gr->Box(); gr->Line(mglPoint(0.5,0),mglPoint(0.5,1),"B|"); }
Some common curvilinear coordinates.
MGL code:
origin -1 1 -1 subplot 2 2 0:title 'Cartesian':rotate 50 60:fplot '2*t-1' '0.5' '0' '2r':axis:grid axis 'y*sin(pi*x)' 'y*cos(pi*x)' '':subplot 2 2 1:title 'Cylindrical':rotate 50 60:fplot '2*t-1' '0.5' '0' '2r':axis:grid axis '2*y*x' 'y*y - x*x' '':subplot 2 2 2:title 'Parabolic':rotate 50 60:fplot '2*t-1' '0.5' '0' '2r':axis:grid axis 'y*sin(pi*x)' 'y*cos(pi*x)' 'x+z':subplot 2 2 3:title 'Spiral':rotate 50 60:fplot '2*t-1' '0.5' '0' '2r':axis:grid
C++ code:
void smgl_curvcoor(mglGraph *gr) // curvilinear coordinates { gr->SetOrigin(-1,1,-1); gr->SubPlot(2,2,0); gr->Title("Cartesian"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc("y*sin(pi*x)","y*cos(pi*x)",0); gr->SubPlot(2,2,1); gr->Title("Cylindrical"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc("2*y*x","y*y - x*x",0); gr->SubPlot(2,2,2); gr->Title("Parabolic"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc("y*sin(pi*x)","y*cos(pi*x)","x+z"); gr->SubPlot(2,2,3); gr->Title("Spiral"); gr->Rotate(50,60); gr->FPlot("2*t-1","0.5","0","r2"); gr->Axis(); gr->Grid(); gr->SetFunc(0,0,0); // set to default Cartesian }
Example of point cutting (cut.
MGL code:
call 'prepare2d' call 'prepare3d' subplot 2 2 0:title 'Cut on (default)':rotate 50 60:light on:box:surf a; zrange -1 0.5 subplot 2 2 1:title 'Cut off':rotate 50 60:box:surf a; zrange -1 0.5; cut off subplot 2 2 2:title 'Cut in box':rotate 50 60:box:alpha on cut 0 -1 -1 1 0 1.1:surf3 c cut 0 0 0 0 0 0 # restore back subplot 2 2 3:title 'Cut by formula':rotate 50 60:box cut '(z>(x+0.5*y-1)^2-1) & (z>(x-0.5*y-1)^2-1)':surf3 c
C++ code:
void smgl_cut(mglGraph *gr) // cutting { mglData a,c,v(1); mgls_prepare2d(&a); mgls_prepare3d(&c); v.a[0]=0.5; gr->SubPlot(2,2,0); gr->Title("Cut on (default)"); gr->Rotate(50,60); gr->Light(true); gr->Box(); gr->Surf(a,"","zrange -1 0.5"); gr->SubPlot(2,2,1); gr->Title("Cut off"); gr->Rotate(50,60); gr->Box(); gr->Surf(a,"","zrange -1 0.5; cut off"); gr->SubPlot(2,2,2); gr->Title("Cut in box"); gr->Rotate(50,60); gr->SetCutBox(mglPoint(0,-1,-1), mglPoint(1,0,1.1)); gr->Alpha(true); gr->Box(); gr->Surf3(c); gr->SetCutBox(mglPoint(0), mglPoint(0)); // switch it off gr->SubPlot(2,2,3); gr->Title("Cut by formula"); gr->Rotate(50,60); gr->CutOff("(z>(x+0.5*y-1)^2-1) & (z>(x-0.5*y-1)^2-1)"); gr->Box(); gr->Surf3(c); gr->CutOff(""); // switch it off }
Example of subfunctions and summation in textual formulas.
MGL code:
title 'Advanced formulas' new b 256 256 'dsum(fn1(_i*pi/5),10)\exp(-64*(x*cos(_1)-y*sin(_1))^2-16*(0.5+y*cos(_1)+x*sin(_1))^2)' crange b:dens b 'BbwrR'
C++ code:
void smgl_daisy(mglGraph *gr) { if(big!=3) gr->Title("Advanced formulas"); mglData b(256,256); gr->Fill(b,"dsum(fn1(_i*pi/5),10)\\exp(-64*(x*cos(_1)-y*sin(_1))^2-16*(0.5+y*cos(_1)+x*sin(_1))^2)"); gr->SetRange('c',b); gr->Dens(b,"BbwrR"); }
Example of diff and integrate.
MGL code:
ranges 0 1 0 1 0 1:new a 30 40 'x*y' subplot 2 2 0:title 'a(x,y)':rotate 60 40:surf a:box subplot 2 2 1:title 'da/dx':rotate 60 40:diff a 'x':surf a:box subplot 2 2 2:title '\int da/dx dxdy':rotate 60 40:integrate a 'xy':surf a:box subplot 2 2 3:title '\int {d^2}a/dxdy dx':rotate 60 40:diff2 a 'y':surf a:box
C++ code:
void smgl_dat_diff(mglGraph *gr) // differentiate { gr->SetRanges(0,1,0,1,0,1); mglData a(30,40); a.Modify("x*y"); gr->SubPlot(2,2,0); gr->Title("a(x,y)"); gr->Rotate(60,40); gr->Surf(a); gr->Box(); gr->SubPlot(2,2,1); gr->Title("da/dx"); gr->Rotate(60,40); a.Diff("x"); gr->Surf(a); gr->Box(); gr->SubPlot(2,2,2); gr->Title("\\int da/dx dxdy"); gr->Rotate(60,40); a.Integral("xy"); gr->Surf(a); gr->Box(); gr->SubPlot(2,2,3); gr->Title("\\int {d^2}a/dxdy dx"); gr->Rotate(60,40); a.Diff2("y"); gr->Surf(a); gr->Box(); }
Example of envelop, sew, smooth and resize.
MGL code:
subplot 2 2 0 '':title 'Envelop sample':new d1 1000 'exp(-8*x^2)*sin(10*pi*x)' axis:plot d1 'b':envelop d1 'x':plot d1 'r' subplot 2 2 1 '':title 'Smooth sample':ranges 0 1 0 1 new y0 30 '0.4*sin(pi*x) + 0.3*cos(1.5*pi*x) - 0.4*sin(2*pi*x)+0.5*rnd' copy y1 y0:smooth y1 'x3':plot y1 'r';legend '"3" style' copy y2 y0:smooth y2 'x5':plot y2 'g';legend '"5" style' copy y3 y0:smooth y3 'x':plot y3 'b';legend 'default' plot y0 '{m7}:s';legend 'none' legend:box subplot 2 2 2:title 'Sew sample':rotate 50 60:light on:alpha on new d2 100 100 'mod((y^2-(1-x)^2)/2,0.1)' box:surf d2 'b':sew d2 'xy' 0.1:surf d2 'r' subplot 2 2 3:title 'Resize sample (interpolation)' new x0 10 'rnd':new v0 10 'rnd' resize x1 x0 100:resize v1 v0 100 plot x0 v0 'b+ ':plot x1 v1 'r-':label x0 v0 '%n'
C++ code:
void smgl_dat_extra(mglGraph *gr) // differentiate { gr->SubPlot(2,2,0,""); gr->Title("Envelop sample"); mglData d1(1000); gr->Fill(d1,"exp(-8*x^2)*sin(10*pi*x)"); gr->Axis(); gr->Plot(d1, "b"); d1.Envelop('x'); gr->Plot(d1, "r"); gr->SubPlot(2,2,1,""); gr->Title("Smooth sample"); mglData y0(30),y1,y2,y3; gr->SetRanges(0,1,0,1); gr->Fill(y0, "0.4*sin(pi*x) + 0.3*cos(1.5*pi*x) - 0.4*sin(2*pi*x)+0.5*rnd"); y1=y0; y1.Smooth("x3"); y2=y0; y2.Smooth("x5"); y3=y0; y3.Smooth("x"); gr->Plot(y0,"{m7}:s", "legend 'none'"); //gr->AddLegend("none","k"); gr->Plot(y1,"r", "legend ''3' style'"); gr->Plot(y2,"g", "legend ''5' style'"); gr->Plot(y3,"b", "legend 'default'"); gr->Legend(); gr->Box(); gr->SubPlot(2,2,2); gr->Title("Sew sample"); mglData d2(100, 100); gr->Fill(d2, "mod((y^2-(1-x)^2)/2,0.1)"); gr->Rotate(50, 60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf(d2, "b"); d2.Sew("xy", 0.1); gr->Surf(d2, "r"); gr->SubPlot(2,2,3); gr->Title("Resize sample (interpolation)"); mglData x0(10), v0(10), x1, v1; gr->Fill(x0,"rnd"); gr->Fill(v0,"rnd"); x1 = x0.Resize(100); v1 = v0.Resize(100); gr->Plot(x0,v0,"b+ "); gr->Plot(x1,v1,"r-"); gr->Label(x0,v0,"%n"); }
MGL code:
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)' light on:alpha on copy b a:diff b 'x':subplot 5 3 0:call 'splot' copy b a:diff2 b 'x':subplot 5 3 1:call 'splot' copy b a:cumsum b 'x':subplot 5 3 2:call 'splot' copy b a:integrate b 'x':subplot 5 3 3:call 'splot' mirror b 'x':subplot 5 3 4:call 'splot' copy b a:diff b 'y':subplot 5 3 5:call 'splot' copy b a:diff2 b 'y':subplot 5 3 6:call 'splot' copy b a:cumsum b 'y':subplot 5 3 7:call 'splot' copy b a:integrate b 'y':subplot 5 3 8:call 'splot' mirror b 'y':subplot 5 3 9:call 'splot' copy b a:diff b 'z':subplot 5 3 10:call 'splot' copy b a:diff2 b 'z':subplot 5 3 11:call 'splot' copy b a:cumsum b 'z':subplot 5 3 12:call 'splot' copy b a:integrate b 'z':subplot 5 3 13:call 'splot' mirror b 'z':subplot 5 3 14:call 'splot' stop func splot 0 title 'max=',b.max:norm b -1 1 on:rotate 70 60:box:surf3 b return
C++ code:
void smgl_data1(mglGraph *gr) // basic data operations { mglData a(40,50,60),b; gr->Fill(a,"exp(-x^2-4*y^2-16*z^2)"); gr->Light(true); gr->Alpha(true); b.Set(a); b.Diff("x"); gr->SubPlot(5,3,0); splot1(gr,b); b.Set(a); b.Diff2("x"); gr->SubPlot(5,3,1); splot1(gr,b); b.Set(a); b.CumSum("x"); gr->SubPlot(5,3,2); splot1(gr,b); b.Set(a); b.Integral("x");gr->SubPlot(5,3,3); splot1(gr,b); b.Mirror("x"); gr->SubPlot(5,3,4); splot1(gr,b); b.Set(a); b.Diff("y"); gr->SubPlot(5,3,5); splot1(gr,b); b.Set(a); b.Diff2("y"); gr->SubPlot(5,3,6); splot1(gr,b); b.Set(a); b.CumSum("y"); gr->SubPlot(5,3,7); splot1(gr,b); b.Set(a); b.Integral("y");gr->SubPlot(5,3,8); splot1(gr,b); b.Mirror("y"); gr->SubPlot(5,3,9); splot1(gr,b); b.Set(a); b.Diff("z"); gr->SubPlot(5,3,10);splot1(gr,b); b.Set(a); b.Diff2("z"); gr->SubPlot(5,3,11);splot1(gr,b); b.Set(a); b.CumSum("z"); gr->SubPlot(5,3,12);splot1(gr,b); b.Set(a); b.Integral("z");gr->SubPlot(5,3,13);splot1(gr,b); b.Mirror("z"); gr->SubPlot(5,3,14);splot1(gr,b); }
MGL code:
new a 40 50 60 'exp(-x^2-4*y^2-16*z^2)' light on:alpha on copy b a:sinfft b 'x':subplot 5 3 0:call 'splot' copy b a:cosfft b 'x':subplot 5 3 1:call 'splot' copy b a:hankel b 'x':subplot 5 3 2:call 'splot' copy b a:swap b 'x':subplot 5 3 3:call 'splot' copy b a:smooth b 'x':subplot 5 3 4:call 'splot' copy b a:sinfft b 'y':subplot 5 3 5:call 'splot' copy b a:cosfft b 'y':subplot 5 3 6:call 'splot' copy b a:hankel b 'y':subplot 5 3 7:call 'splot' copy b a:swap b 'y':subplot 5 3 8:call 'splot' copy b a:smooth b 'y':subplot 5 3 9:call 'splot' copy b a:sinfft b 'z':subplot 5 3 10:call 'splot' copy b a:cosfft b 'z':subplot 5 3 11:call 'splot' copy b a:hankel b 'z':subplot 5 3 12:call 'splot' copy b a:swap b 'z':subplot 5 3 13:call 'splot' copy b a:smooth b 'z':subplot 5 3 14:call 'splot' stop func splot 0 title 'max=',b.max:norm b -1 1 on:rotate 70 60:box surf3 b 0.5:surf3 b -0.5 return
C++ code:
void smgl_data2(mglGraph *gr) // data transforms { mglData a(40,50,60),b; gr->Fill(a,"exp(-x^2-4*y^2-16*z^2)"); gr->Light(true); gr->Alpha(true); b.Set(a); b.SinFFT("x"); gr->SubPlot(5,3,0); splot2(gr,b); b.Set(a); b.CosFFT("x"); gr->SubPlot(5,3,1); splot2(gr,b); b.Set(a); b.Hankel("x"); gr->SubPlot(5,3,2); splot2(gr,b); b.Set(a); b.Swap("x"); gr->SubPlot(5,3,3); splot2(gr,b); b.Set(a); b.Smooth("x"); gr->SubPlot(5,3,4); splot2(gr,b); b.Set(a); b.SinFFT("y"); gr->SubPlot(5,3,5); splot2(gr,b); b.Set(a); b.CosFFT("y"); gr->SubPlot(5,3,6); splot2(gr,b); b.Set(a); b.Hankel("y"); gr->SubPlot(5,3,7); splot2(gr,b); b.Set(a); b.Swap("y"); gr->SubPlot(5,3,8); splot2(gr,b); b.Set(a); b.Smooth("y"); gr->SubPlot(5,3,9); splot2(gr,b); b.Set(a); b.SinFFT("z"); gr->SubPlot(5,3,10);splot2(gr,b); b.Set(a); b.CosFFT("z"); gr->SubPlot(5,3,11);splot2(gr,b); b.Set(a); b.Hankel("z"); gr->SubPlot(5,3,12);splot2(gr,b); b.Set(a); b.Swap("z"); gr->SubPlot(5,3,13);splot2(gr,b); b.Set(a); b.Smooth("z"); gr->SubPlot(5,3,14);splot2(gr,b); }
Function dcont draw lines of intersections of two isosurfaces.
MGL code:
call 'prepare3d' title 'DCont plot':rotate 50 60:light on:alpha on:box:surf3 c 0 'r':surf3 d 0 'b' dcont 0 c d '2k'
C++ code:
void smgl_dcont(mglGraph *gr) { mglData c,d,v; mgls_prepare3d(&c,&d); if(big!=3) gr->Title("DCont plot"); gr->Rotate(50,60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf3(0,c,"r"); gr->Surf3(0,d,"b"); gr->DCont(v,c,d,"2k"); }
Function dens draw density plot (also known as color-map) for surface.
MGL code:
call 'prepare2d' new a1 30 40 3 '0.6*sin(2*pi*x+pi*(z+1)/2)*sin(3*pi*y+pi*z) + 0.4*cos(3*pi*(x*y)+pi*(z+1)^2/2)' subplot 2 2 0 '':title 'Dens plot (default)':box:dens a subplot 2 2 1:title '3d variant':rotate 50 60:box:dens a subplot 2 2 2 '':title '"\#" style; meshnum 10':box:dens a '#'; meshnum 10 subplot 2 2 3:title 'several slices':rotate 50 60:box:dens a1
C++ code:
void smgl_dens3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("Dens3 sample"); gr->Rotate(50,60); gr->Alpha(true); gr->SetAlphaDef(0.7); gr->SetOrigin(0,0,0); gr->Axis("_xyz"); gr->Box(); gr->Dens3(c,"x"); gr->Dens3(c); gr->Dens3(c,"z"); }
Function dens3 draw ordinary density plots but at slices of 3D data.
MGL code:
call 'prepare3d' title 'Dens3 sample':rotate 50 60:alpha on:alphadef 0.7 origin 0 0 0:box:axis '_xyz' dens3 c 'x':dens3 c ':y':dens3 c 'z'
C++ code:
void smgl_dens3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("Dens3 sample"); gr->Rotate(50,60); gr->Alpha(true); gr->SetAlphaDef(0.7); gr->SetOrigin(0,0,0); gr->Axis("_xyz"); gr->Box(); gr->Dens3(c,"x"); gr->Dens3(c); gr->Dens3(c,"z"); }
Functions densz, densy, densx draw density plot on plane perpendicular to corresponding axis. One of possible application is drawing projections of 3D field.
MGL code:
call 'prepare3d' title 'Dens[XYZ] sample':rotate 50 60:box densx {sum c 'x'} '' -1:densy {sum c 'y'} '' 1:densz {sum c 'z'} '' -1
C++ code:
void smgl_dens_xyz(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) gr->Title("Dens[XYZ] sample"); gr->Rotate(50,60); gr->Box(); gr->DensX(c.Sum("x"),0,-1); gr->DensY(c.Sum("y"),0,1); gr->DensZ(c.Sum("z"),0,-1); }
Example of curve detect.
MGL code:
subplot 1 1 0 '':title 'Detect sample' new a 200 100 'exp(-30*(y-0.5*sin(pi*x))^2-rnd/10)+exp(-30*(y+0.5*sin(pi*x))^2-rnd/10)+exp(-30*(x+y)^2-rnd/10)' ranges 0 a.nx 0 a.ny:box alpha on:crange a:dens a detect r a 0.1 5 plot r(0) r(1) '.'
C++ code:
void smgl_detect(mglGraph *gr) { mglData a(200, 100); gr->Fill(a,"exp(-30*(y-0.5*sin(pi*x))^2-rnd/10)+exp(-30*(y+0.5*sin(pi*x))^2-rnd/10)+exp(-30*(x+y)^2-rnd/10)"); gr->SubPlot(1,1,0,""); if(big!=3) gr->Title("Detect sample"); gr->SetRanges(0,a.nx,0,a.ny); gr->SetRange('c',a); gr->Alpha(true); gr->Box(); gr->Dens(a); mglData r(a.Detect(0.1,5)); gr->Plot(r.SubData(0), r.SubData(1), "."); }
Function dew is similar to vect but use drops instead of arrows.
MGL code:
call 'prepare2v' subplot 1 1 0 '':title 'Dew plot':light on:box:dew a b
C++ code:
void smgl_dew(mglGraph *gr) { mglData a,b; mgls_prepare2v(&a,&b); if(big!=3) {gr->SubPlot(1,1,0,""); gr->Title("Dew plot");} gr->Box(); gr->Light(true); gr->Dew(a,b); }
MGL code:
define n 32 #number of points define m 20 # number of iterations define dt 0.01 # time step new res n m+1 ranges -1 1 0 m*dt 0 1 #tridmat periodic variant new !a n 'i',dt*(n/2)^2/2 copy !b !(1-2*a) new !u n 'exp(-6*x^2)' put res u all 0 for $i 0 m tridmat u a b a u 'xdc' put res u all $i+1 next subplot 2 2 0 '<_':title 'Tridmat, periodic b.c.' axis:box:dens res #fourier variant new k n:fillsample k 'xk' copy !e !exp(-i1*dt*k^2) new !u n 'exp(-6*x^2)' put res u all 0 for $i 0 m fourier u 'x' multo u e fourier u 'ix' put res u all $i+1 next subplot 2 2 1 '<_':title 'Fourier method' axis:box:dens res #tridmat zero variant new !u n 'exp(-6*x^2)' put res u all 0 for $i 0 m tridmat u a b a u 'xd' put res u all $i+1 next subplot 2 2 2 '<_':title 'Tridmat, zero b.c.' axis:box:dens res #diffract exp variant new !u n 'exp(-6*x^2)' define q dt*(n/2)^2/8 # need q<0.4 !!! put res u all 0 for $i 0 m for $j 1 8 # due to smaller dt diffract u 'xe' q next put res u all $i+1 next subplot 2 2 3 '<_':title 'Diffract, exp b.c.' axis:box:dens res
C++ code:
void smgl_diffract(mglGraph *gr) { long n=32; // number of points long m=20; // number of iterations double dt=0.01; // time step mglData res(n,m+1); gr->SetRanges(-1,1, 0,m*dt, 0,1); // tridmat periodic variant mglDataC a(n), b(n); a = dual(0,dt*n*n/8); for(long i=0;i<n;i++) b.a[i] = mreal(1)-mreal(2)*a.a[i]; mglDataC u(n); gr->Fill(u,"exp(-6*x^2)"); res.Put(u,-1,0); for(long i=0;i<m;i++) { u = mglTridMatC(a,b,a,u,"xdc"); res.Put(u,-1,i+1); } gr->SubPlot(2,2,0,"<_"); gr->Title("Tridmat, periodic b.c."); gr->Axis(); gr->Box(); gr->Dens(res); // fourier variant mglData k(n); k.FillSample("xk"); mglDataC e(n); for(long i=0;i<n;i++) e.a[i] = exp(-dual(0,dt*k.a[i]*k.a[i])); gr->Fill(u,"exp(-6*x^2)"); res.Put(u,-1,0); for(long i=0;i<m;i++) { u.FFT("x"); u *= e; u.FFT("ix"); res.Put(u,-1,i+1); } gr->SubPlot(2,2,1,"<_"); gr->Title("Fourier method"); gr->Axis(); gr->Box(); gr->Dens(res); // tridmat zero variant gr->Fill(u,"exp(-6*x^2)"); res.Put(u,-1,0); for(long i=0;i<m;i++) { u = mglTridMatC(a,b,a,u,"xd"); res.Put(u,-1,i+1); } gr->SubPlot(2,2,2,"<_"); gr->Title("Tridmat, zero b.c."); gr->Axis(); gr->Box(); gr->Dens(res); // diffract exp variant gr->Fill(u,"exp(-6*x^2)"); res.Put(u,-1,0); double q=dt*n*n/4/8; // NOTE: need q<0.4 !!! for(long i=0;i<m;i++) { for(long j=0;j<8;j++) // due to smaller dt u.Diffraction("xe",q); res.Put(u,-1,i+1); } gr->SubPlot(2,2,3,"<_"); gr->Title("Diffract, exp b.c."); gr->Axis(); gr->Box(); gr->Dens(res); }
MGL code:
subplot 2 2 0:title 'Dilate&Erode 1D sample' new y 11:put y 1 5 ranges 0 10 0 1:axis:box plot y 'b*' dilate y 0.5 2 plot y 'rs' erode y 0.5 1 plot y 'g#o' subplot 2 2 1:title 'Dilate&Erode 2D sample':rotate 40 60 ranges 0 10 0 10 0 3 axis:box new z 11 11:put z 3 5 5 boxs z 'b':boxs z 'k#' dilate z 1 2 boxs z 'r':boxs z 'k#' erode z 1 1 boxs 2*z 'g':boxs 2*z 'k#' subplot 2 2 2 text 0.5 0.7 'initial' 'ba';size -2 text 0.5 0.5 'dilate=2' 'ra';size -2 text 0.5 0.3 'erode=1' 'ga';size -2 subplot 2 2 3:title 'Dilate&Erode 3D sample' rotate 60 50:light on:alpha on ranges 0 10 0 10 0 10:crange 0 3 axis:box new a 11 11 11:put a 3 5 5 5 surf3a a a 1.5 'b' dilate a 1 2 surf3a a a 0.5 'r' erode a 1 1 surf3a 2*a 2*a 1 'g'
C++ code:
void smgl_dilate(mglGraph *gr) { mglData y(11), z(11,11), a(11,11,11); y.a[5]=1; z.a[5+11*5]=a.a[5+11*(5+11*5)] = 3; if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Dilate&Erode 1D sample"); } else gr->SubPlot(1,1,0,""); gr->SetRanges(0,10,0,1); gr->Axis(); gr->Box(); gr->Plot(y,"b*"); y.Dilate(1,2); gr->Plot(y,"rs"); y.Erode(1,1); gr->Plot(y,"g#o"); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("Dilate&Erode 2D sample"); gr->Rotate(40,60); gr->SetRanges(0,10,0,10,0,3); gr->Axis(); gr->Box(); gr->Boxs(z,"b"); gr->Boxs(z,"k#"); z.Dilate(1,2); gr->Boxs(z,"r"); gr->Boxs(z,"k#"); z.Erode(1,1); z*=2; gr->Boxs(z,"g"); gr->Boxs(z,"k#"); gr->SubPlot(2,2,2); gr->Puts(0.5,0.7,"initial","ba",-2); gr->Puts(0.5,0.5,"dilate=2","ra",-2); gr->Puts(0.5,0.3,"erode=1","ga",-2); gr->SubPlot(2,2,3); gr->Title("Dilate&Erode 3D sample"); gr->Rotate(60,50); gr->Alpha(true); gr->Light(true); gr->SetRanges(0,10,0,10,0,10); gr->SetRange('c',0,3); gr->Axis(); gr->Box(); gr->Surf3A(1.5,a,a,"b"); a.Dilate(1,2); gr->Surf3A(0.5,a,a,"r"); a.Erode(1,1); a*=2; gr->Surf3A(1,a,a,"g"); }
Function dots is another way to draw irregular points. Dots
use color scheme for coloring (see Цветовая схема).
MGL code:
new t 2000 'pi*(rnd-0.5)':new f 2000 '2*pi*rnd' copy x 0.9*cos(t)*cos(f):copy y 0.9*cos(t)*sin(f):copy z 0.6*sin(t):copy c cos(2*t) subplot 2 2 0:title 'Dots sample':rotate 50 60 box:dots x y z alpha on subplot 2 2 1:title 'add transparency':rotate 50 60 box:dots x y z c subplot 2 2 2:title 'add colorings':rotate 50 60 box:dots x y z x c subplot 2 2 3:title 'Only coloring':rotate 50 60 box:tens x y z x ' .'
C++ code:
void smgl_dots(mglGraph *gr) { int i, n=1000; mglData x(n),y(n),z(n),c(n); for(i=0;i<n;i++) { double t=M_PI*(mgl_rnd()-0.5), f=2*M_PI*mgl_rnd(); x.a[i] = 0.9*cos(t)*cos(f); y.a[i] = 0.9*cos(t)*sin(f); z.a[i] = 0.6*sin(t); c.a[i] = cos(2*t); } if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Dots sample"); } gr->Rotate(50,60); gr->Box(); gr->Dots(x,y,z); if(big==3) return; gr->Alpha(true); gr->SubPlot(2,2,1); gr->Title("add transparency"); gr->Rotate(50,60); gr->Box(); gr->Dots(x,y,z,c); gr->SubPlot(2,2,2); gr->Title("add coloring"); gr->Rotate(50,60); gr->Box(); gr->Dots(x,y,z,x,c); gr->SubPlot(2,2,3); gr->Title("Only coloring"); gr->Rotate(50,60); gr->Box(); gr->Tens(x,y,z,x," ."); }
Example of Earth map by using import.
MGL code:
import dat 'Equirectangular-projection.jpg' 'BbGYw' -1 1 subplot 1 1 0 '<>':title 'Earth in 3D':rotate 40 60 copy phi dat 'pi*x':copy tet dat 'pi*y/2' copy x cos(tet)*cos(phi) copy y cos(tet)*sin(phi) copy z sin(tet) light on surfc x y z dat 'BbGYw' contp [-0.51,-0.51] x y z dat 'y'
C++ code:
void smgl_earth(mglGraph *gr) { mglData dat; dat.Import("Equirectangular-projection.jpg","BbGYw",-1,1); // Calc proper 3d coordinates from projection mglData phi(dat.nx,dat.ny); phi.Fill(-M_PI,M_PI); mglData tet(dat.nx,dat.ny); tet.Fill(-M_PI/2,M_PI/2,'y'); mglData x(dat.nx,dat.ny), y(dat.nx,dat.ny), z(dat.nx,dat.ny); #pragma omp parallel for for(long i=0;i<dat.nx*dat.ny;i++) { x.a[i] = cos(tet.a[i])*cos(phi.a[i]); y.a[i] = cos(tet.a[i])*sin(phi.a[i]); z.a[i] = sin(tet.a[i]); } gr->SubPlot(1,1,0,"<>"); if(big!=3) gr->Title("Earth in 3D"); gr->Rotate(40,60); gr->Light(true); gr->SurfC(x,y,z,dat,"BbGYw"); mglData vals(1); vals.a[0]=-0.51; gr->ContP(vals, x,y,z,dat,"y"); }
Function error draw error boxes around the points. You can draw default boxes or semi-transparent symbol (like marker, see Стиль линий). Also you can set individual color for each box. See also Sample ‘error2’.
MGL code:
call 'prepare1d' new y 50 '0.7*sin(pi*x-pi) + 0.5*cos(3*pi*(x+1)/2) + 0.2*sin(pi*(x+1)/2)' new x0 10 'x + 0.1*rnd-0.05':new ex 10 '0.1':new ey 10 '0.2' new y0 10 '0.7*sin(pi*x-pi) + 0.5*cos(3*pi*(x+1)/2) + 0.2*sin(pi*(x+1)/2) + 0.2*rnd-0.1' subplot 2 2 0 '':title 'Error plot (default)':box:plot y:error x0 y0 ex ey 'k' subplot 2 2 1 '':title '"!" style; no e_x':box:plot y:error x0 y0 ey 'o!rgb' subplot 2 2 2 '':title '"\@" style':alpha on:box:plot y:error x0 y0 ex ey '@'; alpha 0.5 subplot 2 2 3:title '3d variant':rotate 50 60:axis for $1 0 9 errbox 2*rnd-1 2*rnd-1 2*rnd-1 0.2 0.2 0.2 'bo' next
C++ code:
void smgl_error2(mglGraph *gr) { mglData x0(10), y0(10), ex(10), ey(10); for(int i=0;i<10;i++) { x0.a[i] = mgl_rnd(); y0.a[i] = mgl_rnd(); ey.a[i] = ex.a[i] = 0.1; } gr->SetRanges(0,1,0,1); gr->Alpha(true); gr->SubPlot(4,3,0,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#+@"); gr->SubPlot(4,3,1,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#x@"); gr->SubPlot(4,3,2,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#s@","alpha 0.5"); gr->SubPlot(4,3,3,""); gr->Box(); gr->Error(x0,y0,ex,ey,"s@"); gr->SubPlot(4,3,4,""); gr->Box(); gr->Error(x0,y0,ex,ey,"d@"); gr->SubPlot(4,3,5,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#d@","alpha 0.5"); gr->SubPlot(4,3,6,""); gr->Box(); gr->Error(x0,y0,ex,ey,"+@"); gr->SubPlot(4,3,7,""); gr->Box(); gr->Error(x0,y0,ex,ey,"x@"); gr->SubPlot(4,3,8,""); gr->Box(); gr->Error(x0,y0,ex,ey,"o@"); gr->SubPlot(4,3,9,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#o@","alpha 0.5"); gr->SubPlot(4,3,10,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#.@"); gr->SubPlot(4,3,11,""); gr->Box(); gr->Error(x0,y0,ex,ey); }
Example of error kinds.
MGL code:
new x0 10 'rnd':new ex 10 '0.1' new y0 10 'rnd':new ey 10 '0.1' ranges 0 1 0 1 subplot 4 3 0 '':box:error x0 y0 ex ey '#+@' subplot 4 3 1 '':box:error x0 y0 ex ey '#x@' subplot 4 3 2 '':box:error x0 y0 ex ey '#s@'; alpha 0.5 subplot 4 3 3 '':box:error x0 y0 ex ey 's@' subplot 4 3 4 '':box:error x0 y0 ex ey 'd@' subplot 4 3 5 '':box:error x0 y0 ex ey '#d@'; alpha 0.5 subplot 4 3 6 '':box:error x0 y0 ex ey '+@' subplot 4 3 7 '':box:error x0 y0 ex ey 'x@' subplot 4 3 8 '':box:error x0 y0 ex ey 'o@' subplot 4 3 9 '':box:error x0 y0 ex ey '#o@'; alpha 0.5 subplot 4 3 10 '':box:error x0 y0 ex ey '#.@' subplot 4 3 11 '':box:error x0 y0 ex ey; alpha 0.5
C++ code:
void smgl_error2(mglGraph *gr) { mglData x0(10), y0(10), ex(10), ey(10); for(int i=0;i<10;i++) { x0.a[i] = mgl_rnd(); y0.a[i] = mgl_rnd(); ey.a[i] = ex.a[i] = 0.1; } gr->SetRanges(0,1,0,1); gr->Alpha(true); gr->SubPlot(4,3,0,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#+@"); gr->SubPlot(4,3,1,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#x@"); gr->SubPlot(4,3,2,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#s@","alpha 0.5"); gr->SubPlot(4,3,3,""); gr->Box(); gr->Error(x0,y0,ex,ey,"s@"); gr->SubPlot(4,3,4,""); gr->Box(); gr->Error(x0,y0,ex,ey,"d@"); gr->SubPlot(4,3,5,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#d@","alpha 0.5"); gr->SubPlot(4,3,6,""); gr->Box(); gr->Error(x0,y0,ex,ey,"+@"); gr->SubPlot(4,3,7,""); gr->Box(); gr->Error(x0,y0,ex,ey,"x@"); gr->SubPlot(4,3,8,""); gr->Box(); gr->Error(x0,y0,ex,ey,"o@"); gr->SubPlot(4,3,9,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#o@","alpha 0.5"); gr->SubPlot(4,3,10,""); gr->Box(); gr->Error(x0,y0,ex,ey,"#.@"); gr->SubPlot(4,3,11,""); gr->Box(); gr->Error(x0,y0,ex,ey); }
Example of data export and import.
MGL code:
new a 100 100 'x^2*y':new b 100 100 export a 'test_data.png' 'BbcyrR' -1 1 import b 'test_data.png' 'BbcyrR' -1 1 subplot 2 1 0 '':title 'initial':box:dens a subplot 2 1 1 '':title 'imported':box:dens b
C++ code:
void smgl_export(mglGraph *gr) // basic data operations { mglData a(100,100), b; gr->Fill(a,"x^2*y"); a.Export("test_data.png","BbcyrR"); b.Import("test_data.png","BbcyrR",-1,1); gr->SubPlot(2,1,0,""); gr->Title("initial"); gr->Box(); gr->Dens(a); gr->SubPlot(2,1,1,""); gr->Title("imported"); gr->Box(); gr->Dens(b); }
Function fall draw waterfall surface. You can use meshnum for changing number of lines to be drawn. Also you can use ‘x’ style for drawing lines in other direction.
MGL code:
call 'prepare2d' title 'Fall plot':rotate 50 60:box:fall a
C++ code:
void smgl_fall(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) gr->Title("Fall plot"); gr->Rotate(50,60); gr->Box(); gr->Fall(a); }
Example of write to different file formats.
MGL code:
subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b' write 'fexport.jpg':#write 'fexport.png' write 'fexport.bmp':write 'fexport.tga' write 'fexport.eps':write 'fexport.svg' write 'fexport.gif':write 'fexport.xyz' write 'fexport.stl':write 'fexport.off' write 'fexport.tex':write 'fexport.obj' write 'fexport.prc':write 'fexport.json' write 'fexport.mgld'
C++ code:
void smgl_fexport(mglGraph *gr) // test file export { all_prims(gr); gr->WriteJPEG("fexport.jpg"); // gr->WritePNG("fexport.png"); gr->WriteBMP("fexport.bmp"); gr->WriteTGA("fexport.tga"); gr->WriteEPS("fexport.eps"); gr->WriteSVG("fexport.svg"); gr->WriteGIF("fexport.gif"); gr->WriteXYZ("fexport.xyz"); gr->WriteSTL("fexport.stl"); gr->WriteOFF("fexport.off"); gr->WriteTEX("fexport.tex"); gr->WriteOBJ("fexport.obj"); gr->WritePRC("fexport.prc"); gr->WriteJSON("fexport.json"); gr->ExportMGLD("fexport.mgld"); gr->Clf(); gr->ImportMGLD("fexport.mgld"); }
Example of nonlinear fit.
MGL code:
new dat 100 '0.4*rnd+0.1+sin(2*pi*x)' new in 100 '0.3+sin(2*pi*x)' list ini 1 1 3:fit res dat 'a+b*sin(c*x)' 'abc' ini title 'Fitting sample':yrange -2 2:box:axis:plot dat 'k. ' plot res 'r':plot in 'b' text -0.9 -1.3 'fitted:' 'r:L' putsfit 0 -1.8 'y = ' 'r':text 0 2.2 'initial: y = 0.3+sin(2\pi x)' 'b'
C++ code:
void smgl_fit(mglGraph *gr) // nonlinear fitting { mglData dat(100), in(100), res; gr->Fill(dat,"0.4*rnd+0.1+sin(2*pi*x)"); gr->Fill(in,"0.3+sin(2*pi*x)"); double ini[3] = {1,1,3}; mglData Ini(3,ini); res = gr->Fit(dat, "a+b*sin(c*x)", "abc", Ini); if(big!=3) gr->Title("Fitting sample"); gr->SetRange('y',-2,2); gr->Box(); gr->Plot(dat, "k. "); 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"); // gr->SetRanges(mglPoint(-1,-1,-1),mglPoint(1,1,1)); gr->SetOrigin(0,0,0); }
Function flame2d generate points for flame fractals in 2d case.
MGL code:
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\ [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2] new B 2 3 A.ny '0.3' put B 3 0 0 -1 put B 3 0 1 -1 put B 3 0 2 -1 flame2d fx fy A B 1000000 subplot 1 1 0 '<_':title 'Flame2d sample' ranges fx fy:box:axis plot fx fy 'r#o ';size 0.05
C++ code:
void smgl_flame2d(mglGraph *gr) { mglData A, B(2,3,5); A.SetList(35, 0.33,0.,0.,0.33,0.,0.,0.2, 0.33,0.,0.,0.33,0.67,0.,0.2, 0.33,0.,0.,0.33,0.33,0.33,0.2, 0.33,0.,0.,0.33,0.,0.67,0.2, 0.33,0.,0.,0.33,0.67,0.67,0.2); A.Rearrange(7); for(long i=0;i<2*3*5;i++) B.a[i] = 0.3; for(long i=0;i<5;i++) B.a[2*3*i] = B.a[2*3*i+1*2] = B.a[2*3*i+2*2] = 3; mglData f(mglFlame2d(A,B,1000000)); gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Flame2d sample"); gr->SetRanges(f.SubData(0), f.SubData(1)); gr->Axis(); gr->Box(); gr->Plot(f.SubData(0), f.SubData(1),"r#o ","size 0.05"); }
Function flow is another standard way to visualize vector fields – it draw lines (threads) which is tangent to local vector field direction. MathGL draw threads from edges of bounding box and from central slices. Sometimes it is not most appropriate variant – you may want to use flowp
to specify manual position of threads. The color scheme is used for coloring (see Цветовая схема). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
MGL code:
call 'prepare2v' call 'prepare3v' subplot 2 2 0 '':title 'Flow plot (default)':box:flow a b subplot 2 2 1 '':title '"v" style':box:flow a b 'v' subplot 2 2 2 '':title '"#" and "." styles':box:flow a b '#':flow a b '.2k' subplot 2 2 3:title '3d variant':rotate 50 60:box:flow ex ey ez
C++ code:
void smgl_flow(mglGraph *gr) { mglData a,b; mgls_prepare2v(&a,&b); if(big!=3) {gr->SubPlot(2,2,0,""); gr->Title("Flow plot (default)");} gr->Box(); gr->Flow(a,b); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Title("'v' style"); gr->Box(); gr->Flow(a,b,"v"); gr->SubPlot(2,2,2,""); gr->Title("'\\#' and '.' styles"); gr->Box(); gr->Flow(a,b,"#"); gr->Flow(a,b,".2k"); mglData ex,ey,ez; mgls_prepare3v(&ex,&ey,&ez); gr->SubPlot(2,2,3); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); gr->Flow(ex,ey,ez); }
Function flow3 draw flow threads, which start from given plane.
MGL code:
call 'prepare3v' subplot 2 2 0:title 'Flow3 plot (default)':rotate 50 60:box flow3 ex ey ez subplot 2 2 1:title '"v" style, from boundary':rotate 50 60:box flow3 ex ey ez 'v' 0 subplot 2 2 2:title '"t" style':rotate 50 60:box flow3 ex ey ez 't' 0 subplot 2 2 3:title 'from \i z planes':rotate 50 60:box flow3 ex ey ez 'z' 0 flow3 ex ey ez 'z' 9
C++ code:
void smgl_flow3(mglGraph *gr) { mglData ex,ey,ez; mgls_prepare3v(&ex,&ey,&ez); if(big!=3) {gr->SubPlot(2,2,0); gr->Title("Flow3 plot (default)");} gr->Rotate(50,60); gr->Box(); gr->Flow3(ex,ey,ez); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'v' style, from boundary"); gr->Rotate(50,60); gr->Box(); gr->Flow3(ex,ey,ez,"v",0); gr->SubPlot(2,2,2); gr->Title("'t' style"); gr->Rotate(50,60); gr->Box(); gr->Flow3(ex,ey,ez,"t",0); gr->SubPlot(2,2,3); gr->Title("from \\i z planes"); gr->Rotate(50,60); gr->Box(); gr->Flow3(ex,ey,ez,"z",0); gr->Flow3(ex,ey,ez,"z",9); }
Example of fog.
MGL code:
call 'prepare2d' title 'Fog sample':rotate 50 60:light on:fog 1 box:surf a:cont a 'y'
C++ code:
void smgl_fog(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) gr->Title("Fog sample"); gr->Light(true); gr->Rotate(50,60); gr->Fog(1); gr->Box(); gr->Surf(a); gr->Cont(a,"y"); }
Example of font typefaces.
MGL code:
define d 0.25 loadfont 'STIX':text 0 1.1 'default font (STIX)' loadfont 'adventor':text 0 1.1-d 'adventor font' loadfont 'bonum':text 0 1.1-2*d 'bonum font' loadfont 'chorus':text 0 1.1-3*d 'chorus font' loadfont 'cursor':text 0 1.1-4*d 'cursor font' loadfont 'heros':text 0 1.1-5*d 'heros font' loadfont 'heroscn':text 0 1.1-6*d 'heroscn font' loadfont 'pagella':text 0 1.1-7*d 'pagella font' loadfont 'schola':text 0 1.1-8*d 'schola font' loadfont 'termes':text 0 1.1-9*d 'termes font' loadfont ''
C++ code:
void smgl_fonts(mglGraph *gr) // font typefaces { double h=1.1, d=0.25; gr->LoadFont("STIX"); gr->Puts(mglPoint(0,h), "default font (STIX)"); gr->LoadFont("adventor"); gr->Puts(mglPoint(0,h-d), "adventor font"); gr->LoadFont("bonum"); gr->Puts(mglPoint(0,h-2*d), "bonum font"); gr->LoadFont("chorus"); gr->Puts(mglPoint(0,h-3*d), "chorus font"); gr->LoadFont("cursor"); gr->Puts(mglPoint(0,h-4*d), "cursor font"); gr->LoadFont("heros"); gr->Puts(mglPoint(0,h-5*d), "heros font"); gr->LoadFont("heroscn"); gr->Puts(mglPoint(0,h-6*d), "heroscn font"); gr->LoadFont("pagella"); gr->Puts(mglPoint(0,h-7*d), "pagella font"); gr->LoadFont("schola"); gr->Puts(mglPoint(0,h-8*d), "schola font"); gr->LoadFont("termes"); gr->Puts(mglPoint(0,h-9*d), "termes font"); gr->LoadFont(""); }
Function grad draw gradient lines for matrix.
MGL code:
call 'prepare2d' subplot 1 1 0 '':title 'Grad plot':box:grad a:dens a '{u8}w{q8}'
C++ code:
void smgl_grad(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) {gr->SubPlot(1,1,0,""); gr->Title("Grad plot");} gr->Box(); gr->Grad(a); gr->Dens(a,"{u8}w{q8}"); }
Example of hist (histogram).
MGL code:
new x 10000 '2*rnd-1':new y 10000 '2*rnd-1':copy z exp(-6*(x^2+y^2)) hist xx x z:norm xx 0 1:hist yy y z:norm yy 0 1 multiplot 3 3 3 2 2 '':ranges -1 1 -1 1 0 1:box:dots x y z 'wyrRk' multiplot 3 3 0 2 1 '':ranges -1 1 0 1:box:bars xx multiplot 3 3 5 1 2 '':ranges 0 1 -1 1:box:barh yy subplot 3 3 2:text 0.5 0.5 'Hist and\n{}MultiPlot\n{}sample' 'a' -3
C++ code:
void smgl_hist(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",-3); }
Default UDAV and mgllab icon.
MGL code:
setsize 200 200 zrange 0 2 define $s 0.8 new x 200 '$s*(x+1)/2*sin(2*pi*x)' new y 200 '$s*(x+1)/2*cos(2*pi*x)' new z 200 '$s*(2-(x+1))+0.1' new r 200 '0.02+0.07*(x+1)' subplot 1 1 0 '#' fsurf 'v*cos(2*pi*u)' 'v*sin(2*pi*u)-0.05' 'v/2' 'Yyyww' light on rotate 65 80 tube x y z+0.15 r define $r 0.13 fsurf '0+$r*cos(2*pi*u)*cos(2*pi*v)' '0.03+$r*cos(2*pi*u)*sin(2*pi*v)' '2*$s+0.25+$r*sin(2*pi*u)' 'r' define $r 0.155 fsurf '$r*cos(2*pi*u)*cos(2*pi*v)' '$s+$r*cos(2*pi*u)*sin(2*pi*v)' '0.25+$r*sin(2*pi*u)' 'b'
C++ code:
void smgl_icon(mglGraph *gr) { gr->SetSize(200,200); gr->SetRange('z',0,2); mglData x(200); gr->Fill(x,"0.8*(x+1)/2*sin(2*pi*x)"); mglData y(200); gr->Fill(y,"0.8*(x+1)/2*cos(2*pi*x)"); mglData z(200); gr->Fill(z,"0.8*(2-(x+1))+0.25"); mglData r(200); gr->Fill(r,"0.02+0.07*(x+1)"); gr->SubPlot(1,1,0,"#"); gr->FSurf("v*cos(2*pi*u)","v*sin(2*pi*u)-0.05","v/2","Yyyww"); gr->Light(true); gr->Rotate(65,80); gr->Tube(x,y,z,r); gr->FSurf("0.13*cos(2*pi*u)*cos(2*pi*v)","0.03+0.13*cos(2*pi*u)*sin(2*pi*v)","1.85+0.13*sin(2*pi*u)","r"); gr->FSurf("0.155*cos(2*pi*u)*cos(2*pi*v)","0.8+0.155*cos(2*pi*u)*sin(2*pi*v)","0.25+0.155*sin(2*pi*u)","b"); }
Function ifs2d generate points for fractals using iterated function system in 2d case.
MGL code:
list A [0.33,0,0,0.33,0,0,0.2] [0.33,0,0,0.33,0.67,0,0.2] [0.33,0,0,0.33,0.33,0.33,0.2]\ [0.33,0,0,0.33,0,0.67,0.2] [0.33,0,0,0.33,0.67,0.67,0.2] ifs2d fx fy A 100000 subplot 1 1 0 '<_':title 'IFS 2d sample' ranges fx fy:axis plot fx fy 'r#o ';size 0.05
C++ code:
void smgl_ifs2d(mglGraph *gr) { mglData A; A.SetList(35, 0.33,0.,0.,0.33,0.,0.,0.2, 0.33,0.,0.,0.33,0.67,0.,0.2, 0.33,0.,0.,0.33,0.33,0.33,0.2, 0.33,0.,0.,0.33,0.,0.67,0.2, 0.33,0.,0.,0.33,0.67,0.67,0.2); A.Rearrange(7); mglData f(mglIFS2d(A,100000)); gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("IFS 2d sample"); gr->SetRanges(f.SubData(0), f.SubData(1)); gr->Axis(); gr->Plot(f.SubData(0), f.SubData(1),"r#o ","size 0.05"); }
Function ifs3d generate points for fractals using iterated function system in 3d case.
MGL code:
list A [0,0,0,0,.18,0,0,0,0,0,0,0,.01] [.85,0,0,0,.85,.1,0,-0.1,0.85,0,1.6,0,.85]\ [.2,-.2,0,.2,.2,0,0,0,0.3,0,0.8,0,.07] [-.2,.2,0,.2,.2,0,0,0,0.3,0,0.8,0,.07] ifs3d f A 100000 title 'IFS 3d sample':rotate 50 60 ranges f(0) f(1) f(2):axis:box dots f(0) f(1) f(2) 'G#o';size 0.05
C++ code:
void smgl_ifs3d(mglGraph *gr) { mglData A; A.SetList(52, 0.,0.,0.,0.,.18,0.,0.,0.,0.,0.,0.,0.,.01, .85,0.,0.,0.,.85,.1,0.,-0.1,0.85,0.,1.6,0.,.85, .2,-.2,0.,.2,.2,0.,0.,0.,0.3,0.,0.8,0.,.07, -.2,.2,0.,.2,.2,0.,0.,0.,0.3,0.,0.8,0.,.07); A.Rearrange(13); mglData f(mglIFS3d(A,100000)); if(big!=3) gr->Title("IFS 3d sample"); gr->SetRanges(f.SubData(0), f.SubData(1), f.SubData(2)); gr->Rotate(50,60); gr->Axis(); gr->Box(); gr->Dots(f.SubData(0), f.SubData(1), f.SubData(2),"G#o","size 0.05"); }
Comparison of subdata vs evaluate/
MGL code:
subplot 1 1 0 '':title 'SubData vs Evaluate' new in 9 'x^3/1.1':plot in 'ko ':box new arg 99 '4*x+4' evaluate e in arg off:plot e 'b.'; legend 'Evaluate' subdata s in arg:plot s 'r.';legend 'SubData' legend 2
C++ code:
void smgl_indirect(mglGraph *gr) { gr->SubPlot(1,1,0,""); gr->Title("SubData vs Evaluate"); mglData in(9), arg(99), e, s; gr->Fill(in,"x^3/1.1"); gr->Fill(arg,"4*x+4"); gr->Plot(in,"ko "); gr->Box(); e = in.Evaluate(arg,false); gr->Plot(e,"b.","legend 'Evaluate'"); s = in.SubData(arg); gr->Plot(s,"r.","legend 'SubData'"); gr->Legend(2); }
Example of inplot, multiplot, columnplot, gridplot, shearplot, stickplot.
MGL code:
subplot 3 2 0:title 'StickPlot' stickplot 3 0 20 30:box 'r':text 0 0 0 '0' 'r' stickplot 3 1 20 30:box 'g':text 0 0 0 '1' 'g' stickplot 3 2 20 30:box 'b':text 0 9 0 '2' 'b' subplot 3 2 3 '':title 'ColumnPlot' columnplot 3 0:box 'r':text 0 0 '0' 'r' columnplot 3 1:box 'g':text 0 0 '1' 'g' columnplot 3 2:box 'b':text 0 0 '2' 'b' subplot 3 2 4 '':title 'GridPlot' gridplot 2 2 0:box 'r':text 0 0 '0' 'r' gridplot 2 2 1:box 'g':text 0 0 '1' 'g' gridplot 2 2 2:box 'b':text 0 0 '2' 'b' gridplot 2 2 3:box 'm':text 0 0 '3' 'm' subplot 3 2 5 '':title 'InPlot':box inplot 0.4 1 0.6 1 on:box 'r' multiplot 3 2 1 2 1 '':title 'MultiPlot and ShearPlot':box shearplot 3 0 0.2 0.1:box 'r':text 0 0 '0' 'r' shearplot 3 1 0.2 0.1:box 'g':text 0 0 '1' 'g' shearplot 3 2 0.2 0.1:box 'b':text 0 0 '2' 'b'
C++ code:
void smgl_inplot(mglGraph *gr) { gr->SubPlot(3,2,0); gr->Title("StickPlot"); gr->StickPlot(3, 0, 20, 30); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->StickPlot(3, 1, 20, 30); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->StickPlot(3, 2, 20, 30); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); gr->SubPlot(3,2,3,""); gr->Title("ColumnPlot"); gr->ColumnPlot(3, 0); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->ColumnPlot(3, 1); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->ColumnPlot(3, 2); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); gr->SubPlot(3,2,4,""); gr->Title("GridPlot"); gr->GridPlot(2, 2, 0); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->GridPlot(2, 2, 1); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->GridPlot(2, 2, 2); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); gr->GridPlot(2, 2, 3); gr->Box("m"); gr->Puts(mglPoint(0),"3","m"); gr->SubPlot(3,2,5,""); gr->Title("InPlot"); gr->Box(); gr->InPlot(0.4, 1, 0.6, 1, true); gr->Box("r"); gr->MultiPlot(3,2,1, 2, 1,""); gr->Title("MultiPlot and ShearPlot"); gr->Box(); gr->ShearPlot(3, 0, 0.2, 0.1); gr->Box("r"); gr->Puts(mglPoint(0),"0","r"); gr->ShearPlot(3, 1, 0.2, 0.1); gr->Box("g"); gr->Puts(mglPoint(0),"1","g"); gr->ShearPlot(3, 2, 0.2, 0.1); gr->Box("b"); gr->Puts(mglPoint(0),"2","b"); }
Function iris draw Iris plot for columns of data array.
MGL code:
read a 'iris.dat' crop a 0 4 'x':rearrange a a.nx 50 subplot 1 1 0 '':title 'Iris plot' iris a 'sepal\n length;sepal\n width;petal\n length;petal\n width' '. ';value -1.5;size -2
C++ code:
void smgl_iris(mglGraph *gr) { mglData a("iris.dat"); a.Crop(0,4,'x'); a.Rearrange(4,50); gr->SubPlot(1,1,0,""); if(big!=3) gr->Title("Iris sample"); gr->Iris(a, "sepal\nlength;sepal\nwidth;petal\nlength;petal\nwidth", ". ", "value -1.5;size -2"); }
Function keep conserve initial phase along specified direction(s).
MGL code:
yrange 0 pi new !a 100 300 'exp(-6*x^2+10i*(x+y^2))'subplot 2 1 0 '':box dens real(a) 'BbwrR' text 1.1 0.5 ' o' 'a'keep a 'y' 50 subplot 2 1 1 '':box dens real(a) 'BbwrR'
C++ code:
void smgl_keep(mglGraph *gr) { gr->SetRange('y',0,M_PI); mglDataC a(100,300); gr->Fill(a,"exp(-6*x^2+10i*(x+y^2))"); gr->SubPlot(2,1,0,""); gr->Box(); gr->Dens(a.Real(),"BbwrR"); gr->Puts(1.1,0.5,"\\to","a"); a.Keep("y",50); gr->SubPlot(2,1,1,""); gr->Box(); gr->Dens(a.Real(),"BbwrR"); }
Function label print text at data points. The string may contain ‘%x’, ‘%y’, ‘%z’ for x-, y-, z-coordinates of points, ‘%n’ for point index.
MGL code:
new ys 10 '0.2*rnd-0.8*sin(pi*x)' subplot 1 1 0 '':title 'Label plot':box:plot ys ' *':label ys 'y=%y'
C++ code:
void smgl_label(mglGraph *gr) { mglData ys(10); ys.Modify("0.8*sin(pi*2*x)+0.2*rnd"); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("Label plot"); } gr->Box(); gr->Plot(ys," *"); gr->Label(ys,"y=%y"); }
Function lamerey draw Lamerey diagram.
MGL code:
subplot 1 1 0 '<_':title 'Lamerey sample' axis:xlabel '\i x':ylabel '\bar{\i x} = 2 \i{x}' fplot 'x' 'k=' fplot '2*x' 'b' lamerey 0.00097 '2*x' 'rv~';size 2 lamerey -0.00097 '2*x' 'rv~';size 2
C++ code:
void smgl_lamerey(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Lamerey sample"); gr->Axis(); gr->Label('x',"\\i x"); gr->Label('y',"\\bar{\\i x} = 2 \\i{x}"); gr->FPlot("x","k="); gr->FPlot("2*x","b"); gr->Lamerey( 0.00097,"2*x","rv~"); gr->Lamerey(-0.00097,"2*x","rv~"); }
Example of legend styles.
MGL code:
addlegend 'sin(\pi {x^2})' 'b':addlegend 'sin(\pi x)' 'g*' addlegend 'sin(\pi \sqrt{x})' 'rd':addlegend 'jsut text' ' ':addlegend 'no indent for this' '' subplot 2 2 0 '':title 'Legend (default)':box:legend legend 1 0.5 '^':text 0.49 0.88 'Style "\^"' 'A:L' legend 3 'A#':text 0.75 0.65 'Absolute position' 'A' subplot 2 2 2 '':title 'coloring':box:legend 0 'r#':legend 1 'Wb#':legend 2 'ygr#' subplot 2 2 3 '':title 'manual position':box legend 0.5 1:text 0.5 0.5 'at x=0.5, y=1' 'a' legend 1 '#-':text 0.75 0.25 'Horizontal legend' 'a'
C++ code:
void smgl_legend(mglGraph *gr) { gr->AddLegend("sin(\\pi {x^2})","b"); gr->AddLegend("sin(\\pi x)","g*"); gr->AddLegend("sin(\\pi \\sqrt{x})","rd"); gr->AddLegend("just text"," "); gr->AddLegend("no indent for this",""); if(big!=3) {gr->SubPlot(2,2,0,""); gr->Title("Legend (default)");} gr->Box(); gr->Legend(); if(big==3) return; gr->Legend(1,0.5,"^"); gr->Puts(0.49, 0.88, "Style '\\^'","A:L"); gr->Legend(3,"A#"); gr->Puts(mglPoint(0.75,0.65),"Absolute position","A"); gr->SubPlot(2,2,2,""); gr->Title("coloring"); gr->Box(); gr->Legend(0,"r#"); gr->Legend(1,"Wb#"); gr->Legend(2,"ygr#"); gr->SubPlot(2,2,3,""); gr->Title("manual position"); gr->Box(); gr->Legend(0.5,1); gr->Puts(mglPoint(0.5,0.5),"at x=0.5, y=1","a"); gr->Legend(1,"#-"); gr->Puts(mglPoint(0.75,0.25),"Horizontal legend","a"); }
Example of light with different types.
MGL code:
light on:attachlight on call 'prepare2d' subplot 2 2 0:title 'Default':rotate 50 60:box:surf a line -1 -0.7 1.7 -1 -0.7 0.7 'BA' subplot 2 2 1:title 'Local':rotate 50 60 light 0 1 0 1 -2 -1 -1 line 1 0 1 -1 -1 0 'BAO':box:surf a subplot 2 2 2:title 'no diffuse':rotate 50 60 diffuse 0 line 1 0 1 -1 -1 0 'BAO':box:surf a subplot 2 2 3:title 'diffusive only':rotate 50 60 diffuse 0.5:light 0 1 0 1 -2 -1 -1 'w' 0 line 1 0 1 -1 -1 0 'BAO':box:surf a
C++ code:
void smgl_light(mglGraph *gr) // local light sources { mglData a; mgls_prepare2d(&a); gr->Light(true); gr->AttachLight(true); if(big==3) { gr->Rotate(50,60); gr->Box(); gr->Surf(a); return; } gr->SubPlot(2,2,0); gr->Title("Default"); gr->Rotate(50,60); gr->Line(mglPoint(-1,-0.7,1.7),mglPoint(-1,-0.7,0.7),"BA"); gr->Box(); gr->Surf(a); gr->SubPlot(2,2,1); gr->Title("Local"); gr->Rotate(50,60); gr->AddLight(0,mglPoint(1,0,1),mglPoint(-2,-1,-1)); gr->Line(mglPoint(1,0,1),mglPoint(-1,-1,0),"BAO"); gr->Box(); gr->Surf(a); gr->SubPlot(2,2,2); gr->Title("no diffuse"); gr->Rotate(50,60); gr->SetDiffuse(0); gr->Line(mglPoint(1,0,1),mglPoint(-1,-1,0),"BAO"); gr->Box(); gr->Surf(a); gr->SubPlot(2,2,3); gr->Title("diffusive only"); gr->Rotate(50,60); gr->SetDiffuse(0.5); gr->AddLight(0,mglPoint(1,0,1),mglPoint(-2,-1,-1),'w',0); gr->Line(mglPoint(1,0,1),mglPoint(-1,-1,0),"BAO"); gr->Box(); gr->Surf(a); }
Function lines draw a set of lines.
MGL code:
subplot 1 1 0 '':title 'Lines plot' new x1 11 '0.3*cos(pi*i/5)' new y1 11 '0.3*sin(pi*i/5)' new x2 11 '0.7*cos(pi*i/5)' new y2 11 '0.7*sin(pi*i/5)' plot x1 y1 lines x1 y1 x2 y2 '_A'
C++ code:
void smgl_lines(mglGraph *gr) { mglData x1(11),y1(11),x2(11),y2(11); for(long i=0;i<11;i++) { x1.a[i] = 0.3*cos(M_PI*i/5); y1.a[i] = 0.3*sin(M_PI*i/5); x2.a[i] = 0.7*cos(M_PI*i/5); y2.a[i] = 0.7*sin(M_PI*i/5); } if(big!=3) {gr->SubPlot(1,1,0,""); gr->Title("Lines plot");} gr->Plot(x1,y1); gr->Lines(x1,y1,x2,y2,"_A"); }
Example of log- and log-log- axis labels.
MGL code:
subplot 2 2 0 '<_':title 'Semi-log axis':ranges 0.01 100 -1 1:axis 'lg(x)' '' '' axis:grid 'xy' 'g':fplot 'sin(1/x)':xlabel 'x' 0:ylabel 'y = sin 1/x' 0 subplot 2 2 1 '<_':title 'Log-log axis':ranges 0.01 100 0.1 100:axis 'lg(x)' 'lg(y)' '' axis:grid '!' 'h=':grid:fplot 'sqrt(1+x^2)' xlabel 'x' 0:ylabel 'y = \sqrt{1+x^2}' 0 subplot 2 2 2 '<_':title 'Minus-log axis':ranges -100 -0.01 -100 -0.1:axis '-lg(-x)' '-lg(-y)' '' axis:fplot '-sqrt(1+x^2)':xlabel 'x' 0:ylabel 'y = -\sqrt{1+x^2}' 0 subplot 2 2 3 '<_':title 'Log-ticks':ranges 0.01 100 0 100:axis 'sqrt(x)' '' '' axis:fplot 'x':xlabel 'x' 1:ylabel 'y = x' 0
C++ code:
void smgl_loglog(mglGraph *gr) // log-log axis { gr->SubPlot(2,2,0,"<_"); gr->Title("Semi-log axis"); gr->SetRanges(0.01,100,-1,1); gr->SetFunc("lg(x)",""); gr->Axis(); gr->Grid("xy","g"); gr->FPlot("sin(1/x)"); gr->Label('x',"x",0); gr->Label('y', "y = sin 1/x",0); gr->SubPlot(2,2,1,"<_"); gr->Title("Log-log axis"); gr->SetRanges(0.01,100,0.1,100); gr->SetFunc("lg(x)","lg(y)"); gr->Axis(); gr->Grid("!","h="); gr->Grid(); gr->FPlot("sqrt(1+x^2)"); gr->Label('x',"x",0); gr->Label('y', "y = \\sqrt{1+x^2}",0); gr->SubPlot(2,2,2,"<_"); gr->Title("Minus-log axis"); gr->SetRanges(-100,-0.01,-100,-0.1); gr->SetFunc("-lg(-x)","-lg(-y)"); gr->Axis(); gr->FPlot("-sqrt(1+x^2)"); gr->Label('x',"x",0); gr->Label('y', "y = -\\sqrt{1+x^2}",0); gr->SubPlot(2,2,3,"<_"); gr->Title("Log-ticks"); gr->SetRanges(0.1,100,0,100); gr->SetFunc("sqrt(x)",""); gr->Axis(); gr->FPlot("x"); gr->Label('x',"x",1); gr->Label('y', "y = x",0); }
Example of map.
MGL code:
new a 50 40 'x':new b 50 40 'y':zrange -2 2:text 0 0 '\to' subplot 2 1 0:text 0 1.1 '\{x, y\}' '' -2:box:map a b 'brgk' subplot 2 1 1:text 0 1.1 '\{\frac{x^3+y^3}{2}, \frac{x-y}{2}\}' '' -2 box:fill a '(x^3+y^3)/2':fill b '(x-y)/2':map a b 'brgk'
C++ code:
void smgl_map(mglGraph *gr) // example of mapping { 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"); }
Example of mark.
MGL code:
call 'prepare1d' subplot 1 1 0 '':title 'Mark plot (default)':box:mark y y1 's'
C++ code:
void smgl_mark(mglGraph *gr) { mglData y,y1; mgls_prepare1d(&y,&y1); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("Mark plot (default)"); } gr->Box(); gr->Mark(y,y1,"s"); }
Example of mask kinds.
MGL code:
new a 10 10 'x' subplot 5 4 0 '':title '"-" mask':dens a '3-' subplot 5 4 1 '':title '"+" mask':dens a '3+' subplot 5 4 2 '':title '"=" mask':dens a '3=' subplot 5 4 3 '':title '";" mask':dens a '3;' subplot 5 4 4 '':title '";I" mask':dens a '3;I' subplot 5 4 5 '':title '"o" mask':dens a '3o' subplot 5 4 6 '':title '"O" mask':dens a '3O' subplot 5 4 7 '':title '"s" mask':dens a '3s' subplot 5 4 8 '':title '"S" mask':dens a '3S' subplot 5 4 9 '':title '";/" mask':dens a '3;/' subplot 5 4 10 '':title '"~" mask':dens a '3~' subplot 5 4 11 '':title '"<" mask':dens a '3<' subplot 5 4 12 '':title '">" mask':dens a '3>' subplot 5 4 13 '':title '"j" mask':dens a '3j' subplot 5 4 14 '':title '"-;\" mask':dens a '3\;' subplot 5 4 15 '':title '"d" mask':dens a '3d' subplot 5 4 16 '':title '"D" mask':dens a '3D' subplot 5 4 17 '':title '"*" mask':dens a '3*' subplot 5 4 18 '':title '"\^" mask':dens a '3^' subplot 5 4 19 '':title 'manual mask' mask '+' '24242424FF0101FF':dens a '3+'
C++ code:
void smgl_mask(mglGraph *gr) { mglData a(10,10); a.Fill(-1,1); gr->SubPlot(5,4,0,""); gr->Title("'-' mask"); gr->Dens(a,"3-"); gr->SubPlot(5,4,1,""); gr->Title("'+' mask"); gr->Dens(a,"3+"); gr->SubPlot(5,4,2,""); gr->Title("'=' mask"); gr->Dens(a,"3="); gr->SubPlot(5,4,3,""); gr->Title("';' mask"); gr->Dens(a,"3;"); gr->SubPlot(5,4,4,""); gr->Title("';I' mask"); gr->Dens(a,"3;I"); gr->SubPlot(5,4,5,""); gr->Title("'o' mask"); gr->Dens(a,"3o"); gr->SubPlot(5,4,6,""); gr->Title("'O' mask"); gr->Dens(a,"3O"); gr->SubPlot(5,4,7,""); gr->Title("'s' mask"); gr->Dens(a,"3s"); gr->SubPlot(5,4,8,""); gr->Title("'S' mask"); gr->Dens(a,"3S"); gr->SubPlot(5,4,9,""); gr->Title("';/' mask"); gr->Dens(a,"3;/"); gr->SubPlot(5,4,10,""); gr->Title("'~' mask"); gr->Dens(a,"3~"); gr->SubPlot(5,4,11,""); gr->Title("'<' mask"); gr->Dens(a,"3<"); gr->SubPlot(5,4,12,""); gr->Title("'>' mask"); gr->Dens(a,"3>"); gr->SubPlot(5,4,13,""); gr->Title("'j' mask"); gr->Dens(a,"3j"); gr->SubPlot(5,4,14,""); gr->Title("';\\\\' mask"); gr->Dens(a,"3;\\"); gr->SubPlot(5,4,15,""); gr->Title("'d' mask"); gr->Dens(a,"3d"); gr->SubPlot(5,4,16,""); gr->Title("'D' mask"); gr->Dens(a,"3D"); gr->SubPlot(5,4,17,""); gr->Title("'*' mask"); gr->Dens(a,"3*"); gr->SubPlot(5,4,18,""); gr->Title("'\\^' mask"); gr->Dens(a,"3^"); gr->SubPlot(5,4,19,""); gr->Title("manual mask"); gr->SetMask('+', "24242424FF0101FF"); gr->Dens(a,"3+"); }
Function mesh draw wired surface. You can use meshnum for changing number of lines to be drawn.
MGL code:
call 'prepare2d' title 'Mesh plot':rotate 50 60:box:mesh a
C++ code:
void smgl_mesh(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) gr->Title("Mesh plot"); gr->Rotate(50,60); gr->Box(); gr->Mesh(a); }
Function minmax get position of local minimums and maximums.
MGL code:
define $p 30 new h 300 300 '-sqrt(1-x^2-y^2)*(3*x*y^2*$p-x^3*$p+6*y)/(3*sqrt(2))+x*y+(y^2+x^2)*$p/3 -7*(y^2+x^2)^2*$p/24+y^2+3*x^2' minmax e h subplot 1 1 0 '':title 'MinMax sample' crange h:dens h:box fplot 'sin(2*pi*t)' 'cos(2*pi*t)' '0' 'k' plot e(0)*2-1 e(1)*2-1 '. c'
C++ code:
void smgl_minmax(mglGraph *gr) // test minmax { mglData h(300,300); gr->Fill(h,"-sqrt(1-x^2-y^2)*(3*x*y^2*30-x^3*30+6*y)/(3*sqrt(2))+x*y+(y^2+x^2)*10 -7*(y^2+x^2)^2*30/24+y^2+3*x^2"); mglData e=h.MinMax(); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("MinMax sample"); } gr->SetRange('c',h); gr->Dens(h); gr->Box(); gr->FPlot("sin(2*pi*t)","cos(2*pi*t)","0","k"); e*=2; e-=1; gr->Plot(e(0),e(1),". c"); }
Example of using options.
MGL code:
new a 31 41 '-pi*x*exp(-(y+1)^2-4*x^2)' subplot 2 2 0:title 'Options for coordinates':alpha on:light on:rotate 40 60:box surf a 'r';yrange 0 1:surf a 'b';yrange 0 -1 subplot 2 2 1:title 'Option "meshnum"':rotate 40 60:box mesh a 'r'; yrange 0 1:mesh a 'b';yrange 0 -1; meshnum 5 subplot 2 2 2:title 'Option "alpha"':rotate 40 60:box surf a 'r';yrange 0 1; alpha 0.7:surf a 'b';yrange 0 -1; alpha 0.3 subplot 2 2 3 '<_':title 'Option "legend"' fplot 'x^3' 'r'; legend 'y = x^3':fplot 'cos(pi*x)' 'b'; legend 'y = cos \pi x' box:axis:legend 2
C++ code:
void smgl_mirror(mglGraph *gr) // flag # { mglData a(31,41); gr->Fill(a,"-pi*x*exp(-(y+1)^2-4*x^2)"); if(big!=3) { 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(big==3) 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 drawing molecules.
MGL code:
alpha on:light on subplot 2 2 0 '':title 'Methane, CH_4':rotate 60 120 sphere 0 0 0 0.25 'k':drop 0 0 0 0 0 1 0.35 'h' 1 2:sphere 0 0 0.7 0.25 'g' drop 0 0 0 -0.94 0 -0.33 0.35 'h' 1 2:sphere -0.66 0 -0.23 0.25 'g' drop 0 0 0 0.47 0.82 -0.33 0.35 'h' 1 2:sphere 0.33 0.57 -0.23 0.25 'g' drop 0 0 0 0.47 -0.82 -0.33 0.35 'h' 1 2:sphere 0.33 -0.57 -0.23 0.25 'g' subplot 2 2 1 '':title 'Water, H{_2}O':rotate 60 100 sphere 0 0 0 0.25 'r':drop 0 0 0 0.3 0.5 0 0.3 'm' 1 2:sphere 0.3 0.5 0 0.25 'g' drop 0 0 0 0.3 -0.5 0 0.3 'm' 1 2:sphere 0.3 -0.5 0 0.25 'g' subplot 2 2 2 '':title 'Oxygen, O_2':rotate 60 120 drop 0 0.5 0 0 -0.3 0 0.3 'm' 1 2:sphere 0 0.5 0 0.25 'r' drop 0 -0.5 0 0 0.3 0 0.3 'm' 1 2:sphere 0 -0.5 0 0.25 'r' subplot 2 2 3 '':title 'Ammonia, NH_3':rotate 60 120 sphere 0 0 0 0.25 'b':drop 0 0 0 0.33 0.57 0 0.32 'n' 1 2 sphere 0.33 0.57 0 0.25 'g':drop 0 0 0 0.33 -0.57 0 0.32 'n' 1 2 sphere 0.33 -0.57 0 0.25 'g':drop 0 0 0 -0.65 0 0 0.32 'n' 1 2 sphere -0.65 0 0 0.25 'g'
C++ code:
void smgl_molecule(mglGraph *gr) // example of moleculas { gr->VertexColor(false); gr->Compression(false); // per-vertex colors and compression are detrimental to transparency gr->DoubleSided(false); // we do not get into atoms, while rendering internal surface has negative impact on trasparency 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(); gr->DoubleSided( true ); // put back }
Example of phase plain created by ode solving, contour lines (cont) and flow threads.
MGL code:
subplot 2 2 0 '<_':title 'Cont':box axis:xlabel 'x':ylabel '\dot{x}' new f 100 100 'y^2+2*x^3-x^2-0.5':cont f subplot 2 2 1 '<_':title 'Flow':box axis:xlabel 'x':ylabel '\dot{x}' new fx 100 100 'x-3*x^2' new fy 100 100 'y' flow fy fx 'v';value 7 subplot 2 2 2 '<_':title 'ODE':box axis:xlabel 'x':ylabel '\dot{x}' for $x -1 1 0.1 ode r 'y;x-3*x^2' 'xy' [$x,0] plot r(0) r(1) ode r '-y;-x+3*x^2' 'xy' [$x,0] plot r(0) r(1) next
C++ code:
void smgl_ode(mglGraph *gr) { gr->SubPlot(2,2,0,"<_"); gr->Title("Cont"); gr->Box(); gr->Axis(); gr->Label('x',"x"); gr->Label('y',"\\dot{x}"); mglData f(100,100); gr->Fill(f,"y^2+2*x^3-x^2-0.5"); gr->Cont(f); gr->SubPlot(2,2,1,"<_"); gr->Title("Flow"); gr->Box(); gr->Axis(); gr->Label('x',"x"); gr->Label('y',"\\dot{x}"); mglData fx(100,100), fy(100,100); gr->Fill(fx,"x-3*x^2"); gr->Fill(fy,"y"); gr->Flow(fy,fx,"v","value 7"); gr->SubPlot(2,2,2,"<_"); gr->Title("ODE"); gr->Box(); gr->Axis(); gr->Label('x',"x"); gr->Label('y',"\\dot{x}"); for(double x=-1;x<1;x+=0.1) { mglData in(2), r; in.a[0]=x; r = mglODE("y;x-3*x^2","xy",in); gr->Plot(r.SubData(0), r.SubData(1)); r = mglODE("-y;-x+3*x^2","xy",in); gr->Plot(r.SubData(0), r.SubData(1)); } }
Function ohlc draw Open-High-Low-Close diagram. This diagram show vertical line for between maximal(high) and minimal(low) values, as well as horizontal lines before/after vertical line for initial(open)/final(close) values of some process.
MGL code:
new o 10 '0.5*sin(pi*x)' new c 10 '0.5*sin(pi*(x+2/9))' new l 10 '0.3*rnd-0.8' new h 10 '0.3*rnd+0.5' subplot 1 1 0 '':title 'OHLC plot':box:ohlc o h l c
C++ code:
void smgl_ohlc(mglGraph *gr) // flow threads and density plot { mglData o(10), h(10), l(10), c(10); gr->Fill(o,"0.5*sin(pi*x)"); gr->Fill(c,"0.5*sin(pi*(x+2/9))"); gr->Fill(l,"0.3*rnd-0.8"); gr->Fill(h,"0.3*rnd+0.5"); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("OHLC plot"); } gr->Box(); gr->OHLC(o,h,l,c); }
Example of parametric plots for 1D data.
MGL code:
new x 100 'sin(pi*x)' new y 100 'cos(pi*x)' new z 100 'sin(2*pi*x)' new c 100 'cos(2*pi*x)' subplot 4 3 0:rotate 40 60:box:plot x y z subplot 4 3 1:rotate 40 60:box:area x y z subplot 4 3 2:rotate 40 60:box:tens x y z c subplot 4 3 3:rotate 40 60:box:bars x y z subplot 4 3 4:rotate 40 60:box:stem x y z subplot 4 3 5:rotate 40 60:box:textmark x y z c*2 '\alpha' subplot 4 3 6:rotate 40 60:box:tube x y z c/10 subplot 4 3 7:rotate 40 60:box:mark x y z c 's' subplot 4 3 8:box:error x y z/10 c/10 subplot 4 3 9:rotate 40 60:box:step x y z subplot 4 3 10:rotate 40 60:box:torus x z 'z';light on subplot 4 3 11:rotate 40 60:box:label x y z '%z'
C++ code:
void smgl_param1(mglGraph *gr) // 1d parametric plots { mglData x(100), y(100), z(100), c(100); gr->Fill(x,"sin(pi*x)"); gr->Fill(y,"cos(pi*x)"); gr->Fill(z,"sin(2*pi*x)"); gr->Fill(c,"cos(2*pi*x)"); gr->SubPlot(4,3,0); gr->Rotate(40,60); gr->Box(); gr->Plot(x,y,z); gr->SubPlot(4,3,1); gr->Rotate(40,60); gr->Box(); gr->Area(x,y,z); gr->SubPlot(4,3,2); gr->Rotate(40,60); gr->Box(); gr->Tens(x,y,z,c); gr->SubPlot(4,3,3); gr->Rotate(40,60); gr->Box(); gr->Bars(x,y,z); gr->SubPlot(4,3,4); gr->Rotate(40,60); gr->Box(); gr->Stem(x,y,z); gr->SubPlot(4,3,5); gr->Rotate(40,60); gr->Box(); gr->TextMark(x,y,z,c*2,"\\alpha"); gr->SubPlot(4,3,6); gr->Rotate(40,60); gr->Box(); gr->Tube(x,y,z,c/10,"","light on"); gr->SubPlot(4,3,7); gr->Rotate(40,60); gr->Box(); gr->Mark(x,y,z,c,"s"); gr->SubPlot(4,3,8); gr->Rotate(40,60); gr->Box(); gr->Error(x,y,z/10,c/10); gr->SubPlot(4,3,9); gr->Rotate(40,60); gr->Box(); gr->Step(x,y,z); gr->SubPlot(4,3,10);gr->Rotate(40,60); gr->Box(); gr->Torus(x,z,"z","light on"); gr->SubPlot(4,3,11);gr->Rotate(40,60); gr->Box(); gr->Label(x,y,z,"%z"); }
Example of parametric plots for 2D data.
MGL code:
new x 100 100 'sin(pi*(x+y)/2)*cos(pi*y/2)' new y 100 100 'cos(pi*(x+y)/2)*cos(pi*y/2)' new z 100 100 'sin(pi*y/2)' new c 100 100 'cos(pi*x)' subplot 4 4 0:rotate 40 60:box:surf x y z subplot 4 4 1:rotate 40 60:box:surfc x y z c subplot 4 4 2:rotate 40 60:box:surfa x y z c;alpha 1 subplot 4 4 3:rotate 40 60:box:mesh x y z;meshnum 10 subplot 4 4 4:rotate 40 60:box:tile x y z;meshnum 10 subplot 4 4 5:rotate 40 60:box:tiles x y z c;meshnum 10 subplot 4 4 6:rotate 40 60:box:axial x y z;alpha 0.5;light on subplot 4 4 7:rotate 40 60:box:cont x y z subplot 4 4 8:rotate 40 60:box:contf x y z;light on:contv x y z;light on subplot 4 4 9:rotate 40 60:box:belt x y z 'x';meshnum 10;light on subplot 4 4 10:rotate 40 60:box:dens x y z;alpha 0.5 subplot 4 4 11:rotate 40 60:box fall x y z 'g';meshnum 10:fall x y z 'rx';meshnum 10 subplot 4 4 12:rotate 40 60:box:belt x y z '';meshnum 10;light on subplot 4 4 13:rotate 40 60:box:boxs x y z '';meshnum 10;light on subplot 4 4 14:rotate 40 60:box:boxs x y z '#';meshnum 10;light on subplot 4 4 15:rotate 40 60:box:boxs x y z '@';meshnum 10;light on
C++ code:
void smgl_param2(mglGraph *gr) // 2d parametric plots { mglData x(100,100), y(100,100), z(100,100), c(100,100); gr->Fill(x,"sin(pi*(x+y)/2)*cos(pi*y/2)"); gr->Fill(y,"cos(pi*(x+y)/2)*cos(pi*y/2)"); gr->Fill(z,"sin(pi*y/2)"); gr->Fill(c,"cos(pi*x)"); gr->SubPlot(4,4,0); gr->Rotate(40,60); gr->Box(); gr->Surf(x,y,z); gr->SubPlot(4,4,1); gr->Rotate(40,60); gr->Box(); gr->SurfC(x,y,z,c); gr->SubPlot(4,4,2); gr->Rotate(40,60); gr->Box(); gr->SurfA(x,y,z,c,"","alpha 1"); gr->SubPlot(4,4,3); gr->Rotate(40,60); gr->Box(); gr->Mesh(x,y,z,"","meshnum 10"); gr->SubPlot(4,4,4); gr->Rotate(40,60); gr->Box(); gr->Tile(x,y,z,"","meshnum 10"); gr->SubPlot(4,4,5); gr->Rotate(40,60); gr->Box(); gr->TileS(x,y,z,c,"","meshnum 10"); gr->SubPlot(4,4,6); gr->Rotate(40,60); gr->Box(); gr->Axial(x,y,z,"","alpha 0.5;light on"); gr->SubPlot(4,4,7); gr->Rotate(40,60); gr->Box(); gr->Cont(x,y,z); gr->SubPlot(4,4,8); gr->Rotate(40,60); gr->Box(); gr->ContF(x,y,z,"","light on"); gr->ContV(x,y,z,"","light on"); gr->SubPlot(4,4,9); gr->Rotate(40,60); gr->Box(); gr->Belt(x,y,z,"x","meshnum 10;light on"); gr->SubPlot(4,4,10);gr->Rotate(40,60); gr->Box(); gr->Dens(x,y,z,"","alpha 0.5"); gr->SubPlot(4,4,11);gr->Rotate(40,60); gr->Box(); gr->Fall(x,y,z,"g","meshnum 10"); gr->Fall(x,y,z,"rx","meshnum 10"); gr->SubPlot(4,4,12); gr->Rotate(40,60); gr->Box(); gr->Belt(x,y,z,"","meshnum 10;light on"); gr->SubPlot(4,4,13); gr->Rotate(40,60); gr->Box(); gr->Boxs(x,y,z,"","meshnum 10;light on"); gr->SubPlot(4,4,14); gr->Rotate(40,60); gr->Box(); gr->Boxs(x,y,z,"#","meshnum 10"); gr->SubPlot(4,4,15); gr->Rotate(40,60); gr->Box(); gr->Boxs(x,y,z,"@","meshnum 10;light on"); }
Example of parametric plots for 3D data.
MGL code:
new x 50 50 50 '(x+2)/3*sin(pi*y/2)' new y 50 50 50 '(x+2)/3*cos(pi*y/2)' new z 50 50 50 'z' new c 50 50 50 '-2*(x^2+y^2+z^4-z^2)+0.2' new d 50 50 50 '1-2*tanh(2*(x+y)^2)' alpha on:light on subplot 4 3 0:rotate 40 60:box:surf3 x y z c subplot 4 3 1:rotate 40 60:box:surf3c x y z c d subplot 4 3 2:rotate 40 60:box:surf3a x y z c d subplot 4 3 3:rotate 40 60:box:cloud x y z c subplot 4 3 4:rotate 40 60:box:cont3 x y z c:cont3 x y z c 'x':cont3 x y z c 'z' subplot 4 3 5:rotate 40 60:box:contf3 x y z c:contf3 x y z c 'x':contf3 x y z c 'z' subplot 4 3 6:rotate 40 60:box:dens3 x y z c:dens3 x y z c 'x':dens3 x y z c 'z' subplot 4 3 7:rotate 40 60:box:dots x y z c;meshnum 15 subplot 4 3 8:rotate 40 60:box:densx c '' 0:densy c '' 0:densz c '' 0 subplot 4 3 9:rotate 40 60:box:contx c '' 0:conty c '' 0:contz c '' 0 subplot 4 3 10:rotate 40 60:box:contfx c '' 0:contfy c '' 0:contfz c '' 0
C++ code:
void smgl_param3(mglGraph *gr) // 3d parametric plots { mglData x(50,50,50), y(50,50,50), z(50,50,50), c(50,50,50), d(50,50,50); gr->Fill(x,"(x+2)/3*sin(pi*y/2)"); gr->Fill(y,"(x+2)/3*cos(pi*y/2)"); gr->Fill(z,"z"); gr->Fill(c,"-2*(x^2+y^2+z^4-z^2)+0.2"); gr->Fill(d,"1-2*tanh(2*(x+y)^2)"); gr->Light(true); gr->Alpha(true); gr->SubPlot(4,3,0); gr->Rotate(40,60); gr->Box(); gr->Surf3(x,y,z,c); gr->SubPlot(4,3,1); gr->Rotate(40,60); gr->Box(); gr->Surf3C(x,y,z,c,d); gr->SubPlot(4,3,2); gr->Rotate(40,60); gr->Box(); gr->Surf3A(x,y,z,c,d); gr->SubPlot(4,3,3); gr->Rotate(40,60); gr->Box(); gr->Cloud(x,y,z,c); gr->SubPlot(4,3,4); gr->Rotate(40,60); gr->Box(); gr->Cont3(x,y,z,c); gr->Cont3(x,y,z,c,"x"); gr->Cont3(x,y,z,c,"z"); gr->SubPlot(4,3,5); gr->Rotate(40,60); gr->Box(); gr->ContF3(x,y,z,c);gr->ContF3(x,y,z,c,"x");gr->ContF3(x,y,z,c,"z"); gr->SubPlot(4,3,6); gr->Rotate(40,60); gr->Box(); gr->Dens3(x,y,z,c); gr->Dens3(x,y,z,c,"x"); gr->Dens3(x,y,z,c,"z"); gr->SubPlot(4,3,7); gr->Rotate(40,60); gr->Box(); gr->Dots(x,y,z,c,"","meshnum 15"); gr->SubPlot(4,3,8); gr->Rotate(40,60); gr->Box(); gr->DensX(c,"",0); gr->DensY(c,"",0); gr->DensZ(c,"",0); gr->SubPlot(4,3,9); gr->Rotate(40,60); gr->Box(); gr->ContX(c,"",0); gr->ContY(c,"",0); gr->ContZ(c,"",0); gr->SubPlot(4,3,10);gr->Rotate(40,60); gr->Box(); gr->ContFX(c,"",0); gr->ContFY(c,"",0); gr->ContFZ(c,"",0); }
Example of parametric plots for vector fields.
MGL code:
new x 20 20 20 '(x+2)/3*sin(pi*y/2)' new y 20 20 20 '(x+2)/3*cos(pi*y/2)' new z 20 20 20 'z+x' new ex 20 20 20 'x' new ey 20 20 20 'x^2+y' new ez 20 20 20 'y^2+z' new x1 50 50 '(x+2)/3*sin(pi*y/2)' new y1 50 50 '(x+2)/3*cos(pi*y/2)' new e1 50 50 'x' new e2 50 50 'x^2+y' subplot 3 3 0:rotate 40 60:box:vect x1 y1 e1 e2 subplot 3 3 1:rotate 40 60:box:flow x1 y1 e1 e2 subplot 3 3 2:rotate 40 60:box:pipe x1 y1 e1 e2 subplot 3 3 3:rotate 40 60:box:dew x1 y1 e1 e2 subplot 3 3 4:rotate 40 60:box:vect x y z ex ey ez subplot 3 3 5:rotate 40 60:box vect3 x y z ex ey ez:vect3 x y z ex ey ez 'x':vect3 x y z ex ey ez 'z' grid3 x y z z '{r9}':grid3 x y z z '{g9}x':grid3 x y z z '{b9}z' subplot 3 3 6:rotate 40 60:box:flow x y z ex ey ez subplot 3 3 7:rotate 40 60:box:pipe x y z ex ey ez
C++ code:
void smgl_paramv(mglGraph *gr) // parametric plots for vector field { mglData x(20,20,20), y(20,20,20), z(20,20,20), ex(20,20,20), ey(20,20,20), ez(20,20,20); gr->Fill(x,"(x+2)/3*sin(pi*y/2)"); gr->Fill(y,"(x+2)/3*cos(pi*y/2)"); gr->Fill(z,"x+z"); gr->Fill(ex,"x"); gr->Fill(ey,"x^2+y"); gr->Fill(ez,"y^2+z"); mglData x1(20,20), y1(20,20), e1(20,20), e2(20,20); gr->Fill(x1,"(x+2)/3*sin(pi*y/2)"); gr->Fill(y1,"(x+2)/3*cos(pi*y/2)"); gr->Fill(e1,"x"); gr->Fill(e2,"x^2+y"); gr->SubPlot(3,3,0); gr->Rotate(40,60); gr->Box(); gr->Vect(x1,y1,e1,e2); gr->SubPlot(3,3,1); gr->Rotate(40,60); gr->Box(); gr->Flow(x1,y1,e1,e2); gr->SubPlot(3,3,2); gr->Rotate(40,60); gr->Box(); gr->Pipe(x1,y1,e1,e2); gr->SubPlot(3,3,3); gr->Rotate(40,60); gr->Box(); gr->Dew(x1,y1,e1,e2); gr->SubPlot(3,3,4); gr->Rotate(40,60); gr->Box(); gr->Vect(x,y,z,ex,ey,ez); gr->SubPlot(3,3,5); gr->Rotate(40,60); gr->Box(); gr->Vect3(x,y,z,ex,ey,ez); gr->Vect3(x,y,z,ex,ey,ez,"x"); gr->Vect3(x,y,z,ex,ey,ez,"z"); gr->Grid3(x,y,z,z,"{r9}"); gr->Grid3(x,y,z,z,"{g9}x"); gr->Grid3(x,y,z,z,"{b9}z"); gr->SubPlot(3,3,6); gr->Rotate(40,60); gr->Box(); gr->Flow(x,y,z,ex,ey,ez); gr->SubPlot(3,3,7); gr->Rotate(40,60); gr->Box(); gr->Pipe(x,y,z,ex,ey,ez); }
Basic MGL script.
MGL code:
title 'MGL parser sample' # call function call 'sample' # ordinary for-loop for $0 -1 1 0.1 if $0<0:line 0 0 1 $0 'r':else:line 0 0 1 $0 'g':endif next # if-elseif-else for $i -1 1 0.5 if $i<0 text 1.1 $i '$i' 'b' elseif $i>0 text 1.1 $i '$i' 'r' else text 1.1 $i '$i' endif next # ordinary do-while do defnum $i $i-0.2 line 0 0 $i 1 'b' while $i>0 # do-next-break do defnum $i $i-0.2 if $i<-1 then break line 0 0 $i 1 'm' next # for-while-continue for $i -5 10 text $i/5 1.1 'a'+($i+5) if $i<0 text $i/5-0.06 1.1 '--' 'b' elseif mod($i,2)=0 text $i/5-0.06 1.1 '~' 'r' else # NOTE: 'continue' bypass the 'while'! continue endif # NOTE: 'while' limit the actual number of iterations while $i<5 # nested loops for $i 0 1 0.1 for $j 0 1 0.1 ball $i $j if $j>0.5 then continue ball $i $j 'b+' next next func 'sample' new dat 100 'sin(2*pi*(i/99+1))' plot dat;xrange -1 0 box:axis xlabel 'x':ylabel 'y' return
C++ code:
void smgl_parser(mglGraph *gr) // example of MGL parsing { // NOTE: MGL version show much more variants of loops and conditions. gr->Title("MGL parser sample"); double a[100]; // let a_i = sin(4*pi*x), x=0...1 for(int i=0;i<100;i++)a[i]=sin(2*M_PI*i/99); mglParse *parser = new mglParse; // Add MGL variable and set yours data to it. mglData *d = dynamic_cast<mglData*>(parser->AddVar("dat")); if(d) d->Set(a,100); parser->Execute(gr, "plot dat; xrange -1 0\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"); // You may use for or do-while loops as C/C++ one double i=1; do { char buf[64]; sprintf(buf,"line 0 0 %g 1 'b'",i); parser->Execute(gr, buf); i=i-0.2; } while(i>0); // or as MGL one. parser->Execute(gr, "for $i -1 1 0.5\n" "if $i<0\ntext 1.1 $i '$i' 'b'\n" "elseif $i>0\ntext 1.1 $i '$i' 'r'\n" "else\ntext 1.1 $i '$i'\nendif\nnext\n"); // There are 'break' and 'continue' commands in MGL too. // NOTE: 'next' act as "while(1)" in do-while loops. parser->Execute(gr, "do\ndefnum $i $i-0.2\n" "if $i<-1 then break\nline 0 0 $i 1 'm'\nnext\n"); // One issue with 'continue' -- it bypass 'while' checking parser->Execute(gr, "for $i -5 10\ntext $i/5 1.1 'a'+($i+5)\nif $i<0\n" "text $i/5-0.06 1.1 '--' 'b'\n" "elseif mod($i,2)=0\ntext $i/5-0.06 1.1 '~' 'r'\n" "else\ncontinue\nendif\n" // NOTE: 'while' limit the actual number of iterations in for-loop. "while $i<5\n"); // Finally, MGL support nested loops too. parser->Execute(gr, "for $i 0 1 0.1\nfor $j 0 1 0.1\nball $i $j\n" "if $j>0.5 then continue\nball $i $j 'b+'\nnext\nnext\n"); // Clean up memory. delete parser; }
Example of pde solver.
MGL code:
new re 128 'exp(-48*(x+0.7)^2)':new im 128 pde a 'p^2+q^2-x-1+i*0.5*(z+x)*(z>-x)' re im 0.01 30 transpose a subplot 1 1 0 '<_':title 'PDE solver' axis:xlabel '\i x':ylabel '\i z' crange 0 1:dens a 'wyrRk' fplot '-x' 'k|' text 0 0.95 'Equation: ik_0\partial_zu + \Delta u + x\cdot u + i \frac{x+z}{2}\cdot u = 0\n{}absorption: (x+z)/2 for x+z>0'
C++ code:
void smgl_pde(mglGraph *gr) // PDE sample { 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"); if(big!=3) {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.95), "Equation: ik_0\\partial_zu + \\Delta u + x\\cdot u + i \\frac{x+z}{2}\\cdot u = 0\nabsorption: (x+z)/2 for x+z>0"); }
Example of pendelta for lines and glyphs smoothing.
MGL code:
quality 6 list a 0.25 0.5 1 2 4 for $0 0 4 pendelta a($0) define $1 0.5*$0-1 line -1 $1 1 $1 'r' text 0 $1 'delta=',a($0) next
C++ code:
void smgl_pendelta(mglGraph *gr) { double a[5]={0.25,0.5,1,2,4}; gr->SetQuality(6); char buf[64]; for(int i=0;i<5;i++) { gr->SetPenDelta(a[i]); gr->Line(mglPoint(-1,0.5*i-1), mglPoint(1,0.5*i-1),"r"); sprintf(buf,"delta=%g",a[i]); gr->Puts(mglPoint(0,0.5*i-1),buf); } }
Function pipe is similar to flow but draw pipes (tubes) which radius is proportional to the amplitude of vector field. The color scheme is used for coloring (see Цветовая схема). At this warm color corresponds to normal flow (like attractor), cold one corresponds to inverse flow (like source).
MGL code:
call 'prepare2v' call 'prepare3v' subplot 2 2 0 '':title 'Pipe plot (default)':light on:box:pipe a b subplot 2 2 1 '':title '"i" style':box:pipe a b 'i' subplot 2 2 2 '':title 'from edges only':box:pipe a b '#' subplot 2 2 3:title '3d variant':rotate 50 60:box:pipe ex ey ez '' 0.1
C++ code:
void smgl_pipe(mglGraph *gr) { mglData a,b; mgls_prepare2v(&a,&b); if(big!=3) {gr->SubPlot(2,2,0,""); gr->Title("Pipe plot (default)");} gr->Light(true); gr->Box(); gr->Pipe(a,b); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Title("'i' style"); gr->Box(); gr->Pipe(a,b,"i"); gr->SubPlot(2,2,2,""); gr->Title("'\\#' style"); gr->Box(); gr->Pipe(a,b,"#"); mglData ex,ey,ez; mgls_prepare3v(&ex,&ey,&ez); gr->SubPlot(2,2,3); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); gr->Pipe(ex,ey,ez,"",0.1); }
Function plot is most standard way to visualize 1D data array. By default, Plot
use colors from palette. However, you can specify manual color/palette, and even set to use new color for each points by using ‘!’ style. Another feature is ‘ ’ style which draw only markers without line between points.
MGL code:
call 'prepare1d' subplot 2 2 0 '':title 'Plot plot (default)':box:plot y subplot 2 2 2 '':title ''!' style; 'rgb' palette':box:plot y 'o!rgb' subplot 2 2 3 '':title 'just markers':box:plot y ' +' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box:plot xc yc z 'rs'
C++ code:
void smgl_plot(mglGraph *gr) { mglData y; mgls_prepare1d(&y); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Plot plot (default)"); } gr->Box(); gr->Plot(y); if(big==3) return; gr->SubPlot(2,2,2,""); gr->Title("'!' style; 'rgb' palette"); gr->Box(); gr->Plot(y,"o!rgb"); gr->SubPlot(2,2,3,""); gr->Title("just markers"); gr->Box(); gr->Plot(y," +"); gr->SubPlot(2,2,1); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); mglData yc(30), xc(30), z(30); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); gr->Plot(xc,yc,z,"rs"); }
Function pmap draw Poincare map – show intersections of the curve and the surface.
MGL code:
subplot 1 1 0 '<_^':title 'Poincare map sample' ode r 'cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)' 'xyz' [0.1,0,0] 0.1 100 rotate 40 60:copy x r(0):copy y r(1):copy z r(2) ranges x y z axis:plot x y z 'b' xlabel '\i x' 0:ylabel '\i y' 0:zlabel '\i z' pmap x y z z 'b#o' fsurf '0'
C++ code:
void smgl_pmap(mglGraph *gr) { gr->SubPlot(1,1,0,"<_^"); if(big!=3) gr->Title("Poincare map sample"); mglData ini(3); ini[0]=0.1; mglData r(mglODE("cos(y)+sin(z);cos(z)+sin(x);cos(x)+sin(y)","xyz",ini,0.1,100)); mglData x(r.SubData(0)),y(r.SubData(1)), z(r.SubData(2)); gr->Rotate(40,60); gr->SetRanges(x,y,z); gr->Axis(); gr->FSurf("0"); gr->Plot(x,y,z,"b"); gr->Label('x',"\\i x",0); gr->Label('y',"\\i y",0); gr->Label('z',"\\i z",0); gr->Pmap(x,y,z,z, "b#o"); }
Example of primitives: line, curve, rhomb, ellipse, face, sphere, drop, cone.
MGL code:
subplot 2 2 0 '':title 'Line, Curve, Rhomb, Ellipse' '' -1.5 line -1 -1 -0.5 1 'qAI' curve -0.6 -1 1 1 0 1 1 1 'rA' ball 0 -0.5 '*':ball 1 -0.1 '*' rhomb 0 0.4 1 0.9 0.2 'b#' rhomb 0 0 1 0.4 0.2 'cg@' ellipse 0 -0.5 1 -0.1 0.2 'u#' ellipse 0 -1 1 -0.6 0.2 'm@' subplot 2 3 1 '':title 'Arc, Polygon, Symbol';size -1.2 arc -0.6 0 -0.6 0.3 180 '2kA':ball -0.6 0 polygon 0 0 0 0.4 6 'r' new x 50 'cos(3*pi*x)':new y 50 'sin(pi*x)' addsymbol 'a' x y symbol 0.7 0 'a' light on subplot 2 3 3 '<^>' 0 -0.2:title 'Face[xyz]';size -1.5:rotate 50 60:box facex 1 0 -1 1 1 'r':facey -1 -1 -1 1 1 'g':facez 1 -1 -1 -1 1 'b' face -1 -1 1 -1 1 1 1 -1 0 1 1 1 'bmgr' subplot 2 3 5 '':title 'Cone';size -1.5 cone -0.7 -0.3 0 -0.7 0.7 0.5 0.2 0.1 'b':text -0.7 -0.7 'no edges\n(default)';size -1.5 cone 0 -0.3 0 0 0.7 0.5 0.2 0.1 'g@':text 0 -0.7 'with edges\n("\@" style)';size -1.5 cone 0.7 -0.3 0 0.7 0.7 0.5 0.2 0 'Ggb':text 0.7 -0.7 '"arrow" with\n{}gradient';size -1.5 subplot 2 2 2 '':title 'Sphere and Drop' line -0.9 0 1 0.9 0 1 text -0.9 0.4 'sh=0':drop -0.9 0 0 1 0.5 'r' 0:ball -0.9 0 1 'k' text -0.3 0.6 'sh=0.33':drop -0.3 0 0 1 0.5 'r' 0.33:ball -0.3 0 1 'k' text 0.3 0.8 'sh=0.67':drop 0.3 0 0 1 0.5 'r' 0.67:ball 0.3 0 1 'k' text 0.9 1. 'sh=1':drop 0.9 0 0 1 0.5 'r' 1:ball 0.9 0 1 'k' text -0.9 -1.1 'asp=0.33':drop -0.9 -0.7 0 1 0.5 'b' 0 0.33 text -0.3 -1.1 'asp=0.67':drop -0.3 -0.7 0 1 0.5 'b' 0 0.67 text 0.3 -1.1 'asp=1':drop 0.3 -0.7 0 1 0.5 'b' 0 1 text 0.9 -1.1 'asp=1.5':drop 0.9 -0.7 0 1 0.5 'b' 0 1.5
C++ code:
void smgl_primitives(mglGraph *gr) // flag # { gr->SubPlot(2,2,0,""); gr->Title("Line, Curve, Rhomb, Ellipse","",-1.5); gr->Line(mglPoint(-1,-1),mglPoint(-0.5,1),"qAI"); gr->Curve(mglPoint(-0.6,-1),mglPoint(1,1),mglPoint(0,1),mglPoint(1,1),"rA"); gr->Rhomb(mglPoint(0,0.4),mglPoint(1,0.9),0.2,"b#"); gr->Rhomb(mglPoint(0,0),mglPoint(1,0.4),0.2,"cg@"); gr->Ellipse(mglPoint(0,-0.5),mglPoint(1,-0.1),0.2,"u#"); gr->Ellipse(mglPoint(0,-1),mglPoint(1,-0.6),0.2,"m@"); gr->Mark(mglPoint(0,-0.5),"*"); gr->Mark(mglPoint(1,-0.1),"*"); gr->SubPlot(2,3,1,""); gr->Title("Arc, Polygon, Symbol","", -1.2*2); gr->Arc(mglPoint(-0.6,0), mglPoint(-0.6,0.3), 180, "2kA"); gr->Ball(-0.6,0); gr->Polygon(mglPoint(), mglPoint(0,0.4), 6, "r"); mglData x(50), y(50); gr->Fill(x,"cos(3*pi*x)"); gr->Fill(y,"sin(pi*x)"); gr->DefineSymbol('a',x,y); gr->Symbol(mglPoint(0.7),'a'); gr->Light(true); gr->SubPlot(2,3,3,"<^>",0,-0.2); gr->Title("Face[xyz]", "", -1.5*2); gr->Rotate(50,60); gr->Box(); gr->FaceX(mglPoint(1,0,-1),1,1,"r"); gr->FaceY(mglPoint(-1,-1,-1),1,1,"g"); gr->FaceZ(mglPoint(1,-1,-1),-1,1,"b"); gr->Face(mglPoint(-1,-1,1),mglPoint(-1,1,1),mglPoint(1,-1,0),mglPoint(1,1,1),"bmgr"); gr->SubPlot(2,3,5,""); gr->Title("Cone", "", -1.5*2); gr->Cone(mglPoint(-0.7,-0.3),mglPoint(-0.7,0.7,0.5),0.2,0.1,"b"); gr->Puts(mglPoint(-0.7,-0.7),"no edges\n(default)","", -1.5); gr->Cone(mglPoint(0,-0.3),mglPoint(0,0.7,0.5),0.2,0.1,"g@"); gr->Puts(mglPoint(0,-0.7),"with edges\n('\\@' style)","", -1.5); gr->Cone(mglPoint(0.7,-0.3),mglPoint(0.7,0.7,0.5),0.2,0,"ry"); gr->Puts(mglPoint(0.7,-0.7),"'arrow' with\ngradient","", -1.5); gr->SubPlot(2,2,2,""); gr->Title("Sphere and Drop"); gr->Alpha(false); gr->Puts(mglPoint(-0.9,0.4),"sh=0"); gr->Ball(mglPoint(-0.9,0,1),'k'); gr->Drop(mglPoint(-0.9,0),mglPoint(0,1),0.5,"r",0); gr->Puts(mglPoint(-0.3,0.6),"sh=0.33"); gr->Ball(mglPoint(-0.3,0,1),'k'); gr->Drop(mglPoint(-0.3,0),mglPoint(0,1),0.5,"r",0.33); gr->Puts(mglPoint(0.3,0.8),"sh=0.67"); gr->Ball(mglPoint(0.3,0,1),'k'); gr->Drop(mglPoint(0.3,0),mglPoint(0,1),0.5,"r",0.67); gr->Puts(mglPoint(0.9,1),"sh=1"); gr->Ball(mglPoint(0.9,0,1),'k'); gr->Drop(mglPoint(0.9,0),mglPoint(0,1),0.5,"r",1); gr->Line(mglPoint(-0.9,0,1),mglPoint(0.9,0,1),"b"); gr->Puts(mglPoint(-0.9,-1.1),"asp=0.33"); gr->Drop(mglPoint(-0.9,-0.7),mglPoint(0,1),0.5,"b",0,0.33); gr->Puts(mglPoint(-0.3,-1.1),"asp=0.67"); gr->Drop(mglPoint(-0.3,-0.7),mglPoint(0,1),0.5,"b",0,0.67); gr->Puts(mglPoint(0.3,-1.1),"asp=1"); gr->Drop(mglPoint(0.3,-0.7),mglPoint(0,1),0.5,"b",0,1); gr->Puts(mglPoint(0.9,-1.1),"asp=1.5"); gr->Drop(mglPoint(0.9,-0.7),mglPoint(0,1),0.5,"b",0,1.5); }
Example of plot projection (ternary=4).
MGL code:
ranges 0 1 0 1 0 1 new x 50 '0.25*(1+cos(2*pi*x))' new y 50 '0.25*(1+sin(2*pi*x))' new z 50 'x' new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)' new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx light on title 'Projection sample':ternary 4:rotate 50 60 box:axis:grid plot x y z 'r2':surf a '#' xlabel 'X':ylabel 'Y':zlabel 'Z'
C++ code:
void smgl_projection(mglGraph *gr) // flag # { 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"); if(big!=3) 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 plot projection in ternary coordinates (ternary=5).
MGL code:
ranges 0 1 0 1 0 1 new x 50 '0.25*(1+cos(2*pi*x))' new y 50 '0.25*(1+sin(2*pi*x))' new z 50 'x' new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)' new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx light on title 'Projection sample (ternary)':ternary 5:rotate 50 60 box:axis:grid plot x y z 'r2':surf a '#' xlabel 'X':ylabel 'Y':zlabel 'Z'
C++ code:
void smgl_projection5(mglGraph *gr) // flag # { 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"); if(big!=3) gr->Title("Projection sample (ternary)"); gr->Ternary(5); 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 pulse parameter determining.
MGL code:
subplot 1 1 0 '<_':title 'Pulse sample' new a 100 'exp(-6*x^2)':ranges 0 a.nx-1 0 1 axis:plot a pulse b a 'x' define m a.max line b(1) 0 b(1) m 'r=' line b(1)-b(3)/2 0 b(1)-b(3)/2 m 'm|' line b(1)+b(3)/2 0 b(1)+b(3)/2 m 'm|' line 0 0.5*m a.nx-1 0.5*m 'h' new x 100 'x' plot b(0)*(1-((x-b(1))/b(2))^2) 'g'
C++ code:
void smgl_pulse(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Pulse sample"); mglData a(100); gr->Fill(a,"exp(-6*x^2)"); gr->SetRanges(0, a.nx-1, 0, 1); gr->Axis(); gr->Plot(a); mglData b(a.Pulse('x')); double m = b[0]; gr->Line(mglPoint(b[1],0), mglPoint(b[1],m),"r="); gr->Line(mglPoint(b[1]-b[3]/2,0), mglPoint(b[1]-b[3]/2,m),"m|"); gr->Line(mglPoint(b[1]+b[3]/2,0), mglPoint(b[1]+b[3]/2,m),"m|"); gr->Line(mglPoint(0,m/2), mglPoint(a.nx-1,m/2),"h"); char func[128]; sprintf(func,"%g*(1-((x-%g)/%g)^2)",b[0],b[1],b[2]); gr->FPlot(func,"g"); }
Example of PDE solving by quasioptical approach qo2d.
MGL code:
define $1 'p^2+q^2-x-1+i*0.5*(y+x)*(y>-x)' subplot 1 1 0 '<_':title 'Beam and ray tracing' ray r $1 -0.7 -1 0 0 0.5 0 0.02 2:plot r(0) r(1) 'k' axis:xlabel '\i x':ylabel '\i z' new re 128 'exp(-48*x^2)':new im 128 new xx 1:new yy 1 qo2d a $1 re im r 1 30 xx yy crange 0 1:dens xx yy a 'wyrRk':fplot '-x' 'k|' text 0 0.85 'absorption: (x+y)/2 for x+y>0' text 0.7 -0.05 'central ray'
C++ code:
void smgl_qo2d(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); if(big!=3) {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 y"); // 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"); }
Show all kind of primitives in quality=0.
MGL code:
quality 0 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality0(mglGraph *gr) // test file export { gr->SetQuality(0); all_prims(gr); }
Show all kind of primitives in quality=1.
MGL code:
quality 1 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality1(mglGraph *gr) // test file export { gr->SetQuality(1); all_prims(gr); }
Show all kind of primitives in quality=2.
MGL code:
quality 2 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality2(mglGraph *gr) // test file export { gr->SetQuality(2); all_prims(gr); }
Show all kind of primitives in quality=4.
MGL code:
quality 4 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality4(mglGraph *gr) // test file export { gr->SetQuality(4); all_prims(gr); }
Show all kind of primitives in quality=5.
MGL code:
quality 5 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality5(mglGraph *gr) // test file export { gr->SetQuality(5); all_prims(gr); }
Show all kind of primitives in quality=6.
MGL code:
quality 6 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality6(mglGraph *gr) // test file export { gr->SetQuality(6); all_prims(gr); }
Show all kind of primitives in quality=8.
MGL code:
quality 8 subplot 3 2 0:define y 0.95 define d 0.3:define x0 0.2:define x1 0.5:define x2 0.6 line x0 1-0*d x1 1-0*d 'k-':text x2 y-0*d 'Solid `-`' ':rL' line x0 1-1*d x1 1-1*d 'k|':text x2 y-1*d 'Long Dash `|`' ':rL' line x0 1-2*d x1 1-2*d 'k;':text x2 y-2*d 'Dash 1;`' ':rL' line x0 1-3*d x1 1-3*d 'k=':text x2 y-3*d 'Small dash `=`' ':rL' line x0 1-4*d x1 1-4*d 'kj':text x2 y-4*d 'Dash-dot `j`' ':rL' line x0 1-5*d x1 1-5*d 'ki':text x2 y-5*d 'Small dash-dot `i`' ':rL' line x0 1-6*d x1 1-6*d 'k:':text x2 y-6*d 'Dots `:`' ':rL' line x0 1-7*d x1 1-7*d 'k ':text x2 y-7*d 'None ``' ':rL' define d 0.25:define x0 -0.8:define x1 -1:define x2 -0.05 ball x1 5*d 'k.':text x0 5*d '.' ':rL' ball x1 4*d 'k+':text x0 4*d '+' ':rL' ball x1 3*d 'kx':text x0 3*d 'x' ':rL' ball x1 2*d 'k*':text x0 2*d '*' ':rL' ball x1 d 'ks':text x0 d 's' ':rL' ball x1 0 'kd':text x0 0 'd' ':rL' ball x1 -d 0 'ko':text x0 y-d 'o' ':rL' ball x1 -2*d 0 'k^':text x0 -2*d '\^' ':rL' ball x1 -3*d 0 'kv':text x0 -3*d 'v' ':rL' ball x1 -4*d 0 'k<':text x0 -4*d '<' ':rL' ball x1 -5*d 0 'k>':text x0 -5*d '>' ':rL' define x0 -0.3:define x1 -0.5 ball x1 5*d 'k#.':text x0 5*d '\#.' ':rL' ball x1 4*d 'k#+':text x0 4*d '\#+' ':rL' ball x1 3*d 'k#x':text x0 3*d '\#x' ':rL' ball x1 2*d 'k#*':text x0 2*d '\#*' ':rL' ball x1 d 'k#s':text x0 d '\#s' ':rL' ball x1 0 'k#d':text x0 0 '\#d' ':rL' ball x1 -d 0 'k#o':text x0 -d '\#o' ':rL' ball x1 -2*d 0 'k#^':text x0 -2*d '\#\^' ':rL' ball x1 -3*d 0 'k#v':text x0 -3*d '\#v' ':rL' ball x1 -4*d 0 'k#<':text x0 -4*d '\#<' ':rL' ball x1 -5*d 0 'k#>':text x0 -5*d '\#>' ':rL' subplot 3 2 1 define a 0.1:define b 0.4:define c 0.5 line a 1 b 1 'k-A':text c 1 'Style `A` or `A\_`' ':rL' line a 0.8 b 0.8 'k-V':text c 0.8 'Style `V` or `V\_`' ':rL' line a 0.6 b 0.6 'k-K':text c 0.6 'Style `K` or `K\_`' ':rL' line a 0.4 b 0.4 'k-I':text c 0.4 'Style `I` or `I\_`' ':rL' line a 0.2 b 0.2 'k-D':text c 0.2 'Style `D` or `D\_`' ':rL' line a 0 b 0 'k-S':text c 0 'Style `S` or `S\_`' ':rL' line a -0.2 b -0.2 'k-O':text c -0.2 'Style `O` or `O\_`' ':rL' line a -0.4 b -0.4 'k-T':text c -0.4 'Style `T` or `T\_`' ':rL' line a -0.6 b -0.6 'k-_':text c -0.6 'Style `\_` or none' ':rL' line a -0.8 b -0.8 'k-AS':text c -0.8 'Style `AS`' ':rL' line a -1 b -1 'k-_A':text c -1 'Style `\_A`' ':rL' define a -1:define b -0.7:define c -0.6 line a 1 b 1 'kAA':text c 1 'Style `AA`' ':rL' line a 0.8 b 0.8 'kVV':text c 0.8 'Style `VV`' ':rL' line a 0.6 b 0.6 'kKK':text c 0.6 'Style `KK`' ':rL' line a 0.4 b 0.4 'kII':text c 0.4 'Style `II`' ':rL' line a 0.2 b 0.2 'kDD':text c 0.2 'Style `DD`' ':rL' line a 0 b 0 'kSS':text c 0 'Style `SS`' ':rL' line a -0.2 b -0.2 'kOO':text c -0.2 'Style `OO`' ':rL' line a -0.4 b -0.4 'kTT':text c -0.4 'Style `TT`' ':rL' line a -0.6 b -0.6 'k-__':text c -0.6 'Style `\_\_`' ':rL' line a -0.8 b -0.8 'k-VA':text c -0.8 'Style `VA`' ':rL' line a -1 b -1 'k-AV':text c -1 'Style `AV`' ':rL' subplot 3 2 2 #LENUQ facez -1 -1 0 0.4 0.3 'L#':text -0.8 -0.9 'L' 'w:C' -1.4 facez -0.6 -1 0 0.4 0.3 'E#':text -0.4 -0.9 'E' 'w:C' -1.4 facez -0.2 -1 0 0.4 0.3 'N#':text 0 -0.9 'N' 'w:C' -1.4 facez 0.2 -1 0 0.4 0.3 'U#':text 0.4 -0.9 'U' 'w:C' -1.4 facez 0.6 -1 0 0.4 0.3 'Q#':text 0.8 -0.9 'Q' 'w:C' -1.4 #lenuq facez -1 -0.7 0 0.4 0.3 'l#':text -0.8 -0.6 'l' 'k:C' -1.4 facez -0.6 -0.7 0 0.4 0.3 'e#':text -0.4 -0.6 'e' 'k:C' -1.4 facez -0.2 -0.7 0 0.4 0.3 'n#':text 0 -0.6 'n' 'k:C' -1.4 facez 0.2 -0.7 0 0.4 0.3 'u#':text 0.4 -0.6 'u' 'k:C' -1.4 facez 0.6 -0.7 0 0.4 0.3 'q#':text 0.8 -0.6 'q' 'k:C' -1.4 #CMYkP facez -1 -0.4 0 0.4 0.3 'C#':text -0.8 -0.3 'C' 'w:C' -1.4 facez -0.6 -0.4 0 0.4 0.3 'M#':text -0.4 -0.3 'M' 'w:C' -1.4 facez -0.2 -0.4 0 0.4 0.3 'Y#':text 0 -0.3 'Y' 'w:C' -1.4 facez 0.2 -0.4 0 0.4 0.3 'k#':text 0.4 -0.3 'k' 'w:C' -1.4 facez 0.6 -0.4 0 0.4 0.3 'P#':text 0.8 -0.3 'P' 'w:C' -1.4 #cmywp facez -1 -0.1 0 0.4 0.3 'c#':text -0.8 0 'c' 'k:C' -1.4 facez -0.6 -0.1 0 0.4 0.3 'm#':text -0.4 0 'm' 'k:C' -1.4 facez -0.2 -0.1 0 0.4 0.3 'y#':text 0 0 'y' 'k:C' -1.4 facez 0.2 -0.1 0 0.4 0.3 'w#':text 0.4 0 'w' 'k:C' -1.4 facez 0.6 -0.1 0 0.4 0.3 'p#':text 0.8 0 'p' 'k:C' -1.4 #BGRHW facez -1 0.2 0 0.4 0.3 'B#':text -0.8 0.3 'B' 'w:C' -1.4 facez -0.6 0.2 0 0.4 0.3 'G#':text -0.4 0.3 'G' 'w:C' -1.4 facez -0.2 0.2 0 0.4 0.3 'R#':text 0 0.3 'R' 'w:C' -1.4 facez 0.2 0.2 0 0.4 0.3 'H#':text 0.4 0.3 'H' 'w:C' -1.4 facez 0.6 0.2 0 0.4 0.3 'W#':text 0.8 0.3 'W' 'w:C' -1.4 #bgrhw facez -1 0.5 0 0.4 0.3 'b#':text -0.8 0.6 'b' 'k:C' -1.4 facez -0.6 0.5 0 0.4 0.3 'g#':text -0.4 0.6 'g' 'k:C' -1.4 facez -0.2 0.5 0 0.4 0.3 'r#':text 0 0.6 'r' 'k:C' -1.4 facez 0.2 0.5 0 0.4 0.3 'h#':text 0.4 0.6 'h' 'k:C' -1.4 facez 0.6 0.5 0 0.4 0.3 'w#':text 0.8 0.6 'w' 'k:C' -1.4 #brighted facez -1 0.8 0 0.4 0.3 '{r1}#':text -0.8 0.9 '\{r1\}' 'w:C' -1.4 facez -0.6 0.8 0 0.4 0.3 '{r3}#':text -0.4 0.9 '\{r3\}' 'w:C' -1.4 facez -0.2 0.8 0 0.4 0.3 '{r5}#':text 0 0.9 '\{r5\}' 'k:C' -1.4 facez 0.2 0.8 0 0.4 0.3 '{r7}#':text 0.4 0.9 '\{r7\}' 'k:C' -1.4 facez 0.6 0.8 0 0.4 0.3 '{r9}#':text 0.8 0.9 '\{r9\}' 'k:C' -1.4 # HEX facez -1 -1.3 0 1 0.3 '{xff9966}#':text -0.5 -1.2 '\{xff9966\}' 'k:C' -1.4 facez 0 -1.3 0 1 0.3 '{x83CAFF}#':text 0.5 -1.2 '\{x83caff\}' 'k:C' -1.4 subplot 3 2 3 for $i 0 9 line -1 0.2*$i-1 1 0.2*$i-1 'r','0'+$i text 1.05 0.2*$i-1 '0'+$i ':L' next subplot 3 2 4:title 'TriPlot sample':rotate 50 60 list tt 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0:list yt -1 -1 1 0:list zt -1 -1 -1 1:light on triplot tt xt yt zt 'b':triplot tt xt yt zt 'k#' subplot 3 2 5:new r 4 'i+1':ranges 1 4 1 4 axis:mark r r 's':plot r 'b'
C++ code:
void smgl_quality8(mglGraph *gr) // test file export { gr->SetQuality(8); all_prims(gr); }
The radar plot is variant of plot, which make plot in polar coordinates and draw radial rays in point directions. If you just need a plot in polar coordinates then I recommend to use Curvilinear coordinates or plot in parametric form with x=r*cos(fi); y=r*sin(fi);
.
MGL code:
new yr 10 3 '0.4*sin(pi*(x+1.5+y/2)+0.1*rnd)' subplot 1 1 0 '':title 'Radar plot (with grid, "\#")':radar yr '#'
C++ code:
void smgl_radar(mglGraph *gr) { mglData yr(10,3); yr.Modify("0.4*sin(pi*(2*x+y))+0.1*rnd"); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("Radar plot (with grid, '\\#')"); } gr->Radar(yr,"#"); }
Example of refill and gspline.
MGL code:
new x 10 '0.5+rnd':cumsum x 'x':norm x -1 1 copy y sin(pi*x)/1.5 subplot 2 2 0 '<_':title 'Refill sample' box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:' new r 100:refill r x y:plot r 'r' subplot 2 2 1 '<_':title 'Global spline' box:axis:plot x y 'o ':fplot 'sin(pi*x)/1.5' 'B:' new r 100:gspline r x y:plot r 'r' new y 10 '0.5+rnd':cumsum y 'x':norm y -1 1 copy xx x:extend xx 10 copy yy y:extend yy 10:transpose yy copy z sin(pi*xx*yy)/1.5 alpha on:light on subplot 2 2 2:title '2d regular':rotate 40 60 box:axis:mesh xx yy z 'k' new rr 100 100:refill rr x y z:surf rr new xx 10 10 '(x+1)/2*cos(y*pi/2-1)':new yy 10 10 '(x+1)/2*sin(y*pi/2-1)' copy z sin(pi*xx*yy)/1.5 subplot 2 2 3:title '2d non-regular':rotate 40 60 box:axis:plot xx yy z 'ko ' new rr 100 100:refill rr xx yy z:surf rr
C++ code:
void smgl_refill(mglGraph *gr) { mglData x(10), y(10), r(100); x.Modify("0.5+rnd"); x.CumSum("x"); x.Norm(-1,1); y.Modify("sin(pi*v)/1.5",x); if(big!=3) { gr->SubPlot(2,2,0,"<_"); gr->Title("Refill sample"); } gr->Axis(); gr->Box(); gr->Plot(x,y,"o "); gr->Refill(r,x,y); // or you can use r.Refill(x,y,-1,1); gr->Plot(r,"r"); gr->FPlot("sin(pi*x)/1.5","B:"); if(big==3) return; gr->SubPlot(2,2,1,"<_"); gr->Title("Global spline"); gr->Axis(); gr->Box(); gr->Plot(x,y,"o "); r.RefillGS(x,y,-1,1); gr->Plot(r,"r"); gr->FPlot("sin(pi*x)/1.5","B:"); gr->Alpha(true); gr->Light(true); mglData z(10,10), xx(10,10), yy(10,10), rr(100,100); y.Modify("0.5+rnd"); y.CumSum("x"); y.Norm(-1,1); for(int i=0;i<10;i++) for(int j=0;j<10;j++) z.a[i+10*j] = sin(M_PI*x.a[i]*y.a[j])/1.5; gr->SubPlot(2,2,2); gr->Title("2d regular"); gr->Rotate(40,60); gr->Axis(); gr->Box(); gr->Mesh(x,y,z,"k"); gr->Refill(rr,x,y,z); gr->Surf(rr); gr->Fill(xx,"(x+1)/2*cos(y*pi/2-1)"); gr->Fill(yy,"(x+1)/2*sin(y*pi/2-1)"); for(int i=0;i<10*10;i++) z.a[i] = sin(M_PI*xx.a[i]*yy.a[i])/1.5; gr->SubPlot(2,2,3); gr->Title("2d non-regular"); gr->Rotate(40,60); gr->Axis(); gr->Box(); gr->Plot(xx,yy,z,"ko "); gr->Refill(rr,xx,yy,z); gr->Surf(rr); }
Function region fill the area between 2 curves. It support gradient filling if 2 colors per curve is specified. Also it can fill only the region y1<y<y2 if style ‘i’ is used.
MGL code:
call 'prepare1d' copy y1 y(:,1):copy y2 y(:,2) subplot 2 2 0 '':title 'Region plot (default)':box:region y1 y2:plot y1 'k2':plot y2 'k2' subplot 2 2 1 '':title '2 colors':box:region y1 y2 'yr':plot y1 'k2':plot y2 'k2' subplot 2 2 2 '':title '"i" style':box:region y1 y2 'ir':plot y1 'k2':plot y2 'k2' subplot 2 2 3 '^_':title '3d variant':rotate 40 60:box new x1 100 'sin(pi*x)':new y1 100 'cos(pi*x)':new z 100 'x' new x2 100 'sin(pi*x+pi/3)':new y2 100 'cos(pi*x+pi/3)' plot x1 y1 z 'r2':plot x2 y2 z 'b2' region x1 y1 z x2 y2 z 'cmy!'
C++ code:
void smgl_region(mglGraph *gr) { mglData y; mgls_prepare1d(&y); mglData y1 = y.SubData(-1,1), y2 = y.SubData(-1,2); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Region plot (default)"); } gr->Box(); gr->Region(y1,y2); gr->Plot(y1,"k2"); gr->Plot(y2,"k2"); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Title("2 colors"); gr->Box(); gr->Region(y1,y2,"yr"); gr->Plot(y1,"k2"); gr->Plot(y2,"k2"); gr->SubPlot(2,2,2,""); gr->Title("'i' style"); gr->Box(); gr->Region(y1,y2,"ir"); gr->Plot(y1,"k2"); gr->Plot(y2,"k2"); gr->SubPlot(2,2,3,"^_"); gr->Title("3d variant"); gr->Rotate(40,60); gr->Box(); gr->Fill(y1,"cos(pi*x)"); gr->Fill(y2,"cos(pi*x+pi/3)"); mglData x1(y1.nx), x2(y1.nx), z(y1.nx); gr->Fill(x1,"sin(pi*x)"); gr->Fill(x2,"sin(pi*x+pi/3)"); gr->Fill(z,"x"); gr->Plot(x1,y1,z,"r2"); gr->Plot(x2,y2,z,"b2"); gr->Region(x1,y1,z,x2,y2,z,"cmy!"); }
Example of scanfile for reading ’named’ data.
MGL code:
subplot 1 1 0 '<_':title 'Save and scanfile sample' list a 1 -1 0 save 'This is test: 0 -> ',a(0),' q' 'test.txt' 'w' save 'This is test: 1 -> ',a(1),' q' 'test.txt' save 'This is test: 2 -> ',a(2),' q' 'test.txt' scanfile a 'test.txt' 'This is test: %g -> %g' ranges a(0) a(1):axis:plot a(0) a(1) 'o'
C++ code:
void smgl_scanfile(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Save and scanfile sample"); FILE *fp=fopen("test.txt","w"); fprintf(fp,"This is test: 0 -> 1 q\n"); fprintf(fp,"This is test: 1 -> -1 q\n"); fprintf(fp,"This is test: 2 -> 0 q\n"); fclose(fp); mglData a; a.ScanFile("test.txt","This is test: %g -> %g"); gr->SetRanges(a.SubData(0), a.SubData(1)); gr->Axis(); gr->Plot(a.SubData(0),a.SubData(1),"o"); }
Example of popular color schemes.
MGL code:
new x 100 100 'x':new y 100 100 'y' call 'sch' 0 'kw' call 'sch' 1 '%gbrw' call 'sch' 2 'kHCcw' call 'sch' 3 'kBbcw' call 'sch' 4 'kRryw' call 'sch' 5 'kGgew' call 'sch' 6 'BbwrR' call 'sch' 7 'BbwgG' call 'sch' 8 'GgwmM' call 'sch' 9 'UuwqR' call 'sch' 10 'QqwcC' call 'sch' 11 'CcwyY' call 'sch' 12 'bcwyr' call 'sch' 13 'bwr' call 'sch' 14 'wUrqy' call 'sch' 15 'UbcyqR' call 'sch' 16 'BbcyrR' call 'sch' 17 'bgr' call 'sch' 18 'BbcyrR|' call 'sch' 19 'b{g,0.3}r' stop func 'sch' 2 subplot 2 10 $1 '<>_^' 0.2 0:surfa x y $2 text 0.07+0.5*mod($1,2) 0.92-0.1*int($1/2) $2 'A' return
C++ code:
void smgl_schemes(mglGraph *gr) // Color table { mglData a(256,2), b(256,2); a.Fill(-1,1); b.Fill(-1,1,'y'); gr->SubPlot(2,10,0,NULL,0.2); gr->Dens(a,"kw"); gr->Puts(0.07, 0.92, "kw", "A"); gr->SubPlot(2,10,1,NULL,0.2); gr->SurfA(a,b,"%gbrw"); gr->Puts(0.57, 0.92, "%gbrw", "A"); gr->SubPlot(2,10,2,NULL,0.2); gr->Dens(a,"kHCcw"); gr->Puts(0.07, 0.82, "kHCcw", "A"); gr->SubPlot(2,10,3,NULL,0.2); gr->Dens(a,"kBbcw"); gr->Puts(0.57, 0.82, "kBbcw", "A"); gr->SubPlot(2,10,4,NULL,0.2); gr->Dens(a,"kRryw"); gr->Puts(0.07, 0.72, "kRryw", "A"); gr->SubPlot(2,10,5,NULL,0.2); gr->Dens(a,"kGgew"); gr->Puts(0.57, 0.72, "kGgew", "A"); gr->SubPlot(2,10,6,NULL,0.2); gr->Dens(a,"BbwrR"); gr->Puts(0.07, 0.62, "BbwrR", "A"); gr->SubPlot(2,10,7,NULL,0.2); gr->Dens(a,"BbwgG"); gr->Puts(0.57, 0.62, "BbwgG", "A"); gr->SubPlot(2,10,8,NULL,0.2); gr->Dens(a,"GgwmM"); gr->Puts(0.07, 0.52, "GgwmM", "A"); gr->SubPlot(2,10,9,NULL,0.2); gr->Dens(a,"UuwqR"); gr->Puts(0.57, 0.52, "UuwqR", "A"); gr->SubPlot(2,10,10,NULL,0.2); gr->Dens(a,"QqwcC"); gr->Puts(0.07, 0.42, "QqwcC", "A"); gr->SubPlot(2,10,11,NULL,0.2); gr->Dens(a,"CcwyY"); gr->Puts(0.57, 0.42, "CcwyY", "A"); gr->SubPlot(2,10,12,NULL,0.2); gr->Dens(a,"bcwyr"); gr->Puts(0.07, 0.32, "bcwyr", "A"); gr->SubPlot(2,10,13,NULL,0.2); gr->Dens(a,"bwr"); gr->Puts(0.57, 0.32, "bwr", "A"); gr->SubPlot(2,10,14,NULL,0.2); gr->Dens(a,"wUrqy"); gr->Puts(0.07, 0.22, "wUrqy", "A"); gr->SubPlot(2,10,15,NULL,0.2); gr->Dens(a,"UbcyqR"); gr->Puts(0.57, 0.22, "UbcyqR", "A"); gr->SubPlot(2,10,16,NULL,0.2); gr->Dens(a,"BbcyrR"); gr->Puts(0.07, 0.12, "BbcyrR", "A"); gr->SubPlot(2,10,17,NULL,0.2); gr->Dens(a,"bgr"); gr->Puts(0.57, 0.12, "bgr", "A"); gr->SubPlot(2,10,18,NULL,0.2); gr->Dens(a,"BbcyrR|"); gr->Puts(0.07, 0.02, "BbcyrR|", "A"); gr->SubPlot(2,10,19,NULL,0.2); gr->Dens(a,"b{g,0.3}r"); gr->Puts(0.57, 0.02, "b\\{g,0.3\\}r", "A"); }
Example of section to separate data and join it back.
MGL code:
subplot 1 1 0 '<_':title 'Section&Join sample' axis:box:line -1 0 1 0 'h:' # first lets demonstrate 'join' new aa 11 'x^2':new a1 3 '-x':new a2 15 'x^3' join aa a1:join aa a2 # add x-coordinate new xx aa.nx 'x':join aa xx plot aa(:,1) aa(:,0) '2y' # now select 1-st (id=0) section between zeros section b1 aa 0 'x' 0 plot b1(:,1) b1(:,0) 'bo' # next, select 3-d (id=2) section between zeros section b3 aa 2 'x' 0 plot b3(:,1) b3(:,0) 'gs' # finally, select 2-nd (id=-2) section from the end section b4 aa -2 'x' 0 plot b4(:,1) b4(:,0) 'r#o'
C++ code:
void smgl_section(mglGraph *gr) { gr->SubPlot(1,1,0,"<_"); if(big!=3) gr->Title("Section&Join sample"); gr->Axis(); gr->Box(); gr->Line(mglPoint(-1,0),mglPoint(1,0),"h:"); // first lets demonstrate 'join' mglData aa(11), a1(3), a2(15); gr->Fill(aa,"x^2"); gr->Fill(a1,"-x"); gr->Fill(a2,"x^3"); aa.Join(a1); aa.Join(a2); // add x-coordinate mglData xx(aa.nx); gr->Fill(xx,"x"); aa.Join(xx); gr->Plot(aa.SubData(-1,1), aa.SubData(-1,0), "2y"); // now select 1-st (id=0) section between zeros mglData b1(aa.Section(0,'x',0)); gr->Plot(b1.SubData(-1,1), b1.SubData(-1,0), "bo"); // next, select 3-d (id=2) section between zeros mglData b2(aa.Section(2,'x',0)); gr->Plot(b2.SubData(-1,1), b2.SubData(-1,0), "gs"); // finally, select 2-nd (id=-2) section from the end mglData b3(aa.Section(-2,'x',0)); gr->Plot(b3.SubData(-1,1), b3.SubData(-1,0), "r#o"); }
Example of using several light sources.
MGL code:
call 'prepare2d' title 'Several light sources':rotate 50 60:light on light 1 0 1 0 'c':light 2 1 0 0 'y':light 3 0 -1 0 'm' box:surf a 'h'
C++ code:
void smgl_several_light(mglGraph *gr) // several light sources { mglData a; mgls_prepare2d(&a); if(big!=3) 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"); }
Example of solve for root finding.
MGL code:
zrange 0 1 new x 20 30 '(x+2)/3*cos(pi*y)' new y 20 30 '(x+2)/3*sin(pi*y)' new z 20 30 'exp(-6*x^2-2*sin(pi*y)^2)' subplot 2 1 0:title 'Cartesian space':rotate 30 -40 axis 'xyzU':box xlabel 'x':ylabel 'y' origin 1 1:grid 'xy' mesh x y z # section along 'x' direction solve u x 0.5 'x' var v u.nx 0 1 evaluate yy y u v evaluate xx x u v evaluate zz z u v plot xx yy zz 'k2o' # 1st section along 'y' direction solve u1 x -0.5 'y' var v1 u1.nx 0 1 evaluate yy y v1 u1 evaluate xx x v1 u1 evaluate zz z v1 u1 plot xx yy zz 'b2^' # 2nd section along 'y' direction solve u2 x -0.5 'y' u1 evaluate yy y v1 u2 evaluate xx x v1 u2 evaluate zz z v1 u2 plot xx yy zz 'r2v' subplot 2 1 1:title 'Accompanied space' ranges 0 1 0 1:origin 0 0 axis:box:xlabel 'i':ylabel 'j':grid2 z 'h' plot u v 'k2o':line 0.4 0.5 0.8 0.5 'kA' plot v1 u1 'b2^':line 0.5 0.15 0.5 0.3 'bA' plot v1 u2 'r2v':line 0.5 0.7 0.5 0.85 'rA'
C++ code:
void smgl_solve(mglGraph *gr) // solve and evaluate { gr->SetRange('z',0,1); mglData x(20,30), y(20,30), z(20,30), xx,yy,zz; gr->Fill(x,"(x+2)/3*cos(pi*y)"); gr->Fill(y,"(x+2)/3*sin(pi*y)"); gr->Fill(z,"exp(-6*x^2-2*sin(pi*y)^2)"); gr->SubPlot(2,1,0); gr->Title("Cartesian space"); gr->Rotate(30,-40); gr->Axis("xyzU"); gr->Box(); gr->Label('x',"x"); gr->Label('y',"y"); gr->SetOrigin(1,1); gr->Grid("xy"); gr->Mesh(x,y,z); // section along 'x' direction mglData u = x.Solve(0.5,'x'); mglData v(u.nx); v.Fill(0,1); xx = x.Evaluate(u,v); yy = y.Evaluate(u,v); zz = z.Evaluate(u,v); gr->Plot(xx,yy,zz,"k2o"); // 1st section along 'y' direction mglData u1 = x.Solve(-0.5,'y'); mglData v1(u1.nx); v1.Fill(0,1); xx = x.Evaluate(v1,u1); yy = y.Evaluate(v1,u1); zz = z.Evaluate(v1,u1); gr->Plot(xx,yy,zz,"b2^"); // 2nd section along 'y' direction mglData u2 = x.Solve(-0.5,'y',u1); xx = x.Evaluate(v1,u2); yy = y.Evaluate(v1,u2); zz = z.Evaluate(v1,u2); gr->Plot(xx,yy,zz,"r2v"); gr->SubPlot(2,1,1); gr->Title("Accompanied space"); gr->SetRanges(0,1,0,1); gr->SetOrigin(0,0); gr->Axis(); gr->Box(); gr->Label('x',"i"); gr->Label('y',"j"); gr->Grid(z,"h"); gr->Plot(u,v,"k2o"); gr->Line(mglPoint(0.4,0.5),mglPoint(0.8,0.5),"kA"); gr->Plot(v1,u1,"b2^"); gr->Line(mglPoint(0.5,0.15),mglPoint(0.5,0.3),"bA"); gr->Plot(v1,u2,"r2v"); gr->Line(mglPoint(0.5,0.7),mglPoint(0.5,0.85),"rA"); }
Function stem draw vertical bars. It is most attractive if markers are drawn too.
MGL code:
call 'prepare1d' origin 0 0 0:subplot 2 2 0 '':title 'Stem plot (default)':box:stem y new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box:stem xc yc z 'rx' subplot 2 2 2 '':title '"!" style':box:stem y 'o!rgb'
C++ code:
void smgl_stem(mglGraph *gr) { mglData y; mgls_prepare1d(&y); gr->SetOrigin(0,0,0); mglData yc(30), xc(30), z(30); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Stem plot (default)"); } gr->Box(); gr->Stem(y); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); gr->Stem(xc,yc,z,"rx"); gr->SubPlot(2,2,2,""); gr->Title("'!' style"); gr->Box(); gr->Stem(y,"o!rgb"); }
Function step plot data as stairs. At this stairs can be centered if sizes are differ by 1.
MGL code:
call 'prepare1d' origin 0 0 0:subplot 2 2 0 '':title 'Step plot (default)':box:step y new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box:step xc yc z 'r' subplot 2 2 2 '':title '"!" style':box:step y 's!rgb'
C++ code:
void smgl_step(mglGraph *gr) { mglData y; mgls_prepare1d(&y); gr->SetOrigin(0,0,0); mglData yc(30), xc(30), z(30); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Step plot (default)"); } gr->Box(); gr->Step(y); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); gr->Step(xc,yc,z,"r"); gr->SubPlot(2,2,2,""); gr->Title("'!' style"); gr->Box(); gr->Step(y,"s!rgb"); }
Example of stereo image of surf.
MGL code:
call 'prepare2d' light on subplot 2 1 0:rotate 50 60+1:box:surf a subplot 2 1 1:rotate 50 60-1:box:surf a
C++ code:
void smgl_stereo(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); }
Example of stfa.
MGL code:
new a 2000:new b 2000 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)' subplot 1 2 0 '<_':title 'Initial signal':plot a:axis:xlabel '\i t' subplot 1 2 1 '<_':title 'STFA plot':stfa a b 64:axis:ylabel '\omega' 0:xlabel '\i t'
C++ code:
void smgl_stfa(mglGraph *gr) // STFA sample { 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); }
Example of colors and styles for plots.
MGL code:
C++ code:
void smgl_style(mglGraph *gr) // pen styles { gr->SubPlot(2,2,0); double d,x1,x2,x0,y=1.1, y1=1.15; d=0.3, x0=0.2, x1=0.5, x2=0.6; gr->Line(mglPoint(x0,y1-0*d),mglPoint(x1,y1-0*d),"k-"); gr->Puts(mglPoint(x2,y-0*d),"Solid '-'",":rL"); gr->Line(mglPoint(x0,y1-1*d),mglPoint(x1,y1-1*d),"k|"); gr->Puts(mglPoint(x2,y-1*d),"Long Dash '|'",":rL"); gr->Line(mglPoint(x0,y1-2*d),mglPoint(x1,y1-2*d),"k;"); gr->Puts(mglPoint(x2,y-2*d),"Dash ';'",":rL"); gr->Line(mglPoint(x0,y1-3*d),mglPoint(x1,y1-3*d),"k="); gr->Puts(mglPoint(x2,y-3*d),"Small dash '='",":rL"); gr->Line(mglPoint(x0,y1-4*d),mglPoint(x1,y1-4*d),"kj"); gr->Puts(mglPoint(x2,y-4*d),"Dash-dot 'j'",":rL"); gr->Line(mglPoint(x0,y1-5*d),mglPoint(x1,y1-5*d),"ki"); gr->Puts(mglPoint(x2,y-5*d),"Small dash-dot 'i'",":rL"); gr->Line(mglPoint(x0,y1-6*d),mglPoint(x1,y1-6*d),"k:"); gr->Puts(mglPoint(x2,y-6*d),"Dots ':'",":rL"); gr->Line(mglPoint(x0,y1-7*d),mglPoint(x1,y1-7*d),"k "); gr->Puts(mglPoint(x2,y-7*d),"None ' '",":rL"); gr->Line(mglPoint(x0,y1-8*d),mglPoint(x1,y1-8*d),"k{df090}"); gr->Puts(mglPoint(x2,y-8*d),"Manual '{df090}'",":rL"); d=0.25; x1=-1; x0=-0.8; y = -0.05; gr->Mark(mglPoint(x1,5*d),"k."); gr->Puts(mglPoint(x0,y+5*d),"'.'",":rL"); gr->Mark(mglPoint(x1,4*d),"k+"); gr->Puts(mglPoint(x0,y+4*d),"'+'",":rL"); gr->Mark(mglPoint(x1,3*d),"kx"); gr->Puts(mglPoint(x0,y+3*d),"'x'",":rL"); gr->Mark(mglPoint(x1,2*d),"k*"); gr->Puts(mglPoint(x0,y+2*d),"'*'",":rL"); gr->Mark(mglPoint(x1,d),"ks"); gr->Puts(mglPoint(x0,y+d),"'s'",":rL"); gr->Mark(mglPoint(x1,0),"kd"); gr->Puts(mglPoint(x0,y),"'d'",":rL"); gr->Mark(mglPoint(x1,-d,0),"ko"); gr->Puts(mglPoint(x0,y-d),"'o'",":rL"); gr->Mark(mglPoint(x1,-2*d,0),"k^"); gr->Puts(mglPoint(x0,y-2*d),"'\\^'",":rL"); gr->Mark(mglPoint(x1,-3*d,0),"kv"); gr->Puts(mglPoint(x0,y-3*d),"'v'",":rL"); gr->Mark(mglPoint(x1,-4*d,0),"k<"); gr->Puts(mglPoint(x0,y-4*d),"'<'",":rL"); gr->Mark(mglPoint(x1,-5*d,0),"k>"); gr->Puts(mglPoint(x0,y-5*d),"'>'",":rL"); d=0.25; x1=-0.5; x0=-0.3; y = -0.05; gr->Mark(mglPoint(x1,5*d),"k#."); gr->Puts(mglPoint(x0,y+5*d),"'\\#.'",":rL"); gr->Mark(mglPoint(x1,4*d),"k#+"); gr->Puts(mglPoint(x0,y+4*d),"'\\#+'",":rL"); gr->Mark(mglPoint(x1,3*d),"k#x"); gr->Puts(mglPoint(x0,y+3*d),"'\\#x'",":rL"); gr->Mark(mglPoint(x1,2*d),"k#*"); gr->Puts(mglPoint(x0,y+2*d),"'\\#*'",":rL"); gr->Mark(mglPoint(x1,d),"k#s"); gr->Puts(mglPoint(x0,y+d),"'\\#s'",":rL"); gr->Mark(mglPoint(x1,0),"k#d"); gr->Puts(mglPoint(x0,y),"'\\#d'",":rL"); gr->Mark(mglPoint(x1,-d,0),"k#o"); gr->Puts(mglPoint(x0,y-d),"'\\#o'",":rL"); gr->Mark(mglPoint(x1,-2*d,0),"k#^"); gr->Puts(mglPoint(x0,y-2*d),"'\\#\\^'",":rL"); gr->Mark(mglPoint(x1,-3*d,0),"k#v"); gr->Puts(mglPoint(x0,y-3*d),"'\\#v'",":rL"); gr->Mark(mglPoint(x1,-4*d,0),"k#<"); gr->Puts(mglPoint(x0,y-4*d),"'\\#<'",":rL"); gr->Mark(mglPoint(x1,-5*d,0),"k#>"); gr->Puts(mglPoint(x0,y-5*d),"'\\#>'",":rL"); gr->SubPlot(2,2,1); double a=0.1,b=0.4,c=0.5; gr->Line(mglPoint(a,1),mglPoint(b,1),"k-A"); gr->Puts(mglPoint(c,1),"Style 'A' or 'A\\_'",":rL"); gr->Line(mglPoint(a,0.8),mglPoint(b,0.8),"k-V"); gr->Puts(mglPoint(c,0.8),"Style 'V' or 'V\\_'",":rL"); gr->Line(mglPoint(a,0.6),mglPoint(b,0.6),"k-K"); gr->Puts(mglPoint(c,0.6),"Style 'K' or 'K\\_'",":rL"); gr->Line(mglPoint(a,0.4),mglPoint(b,0.4),"k-I"); gr->Puts(mglPoint(c,0.4),"Style 'I' or 'I\\_'",":rL"); gr->Line(mglPoint(a,0.2),mglPoint(b,0.2),"k-D"); gr->Puts(mglPoint(c,0.2),"Style 'D' or 'D\\_'",":rL"); gr->Line(mglPoint(a,0),mglPoint(b,0),"k-S"); gr->Puts(mglPoint(c,0),"Style 'S' or 'S\\_'",":rL"); gr->Line(mglPoint(a,-0.2),mglPoint(b,-0.2),"k-O"); gr->Puts(mglPoint(c,-0.2),"Style 'O' or 'O\\_'",":rL"); gr->Line(mglPoint(a,-0.4),mglPoint(b,-0.4),"k-T"); gr->Puts(mglPoint(c,-0.4),"Style 'T' or 'T\\_'",":rL"); gr->Line(mglPoint(a,-0.6),mglPoint(b,-0.6),"k-X"); gr->Puts(mglPoint(c,-0.6),"Style 'X' or 'X\\_'",":rL"); gr->Line(mglPoint(a,-0.8),mglPoint(b,-0.8),"k-_"); gr->Puts(mglPoint(c,-0.8),"Style '\\_' or none",":rL"); gr->Line(mglPoint(a,-1),mglPoint(b,-1),"k-AS"); gr->Puts(mglPoint(c,-1),"Style 'AS'",":rL"); gr->Line(mglPoint(a,-1.2),mglPoint(b,-1.2),"k-_A"); gr->Puts(mglPoint(c,-1.2),"Style '\\_A'",":rL"); a=-1; b=-0.7; c=-0.6; gr->Line(mglPoint(a,1),mglPoint(b,1),"kAA"); gr->Puts(mglPoint(c,1),"Style 'AA'",":rL"); gr->Line(mglPoint(a,0.8),mglPoint(b,0.8),"kVV"); gr->Puts(mglPoint(c,0.8),"Style 'VV'",":rL"); gr->Line(mglPoint(a,0.6),mglPoint(b,0.6),"kKK"); gr->Puts(mglPoint(c,0.6),"Style 'KK'",":rL"); gr->Line(mglPoint(a,0.4),mglPoint(b,0.4),"kII"); gr->Puts(mglPoint(c,0.4),"Style 'II'",":rL"); gr->Line(mglPoint(a,0.2),mglPoint(b,0.2),"kDD"); gr->Puts(mglPoint(c,0.2),"Style 'DD'",":rL"); gr->Line(mglPoint(a,0),mglPoint(b,0),"kSS"); gr->Puts(mglPoint(c,0),"Style 'SS'",":rL"); gr->Line(mglPoint(a,-0.2),mglPoint(b,-0.2),"kOO"); gr->Puts(mglPoint(c,-0.2),"Style 'OO'",":rL"); gr->Line(mglPoint(a,-0.4),mglPoint(b,-0.4),"kTT"); gr->Puts(mglPoint(c,-0.4),"Style 'TT'",":rL"); gr->Line(mglPoint(a,-0.6),mglPoint(b,-0.6),"kXX"); gr->Puts(mglPoint(c,-0.6),"Style 'XX'",":rL"); gr->Line(mglPoint(a,-0.8),mglPoint(b,-0.8),"k-__"); gr->Puts(mglPoint(c,-0.8),"Style '\\_\\_'",":rL"); gr->Line(mglPoint(a,-1),mglPoint(b,-1),"k-VA"); gr->Puts(mglPoint(c,-1),"Style 'VA'",":rL"); gr->Line(mglPoint(a,-1.2),mglPoint(b,-1.2),"k-AV"); gr->Puts(mglPoint(c,-1.2),"Style 'AV'",":rL"); gr->SubPlot(2,2,2); //#LENUQ gr->FaceZ(mglPoint(-1, -1), 0.4, 0.3, "L#"); gr->Puts(mglPoint(-0.8,-0.9), "L", "w:C", -1.4); gr->FaceZ(mglPoint(-0.6,-1), 0.4, 0.3, "E#"); gr->Puts(mglPoint(-0.4,-0.9), "E", "w:C", -1.4); gr->FaceZ(mglPoint(-0.2,-1), 0.4, 0.3, "N#"); gr->Puts(mglPoint(0, -0.9), "N", "w:C", -1.4); gr->FaceZ(mglPoint(0.2, -1), 0.4, 0.3, "U#"); gr->Puts(mglPoint(0.4,-0.9), "U", "w:C", -1.4); gr->FaceZ(mglPoint(0.6, -1), 0.4, 0.3, "Q#"); gr->Puts(mglPoint(0.8,-0.9), "Q", "w:C", -1.4); //#lenuq gr->FaceZ(mglPoint(-1, -0.7), 0.4, 0.3, "l#"); gr->Puts(mglPoint(-0.8,-0.6), "l", "k:C", -1.4); gr->FaceZ(mglPoint(-0.6,-0.7), 0.4, 0.3, "e#"); gr->Puts(mglPoint(-0.4,-0.6), "e", "k:C", -1.4); gr->FaceZ(mglPoint(-0.2,-0.7), 0.4, 0.3, "n#"); gr->Puts(mglPoint(0, -0.6), "n", "k:C", -1.4); gr->FaceZ(mglPoint(0.2, -0.7), 0.4, 0.3, "u#"); gr->Puts(mglPoint(0.4,-0.6), "u", "k:C", -1.4); gr->FaceZ(mglPoint(0.6, -0.7), 0.4, 0.3, "q#"); gr->Puts(mglPoint(0.8,-0.6), "q", "k:C", -1.4); //#CMYkP gr->FaceZ(mglPoint(-1, -0.4), 0.4, 0.3, "C#"); gr->Puts(mglPoint(-0.8,-0.3), "C", "w:C", -1.4); gr->FaceZ(mglPoint(-0.6,-0.4), 0.4, 0.3, "M#"); gr->Puts(mglPoint(-0.4,-0.3), "M", "w:C", -1.4); gr->FaceZ(mglPoint(-0.2,-0.4), 0.4, 0.3, "Y#"); gr->Puts(mglPoint(0, -0.3), "Y", "w:C", -1.4); gr->FaceZ(mglPoint(0.2, -0.4), 0.4, 0.3, "k#"); gr->Puts(mglPoint(0.4,-0.3), "k", "w:C", -1.4); gr->FaceZ(mglPoint(0.6, -0.4), 0.4, 0.3, "P#"); gr->Puts(mglPoint(0.8,-0.3), "P", "w:C", -1.4); //#cmywp gr->FaceZ(mglPoint(-1, -0.1), 0.4, 0.3, "c#"); gr->Puts(mglPoint(-0.8, 0), "c", "k:C", -1.4); gr->FaceZ(mglPoint(-0.6,-0.1), 0.4, 0.3, "m#"); gr->Puts(mglPoint(-0.4, 0), "m", "k:C", -1.4); gr->FaceZ(mglPoint(-0.2,-0.1), 0.4, 0.3, "y#"); gr->Puts(mglPoint(0, 0), "y", "k:C", -1.4); gr->FaceZ(mglPoint(0.2, -0.1), 0.4, 0.3, "w#"); gr->Puts(mglPoint(0.4, 0), "w", "k:C", -1.4); gr->FaceZ(mglPoint(0.6, -0.1), 0.4, 0.3, "p#"); gr->Puts(mglPoint(0.8, 0), "p", "k:C", -1.4); //#BGRHW gr->FaceZ(mglPoint(-1, 0.2), 0.4, 0.3, "B#"); gr->Puts(mglPoint(-0.8, 0.3), "B", "w:C", -1.4); gr->FaceZ(mglPoint(-0.6,0.2), 0.4, 0.3, "G#"); gr->Puts(mglPoint(-0.4, 0.3), "G", "w:C", -1.4); gr->FaceZ(mglPoint(-0.2,0.2), 0.4, 0.3, "R#"); gr->Puts(mglPoint(0, 0.3), "R", "w:C", -1.4); gr->FaceZ(mglPoint(0.2, 0.2), 0.4, 0.3, "H#"); gr->Puts(mglPoint(0.4, 0.3), "H", "w:C", -1.4); gr->FaceZ(mglPoint(0.6, 0.2), 0.4, 0.3, "W#"); gr->Puts(mglPoint(0.8, 0.3), "W", "w:C", -1.4); //#bgrhw gr->FaceZ(mglPoint(-1, 0.5), 0.4, 0.3, "b#"); gr->Puts(mglPoint(-0.8, 0.6), "b", "k:C", -1.4); gr->FaceZ(mglPoint(-0.6,0.5), 0.4, 0.3, "g#"); gr->Puts(mglPoint(-0.4, 0.6), "g", "k:C", -1.4); gr->FaceZ(mglPoint(-0.2,0.5), 0.4, 0.3, "r#"); gr->Puts(mglPoint(0, 0.6), "r", "k:C", -1.4); gr->FaceZ(mglPoint(0.2, 0.5), 0.4, 0.3, "h#"); gr->Puts(mglPoint(0.4, 0.6), "h", "k:C", -1.4); gr->FaceZ(mglPoint(0.6, 0.5), 0.4, 0.3, "w#"); gr->Puts(mglPoint(0.8, 0.6), "w", "k:C", -1.4); //#brighted gr->FaceZ(mglPoint(-1, 0.8), 0.4, 0.3, "{r1}#"); gr->Puts(mglPoint(-0.8, 0.9), "\\{r1\\}", "w:C", -1.4); gr->FaceZ(mglPoint(-0.6,0.8), 0.4, 0.3, "{r3}#"); gr->Puts(mglPoint(-0.4, 0.9), "\\{r3\\}", "w:C", -1.4); gr->FaceZ(mglPoint(-0.2,0.8), 0.4, 0.3, "{r5}#"); gr->Puts(mglPoint(0, 0.9), "\\{r5\\}", "k:C", -1.4); gr->FaceZ(mglPoint(0.2, 0.8), 0.4, 0.3, "{r7}#"); gr->Puts(mglPoint(0.4, 0.9), "\\{r7\\}", "k:C", -1.4); gr->FaceZ(mglPoint(0.6, 0.8), 0.4, 0.3, "{r9}#"); gr->Puts(mglPoint(0.8, 0.9), "\\{r9\\}", "k:C", -1.4); // HEX gr->FaceZ(mglPoint(-1, -1.3), 1, 0.3, "{xff9966}#"); gr->Puts(mglPoint(-0.5,-1.2), "\\{xff9966\\}", "k:C", -1.4); gr->FaceZ(mglPoint(0, -1.3), 1, 0.3, "{x83CAFF}#"); gr->Puts(mglPoint( 0.5,-1.2), "\\{x83CAFF\\}", "k:C", -1.4); gr->SubPlot(2,2,3); char stl[3]="r1", txt[4]="'1'"; for(int i=0;i<10;i++) { txt[1]=stl[1]='0'+i; gr->Line(mglPoint(-1,0.2*i-1),mglPoint(1,0.2*i-1),stl); gr->Puts(mglPoint(1.05,0.2*i-1),txt,":L"); } }
Function surf is most standard way to visualize 2D data array. Surf
use color scheme for coloring (see Цветовая схема). You can use ‘#’ style for drawing black meshes on the surface.
MGL code:
call 'prepare2d' subplot 2 2 0:title 'Surf plot (default)':rotate 50 60:light on:box:surf a subplot 2 2 1:title '"\#" style; meshnum 10':rotate 50 60:box:surf a '#'; meshnum 10 subplot 2 2 2:title '"." style':rotate 50 60:box:surf a '.' new x 50 40 '0.8*sin(pi*x)*sin(pi*(y+1)/2)' new y 50 40 '0.8*cos(pi*x)*sin(pi*(y+1)/2)' new z 50 40 '0.8*cos(pi*(y+1)/2)' subplot 2 2 3:title 'parametric form':rotate 50 60:box:surf x y z 'BbwrR'
C++ code:
void smgl_surf3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Surf3 plot (default)"); } gr->Rotate(50,60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf3(c); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Surf3(c,"#"); gr->SubPlot(2,2,2); gr->Title("'.' style"); gr->Rotate(50,60); gr->Box(); gr->Surf3(c,"."); }
Function surf3 is one of most suitable (for my opinion) functions to visualize 3D data. It draw the isosurface(s) – surface(s) of constant amplitude (3D analogue of contour lines). You can draw wired isosurfaces if specify ‘#’ style.
MGL code:
call 'prepare3d' light on:alpha on subplot 2 2 0:title 'Surf3 plot (default)' rotate 50 60:box:surf3 c subplot 2 2 1:title '"\#" style' rotate 50 60:box:surf3 c '#' subplot 2 2 2:title '"." style' rotate 50 60:box:surf3 c '.'
C++ code:
void smgl_surf3(mglGraph *gr) { mglData c; mgls_prepare3d(&c); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Surf3 plot (default)"); } gr->Rotate(50,60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf3(c); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Surf3(c,"#"); gr->SubPlot(2,2,2); gr->Title("'.' style"); gr->Rotate(50,60); gr->Box(); gr->Surf3(c,"."); }
Function surf3c is similar to surf3 but its transparency is determined by another data.
MGL code:
call 'prepare3d' title 'Surf3A plot':rotate 50 60:light on:alpha on:box:surf3a c d
C++ code:
void smgl_surf3a(mglGraph *gr) { mglData c,d; mgls_prepare3d(&c,&d); if(big!=3) gr->Title("Surf3A plot"); gr->Rotate(50,60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf3A(c,d); }
Function surf3c is similar to surf3 but its coloring is determined by another data.
MGL code:
call 'prepare3d' title 'Surf3C plot':rotate 50 60:light on:alpha on:box:surf3c c d
C++ code:
void smgl_surf3c(mglGraph *gr) { mglData c,d; mgls_prepare3d(&c,&d); if(big!=3) gr->Title("Surf3C plot"); gr->Rotate(50,60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf3C(c,d); }
Function surf3c is similar to surf3 but its coloring and transparency is determined by another data arrays.
MGL code:
call 'prepare3d' title 'Surf3CA plot':rotate 50 60:light on:alpha on:box:surf3ca c d c
C++ code:
void smgl_surf3ca(mglGraph *gr) { mglData c,d; mgls_prepare3d(&c,&d); if(big!=3) gr->Title("Surf3CA plot"); gr->Rotate(50,60); gr->Light(true); gr->Alpha(true); gr->Box(); gr->Surf3CA(c,d,c); }
Function surfa is similar to surf but its transparency is determined by another data.
MGL code:
call 'prepare2d' title 'SurfA plot':rotate 50 60:light on:alpha on:box:surfa a b
C++ code:
void smgl_surfa(mglGraph *gr) { mglData a,b; mgls_prepare2d(&a,&b); if(big!=3) gr->Title("SurfA plot"); gr->Rotate(50,60); gr->Alpha(true); gr->Light(true); gr->Box(); gr->SurfA(a,b); }
Function surfc is similar to surf but its coloring is determined by another data.
MGL code:
call 'prepare2d' title 'SurfC plot':rotate 50 60:light on:box:surfc a b
C++ code:
void smgl_surfc(mglGraph *gr) { mglData a,b; mgls_prepare2d(&a,&b); if(big!=3) gr->Title("SurfC plot"); gr->Rotate(50,60); gr->Light(true); gr->Box(); gr->SurfC(a,b); }
Function surfca is similar to surf but its coloring and transparency is determined by another data arrays.
MGL code:
call 'prepare2d' title 'SurfCA plot':rotate 50 60:light on:alpha on:box:surfca a b a
C++ code:
void smgl_surfca(mglGraph *gr) { mglData a,b; mgls_prepare2d(&a,&b); if(big!=3) gr->Title("SurfCA plot"); gr->Rotate(50,60); gr->Alpha(true); gr->Light(true); gr->Box(); gr->SurfCA(a,b,a); }
Function table draw table with data values.
MGL code:
new ys 10 3 '0.8*sin(pi*(x+y/4+1.25))+0.2*rnd' subplot 2 2 0:title 'Table sample':box table ys 'y_1\n{}y_2\n{}y_3' subplot 2 2 1:title 'no borders, colored' table ys 'y_1\n{}y_2\n{}y_3' 'r|' subplot 2 2 2:title 'no font decrease' table ys 'y_1\n{}y_2\n{}y_3' '#' subplot 2 2 3:title 'manual width and position':box table 0.5 0.95 ys 'y_1\n{}y_2\n{}y_3' '#';value 0.7
C++ code:
void smgl_table(mglGraph *gr) { mglData ys(10,3); ys.Modify("0.8*sin(pi*(2*x+y/2))+0.2*rnd"); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Table plot"); } gr->Table(ys,"y_1\ny_2\ny_3"); gr->Box(); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("no borders, colored"); gr->Table(ys,"y_1\ny_2\ny_3","r|"); gr->SubPlot(2,2,2); gr->Title("no font decrease"); gr->Table(ys,"y_1\ny_2\ny_3","#"); gr->SubPlot(2,2,3); gr->Title("manual width, position"); gr->Table(0.5, 0.95, ys,"y_1\ny_2\ny_3","#", "value 0.7"); gr->Box(); }
Function tape draw tapes which rotate around the curve as transverse orts of accompanied coordinates.
MGL code:
call 'prepare1d' new yc 50 'sin(pi*x)':new xc 50 'cos(pi*x)':new z 50 'x' subplot 2 2 0 '':title 'Tape plot (default)':box:tape y:plot y 'k' subplot 2 2 1:title '3d variant, 2 colors':rotate 50 60:light on box:plot xc yc z 'k':tape xc yc z 'rg' subplot 2 2 2:title '3d variant, x only':rotate 50 60 box:plot xc yc z 'k':tape xc yc z 'xr':tape xc yc z 'xr#' subplot 2 2 3:title '3d variant, z only':rotate 50 60 box:plot xc yc z 'k':tape xc yc z 'zg':tape xc yc z 'zg#'
C++ code:
void smgl_tape(mglGraph *gr) { mglData y; mgls_prepare1d(&y); mglData xc(50), yc(50), z(50); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); z.Fill(-1,1); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Tape plot (default)"); } gr->Box(); gr->Tape(y); gr->Plot(y,"k"); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("3d variant, 2 colors"); gr->Rotate(50,60); gr->Light(true); gr->Box(); gr->Plot(xc,yc,z,"k"); gr->Tape(xc,yc,z,"rg"); gr->SubPlot(2,2,2); gr->Title("3d variant, x only"); gr->Rotate(50,60); gr->Box(); gr->Plot(xc,yc,z,"k"); gr->Tape(xc,yc,z,"xr"); gr->Tape(xc,yc,z,"xr#"); gr->SubPlot(2,2,3); gr->Title("3d variant, z only"); gr->Rotate(50,60); gr->Box(); gr->Plot(xc,yc,z,"k"); gr->Tape(xc,yc,z,"zg"); gr->Tape(xc,yc,z,"zg#"); }
Function tens is variant of plot with smooth coloring along the curves. At this, color is determined as for surfaces (see Цветовая схема).
MGL code:
call 'prepare1d' subplot 2 2 0 '':title 'Tens plot (default)':box:tens y(:,0) y(:,1) subplot 2 2 2 '':title '" " style':box:tens y(:,0) y(:,1) 'o ' new yc 30 'sin(pi*x)':new xc 30 'cos(pi*x)':new z 30 'x' subplot 2 2 1:title '3d variant':rotate 50 60:box:tens xc yc z z 's'
C++ code:
void smgl_tens(mglGraph *gr) { mglData y; mgls_prepare1d(&y); gr->SetOrigin(0,0,0); if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Tens plot (default)"); } gr->Box(); gr->Tens(y.SubData(-1,0), y.SubData(-1,1)); if(big==3) return; gr->SubPlot(2,2,2,""); gr->Title("' ' style"); gr->Box(); gr->Tens(y.SubData(-1,0), y.SubData(-1,1),"o "); gr->SubPlot(2,2,1); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); mglData yc(30), xc(30), z(30); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); gr->Tens(xc,yc,z,z,"s"); }
Example of ternary coordinates.
MGL code:
ranges 0 1 0 1 0 1 new x 50 '0.25*(1+cos(2*pi*x))' new y 50 '0.25*(1+sin(2*pi*x))' new z 50 'x' new a 20 30 '30*x*y*(1-x-y)^2*(x+y<1)' new rx 10 'rnd':new ry 10:fill ry '(1-v)*rnd' rx light on subplot 2 2 0:title 'Ordinary axis 3D':rotate 50 60 box:axis:grid plot x y z 'r2':surf a '#' xlabel 'B':ylabel 'C':zlabel 'Z' subplot 2 2 1:title 'Ternary axis (x+y+t=1)':ternary 1 box:axis:grid 'xyz' 'B;' plot x y 'r2':plot rx ry 'q^ ':cont a:line 0.5 0 0 0.75 'g2' xlabel 'B':ylabel 'C':tlabel 'A' subplot 2 2 2:title 'Quaternary axis 3D':rotate 50 60:ternary 2 box:axis:grid 'xyz' 'B;' plot x y z 'r2':surf a '#' xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'D' subplot 2 2 3:title 'Ternary axis 3D':rotate 50 60:ternary 1 box:axis:grid 'xyz' 'B;' plot x y z 'r2':surf a '#' xlabel 'B':ylabel 'C':tlabel 'A':zlabel 'Z'
C++ code:
void smgl_ternary(mglGraph *gr) // flag # { 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->SubPlot(2,2,0); gr->Title("Ordinary axis 3D"); gr->Rotate(50,60); gr->Light(true); gr->Plot(x,y,z,"r2"); gr->Surf(a,"BbcyrR#"); gr->Axis(); gr->Grid(); gr->Box(); gr->Label('x',"B",1); gr->Label('y',"C",1); gr->Label('z',"Z",1); gr->SubPlot(2,2,1); gr->Title("Ternary axis (x+y+t=1)"); gr->Ternary(1); gr->Plot(x,y,"r2"); gr->Plot(rx,ry,"q^ "); gr->Cont(a); gr->Line(mglPoint(0.5,0), mglPoint(0,0.75), "g2"); gr->Axis(); gr->Grid("xyz","B;"); gr->Label('x',"B"); gr->Label('y',"C"); gr->Label('t',"A"); gr->SubPlot(2,2,2); gr->Title("Quaternary axis 3D"); gr->Rotate(50,60); gr->Light(true); gr->Ternary(2); gr->Plot(x,y,z,"r2"); gr->Surf(a,"BbcyrR#"); gr->Axis(); gr->Grid(); gr->Box(); gr->Label('t',"A",1); gr->Label('x',"B",1); gr->Label('y',"C",1); gr->Label('z',"D",1); gr->SubPlot(2,2,3); gr->Title("Ternary axis 3D"); gr->Rotate(50,60); gr->Light(true); gr->Ternary(1); gr->Plot(x,y,z,"r2"); gr->Surf(a,"BbcyrR#"); gr->Axis(); gr->Grid(); gr->Box(); gr->Label('t',"A",1); gr->Label('x',"B",1); gr->Label('y',"C",1); gr->Label('z',"Z",1); }
Example of text possibilities.
MGL code:
call 'prepare1d' subplot 2 2 0 '' text 0 1 'Text can be in ASCII and in Unicode' text 0 0.6 'It can be \wire{wire}, \big{big} or #r{colored}' text 0 0.2 'One can change style in string: \b{bold}, \i{italic, \b{both}}' text 0 -0.2 'Easy to \a{overline} or \u{underline}' text 0 -0.6 'Easy to change indexes ^{up} _{down} @{center}' text 0 -1 'It parse TeX: \int \alpha \cdot \ \sqrt3{sin(\pi x)^2 + \gamma_{i_k}} dx' subplot 2 2 1 '' text 0 0.5 '\sqrt{\frac{\alpha^{\gamma^2}+\overset 1{\big\infty}}{\sqrt3{2+b}}}' '@' -2 text 0 -0.1 'More text position: \frac{a}{b}, \dfrac{a}{b}, [\stack{a}{bbb}], [\stackl{a}{bbb}], [\stackr{a}{bbb}], \sup{a}{sup}, \sub{a}{sub}'text 0 -0.5 'Text can be printed\n{}on several lines' text 0 -0.9 'or with color gradient' 'BbcyrR' subplot 2 2 2 '':box:plot y(:,0) text y 'This is very very long string drawn along a curve' 'k' text y 'Another string drawn above a curve' 'Tr' subplot 2 2 3 '':line -1 -1 1 -1 'rA':text 0 -1 1 -1 'Horizontal' line -1 -1 1 1 'rA':text 0 0 1 1 'At angle' '@' line -1 -1 -1 1 'rA':text -1 0 -1 1 'Vertical'
C++ code:
void smgl_text(mglGraph *gr) // text drawing { if(big!=3) gr->SubPlot(2,2,0,""); gr->Putsw(mglPoint(0,1),L"Text can be in ASCII and in Unicode"); gr->Puts(mglPoint(0,0.6),"It can be \\wire{wire}, \\big{big} or #r{colored}"); gr->Puts(mglPoint(0,0.2),"One can change style in string: " "\\b{bold}, \\i{italic, \\b{both}}"); gr->Puts(mglPoint(0,-0.2),"Easy to \\a{overline} or " "\\u{underline}"); gr->Puts(mglPoint(0,-0.6),"Easy to change indexes ^{up} _{down} @{center}"); gr->Puts(mglPoint(0,-1),"It parse TeX: \\int \\alpha \\cdot " "\\sqrt3{sin(\\pi x)^2 + \\gamma_{i_k}} dx"); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Puts(mglPoint(0,0.5), "\\sqrt{\\frac{\\alpha^{\\gamma^2}+\\overset 1{\\big\\infty}}{\\sqrt3{2+b}}}", "@", -2); gr->Puts(mglPoint(0,-0.1),"More text position: \\frac{a}{b}, \\dfrac{a}{b}, [\\stack{a}{bbb}], [\\stackl{a}{bbb}], [\\stackr{a}{bbb}], \\sup{a}{sup}, \\sub{a}{sub}"); gr->Puts(mglPoint(0,-0.5),"Text can be printed\non several lines"); gr->Puts(mglPoint(0,-0.9),"or with col\bor gradient","BbcyrR"); gr->SubPlot(2,2,2,""); mglData y; mgls_prepare1d(&y); gr->Box(); gr->Plot(y.SubData(-1,0)); gr->Text(y,"This is very very long string drawn along a curve","k"); gr->Text(y,"Another string drawn under a curve","Tr"); gr->SubPlot(2,2,3,""); gr->Line(mglPoint(-1,-1),mglPoint(1,-1),"rA"); gr->Puts(mglPoint(0,-1),mglPoint(1,-1),"Horizontal"); gr->Line(mglPoint(-1,-1),mglPoint(1,1),"rA"); gr->Puts(mglPoint(0,0),mglPoint(1,1),"At angle","@"); gr->Line(mglPoint(-1,-1),mglPoint(-1,1),"rA"); gr->Puts(mglPoint(-1,0),mglPoint(-1,1),"Vertical"); }
Example of text along curve.
MGL code:
call 'prepare1d' subplot 1 3 0 '':box:plot y(:,0) text y 'This is very very long string drawn along a curve' 'k' text y 'Another string drawn under a curve' 'Tr' subplot 1 3 1 '':box:plot y(:,0) text y 'This is very very long string drawn along a curve' 'k:C' text y 'Another string drawn under a curve' 'Tr:C' subplot 1 3 2 '':box:plot y(:,0) text y 'This is very very long string drawn along a curve' 'k:R' text y 'Another string drawn under a curve' 'Tr:R'
C++ code:
void smgl_text2(mglGraph *gr) // text drawing { mglData y; mgls_prepare1d(&y); if(big!=3) gr->SubPlot(1,3,0,""); gr->Box(); gr->Plot(y.SubData(-1,0)); gr->Text(y,"This is very very long string drawn along a curve","k"); gr->Text(y,"Another string drawn under a curve","Tr"); if(big==3) return; gr->SubPlot(1,3,1,""); gr->Box(); gr->Plot(y.SubData(-1,0)); gr->Text(y,"This is very very long string drawn along a curve","k:C"); gr->Text(y,"Another string drawn under a curve","Tr:C"); gr->SubPlot(1,3,2,""); gr->Box(); gr->Plot(y.SubData(-1,0)); gr->Text(y,"This is very very long string drawn along a curve","k:R"); gr->Text(y,"Another string drawn under a curve","Tr:R"); }
Function textmark is similar to mark but draw text instead of markers.
MGL code:
call 'prepare1d' subplot 1 1 0 '':title 'TextMark plot (default)':box:textmark y y1 '\gamma' 'r'
C++ code:
void smgl_textmark(mglGraph *gr) { mglData y,y1; mgls_prepare1d(&y,&y1); if(big!=3) { gr->SubPlot(1,1,0,""); gr->Title("TextMark plot (default)"); } gr->Box(); gr->TextMark(y,y1,"\\gamma","r"); }
Example of axis ticks.
MGL code:
subplot 3 3 0:title 'Usual axis with ":" style' axis ':' subplot 3 3 1:title 'Too big/small range' ranges -1000 1000 0 0.001:axis subplot 3 3 2:title 'LaTeX-like labels' axis 'F!' subplot 3 3 3:title 'Too narrow range' ranges 100 100.1 10 10.01:axis subplot 3 3 4:title 'No tuning, manual "+"' axis '+!' # for version <2.3 you can use #tuneticks off:axis subplot 3 3 5:title 'Template for ticks' xtick 'xxx:%g':ytick 'y:%g' axis xtick '':ytick '' # switch it off for other plots subplot 3 3 6:title 'No tuning, higher precision' axis '!4' subplot 3 3 7:title 'Manual ticks' ranges -pi pi 0 2 xtick pi 3 '\pi' xtick 0.886 'x^*' on # note this will disable subticks drawing # or you can use #xtick -pi '\pi' -pi/2 '-\pi/2' 0 '0' 0.886 'x^*' pi/2 '\pi/2' pi 'pi' list v 0 0.5 1 2:ytick v '0 0.5 1 2' axis:grid:fplot '2*cos(x^2)^2' 'r2' subplot 3 3 8:title 'Time ticks' xrange 0 3e5:ticktime 'x':axis
C++ code:
void smgl_ticks(mglGraph *gr) { gr->SubPlot(3,3,0); gr->Title("Usual axis with ':' style"); gr->Axis(":"); gr->SubPlot(3,3,1); gr->Title("Too big/small range"); gr->SetRanges(-1000,1000,0,0.001); gr->Axis(); gr->SubPlot(3,3,2); gr->Title("LaTeX-like labels"); gr->Axis("F!"); gr->SubPlot(3,3,3); gr->Title("Too narrow range"); gr->SetRanges(100,100.1,10,10.01); gr->Axis(); gr->SubPlot(3,3,4); gr->Title("No tuning, manual '+'"); // for version<2.3 you need first call gr->SetTuneTicks(0); gr->Axis("+!"); gr->SubPlot(3,3,5); gr->Title("Template for ticks"); gr->SetTickTempl('x',"xxx:%g"); gr->SetTickTempl('y',"y:%g"); gr->Axis(); // now switch it off for other plots gr->SetTickTempl('x',""); gr->SetTickTempl('y',""); gr->SubPlot(3,3,6); gr->Title("No tuning, higher precision"); gr->Axis("!4"); gr->SubPlot(3,3,7); gr->Title("Manual ticks"); gr->SetRanges(-M_PI,M_PI, 0, 2); gr->SetTicks('x',M_PI,0,0,"\\pi"); gr->AddTick('x',0.886,"x^*"); // alternatively you can use following lines double val[]={0, 0.5, 1, 2}; gr->SetTicksVal('y', mglData(4,val), "0\n0.5\n1\n2"); gr->Axis(); gr->Grid(); gr->FPlot("2*cos(x^2)^2", "r2"); gr->SubPlot(3,3,8); gr->Title("Time ticks"); gr->SetRange('x',0,3e5); gr->SetTicksTime('x',0); gr->Axis(); }
Function tile draw surface by tiles.
MGL code:
call 'prepare2d' title 'Tile plot':rotate 50 60:box:tile a
C++ code:
void smgl_tile(mglGraph *gr) { mglData a; mgls_prepare2d(&a); if(big!=3) gr->Title("Tile plot"); gr->Rotate(40,60); gr->Box(); gr->Tile(a); }
Function tiles is similar to tile but tile sizes is determined by another data. This allows one to simulate transparency of the plot.
MGL code:
call 'prepare2d' subplot 1 1 0 '':title 'Tiles plot':box:tiles a b
C++ code:
void smgl_tiles(mglGraph *gr) { mglData a,b; mgls_prepare2d(&a,&b); if(big!=3) {gr->SubPlot(1,1,0,""); gr->Title("TileS plot");} gr->Box(); gr->TileS(a,b); }
Function torus draw surface of the curve rotation.
MGL code:
call 'prepare1d' subplot 2 2 0:title 'Torus plot (default)':light on:rotate 50 60:box:torus y1 y2 subplot 2 2 1:title '"x" style':light on:rotate 50 60:box:torus y1 y2 'x' subplot 2 2 2:title '"z" style':light on:rotate 50 60:box:torus y1 y2 'z' subplot 2 2 3:title '"\#" style':light on:rotate 50 60:box:torus y1 y2 '#'
C++ code:
void smgl_torus(mglGraph *gr) { mglData y1,y2; mgls_prepare1d(0,&y1,&y2); if(big!=3) { gr->SubPlot(2,2,0); gr->Title("Torus plot (default)"); } gr->Light(true); gr->Rotate(50,60); gr->Box(); gr->Torus(y1,y2); if(big==3) return; gr->SubPlot(2,2,1); gr->Title("'x' style"); gr->Rotate(50,60); gr->Box(); gr->Torus(y1,y2,"x"); gr->SubPlot(2,2,2); gr->Title("'z' style"); gr->Rotate(50,60); gr->Box(); gr->Torus(y1,y2,"z"); gr->SubPlot(2,2,3); gr->Title("'\\#' style"); gr->Rotate(50,60); gr->Box(); gr->Torus(y1,y2,"#"); }
Function traj is 1D analogue of vect. It draw vectors from specified points.
MGL code:
call 'prepare1d' subplot 1 1 0 '':title 'Traj plot':box:plot x1 y:traj x1 y y1 y2
C++ code:
void smgl_traj(mglGraph *gr) { mglData x,y,y1,y2; mgls_prepare1d(&y,&y1,&y2,&x); if(big!=3) {gr->SubPlot(1,1,0,""); gr->Title("Traj plot");} gr->Box(); gr->Plot(x,y); gr->Traj(x,y,y1,y2); }
Example of use triangulate for arbitrary placed points.
MGL code:
new x 100 '2*rnd-1':new y 100 '2*rnd-1':copy z x^2-y^2 new g 30 30:triangulate d x y title 'Triangulation' rotate 50 60:box:light on triplot d x y z:triplot d x y z '#k' datagrid g x y z:mesh g 'm'
C++ code:
void smgl_triangulation(mglGraph *gr) // surface triangulation { mglData x(100), y(100), z(100); gr->Fill(x,"2*rnd-1"); gr->Fill(y,"2*rnd-1"); gr->Fill(z,"v^2-w^2",x,y); mglData d = mglTriangulation(x,y), g(30,30); if(big!=3) gr->Title("Triangulation"); gr->Rotate(40,60); gr->Box(); gr->Light(true); gr->TriPlot(d,x,y,z); gr->TriPlot(d,x,y,z,"#k"); gr->DataGrid(g,x,y,z); gr->Mesh(g,"m"); }
Functions triplot and quadplot draw set of triangles (or quadrangles, correspondingly) for irregular data arrays. Note, that you have to provide not only vertexes, but also the indexes of triangles or quadrangles. I.e. perform triangulation by some other library. See also triangulate.
MGL code:
list q 0 1 2 3 | 4 5 6 7 | 0 2 4 6 | 1 3 5 7 | 0 4 1 5 | 2 6 3 7 list xq -1 1 -1 1 -1 1 -1 1 list yq -1 -1 1 1 -1 -1 1 1 list zq -1 -1 -1 -1 1 1 1 1 light on subplot 2 2 0:title 'QuadPlot sample':rotate 50 60 quadplot q xq yq zq 'yr' quadplot q xq yq zq '#k' subplot 2 2 2:title 'QuadPlot coloring':rotate 50 60 quadplot q xq yq zq yq 'yr' quadplot q xq yq zq '#k' list t 0 1 2 | 0 1 3 | 0 2 3 | 1 2 3 list xt -1 1 0 0 list yt -1 -1 1 0 list zt -1 -1 -1 1 subplot 2 2 1:title 'TriPlot sample':rotate 50 60 triplot t xt yt zt 'b' triplot t xt yt zt '#k' subplot 2 2 3:title 'TriPlot coloring':rotate 50 60 triplot t xt yt zt yt 'cb' triplot t xt yt zt '#k' tricont t xt yt zt 'B'
C++ code:
void smgl_triplot(mglGraph *gr) { double q[] = {0,1,2,3, 4,5,6,7, 0,2,4,6, 1,3,5,7, 0,4,1,5, 2,6,3,7}; double xc[] = {-1,1,-1,1,-1,1,-1,1}, yc[] = {-1,-1,1,1,-1,-1,1,1}, zc[] = {-1,-1,-1,-1,1,1,1,1}; mglData qq(6,4,q), xx(8,xc), yy(8,yc), zz(8,zc); gr->Light(true); //gr->Alpha(true); gr->SubPlot(2,2,0); gr->Title("QuadPlot sample"); gr->Rotate(50,60); gr->QuadPlot(qq,xx,yy,zz,"yr"); gr->QuadPlot(qq,xx,yy,zz,"k#"); gr->SubPlot(2,2,2); gr->Title("QuadPlot coloring"); gr->Rotate(50,60); gr->QuadPlot(qq,xx,yy,zz,yy,"yr"); gr->QuadPlot(qq,xx,yy,zz,"k#"); double t[] = {0,1,2, 0,1,3, 0,2,3, 1,2,3}; double xt[] = {-1,1,0,0}, yt[] = {-1,-1,1,0}, zt[] = {-1,-1,-1,1}; mglData tt(4,3,t), uu(4,xt), vv(4,yt), ww(4,zt); gr->SubPlot(2,2,1); gr->Title("TriPlot sample"); gr->Rotate(50,60); gr->TriPlot(tt,uu,vv,ww,"b"); gr->TriPlot(tt,uu,vv,ww,"k#"); gr->SubPlot(2,2,3); gr->Title("TriPlot coloring"); gr->Rotate(50,60); gr->TriPlot(tt,uu,vv,ww,vv,"cb"); gr->TriPlot(tt,uu,vv,ww,"k#"); gr->TriCont(tt,uu,vv,ww,"B"); }
Function tube draw tube with variable radius.
MGL code:
call 'prepare1d' light on new yc 50 'sin(pi*x)':new xc 50 'cos(pi*x)':new z 50 'x':divto y1 20 subplot 2 2 0 '':title 'Tube plot (default)':box:tube y 0.05 subplot 2 2 1 '':title 'variable radius':box:tube y y1 subplot 2 2 2 '':title '"\#" style':box:tube y 0.05 '#' subplot 2 2 3:title '3d variant':rotate 50 60:box:tube xc yc z y2 'r'
C++ code:
void smgl_tube(mglGraph *gr) { mglData y,y1,y2; mgls_prepare1d(&y,&y1,&y2); y1/=20; if(big!=3) { gr->SubPlot(2,2,0,""); gr->Title("Tube plot (default)"); } gr->Light(true); gr->Box(); gr->Tube(y,0.05); if(big==3) return; gr->SubPlot(2,2,1,""); gr->Title("variable radius"); gr->Box(); gr->Tube(y,y1); gr->SubPlot(2,2,2,""); gr->Title("'\\#' style"); gr->Box(); gr->Tube(y,0.05,"#"); mglData yc(50), xc(50), z(50); z.Modify("2*x-1"); yc.Modify("sin(pi*(2*x-1))"); xc.Modify("cos(pi*2*x-pi)"); gr->SubPlot(2,2,3); gr->Title("3d variant"); gr->Rotate(50,60); gr->Box(); gr->Tube(xc,yc,z,y2,"r"); }
Example of ordinary transparency (transptype=0).
MGL code:
call 'prepare2d' alpha on:light on:transptype 0:clf subplot 2 2 0:rotate 50 60:surf a:box subplot 2 2 1:rotate 50 60:dens a:box subplot 2 2 2:rotate 50 60:cont a:box subplot 2 2 3:rotate 50 60:axial a:box
C++ code:
void smgl_type0(mglGraph *gr) // TranspType = 0 { 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(); }
Example of glass-like transparency (transptype=1).
MGL code:
call 'prepare2d' alpha on:light on:transptype 1:clf subplot 2 2 0:rotate 50 60:surf a:box subplot 2 2 1:rotate 50 60:dens a:box subplot 2 2 2:rotate 50 60:cont a:box subplot 2 2 3:rotate 50 60:axial a:box
C++ code:
void smgl_type1(mglGraph *gr) // TranspType = 1 { gr->Alpha(true); gr->Light(true); mglData a; mgls_prepare2d(&a); gr->SetTranspType(1); 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(); }
Example of lamp-like transparency (transptype=2).
MGL code:
call 'prepare2d' alpha on:light on:transptype 2:clf subplot 2 2 0:rotate 50 60:surf a:box subplot 2 2 1:rotate 50 60:dens a:box subplot 2 2 2:rotate 50 60:cont a:box subplot 2 2 3:rotate 50 60:axial a:box
C++ code:
void smgl_type2(mglGraph *gr) // TranspType = 2 { gr->Alpha(true); gr->Light(true); mglData a; mgls_prepare2d(&a); gr->SetTranspType(2); 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(); }
Function vect is most standard way to visualize vector fields – it draw a lot of arrows or hachures for each data cell. It have a lot of options which can be seen on the figure (and in the sample code), and use color scheme for coloring (see Цветовая схема).
MGL code:
call 'prepare2v' call 'prepare3v' subplot 3 2 0 '':title 'Vect plot (default)':box:vect a b subplot 3 2 1 '':title '"." style; "=" style':box:vect a b '.=' subplot 3 2 2 '':title '"f" style':box:vect a b 'f' subplot 3 2 3 '':title '">" style':box:vect a b '>' subplot 3 2 4 '':title '"<" style':box:vect a b '<' subplot 3 2 5:title '3d variant':rotate 50 60:box:vect ex ey ez
C++ code:
void smgl_vect3(mglGraph *gr) { mglData ex,ey,ez; mgls_prepare3v(&ex,&ey,&ez); if(big!=3) { gr->SubPlot(2,1,0); gr->Title("Vect3 sample"); } gr->Rotate(50,60); gr->SetOrigin(0,0,0); gr->Axis("_xyz"); gr->Box(); gr->Vect3(ex,ey,ez,"x"); gr->Vect3(ex,ey,ez); gr->Vect3(ex,ey,ez,"z"); if(big==3) return; gr->SubPlot(2,1,1); gr->Title("'f' style"); gr->Rotate(50,60); gr->SetOrigin(0,0,0); gr->Axis("_xyz"); gr->Box(); gr->Vect3(ex,ey,ez,"fx"); gr->Vect3(ex,ey,ez,"f"); gr->Vect3(ex,ey,ez,"fz"); gr->Grid3(ex,"Wx"); gr->Grid3(ex,"W"); gr->Grid3(ex,"Wz"); }
Function vect3 draw ordinary vector field plot but at slices of 3D data.
MGL code:
call 'prepare3v' subplot 2 1 0:title 'Vect3 sample':rotate 50 60 origin 0 0 0:box:axis '_xyz' vect3 ex ey ez 'x':vect3 ex ey ez:vect3 ex ey ez 'z' subplot 2 1 1:title '"f" style':rotate 50 60 origin 0 0 0:box:axis '_xyz' vect3 ex ey ez 'fx':vect3 ex ey ez 'f':vect3 ex ey ez 'fz' grid3 ex 'Wx':grid3 ex 'W':grid3 ex 'Wz'
C++ code:
void smgl_vect3(mglGraph *gr) { mglData ex,ey,ez; mgls_prepare3v(&ex,&ey,&ez); if(big!=3) { gr->SubPlot(2,1,0); gr->Title("Vect3 sample"); } gr->Rotate(50,60); gr->SetOrigin(0,0,0); gr->Axis("_xyz"); gr->Box(); gr->Vect3(ex,ey,ez,"x"); gr->Vect3(ex,ey,ez); gr->Vect3(ex,ey,ez,"z"); if(big==3) return; gr->SubPlot(2,1,1); gr->Title("'f' style"); gr->Rotate(50,60); gr->SetOrigin(0,0,0); gr->Axis("_xyz"); gr->Box(); gr->Vect3(ex,ey,ez,"fx"); gr->Vect3(ex,ey,ez,"f"); gr->Vect3(ex,ey,ez,"fz"); gr->Grid3(ex,"Wx"); gr->Grid3(ex,"W"); gr->Grid3(ex,"Wz"); }
Example of venn-like diagram.
MGL code:
list x -0.3 0 0.3:list y 0.3 -0.3 0.3:list e 0.7 0.7 0.7 subplot 1 1 0:title 'Venn-like diagram' transptype 1:alpha on:error x y e e '!rgb@#o';alpha 0.1
C++ code:
void smgl_venn(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->SubPlot(1,1,0); gr->Title("Venn-like diagram"); gr->SetTranspType(1); gr->Alpha(true); gr->Error(x,y,e,e,"!rgb@#o","alpha 0.1"); }
This appendix contain the full list of symbols (characters) used by MathGL for setting up plot. Also it contain sections for full list of hot-keys supported by mglview tool and by UDAV program.
Below is full list of all characters (symbols) which MathGL use for setting up the plot.
empty line style (see Стиль линий);
empty color in chart.
set to use new color from palette for each point (not for each curve, as default) in 1D графики;
set to disable ticks tuning in axis and colorbar;
set to draw grid lines at subticks coordinates too;
define complex variable/expression in MGL script if placed at beginning.
set to use solid marks (see Стиль линий) or solid error boxes;
set to draw wired plot for axial, surf3, surf3a, surf3c, triplot, quadplot, area, region, bars, barh, tube, tape, cone, boxs and draw boundary only for circle, ellipse, rhomb;
set to draw also mesh lines for surf, surfc, surfa, dens, densx, densy, densz, dens3, or boundary for chart, facex, facey, facez, rect;
set to draw boundary and box for legend, title, or grid lines for table;
set to draw grid for radar;
set to start flow threads and pipes from edges only for flow, pipe;
set to use whole are for axis range in subplot, inplot;
change text color inside a string (see Стиль текста);
start comment in Скрипты MGL or in Опции команд.
denote parameter of Скрипты MGL.
set color scheme along 2 coordinates Цветовая схема;
operation in Текстовые формулы.
set to pass long integer number in tick template xtick, ytick, ztick, ctick;
specifier of drawing user-defined symbols as mark (see Стиль линий);
operation in Текстовые формулы.
denote string in Скрипты MGL or in Опции команд.
one of marks (see Стиль линий);
one of mask for face filling (see Цветовая схема);
set to start flow threads from 2d array inside data (see flow);
operation in Текстовые формулы.
one of marks (see Стиль линий) or kind of error boxes;
one of mask for face filling (see Цветовая схема);
set to print ‘+’ for positive numbers in axis, label, table;
operation of increasing last character value in MGL strings;
operation in Текстовые формулы.
separator for color positions (see Цвета) or items in a list
concatenation of MGL string with another string or numerical value.
solid line style (see Стиль линий);
one of mask for face filling (see Цветовая схема);
place entries horizontally in legend;
set to use usual ‘-’ for negative numbers in axis, label, table;
operation in Текстовые формулы.
one of marks (see Стиль линий) or kind of error boxes;
set to draw hachures instead of arrows for vect, vect3;
set to use dots instead of faces for cloud, torus, axial, surf3, surf3a, surf3c, surf, surfa, surfc, dens, map;
delimiter of fractional parts for numbers.
operation in Текстовые формулы.
line dashing style (see Стиль линий);
stop color scheme parsing (see Цветовая схема);
range operation in Скрипты MGL;
style for axis;
separator of commands in Скрипты MGL.
line dashing style (see Стиль линий);
one of mask for face filling (see Цветовая схема);
start of an option in Скрипты MGL or in Опции команд;
separator of equations in ode;
separator of labels in iris.
one of marks (see Стиль линий);
one of mask for face filling (see Цветовая схема);
set position of colorbar;
align left in bars, barh, boxplot, cones, candle, ohlc;
operation in Текстовые формулы.
one of marks (see Стиль линий);
one of mask for face filling (see Цветовая схема);
set position of colorbar;
align right in bars, barh, boxplot, cones, candle, ohlc;
operation in Текстовые формулы.
line dashing style (see Стиль линий);
one of mask for face filling (see Цветовая схема);
set to use equidistant columns for table;
set to use color gradient for vect, vect3;
operation in Текстовые формулы.
set to draw box around text for text and similar functions;
set to draw boundary and fill it for circle, ellipse, rhomb;
set to fill faces for box;
set to draw large semitransparent mark instead of error box for error;
set to draw edges for cone;
set to draw filled boxes for boxs;
reduce text size inside a string (see Стиль текста);
operation in Текстовые формулы.
one of marks (see Стиль линий);
one of mask for face filling (see Цветовая схема);
set position of colorbar;
set outer position for legend;
inverse default position for axis;
switch to upper index inside a string (see Стиль текста);
align center in bars, barh, boxplot, cones, candle, ohlc;
operation in Текстовые формулы.
empty arrow style (see Стиль линий);
disable drawing of tick labels for axis;
set position of colorbar;
set to draw contours at bottom for cont, contf, contd, contv, tricont;
switch to lower index inside a string (see Стиль текста).
contain symbols excluded from color scheme parsing (see Цветовая схема);
operation of getting n-th character from MGL string.
contain extended specification of color (see Цвета), dashing (see Стиль линий) or mask (see Цветовая схема);
denote special operation in Скрипты MGL;
denote ’meta-symbol’ for LaTeX like string parsing (see Стиль текста).
line dashing style (see Стиль линий);
set to use sharp color scheme (see Цветовая схема);
set to limit width by subplot width for table;
delimiter in list command;
operation in Текстовые формулы.
string continuation symbol on next line for Скрипты MGL.
disable drawing of tick labels for axis and colorbar;
disable first segment in lamerey;
reduce number of segments in plot and tens;
one of mask for face filling (see Цветовая схема).
line width (see Стиль линий);
brightness of a color (see Цвета);
precision of numbers in axis, label, table;
kind of smoothing (for digits 1,3,5) in smooth;
digits for a value.
set to draw square, hex- or octo-pyramids instead of cones in cone, cones.
can be hex-digit for color specification if placed inside {} (see Цвета).
arrow style (see Стиль линий);
set to use absolute position in whole picture for text, colorbar, legend.
set to use absolute position in subplot for text;
style of plot, radar, tens, area, region to draw segments between points outside of axis range;
dark blue color (see Цвета).
blue color (see Цвета);
bold font face if placed after ‘:’ (see Стиль текста).
dark cyan color (see Цвета);
align text to center if placed after ‘:’ (see Стиль текста).
cyan color (see Цвета);
name of color axis;
cosine transform for transform.
arrow style (see Стиль линий);
one of mask for face filling (see Цветовая схема).
one of marks (see Стиль линий) or kind of error boxes;
one of mask for face filling (see Цветовая схема);
start hex-dash description if placed inside {} (see Стиль линий).
dark green-yellow color (see Цвета).
green-yellow color (see Цвета).
set fixed format for numbers in axis, label, table;
Fourier transform for transform.
dark green color (see Цвета).
green color (see Цвета).
dark gray color (see Цвета).
gray color (see Цвета);
Hankel transform for transform.
arrow style (see Стиль линий);
set colorbar position near boundary.
line dashing style (see Стиль линий);
italic font face if placed after ‘:’ (see Стиль текста).
set to use inverse values for cloud, pipe, dew;
set to fill only area with y1<y<y2 for region;
inverse Fourier transform for transform, transforma, fourier.
line dashing style (see Стиль линий);
one of mask for face filling (see Цветовая схема).
arrow style (see Стиль линий).
black color (see Цвета).
dark green-blue color (see Цвета);
align text to left if placed after ‘:’ (see Стиль текста).
green-blue color (see Цвета).
dark magenta color (see Цвета).
magenta color (see Цвета).
dark sky-blue color (see Цвета).
sky-blue color (see Цвета).
arrow style (see Стиль линий);
one of mask for face filling (see Цветовая схема).
one of marks (see Стиль линий) or kind of error boxes;
one of mask for face filling (see Цветовая схема);
over-line text if placed after ‘:’ (see Стиль текста).
dark purple color (see Цвета).
purple color (see Цвета).
dark orange or brown color (see Цвета).
orange color (see Цвета).
dark red color (see Цвета);
align text to right if placed after ‘:’ (see Стиль текста).
red color (see Цвета).
arrow style (see Стиль линий);
one of mask for face filling (see Цветовая схема).
one of marks (see Стиль линий) or kind of error boxes;
one of mask for face filling (see Цветовая схема);
start hex-mask description if placed inside {} (see Цветовая схема);
sine transform for transform.
arrow style (see Стиль линий);
set to draw text labels for cont, cont3;
name of t-axis (one of ternary axis);
variable in Текстовые формулы, which usually is varied in range [0,1].
dark blue-violet color (see Цвета);
disable rotation of tick labels for axis.
blue-violet color (see Цвета);
under-line text if placed after ‘:’ (see Стиль текста);
name of u-axis (one of ternary axis);
variable in Текстовые формулы, which usually denote array itself.
arrow style (see Стиль линий);
place text centering on vertical direction for text.
one of marks (see Стиль линий);
set to draw vectors on flow threads for flow and on segments for lamerey.
bright gray color (see Цвета).
white color (see Цвета);
wired text if placed after ‘:’ (see Стиль текста);
name of w-axis (one of ternary axis);
arrow style (see Стиль линий).
name of x-axis or x-direction or 1st dimension of a data array;
start hex-color description if placed inside {} (see Цвета);
one of marks (see Стиль линий) or kind of error boxes;
tiles orientation perpendicular to x-axis in tile, tiles;
style of tape.
dark yellow or gold color (see Цвета).
yellow color (see Цвета);
name of y-axis or y-direction or 2nd dimension of a data array;
name of z-axis or z-direction or 3d dimension of a data array;
style of tape.
Key | Description |
---|---|
Ctrl-P | Open printer dialog and print graphics. |
Ctrl-W | Close window. |
Ctrl-T | Switch on/off transparency for the graphics. |
Ctrl-L | Switch on/off additional lightning for the graphics. |
Ctrl-Space | Restore default graphics rotation, zoom and perspective. |
F5 | Execute script and redraw graphics. |
F6 | Change canvas size to fill whole region. |
F7 | Stop drawing and script execution. |
Ctrl-F5 | Run slideshow. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-Comma, Ctrl-Period | Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-Shift-G | Copy graphics to clipboard. |
Alt-P | Export as semitransparent PNG. |
Alt-F | Export as solid PNG. |
Alt-J | Export as JPEG. |
Alt-E | Export as vector EPS. |
Alt-S | Export as vector SVG. |
Alt-L | Export as LaTeX/Tikz image. |
Alt-M | Export as MGLD. |
Alt-D | Export as PRC/PDF. |
Alt-O | Export as OBJ. |
Key | Description |
---|---|
Ctrl-N | Create new window with empty script. Note, all scripts share variables. So, second window can be used to see some additional information of existed variables. |
Ctrl-O | Open and execute/show script or data from file. You may switch off automatic execution in UDAV properties |
Ctrl-S | Save script to a file. |
Ctrl-P | Open printer dialog and print graphics. |
Ctrl-Z | Undo changes in script editor. |
Ctrl-Shift-Z | Redo changes in script editor. |
Ctrl-X | Cut selected text into clipboard. |
Ctrl-C | Copy selected text into clipboard. |
Ctrl-V | Paste selected text from clipboard. |
Ctrl-A | Select all text in editor. |
Ctrl-F | Show dialog for text finding. |
F3 | Find next occurrence of the text. |
Win-C or Meta-C | Show dialog for new command and put it into the script. |
Win-F or Meta-F | Insert last fitted formula with found coefficients. |
Win-S or Meta-S | Show dialog for styles and put it into the script. Styles define the plot view (color scheme, marks, dashing and so on). |
Win-O or Meta-O | Show dialog for options and put it into the script. Options are used for additional setup the plot. |
Win-N or Meta-N | Replace selected expression by its numerical value. |
Win-P or Meta-P | Select file and insert its file name into the script. |
Win-G or Meta-G | Show dialog for plot setup and put resulting code into the script. This dialog setup axis, labels, lighting and other general things. |
Ctrl-Shift-O | Load data from file. Data will be deleted only at exit but UDAV will not ask to save it. |
Ctrl-Shift-S | Save data to a file. |
Ctrl-Shift-C | Copy range of numbers to clipboard. |
Ctrl-Shift-V | Paste range of numbers from clipboard. |
Ctrl-Shift-N | Recreate the data with new sizes and fill it by zeros. |
Ctrl-Shift-R | Resize (interpolate) the data to specified sizes. |
Ctrl-Shift-T | Transform data along dimension(s). |
Ctrl-Shift-M | Make another data. |
Ctrl-Shift-H | Find histogram of data. |
Ctrl-T | Switch on/off transparency for the graphics. |
Ctrl-L | Switch on/off additional lightning for the graphics. |
Ctrl-G | Switch on/off grid of absolute coordinates. |
Ctrl-Space | Restore default graphics rotation, zoom and perspective. |
F5 | Execute script and redraw graphics. |
F6 | Change canvas size to fill whole region. |
F7 | Stop script execution and drawing. |
F8 | Show/hide tool window with list of hidden plots. |
F9 | Restore status for ’once’ command and reload data. |
Ctrl-F5 | Run slideshow. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-Comma, Ctrl-Period | Show next/previous slide. If no parameter specified then the dialog with slideshow options will appear. |
Ctrl-W | Open dialog with slideshow options. |
Ctrl-Shift-G | Copy graphics to clipboard. |
F1 | Show help on MGL commands |
F2 | Show/hide tool window with messages and information. |
F4 | Show/hide calculator which evaluate and help to type textual formulas. Textual formulas may contain data variables too. |
Meta-Shift-Up, Meta-Shift-Down | Change view angle \theta. |
Meta-Shift-Left, Meta-Shift-Right | Change view angle \phi. |
Alt-Minus, Alt-Equal | Zoom in/out whole image. |
Alt-Up, Alt-Down, Alt-Right, Alt-Left | Shift whole image. |
Alt-P | Export as semitransparent PNG. |
Alt-F | Export as solid PNG. |
Alt-J | Export as JPEG. |
Alt-E | Export as vector EPS. |
Alt-S | Export as vector SVG. |
Alt-L | Export as LaTeX/Tikz image. |
Alt-M | Export as MGLD. |
Alt-D | Export as PRC/PDF. |
Alt-O | Export as OBJ. |
This appendix contain description of file formats used by MathGL.
Starting from v.1.6 the MathGL library uses new font files. The font is defined in 4 files with suffixes ‘*.vfm’, ‘*_b.vfm’, ‘*_i.vfm’, ‘*_bi.vfm’. These files are text files containing the data for roman font, bold font, italic font and bold italic font. The files (or some symbols in the files) for bold, italic or bold italic fonts can be absent. In this case the roman glyph will be used for them. By analogy, if the bold italic font is absent but the bold font is present then bold glyph will be used for bold italic. You may create these font files by yourself from *.ttf, *.otf files with the help of program font_tools
. This program can be found at MathGL home site.
The format of font files (*.vfm – vector font for MathGL) is the following.
Each font file can be compressed by gzip.
Note: the closing contour line is done automatically (so the last segment may be absent). For starting new contour use a point with coordinates {0x3fff, 0x3fff}
.
MGLD is textual file, which contain all required information for drawing 3D image, i.e. it contain vertexes with colors and normales, primitives with all properties, textures, and glyph descriptions. MGLD file can be imported or viewed separately, without parsing data files itself.
MGLD file start from string
MGLD npnts nprim ntxtr nglfs # optional description
which contain signature ‘MGLD’ and number of points npnts, number of primitives nprim, number of textures ntxtr, number of glyph descriptions nglfs, and optional description. Empty strings and string with ‘#’ are ignored.
Next, file contain npnts strings with points coordinates and colors. The format of each string is
x y z c t ta u v w r g b a
Here x, y, z are coordinates, c, t are color indexes in texture, ta is normalized t according to current alpha setting, u, v, w are coordinates of normal vector (can be NAN
if disabled), r, g, b, a are RGBA color values.
Next, file contain nprim strings with properties of primitives. The format of each string is
type n1 n2 n3 n4 id s w p
Here type is kind of primitive (0 - mark, 1 - line, 2 - triangle, 3 - quadrangle, 4 - glyph), n1...n4 is index of point for vertexes, id is primitive identification number, s and w are size and width if applicable, p is scaling factor for glyphs.
Next, file contain ntxtr strings with descriptions of textures. The format of each string is
smooth alpha colors
Here smooth set to enable smoothing between colors, alpha set to use half-transparent texture, colors contain color scheme itself as it described in Цветовая схема.
Finally, file contain nglfs entries with description of each glyph used in the figure. The format of entries are
nT nL xA yA xB yB xC yC ... xP yP ...
Here nT is the number of triangles; nL is the number of line vertexes; xA, yA, xB, yB, xC, yC are coordinates of triangles; and xP, yP, xQ, yQ are coordinates of lines. Line coordinate xP=0x3fff, yP=0x3fff denote line breaking.
MathGL can save points and primitives of 3D object. It contain a set of variables listed below.
width of the image;
height of the image
depth of the image, usually =sqrt(width*height);
number of points (vertexes);
array of coordinates of points (vertexes), each element is array in form [x, y, z];
number of primitives;
array of primitives, each element is array in form [type, n1, n2, n3, n4, id, s, w, p, z, color].
Here type is kind of primitive (0 - mark, 1 - line, 2 - triangle, 3 - quadrangle, 4 - glyph), n1...n4 is index of point for vertexes and n2 can be index of glyph coordinate, s and w are size and width if applicable, z is average z-coordinate, id is primitive identification number, p is scaling factor for glyphs.
number of glyph positions
array of glyph positions, each element is array in form [dx,dy]
number of glyph descriptions
array of glyph descriptions, each element is array in form [nL, [xP0, yP0, xP1, yP1 ...]]
. Here nL
is the number of line vertexes; and xP, yP, xQ, yQ
are coordinates of lines. Line coordinate xP=0x3fff, yP=0x3fff denote line breaking.
MathGL can read IFS fractal parameters (see ifsfile) from a IFS file. Let remind IFS file format. File may contain several records. Each record contain the name of fractal (‘binary’ in the example below) and the body of fractal, which is enclosed in curly braces {}. Symbol ‘;’ start the comment. If the name of fractal contain ‘(3D)’ or ‘(3d)’ then the 3d IFS fractal is specified. The sample below contain two fractals: ‘binary’ – usual 2d fractal, and ‘3dfern (3D)’ – 3d fractal.
binary { ; comment allowed here ; and here .5 .0 .0 .5 -2.563477 -0.000003 .333333 ; also comment allowed here .5 .0 .0 .5 2.436544 -0.000003 .333333 .0 -.5 .5 .0 4.873085 7.563492 .333333 } 3dfern (3D) { .00 .00 0 .0 .18 .0 0 0.0 0.00 0 0.0 0 .01 .85 .00 0 .0 .85 .1 0 -0.1 0.85 0 1.6 0 .85 .20 -.20 0 .2 .20 .0 0 0.0 0.30 0 0.8 0 .07 -.20 .20 0 .2 .20 .0 0 0.0 0.30 0 0.8 0 .07 }
В таблице показаны времена создания графика для всех примеров из файла examples/samples.cpp. Тест выполнен на моем ноутбуке (i5-2430M) с 64-bit Debian.
Несколько слов о скорости. Во-первых, прямое рисование в память (Quality=4,5,6) быстрее буферизованного (Quality=0,1,2), но иногда результат некоректен (см. cloud) и пропадает возможность экспорта в векторные и 3d форматы (например, EPS, SVG, PDF, ...). Во-вторых, обычно картинка худшего качества рисуется быстрее, т.е. Quality=1 быстрее Quality=2, и Quality=0 быстрее Quality=1. Однако, если график содержит множество граней (например cloud, surf3, pipe, dew), то Quality=0 может быть достаточно медленным, особенно для маленьких картинок. Наконец, картинки меньшего размера рисуются быстрее.
Результаты для изображения размером 800*600 (по умолчанию).
Name | q=0 | q=1 | q=2 | q=4 | q=5 | q=6 | q=8 |
---|---|---|---|---|---|---|---|
3wave | 0.0322 | 0.0627 | 0.0721 | 0.0425 | 0.11 | 0.136 | 0.0271 |
alpha | 0.0892 | 0.108 | 0.113 | 0.0473 | 0.124 | 0.145 | 0.0297 |
apde | 48.2 | 47.4 | 47.6 | 47.4 | 47.8 | 48.4 | 47.9 |
area | 0.0376 | 0.0728 | 0.0752 | 0.033 | 0.141 | 0.165 | 0.0186 |
aspect | 0.0442 | 0.0572 | 0.0551 | 0.031 | 0.0999 | 0.103 | 0.0146 |
axial | 0.639 | 0.917 | 0.926 | 0.195 | 0.525 | 0.552 | 0.119 |
axis | 0.0683 | 0.107 | 0.108 | 0.0466 | 0.196 | 0.202 | 0.0169 |
barh | 0.0285 | 0.0547 | 0.0603 | 0.0292 | 0.101 | 0.115 | 0.0114 |
bars | 0.0414 | 0.0703 | 0.0843 | 0.1 | 0.185 | 0.184 | 0.0295 |
belt | 0.0286 | 0.0532 | 0.0577 | 0.0384 | 0.0735 | 0.1 | 0.0131 |
bifurcation | 0.589 | 0.635 | 0.609 | 0.531 | 0.572 | 0.579 | 0.512 |
box | 0.0682 | 0.0805 | 0.0828 | 0.0314 | 0.124 | 0.121 | 0.0169 |
boxplot | 0.0102 | 0.0317 | 0.0347 | 0.02 | 0.0499 | 0.0554 | 0.0167 |
boxs | 0.239 | 0.363 | 0.4 | 0.0798 | 0.216 | 0.234 | 0.0721 |
candle | 0.0286 | 0.0549 | 0.053 | 0.0263 | 0.0483 | 0.0564 | 0.0109 |
chart | 0.416 | 0.613 | 0.707 | 0.26 | 1.07 | 1.59 | 0.191 |
cloud | 0.0312 | 4.15 | 4.11 | 0.0306 | 0.715 | 0.924 | 0.0168 |
colorbar | 0.108 | 0.172 | 0.177 | 0.0787 | 0.258 | 0.266 | 0.0452 |
combined | 0.36 | 0.336 | 0.332 | 0.198 | 0.316 | 0.33 | 0.196 |
cones | 0.145 | 0.139 | 0.14 | 0.0937 | 0.248 | 0.276 | 0.0363 |
cont | 0.0987 | 0.141 | 0.141 | 0.0585 | 0.207 | 0.194 | 0.0455 |
cont3 | 0.0323 | 0.058 | 0.0587 | 0.0304 | 0.0726 | 0.0837 | 0.0162 |
cont_xyz | 0.0417 | 0.0585 | 0.0612 | 0.0417 | 0.0833 | 0.0845 | 0.0294 |
contd | 0.191 | 0.245 | 0.236 | 0.104 | 0.189 | 0.201 | 0.0902 |
contf | 0.162 | 0.179 | 0.182 | 0.0789 | 0.166 | 0.177 | 0.067 |
contf3 | 0.123 | 0.12 | 0.134 | 0.065 | 0.123 | 0.155 | 0.0538 |
contf_xyz | 0.0751 | 0.0922 | 0.111 | 0.0756 | 0.0879 | 0.0956 | 0.0462 |
contv | 0.0947 | 0.123 | 0.136 | 0.0757 | 0.163 | 0.18 | 0.0469 |
correl | 0.0339 | 0.0629 | 0.0599 | 0.0288 | 0.115 | 0.138 | 0.0165 |
curvcoor | 0.112 | 0.164 | 0.171 | 0.0864 | 0.296 | 0.298 | 0.0739 |
cut | 0.695 | 0.465 | 0.484 | 0.303 | 0.385 | 0.371 | 0.316 |
dat_diff | 0.0457 | 0.079 | 0.0825 | 0.0346 | 0.136 | 0.158 | 0.0186 |
dat_extra | 0.175 | 0.181 | 0.173 | 0.0877 | 0.163 | 0.173 | 0.0463 |
data1 | 2.39 | 1.76 | 1.75 | 1.33 | 1.38 | 1.37 | 1.4 |
data2 | 1.42 | 1.26 | 1.28 | 1.17 | 1.24 | 1.29 | 1.14 |
dens | 0.0867 | 0.122 | 0.131 | 0.0615 | 0.145 | 0.168 | 0.032 |
dens3 | 0.0722 | 0.0769 | 0.0937 | 0.0437 | 0.0947 | 0.151 | 0.0797 |
dens_xyz | 0.0599 | 0.0875 | 0.0961 | 0.0463 | 0.089 | 0.0897 | 0.0315 |
detect | 0.133 | 0.151 | 0.176 | 0.0861 | 0.116 | 0.138 | 0.0721 |
dew | 1.48 | 1.07 | 0.971 | 0.473 | 0.537 | 0.416 | 0.195 |
diffract | 0.0878 | 0.127 | 0.139 | 0.0607 | 0.219 | 0.237 | 0.0274 |
dilate | 0.0778 | 0.128 | 0.138 | 0.0592 | 0.242 | 0.232 | 0.0298 |
dots | 0.0685 | 0.1 | 0.101 | 0.0694 | 0.134 | 0.129 | 0.0261 |
earth | 0.0147 | 0.033 | 0.0218 | 0.0168 | 0.0168 | 0.0191 | 0.00177 |
error | 0.0312 | 0.0707 | 0.0709 | 0.0288 | 0.135 | 0.137 | 0.016 |
error2 | 0.0581 | 0.0964 | 0.0958 | 0.0595 | 0.173 | 0.187 | 0.0444 |
export | 0.116 | 0.158 | 0.167 | 0.0799 | 0.132 | 0.133 | 0.0685 |
fall | 0.035 | 0.051 | 0.0577 | 0.018 | 0.0585 | 0.0709 | 0.0142 |
fexport | 1.52 | 1.76 | 1.78 | 0.278 | 0.604 | 0.606 | 1.35 |
fit | 0.0371 | 0.0653 | 0.0666 | 0.0277 | 0.081 | 0.0837 | 0.014 |
flame2d | 5.37 | 5.54 | 5.5 | 3.04 | 3.21 | 3.09 | 1.13 |
flow | 0.368 | 0.451 | 0.444 | 0.36 | 0.5 | 0.48 | 0.352 |
fog | 0.0406 | 0.0645 | 0.0688 | 0.0379 | 0.0793 | 0.0894 | 0.0156 |
fonts | 0.0477 | 0.0926 | 0.112 | 0.0347 | 0.0518 | 0.0519 | 0.0413 |
grad | 0.0607 | 0.104 | 0.129 | 0.0715 | 0.103 | 0.12 | 0.0633 |
hist | 0.125 | 0.148 | 0.159 | 0.0919 | 0.116 | 0.129 | 0.0372 |
ifs2d | 0.594 | 0.623 | 0.62 | 0.315 | 0.349 | 0.33 | 0.109 |
ifs3d | 0.787 | 0.777 | 0.784 | 0.294 | 0.353 | 0.366 | 0.117 |
indirect | 0.0286 | 0.0517 | 0.0543 | 0.031 | 0.0612 | 0.104 | 0.0144 |
inplot | 0.0687 | 0.0979 | 0.0993 | 0.0622 | 0.181 | 0.195 | 0.0444 |
iris | 0.00846 | 0.025 | 0.0198 | 0.00349 | 0.0172 | 0.0182 | 0.0018 |
label | 0.0285 | 0.045 | 0.058 | 0.0267 | 0.0525 | 0.0618 | 0.014 |
lamerey | 0.0305 | 0.0372 | 0.0455 | 0.019 | 0.0604 | 0.0633 | 0.0024 |
legend | 0.0764 | 0.202 | 0.207 | 0.0455 | 0.138 | 0.148 | 0.0162 |
light | 0.0903 | 0.129 | 0.122 | 0.0573 | 0.132 | 0.144 | 0.021 |
loglog | 0.103 | 0.168 | 0.16 | 0.0806 | 0.228 | 0.235 | 0.0802 |
map | 0.0303 | 0.0653 | 0.0721 | 0.0337 | 0.0821 | 0.0866 | 0.015 |
mark | 0.0191 | 0.0324 | 0.0368 | 0.0261 | 0.0533 | 0.045 | 0.0072 |
mask | 0.0442 | 0.0964 | 0.101 | 0.0343 | 0.205 | 0.211 | 0.0115 |
mesh | 0.034 | 0.0774 | 0.0682 | 0.0192 | 0.0765 | 0.0742 | 0.0145 |
mirror | 0.092 | 0.128 | 0.142 | 0.0607 | 0.174 | 0.176 | 0.0312 |
molecule | 0.0827 | 0.0842 | 0.0859 | 0.0443 | 0.0997 | 0.146 | 0.0115 |
ode | 0.149 | 0.202 | 0.202 | 0.147 | 0.282 | 0.316 | 0.133 |
ohlc | 0.0059 | 0.0278 | 0.0271 | 0.0152 | 0.0517 | 0.045 | 0.0152 |
param1 | 0.161 | 0.252 | 0.26 | 0.0941 | 0.301 | 0.341 | 0.0466 |
param2 | 0.535 | 0.58 | 0.539 | 0.26 | 0.452 | 0.475 | 0.189 |
param3 | 1.75 | 2.37 | 2.32 | 0.677 | 0.899 | 0.907 | 0.758 |
paramv | 1.21 | 1.39 | 1.36 | 0.788 | 0.974 | 0.968 | 0.69 |
parser | 0.0346 | 0.0582 | 0.0687 | 0.0317 | 0.108 | 0.11 | 0.0275 |
pde | 0.329 | 0.358 | 0.373 | 0.272 | 0.311 | 0.364 | 0.264 |
pendelta | 0.0653 | 0.0525 | 0.0648 | 0.0517 | 0.0531 | 0.0522 | 0.0653 |
pipe | 0.598 | 0.737 | 0.738 | 0.382 | 0.493 | 0.505 | 0.34 |
plot | 0.0397 | 0.0642 | 0.114 | 0.0444 | 0.123 | 0.118 | 0.0194 |
pmap | 0.0913 | 0.115 | 0.125 | 0.0572 | 0.0999 | 0.113 | 0.0469 |
primitives | 0.0581 | 0.108 | 0.128 | 0.0649 | 0.181 | 0.21 | 0.00928 |
projection | 0.13 | 0.264 | 0.286 | 0.0704 | 0.351 | 0.349 | 0.0683 |
projection5 | 0.117 | 0.207 | 0.215 | 0.0717 | 0.3 | 0.312 | 0.0437 |
pulse | 0.0273 | 0.0395 | 0.0413 | 0.0183 | 0.0576 | 0.0635 | 0.0023 |
qo2d | 0.218 | 0.246 | 0.274 | 0.198 | 0.243 | 0.255 | 0.177 |
quality0 | 0.0859 | 0.0902 | 0.087 | 0.0808 | 0.0808 | 0.0823 | 0.0796 |
quality1 | 0.189 | 0.166 | 0.171 | 0.175 | 0.17 | 0.173 | 0.166 |
quality2 | 0.183 | 0.183 | 0.175 | 0.172 | 0.171 | 0.183 | 0.184 |
quality4 | 0.082 | 0.0713 | 0.0728 | 0.0636 | 0.0843 | 0.0651 | 0.0592 |
quality5 | 0.366 | 0.359 | 0.363 | 0.366 | 0.354 | 0.356 | 0.357 |
quality6 | 0.373 | 0.367 | 0.365 | 0.366 | 0.368 | 0.383 | 0.366 |
quality8 | 0.0193 | 0.019 | 0.0289 | 0.0298 | 0.0165 | 0.0244 | 0.0229 |
radar | 0.0193 | 0.0369 | 0.0545 | 0.0158 | 0.0525 | 0.0532 | 0.0115 |
refill | 0.153 | 0.168 | 0.166 | 0.0746 | 0.239 | 0.258 | 0.0467 |
region | 0.0396 | 0.0723 | 0.0859 | 0.0342 | 0.133 | 0.159 | 0.017 |
scanfile | 0.0315 | 0.036 | 0.0497 | 0.0169 | 0.0486 | 0.053 | 0.014 |
schemes | 0.0703 | 0.114 | 0.117 | 0.062 | 0.204 | 0.21 | 0.019 |
section | 0.0294 | 0.0483 | 0.054 | 0.0221 | 0.0804 | 0.0821 | 0.00568 |
several_light | 0.0441 | 0.0541 | 0.0701 | 0.0299 | 0.0602 | 0.0815 | 0.0117 |
solve | 0.0461 | 0.109 | 0.105 | 0.0462 | 0.18 | 0.191 | 0.0184 |
stem | 0.0418 | 0.0599 | 0.0591 | 0.0308 | 0.126 | 0.139 | 0.015 |
step | 0.0399 | 0.0614 | 0.0554 | 0.0315 | 0.0958 | 0.113 | 0.0145 |
stereo | 0.0569 | 0.0652 | 0.0811 | 0.031 | 0.0807 | 0.093 | 0.0163 |
stfa | 0.0425 | 0.117 | 0.111 | 0.0416 | 0.115 | 0.121 | 0.0157 |
style | 0.0892 | 0.197 | 0.204 | 0.0596 | 0.349 | 0.369 | 0.0158 |
surf | 0.109 | 0.133 | 0.157 | 0.0657 | 0.16 | 0.158 | 0.0315 |
surf3 | 1.79 | 2.6 | 2.57 | 0.949 | 2.36 | 2.44 | 0.625 |
surf3a | 0.431 | 0.281 | 0.297 | 0.176 | 0.235 | 0.252 | 0.178 |
surf3c | 0.423 | 0.285 | 0.301 | 0.175 | 0.202 | 0.265 | 0.177 |
surf3ca | 0.428 | 0.303 | 0.31 | 0.176 | 0.203 | 0.265 | 0.19 |
surfa | 0.0409 | 0.0577 | 0.0714 | 0.0265 | 0.062 | 0.0725 | 0.0154 |
surfc | 0.0422 | 0.0453 | 0.058 | 0.0282 | 0.0628 | 0.0749 | 0.0161 |
surfca | 0.0416 | 0.0598 | 0.058 | 0.0254 | 0.0541 | 0.0671 | 0.015 |
table | 0.103 | 0.213 | 0.214 | 0.0484 | 0.112 | 0.117 | 0.0156 |
tape | 0.0409 | 0.0784 | 0.0836 | 0.0347 | 0.124 | 0.138 | 0.0164 |
tens | 0.0329 | 0.0485 | 0.0441 | 0.0279 | 0.0805 | 0.0757 | 0.00561 |
ternary | 0.104 | 0.218 | 0.214 | 0.0634 | 0.393 | 0.425 | 0.0352 |
text | 0.0827 | 0.156 | 0.15 | 0.0261 | 0.114 | 0.127 | 0.015 |
text2 | 0.0719 | 0.12 | 0.131 | 0.115 | 0.129 | 0.137 | 0.016 |
textmark | 0.0403 | 0.0749 | 0.0788 | 0.0223 | 0.0607 | 0.0653 | 0.014 |
ticks | 0.0868 | 0.193 | 0.195 | 0.0611 | 0.259 | 0.249 | 0.0275 |
tile | 0.0349 | 0.0444 | 0.0597 | 0.0308 | 0.0546 | 0.0547 | 0.0111 |
tiles | 0.0393 | 0.0585 | 0.0534 | 0.0205 | 0.0648 | 0.0597 | 0.0174 |
torus | 0.114 | 0.197 | 0.193 | 0.0713 | 0.394 | 0.457 | 0.0306 |
traj | 0.0251 | 0.0413 | 0.043 | 0.0178 | 0.0628 | 0.0968 | 0.0129 |
triangulation | 0.0328 | 0.0659 | 0.0792 | 0.0319 | 0.0966 | 0.0888 | 0.0155 |
triplot | 0.0302 | 0.0705 | 0.102 | 0.0198 | 0.0973 | 0.127 | 0.0143 |
tube | 0.077 | 0.143 | 0.192 | 0.0593 | 0.191 | 0.21 | 0.0197 |
type0 | 0.177 | 0.172 | 0.198 | 0.0673 | 0.141 | 0.2 | 0.0576 |
type1 | 0.174 | 0.173 | 0.2 | 0.0648 | 0.153 | 0.17 | 0.0571 |
type2 | 0.188 | 0.198 | 0.197 | 0.0773 | 0.186 | 0.193 | 0.0647 |
vect | 0.129 | 0.336 | 0.194 | 0.0608 | 0.174 | 0.177 | 0.043 |
vect3 | 0.0317 | 0.0781 | 0.0869 | 0.0366 | 0.155 | 0.159 | 0.0174 |
venn | 0.0153 | 0.0503 | 0.0787 | 0.0115 | 0.0665 | 0.075 | 0.00249 |
Результаты для изображения размером 1920*1440 (для печати)
Name | q=0 | q=1 | q=2 | q=4 | q=5 | q=6 | q=8 |
---|---|---|---|---|---|---|---|
3wave | 0.0763 | 0.134 | 0.157 | 0.0764 | 0.198 | 0.207 | 0.0598 |
alpha | 0.111 | 0.176 | 0.254 | 0.104 | 0.244 | 0.272 | 0.0591 |
apde | 48 | 47.6 | 47.5 | 47.1 | 47.2 | 47.7 | 47 |
area | 0.0783 | 0.169 | 0.245 | 0.107 | 0.277 | 0.335 | 0.0408 |
aspect | 0.0622 | 0.105 | 0.129 | 0.0638 | 0.185 | 0.234 | 0.0478 |
axial | 0.681 | 1.38 | 1.61 | 0.297 | 0.878 | 1.12 | 0.141 |
axis | 0.0863 | 0.153 | 0.17 | 0.0773 | 0.274 | 0.297 | 0.0479 |
barh | 0.0631 | 0.118 | 0.134 | 0.0661 | 0.218 | 0.259 | 0.049 |
bars | 0.0654 | 0.126 | 0.153 | 0.0803 | 0.28 | 0.318 | 0.0479 |
belt | 0.0624 | 0.11 | 0.133 | 0.0614 | 0.228 | 0.354 | 0.0454 |
bifurcation | 0.604 | 0.696 | 0.758 | 0.602 | 0.656 | 0.692 | 0.572 |
box | 0.081 | 0.152 | 0.211 | 0.0754 | 0.204 | 0.238 | 0.0516 |
boxplot | 0.0458 | 0.072 | 0.108 | 0.0493 | 0.106 | 0.12 | 0.0329 |
boxs | 0.276 | 0.623 | 0.823 | 0.131 | 0.387 | 0.52 | 0.0935 |
candle | 0.0566 | 0.1 | 0.113 | 0.059 | 0.126 | 0.154 | 0.0435 |
chart | 0.46 | 1.08 | 1.78 | 0.377 | 2.57 | 3.84 | 0.19 |
cloud | 0.0618 | 5.78 | 6.76 | 0.061 | 1.49 | 2.72 | 0.0441 |
colorbar | 0.144 | 0.259 | 0.297 | 0.142 | 0.383 | 0.455 | 0.075 |
combined | 0.429 | 0.457 | 0.556 | 0.286 | 0.474 | 0.564 | 0.245 |
cones | 0.17 | 0.226 | 0.272 | 0.157 | 0.521 | 0.667 | 0.0624 |
cont | 0.0989 | 0.193 | 0.235 | 0.0952 | 0.285 | 0.304 | 0.0637 |
cont3 | 0.0645 | 0.11 | 0.122 | 0.0629 | 0.13 | 0.152 | 0.0479 |
cont_xyz | 0.0676 | 0.105 | 0.129 | 0.0628 | 0.134 | 0.148 | 0.0523 |
contd | 0.237 | 0.307 | 0.368 | 0.151 | 0.294 | 0.346 | 0.106 |
contf | 0.193 | 0.262 | 0.305 | 0.136 | 0.274 | 0.322 | 0.0921 |
contf3 | 0.169 | 0.206 | 0.3 | 0.117 | 0.232 | 0.353 | 0.0796 |
contf_xyz | 0.118 | 0.18 | 0.206 | 0.103 | 0.177 | 0.231 | 0.0661 |
contv | 0.131 | 0.226 | 0.259 | 0.114 | 0.282 | 0.334 | 0.0753 |
correl | 0.0578 | 0.108 | 0.115 | 0.0616 | 0.193 | 0.216 | 0.0463 |
curvcoor | 0.125 | 0.203 | 0.219 | 0.12 | 0.454 | 0.504 | 0.0933 |
cut | 0.768 | 0.661 | 0.73 | 0.43 | 0.53 | 0.669 | 0.431 |
dat_diff | 0.0922 | 0.151 | 0.193 | 0.092 | 0.235 | 0.274 | 0.0439 |
dat_extra | 0.202 | 0.236 | 0.263 | 0.132 | 0.254 | 0.292 | 0.0747 |
data1 | 2.62 | 2.07 | 2.14 | 1.43 | 1.69 | 1.83 | 1.56 |
data2 | 1.51 | 1.41 | 1.49 | 1.22 | 1.43 | 1.44 | 1.24 |
dens | 0.115 | 0.236 | 0.32 | 0.134 | 0.271 | 0.327 | 0.0746 |
dens3 | 0.101 | 0.154 | 0.214 | 0.0981 | 0.173 | 0.244 | 0.0429 |
dens_xyz | 0.102 | 0.179 | 0.242 | 0.119 | 0.164 | 0.22 | 0.0495 |
detect | 0.17 | 0.283 | 0.357 | 0.129 | 0.217 | 0.293 | 0.0927 |
dew | 1.63 | 1.1 | 1.19 | 0.557 | 0.797 | 0.881 | 0.288 |
diffract | 0.0961 | 0.253 | 0.346 | 0.114 | 0.382 | 0.43 | 0.0508 |
dilate | 0.098 | 0.231 | 0.259 | 0.101 | 0.347 | 0.404 | 0.0539 |
dots | 0.0986 | 0.139 | 0.167 | 0.106 | 0.24 | 0.221 | 0.223 |
earth | 0.0455 | 0.0532 | 0.0659 | 0.0448 | 0.0404 | 0.0592 | 0.0294 |
error | 0.0764 | 0.128 | 0.134 | 0.0758 | 0.203 | 0.227 | 0.076 |
error2 | 0.0739 | 0.166 | 0.188 | 0.0934 | 0.374 | 0.416 | 0.0608 |
export | 0.177 | 0.273 | 0.382 | 0.131 | 0.244 | 0.312 | 0.0968 |
fall | 0.0481 | 0.127 | 0.114 | 0.051 | 0.115 | 0.125 | 0.0442 |
fexport | 2.33 | 2.69 | 2.81 | 1.12 | 1.43 | 1.52 | 2.19 |
fit | 0.072 | 0.112 | 0.121 | 0.0657 | 0.154 | 0.166 | 0.0442 |
flame2d | 6.16 | 6.34 | 6.31 | 3.71 | 3.91 | 3.75 | 1.26 |
flow | 0.43 | 0.529 | 0.557 | 0.403 | 0.582 | 0.599 | 0.372 |
fog | 0.0651 | 0.146 | 0.209 | 0.07 | 0.172 | 0.242 | 0.0466 |
fonts | 0.0842 | 0.13 | 0.135 | 0.0669 | 0.0969 | 0.0965 | 0.0696 |
grad | 0.111 | 0.223 | 0.318 | 0.133 | 0.216 | 0.284 | 0.0783 |
hist | 0.185 | 0.227 | 0.25 | 0.136 | 0.234 | 0.253 | 0.0632 |
ifs2d | 0.7 | 0.777 | 0.762 | 0.396 | 0.457 | 0.443 | 0.133 |
ifs3d | 0.827 | 0.835 | 0.893 | 0.369 | 0.45 | 0.484 | 0.127 |
indirect | 0.0579 | 0.0904 | 0.116 | 0.0599 | 0.128 | 0.152 | 0.0316 |
inplot | 0.0931 | 0.151 | 0.19 | 0.107 | 0.32 | 0.329 | 0.0601 |
iris | 0.0446 | 0.0544 | 0.0751 | 0.0468 | 0.0457 | 0.0578 | 0.0371 |
label | 0.0484 | 0.0879 | 0.105 | 0.0601 | 0.112 | 0.164 | 0.078 |
lamerey | 0.0723 | 0.0728 | 0.0978 | 0.0611 | 0.104 | 0.154 | 0.0522 |
legend | 0.123 | 0.282 | 0.3 | 0.0796 | 0.232 | 0.311 | 0.041 |
light | 0.12 | 0.186 | 0.448 | 0.104 | 0.22 | 0.417 | 0.0528 |
loglog | 0.136 | 0.252 | 0.252 | 0.125 | 0.405 | 0.481 | 0.0956 |
map | 0.0768 | 0.157 | 0.195 | 0.0734 | 0.168 | 0.232 | 0.0471 |
mark | 0.0659 | 0.0909 | 0.0881 | 0.0718 | 0.239 | 0.151 | 0.0372 |
mask | 0.0878 | 0.207 | 0.326 | 0.0944 | 0.279 | 0.347 | 0.0511 |
mesh | 0.0719 | 0.131 | 0.163 | 0.0683 | 0.147 | 0.181 | 0.0418 |
mirror | 0.135 | 0.217 | 0.259 | 0.105 | 0.296 | 0.308 | 0.0548 |
molecule | 0.0979 | 0.146 | 0.237 | 0.0953 | 0.241 | 0.361 | 0.044 |
ode | 0.193 | 0.28 | 0.29 | 0.191 | 0.419 | 0.436 | 0.163 |
ohlc | 0.0482 | 0.071 | 0.0936 | 0.0574 | 0.109 | 0.121 | 0.0447 |
param1 | 0.186 | 0.348 | 0.424 | 0.15 | 0.545 | 0.845 | 0.0861 |
param2 | 0.57 | 0.732 | 0.806 | 0.313 | 0.698 | 0.827 | 0.23 |
param3 | 1.91 | 2.56 | 2.93 | 0.767 | 1.17 | 1.58 | 0.844 |
paramv | 1.29 | 1.55 | 1.5 | 0.816 | 1.12 | 1.11 | 0.718 |
parser | 0.0631 | 0.112 | 0.14 | 0.0643 | 0.209 | 0.232 | 0.0467 |
pde | 0.37 | 0.511 | 0.554 | 0.318 | 0.429 | 0.455 | 0.284 |
pendelta | 0.108 | 0.115 | 0.102 | 0.108 | 0.115 | 0.104 | 0.105 |
pipe | 0.661 | 0.922 | 1.04 | 0.414 | 0.669 | 0.828 | 0.36 |
plot | 0.0961 | 0.116 | 0.142 | 0.0932 | 0.22 | 0.237 | 0.0457 |
pmap | 0.137 | 0.184 | 0.216 | 0.0994 | 0.165 | 0.21 | 0.0737 |
primitives | 0.0978 | 0.191 | 0.289 | 0.0971 | 0.304 | 0.353 | 0.0386 |
projection | 0.166 | 0.403 | 0.484 | 0.124 | 0.578 | 0.626 | 0.078 |
projection5 | 0.149 | 0.323 | 0.36 | 0.117 | 0.496 | 0.546 | 0.0722 |
pulse | 0.0488 | 0.0751 | 0.0911 | 0.0503 | 0.112 | 0.13 | 0.0347 |
qo2d | 0.252 | 0.389 | 0.455 | 0.244 | 0.354 | 0.414 | 0.208 |
quality0 | 0.112 | 0.112 | 0.119 | 0.119 | 0.11 | 0.123 | 0.114 |
quality1 | 0.239 | 0.254 | 0.24 | 0.24 | 0.252 | 0.26 | 0.232 |
quality2 | 0.276 | 0.273 | 0.272 | 0.277 | 0.275 | 0.274 | 0.278 |
quality4 | 0.107 | 0.104 | 0.103 | 0.104 | 0.104 | 0.112 | 0.107 |
quality5 | 0.455 | 0.448 | 0.46 | 0.466 | 0.45 | 0.45 | 0.456 |
quality6 | 0.489 | 0.478 | 0.48 | 0.489 | 0.48 | 0.479 | 0.492 |
quality8 | 0.0575 | 0.0467 | 0.0453 | 0.0439 | 0.047 | 0.0462 | 0.0486 |
radar | 0.058 | 0.0675 | 0.0872 | 0.07 | 0.0969 | 0.123 | 0.0284 |
refill | 0.186 | 0.232 | 0.278 | 0.129 | 0.356 | 0.389 | 0.07 |
region | 0.0706 | 0.166 | 0.21 | 0.0803 | 0.274 | 0.3 | 0.0442 |
scanfile | 0.0563 | 0.0769 | 0.0884 | 0.0469 | 0.0891 | 0.106 | 0.0341 |
schemes | 0.121 | 0.227 | 0.283 | 0.189 | 0.284 | 0.338 | 0.0454 |
section | 0.0593 | 0.0948 | 0.0974 | 0.0622 | 0.159 | 0.175 | 0.0417 |
several_light | 0.076 | 0.109 | 0.244 | 0.0697 | 0.123 | 0.246 | 0.0442 |
solve | 0.0925 | 0.188 | 0.195 | 0.108 | 0.344 | 0.334 | 0.0485 |
stem | 0.0633 | 0.129 | 0.145 | 0.0827 | 0.203 | 0.212 | 0.0407 |
step | 0.0632 | 0.102 | 0.114 | 0.112 | 0.183 | 0.194 | 0.0447 |
stereo | 0.0901 | 0.126 | 0.206 | 0.0807 | 0.151 | 0.237 | 0.0441 |
stfa | 0.0925 | 0.245 | 0.291 | 0.0801 | 0.214 | 0.299 | 0.0438 |
style | 0.114 | 0.271 | 0.321 | 0.102 | 0.44 | 0.468 | 0.0451 |
surf | 0.149 | 0.241 | 0.303 | 0.12 | 0.24 | 0.319 | 0.0498 |
surf3 | 2.01 | 3.41 | 3.44 | 1.41 | 3.34 | 3.33 | 0.667 |
surf3a | 0.514 | 0.397 | 0.537 | 0.24 | 0.397 | 0.74 | 0.205 |
surf3c | 0.482 | 0.4 | 0.533 | 0.235 | 0.423 | 0.728 | 0.208 |
surf3ca | 0.494 | 0.401 | 0.536 | 0.26 | 0.402 | 0.709 | 0.243 |
surfa | 0.0643 | 0.105 | 0.181 | 0.0572 | 0.122 | 0.192 | 0.0456 |
surfc | 0.0644 | 0.111 | 0.184 | 0.0609 | 0.128 | 0.199 | 0.0399 |
surfca | 0.0645 | 0.106 | 0.181 | 0.0696 | 0.128 | 0.201 | 0.044 |
table | 0.128 | 0.263 | 0.29 | 0.0813 | 0.176 | 0.197 | 0.0481 |
tape | 0.0779 | 0.143 | 0.167 | 0.0788 | 0.224 | 0.242 | 0.0463 |
tens | 0.0605 | 0.0956 | 0.0935 | 0.0699 | 0.146 | 0.162 | 0.046 |
ternary | 0.13 | 0.334 | 0.357 | 0.116 | 0.589 | 0.65 | 0.061 |
text | 0.11 | 0.214 | 0.225 | 0.0678 | 0.172 | 0.19 | 0.0438 |
text2 | 0.0809 | 0.175 | 0.189 | 0.0797 | 0.22 | 0.235 | 0.0425 |
textmark | 0.0742 | 0.129 | 0.14 | 0.0574 | 0.126 | 0.143 | 0.0438 |
ticks | 0.126 | 0.252 | 0.274 | 0.111 | 0.329 | 0.359 | 0.0488 |
tile | 0.062 | 0.091 | 0.135 | 0.0605 | 0.11 | 0.156 | 0.0613 |
tiles | 0.06 | 0.119 | 0.158 | 0.0604 | 0.129 | 0.163 | 0.0466 |
torus | 0.148 | 0.277 | 0.391 | 0.121 | 0.817 | 1.19 | 0.0653 |
traj | 0.0476 | 0.0899 | 0.108 | 0.0559 | 0.153 | 0.162 | 0.0336 |
triangulation | 0.0622 | 0.159 | 0.218 | 0.0667 | 0.173 | 0.244 | 0.0451 |
triplot | 0.0494 | 0.181 | 0.371 | 0.0608 | 0.181 | 0.32 | 0.0308 |
tube | 0.108 | 0.286 | 0.373 | 0.104 | 0.311 | 0.379 | 0.0493 |
type0 | 0.238 | 0.326 | 0.5 | 0.144 | 0.314 | 0.479 | 0.108 |
type1 | 0.237 | 0.34 | 0.531 | 0.137 | 0.317 | 0.5 | 0.102 |
type2 | 0.243 | 0.335 | 0.509 | 0.148 | 0.317 | 0.484 | 0.115 |
vect | 0.11 | 0.248 | 0.328 | 0.127 | 0.354 | 0.325 | 0.0732 |
vect3 | 0.0692 | 0.153 | 0.173 | 0.0884 | 0.526 | 0.366 | 0.0356 |
venn | 0.0494 | 0.194 | 0.289 | 0.0664 | 0.158 | 0.236 | 0.044 |
The full list of TeX-like commands recognizable by MathGL is shown below. If command is not recognized then it will be printed as is by ommitting ‘\’ symbol. For example, ‘\#’ produce “#”, ‘\\’ produce “\”, ‘\qq’ produce “qq”.
Change case: _, ^, @.
Text style: \big, \b, \textbf, \i, \textit, \bi, \r, \textrm, \a, \overline, \u, \underline, \w, \wire, #, \color[wkrgbcymhRGBCYMHWlenupqLENUPQ]
Roots: \sqrt, \sqrt3, \sqrt4
Fractions: \frac, \dfrac, \stack, \overset, \underset, \stackr, \stackl
Accents: \hat, \tilde, \dot, \ddot, \dddot, \ddddot, \acute, \check, \grave, \vec, \bar, \breve
Special symbols:
\# (#), \% (%), \& (&), \^ (^).
\AA (Å), \AE (Æ), \APLboxquestion (⍰), \APLboxupcaret (⍓), \APLnotbackslash (⍀), \APLnotslash (⌿), \Alpha (Α), \And (&), \Angstrom (Å), \Barv (⫧), \BbbC (ℂ), \BbbGamma (ℾ), \BbbH (ℍ), \BbbN (ℕ), \BbbP (ℙ), \BbbPi (ℿ), \BbbQ (ℚ), \BbbR (ℝ), \BbbZ (ℤ), \Bbbgamma (ℽ), \Bbbpi (ℼ), \Bbbsum (⅀), \Beta (Β), \Bumpeq (≎), \Cap (⋒), \Chi (Χ), \Colon (∷), \Coloneq (⩴), \Cup (⋓), \DDownarrow (⟱), \DH (Ð), \DJ (Đ), \DashV (⫥), \DashVDash (⟚), \Dashv (⫤), \Ddownarrow (⤋), \Delta (Δ), \Digamma (Ϝ), \Doteq (≑), \Downarrow (⇓), \Epsilon (Ε), \Equiv (≣), \Eta (Η), \Eulerconst (ℇ), \Exclam (‼), \Finv (Ⅎ), \Game (⅁), \Gamma (Γ), \Gt (⪢), \Hermaphrodite (⚥), \Im (ℑ), \Iota (Ι), \Kappa (Κ), \Koppa (Ϟ), \L (Ł), \LLeftarrow (⭅), \Lambda (Λ), \Lbrbrak (⟬), \Ldsh (↲), \Leftarrow (⇐), \Leftrightarrow (⇔), \Lleftarrow (⇚), \Longleftarrow (⟸), \Longleftrightarrow (⟺), \Longmapsfrom (⟽), \Longmapsto (⟾), \Longrightarrow (⟹), \Lparengtr (⦕), \Lsh (↰), \Lt (⪡), \Lvzigzag (⧚), \Mapsfrom (⤆), \Mapsto (⤇), \Mu (Μ), \NG (Ŋ), \Nearrow (⇗), \Not (⫬), \Nu (Ν), \Nwarrow (⇖), \O (Ø), \OE (Œ), \Ohorn (Ơ), \Omega (Ω), \Omicron (Ο), \Otimes (⨷), \P (¶), \Phi (Φ), \Pi (Π), \Planckconst (ℎ), \Prec (⪻), \PropertyLine (⅊), \Psi (Ψ), \QED (∎), \Question (⁇), \RRightarrow (⭆), \Rbrbrak (⟭), \Rdsh (↳), \Re (ℜ), \Rho (Ρ), \Rightarrow (⇒), \Rparenless (⦖), \Rrightarrow (⇛), \Rsh (↱), \Rvzigzag (⧛), \S (§), \Sc (⪼), \Searrow (⇘), \Sigma (Σ), \Sqcap (⩎), \Sqcup (⩏), \Stigma (Ϛ), \Subset (⋐), \Supset (⋑), \Swarrow (⇙), \TH (Þ), \Tau (Τ), \Theta (Θ), \UUparrow (⟰), \Uhorn (Ư), \Uparrow (⇑), \Updownarrow (⇕), \Uuparrow (⤊), \VDash (⊫), \Vbar (⫫), \Vdash (⊩), \Vee (⩔), \Vert (‖), \Vvdash (⊪), \Vvert (⦀), \Wedge (⩓), \XBox (☒), \Xi (Ξ), \Yup (⅄), \Zbar (Ƶ), \Zeta (Ζ).
\aa (å), \ac (∾), \accurrent (⏦), \acidfree (♾), \acwcirclearrow (⥀), \acwgapcirclearrow (⟲), \acwleftarcarrow (⤹), \acwopencirclearrow (↺), \acwoverarcarrow (⤺), \acwundercurvearrow (⤻), \adots (⋰), \ae (æ), \aleph (ℵ), \alpha (α), \amalg (⨿), \angdnr (⦟), \angle (∠), \angles (⦞), \angleubar (⦤), \approx (≈), \approxeq (≊), \approxeqq (⩰), \approxident (≋), \arceq (≘), \aries (♈), \assert (⊦), \ast (∗), \asteq (⩮), \astrosun (☉), \asymp (≍), \awint (⨑).
\bNot (⫭), \backcong (≌), \backdprime (‶), \backepsilon (϶), \backprime (‵), \backsim (∽), \backsimeq (⋍), \backslash (\), \backtrprime (‷), \bagmember (⋿), \barV (⫪), \barcap (⩃), \barcup (⩂), \bardownharpoonleft (⥡), \bardownharpoonright (⥝), \barleftarrow (⇤), \barleftarrowrightarrowbar (↹), \barleftharpoondown (⥖), \barleftharpoonup (⥒), \barovernorthwestarrow (↸), \barrightarrowdiamond (⤠), \barrightharpoondown (⥟), \barrightharpoonup (⥛), \baruparrow (⤒), \barupharpoonleft (⥘), \barupharpoonright (⥔), \barvee (⊽), \barwedge (⊼), \bbrktbrk (⎶), \bdHrule (═), \bdVrule (║), \bdbVbH (╬), \bdbVbh (╫), \bdbVlH (╣), \bdbVlh (╢), \bdbVrH (╠), \bdbVrh (╟), \bdbvbH (╪), \bdbvbh (┼), \bdbvlH (╡), \bdbvlh (┤), \bdbvrH (╞), \bdbvrh (├), \bddVbH (╦), \bddVbh (╥), \bddVlH (╗), \bddVlh (╖), \bddVrH (╔), \bddVrh (╓), \bddvbH (╤), \bddvbh (┬), \bddvlH (╕), \bddvlh (┐), \bddvrH (╒), \bddvrh (┌), \bdhrule (─), \bdnesw (╱), \bdnwse (╲), \bdquadhdash (┈), \bdquadvdash (┊), \bdtriplevdash (┆), \bduVbH (╩), \bduVbh (╨), \bduVlH (╝), \bduVlh (╜), \bduVrH (╚), \bduVrh (╙), \bduvbH (╧), \bduvbh (┴), \bduvlH (╛), \bduvlh (┘), \bduvrH (╘), \bduvrh (└), \bdvrule (│), \because (∵), \benzenr (⏣), \beta (β), \beth (ℶ), \between (≬), \bigblacktriangledown (▼), \bigblacktriangleup (▲), \bigbot (⟘), \bigcap (⋂), \bigcup (⋃), \bigslopedvee (⩗), \bigslopedwedge (⩘), \bigstar (★), \bigtop (⟙), \bigtriangledown (▽), \bigtriangleup (△), \bigvee (⋁), \bigwedge (⋀), \bigwhitestar (☆), \blackcircledownarrow (⧭), \blackcircledrightdot (⚈), \blackcircledsanseight (➑), \blackcircledsansfive (➎), \blackcircledsansfour (➍), \blackcircledsansnine (➒), \blackcircledsansone (➊), \blackcircledsansseven (➐), \blackcircledsanssix (➏), \blackcircledsansten (➓), \blackcircledsansthree (➌), \blackcircledsanstwo (➋), \blackcircledtwodots (⚉), \blackcircleulquadwhite (◕), \blackdiamonddownarrow (⧪), \blackhourglass (⧗), \blackinwhitediamond (◈), \blackinwhitesquare (▣), \blacklefthalfcircle (◖), \blackpointerleft (◄), \blackpointerright (►), \blackrighthalfcircle (◗), \blacksmiley (☻), \blacktriangle (▴), \blacktriangledown (▾), \blacktriangleleft (◀), \blacktriangleright (▶), \blkhorzoval (⬬), \blkvertoval (⬮), \blockfull (█), \blockhalfshaded (▒), \blocklefthalf (▌), \blocklowhalf (▄), \blockqtrshaded (░), \blockrighthalf (▐), \blockthreeqtrshaded (▓), \blockuphalf (▀), \bot (⊥), \botsemicircle (◡), \bowtie (⋈), \box (◻), \boxast (⧆), \boxbar (◫), \boxbox (⧈), \boxbslash (⧅), \boxcircle (⧇), \boxdiag (⧄), \boxdot (⊡), \boxminus (⊟), \boxonbox (⧉), \boxplus (⊞), \boxtimes (⊠), \bsimilarleftarrow (⭁), \bsimilarrightarrow (⭇), \bsolhsub (⟈), \btimes (⨲), \bullet (∙), \bullseye (◎), \bumpeq (≏), \bumpeqq (⪮).
\calB (ℬ), \calE (ℰ), \calF (ℱ), \calH (ℋ), \calM (ℳ), \calR (ℛ), \cap (∩), \capdot (⩀), \capwedge (⩄), \caretinsert (‸), \carreturn (⏎), \carriagereturn (↵), \ccwundercurvearrow (⤿), \cdot (⋅), \cdotp (·), \cdots (⋯), \cdprime (ʺ), \checkmark (✓), \chi (χ), \cirE (⧃), \cirbot (⟟), \circ (∘), \circeq (≗), \circfint (⨐), \circlebottomhalfblack (◒), \circledA (Ⓐ), \circledB (Ⓑ), \circledC (Ⓒ), \circledD (Ⓓ), \circledE (Ⓔ), \circledF (Ⓕ), \circledG (Ⓖ), \circledH (Ⓗ), \circledI (Ⓘ), \circledJ (Ⓙ), \circledK (Ⓚ), \circledL (Ⓛ), \circledM (Ⓜ), \circledN (Ⓝ), \circledO (Ⓞ), \circledP (Ⓟ), \circledQ (Ⓠ), \circledR (Ⓡ), \circledS (Ⓢ), \circledT (Ⓣ), \circledU (Ⓤ), \circledV (Ⓥ), \circledW (Ⓦ), \circledX (Ⓧ), \circledY (Ⓨ), \circledZ (Ⓩ), \circleda (ⓐ), \circledast (⊛), \circledb (ⓑ), \circledbullet (⦿), \circledc (ⓒ), \circledcirc (⊚), \circledd (ⓓ), \circleddash (⊝), \circlede (ⓔ), \circledeight (⑧), \circledequal (⊜), \circledf (ⓕ), \circledfive (⑤), \circledfour (④), \circledg (ⓖ), \circledh (ⓗ), \circledi (ⓘ), \circledj (ⓙ), \circledk (ⓚ), \circledl (ⓛ), \circledm (ⓜ), \circledn (ⓝ), \circlednine (⑨), \circledo (ⓞ), \circledone (①), \circledownarrow (⧬), \circledp (ⓟ), \circledparallel (⦷), \circledq (ⓠ), \circledr (ⓡ), \circledrightdot (⚆), \circleds (ⓢ), \circledsanseight (➇), \circledsansfive (➄), \circledsansfour (➃), \circledsansnine (➈), \circledsansone (➀), \circledsansseven (➆), \circledsanssix (➅), \circledsansten (➉), \circledsansthree (➂), \circledsanstwo (➁), \circledseven (⑦), \circledsix (⑥), \circledstar (✪), \circledt (ⓣ), \circledthree (③), \circledtwo (②), \circledtwodots (⚇), \circledu (ⓤ), \circledv (ⓥ), \circledvert (⦶), \circledw (ⓦ), \circledwhitebullet (⦾), \circledx (ⓧ), \circledy (ⓨ), \circledz (ⓩ), \circledzero (⓪), \circlehbar (⦵), \circlelefthalfblack (◐), \circlellquad (◵), \circlelrquad (◶), \circleonleftarrow (⬰), \circleonrightarrow (⇴), \circlerighthalfblack (◑), \circletophalfblack (◓), \circleulquad (◴), \circleurquad (◷), \circleurquadblack (◔), \circlevertfill (◍), \cirmid (⫯), \cirscir (⧂), \clangle (〈), \closedvarcap (⩍), \closedvarcup (⩌), \closedvarcupsmashprod (⩐), \closure (⁐), \cloverleaf (⌘), \clubsuit (♣), \colon (:), \colon (∶), \coloneq (≔), \commaminus (⨩), \complement (∁), \concavediamond (⟡), \concavediamondtickleft (⟢), \concavediamondtickright (⟣), \cong (≅), \congdot (⩭), \conictaper (⌲), \conjunction (☌), \coprod (∐), \cprime (ʹ), \crangle (〉), \csub (⫏), \csube (⫑), \csup (⫐), \csupe (⫒), \cuberoot (∛), \cup (∪), \cupdot (⊍), \cupleftarrow (⊌), \cupvee (⩅), \curlyeqprec (⋞), \curlyeqsucc (⋟), \curlyvee (⋎), \curlywedge (⋏), \curvearrowleft (↶), \curvearrowleftplus (⤽), \curvearrowright (↷), \curvearrowrightminus (⤼), \cwcirclearrow (⥁), \cwgapcirclearrow (⟳), \cwopencirclearrow (↻), \cwrightarcarrow (⤸), \cwundercurvearrow (⤾), \cylcty (⌭).
\dag (†), \dagger (†), \daleth (ℸ), \danger (☡), \dashV (⫣), \dashVdash (⟛), \dashcolon (∹), \dashleftharpoondown (⥫), \dashrightharpoondown (⥭), \dashv (⊣), \dbkarow (⤏), \ddag (‡), \ddagger (‡), \ddots (⋱), \ddotseq (⩷), \delta (δ), \dh (ð), \diameter (⌀), \diamond (◇), \diamondbotblack (⬙), \diamondcdot (⟐), \diamondleftarrow (⤝), \diamondleftarrowbar (⤟), \diamondleftblack (⬖), \diamondrightblack (⬗), \diamondsuit (♢), \diamondtopblack (⬘), \dicei (⚀), \diceii (⚁), \diceiii (⚂), \diceiv (⚃), \dicev (⚄), \dicevi (⚅), \digamma (ϝ), \dingasterisk (✽), \dircurrent (⎓), \disin (⋲), \div (÷), \divideontimes (⋇), \dj (đ), \dlcrop (⌍), \doteq (≐), \dotequiv (⩧), \dotminus (∸), \dotplus (∔), \dots (…), \dotsim (⩪), \dotsminusdots (∺), \dottedcircle (◌), \dottedsquare (⬚), \dottimes (⨰), \doublebarvee (⩢), \doublebarwedge (⩞), \doubleplus (⧺), \downarrow (↓), \downarrowbar (⤓), \downarrowbarred (⤈), \downdasharrow (⇣), \downdownarrows (⇊), \downfishtail (⥿), \downharpoonleft (⇃), \downharpoonleftbar (⥙), \downharpoonright (⇂), \downharpoonrightbar (⥕), \downharpoonsleftright (⥥), \downrightcurvedarrow (⤵), \downtriangleleftblack (⧨), \downtrianglerightblack (⧩), \downuparrows (⇵), \downupharpoonsleftright (⥯), \downwhitearrow (⇩), \downzigzagarrow (↯), \dprime (″), \draftingarrow (➛), \drbkarow (⤐), \drcrop (⌌), \dsol (⧶), \dsub (⩤), \dualmap (⧟).
\earth (♁), \egsdot (⪘), \eighthnote (♪), \elinters (⏧), \ell (ℓ), \elsdot (⪗), \emdash (—), \emptyset (∅), \emptysetoarr (⦳), \emptysetoarrl (⦴), \emptysetobar (⦱), \emptysetocirc (⦲), \endash (–), \enleadertwodots (‥), \envelope (✉), \eparsl (⧣), \epsilon (ϵ), \eqcirc (≖), \eqcolon (≕), \eqdef (≝), \eqdot (⩦), \eqeq (⩵), \eqeqeq (⩶), \eqgtr (⋝), \eqless (⋜), \eqqgtr (⪚), \eqqless (⪙), \eqqplus (⩱), \eqqsim (⩳), \eqqslantgtr (⪜), \eqqslantless (⪛), \eqsim (≂), \eqslantgtr (⪖), \eqslantless (⪕), \equalleftarrow (⭀), \equalparallel (⋕), \equalrightarrow (⥱), \equiv (≡), \equivDD (⩸), \equivVert (⩨), \equivVvert (⩩), \eqvparsl (⧥), \errbarblackcircle (⧳), \errbarblackdiamond (⧱), \errbarblacksquare (⧯), \errbarcircle (⧲), \errbardiamond (⧰), \errbarsquare (⧮), \eta (η), \euro (€), \exists (∃).
\fallingdotseq (≒), \fbowtie (⧓), \fcmp (⨾), \fdiagovnearrow (⤯), \fdiagovrdiag (⤬), \female (♀), \figdash (‒), \fint (⨏), \fisheye (◉), \flat (♭), \fltns (⏥), \forall (∀), \forks (⫝̸), \forksnot (⫝), \forkv (⫙), \fourthroot (∜), \fourvdots (⦙), \fracfiveeighths (⅝), \fracfivesixths (⅚), \fracfourfifths (⅘), \fraconeeighth (⅛), \fraconefifth (⅕), \fraconesixth (⅙), \fraconethird (⅓), \fracseveneights (⅞), \fracslash (⁄), \fracthreeeighths (⅜), \fracthreefifths (⅗), \fractwofifths (⅖), \fractwothirds (⅔), \frakC (ℭ), \frakH (ℌ), \frakZ (ℨ), \frown (⌢), \frownie (☹), \fullouterjoin (⟗).
\gamma (γ), \ge (≥), \geq (≥), \geqq (≧), \geqslant (⩾), \gescc (⪩), \gesdot (⪀), \gesdoto (⪂), \gesdotol (⪄), \gesles (⪔), \gets (←), \gg (≫), \ggg (⋙), \gggnest (⫸), \gimel (ℷ), \glE (⪒), \gla (⪥), \gleichstark (⧦), \glj (⪤), \gnapprox (⪊), \gneq (⪈), \gneqq (≩), \gnsim (⋧), \greater (>), \gsime (⪎), \gsiml (⪐), \gtcc (⪧), \gtcir (⩺), \gtlpar (⦠), \gtquest (⩼), \gtrapprox (⪆), \gtrarr (⥸), \gtrdot (⋗), \gtreqless (⋛), \gtreqqless (⪌), \gtrless (≷), \gtrsim (≳), \guillemotleft («), \guillemotright (»), \guilsinglleft (‹), \guilsinglright (›).
\harrowextender (⎯), \hatapprox (⩯), \hbar (ℏ), \heartsuit (♡), \hermitmatrix (⊹), \hexagon (⎔), \hexagonblack (⬣), \hiraganano (の), \hknearrow (⤤), \hknwarrow (⤣), \hksearow (⤥), \hkswarow (⤦), \hookleftarrow (↩), \hookrightarrow (↪), \horizbar (―), \hourglass (⧖), \house (⌂), \hrectangle (▭), \hrectangleblack (▬), \hslash (ℏ), \hyphenbullet (⁃), \hzigzag (〰).
\iiiint (⨌), \iiint (∭), \iinfin (⧜), \iint (∬), \imageof (⊷), \in (∈), \incare (℅), \increment (∆), \infty (∞), \int (∫), \intBar (⨎), \intbar (⨍), \intbottom (⌡), \intcap (⨙), \intclockwise (∱), \intcup (⨚), \intercal (⊺), \interleave (⫴), \intextender (⎮), \intlharhk (⨗), \intprod (⨼), \intprodr (⨽), \inttop (⌠), \intx (⨘), \inversebullet (◘), \inversewhitecircle (◙), \invnot (⌐), \invwhitelowerhalfcircle (◛), \invwhiteupperhalfcircle (◚), \iota (ι), \ipasupgamma (ˠ), \ipasupl (ˡ), \ipasuprerglotstpp (ˤ), \ipasups (ˢ), \ipasupx (ˣ), \ipaunaspirated (˭), \ipavoicing (ˬ), \isinE (⋹), \isindot (⋵), \isinobar (⋷), \isins (⋴), \isinvb (⋸), \itBbbD (ⅅ), \itBbbd (ⅆ), \itBbbe (ⅇ), \itBbbi (ⅈ), \itBbbj (ⅉ).
\jupiter (♃), \kappa (κ), \kernelcontraction (∻), \koppa (ϟ).
\l (ł), \lAngle (⟪), \lBrace (⦃), \lBrack (⟦), \lParen (⦅), \lambda (λ), \lambdabar (ƛ), \langle (⟨), \langledot (⦑), \laplac (⧠), \lasp (ʽ), \lat (⪫), \late (⪭), \lbag (⟅), \lblkbrbrak (⦗), \lbrace ({), \lbracelend (⎩), \lbracemid (⎨), \lbraceuend (⎧), \lbrack ([), \lbrackextender (⎢), \lbracklend (⎣), \lbracklltick (⦏), \lbrackubar (⦋), \lbrackuend (⎡), \lbrackultick (⦍), \lbrbrak (❲), \lceil (⌈), \lcurvyangle (⧼), \ldasharrhead (⇠), \le (≤), \leadsto (↝), \leftarrow (←), \leftarrowapprox (⭊), \leftarrowbackapprox (⭂), \leftarrowbsimilar (⭋), \leftarrowless (⥷), \leftarrowonoplus (⬲), \leftarrowplus (⥆), \leftarrowshortrightarrow (⥃), \leftarrowsimilar (⥳), \leftarrowsubset (⥺), \leftarrowtail (↢), \leftarrowtriangle (⇽), \leftarrowx (⬾), \leftbkarrow (⤌), \leftcurvedarrow (⬿), \leftdasharrow (⇠), \leftdasharrowhead (⇡), \leftdbkarrow (⤎), \leftdbltail (⤛), \leftdotarrow (⬸), \leftdowncurvedarrow (⤶), \leftfishtail (⥼), \leftharpoondown (↽), \leftharpoondownbar (⥞), \leftharpoonsupdown (⥢), \leftharpoonup (↼), \leftharpoonupbar (⥚), \leftharpoonupdash (⥪), \leftleftarrows (⇇), \leftmoon (☾), \leftouterjoin (⟕), \leftrightarrow (↔), \leftrightarrowcircle (⥈), \leftrightarrows (⇆), \leftrightarrowtriangle (⇿), \leftrightharpoondowndown (⥐), \leftrightharpoondownup (⥋), \leftrightharpoons (⇋), \leftrightharpoonsdown (⥧), \leftrightharpoonsup (⥦), \leftrightharpoonupdown (⥊), \leftrightharpoonupup (⥎), \leftrightsquigarrow (↭), \leftsquigarrow (↜), \leftsquigarrow (⇜), \lefttail (⤙), \leftthreearrows (⬱), \leftthreetimes (⋋), \leftwhitearrow (⇦), \leq (≤), \leqq (≦), \leqqslant (⫹), \leqqslant (⫺), \leqslant (⩽), \lescc (⪨), \lesdot (⩿), \lesdoto (⪁), \lesdotor (⪃), \lesges (⪓), \less (<), \lessapprox (⪅), \lessdot (⋖), \lesseqgtr (⋚), \lesseqqgtr (⪋), \lessgtr (≶), \lesssim (≲), \lfbowtie (⧑), \lfloor (⌊), \lftimes (⧔), \lgE (⪑), \lgblkcircle (⬤), \lgblksquare (⬛), \lgwhtcircle (◯), \lgwhtsquare (⬜), \lhd (⊲), \linefeed (↴), \ll (≪), \llangle (⦉), \llarc (◟), \llblacktriangle (◣), \llcorner (⌞), \lll (⋘), \lllnest (⫷), \llparenthesis (⦇), \lltriangle (◺), \lmoustache (⎰), \lnapprox (⪉), \lneq (⪇), \lneqq (≨), \lnsim (⋦), \longdashv (⟞), \longdivision (⟌), \longleftarrow (⟵), \longleftrightarrow (⟷), \longleftsquigarrow (⬳), \longmapsfrom (⟻), \longmapsto (⟼), \longrightarrow (⟶), \longrightsquigarrow (⟿), \looparrowleft (↫), \looparrowright (↬), \lowint (⨜), \lozenge (◊), \lozengeminus (⟠), \lparenextender (⎜), \lparenlend (⎝), \lparenless (⦓), \lparenuend (⎛), \lq (‘), \lrarc (◞), \lrblacktriangle (◢), \lrcorner (⌟), \lrtriangle (◿), \lrtriangleeq (⧡), \lsime (⪍), \lsimg (⪏), \lsqhook (⫍), \ltcc (⪦), \ltcir (⩹), \ltimes (⋉), \ltlarr (⥶), \ltquest (⩻), \ltrivb (⧏), \lvboxline (⎸), \lvzigzag (⧘).
\male (♂), \maltese (✠), \mapsdown (↧), \mapsfrom (↤), \mapsto (↦), \mapsup (↥), \mdblkdiamond (⬥), \mdblklozenge (⬧), \mdblkrcl (⚫), \mdblksquare (◼), \mdlgblkcircle (●), \mdlgblkdiamond (◆), \mdlgblklozenge (⧫), \mdlgblksquare (■), \mdlgwhtcircle (○), \mdlgwhtdiamond (◇), \mdlgwhtsquare (□), \mdsmblkcircle (⦁), \mdsmblksquare (◾), \mdsmwhtcircl (⚬), \mdsmwhtsquare (◽), \mdwhtcircl (⚪), \mdwhtdiamond (⬦), \mdwhtlozenge (⬨), \mdwhtsquare (◻), \measangledltosw (⦯), \measangledrtose (⦮), \measangleldtosw (⦫), \measanglelutonw (⦩), \measanglerdtose (⦪), \measanglerutone (⦨), \measangleultonw (⦭), \measangleurtone (⦬), \measeq (≞), \measuredangle (∡), \measuredangleleft (⦛), \measuredrightangle (⊾), \medblackstar (⭑), \medmathspace ( ), \medwhitestar (⭐), \mercury (☿), \mho (℧), \mid (∣), \midbarvee (⩝), \midbarwedge (⩜), \midcir (⫰), \minus (−), \minusdot (⨪), \minusfdots (⨫), \minusrdots (⨬), \mlcp (⫛), \models (⊧), \mp (∓), \mu (μ), \multimap (⊸), \multimapinv (⟜).
\nHdownarrow (⇟), \nHuparrow (⇞), \nLeftarrow (⇍), \nLeftrightarrow (⇎), \nRightarrow (⇏), \nVDash (⊯), \nVdash (⊮), \nVleftarrow (⇺), \nVleftarrowtail (⬺), \nVleftrightarrow (⇼), \nVrightarrow (⇻), \nVrightarrowtail (⤕), \nVtwoheadleftarrow (⬵), \nVtwoheadleftarrowtail (⬽), \nVtwoheadrightarrow (⤁), \nVtwoheadrightarrowtail (⤘), \nabla (∇), \napprox (≉), \nasymp (≭), \natural (♮), \ncong (≇), \ne (≠), \nearrow (↗), \neg (¬), \neovnwarrow (⤱), \neovsearrow (⤮), \neptune (♆), \neq (≠), \nequiv (≢), \neswarrow (⤢), \neuter (⚲), \nexists (∄), \ng (ŋ), \ngeq (≱), \ngtr (≯), \ngtrless (≹), \ngtrsim (≵), \nhVvert (⫵), \nhpar (⫲), \ni (∋), \niobar (⋾), \nis (⋼), \nisd (⋺), \nleftarrow (↚), \nleftrightarrow (↮), \nleq (≰), \nless (≮), \nlessgtr (≸), \nlesssim (≴), \nmid (∤), \nni (∌), \nobreakhyphen (‑), \notin (∉), \nparallel (∦), \npolint (⨔), \nprec (⊀), \npreccurlyeq (⋠), \nrightarrow (↛), \nsim (≁), \nsime (≄), \nsqsubseteq (⋢), \nsqsupseteq (⋣), \nsubset (⊄), \nsubseteq (⊈), \nsucc (⊁), \nsucccurlyeq (⋡), \nsupset (⊅), \nsupseteq (⊉), \ntriangleleft (⋪), \ntrianglelefteq (⋬), \ntriangleright (⋫), \ntrianglerighteq (⋭), \nu (ν), \nvDash (⊭), \nvLeftarrow (⤂), \nvLeftrightarrow (⤄), \nvRightarrow (⤃), \nvdash (⊬), \nvinfty (⧞), \nvleftarrow (⇷), \nvleftarrowtail (⬹), \nvleftrightarrow (⇹), \nvrightarrow (⇸), \nvrightarrowtail (⤔), \nvtwoheadleftarrow (⬴), \nvtwoheadleftarrowtail (⬼), \nvtwoheadrightarrow (⤀), \nvtwoheadrightarrowtail (⤗), \nwarrow (↖), \nwovnearrow (⤲), \nwsearrow (⤡).
\o (ø), \obar (⌽), \obot (⦺), \obrbrak (⏠), \obslash (⦸), \odiv (⨸), \odot (⊙), \odotslashdot (⦼), \oe (œ), \ogreaterthan (⧁), \ohorn (ơ), \oiiint (∰), \oiint (∯), \oint (∮), \ointctrclockwise (∳), \olcross (⦻), \oldKoppa (Ϙ), \oldkoppa (ϙ), \olessthan (⧀), \omega (ω), \omicron (ο), \ominus (⊖), \operp (⦹), \oplus (⊕), \opluslhrim (⨭), \oplusrhrim (⨮), \origof (⊶), \oslash (⊘), \otimes (⊗), \otimeshat (⨶), \otimeslhrim (⨴), \otimesrhrim (⨵), \overbrace (⏞), \overbracket (⎴), \overline (‾), \overparen (⏜), \owns (∋).
\parallel (∥), \parallelogram (▱), \parallelogramblack (▰), \parsim (⫳), \partial (∂), \partialmeetcontraction (⪣), \pentagon (⬠), \pentagonblack (⬟), \perp (⟂), \perps (⫡), \phi (ϕ), \phone (☎), \pi (π), \pitchfork (⋔), \plusdot (⨥), \pluseqq (⩲), \plushat (⨣), \plussim (⨦), \plussubtwo (⨧), \plustrif (⨨), \pluto (♇), \pm (±), \pointnt (⨕), \postalmark (〒), \prec (≺), \precapprox (⪷), \preccurlyeq (≼), \preceq (⪯), \preceqq (⪳), \precnapprox (⪹), \precneq (⪱), \precneqq (⪵), \precnsim (⋨), \precsim (≾), \prime (′), \prod (∏), \profalar (⌮), \profline (⌒), \profsurf (⌓), \propto (∝), \prurel (⊰), \psi (ψ), \pullback (⟓), \pushout (⟔).
\qprime (⁗), \quarternote (♩), \questeq (≟), \quotdblbase („), \quotdblright (‟), \quotsinglbase (‚), \quotsinglright (‛).
\rAngle (⟫), \rBrace (⦄), \rBrack (⟧), \rParen (⦆), \rangle (⟩), \rangledot (⦒), \rangledownzigzagarrow (⍼), \rasp (ʼ), \rbag (⟆), \rblkbrbrak (⦘), \rbrace (}), \rbracelend (⎭), \rbracemid (⎬), \rbraceuend (⎫), \rbrack (]), \rbrackextender (⎥), \rbracklend (⎦), \rbracklrtick (⦎), \rbrackubar (⦌), \rbrackuend (⎤), \rbrackurtick (⦐), \rbrbrak (❳), \rceil (⌉), \rcurvyangle (⧽), \rdiagovfdiag (⤫), \rdiagovsearrow (⤰), \recorder (⌕), \revangle (⦣), \revangleubar (⦥), \revemptyset (⦰), \revnmid (⫮), \rfbowtie (⧒), \rfloor (⌋), \rftimes (⧕), \rhd (⊳), \rho (ρ), \righarrowbsimilar (⭌), \rightangle (∟), \rightanglemdot (⦝), \rightanglesqr (⦜), \rightarrow (→), \rightarrowapprox (⥵), \rightarrowbackapprox (⭈), \rightarrowbar (⇥), \rightarrowdiamond (⤞), \rightarrowgtr (⭃), \rightarrowonoplus (⟴), \rightarrowplus (⥅), \rightarrowshortleftarrow (⥂), \rightarrowsimilar (⥴), \rightarrowsupset (⭄), \rightarrowtail (↣), \rightarrowtriangle (⇾), \rightarrowx (⥇), \rightbkarrow (⤍), \rightcurvedarrow (⤳), \rightdasharrow (⇢), \rightdbltail (⤜), \rightdotarrow (⤑), \rightdowncurvedarrow (⤷), \rightfishtail (⥽), \rightharpoondown (⇁), \rightharpoondownbar (⥗), \rightharpoonsupdown (⥤), \rightharpoonup (⇀), \rightharpoonupbar (⥓), \rightharpoonupdash (⥬), \rightimply (⥰), \rightleftarrows (⇄), \rightleftharpoons (⇌), \rightleftharpoonsdown (⥩), \rightleftharpoonsup (⥨), \rightmoon (☽), \rightouterjoin (⟖), \rightpentagon (⭔), \rightpentagonblack (⭓), \rightrightarrows (⇉), \rightsquigarrow (↝), \rightsquigarrow (⇝), \righttail (⤚), \rightthreearrows (⇶), \rightthreetimes (⋌), \rightwhitearrow (⇨), \ringplus (⨢), \risingdotseq (≓), \rmoustache (⎱), \rparenextender (⎟), \rparengtr (⦔), \rparenlend (⎠), \rparenuend (⎞), \rppolint (⨒), \rq (’), \rrangle (⦊), \rrparenthesis (⦈), \rsolbar (⧷), \rsqhook (⫎), \rsub (⩥), \rtimes (⋊), \rtriltri (⧎), \ruledelayed (⧴), \rvboxline (⎹), \rvzigzag (⧙).
\sampi (ϡ), \sansLmirrored (⅃), \sansLturned (⅂), \saturn (♄), \scissors (✂), \scpolint (⨓), \scrB (ℬ), \scrE (ℰ), \scrF (ℱ), \scrH (ℋ), \scrI (ℐ), \scrL (ℒ), \scrM (ℳ), \scrR (ℛ), \scre (ℯ), \scrg (ℊ), \scro (ℴ), \scurel (⊱), \searrow (↘), \seovnearrow (⤭), \setminus (∖), \setminus (⧵), \sharp (♯), \shortdowntack (⫟), \shortleftarrow (←), \shortlefttack (⫞), \shortrightarrow (→), \shortrightarrowleftarrow (⥄), \shortuptack (⫠), \shuffle (⧢), \sigma (σ), \silon (υ), \silon (ϒ), \sim (∼), \simeq (≃), \simgE (⪠), \simgtr (⪞), \similarleftarrow (⭉), \similarrightarrow (⥲), \simlE (⪟), \simless (⪝), \simminussim (⩬), \simneqq (≆), \simplus (⨤), \simrdots (⩫), \sinewave (∿), \slash (∕), \smallblacktriangleleft (◂), \smallblacktriangleright (▸), \smalldiamond (⋄), \smallin (∊), \smallint (∫), \smallni (∍), \smallsetminus (∖), \smalltriangleleft (◃), \smalltriangleright (▹), \smashtimes (⨳), \smblkdiamond (⬩), \smblklozenge (⬪), \smblksquare (▪), \smeparsl (⧤), \smile (⌣), \smiley (☺), \smt (⪪), \smte (⪬), \smwhitestar (⭒), \smwhtcircle (◦), \smwhtlozenge (⬫), \smwhtsquare (▫), \spadesuit (♠), \sphericalangle (∢), \sphericalangleup (⦡), \sqcap (⊓), \sqcup (⊔), \sqint (⨖), \sqlozenge (⌑), \sqrt (√), \sqrt3 (∛), \sqrt4 (∜), \sqrtbottom (⎷), \sqsubset (⊏), \sqsubseteq (⊑), \sqsubsetneq (⋤), \sqsupset (⊐), \sqsupseteq (⊒), \sqsupsetneq (⋥), \squarecrossfill (▩), \squaregrayfill (▩), \squarehfill (▤), \squarehvfill (▦), \squareleftblack (◧), \squareleftblack (◨), \squarellblack (⬕), \squarellquad (◱), \squarelrblack (◪), \squarelrquad (◲), \squareneswfill (▨), \squarenwsefill (▧), \squareulblack (◩), \squareulquad (◰), \squareurblack (⬔), \squareurquad (◳), \squarevfill (▥), \squoval (▢), \ss (ß), \star (⋆), \stareq (≛), \sterling (£), \stigma (ϛ), \strns (⏤), \subedot (⫃), \submult (⫁), \subrarr (⥹), \subset (⊂), \subsetapprox (⫉), \subsetcirc (⟃), \subsetdot (⪽), \subseteq (⊆), \subseteqq (⫅), \subsetneq (⊊), \subsetneqq (⫋), \subsetplus (⪿), \subsim (⫇), \subsub (⫕), \subsup (⫓), \succ (≻), \succapprox (⪸), \succcurlyeq (≽), \succeq (⪰), \succeqq (⪴), \succnapprox (⪺), \succneq (⪲), \succneqq (⪶), \succnsim (⋩), \succsim (≿), \sum (∑), \sumbottom (⎳), \sumint (⨋), \sumtop (⎲), \sun (☼), \supdsub (⫘), \supedot (⫄), \suphsol (⟉), \suphsub (⫗), \suplarr (⥻), \supmult (⫂), \supn (ⁿ), \supset (⊃), \supsetapprox (⫊), \supsetcirc (⟄), \supsetdot (⪾), \supseteq (⊇), \supseteqq (⫆), \supsetneq (⊋), \supsetneqq (⫌), \supsetplus (⫀), \supsim (⫈), \supsub (⫔), \supsup (⫖), \surd (√), \swarrow (↙).
\talloblong (⫾), \target (⌖), \tau (τ), \taurus (♉), \testhookx (ᶍ), \textAsterisks (⁑), \textacute (ˊ), \textadvanced (˖), \textain (ʿ), \textasciiacute (´), \textasciicircum (^), \textasciidieresis (¨), \textasciigrave (‘), \textasciimacron (¯), \textasciitilde (~), \textasterisklow (⁎), \textbackdprime (‶), \textbackprime (‵), \textbacktrprime (‷), \textbardotlessj (ɟ), \textbardotlessjvar (ʄ), \textbarglotstop (ʡ), \textbari (ɨ), \textbarl (ƚ), \textbaro (ɵ), \textbarrevglotstop (ʢ), \textbaru (ʉ), \textbeltl (ɬ), \textbenttailyogh (ƺ), \textbreve (˘), \textbrokenbar (¦), \textbullet (•), \textbullseye (ʘ), \textcent (¢), \textcircledP (℗), \textcloseepsilon (ʚ), \textcloseomega (ɷ), \textcloserevepsilon (ɞ), \textcopyright (©), \textcrb (ƀ), \textcrh (ħ), \textcrinvglotstop (ƾ), \textcrlambda (ƛ), \textcrtwo (ƻ), \textctc (ɕ), \textctd (ȡ), \textctesh (ʆ), \textctj (ʝ), \textctl (ȴ), \textctn (ȵ), \textctt (ȶ), \textctyogh (ʓ), \textctz (ʑ), \textcurrency (¤), \textdctzlig (ʥ), \textdegree (°), \textdiscount (⁒), \textdollar ($), \textdotaccent (˙), \textdotlessj (ȷ), \textdoubleacute (˝), \textdoublebarpipe (ǂ), \textdoublepipe (ǁ), \textdprime (″), \textdptr (˅), \textdyoghlig (ʤ), \textdzlig (ʣ), \textepsilon (ɛ), \textesh (ʃ), \textestimated (℮), \textexclam (ǃ), \textexclamdown (¡), \textfishhookr (ɾ), \textflorin (ƒ), \textfranc (₣), \textgamma (ɣ), \textglotstop (ʔ), \textgrave (ˋ), \texthalflength (ˑ), \texthamza (ʾ), \texthen (ꜧ), \textheng (ꜧ), \texthooks (ᶊ), \texthookz (ᶎ), \texthtb (ɓ), \texthtc (ƈ), \texthtd (ɗ), \texthtg (ɠ), \texthth (ɦ), \texththeng (ɧ), \texthtk (ƙ), \texthtp (ƥ), \texthtq (ʠ), \texthtscg (ʛ), \texthtt (ƭ), \texthvlig (ƕ), \texthyphen (‐), \textinvglotstop (ʖ), \textinvscr (ʁ), \textiota (ɩ), \textlengthmark (ː), \textlhalfring (˓), \textlhookd (ᶁ), \textlhookk (ᶄ), \textlhookl (ᶅ), \textlhookt (ƫ), \textlhti (ɿ), \textlira (₤), \textlonglegr (ɼ), \textlongy (ʮ), \textlongy (ʯ), \textlooptoprevesh (ƪ), \textlowacute (ˏ), \textlowered (˕), \textlowgrave (ˎ), \textlowmacron (ˍ), \textlptr (˂), \textltailm (ɱ), \textltailn (ɲ), \textltilde (ɫ), \textlyoghlig (ɮ), \textmacron (ˉ), \textmu (µ), \textnumero (№), \textogonek (˛), \textohm (Ω), \textonehalf (½), \textonequarter (¼), \textonesuperior (¹), \textopeno (ɔ), \textordfeminine (ª), \textordmasculine (º), \textovercross (˟), \textoz (℥), \textpertenthousand (‱), \textperthousand (‰), \textpesetas (₧), \textphi (ɸ), \textpipe (ǀ), \textprime (′), \textprimstress (ˈ), \textqprime (⁗), \textquestiondown (¿), \textquotedbl ("), \textquotedblleft (“), \textquotedblright (”), \textraised (˔), \textraiseglotstop (ˀ), \textraiserevglotstop (ˁ), \textramshorns (ɤ), \textrecipe (℞), \textreferencemark (※), \textregistered (®), \textretracted (˗), \textreve (ɘ), \textrevepsilon (ɜ), \textrevglotstop (ʕ), \textrhalfring (˒), \textrhookrevepsilon (ɝ), \textrhookschwa (ɚ), \textrhoticity (˞), \textringaccent (˚), \textrptr (˃), \textrtaild (ɖ), \textrtaill (ɭ), \textrtailn (ɳ), \textrtailr (ɽ), \textrtails (ʂ), \textrtailt (ʈ), \textrtailz (ʐ), \textsca (ᴀ), \textscb (ʙ), \textsce (ᴇ), \textscg (ɢ), \textsch (ʜ), \textschwa (ə), \textsci (ɪ), \textscl (ʟ), \textscn (ɴ), \textscoelig (ɶ), \textscr (ʀ), \textscripta (ɑ), \textscriptg (ɡ), \textscriptv (ʋ), \textscu (ᴜ), \textscy (ʏ), \textsecstress (ˌ), \textsemicolonreversed (⁏), \textsilon (Υ), \textsmalltilde (˜), \textstretchcvar (ʗ), \textsubw (w), \textsuph (ʰ), \textsuphth (ʱ), \textsupinvscr (ʶ), \textsupj (ʲ), \textsupr (ʳ), \textsupturnr (ʴ), \textsupturnrrtail (ʵ), \textsupw (ʷ), \textsupy (ʸ), \texttctctlig (ʧ), \texttctctlig (ʨ), \textthreequarters (¾), \textthreesuperior (³), \texttrademark (™), \texttrprime (‴), \texttslig (ʦ), \textturna (ɐ), \textturncomma (ʻ), \textturnh (ɥ), \textturnk (ʞ), \textturnlonglegr (ɺ), \textturnm (ɯ), \textturnmrleg (ɰ), \textturnr (ɹ), \textturnrrtail (ɻ), \textturnscripta (ɒ), \textturnt (ʇ), \textturnv (ʌ), \textturnw (ʍ), \textturny (ʎ), \texttwosuperior (²), \textupsilon (ʊ), \textuptr (˄), \textvibyi (ʅ), \textvisiblespace (␣), \textyogh (ʒ), \th (þ), \therefore (∴), \thermod (⧧), \theta (θ), \thickapprox (≈), \thicksim (∼), \threedangle (⟀), \threedotcolon (⫶), \tieconcat (⁀), \tieinfty (⧝), \times (×), \timesbar (⨱), \tminus (⧿), \to (→), \toea (⤨), \tona (⤧), \tonebarextrahigh (˥), \tonebarextralow (˩), \tonebarhigh (˦), \tonebarlow (˨), \tonebarmid (˧), \top (⊤), \topbot (⌶), \topcir (⫱), \topfork (⫚), \topsemicircle (◠), \tosa (⤩), \towa (⤪), \tplus (⧾), \trapezium (⏢), \trianglecdot (◬), \triangledown (▿), \triangleexclam (⚠), \triangleleft (◁), \triangleleftblack (◭), \trianglelefteq (⊴), \triangleminus (⨺), \triangleodot (⧊), \triangleplus (⨹), \triangleq (≜), \triangleright (▷), \trianglerightblack (◮), \trianglerighteq (⊵), \triangles (⧌), \triangleserifs (⧍), \triangletimes (⨻), \triangleubar (⧋), \tripleplus (⧻), \trprime (‴), \turnangle (⦢), \turnediota (℩), \turnednot (⌙), \twocaps (⩋), \twocups (⩊), \twoheaddownarrow (↡), \twoheadleftarrow (↞), \twoheadleftarrowtail (⬻), \twoheadleftdbkarrow (⬷), \twoheadmapsfrom (⬶), \twoheadmapsto (⤅), \twoheadrightarrow (↠), \twoheadrightarrowtail (⤖), \twoheaduparrow (↟), \twoheaduparrowcircle (⥉), \twolowline (‗), \twonotes (♫), \typecolon (⦂).
\ubrbrak (⏡), \uhorn (ư), \ularc (◜), \ulblacktriangle (◤), \ulcorner (⌜), \ulcrop (⌏), \ultriangle (◸), \uminus (⩁), \underbrace (⏟), \underbracket (⎵), \underparen (⏝), \unlhd (⊴), \unrhd (⊵), \upand (⅋), \uparrow (↑), \uparrowbarred (⤉), \uparrowoncircle (⦽), \updasharrow (⇢), \updownarrow (↕), \updownarrowbar (↨), \updownarrows (⇅), \updownharpoonleftleft (⥑), \updownharpoonleftright (⥍), \updownharpoonrightleft (⥌), \updownharpoonrightright (⥏), \updownharpoonsleftright (⥮), \upfishtail (⥾), \upharpoonleft (↿), \upharpoonleftbar (⥠), \upharpoonright (↾), \upharpoonrightbar (⥜), \upharpoonsleftright (⥣), \upin (⟒), \upint (⨛), \uplus (⊎), \uprightcurvearrow (⤴), \upuparrows (⇈), \upwhitearrow (⇧), \urarc (◝), \urblacktriangle (◥), \urcorner (⌝), \urcrop (⌎), \urtriangle (◹).
\v (ˇ), \vBar (⫨), \vBarv (⫩), \vDash (⊨), \vDdash (⫢), \varTheta (ϴ), \varVdash (⫦), \varbarwedge (⌅), \varbeta (ϐ), \varclubsuit (♧), \vardiamondsuit (♦), \vardoublebarwedge (⌆), \varepsilon (ε), \varheartsuit (♥), \varhexagon (⬡), \varhexagonblack (⬢), \varhexagonlrbonds (⌬), \varin (∈), \varisinobar (⋶), \varisins (⋳), \varkappa (ϰ), \varlrtriangle (⊿), \varni (∋), \varniobar (⋽), \varnis (⋻), \varnothing (∅), \varointclockwise (∲), \varphi (φ), \varpi (ϖ), \varpropto (∝), \varrho (ϱ), \varrowextender (⏐), \varsigma (ς), \varspadesuit (♤), \varstar (✶), \vartheta (ϑ), \vartriangle (▵), \vartriangleleft (⊲), \vartriangleright (⊳), \varveebar (⩡), \vbraceextender (⎪), \vbrtri (⧐), \vdash (⊢), \vdots (⋮), \vectimes (⨯), \vee (∨), \veebar (⊻), \veedot (⟇), \veedoublebar (⩣), \veeeq (≚), \veemidvert (⩛), \veeodot (⩒), \veeonvee (⩖), \veeonwedge (⩙), \vert (|), \viewdata (⌗), \vlongdash (⟝), \vrectangle (▯), \vrectangleblack (▮), \vysmlblksquare (⬝), \vysmlwhtsquare (⬞), \vzigzag (⦚).
\watchicon (⌚), \wedge (∧), \wedgebar (⩟), \wedgedot (⟑), \wedgedoublebar (⩠), \wedgemidvert (⩚), \wedgeodot (⩑), \wedgeonwedge (⩕), \wedgeq (≙), \whitearrowupfrombar (⇪), \whiteinwhitetriangle (⟁), \whitepointerleft (◅), \whitepointerright (▻), \whitesquaretickleft (⟤), \whitesquaretickright (⟥), \whthorzoval (⬭), \whtvertoval (⬯), \wideangledown (⦦), \wideangleup (⦧), \wp (℘), \wr (≀).
\xbsol (⧹), \xi (ξ), \xsol (⧸), \yen (¥), \zeta (ζ), \zpipe (⨠),
IF ANYBODY WILL CHECK WHETHER ALL NAMES CORRESPOND TO RIGHT TEX SYMBOLS I SHALL APPRECIATE IT GREATLY.
Copyright © 2000,2001,2002 Free Software Foundation, Inc. 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA Everyone is permitted to copy and distribute verbatim copies of this license document, but changing it is not allowed.
The purpose of this License is to make a manual, textbook, or other functional and useful document free in the sense of freedom: to assure everyone the effective freedom to copy and redistribute it, with or without modifying it, either commercially or noncommercially. Secondarily, this License preserves for the author and publisher a way to get credit for their work, while not being considered responsible for modifications made by others.
This License is a kind of “copyleft”, which means that derivative works of the document must themselves be free in the same sense. It complements the GNU General Public License, which is a copyleft license designed for free software.
We have designed this License in order to use it for manuals for free software, because free software needs free documentation: a free program should come with manuals providing the same freedoms that the software does. But this License is not limited to software manuals; it can be used for any textual work, regardless of subject matter or whether it is published as a printed book. We recommend this License principally for works whose purpose is instruction or reference.
This License applies to any manual or other work, in any medium, that contains a notice placed by the copyright holder saying it can be distributed under the terms of this License. Such a notice grants a world-wide, royalty-free license, unlimited in duration, to use that work under the conditions stated herein. The “Document”, below, refers to any such manual or work. Any member of the public is a licensee, and is addressed as “you”. You accept the license if you copy, modify or distribute the work in a way requiring permission under copyright law.
A “Modified Version” of the Document means any work containing the Document or a portion of it, either copied verbatim, or with modifications and/or translated into another language.
A “Secondary Section” is a named appendix or a front-matter section of the Document that deals exclusively with the relationship of the publishers or authors of the Document to the Document’s overall subject (or to related matters) and contains nothing that could fall directly within that overall subject. (Thus, if the Document is in part a textbook of mathematics, a Secondary Section may not explain any mathematics.) The relationship could be a matter of historical connection with the subject or with related matters, or of legal, commercial, philosophical, ethical or political position regarding them.
The “Invariant Sections” are certain Secondary Sections whose titles are designated, as being those of Invariant Sections, in the notice that says that the Document is released under this License. If a section does not fit the above definition of Secondary then it is not allowed to be designated as Invariant. The Document may contain zero Invariant Sections. If the Document does not identify any Invariant Sections then there are none.
The “Cover Texts” are certain short passages of text that are listed, as Front-Cover Texts or Back-Cover Texts, in the notice that says that the Document is released under this License. A Front-Cover Text may be at most 5 words, and a Back-Cover Text may be at most 25 words.
A “Transparent” copy of the Document means a machine-readable copy, represented in a format whose specification is available to the general public, that is suitable for revising the document straightforwardly with generic text editors or (for images composed of pixels) generic paint programs or (for drawings) some widely available drawing editor, and that is suitable for input to text formatters or for automatic translation to a variety of formats suitable for input to text formatters. A copy made in an otherwise Transparent file format whose markup, or absence of markup, has been arranged to thwart or discourage subsequent modification by readers is not Transparent. An image format is not Transparent if used for any substantial amount of text. A copy that is not “Transparent” is called “Opaque”.
Examples of suitable formats for Transparent copies include plain ASCII without markup, Texinfo input format, LaTeX input format, SGML or XML using a publicly available DTD, and standard-conforming simple HTML, PostScript or PDF designed for human modification. Examples of transparent image formats include PNG, XCF and JPG. Opaque formats include proprietary formats that can be read and edited only by proprietary word processors, SGML or XML for which the DTD and/or processing tools are not generally available, and the machine-generated HTML, PostScript or PDF produced by some word processors for output purposes only.
The “Title Page” means, for a printed book, the title page itself, plus such following pages as are needed to hold, legibly, the material this License requires to appear in the title page. For works in formats which do not have any title page as such, “Title Page” means the text near the most prominent appearance of the work’s title, preceding the beginning of the body of the text.
A section “Entitled XYZ” means a named subunit of the Document whose title either is precisely XYZ or contains XYZ in parentheses following text that translates XYZ in another language. (Here XYZ stands for a specific section name mentioned below, such as “Acknowledgements”, “Dedications”, “Endorsements”, or “History”.) To “Preserve the Title” of such a section when you modify the Document means that it remains a section “Entitled XYZ” according to this definition.
The Document may include Warranty Disclaimers next to the notice which states that this License applies to the Document. These Warranty Disclaimers are considered to be included by reference in this License, but only as regards disclaiming warranties: any other implication that these Warranty Disclaimers may have is void and has no effect on the meaning of this License.
You may copy and distribute the Document in any medium, either commercially or noncommercially, provided that this License, the copyright notices, and the license notice saying this License applies to the Document are reproduced in all copies, and that you add no other conditions whatsoever to those of this License. You may not use technical measures to obstruct or control the reading or further copying of the copies you make or distribute. However, you may accept compensation in exchange for copies. If you distribute a large enough number of copies you must also follow the conditions in section 3.
You may also lend copies, under the same conditions stated above, and you may publicly display copies.
If you publish printed copies (or copies in media that commonly have printed covers) of the Document, numbering more than 100, and the Document’s license notice requires Cover Texts, you must enclose the copies in covers that carry, clearly and legibly, all these Cover Texts: Front-Cover Texts on the front cover, and Back-Cover Texts on the back cover. Both covers must also clearly and legibly identify you as the publisher of these copies. The front cover must present the full title with all words of the title equally prominent and visible. You may add other material on the covers in addition. Copying with changes limited to the covers, as long as they preserve the title of the Document and satisfy these conditions, can be treated as verbatim copying in other respects.
If the required texts for either cover are too voluminous to fit legibly, you should put the first ones listed (as many as fit reasonably) on the actual cover, and continue the rest onto adjacent pages.
If you publish or distribute Opaque copies of the Document numbering more than 100, you must either include a machine-readable Transparent copy along with each Opaque copy, or state in or with each Opaque copy a computer-network location from which the general network-using public has access to download using public-standard network protocols a complete Transparent copy of the Document, free of added material. If you use the latter option, you must take reasonably prudent steps, when you begin distribution of Opaque copies in quantity, to ensure that this Transparent copy will remain thus accessible at the stated location until at least one year after the last time you distribute an Opaque copy (directly or through your agents or retailers) of that edition to the public.
It is requested, but not required, that you contact the authors of the Document well before redistributing any large number of copies, to give them a chance to provide you with an updated version of the Document.
You may copy and distribute a Modified Version of the Document under the conditions of sections 2 and 3 above, provided that you release the Modified Version under precisely this License, with the Modified Version filling the role of the Document, thus licensing distribution and modification of the Modified Version to whoever possesses a copy of it. In addition, you must do these things in the Modified Version:
If the Modified Version includes new front-matter sections or appendices that qualify as Secondary Sections and contain no material copied from the Document, you may at your option designate some or all of these sections as invariant. To do this, add their titles to the list of Invariant Sections in the Modified Version’s license notice. These titles must be distinct from any other section titles.
You may add a section Entitled “Endorsements”, provided it contains nothing but endorsements of your Modified Version by various parties—for example, statements of peer review or that the text has been approved by an organization as the authoritative definition of a standard.
You may add a passage of up to five words as a Front-Cover Text, and a passage of up to 25 words as a Back-Cover Text, to the end of the list of Cover Texts in the Modified Version. Only one passage of Front-Cover Text and one of Back-Cover Text may be added by (or through arrangements made by) any one entity. If the Document already includes a cover text for the same cover, previously added by you or by arrangement made by the same entity you are acting on behalf of, you may not add another; but you may replace the old one, on explicit permission from the previous publisher that added the old one.
The author(s) and publisher(s) of the Document do not by this License give permission to use their names for publicity for or to assert or imply endorsement of any Modified Version.
You may combine the Document with other documents released under this License, under the terms defined in section 4 above for modified versions, provided that you include in the combination all of the Invariant Sections of all of the original documents, unmodified, and list them all as Invariant Sections of your combined work in its license notice, and that you preserve all their Warranty Disclaimers.
The combined work need only contain one copy of this License, and multiple identical Invariant Sections may be replaced with a single copy. If there are multiple Invariant Sections with the same name but different contents, make the title of each such section unique by adding at the end of it, in parentheses, the name of the original author or publisher of that section if known, or else a unique number. Make the same adjustment to the section titles in the list of Invariant Sections in the license notice of the combined work.
In the combination, you must combine any sections Entitled “History” in the various original documents, forming one section Entitled “History”; likewise combine any sections Entitled “Acknowledgements”, and any sections Entitled “Dedications”. You must delete all sections Entitled “Endorsements.”
You may make a collection consisting of the Document and other documents released under this License, and replace the individual copies of this License in the various documents with a single copy that is included in the collection, provided that you follow the rules of this License for verbatim copying of each of the documents in all other respects.
You may extract a single document from such a collection, and distribute it individually under this License, provided you insert a copy of this License into the extracted document, and follow this License in all other respects regarding verbatim copying of that document.
A compilation of the Document or its derivatives with other separate and independent documents or works, in or on a volume of a storage or distribution medium, is called an “aggregate” if the copyright resulting from the compilation is not used to limit the legal rights of the compilation’s users beyond what the individual works permit. When the Document is included in an aggregate, this License does not apply to the other works in the aggregate which are not themselves derivative works of the Document.
If the Cover Text requirement of section 3 is applicable to these copies of the Document, then if the Document is less than one half of the entire aggregate, the Document’s Cover Texts may be placed on covers that bracket the Document within the aggregate, or the electronic equivalent of covers if the Document is in electronic form. Otherwise they must appear on printed covers that bracket the whole aggregate.
Translation is considered a kind of modification, so you may distribute translations of the Document under the terms of section 4. Replacing Invariant Sections with translations requires special permission from their copyright holders, but you may include translations of some or all Invariant Sections in addition to the original versions of these Invariant Sections. You may include a translation of this License, and all the license notices in the Document, and any Warranty Disclaimers, provided that you also include the original English version of this License and the original versions of those notices and disclaimers. In case of a disagreement between the translation and the original version of this License or a notice or disclaimer, the original version will prevail.
If a section in the Document is Entitled “Acknowledgements”, “Dedications”, or “History”, the requirement (section 4) to Preserve its Title (section 1) will typically require changing the actual title.
You may not copy, modify, sublicense, or distribute the Document except as expressly provided for under this License. Any other attempt to copy, modify, sublicense or distribute the Document is void, and will automatically terminate your rights under this License. However, parties who have received copies, or rights, from you under this License will not have their licenses terminated so long as such parties remain in full compliance.
The Free Software Foundation may publish new, revised versions of the GNU Free Documentation License from time to time. Such new versions will be similar in spirit to the present version, but may differ in detail to address new problems or concerns. See http://www.gnu.org/copyleft/.
Each version of the License is given a distinguishing version number. If the Document specifies that a particular numbered version of this License “or any later version” applies to it, you have the option of following the terms and conditions either of that specified version or of any later version that has been published (not as a draft) by the Free Software Foundation. If the Document does not specify a version number of this License, you may choose any version ever published (not as a draft) by the Free Software Foundation.
To use this License in a document you have written, include a copy of the License in the document and put the following copyright and license notices just after the title page:
Copyright (C) year your name. Permission is granted to copy, distribute and/or modify this document under the terms of the GNU Free Documentation License, Version 1.2 or any later version published by the Free Software Foundation; with no Invariant Sections, no Front-Cover Texts, and no Back-Cover Texts. A copy of the license is included in the section entitled ``GNU Free Documentation License''.
If you have Invariant Sections, Front-Cover Texts and Back-Cover Texts, replace the “with…Texts.” line with this:
with the Invariant Sections being list their titles, with the Front-Cover Texts being list, and with the Back-Cover Texts being list.
If you have Invariant Sections without Cover Texts, or some other combination of the three, merge those two alternatives to suit the situation.
If your document contains nontrivial examples of program code, we recommend releasing these examples in parallel under your choice of free software license, such as the GNU General Public License, to permit their use in free software.
Jump to: | A B C D E F G H I J L M N O P Q R S T V W X Y Z Н О С Т Ц |
---|
Jump to: | A B C D E F G H I J L M N O P Q R S T V W X Y Z Н О С Т Ц |
---|