Blame view

src/ParamOutputImpl/Plot/Time/TimePlot.cc 45.2 KB
fbe3c2bb   Benjamin Renard   First commit
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
/*
 * TimePlot.cc
 *
 *  Created on: 22 nov. 2013
 *      Author: CS
 */

#include "TimePlot.hh"
#include "ParamsNode.hh"
#include "AxesNode.hh"
#include "PlotOutput.hh"
#include "TimeUtil.hh"
#include "Parameter.hh"
#include "ParamInfo.hh"
#include "ParamTable.hh"
#include "ParamMgr.hh"
#include "ShadesTools.hh"
#include "AxisLegendManager.hh"
#include <fstream>
2acc7d49   Hacene SI HADJ MOHAND   progress
20
21
#include <limits>
#include <cstddef>
fbe3c2bb   Benjamin Renard   First commit
22
23
24
25
26
27

#include "DefaultTimeAxisDecorator.hh"
#include "TickMarkDecorator.hh"
#include "PlotLogger.hh"
#include "ParamMgr.hh"
#include "TimeUtil.hh"
f6eaec4e   Benjamin Renard   Optimize plot ele...
28
#include "PlPlotUtil.hh"
faf4d845   Benjamin Renard   Add common functi...
29
#include "Range.hh"
fbe3c2bb   Benjamin Renard   First commit
30
31
32
33
34
35
36
37
38
39
40
41

#include <boost/format.hpp>

using namespace AMDA::Parameters;
using namespace AMDA::Info;

