HistoPlot.cc 18.3 KB
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 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 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 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 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323 324 325 326 327 328 329 330 331 332 333 334 335 336 337 338 339 340 341 342 343 344 345 346 347 348 349 350 351 352 353 354 355 356 357 358 359 360 361 362 363 364 365 366 367 368 369 370 371 372 373 374 375 376 377 378 379 380 381 382 383 384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406 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 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 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
/*
 * HistoPlot.cc
 *
 *  Created on: 29 oct. 2013
 *      Author: CS
 */

#include <fstream>
#include <iomanip>
#include <boost/lexical_cast.hpp>
#include <boost/algorithm/string.hpp>

#include "HistoPlot.hh"
#include "ParamsNode.hh"
#include "AxesNode.hh"
#include "Axis.hh"
#include "PlotLogger.hh"
#include "PlotOutput.hh"
#include "TimeUtil.hh"
#include "ParamMgr.hh"
#include "AxisLegendManager.hh"

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

namespace plot {

HistoPlot::HistoPlot(AMDA::Parameters::ParameterManager& manager,
		boost::shared_ptr<Panel> panel) :
		PanelPlotOutput(manager, panel){
			_plotted=false;

}

/**
 * @overload PanelPlotOutput::preparePlotArea()
 */
void HistoPlot::preparePlotArea(double startTime, double stopTime, int intervalIndex, std::vector<std::string>* ttNames) {
	// for test, dump plot properties
	const char* lBuildType=getenv("BUILD_TYPE");
	if(lBuildType && std::string(lBuildType) == "Debug") {
		std::ofstream out("HistoPlot.txt");
		dump(out);
		out.close();
	}

	// Configure range of series and color.
	configureSeriesAxis(startTime,stopTime);
	configureAxisLegend();

	// Configure params legend
	configureParamsLegend(startTime,stopTime,intervalIndex);

	// If panel title is empty, replace it with start and end date.
	if (_panel->getTitle()->_text.empty() || _panel->_updateTitleOnNextInterval) {
		//Title must be updated during the next interval plot
		_panel->_updateTitleOnNextInterval = true;
		// Set start date and end date.
		std::string lTimeFormat("%Y/%m/%d %H:%M:%S");

		long int lStartTime = static_cast<long int>(startTime);
		tm * lStartTimeTm = gmtime(&lStartTime);
		char lStartTimeChr[80];

		// Format date.
		strftime(lStartTimeChr, 80, lTimeFormat.c_str(), lStartTimeTm);
		std::string lStartTimeStr= lStartTimeChr;
		lStartTimeStr += '.'+std::to_string(startTime -lStartTime ).substr(2,3);

		long int lStopTime = static_cast<long int>(stopTime);
		tm * lStopTimeTm = gmtime(&lStopTime);
		char lStopTimeChr[80];

		// Format date.
		strftime(lStopTimeChr, 80, lTimeFormat.c_str(), lStopTimeTm);
		std::string lStopTimeStr= lStopTimeChr;
		lStopTimeStr += '.'+std::to_string(stopTime -lStopTime ).substr(2,3);
		std::string titleText = lStartTimeStr + " - " + lStopTimeStr;

		if(_panel->_page->_superposeMode){

			std::string superposedModeText = "Events from ";
			if (ttNames != nullptr) {
				// Iterate through the vector's elements using the pointer
				for (const std::string& name : *ttNames) {
					if (name == ttNames->back() && ttNames->size()>1)
						superposedModeText +=" and '"+name+"' in "+titleText;
					else if (ttNames->size()==1)
						superposedModeText +=" '"+name+"' in "+titleText;
					else if (name == ttNames->at(ttNames->size()-2) && ttNames->size()>1)
						superposedModeText += "'"+name+"'";
					else
						superposedModeText += "'"+name+"',";
				}
			}

			_panel->setTitleText(superposedModeText.c_str());
		}
		else{
			_panel->setTitleText(titleText.c_str());
		}
	}

	PanelPlotOutput::preparePlotArea(startTime,stopTime,intervalIndex, ttNames);
}

void HistoPlot::createParameters(std::list<std::string>& usedParametersId_)
{

	for (ParameterAxesList::iterator it = _parameterAxesList.begin();
				it != _parameterAxesList.end(); ++it)
	{
		AMDA::Parameters::ParameterSPtr originalYParam =
			_parameterManager.getParameter(it->_originalParamId);

		AMDA::Parameters::ParameterSPtr usedXParam;
		AMDA::Parameters::ParameterSPtr usedYParam;
		AMDA::Parameters::ParameterSPtr usedColorParam;

		for (auto pHistogramProperties : it->getHistogramSeriesPropertiesList())
		{
			if(pHistogramProperties != nullptr){
				if(pHistogramProperties->getHistogramType() == "histogram1d"){
					AMDA::Parameters::ParameterSPtr originalColorParam;
					if(!pHistogramProperties->getHistotypeProperties().getParamId().empty())
						originalColorParam =_parameterManager.getParameter(pHistogramProperties->getHistotypeProperties().getParamId());
					if (std::find (usedParametersId_.begin(),usedParametersId_.end(),originalYParam->getId()) == usedParametersId_.end())
									usedParametersId_.push_back(originalYParam->getId());
					pHistogramProperties->setParamId(originalYParam->getId());

					if(originalColorParam != nullptr)
						pHistogramProperties->getHistotypeProperties().setParamId(originalColorParam->getId());
					
				}
				else if(pHistogramProperties->getHistogramType() == "histogram2d"){
					ParameterAxes* xSerieParameterAxes = getParameterAxesByXSerieId(pHistogramProperties->getXId());
					XSeriesProperties& xSerie = xSerieParameterAxes->getXSeriePropertiesById(pHistogramProperties->getXId());
					AMDA::Parameters::ParameterSPtr originalXSerieParam = _parameterManager.getParameter(xSerieParameterAxes->_originalParamId);
					AMDA::Parameters::ParameterSPtr originalColorParam;

					if(pHistogramProperties->getHistotypeProperties().getParamId() != ""){
						originalColorParam = _parameterManager.getParameter(pHistogramProperties->getHistotypeProperties().getParamId());
					}

					getUsedParameters(originalXSerieParam,originalYParam,nullptr,pHistogramProperties->getResamplingProperties(),-1,
										usedXParam,usedYParam,usedColorParam );

					if (std::find (usedParametersId_.begin(),usedParametersId_.end(),usedXParam->getId()) == usedParametersId_.end())
								usedParametersId_.push_back(usedXParam->getId());

					if (std::find (usedParametersId_.begin(),usedParametersId_.end(),usedYParam->getId()) == usedParametersId_.end())
									usedParametersId_.push_back(usedYParam->getId());

					if (originalColorParam != nullptr)
					{
						if (std::find (usedParametersId_.begin(),usedParametersId_.end(),usedColorParam->getId()) == usedParametersId_.end())
							usedParametersId_.push_back(usedColorParam->getId());

						pHistogramProperties->getHistotypeProperties().setParamId(usedColorParam->getId());
						
					}
					pHistogramProperties->setZAxis(true);
					//link serie to this resampled parameter
					pHistogramProperties->setParamId(usedYParam->getId());
					xSerie.setParamId(usedXParam->getId());
				}
			}
		}
    }
}

void HistoPlot::getUsedParameters(AMDA::Parameters::ParameterSPtr originalXParam_,AMDA::Parameters::ParameterSPtr originalYParam_,
								AMDA::Parameters::ParameterSPtr originalZParam_, ResamplingProperties &resamplingProperties_,
								int maxResolution_,AMDA::Parameters::ParameterSPtr &usedXParam_,
								AMDA::Parameters::ParameterSPtr &usedYParam_,AMDA::Parameters::ParameterSPtr &usedZParam_)
{
	double samplingYValue = getSamplingInTreeParameter(originalYParam_);
	double samplingXValue = getSamplingInTreeParameter(originalXParam_);

	switch (resamplingProperties_.getType())
	{
	case ResamplingType::MANUAL :
		{
			LOG4CXX_DEBUG(gLogger, "HistoPlot::getUsedParameters - ResamplingType::MANUAL");
			//create resampling parameters for xparam
			usedXParam_ = createSampledParameter(originalXParam_, resamplingProperties_.getValue());
			
			if (originalXParam_ == originalYParam_)
			{
				//same original parameter => re-use xparam
				usedYParam_ = usedXParam_;
			}
			else
			{
				//create resampling parameters for xparam
				usedYParam_ = createSampledParameter(originalYParam_, resamplingProperties_.getValue());
			}
		}
		break;
	case ResamplingType::AUTO   :
	case ResamplingType::XPARAM :
		{
			LOG4CXX_DEBUG(gLogger, "HistoPlot::getUsedParameters - ResamplingType::XPARAM");
			double correctedSamplingValue = getCorrectedSamplingValue(maxResolution_, samplingXValue);
			if (abs(samplingXValue - correctedSamplingValue) > 1.)
			{
				//create resampling parameter for xparam
				usedXParam_ = createSampledParameter(originalXParam_, correctedSamplingValue);
				if (originalXParam_ == originalYParam_)
				{
					//same original parameter => re-use xparam
					usedYParam_ = usedXParam_;
				}
				else
				{
					//create resampling parameter for yparam
					usedYParam_ = createSampledParameter(originalYParam_, correctedSamplingValue);
				}
			}
			else
			{
				//get original parameter for xparam
				usedXParam_ = originalXParam_;
				if (originalXParam_ == originalYParam_)
				{
					//same original parameter => re-use xparam
					usedYParam_ = usedXParam_;
				}
				else
				{
					//create resampled parameter under times of xparam for yparam
					usedYParam_ = createSampledParameterUnderReferenceParameter(originalYParam_, originalXParam_);
				}
			}
		}
		break;
	case ResamplingType::YPARAM :
		LOG4CXX_DEBUG(gLogger, "HistoPlot::getUsedParameters - ResamplingType::YPARAM");
		double correctedSamplingValue = getCorrectedSamplingValue(maxResolution_, samplingYValue);
		if (abs(samplingYValue - correctedSamplingValue) > 1.)
		{
			//create resampling parameter for xparam
			usedXParam_ = createSampledParameter(originalXParam_, correctedSamplingValue);
			if (originalXParam_ == originalYParam_)
			{
				//same original parameter => re-use xparam
				usedYParam_ = usedXParam_;
			}
			else
			{
				//create resampling parameter for yparam
				usedYParam_ = createSampledParameter(originalYParam_, correctedSamplingValue);
			}
		}
		else
		{
			//get original parameter for yparam
			usedYParam_ = originalYParam_;
			if (originalXParam_ == originalYParam_)
			{
				//same original parameter => re-use yparam
				usedXParam_ = usedYParam_;
			}
			else
			{
				//create resampled parameter under times of yparam for cparam
				usedXParam_ = createSampledParameterUnderReferenceParameter(originalXParam_, originalYParam_);
			}
		}
		break;
	}
	if (originalZParam_ != nullptr)
	{
		usedZParam_ = createSampledParameterUnderReferenceParameter(originalZParam_, usedYParam_);
	}
}

void HistoPlot::configureSeriesAxis(double startDate, double stopDate) {
	// map<X/YAxisId, automaticRange>
	Range lColorAxeRange;

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

	SeriesProperties lSeriesProperties;
	// Parse each parameter to define on which axis to draw series.
	for (auto param: _parameterAxesList) {

		for (auto pHistogramProperties : param.getHistogramSeriesPropertiesList())
		{
			if(pHistogramProperties != nullptr){ 

					boost::shared_ptr<Axis> lXAxis = _panel->getAxis(pHistogramProperties->getXAxisId());
					boost::shared_ptr<Axis> lYAxis = _panel->getAxis(pHistogramProperties->getYAxisId());
					lXAxis->_used = true; lYAxis->_used = true;

				if(pHistogramProperties->getHistogramType() == "histogram1d"){
					
					std::vector<std::pair<double,double>> grid;
					double xBinSize = 0;

					// Call histo1DUtils to get yMin/yMax and send these to PanelPlotOutput::drawHistogram to draw the y axis
					histo1DUtils(startDate, stopDate,*pHistogramProperties.get(), grid, xBinSize);
				}

				else if(pHistogramProperties->getHistogramType() == "histogram2d"){
					lZAxis->_used = true;
					if(_panel->_page->_superposeMode){
						_globalStartTime = startDate;
						_globalStopTime = stopDate;
					}
				}
			}
		}
	}

	if (lZAxis != nullptr && lColorAxeRange.isSet())
		lZAxis->setRange(lColorAxeRange);
}

void HistoPlot::configureAxisLegend () {
	// Y axis
	AxisLegendManager::configureYAxisLegendForSeries(this);

	// X axis
	AxisLegendManager::configureXAxisLegendForSeries(this);

	// Z axis
	AxisLegendManager::configureColorAxisLegendForSeries(this);

}

void HistoPlot::histo1DUtils(double startDate, double stopDate, HistogramSeriesProperties &pHistogramProperties,
								std::vector<std::pair<double,double>> &grid, double &xBinSize){
	// Get X, Y  axis.
	boost::shared_ptr<Axis> lXAxis(_panel->getAxis(pHistogramProperties.getXAxisId()));
    boost::shared_ptr<Axis> lYAxis(_panel->getAxis(pHistogramProperties.getYAxisId()));

	Range lXRange = lXAxis->getRange();

	if(std::isnan(lXRange.getMin()) || std::isnan(lXRange.getMax()))
		return;
    Range lYRange = lYAxis->Axis::getRange();
	double yMin = lYRange.getMin() ; 
	double yMax = lYRange.getMax() ;

	unsigned int xBinNumber = pHistogramProperties.getManualProperties().getXBinNumber();

	xBinSize = (lXRange.getMax() - lXRange.getMin())/ xBinNumber;

	//std::cout << pHistogramProperties.getHistotypeProperties().getParamId() << std::endl;
	ParameterData &xData = (*_pParameterValues)[pHistogramProperties.getParamId()];
	

    int xStartIndex;
	int xNbValues;
	
	xData.getIntervalBounds(startDate, stopDate, xStartIndex, xNbValues);	
    double* xValues =nullptr;
	double* yValues =nullptr;

	if(lXAxis->_scale==Axis::Scale::LOGARITHMIC)
		xValues =  lXAxis->getComputedValues(xData.getValues(pHistogramProperties.getIndex(), xStartIndex),xNbValues,exp10(lXRange.getMin()), exp10(lXRange.getMax()));
	else
		xValues = xData.getValues(pHistogramProperties.getIndex(), xStartIndex);

	

	if(!pHistogramProperties.getHistotypeProperties().getParamId().empty()){
		ParameterData &yData = (*_pParameterValues)[pHistogramProperties.getHistotypeProperties().getParamId()];
		int yStartIndex;	
		int yNbValues;

		xData.getIntervalBounds(startDate, stopDate, yStartIndex, yNbValues);
		yValues = yData.getValues(pHistogramProperties.getHistotypeProperties().getIndex(), yStartIndex);
	}
	
    pHistogramProperties.getHistotypeProperties().getHisto1DFunction()->apply(grid,xValues,yValues,xNbValues,lXRange, xBinSize, 
													(lYAxis->_scale==Axis::Scale::LOGARITHMIC) ,yMin, yMax);
	


	if(lXAxis->_scale==Axis::Scale::LOGARITHMIC)
		free(xValues);
	
	if(!std::isnan(yMin))
		lYRange.setMin(yMin);
	if(!std::isnan(yMax))
		lYRange.setMax(yMax);
	lYRange._extend = lYAxis->isExtended();
	lYAxis->setRange(lYRange);
}

void HistoPlot::drawHistogram(double startDate, double stopDate, std::string pParamId, 
								HistogramSeriesProperties &pHistogramProperties){
	
	if(pHistogramProperties.getHistogramType() == "histogram1d"){
		if(_panel->_page->_superposeMode && _plotted)
			return;

		std::vector<std::pair<double,double>> grid;
		Color color = pHistogramProperties.getColor();
		double xBinSize = 0;
		boost::shared_ptr<Axis> lYAxis(_panel->getAxis(pHistogramProperties.getYAxisId()));
		Range lYRange = lYAxis->getRange();

		histo1DUtils(startDate, stopDate,pHistogramProperties, grid, xBinSize);
		
		PanelPlotOutput::drawHistogram(startDate,stopDate,pParamId, pHistogramProperties);
		PanelPlotOutput::drawHistogramBoxes(grid,color,xBinSize, lYRange.getMin(), pHistogramProperties.getManualProperties().hasStairs());
		_plotted = true;

	}
	else {
		if(_panel->_page->_superposeMode && _plotted)
			return;

		if(_panel->_page->_superposeMode){
			startDate= _globalStartTime;
			stopDate = _globalStopTime;
		}
		// Get X, Y and Z axis.
		boost::shared_ptr<Axis> lXAxis(_panel->getAxis(pHistogramProperties.getXAxisId()));
		boost::shared_ptr<Axis> lYAxis(_panel->getAxis(pHistogramProperties.getYAxisId()));
		//boost::shared_ptr<Axis> lZAxis(_panel->getAxis(pHistogramProperties.getZAxisId()));
		boost::shared_ptr<ColorAxis> lZAxis = _panel->getColorAxis();

		Range lXRange = lXAxis->getRange();
		Range lYRange = lYAxis->getRange();
		Range lZRange = lZAxis->getRequestedRange();
		

		Color minValColor = lZAxis->getMinValColor();
		Color maxValColor = lZAxis->getMaxValColor();

		GridPart grid;
		MatrixGrid matrixGrid;
		int smoothFactor = pHistogramProperties.getHistotypeProperties().getSmoothFactor();

		unsigned int xBinNumber = pHistogramProperties.getManualProperties().getXBinNumber();
		unsigned int yBinNumber = pHistogramProperties.getManualProperties().getYBinNumber();

		

		double xBinSize = (lXRange.getMax() - lXRange.getMin())/ xBinNumber;
		double yBinSize = (lYRange.getMax() - lYRange.getMin())/ yBinNumber;

		//get parameter x data for this serie
		ParameterAxes* xSerieParameterAxes = getParameterAxesByXSerieId(pHistogramProperties.getXId());
		XSeriesProperties& xSerie = xSerieParameterAxes->getXSeriePropertiesById(pHistogramProperties.getXId());

		ParameterData &xData = (*_pParameterValues)[xSerie.getParamId()];
		ParameterData &yData = (*_pParameterValues)[pHistogramProperties.getParamId()];
		ParameterData &zData = (*_pParameterValues)[pHistogramProperties.getHistotypeProperties().getParamId()];


		int xStartIndex;
		int yStartIndex;
		int zStartIndex;
		int xNbValues;
		int yNbValues;
		int zNbValues;
		double zMin = NAN ; 
		double zMax = NAN ;
		
		xData.getIntervalBounds(startDate, stopDate, xStartIndex, xNbValues);
		yData.getIntervalBounds(startDate, stopDate, yStartIndex, yNbValues);
		zData.getIntervalBounds(startDate, stopDate, zStartIndex, zNbValues);

		double* xValues;
		double* yValues;
		double* zValues;
		if(lXAxis->_scale==Axis::Scale::LOGARITHMIC)
			xValues =  lXAxis->getComputedValues(xData.getValues(xSerie.getIndex(), xStartIndex),xNbValues,exp10(lXRange.getMin()), exp10(lXRange.getMax()));
		else
			xValues = xData.getValues(xSerie.getIndex(), xStartIndex);
		if(lYAxis->_scale==Axis::Scale::LOGARITHMIC)
			yValues =  lYAxis->getComputedValues(yData.getValues(pHistogramProperties.getIndex(), yStartIndex),yNbValues,exp10(lYRange.getMin()), exp10(lYRange.getMax()));
		else
			yValues = yData.getValues(pHistogramProperties.getIndex(), yStartIndex);
		
		zValues = zData.getValues(pHistogramProperties.getHistotypeProperties().getIndex(), zStartIndex);

		for (unsigned int i(0); i < xBinNumber; ++i)
		{
			for (unsigned int j(0); j < yBinNumber; ++j)
			{
				grid.x[0] =  lXRange.getMin()+xBinSize*i;
				grid.x[1] = grid.x[0]+xBinSize;
				grid.y[0] = lYRange.getMin() + yBinSize*j;
				grid.y[1] = grid.y[0]+yBinSize;
				grid.value = NAN;
				grid.isColorIndex= false;

				matrixGrid.push_back(grid);
			}
		}

		pHistogramProperties.getHistotypeProperties().getHisto2DFunction()->apply(matrixGrid, xValues, yValues, zValues, xNbValues,lXRange,lYRange,
														xBinNumber, yBinNumber, zMin, zMax, smoothFactor);
		if(lXAxis->_scale==Axis::Scale::LOGARITHMIC)
			free(xValues);
		if(lYAxis->_scale==Axis::Scale::LOGARITHMIC)
			free(yValues);
		
		if(std::isnan(lZRange.getMin()))
			lZRange.setMin(zMin);
		if(std::isnan(lZRange.getMax()))
			lZRange.setMax(zMax);
		
		lZRange._extend = lZAxis->isExtended();
		lZAxis->setRange(lZRange);

		
		PanelPlotOutput::drawHistogram(startDate,stopDate,pParamId, pHistogramProperties);
		PanelPlotOutput::drawMatrix(matrixGrid, zMin, zMax, minValColor,maxValColor, lZAxis->_color._colorMapIndex, false);
		_plotted = true;
	}
}

void HistoPlot::resetPlot()
{
	for (auto param: _parameterAxesList) {

		for (auto pHistogramProperties : param.getHistogramSeriesPropertiesList())
		{
			if(pHistogramProperties != nullptr){ 

				if(pHistogramProperties->getHistogramType() == "histogram1d"){
					
					pHistogramProperties->getHistotypeProperties().getHisto1DFunction()->resetCache();
				}
				_plotted = false;
			}
		}
	}
	PanelPlotOutput::resetPlot();
}
}

// Events from 'tt' in TIMEMIN - TIMEMAX