/*
plot2dIter.c

plot iteration (2D)
*/

#include "oth.h"
#include "ev.h"

void plot2dIter()
{
	char str1[BUFSIZ], str2[BUFSIZ];
	const int xdiv = 10;
	const double ymax = 2;
	const double ymin = -8;
	const int ydiv = 10;

	// layout
	const double x1 = 0.12 * Width2d;
	const double x2 = 0.90 * Width2d;
	const double y1 = 0.10 * Height2d;
	const double y2 = 0.90 * Height2d;
	const double h = Fontsize2d;

	for (int ifreq = 0; ifreq < NFrequency; ifreq++) {
		if (NIter[ifreq] < 1) continue;
		double e0 = Eaverage[ifreq][NIter[ifreq] - 1];

		// plot
		ev2d_newPage();

		// grid
		ev2dlib_grid(x1, y1, x2, y2, xdiv, ydiv);

		for (int ic = 0; ic < 2; ic++) {
			if (!Piter[ic]) continue;
			ev2d_setColor((ic == 0 ? 255 : 0), 0, (ic == 0 ? 0 : 255));

			for (int n = 0; n < NIter[ifreq] - 1; n++) {
				double px1 = x1 + (x2 - x1) * (n + 0) / (NIter[ifreq] - 1);
				double px2 = x1 + (x2 - x1) * (n + 1) / (NIter[ifreq] - 1);
				double f1 = (ic == 0) ? Residual[ifreq][n + 0] : (1 - MIN(Eaverage[ifreq][n + 0], e0) / MAX(Eaverage[ifreq][n + 0], e0));
				double f2 = (ic == 0) ? Residual[ifreq][n + 1] : (1 - MIN(Eaverage[ifreq][n + 1], e0) / MAX(Eaverage[ifreq][n + 1], e0));
				if ((ic == 1) && (n == NIter[ifreq] - 2)) f2 = f1;
				double py1 = log10(MAX(f1, EPS2));
				double py2 = log10(MAX(f2, EPS2));
				py1 = MAX(ymin, MIN(ymax, py1));
				py2 = MAX(ymin, MIN(ymax, py2));
				py1 = y1 + (y2 - y1) * (py1 - ymin) / (ymax - ymin);
				py2 = y1 + (y2 - y1) * (py2 - ymin) / (ymax - ymin);
				ev2d_drawLine(px1, py1, px2, py2);
			}

			if (ic == 0) ev2d_drawString(x2 - 6.0 * h, y2 + 1.5 * h, h, "Residual");
			if (ic == 1) ev2d_drawString(x2 - 6.0 * h, y2 + 0.3 * h, h, "<E>error");

			ev2d_setColor(0, 0, 0);

			// Y-axis
			sprintf(str1, "%.0e", pow(10, ymin));
			sprintf(str2, "%.0e", pow(10, ymax));
			ev2dlib_Yaxis(y1, y2, x1, h, str1, str2, "");

			// Y=1
			double y = y1 + (y2 - y1) * (0 - ymin) / (ymax - ymin);
			ev2d_drawLine(x1, y, x2, y);
			ev2d_drawString(x1 - 1.5 * h, y - 0.3 * h, h, "1");
		}

		ev2d_setColor(  0,   0,   0);

		// title
		ev2d_drawString(x1 + 1.0 * h, y2 + 0.5 * h, h, Title);

		// frequency
		sprintf(str1, "f=%.3e[Hz]", Frequency[ifreq]);
		ev2d_drawString(x1 + 1.0 * h, y2 + 1.5 * h, h, str1);

		// X-axis
		sprintf(str2, "%d", NIter[ifreq] - 1);
		ev2dlib_Xaxis(x1, x2, y1, h, "0", str2, "iterations");
	}
}