namespace plot {


QSASConfig* TimePlot::qsasconfig = NULL;

TimePlot::TimePlot(AMDA::Parameters::ParameterManager& manager,
8c860e4f   Benjamin Renard   Rework for tickpl...
42
43
		boost::shared_ptr<Panel> panel, TimeAxisDecorator* timeAxisDecorator, bool isStandalone) :
		PanelPlotOutput(manager, panel, isStandalone), _startDateDrawn(false) {
fbe3c2bb   Benjamin Renard   First commit
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
	setTimeAxisDecorator(std::shared_ptr<TimeAxisDecorator>(timeAxisDecorator));
}

TimePlot::~TimePlot() {
	if (qsasconfig != NULL) {
		free(qsasconfig);
		qsasconfig = nullptr;
	}
}


TimeAxis* TimePlot::getTimeAxis(){
	std::string lAxisId = getXAxisId();
	boost::shared_ptr<Axis> xAxis = _panel->getAxis(lAxisId);
	if (xAxis.get() == nullptr) {
		std::stringstream lError;
		lError << "TimePlot::apply" << ": time axis with id '" << lAxisId << "' not found.";
		BOOST_THROW_EXCEPTION(PanelPlotOutputException() << AMDA::ex_msg(lError.str()));
	}
	return dynamic_cast<TimeAxis*>(xAxis.get());
}

void TimePlot::preparePlotArea(double startTime, double stopTime, int intervalIndex) {
	// dump properties for test
	const char* lBuildType=getenv("BUILD_TYPE");
	if(lBuildType && std::string(lBuildType) == "Debug") {
		std::ofstream out("timePlot.txt");
		dump(out);
		out.close();
	}

	// Configure Series to draw on axis by checking which color to use and
	// number of series to draw on a same axis.
	configureSeriesAxis();

	configureAxisLegend();

	configureSpectroAxis();

	configureParamsLegend(startTime,stopTime,intervalIndex);

	// configure X axis
	getTimeAxisDecorator()->configure(this, getTimeAxis(), startTime, stopTime, _pParameterValues);
08ec1dde   Benjamin Renard   Add propertie _us...
87
	getTimeAxis()->_used = true;
fbe3c2bb   Benjamin Renard   First commit
88
89
90
	_pls->timefmt(getTimeAxisDecorator()->getPlFormat().c_str());

	PanelPlotOutput::preparePlotArea(startTime,stopTime,intervalIndex);
20fef3b6   Benjamin Renard   Fix reset functio...
91
92
        
        
fbe3c2bb   Benjamin Renard   First commit
93
94
}

d57f00dc   Benjamin Renard   Draw NO DATA
95
bool TimePlot::draw(double startTime, double stopTime, int intervalIndex,
fbe3c2bb   Benjamin Renard   First commit
96
97
		bool isFirstInterval, bool isLastInterval) {

d57f00dc   Benjamin Renard   Draw NO DATA
98
	bool dataPloted = PanelPlotOutput::draw(startTime,stopTime,intervalIndex,isFirstInterval,isLastInterval);
fbe3c2bb   Benjamin Renard   First commit
99
100

	// Draw start date
b96aa975   Benjamin Renard   Draw border aroun...
101
	if (!_startDateDrawn /*&& getTimeAxis()->_used*/)
fbe3c2bb   Benjamin Renard   First commit
102
103
		drawStartDate (getTimeAxis(), startTime,stopTime);
	_startDateDrawn = true;
d57f00dc   Benjamin Renard   Draw NO DATA
104
	return dataPloted;
fbe3c2bb   Benjamin Renard   First commit
105
106
107
}


8c860e4f   Benjamin Renard   Rework for tickpl...
108
109
void TimePlot::calculatePlotArea(const Bounds& panelBounds_, Bounds& bounds_) {
	PanelPlotOutput::calculatePlotArea(panelBounds_, bounds_);
fbe3c2bb   Benjamin Renard   First commit
110
	// decorator is responsible of reserving extra space for what it manage (labels for instance).
8c860e4f   Benjamin Renard   Rework for tickpl...
111
	getTimeAxisDecorator()->updatePlotArea(this, getTimeAxis(), panelBounds_, bounds_);
fbe3c2bb   Benjamin Renard   First commit
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
}


void TimePlot::configureSeriesAxis() {
	// map<YAxisId, userRangeDefined>
	std::map<std::string, Range> lAxisRange;
	Range lColorAxeRange;
	SeriesProperties lSeriesProperties;

	boost::shared_ptr<ColorAxis> lZAxis = _panel->getColorAxis();

	// Parse each parameter to define on which axis to draw series.
	for (auto param: _parameterAxesList) {
		// Get number of series to draw
		// For each index of parameter identify to which axis series must be drawn.
2fc1f2f8   Benjamin Renard   Full rework for s...
127
		for(auto lSeriesProperties: param.getYSeriePropertiesList()) {
fbe3c2bb   Benjamin Renard   First commit
128
129
130
131
132
133
134
135
136
137
			if(!lSeriesProperties.hasYAxis()){
				continue;
			}
			boost::shared_ptr<Axis> lYAxis = _panel->getAxis(lSeriesProperties.getYAxisId());
			if (lYAxis.get() == nullptr) {
				std::stringstream lError;
				lError << "TimePlot::configureSeriesAxis" << ": Y axis with id '" << lSeriesProperties.getYAxisId() << "' not found.";
				BOOST_THROW_EXCEPTION(PanelPlotOutputException() << AMDA::ex_msg(lError.str()));
			}

08ec1dde   Benjamin Renard   Add propertie _us...
138
			lYAxis->_used = true;
cf664d1b   Hacene SI HADJ MOHAND   resolving 9201
139
140
			Range lYAxisRequestRange = lYAxis->Axis::getRequestedRange();
                                                            Range lRange = lYAxis->Axis::getRange();
fbe3c2bb   Benjamin Renard   First commit
141
			// If range status for this axis is set by the user do not update range "automatically".
cf664d1b   Hacene SI HADJ MOHAND   resolving 9201
142
			if (isnan(lYAxisRequestRange.getMin()) && isnan(lYAxisRequestRange.getMax())) {
fbe3c2bb   Benjamin Renard   First commit
143
				Range lEstimatedRange(lAxisRange[lYAxis->_id]);
2fc1f2f8   Benjamin Renard   Full rework for s...
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
				for (auto index : lSeriesProperties.getIndexList(_pParameterValues)) {
					Range lParamIndexRange(
							(*_pParameterValues)[lSeriesProperties.getParamId()].getMin(index),
							(*_pParameterValues)[lSeriesProperties.getParamId()].getMax(index));

					ErrorBarProperties & errBarProp = lSeriesProperties.getErrorBarProperties();

					// Update lParamIndexRange depending on the use of ErrorBars on the plot
					if (errBarProp.getErrorMinMax() != nullptr) {
						Range lParamMinRange(
								(*_pParameterValues)[errBarProp.getErrorMinMax()->getUsedParamMin()].getMin(-1),
								(*_pParameterValues)[errBarProp.getErrorMinMax()->getUsedParamMin()].getMax(-1));
						Range lParamMaxRange(
								(*_pParameterValues)[errBarProp.getErrorMinMax()->getUsedParamMax()].getMin(-1),
								(*_pParameterValues)[errBarProp.getErrorMinMax()->getUsedParamMax()].getMax(-1));

						if (lParamMinRange.getMin() < lParamIndexRange.getMin())
							lParamIndexRange.setMin(lParamMinRange.getMin());
						if (lParamMinRange.getMax() > lParamIndexRange.getMax())
							lParamIndexRange.setMax(lParamMinRange.getMax());

						if (lParamMaxRange.getMin() < lParamIndexRange.getMin())
							lParamIndexRange.setMin(lParamMaxRange.getMin());
						if (lParamMaxRange.getMax() > lParamIndexRange.getMax())
							lParamIndexRange.setMax(lParamMaxRange.getMax());
					}
fbe3c2bb   Benjamin Renard   First commit
170

2fc1f2f8   Benjamin Renard   Full rework for s...
171
172
173
174
175
176
177
					if (isnan(lEstimatedRange.getMin()) && isnan(lEstimatedRange.getMax())) {
						lEstimatedRange.setMin(lParamIndexRange.getMin());
						lEstimatedRange.setMax(lParamIndexRange.getMax());
					} else {
						lEstimatedRange.setMin(std::min(lEstimatedRange.getMin(), lParamIndexRange.getMin()));
						lEstimatedRange.setMax(std::max(lEstimatedRange.getMax(), lParamIndexRange.getMax()));
					}
641ba7e4   Hacene SI HADJ MOHAND   ok for time plot
178
179
                                                                                                    if(lParamIndexRange.getMin()==lParamIndexRange.getMax())
                                                                                                    lEstimatedRange.setMargin(0.05);
fbe3c2bb   Benjamin Renard   First commit
180
				}
e062d6ef   Benjamin Renard   Fix axes range wh...
181

fbe3c2bb   Benjamin Renard   First commit
182
				lEstimatedRange._extend = lRange._extend;
641ba7e4   Hacene SI HADJ MOHAND   ok for time plot
183
184

                                
fbe3c2bb   Benjamin Renard   First commit
185
				lAxisRange[lYAxis->_id] = lEstimatedRange;
fbe3c2bb   Benjamin Renard   First commit
186
187
188
189
190
191
192
			}

			// Set ZAxis range if a color param is defined for this serie
			if (lZAxis != nullptr)
			{
				if (!lSeriesProperties.getColorParamId().empty())
				{
08ec1dde   Benjamin Renard   Add propertie _us...
193
					lZAxis->_used = true;
fbe3c2bb   Benjamin Renard   First commit
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
					Range lRange(lZAxis->getRange());
					ParameterAxes* colorSerieParameterAxes = getParameterAxesByColorSerieId(lSeriesProperties.getColorSerieId());
					if (colorSerieParameterAxes == NULL)
						continue;
					ColorSeriesProperties& colorSerieProp = colorSerieParameterAxes->getColorSeriePropertiesById(lSeriesProperties.getColorSerieId());
					// If range status for this axis is set by the user do not update range "automatically".
					if (isnan(lRange.getMin()) && isnan(lRange.getMax())) {
						Range lEstimatedRange(lColorAxeRange);
						Range lParamIndexRange(
							(*_pParameterValues)[lSeriesProperties.getColorParamId()].getMin(
								colorSerieProp.getIndex()),
							(*_pParameterValues)[lSeriesProperties.getColorParamId()].getMax(
								colorSerieProp.getIndex()));

						if (isnan(lEstimatedRange.getMin()) && isnan(lEstimatedRange.getMax())) {
							lEstimatedRange.setMin(lParamIndexRange.getMin());
							lEstimatedRange.setMax(lParamIndexRange.getMax());
						} else {
							lEstimatedRange.setMin(std::min(lEstimatedRange.getMin(), lParamIndexRange.getMin()));
							lEstimatedRange.setMax(std::max(lEstimatedRange.getMax(), lParamIndexRange.getMax()));
						}
641ba7e4   Hacene SI HADJ MOHAND   ok for time plot
215
216
                                                                                                                        if(lParamIndexRange.getMin()==lParamIndexRange.getMax())
                                                                                                                        lEstimatedRange.setMargin(0.05);
fbe3c2bb   Benjamin Renard   First commit
217
218
219
220
221
222
223
224
225
226
						lEstimatedRange._extend = lRange._extend;
						lColorAxeRange = lEstimatedRange;
					}
				}
			}
		}
	}

	// Update range of axis. Done after because, axis range may be processed in several pass (one for each series)
	for (auto lAxis: lAxisRange) {
5c050d50   Benjamin Renard   Fix another bugs ...
227
228
229
230
		boost::shared_ptr<Axis> lYAxis = _panel->getAxis(lAxis.first);
		Range lRange(lAxis.second);
		fixRange(lRange, lYAxis-> _scale == Axis::Scale::LOGARITHMIC);
		lYAxis->setRange(lRange);
fbe3c2bb   Benjamin Renard   First commit
231
232
	}

5c050d50   Benjamin Renard   Fix another bugs ...
233
234
	if (lZAxis != nullptr && lColorAxeRange.isSet()) {
		fixRange(lColorAxeRange, lZAxis->_scale == Axis::Scale::LOGARITHMIC);
fbe3c2bb   Benjamin Renard   First commit
235
		lZAxis->setRange(lColorAxeRange);
5c050d50   Benjamin Renard   Fix another bugs ...
236
	}
fbe3c2bb   Benjamin Renard   First commit
237
238
239
240
}

void TimePlot::configureAxisLegend() {
	// Y axis
c2fa3b5d   Benjamin Renard   Rework of legend ...
241
	AxisLegendManager::configureYAxisLegendForSpectro(this);
fbe3c2bb   Benjamin Renard   First commit
242
243
244
	AxisLegendManager::configureYAxisLegendForSeries(this);

	// Z axis
c2fa3b5d   Benjamin Renard   Rework of legend ...
245
	AxisLegendManager::configureColorAxisLegendForSpectro(this);
fbe3c2bb   Benjamin Renard   First commit
246
247
248
249
250
251
252
253
	AxisLegendManager::configureColorAxisLegendForSeries(this);
}

void TimePlot::configureSpectroAxis() {
		// Parse each parameter to define on which axis to draw spectro
	for (auto param: _parameterAxesList) {
		std::shared_ptr<SpectroProperties> spectroPropertiesPtr = param.getSpectroProperties();
		if (spectroPropertiesPtr == nullptr)
23e6e720   Hacene SI HADJ MOHAND   correcting 9234
254
			continue; //no spectro defined
fbe3c2bb   Benjamin Renard   First commit
255
256

		if(!spectroPropertiesPtr->hasYAxis())
23e6e720   Hacene SI HADJ MOHAND   correcting 9234
257
			continue;
fbe3c2bb   Benjamin Renard   First commit
258
259
260
261
262
263
264
265
266

		LOG4CXX_DEBUG(gLogger, "Spectro Y axis is " << spectroPropertiesPtr->getYAxisId());
		boost::shared_ptr<Axis> lYAxis = _panel->getAxis(spectroPropertiesPtr->getYAxisId());
		if (lYAxis.get() == nullptr) {
			std::stringstream lError;
			lError << "TimePlot::configureSpectroAxis" << ": Y axis with id '" << spectroPropertiesPtr->getYAxisId() << "' not found.";
			BOOST_THROW_EXCEPTION(PanelPlotOutputException() << AMDA::ex_msg(lError.str()));
		}

08ec1dde   Benjamin Renard   Add propertie _us...
267
268
		lYAxis->_used = true;

fbe3c2bb   Benjamin Renard   First commit
269
270
271
272
273
274
275
276
		//set Z axis range
		boost::shared_ptr<Axis> lZAxis = _panel->getAxis(spectroPropertiesPtr->getZAxisId());
		if (lZAxis.get() == nullptr) {
			std::stringstream lError;
			lError << "TimePlot::configureSpectroAxis" << ": Z axis with id '" << spectroPropertiesPtr->getZAxisId() << "' not found.";
			BOOST_THROW_EXCEPTION(PanelPlotOutputException() << AMDA::ex_msg(lError.str()));
		}

08ec1dde   Benjamin Renard   Add propertie _us...
277
278
		lZAxis->_used = true;

fbe3c2bb   Benjamin Renard   First commit
279
280
281
282
283
284
285
		ParameterSPtr p = _parameterManager.getParameter(param._originalParamId);
		int parameterDimension;
		if (spectroPropertiesPtr->getRelatedDim() == 0)
			parameterDimension = (*_pParameterValues)[spectroPropertiesPtr->getParamId()].getDim1Size();
		else
			parameterDimension = (*_pParameterValues)[spectroPropertiesPtr->getParamId()].getDim2Size();

966af096   Benjamin Renard   Fix 'sum in range...
286

fbe3c2bb   Benjamin Renard   First commit
287
		//set Y axis range
cf664d1b   Hacene SI HADJ MOHAND   resolving 9201
288
289
		Range lYAxisRequestRange = lYAxis->Axis::getRequestedRange();
                                        Range lYAxisRange = lYAxis->Axis::getRange();
fbe3c2bb   Benjamin Renard   First commit
290
		AMDA::Info::ParamInfoSPtr paramInfo = AMDA::Info::ParamMgr::getInstance()->getParamInfoFromId(p->getInfoId());
cf664d1b   Hacene SI HADJ MOHAND   resolving 9201
291
		if (isnan(lYAxisRequestRange.getMin()) && isnan(lYAxisRequestRange.getMax()))
fbe3c2bb   Benjamin Renard   First commit
292
293
294
295
296
297
298
299
300
301
302
303
304
305
		{
			boost::shared_ptr<AMDA::Info::ParamTable> tableSPtr;
			if (paramInfo != nullptr)
				tableSPtr = paramInfo->getTable(spectroPropertiesPtr->getRelatedDim());

			if (tableSPtr == nullptr)
			{
				LOG4CXX_DEBUG(gLogger, "No table defined => use index");
				lYAxisRange.setMin(std::min(0.,lYAxisRange.getMin()));
				lYAxisRange.setMax(std::max((double)parameterDimension,lYAxisRange.getMax()));
			}
			else
			{
				AMDA::Info::t_TableBound crtBound;
e7ea756d   Benjamin Renard   Implements tables...
306
				if (!tableSPtr->isVariable(&_parameterManager))
fbe3c2bb   Benjamin Renard   First commit
307
				{
f2db3c16   Benjamin Renard   Support variable ...
308
309
310
					for (int i = 0; i < parameterDimension; ++i)
					{
						crtBound = tableSPtr->getBound(&_parameterManager, i);
ed9a1eaf   Benjamin Renard   Add Maven STATIC ...
311
312
313
314
315
316
317
318
319
320
						if (!std::isnan(crtBound.min))
						{
							if (!((lYAxis->_scale == Axis::Scale::LOGARITHMIC) && (crtBound.min <= 0)))
								lYAxisRange.setMin(std::min(crtBound.min,lYAxisRange.getMin()));
						}
						if (!std::isnan(crtBound.max))
						{
							if (!((lYAxis->_scale == Axis::Scale::LOGARITHMIC) && (crtBound.max <= 0)))
								lYAxisRange.setMax(std::max(crtBound.max,lYAxisRange.getMax()));
						}
f2db3c16   Benjamin Renard   Support variable ...
321
322
323
324
325
326
327
328
329
330
331
332
333
334
					}
				}
				else
				{
					//Variable table => we need to loop under all records to find axis min & max values
					for (int i = 0; i < (*_pParameterValues)[spectroPropertiesPtr->getParamId()].getSize(); ++i)
					{
						std::map<std::string, std::vector<double>> paramsTableData;
						for (std::map<std::string, std::string>::iterator it = spectroPropertiesPtr->getTableParams().begin(); it != spectroPropertiesPtr->getTableParams().end(); ++it)
						{
							ParameterData& data = (*_pParameterValues)[it->second];
							std::vector<double> paramTableValues;
							for (int j = 0; j < data.getDim1Size(); ++j)
							{
91c8f6bb   Benjamin Renard   Fix a buffer over...
335
336
337
338
								if (i < data.getSize()) {
									double* values = data.getValues(AMDA::Common::ParameterIndexComponent(j), i);
									paramTableValues.push_back((*values));
								}
f2db3c16   Benjamin Renard   Support variable ...
339
340
341
342
343
344
							}
							paramsTableData[it->first] = paramTableValues;
						}
						for (int j = 0; j < parameterDimension; ++j)
						{
							crtBound = tableSPtr->getBound(&_parameterManager, j, &paramsTableData);
ed9a1eaf   Benjamin Renard   Add Maven STATIC ...
345
346
347
348
349
350
351
352
353
354
							if (!std::isnan(crtBound.min))
							{
								if (!((lYAxis->_scale == Axis::Scale::LOGARITHMIC) && (crtBound.min <= 0)))
									lYAxisRange.setMin(std::min(crtBound.min,lYAxisRange.getMin()));
							}
							if (!std::isnan(crtBound.max))
							{
								if (!((lYAxis->_scale == Axis::Scale::LOGARITHMIC) && (crtBound.max <= 0)))
									lYAxisRange.setMax(std::max(crtBound.max,lYAxisRange.getMax()));
							}
f2db3c16   Benjamin Renard   Support variable ...
355
356
						}
					}
fbe3c2bb   Benjamin Renard   First commit
357
				}
fbe3c2bb   Benjamin Renard   First commit
358
359
360
361
362
			}
		}

		//do not extend the axis
		lYAxisRange._extend = false;
faf4d845   Benjamin Renard   Add common functi...
363
364
365
	
		fixRange(lYAxisRange, lYAxis->_scale == Axis::Scale::LOGARITHMIC);
	
fbe3c2bb   Benjamin Renard   First commit
366
367
368
369
370
371
372
		lYAxis->setRange(lYAxisRange);

		LOG4CXX_DEBUG(gLogger, "Y axis range : min = " << lYAxisRange.getMin() << ", max = " << lYAxisRange.getMax());

		Range lParamRange = lZAxis->Axis::getRange();
		if (isnan(lParamRange.getMin()) && isnan(lParamRange.getMax()))
		{
a436273c   Hacene SI HADJ MOHAND   evol ok
373
374
375
376
377
378
379
                                                            std::string normalization = spectroPropertiesPtr->getNormalization();
                                                            if(normalization == "log" || normalization == "linear" ){
                                                                  lParamRange.setMin(0);
                                                                  lParamRange.setMax(1);
                                                            }else{
                                                            //auto range
                                                            for(auto index : spectroPropertiesPtr->getIndexes()) {
fbe3c2bb   Benjamin Renard   First commit
380
				//compute global range for all indexes
c6a67968   Benjamin Renard   Fix some violatio...
381
				double minVal, maxVal;
fbe3c2bb   Benjamin Renard   First commit
382
383
384
385
386
				if (lZAxis->_scale == Axis::Scale::LOGARITHMIC)
					minVal = (*_pParameterValues)[spectroPropertiesPtr->getParamId()].getMinStrictPos(index);
				else
					minVal = (*_pParameterValues)[spectroPropertiesPtr->getParamId()].getMin(index);
				maxVal = (*_pParameterValues)[spectroPropertiesPtr->getParamId()].getMax(index);
eaee4062   Elena.Budnik   bug z-axis log
387
				if (!isnan(minVal))
f2db3c16   Benjamin Renard   Support variable ...
388
					lParamRange.setMin(std::min(minVal,lParamRange.getMin()));
d9117537   Benjamin Renard   Fix bug with Zaxi...
389
390
				//else
				//	lParamRange.setMin(0);
f2db3c16   Benjamin Renard   Support variable ...
391
392
				if (!isnan(maxVal))
					lParamRange.setMax(std::max(maxVal,lParamRange.getMax()));
d9117537   Benjamin Renard   Fix bug with Zaxi...
393
394
				//else
				//	lParamRange.setMax(10);
fbe3c2bb   Benjamin Renard   First commit
395
			}
d9117537   Benjamin Renard   Fix bug with Zaxi...
396
397
398
399
			if (isnan(lParamRange.getMin()))
				lParamRange.setMin(0);
			if (isnan(lParamRange.getMax()))
				lParamRange.setMax(10);
a436273c   Hacene SI HADJ MOHAND   evol ok
400
                                                            }
fbe3c2bb   Benjamin Renard   First commit
401
402
403
404
		}
		else
			lParamRange._extend = false;

fbe3c2bb   Benjamin Renard   First commit
405
		//set z axis range
faf4d845   Benjamin Renard   Add common functi...
406
		fixRange(lParamRange, lZAxis->_scale == Axis::Scale::LOGARITHMIC);
fbe3c2bb   Benjamin Renard   First commit
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
		LOG4CXX_DEBUG(gLogger, "ZAxis range : ZMin = " << lParamRange.getMin() << ", ZMax = " << lParamRange.getMax());
		lZAxis->setRange(lParamRange);
	}
}

/**
 * @brief Identify if other side of the plot area need to be drawn or not.
 * @note A plot area side need to be drawn when there is no axis associated to it.
 */
std::string TimePlot::drawOppositeSide(boost::shared_ptr<Axis> pAxis){
	if( pAxis.get() == getTimeAxis() && getTimeAxis()->isOnlyTickmarks()){
		return "";
	}
	else{
		return PanelPlotOutput::drawOppositeSide(pAxis);
	}

}

void TimePlot::drawXAxis(boost::shared_ptr<Axis> pXAxis, PlWindow& pPlWindow, Bounds& pPlotAreaSize, TickConf& pTickConf){
	LOG4CXX_DEBUG(gLogger, "Drawing X axis ");
	// draw main axis...
	PanelPlotOutput::drawXAxis(pXAxis,pPlWindow, pPlotAreaSize, pTickConf);
	// delegate to decorator any extra drawing stuff it needs to perform...
	getTimeAxisDecorator()->draw(this,getTimeAxis(), _pls);

}

// Convert an X axis string value to a double X value assuming it's a DD_Time value
double TimePlot::convertXAxisValue(const std::string &value) {
	return DD_Time2Double (value.c_str());
}

e7b3586a   Benjamin Renard   Fix fill between ...
440
ConstantLine * TimePlot::getConstantLineFromId (int serieId, int constantId, boost::shared_ptr<Axis>& yAxis) {
fbe3c2bb   Benjamin Renard   First commit
441
	for (auto parameter : _parameterAxesList) {
2fc1f2f8   Benjamin Renard   Full rework for s...
442
		for (auto serieProperties : parameter.getYSeriePropertiesList()) {
fbe3c2bb   Benjamin Renard   First commit
443
			if ((serieProperties.getId() == serieId) &&(serieProperties.hasYAxis() == true)) {
e7b3586a   Benjamin Renard   Fix fill between ...
444
				yAxis = _panel->getAxis(serieProperties.getYAxisId());
fbe3c2bb   Benjamin Renard   First commit
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
				for (auto constantLine : yAxis->_constantLines) {
					if (constantLine->getId() == constantId) {
						return constantLine.get();
					}
				}
			}
		}
	}

	// ConstantId not found, we throw an exception
	std::stringstream lError;
	lError << "TimePlot::getConstantLineFromId : Unable to find constantId='" << constantId << "' for serieId='" << serieId << "'";
	BOOST_THROW_EXCEPTION(PanelPlotOutputException() << AMDA::ex_msg(lError.str()));
	return NULL;
}

bool TimePlot::getSeriePropertiesById(int serieId, SeriesProperties &rSerieProperties)
{
	for (auto parameter : _parameterAxesList) {
2fc1f2f8   Benjamin Renard   Full rework for s...
464
465
466
		for (auto serieProperties : parameter.getYSeriePropertiesList()) {
			if (serieProperties.getId() == serieId) {
				rSerieProperties = serieProperties;
fbe3c2bb   Benjamin Renard   First commit
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
				return true;
			}
		}
	}

	return false;
}



void TimePlot::mergeAndSortTime (	double *values1Time, int values1Nb,
									double *values2Time, int values2Nb,
									std::vector<double> &valuesTime) {

	// Build 2 vectors
	std::vector<double> v1(values1Time, values1Time + values1Nb);
	std::vector<double> v2(values2Time, values2Time + values2Nb);

	// Populate resulting vector
	valuesTime.insert( valuesTime.end(), v1.begin(), v1.end() );
	valuesTime.insert( valuesTime.end(), v2.begin(), v2.end() );

	// Sort and remove duplicates for the resulting vector
	sort (valuesTime.begin(), valuesTime.end());
	valuesTime.erase( unique( valuesTime.begin(), valuesTime.end() ), valuesTime.end() );
}

double TimePlot::getInterpolatedValue (double *values, double *valuesTime, int valuesNb, double atTime) {

	// get index of first time after given time_
	if(isnan(atTime)){
		return nan("");
	}

	double *pTime = valuesTime;

	for(int t=0; t<valuesNb; t++) {
		// No interpolation required
		if (*pTime == atTime){
			return values [t];
		}
		// Interpolation required
		if (*pTime >= atTime){
			if (t == 0) {
				return nan("");
			}
			else {
				double v1 = values [t-1];
				double v2 = values [t];
				double d1 = valuesTime [t-1];
				double d2 = valuesTime [t];
				// Return a linear interpolation of the value for the index
				return (v1 + (v2-v1) * (atTime-d1)/(d2-d1));
			}
		}
		pTime++;
	}
	return nan("");
}

bool TimePlot::intersect (	double xi, double y1i, double y2i,
							double xj, double y1j, double y2j,
							double *xInter) {

	// Simply checks if segment are above or below the other
	if ( ((y1i >= y2i) && (y1j >= y2j)) ||( (y1i <= y2i) && (y1j <= y2j)) ) {
		return false;
	}

	// Computes intersection point :
    // Compute a and b (y = a * x + b) for each segment
    double a1 = (y1j - y1i) / (xj - xi);
    double b1 = y1i - a1 * xi ;

    double a2 = (y2j - y2i) / (xj - xi);
    double b2 = y2i - a2 * xi ;

    // Compute intersection point (a1*x+b1 = a2*x+b2)
    *xInter = (b2-b1) / (a1-a2);

    return true;
}

void TimePlot::addIntersectionTime (double *values1, double *values1Time, int values1Nb,
									double *values2, double *values2Time, int values2Nb,
									std::vector<double> &valuesTime) {

	if (valuesTime.empty() == true)
		return;

	// For each time segment compute intersection if it exists
	std::vector<double> intersectionTime;

	double xi = valuesTime [0];
	double y1i = getInterpolatedValue (values1, values1Time, values1Nb, xi);
	double y2i = getInterpolatedValue (values2, values2Time, values2Nb, xi);

fbe3c2bb   Benjamin Renard   First commit
564
	for (size_t t=1; t<valuesTime.size(); t++) {
c6a67968   Benjamin Renard   Fix some violatio...
565
566
567
		double xj = valuesTime [t];
		double y1j = getInterpolatedValue (values1, values1Time, values1Nb, xj);
		double y2j = getInterpolatedValue (values2, values2Time, values2Nb, xj);
fbe3c2bb   Benjamin Renard   First commit
568

c6a67968   Benjamin Renard   Fix some violatio...
569
		double xInter;
fbe3c2bb   Benjamin Renard   First commit
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
		if (intersect (xi, y1i, y2i, xj, y1j, y2j, &xInter) == true) {
			intersectionTime.push_back(xInter);
		}

		// Next vector element
		xi = xj;
		y1i = y1j;
		y2i = y2j;
	}

	// Add intersections informations to the resulting values
	valuesTime.insert( valuesTime.end(), intersectionTime.begin(), intersectionTime.end() );

	// Sort and remove duplicates for the resulting vector
	sort (valuesTime.begin(), valuesTime.end());
	valuesTime.erase( unique( valuesTime.begin(), valuesTime.end() ), valuesTime.end() );
}

void TimePlot::drawFillArea (	double *values1, double *values1Time, int values1Nb,
								double *values2, double *values2Time, int values2Nb,
								std::vector<double> &valuesTime,
								bool colorGreaterSpecified, Color& colorGreater,
								bool colorLessSpecified, Color& colorLess,
								SeriesProperties &rSeriesProperties) {
	// Get X and Y axis.
	boost::shared_ptr<Axis> lXAxis(_panel->getAxis(rSeriesProperties.getXAxisId()));
	boost::shared_ptr<Axis> lYAxis(_panel->getAxis(rSeriesProperties.getYAxisId()));

	Range lXRange = getXAxisRange (rSeriesProperties, lXAxis);
	Range lYRange = getYAxisRange (rSeriesProperties, lYAxis);

	_pls->wind(lXRange.getMin(), lXRange.getMax(), lYRange.getMin(), lYRange.getMax());

	PLFLT x[4], y[4], deltai, deltaj;
	Color curColor;
	Color lInitialColor = changeColor(_pls, colorGreater, _panel->_page->_mode);

	for ( size_t i = 0; i < (valuesTime.size() - 1); i++ )
	{
		x[0] = valuesTime[i];
		x[1] = x[0];
		x[2] = valuesTime[i+1];
		x[3] = x[2];

		y[0] = getInterpolatedValue (values1, values1Time, values1Nb, valuesTime[i]);
		y[1] = getInterpolatedValue (values2, values2Time, values2Nb, valuesTime[i]);
		y[2] = getInterpolatedValue (values2, values2Time, values2Nb, valuesTime[i+1]);
		y[3] = getInterpolatedValue (values1, values1Time, values1Nb, valuesTime[i+1]);

		deltai = y[1] - y[0];
		deltaj = y[2] - y[3];

		// Set fill color depending on segment position
		if ( ((deltai > 0) && (fabs(deltai) > fabs(deltaj))) ||
			 ((deltaj > 0) && (fabs(deltaj) > fabs(deltai))) ) {
			// s1 above s2
			if (colorGreaterSpecified == true) {
				curColor = colorGreater;
			} else {
				continue;
			}
		}
		else if ( 	((deltai < 0) && (fabs(deltai) > fabs(deltaj))) ||
					((deltaj < 0) && (fabs(deltaj) > fabs(deltai))) ) {
			// s1 under s2
			if (colorLessSpecified == true) {
				curColor = colorLess;
			} else {
				continue;
			}
		} else {
			// Colinear segments, no fill required
			continue;
		}

		// Fill polygon using the given color
		changeColor(_pls, curColor, _panel->_page->_mode);
		_pls->fill(4, x, y);
    }

	// Restore color.
	restoreColor(_pls, lInitialColor, _panel->_page->_mode);
}

void TimePlot::drawFills(double startDate, double stopDate) {
	PanelPlotOutput::drawFills(startDate, stopDate);
	LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills");

	SeriesProperties rSeriesProperties;

	double *values1 	= NULL;
	double *values1Time = NULL;
	int 	values1Nb	= 0;

	double *values2 	= NULL;
	double *values2Time = NULL;
	int 	values2Nb 	= 0;

	std::vector<double> valuesTime;

	// Drawing Fill Area located between Serie and Constant (horizontal) line
	for (auto fillSerieConstant : _panel->_fillSerieConstants) {

		// Retrieve serie parameter values for serieId
		if (!getSeriePropertiesById(fillSerieConstant->getSerieId(), rSeriesProperties))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills - Cannot find serie id " << fillSerieConstant->getSerieId());
			continue;
		}

		//get computed values for this serie and interval
		if (!getComputedValuesFromSerieAndInterval(startDate, stopDate, rSeriesProperties,
				rSeriesProperties.getIndex(), &values1, &values1Time, values1Nb))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills - Cannot get computed values for serie id " << fillSerieConstant->getSerieId());
			continue;
		}

		// Retrieve constantLine informations for these fill
e7b3586a   Benjamin Renard   Fix fill between ...
689
690
691
692
693
		boost::shared_ptr<Axis> yAxis;
		ConstantLine *constantLine = getConstantLineFromId (	fillSerieConstant->getSerieId(),													fillSerieConstant->getConstantId(), yAxis);

		// Retrieve axis attachment

fbe3c2bb   Benjamin Renard   First commit
694
695
696
697
698
699
700
701

		// Build values2 values2Time array with 2 values : yConst & (first time, last time) for serie
		values2 = new double [2];
		values2Time = new double [2];

		values2 [0] = convertYAxisValue (constantLine->getValue());
		values2 [1] = convertYAxisValue (constantLine->getValue());

e7b3586a   Benjamin Renard   Fix fill between ...
702
703
704
705
706
		if (yAxis->_scale == Axis::Scale::LOGARITHMIC) {
                        values2[0] = log10 (values2[0]);
                        values2[1] = log10 (values2[1]);
                }

fbe3c2bb   Benjamin Renard   First commit
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
		values2Time [0] = values1Time [0];
		values2Time [1] = values1Time [values1Nb-1];

		values2Nb = 2;

		// Build time vector by merging existing times and computing intersections, and draw it !
		mergeAndSortTime (values1Time, values1Nb, values2Time, values2Nb, valuesTime);
		addIntersectionTime (values1, values1Time, values1Nb, values2, values2Time, values2Nb, valuesTime);
		drawFillArea (values1, values1Time, values1Nb, values2, values2Time, values2Nb, valuesTime,
						fillSerieConstant->isColorGreaterSpecified(), fillSerieConstant->getColorGreater(),
						fillSerieConstant->isColorLessSpecified(), fillSerieConstant->getColorLess(),
						rSeriesProperties);

		delete [] values1;
		delete [] values2;
		delete [] values2Time;
	}

	// Drawing Fill Area located between first and second Serie
	for (auto fillSerieSerie : _panel->_fillSerieSeries) {
		// Retrieve serie parameter values for firstSerieId
		if (!getSeriePropertiesById(fillSerieSerie->getFirstSerieId(), rSeriesProperties))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills - Cannot find serie id " << fillSerieSerie->getFirstSerieId());
			continue;
		}

		//get computed values for this serie and interval
		if (!getComputedValuesFromSerieAndInterval(startDate, stopDate, rSeriesProperties,
				rSeriesProperties.getIndex(), &values1, &values1Time, values1Nb))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills - Cannot get computed values for serie id " << fillSerieSerie->getFirstSerieId());
			continue;
		}

		// Retrieve serie parameter values for secondSerieId
		if (!getSeriePropertiesById(fillSerieSerie->getSecondSerieId(), rSeriesProperties))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills - Cannot find serie id " << fillSerieSerie->getSecondSerieId());
			continue;
		}

		//get computed values for this serie and interval
		if (!getComputedValuesFromSerieAndInterval(startDate, stopDate, rSeriesProperties,
				rSeriesProperties.getIndex(), &values2, &values2Time, values2Nb))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawFills - Cannot get computed values for serie id " << fillSerieSerie->getSecondSerieId());
			continue;
		}

		// Build time vector by merging existing times and computing intersections, and draw it !
		mergeAndSortTime (values1Time, values1Nb, values2Time, values2Nb, valuesTime);
		addIntersectionTime (values1, values1Time, values1Nb, values2, values2Time, values2Nb, valuesTime);
		drawFillArea (values1, values1Time, values1Nb, values2, values2Time, values2Nb, valuesTime,
						fillSerieSerie->isColorGreaterSpecified(), fillSerieSerie->getColorGreater(),
						fillSerieSerie->isColorLessSpecified(), fillSerieSerie->getColorLess(),
						rSeriesProperties);

		delete [] values1;
		delete [] values2;
	}
}

void TimePlot::drawSeries(double startDate, double stopDate, int intervalIndex,
		std::string pParamId, SeriesProperties& pSeries,
		AMDA::Common::ParameterIndexComponent pParamIndex,
		ParameterAxes& param, bool moreThanOneSerieForAxis) {
	LOG4CXX_DEBUG(gLogger, "TimePlot::drawSeries - Drawing serie for parameter "<<pParamId<<"["<<pParamIndex.getDim1Index()<<","<<pParamIndex.getDim2Index()<<"]");
	// This will configure window, draw axes (if needed) and legend of axes.
	PanelPlotOutput::drawSeries(startDate, stopDate, intervalIndex, pParamId, pSeries, pParamIndex, param, moreThanOneSerieForAxis);

	if(!pSeries.hasYAxis())
		return;

	// Y axis may be missing (tickplot for example)
	std::string	yAxisId = pSeries.getYAxisId();
	if (yAxisId.empty())
		return;

	//get computed values
	double *computedValues	= NULL;
	double *timeValues      = NULL;
	int    nbValues;
	if (!getComputedValuesFromSerieAndInterval(startDate, stopDate, pSeries, pParamIndex,
				&computedValues, &timeValues, nbValues))
	{
		LOG4CXX_DEBUG(gLogger, "TimePlot::drawSeries - Cannot get computed values for serie");
		return;
	}

	double *coloredComputedValues = NULL;
	double *coloredTimeValues     = NULL;
	//get colored value if needed
	if (!pSeries.getColorParamId().empty() && (_panel->getColorAxis() != nullptr))
	{
		int nbColoredValues;
		if (!getColoredComputedValuesFromSerieAndInterval(startDate, stopDate, pSeries,
				&coloredComputedValues, &coloredTimeValues, nbColoredValues))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawSeries - Cannot get computed values for colored parameter");
			return;
		}
	}

	PlWindow lPlWindow = PlWindow(getTimeAxis()->getRange().getMin(), getTimeAxis()->getRange().getMax(),
			_panel->getAxis(yAxisId)->getRange().getMin(), _panel->getAxis(yAxisId)->getRange().getMax());

	_pls->wind(std::get<0>(lPlWindow), std::get<1>(lPlWindow),
				std::get<2>(lPlWindow), std::get<3>(lPlWindow));

	//draw serie
	Color lineColor   = getSerieLineColor(pSeries, moreThanOneSerieForAxis);
	Color symbolColor = getSerieSymbolColor(pSeries, lineColor);

	drawSymbols(
		pSeries.getSymbolProperties().getType(),
		pSeries.getSymbolProperties().getSize(), 1.,
		symbolColor,
		nbValues, timeValues, computedValues, coloredComputedValues);

	drawLines(
		pSeries.getLineProperties().getType(),
		pSeries.getLineProperties().getStyle(),
		pSeries.getLineProperties().getWidth(),
		lineColor,
		nbValues, timeValues, computedValues, coloredComputedValues);

	//add serie to param legend
	addSerieToParamsLegend(pSeries,pParamIndex,param._originalParamId, lineColor,symbolColor,startDate,stopDate,intervalIndex);

	//draw interval
	drawSerieInterval(pSeries,timeValues,computedValues,timeValues,nbValues,intervalIndex);

	delete[] computedValues;
	if (coloredComputedValues != NULL)
		delete[] coloredComputedValues;

	// Draw min/max error bars if required
	ErrorBarProperties &errorBarProp = pSeries.getErrorBarProperties();
	if (errorBarProp.getErrorMinMax() != nullptr)
	{
		//get computed min/max error data
		double *minComputedValues = NULL;
		double *minTimeValues     = NULL;
		int nbMinValues;

		double *maxComputedValues = NULL;
		double *maxTimeValues     = NULL;
		int nbMaxValues;

		if (!getErrorComputedValuesFromSerieAndInterval(startDate, stopDate, pSeries,
					&minComputedValues, &minTimeValues, nbMinValues,
					&maxComputedValues, &maxTimeValues, nbMaxValues))
		{
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawSeries - Cannot get min/max error values for serie");
			return;
		}

		LineProperties &lineProps = pSeries.getErrorBarProperties().getLineProperties();
		drawYErrors(	lineProps.getType(),
						lineProps.getStyle(),
						lineProps.getWidth(),
						lineProps.getColor(),
						nbMinValues, minTimeValues,
						minComputedValues, maxComputedValues);

		// Free values
		delete [] minComputedValues;
		delete [] maxComputedValues;
	}
}

void TimePlot::drawSpectro(double startDate, double stopDate, std::string pParamId, SpectroProperties& pSpectro)
{
	LOG4CXX_DEBUG(gLogger, "TimePlot::drawSpectro Drawing spectro for parameter "<<pParamId);
	// This will configure window, draw axes (if needed) and legend of axes.
	PanelPlotOutput::drawSpectro(startDate, stopDate, pParamId, pSpectro);

	//get parameter data and info
	ParameterSPtr p = _parameterManager.getParameter(pParamId);

	ParameterData& data = (*_pParameterValues)[pSpectro.getParamId()];

	boost::shared_ptr<AMDA::Info::ParamTable> tableSPtr;
	AMDA::Info::ParamInfoSPtr paramInfo = AMDA::Info::ParamMgr::getInstance()->getParamInfoFromId(p->getInfoId());
	if (paramInfo != nullptr)
		tableSPtr = paramInfo->getTable(pSpectro.getRelatedDim());

	//get axis
	boost::shared_ptr<Axis> lXAxis = _panel->getAxis(pSpectro.getXAxisId());
	boost::shared_ptr<Axis> lYAxis = _panel->getAxis(pSpectro.getYAxisId());
	boost::shared_ptr<ColorAxis> lZAxis = _panel->getColorAxis();

	//Check dimensions
	if (pSpectro.getRelatedDim() == 0)
	{
		if (data.getDim1Size() + 1 <= 0)
		{
			LOG4CXX_INFO(gLogger, "TimePlot::drawSpectro - No data to plot");
			return;
		}
	}
	else
	{
		if (data.getDim2Size() + 1 <= 0)
		{
			LOG4CXX_INFO(gLogger, "TimePlot::drawSpectro - No data to plot");
			return;
		}
	}

90ed4760   Benjamin Renard   Add two logs in d...
918
	LOG4CXX_DEBUG(gLogger, "TimePlot::drawSpectro - Build data grid");
fbe3c2bb   Benjamin Renard   First commit
919
	MatrixGrid matrixGrid;
f2db3c16   Benjamin Renard   Support variable ...
920

2d64c235   Benjamin Renard   Fix bug with spec...
921
922
923
924
	//get specific colors for min / max values
	Color minValColor = lZAxis->getMinValColor();
	Color maxValColor = lZAxis->getMaxValColor();

e7ea756d   Benjamin Renard   Implements tables...
925
	if ((tableSPtr == nullptr) || !tableSPtr->isVariable(&_parameterManager))
fbe3c2bb   Benjamin Renard   First commit
926
	{
8c71f50a   Benjamin Renard   Improve execution...
927
928
929
		int startIndex;
		int nbValues;
		data.getIntervalBounds(startDate, stopDate, startIndex, nbValues);
f2db3c16   Benjamin Renard   Support variable ...
930
		for (auto index : pSpectro.getIndexes())
fbe3c2bb   Benjamin Renard   First commit
931
		{
f2db3c16   Benjamin Renard   Support variable ...
932
933
934
935
936
937
938
939
940
			GridPart part;
			if (tableSPtr == nullptr)
			{
				if (pSpectro.getRelatedDim() == 0)
					part.y[0] = index.getDim1Index();
				else
					part.y[0] = index.getDim2Index();
				part.y[1] = part.y[0]+1;
			}
fbe3c2bb   Benjamin Renard   First commit
941
			else
fbe3c2bb   Benjamin Renard   First commit
942
			{
f2db3c16   Benjamin Renard   Support variable ...
943
944
945
946
947
				AMDA::Info::t_TableBound crtBound;
				if (pSpectro.getRelatedDim() == 0)
					crtBound = tableSPtr->getBound(&_parameterManager, index.getDim1Index());
				else
					crtBound = tableSPtr->getBound(&_parameterManager, index.getDim2Index());
ed9a1eaf   Benjamin Renard   Add Maven STATIC ...
948
949
				if (std::isnan(crtBound.min) || std::isnan(crtBound.max))
					continue;
f2db3c16   Benjamin Renard   Support variable ...
950
951
952
953
				part.y[0] = crtBound.min;
				part.y[1] = crtBound.max;
				if (lYAxis->_scale == Axis::Scale::LOGARITHMIC)
				{
ed9a1eaf   Benjamin Renard   Add Maven STATIC ...
954
955
956
957
					if ((crtBound.min <= 0) || (crtBound.max <= 0))
						continue;
					part.y[0] = log10(part.y[0]);
					part.y[1] = log10(part.y[1]);
f2db3c16   Benjamin Renard   Support variable ...
958
				}
fbe3c2bb   Benjamin Renard   First commit
959
			}
fbe3c2bb   Benjamin Renard   First commit
960

2d64c235   Benjamin Renard   Fix bug with spec...
961
962
963
964
965
966
967
968
969
970
971
972
			if (lYAxis->_reverse) {
				if (((part.y[0] < lYAxis->getRange().getMax()) && (part.y[1] < lYAxis->getRange().getMax())) ||
					((part.y[0] > lYAxis->getRange().getMin()) && (part.y[1] < lYAxis->getRange().getMin()))) {
					continue;
				}
			}
			else {
				if (((part.y[0] < lYAxis->getRange().getMin()) && (part.y[1] < lYAxis->getRange().getMin())) ||
					((part.y[0] > lYAxis->getRange().getMax()) && (part.y[1] < lYAxis->getRange().getMax()))) {
					continue;
				}
			}
2acc7d49   Hacene SI HADJ MOHAND   progress
973
                                                         
8c71f50a   Benjamin Renard   Improve execution...
974
			for (int i = 0; i < nbValues - 1; ++i)
f2db3c16   Benjamin Renard   Support variable ...
975
			{
8c71f50a   Benjamin Renard   Improve execution...
976
977
				part.x[0] = data.getTimes()[startIndex+i];
				part.x[1] = data.getTimes()[startIndex+i+1];
5d98ca3d   Benjamin Renard   Draw intervals in...
978
				part.isColorIndex = false;
2acc7d49   Hacene SI HADJ MOHAND   progress
979
				part.value = data.getValues(index, startIndex)[i];
f2db3c16   Benjamin Renard   Support variable ...
980
981
				matrixGrid.push_back(part);
			}
2d64c235   Benjamin Renard   Fix bug with spec...
982
983
984

			//draw spectro
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawSpectro - Draw data grid - " << matrixGrid.size());
a436273c   Hacene SI HADJ MOHAND   evol ok
985
986
987
                                                            std::string normalization = pSpectro.getNormalization();
                                                            if (!normalization.empty())
                                                                 normalize(matrixGrid, normalization);
2d64c235   Benjamin Renard   Fix bug with spec...
988
989
990
			drawMatrix(matrixGrid, pSpectro.getMin(), pSpectro.getMax(),
				minValColor, maxValColor, lZAxis->_color._colorMapIndex, pSpectro.getUseLog0AsMin());
			matrixGrid.clear();
f2db3c16   Benjamin Renard   Support variable ...
991
992
993
994
995
996
		}
	}
	else
	{
		//Variable table
		AMDA::Info::t_TableBound crtBound;
8c71f50a   Benjamin Renard   Improve execution...
997
998
999
1000
1001
1002
		//for (auto index : pSpectro.getIndexes())
		//{
		int startIndex;
		int nbValues;
		data.getIntervalBounds(startDate, stopDate, startIndex, nbValues);
		for (int i = 0; i < nbValues - 1; ++i)
fbe3c2bb   Benjamin Renard   First commit
1003
		{
8c71f50a   Benjamin Renard   Improve execution...
1004
1005
1006
			GridPart part;
			part.x[0] = data.getTimes()[startIndex+i];
			part.x[1] = data.getTimes()[startIndex+i+1];
f2db3c16   Benjamin Renard   Support variable ...
1007

8c71f50a   Benjamin Renard   Improve execution...
1008
1009
1010
1011
1012
1013
			std::map<std::string, std::vector<double>> paramsTableData;
			for (std::map<std::string, std::string>::iterator it = pSpectro.getTableParams().begin(); it != pSpectro.getTableParams().end(); ++it)
			{
				ParameterData& tableData = (*_pParameterValues)[it->second];
				std::vector<double> paramTableValues;
				for (int j = 0; j < tableData.getDim1Size(); ++j)
f2db3c16   Benjamin Renard   Support variable ...
1014
				{
8c71f50a   Benjamin Renard   Improve execution...
1015
1016
					double* values = tableData.getValues(AMDA::Common::ParameterIndexComponent(j,-1), i);
					paramTableValues.push_back((*values));
f2db3c16   Benjamin Renard   Support variable ...
1017
				}
8c71f50a   Benjamin Renard   Improve execution...
1018
1019
1020
1021
1022
				paramsTableData[it->first] = paramTableValues;
			}

			for (auto index : pSpectro.getIndexes())
			{
5d98ca3d   Benjamin Renard   Draw intervals in...
1023
				part.isColorIndex = false;
8c71f50a   Benjamin Renard   Improve execution...
1024
				part.value = data.getValues(index,startIndex)[i];
f2db3c16   Benjamin Renard   Support variable ...
1025
1026
1027
1028
1029
1030
1031
1032

				if (pSpectro.getRelatedDim() == 0)
					crtBound = tableSPtr->getBound(&_parameterManager, index.getDim1Index(), &paramsTableData);
				else
					crtBound = tableSPtr->getBound(&_parameterManager, index.getDim2Index(), &paramsTableData);

				part.y[0] = crtBound.min;
				part.y[1] = crtBound.max;
ed9a1eaf   Benjamin Renard   Add Maven STATIC ...
1033
1034

				if (!std::isnan(crtBound.min) && !std::isnan(crtBound.max))
f2db3c16   Benjamin Renard   Support variable ...
1035
				{
ed9a1eaf   Benjamin Renard   Add Maven STATIC ...
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
					if (lYAxis->_scale == Axis::Scale::LOGARITHMIC)
					{
						if ((crtBound.min > 0) && (crtBound.max > 0))
						{
							part.y[0] = log10(part.y[0]);
							part.y[1] = log10(part.y[1]);
							matrixGrid.push_back(part);
						}
					}
					else
						matrixGrid.push_back(part);
f2db3c16   Benjamin Renard   Support variable ...
1047
				}
f2db3c16   Benjamin Renard   Support variable ...
1048
			}
7929a8a9   Benjamin Renard   CDF writer optimi...
1049
1050
			//draw spectro
			LOG4CXX_DEBUG(gLogger, "TimePlot::drawSpectro - Draw data grid - " << matrixGrid.size());
a436273c   Hacene SI HADJ MOHAND   evol ok
1051
1052
1053
                                                            std::string normalization = pSpectro.getNormalization();
                                                             if (!normalization.empty())
                                                                 normalize(matrixGrid, normalization);
2acc7d49   Hacene SI HADJ MOHAND   progress
1054
                                                                  
7929a8a9   Benjamin Renard   CDF writer optimi...
1055
1056
1057
			drawMatrix(matrixGrid, pSpectro.getMin(), pSpectro.getMax(),
				minValColor, maxValColor, lZAxis->_color._colorMapIndex, pSpectro.getUseLog0AsMin());
			matrixGrid.clear();
fbe3c2bb   Benjamin Renard   First commit
1058
1059
		}
	}
fbe3c2bb   Benjamin Renard   First commit
1060
}
a436273c   Hacene SI HADJ MOHAND   evol ok
1061
1062
1063
void TimePlot::normalize(MatrixGrid & matrixGrid, std::string normalizationType){
     if(normalizationType == "none")
         return;
2acc7d49   Hacene SI HADJ MOHAND   progress
1064
1065
1066
        double min = DBL_MAX;
        double max  = DBL_MIN;
           int len = matrixGrid.size();
d01dc099   Hacene SI HADJ MOHAND   correcting log no...
1067
1068
1069
1070
1071
1072
1073
1074
            if(normalizationType == "log"){
                        for(auto val :matrixGrid){
            if(val.value <min && val.value > 0 )
                min = val.value;
            if(val.value  > max)
                max = val.value;
        }
            }else{
2acc7d49   Hacene SI HADJ MOHAND   progress
1075
1076
1077
1078
1079
1080
        for(auto val :matrixGrid){
            if(val.value <min)
                min = val.value;
            if(val.value  > max)
                max = val.value;
        }
d01dc099   Hacene SI HADJ MOHAND   correcting log no...
1081
            }
0be91da0   Hacene SI HADJ MOHAND   normalisation at ...
1082
        if(std::isnan(min) || std::isnan(max)){
2acc7d49   Hacene SI HADJ MOHAND   progress
1083
            return;
0be91da0   Hacene SI HADJ MOHAND   normalisation at ...
1084
        }else if(min == max){
2acc7d49   Hacene SI HADJ MOHAND   progress
1085
1086
            for (int i =0; i < len; i++)
                matrixGrid[i].value= matrixGrid[i].value/max;
0be91da0   Hacene SI HADJ MOHAND   normalisation at ...
1087
        }else{
a436273c   Hacene SI HADJ MOHAND   evol ok
1088
    if(normalizationType == "log"){
2acc7d49   Hacene SI HADJ MOHAND   progress
1089
1090
1091
              for (int i =0; i < len; i++)
                matrixGrid[i].value = (std::log10(matrixGrid[i].value)-std::log10(min))/(std::log10(max)-std::log10(min));
              return;
a436273c   Hacene SI HADJ MOHAND   evol ok
1092
    }else if (normalizationType == "linear"){
2acc7d49   Hacene SI HADJ MOHAND   progress
1093
1094
1095
1096
1097
              for (int i =0; i < len; i++)
                matrixGrid[i].value = (matrixGrid[i].value-min)/(max-min);
            return;
    }else{
            std::stringstream lError;
a436273c   Hacene SI HADJ MOHAND   evol ok
1098
            lError << "Unknwon normalization " << normalizationType;
2acc7d49   Hacene SI HADJ MOHAND   progress
1099
1100
1101
		BOOST_THROW_EXCEPTION(PanelPlotOutputException() << AMDA::ex_msg(lError.str()));
            }
    
0be91da0   Hacene SI HADJ MOHAND   normalisation at ...
1102
1103
1104
        }
    
}
fbe3c2bb   Benjamin Renard   First commit
1105

677db865   Benjamin Renard   Draw intervals on...
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
Color TimePlot::getStatusColor(AMDA::Info::ParamInfoSPtr& paramInfo, double value) {
	Color color;
	
	if ((paramInfo != nullptr) && !paramInfo->getStatusDef().empty()) {
		for (int s = 0 ; s < (int)paramInfo->getStatusDef().size(); ++s) {
			if (value >= paramInfo->getStatusDef()[s].getMinValue() && value <= paramInfo->getStatusDef()[s].getMaxValue()) {
				if (!paramInfo->getStatusDef()[s].getColor().empty()) {
					std::string colorStr = paramInfo->getStatusDef()[s].getColor();
					createColor(color, colorStr);
					return color;
				}
			}
		}
	}

	return color;
}

void TimePlot::drawOneInterval(double tmin, double tmax, Color color) {
	if (!color.isSet()) {
		return;
	}

	//Fill interval
	PanelPlotOutput::drawRectangle(tmin, tmax, 0., 1., color, 0.25);

	//Draw borders
	PLFLT x[2], y[2];
        x[0] = tmin;
        y[0] = 0.;
        x[1] = tmin;
        y[1] = 1.;
        PanelPlotOutput::drawLines(LineType::LINE, LineStyle::PLAIN, 2, color, 2, x, y);

        x[0] = tmax;
        y[0] = 0.;
        x[1] = tmax;
        y[1] = 1.;
        PanelPlotOutput::drawLines(LineType::LINE, LineStyle::PLAIN, 2, color, 2, x, y);
}

e257cfb9   Benjamin Renard   First implementat...
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
void TimePlot::drawIntervals(double startDate, double stopDate, std::string pParamId,
		IntervalsProperties& pIntervals) {
	LOG4CXX_DEBUG(gLogger, "TimePlot::drawIntervals Drawing intervals for parameter "<<pParamId);
	// This will configure window, draw axes (if needed) and legend of axes.
	PanelPlotOutput::drawIntervals(startDate, stopDate, pParamId, pIntervals);
        
        PlWindow lPlWindow = PlWindow(getTimeAxis()->getRange().getMin(), getTimeAxis()->getRange().getMax(), 0, 1);

	_pls->wind(std::get<0>(lPlWindow), std::get<1>(lPlWindow),
				std::get<2>(lPlWindow), std::get<3>(lPlWindow));

	ParameterData& data = (*_pParameterValues)[pIntervals.getParamId()];
677db865   Benjamin Renard   Draw intervals on...
1159
1160
1161

	ParameterSPtr p = _parameterManager.getParameter(pIntervals.getParamId());
        AMDA::Info::ParamInfoSPtr paramInfo = AMDA::Info::ParamMgr::getInstance()->getParamInfoFromId(p->getInfoId());
e257cfb9   Benjamin Renard   First implementat...
1162
1163
        
        //get computed values
b7747945   Benjamin Renard   Fix some warning ...
1164
        int startIndex, nbData = 0;
e257cfb9   Benjamin Renard   First implementat...
1165
        data.getIntervalBounds(startDate, stopDate, startIndex, nbData);
677db865   Benjamin Renard   Draw intervals on...
1166
1167

	Color crtColor;
e257cfb9   Benjamin Renard   First implementat...
1168
1169
1170
        
        // Draw intervals
        double crtVal = NAN;
4de2b52c   Benjamin Renard   Fix some tests + ...
1171
        double tmin = 0, tmax = 0;
e257cfb9   Benjamin Renard   First implementat...
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
        for (int i = 0; i < nbData - 1; ++i) {
            double t1 = data.getTimes()[startIndex+i];
            double t2 = data.getTimes()[startIndex+i+1];
            double v = *data.getValues(AMDA::Common::ParameterIndexComponent(-1,-1), startIndex+i);
            
            if (isNAN(crtVal)) {
                tmin = t1;
                tmax = t2;
                crtVal = v;
                continue;
            }
            else if (crtVal == v) {
                tmax = t2;
                continue;
            }
677db865   Benjamin Renard   Draw intervals on...
1187
1188
1189
1190
1191

            crtColor = getStatusColor(paramInfo, crtVal);

            drawOneInterval(tmin, tmax, crtColor);

e257cfb9   Benjamin Renard   First implementat...
1192
1193
1194
            tmin = t1;
            tmax = t2;
            crtVal = v;
5d98ca3d   Benjamin Renard   Draw intervals in...
1195
            crtColor = Color();
e257cfb9   Benjamin Renard   First implementat...
1196
1197
1198
        }
        
        //Draw last interval if need
d321080e   Benjamin Renard   Fix last interval...
1199
1200
        if ((tmin != tmax) && !isNAN(crtVal)) {
		crtColor = getStatusColor(paramInfo, crtVal);
4de2b52c   Benjamin Renard   Fix some tests + ...
1201
1202
        	drawOneInterval(tmin, tmax, crtColor);
	}
e257cfb9   Benjamin Renard   First implementat...
1203
1204
}

fbe3c2bb   Benjamin Renard   First commit
1205
1206
1207
1208
1209
1210
/**
 * @brief Draw further information (for instance start date).
 */
void TimePlot::drawStartDate(TimeAxis* pXAxis, double startTime, double stopTime) {
	LOG4CXX_DEBUG(gLogger, "Drawing start date.");

08ec1dde   Benjamin Renard   Add propertie _us...
1211
	if (pXAxis->_showTickMark == false || !pXAxis->_drawn || !pXAxis->_visible)
fbe3c2bb   Benjamin Renard   First commit
1212
1213
1214
1215
1216
		return;

	// use panel font to draw start date.

	// If font of legend is not defined, use panel font.
f6eaec4e   Benjamin Renard   Optimize plot ele...
1217
	Font font(_panel->getFont());
fbe3c2bb   Benjamin Renard   First commit
1218

f6eaec4e   Benjamin Renard   Optimize plot ele...
1219
1220
	// PlPlotUtil::setPlFont(font);
	//CharSize charsize = PlPlotUtil::getCharacterSizeInPlPage(_panel->_page);
fbe3c2bb   Benjamin Renard   First commit
1221
	// panel bounds.
f6eaec4e   Benjamin Renard   Optimize plot ele...
1222
	Bounds lPanelBounds(_panel->getBoundsInPlPage());
12fd871c   Benjamin Renard   Fix start date po...
1223

fbe3c2bb   Benjamin Renard   First commit
1224
1225
1226
1227
	// plotting area bounds (i.e. current viewport dimensions)
	PLFLT lXMin, lXMax, lYMin, lYMax;
	_pls->gvpd(lXMin, lXMax, lYMin, lYMax);

fbe3c2bb   Benjamin Renard   First commit
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
	// position of reference point of string along the bottom edge
	// expressed as a fraction of the length of the bottom edge
	// set it at the very beginning of edge and use justification to handle
	// reverse axis.
	float lPosition = 0.0;
	// display it one line above the main panel bottom border :
	float disp = -1;

	long int lTime = static_cast<long int>(startTime);
	tm * lTimeTm = gmtime(&lTime);
	char lTimeChr[80];

	// Format date.
	strftime(lTimeChr, 80,
			getPlStartTimeFormat(pXAxis->_timeFormat,
					startTime,
					stopTime).c_str(), lTimeTm);

12fd871c   Benjamin Renard   Fix start date po...
1246
1247
1248
1249
	PLFLT mxmin, mxmax, mymin, mymax;
	plgspa( &mxmin, &mxmax, &mymin, &mymax );
	float x_subpage_per_mm = 1. / ( mxmax - mxmin );

fbe3c2bb   Benjamin Renard   First commit
1250
1251
1252
	LOG4CXX_DEBUG(gLogger, "Start date to draw : " << lTimeChr);

	// Set font
f6eaec4e   Benjamin Renard   Optimize plot ele...
1253
	PlPlotUtil::setPlFont(font);
fbe3c2bb   Benjamin Renard   First commit
1254

12fd871c   Benjamin Renard   Fix start date po...
1255
1256
1257
1258
1259
1260
	PLFLT dateWidthInMm;
	dateWidthInMm = plstrl(lTimeChr);

	// set viewport for start date :
	_pls->vpor(lXMin,lXMax,lPanelBounds._y, lPanelBounds._y+lPanelBounds._height);
	        
fbe3c2bb   Benjamin Renard   First commit
1261
1262
	// Draw start date.
	if (pXAxis->_reverse) {
12fd871c   Benjamin Renard   Fix start date po...
1263
1264
1265
1266
		lPosition = 1.;
		if (dateWidthInMm*x_subpage_per_mm > lPanelBounds._x + lPanelBounds._width - lXMax)
			lPosition = 1. - (dateWidthInMm*x_subpage_per_mm - (lPanelBounds._x + lPanelBounds._width - lXMax)) / (lXMax - lXMin);
		_pls->mtex("b", disp, lPosition , 0., lTimeChr);
fbe3c2bb   Benjamin Renard   First commit
1267
	} else {
12fd871c   Benjamin Renard   Fix start date po...
1268
1269
1270
		lPosition = 0.;
		if (dateWidthInMm*x_subpage_per_mm > lXMin - lPanelBounds._x)
			lPosition = (dateWidthInMm*x_subpage_per_mm - lXMin + lPanelBounds._x) / (lXMax - lXMin);
fbe3c2bb   Benjamin Renard   First commit
1271
1272
1273
1274
1275
1276
		_pls->mtex("b", disp, lPosition, 1., lTimeChr);
	}

	// restore viewport :
	_pls->vpor(lXMin,lXMax,lYMin, lYMax);
}
fbe3c2bb   Benjamin Renard   First commit
1277
1278
1279
1280
1281
1282
1283

const std::string TimePlot::getXAxisId() const {
	// time plot can manage only one x axis.
	// search for its id
	for (auto param : _parameterAxesList)
	{
		//search time axis in color serie if exist
2fc1f2f8   Benjamin Renard   Full rework for s...
1284
1285
		if (!param.getYSeriePropertiesList().empty())
			return param.getYSeriePropertiesList().begin()->getXAxisId();
fbe3c2bb   Benjamin Renard   First commit
1286
1287
1288
1289
1290
		//search time axis in spectro if exist
		if (param.getSpectroProperties() != nullptr)
			return param.getSpectroProperties()->getXAxisId();
	}

2d40f7de   Benjamin Renard   Fix bug with pane...
1291
	return DefaultPlotConfiguration::TIME_DEFAULT_ID;
fbe3c2bb   Benjamin Renard   First commit
1292
1293
1294
1295
}


} /* namespace plot */