src/terralib/qt/widgets/charts/Utils.cpp
Go to the documentation of this file.
1 /* Copyright (C) 2008 National Institute For Space Research (INPE) - Brazil.
2 
3  This file is part of the TerraLib - a Framework for building GIS enabled applications.
4 
5  TerraLib is free software: you can redistribute it and/or modify
6  it under the terms of the GNU Lesser General Public License as published by
7  the Free Software Foundation, either version 3 of the License,
8  or (at your option) any later version.
9 
10  TerraLib is distributed in the hope that it will be useful,
11  but WITHOUT ANY WARRANTY; without even the implied warranty of
12  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
13  GNU Lesser General Public License for more details.
14 
15  You should have received a copy of the GNU Lesser General Public License
16  along with TerraLib. See COPYING. If not, write to
17  TerraLib Team at <terralib-team@terralib.org>.
18  */
19 
20 /*!
21  \file Utils.cpp
22 
23  \brief This file contains a set of utility chart functions
24 */
25 
26 // TerraLib
27 #include "../../../color/RGBAColor.h"
28 #include "../../../common/progress/TaskProgress.h"
29 #include "../../../dataaccess/dataset/DataSet.h"
30 #include "../../../dataaccess/dataset/DataSetType.h"
31 #include "../../../dataaccess/dataset/ObjectIdSet.h"
32 #include "../../../dataaccess/utils/Utils.h"
33 #include "../../../dataaccess/datasource/DataSourceFactory.h"
34 #include "../../../datatype.h"
35 #include "../../../raster.h"
36 #include "../../../maptools/ExternalGraphicRendererManager.h"
37 #include "../../../maptools/MarkRendererManager.h"
38 #include "../../../maptools/Utils.h"
39 #include "../../../memory/DataSet.h"
40 #include "../../../memory/DataSetItem.h"
41 #include "../../../qt/widgets/Utils.h"
42 #include "../../../se/Utils.h"
43 #include "../../../se.h"
44 #include "../../../statistics/core/Enums.h"
45 #include "../../../statistics/core/NumericStatisticalSummary.h"
46 #include "../../../statistics/core/StringStatisticalSummary.h"
47 #include "../../../statistics/core/SummaryFunctions.h"
48 #include "../../../statistics/core/Utils.h"
49 #include "ChartDisplay.h"
50 #include "ChartDisplayWidget.h"
51 #include "ChartStyle.h"
52 #include "Histogram.h"
53 #include "HistogramChart.h"
54 #include "Scatter.h"
55 #include "ScatterChart.h"
56 #include "Utils.h"
57 
58 //Boost
59 #include <boost/lexical_cast.hpp>
60 #include <boost/ptr_container/ptr_vector.hpp>
61 
62 //QT
63 #include <QPen>
64 
65 //STL
66 #include <memory>
67 
68 float gammln( float xx )
69 {
70  double x, tmp, ser;
71  static double cof[6]= {76.18009173, -86.50532033, 24.01409822,
72  -1.231739516, 0.120858003e-2, -0.536382e-5};
73  int j;
74 
75  x = static_cast<double>(xx) - 1.0;
76  tmp = x + 5.5;
77  tmp -= (x+0.5)*log(tmp);
78  ser = 1.0;
79 
80  for (j=0; j<=5; j++)
81  {
82  x += 1.0;
83  ser += cof[j]/x;
84  }
85  return static_cast<float>(-tmp + log(2.50662827465*ser));
86 }
87 
88 void gser( float * gamser, float a, float x, float * gln )
89 {
90  double ITMAX = 100;
91  double EPS = 3.0e-7;
92 
93  int n;
94  float sum, del,ap;
95 
96  *gln = gammln(a);
97 
98  if (x <= 0.0)
99  {
100  if ( x < 0.0)
101  printf ("x less than 0 in the GSER routine");
102 
103  *gamser = 0.0;
104  return;
105  }
106 
107  else
108  {
109  ap = a;
110  del= sum = static_cast<float>(1.0/static_cast<double>(a));
111  for (n=1; n <= ITMAX; n++)
112  {
113  ap += 1.0;
114  del *= x/ap;
115  sum += del;
116  if (fabs (static_cast<double>(del)) < fabs (static_cast<double>(sum))*EPS)
117  {
118  *gamser = static_cast<float>(static_cast<double>(sum)*exp(static_cast<double>(-x+a*static_cast<float>(log(static_cast<double>(x)))-(*gln))));
119  return;
120  }
121  }
122  return;
123  }
124 }
125 
126 void gcf( float * gammcf, float a, float x, float * gln )
127 {
128  double ITMAX = 100;
129  double EPS = 3.0e-7;
130 
131  int n;
132  float gold=0.0, g, fac=1.0, b1=1.0;
133  float b0=0.0, anf, ana, an, a1, a0=1.0;
134 
135  *gln=gammln(a);
136 
137  a1=x;
138 
139  for(n=1; n<= ITMAX; n++)
140  {
141  an = static_cast<float>(n);
142  ana = an - a;
143  a0 = (a1+a0*ana)*fac;
144  b0 = (b1+b0*ana)*fac;
145  anf = an*fac;
146  a1 = x*a0+anf*a1;
147  b1 = x*b0+anf*b1;
148  if (a1)
149  {
150  fac = static_cast<float>(1.0/static_cast<double>(a1));
151  g = b1*fac;
152  if (fabs(static_cast<double>((g-gold)/g)) < EPS)
153  {
154  *gammcf = static_cast<float>(exp (static_cast<double>(-x+a*static_cast<float>(log(static_cast<double>(x)))-(*gln))*static_cast<double>(g)));
155  return;
156  }
157  gold = g;
158  }
159  }
160 }
161 
162 float gammp( float a, float x )
163 {
164  float gamser, gammcf, gln;
165 
166  if (static_cast<double>(x) < (static_cast<double>(a)+1.0))
167  {
168  gser (&gamser, a, x, &gln);
169  return gamser;
170  }
171  else
172  {
173  gcf (&gammcf, a, x, &gln);
174  return static_cast<float>(1.0 - static_cast<double>(gammcf));
175  }
176 }
177 
178 float errFunction( float x )
179 {
180  return static_cast<double>(x) < 0.0 ? -gammp(0.5, x*x) : gammp(0.5,x*x);
181 }
182 
183 double getDouble(const std::string& value, std::vector<std::string>& sVector)
184 {
185  //verify if it exists
186  for(std::size_t i=0;i<sVector.size();++i)
187  {
188  if(value==sVector[i])
189  return static_cast<double>(i);
190  }
191 
192  sVector.push_back(value);
193  return static_cast<double>(sVector.size()-1);
194 }
195 
196 double getDouble(te::dt::DateTime* dateTime)
197 {
198  if(dateTime->getDateTimeType() == te::dt::TIME_INSTANT)
199  {
200  std::unique_ptr<te::dt::TimeInstant> ti (static_cast<te::dt::TimeInstant*>(dateTime));
201  boost::gregorian::date basedate(1400, 01, 01);
202  boost::gregorian::date_duration days = ti->getDate().getDate() - basedate;
203  long long int seconds = ti->getTime().getTimeDuration().total_seconds();
204  long long int dias = days.days();
205  double v = static_cast<double>(dias) * 86400 + seconds;
206  return v;
207  }
208  else if(dateTime->getDateTimeType() == te::dt::DATE)
209  {
210  std::unique_ptr<te::dt::Date> d (static_cast<te::dt::Date*>(dateTime));
211  boost::gregorian::date basedate(1400, 01, 01);
212  boost::gregorian::date_duration days = d->getDate() - basedate;
213  double v = days.days();
214  return v;
215  }
216  return 0.;
217 }
218 
219 /*
220  Auxiliary function used to acquire the current value of the dataset as a double regardless of it's (numeric) type
221 
222  param dataset The dataset being used, must be given at the position of interest
223  param propId The id of the property of interest;
224  note Will return 0 if the type of the property was not numeric.
225 */
226 double getDouble(te::da::DataSet* dataset, int propId)
227 {
228  double res = 0.;
229 
230  int propType = dataset->getPropertyDataType(static_cast<size_t>(propId));
231  switch (propType)
232  {
233  case(te::dt::INT16_TYPE):
234  res = dataset->getInt16(static_cast<size_t>(propId));
235  break;
236  case(te::dt::UINT16_TYPE):
237  res = dataset->getInt16(static_cast<size_t>(propId));
238  break;
239  case(te::dt::INT32_TYPE):
240  res = dataset->getInt32(static_cast<size_t>(propId));
241  break;
242  case(te::dt::UINT32_TYPE):
243  res = dataset->getInt32(static_cast<size_t>(propId));
244  break;
245  case(te::dt::INT64_TYPE):
246  res = dataset->getInt64(static_cast<size_t>(propId));
247  break;
248  case(te::dt::UINT64_TYPE):
249  res = dataset->getInt64(static_cast<size_t>(propId));
250  break;
251  case(te::dt::FLOAT_TYPE):
252  res = static_cast<double>(dataset->getFloat(static_cast<size_t>(propId)));
253  break;
254  case(te::dt::NUMERIC_TYPE):
255  res = boost::lexical_cast<double>(dataset->getNumeric(static_cast<size_t>(propId)));
256  break;
257  default:
258  res = dataset->getDouble(static_cast<size_t>(propId));
259  break;
260  }
261 
262  return res;
263 }
264 
265 /*
266  Auxiliary function used to acquire the summarized string value of the dataset using the selected statistical function
267 
268  param stat The selected satistical function, pass -1 if no function is to be used;
269  param sss The StringStatisticalSummary that will make the relevant calculations and return the result
270 */
272 {
273  std::string res;
274 
275  switch (stat)
276  {
277  case(te::stat::MIN_VALUE):
278  res = sss.m_minVal;
279  break;
280  case(te::stat::MAX_VALUE):
281  res = sss.m_maxVal;
282  break;
283  //case(te::stat::COUNT):
284  // res = dataset->size();
285  // break;
286  //case(te::stat::VALID_COUNT):
287  // break;
288  default:
289  break;
290  }
291  return res;
292 }
293 
294 /*
295  Auxiliary function used to acquire the summarized double value of the dataset using the selected statistical function
296 
297  param stat The selected satistical function, pass -1 if no function is to be used;
298  param sss The NumericStatisticalSummary that will make the relevant calculations and return the result
299 */
301 {
302  double res;
303 
304  switch (stat)
305  {
306  case(te::stat::MIN_VALUE):
307  res = nss.m_minVal;
308  break;
309  case(te::stat::MAX_VALUE):
310  res = nss.m_maxVal;
311  break;
312  //case(te::stat::COUNT):
313  // res = dataset->size();
314  // break;
315  //case(te::stat::VALID_COUNT):
316  // res = getDouble(dataset, propId);
317  // break;
318  case(te::stat::MEAN):
319  res = nss.m_mean;
320  break;
321  case(te::stat::SUM):
322  res = nss.m_sum;
323  break;
325  res = nss.m_stdDeviation;
326  break;
327  case(te::stat::VARIANCE):
328  res = nss.m_variance;
329  break;
330  case(te::stat::SKEWNESS):
331  res = nss.m_skewness;
332  break;
333  case(te::stat::KURTOSIS):
334  res = nss.m_kurtosis;
335  break;
336  case(te::stat::AMPLITUDE):
337  res = nss.m_amplitude;
338  break;
339  case(te::stat::MEDIAN):
340  res = nss.m_median;
341  break;
342  case(te::stat::VAR_COEFF):
343  res = nss.m_varCoeff;
344  break;
345 
346  default:
347  res = 0.0;
348  break;
349  }
350  return res;
351 }
352 
353 /*
354  Auxiliary function used to a scatter with summarized values
355 
356  param stat The selected satistical function, pass -1 if no function is to be used;
357  param oidsToSummarize A map containing all the objectIds mapped by the oid of the base dataset.
358  param valuesToSummarize A map containing all the values9points) mapped by the oid of the base dataset.
359  param scatter Output parameter, the scatter to be populated.
360 
361  note This function is only going to populate the sacatter's data if it a statistical funcion has been selected,
362  otherwise it will return the scatter as it received it.
363 */
364 void buildSummarizedScatter(int stat, std::map<std::string, std::vector<te::da::ObjectId*> > oidsToSummarize,
365  std::map<std::string, std::vector<std::pair<double, double> > > valuesToSummarize,
366  te::qt::widgets::Scatter* scatter)
367 {
368  //Containers used to hold informations temporarily, used to organize them prior to inserting them on the histogram.
369  std::map<std::string, std::vector<te::da::ObjectId*> >::iterator oidsIt;
370  std::map<std::string, std::vector<std::pair<double, double> > > ::iterator valuesIt;
371 
372  //Acquiring the summarized values
373  for(valuesIt = valuesToSummarize.begin(); valuesIt != valuesToSummarize.end(); ++valuesIt)
374  {
377  if((*valuesIt).second.size() > 1 && (stat != -1))
378  {
379  std::vector<double> xValues;
380  std::vector<double> yValues;
381  std::vector<te::da::ObjectId*> oids;
382 
383  for(size_t i = 0; i < (*valuesIt).second.size(); ++i)
384  {
385  xValues.push_back((*valuesIt).second[i].first);
386  yValues.push_back((*valuesIt).second[i].second);
387  oids = oidsToSummarize[(*valuesIt).first];
388  }
389 
390  double summarizedXValue, summarizedYValue;
391 
393  summarizedXValue = getStatisticalValue(stat, ssx);
394 
396  summarizedYValue = getStatisticalValue(stat, ssy);
397 
398  for(size_t j = 0; j < oids.size(); ++j)
399  scatter->addData(summarizedXValue, summarizedYValue, oids[j]);
400  }
401  else
402  {
403  //A summary was requested, but it was not needed due to the fact the there is only one value for each base oid
404 
405  double xValue = (*valuesIt).second[0].first;
406  double yValue = (*valuesIt).second[0].second;
407 
408  std::vector<te::da::ObjectId*> oids;
409  oids = oidsToSummarize[(*valuesIt).first];
410 
411  scatter->addData(xValue, yValue, oids[0]);
412  }
413  }
414 }
415 
416 /*
417  Auxiliary function used to populate the frequencies, interval and their respective objectIds based on a statistical function
418 
419  param slices The number of slices for the histogram, used to calculate the number of intervals;
420  param stat The selected satistical function, pass -1 if no function is to be used;
421  param valuestoSummarize a map containing all the values and their objectIds mapped by the oid of the base dataset,
422  defaults to a one-to-one relationship between value and objectId unless the histogram is based on a linked layer;
423  param intervals Output parameter, the vector containing the intervals.
424  param intervalToOIds Output parameter, the map that associates every interval to their objectIds.
425  param frequencies Output parameter, the vector containing the frequencies.
426  param minValue Output parameter, the minimum value of the histogram.
427  param interval Output parameter, the interval of the histogram.
428 */
429 void buildNumericFrequencies(int slices, int stat, std::map<std::string, std::vector<std::pair<double, te::da::ObjectId*> > > valuestoSummarize,
430  std::vector<double>& intervals, std::map<double, std::vector<te::da::ObjectId*> >& intervalToOIds,
431  std::vector< unsigned int>& frequencies, double& minValue, double& interval)
432 {
433  //Containers used to hold informations temporarily, used to organize them prior to inserting them on the histogram.
434  std::map<std::string, std::vector<std::pair<double, te::da::ObjectId*> > >::iterator valuesIt;
435  std::vector<std::pair<double, std::vector<te::da::ObjectId*> > > summarizedValuesToOId;
436 
437  //Acquiring the summarized values
438  for(valuesIt = valuestoSummarize.begin(); valuesIt != valuestoSummarize.end(); ++valuesIt)
439  {
441  if((*valuesIt).second.size() > 1 && stat != -1)
442  {
443  std::vector<double> values;
444  std::vector<te::da::ObjectId*> oids;
445  for(size_t i = 0; i < (*valuesIt).second.size(); ++i)
446  {
447  values.push_back((*valuesIt).second[i].first);
448  oids.push_back((*valuesIt).second[i].second);
449  }
450 
451  double summarizedValue;
453  summarizedValue = getStatisticalValue(stat, ss);
454  summarizedValuesToOId.push_back(std::make_pair(summarizedValue, oids));
455  }
456  else
457  {
458  for(size_t i = 0; i < (*valuesIt).second.size(); ++i)
459  {
460  std::vector<te::da::ObjectId*> oids;
461  oids.push_back((*valuesIt).second[i].second);
462  summarizedValuesToOId.push_back(std::make_pair((*valuesIt).second[i].first, oids));
463  }
464  }
465  }
466 
467  double maxValue = -std::numeric_limits<double>::max();
468 
469  for(size_t i = 0; i < summarizedValuesToOId.size(); ++i)
470  {
471  double currentValue = summarizedValuesToOId[i].first;
472 
473  //calculate range
474  if(minValue > currentValue)
475  minValue = currentValue;
476  if(maxValue < currentValue)
477  maxValue = currentValue;
478  }
479 
480  //Adjusting the interval to the user-defined number of slices.
481  interval = ((maxValue * 1.000001 - minValue) / slices);
482 
483  //Adjusting the histogram's intervals
484  for (double i = minValue; i <(maxValue+interval); i+=interval)
485  {
486  intervals.push_back(i);
487  std::vector<te::da::ObjectId*> valuesOIds;
488  intervalToOIds.insert(std::make_pair(i, valuesOIds));
489  }
490 
491  frequencies.resize(intervals.size(), 0);
492 
493  //Adjusting the frequencies on each interval
494  for(size_t i = 0; i < summarizedValuesToOId.size(); ++i)
495  {
496  double currentValue = summarizedValuesToOId[i].first;
497  for (size_t j = 0; j<intervals.size(); ++j)
498  {
499  if((currentValue >= intervals[j]) && (currentValue <= intervals[j+1]))
500  {
501  for(size_t k= 0; k < summarizedValuesToOId[i].second.size(); ++k)
502  intervalToOIds.at(intervals[j]).push_back(summarizedValuesToOId[i].second[k]);
503 
504  ++frequencies[j];
505  break;
506  }
507  }
508  }
509 }
510 
511 /*
512  Auxiliary function used to populate the frequencies, interval and their respective objectIds based on a statistical function
513 
514  param stat The selected satistical function, pass -1 if no function is to be used;
515  param valuestoSummarize a map containing all the values and their objectIds mapped by the oid of the base dataset,
516  defaults to a one-to-one relationship between value and objectId unless the histogram is based on a linked layer;
517  param intervalToOIds Output parameter, the map that associates every interval to their objectIds.
518  param frequencies Output parameter, the vector containing the frequencies.
519 
520 */
521 void buildStringFrequencies(int stat, std::map<std::string, std::vector<std::pair<std::string, te::da::ObjectId*> > > valuestoSummarize,
522  std::map<std::string, std::vector<te::da::ObjectId*> >& intervalToOIds,
523  std::vector< unsigned int>& frequencies)
524 {
525  //Containers and iterators used to hold informations temporarily, used to organize them prior to inserting them on the histogram.
526  std::map<std::string, std::vector<std::pair<std::string, te::da::ObjectId*> > >::iterator valuesIt;
527  std::map<std::string, std::vector<te::da::ObjectId*> >::iterator intervalsIt;
528  std::vector<std::pair<std::string, std::vector<te::da::ObjectId*> > > summarizedValuesToOId;
529 
530  //Acquiring the summarized values
531  for(valuesIt = valuestoSummarize.begin(); valuesIt != valuestoSummarize.end(); ++valuesIt)
532  {
534  if((*valuesIt).second.size() > 1 && (stat != -1))
535  {
536  std::vector<std::string> values;
537  std::vector<te::da::ObjectId*> oids;
538  for(size_t i = 0; i < (*valuesIt).second.size(); ++i)
539  {
540  values.push_back((*valuesIt).second[i].first);
541  oids.push_back((*valuesIt).second[i].second);
542  }
543 
544  std::string summarizedValue;
546  summarizedValue = getStatisticalValue(stat, ss);
547  summarizedValuesToOId.push_back(std::make_pair(summarizedValue, oids));
548  }
549  else
550  {
551  for(size_t i = 0; i < (*valuesIt).second.size(); ++i)
552  {
553  std::vector<te::da::ObjectId*> oids;
554  oids.push_back((*valuesIt).second[i].second);
555  summarizedValuesToOId.push_back(std::make_pair((*valuesIt).second[i].first, oids));
556  }
557  }
558  }
559 
560  //Adjusting the frequencies on each interval
561  for(size_t i = 0; i < summarizedValuesToOId.size(); ++i)
562  {
563  int j;
564  std::string currentValue = summarizedValuesToOId[i].first;
565  for ( j= 0, intervalsIt = intervalToOIds.begin(); intervalsIt != intervalToOIds.end(); ++intervalsIt,++j)
566  {
567  if(currentValue == (*intervalsIt).first)
568  {
569  for(size_t k= 0; k < summarizedValuesToOId[i].second.size(); ++k)
570  intervalToOIds.at(currentValue).push_back(summarizedValuesToOId[i].second[k]);
571 
572  ++frequencies[static_cast<size_t>(j)];
573  break;
574  }
575  }
576  }
577 }
578 
579 /*
580  Auxiliary function used to acquire the current objectId of the dataset
581 
582  param dataset The dataset being used, must be given at the position of interest;
583  param pkeys A vector containing all the properties that form the primaryKey of the given dataset
584 */
585 te::da::ObjectId* getObjectId(te::da::DataSet* dataset, std::vector<std::size_t> pkeys)
586 {
587  std::vector<size_t>::iterator it;
588  std::vector<std::string> propNames;
589 
590  for(it=pkeys.begin(); it!=pkeys.end(); ++it)
591  propNames.push_back(dataset->getPropertyName(*it));
592 
593  //The caller will take ownership of the generated pointer.
594  te::da::ObjectId* oid = te::da::GenerateOID(dataset, propNames);
595  return oid;
596 }
597 
598 void getObjectIds (te::da::DataSet* dataset, std::vector<std::size_t> pkeys, std::vector<te::da::ObjectId*>& valuesOIDs)
599 {
600  te::da::ObjectId* oid = getObjectId(dataset,pkeys);
601  valuesOIDs.push_back(oid);
602 }
603 
604 te::qt::widgets::Scatter* te::qt::widgets::createScatter(te::da::DataSet* dataset, te::da::DataSetType* dataType, int propX, int propY, int stat, bool readall)
605 {
607 
608  std::vector<std::size_t> objIdIdx;
609  te::da::GetOIDPropertyPos(dataType, objIdIdx);
610 
611  std::map<double, std::vector<te::da::ObjectId*> > valuesIdsByinterval;
612  std::vector<te::da::ObjectId*> valuesOIds;
613 
614  std::size_t rpos = te::da::GetFirstPropertyPos(dataset, te::dt::RASTER_TYPE);
615  if(rpos != std::string::npos)
616  {
617  std::unique_ptr<te::rst::Raster> raster(dataset->getRaster(rpos));
618  double xDummyValue = raster->getBand(static_cast<size_t>(propX))->getProperty()->m_noDataValue;
619  double yDummyValue = raster->getBand(static_cast<size_t>(propY))->getProperty()->m_noDataValue;
620 
621  unsigned int nCol = raster->getNumberOfColumns();
622  unsigned int nLin = raster->getNumberOfRows();
623 
625  task.setTotalSteps(static_cast<int>(nCol));
626  task.setMessage("Scatter creation");
627 
628  if (!readall)
629  {
630  unsigned int maxInputPoints = static_cast<unsigned int>(nCol * nLin * 0.10);
631  std::vector<te::gm::Point*> randomPoints = te::rst::GetRandomPointsInRaster(*raster, maxInputPoints);
634 
635  while (pit != pitend)
636  {
637  if(!task.isActive())
638  {
639  break;
640  }
641  double val1, val2;
642 
643  raster->getValue(pit.getColumn(), pit.getRow(), val1, static_cast<size_t>(propX));
644  raster->getValue(pit.getColumn(), pit.getRow(), val2, static_cast<size_t>(propY));
645 
646  if ((val1 == xDummyValue) || (val2 == yDummyValue))
647  {
648  ++pit;
649  task.pulse();
650  continue;
651  }
652 
653  newScatter->addX(val1);
654  newScatter->addY(val2);
655  ++pit;
656  task.pulse();
657  }
658  }
659  else
660  {
661  for (unsigned int c=0; c < nCol; ++c)
662  {
663  if(!task.isActive())
664  {
665  break;
666  }
667  for (unsigned int r=0; r <nLin; ++r)
668  {
669  double val1, val2;
670  raster->getValue(c, r, val1, static_cast<size_t>(propX));
671  raster->getValue(c, r, val2, static_cast<size_t>(propY));
672 
673  if ((val1 == xDummyValue) || (val2 == yDummyValue))
674  continue;
675 
676  newScatter->addX(val1);
677  newScatter->addY(val2);
678  }
679 
680  task.pulse();
681  }
682  }
683  }
684  else
685  {
686  int xType = dataset->getPropertyDataType(static_cast<size_t>(propX));
687  int yType = dataset->getPropertyDataType(static_cast<size_t>(propY));
688 
689  //Acquiring the name of the base dataset and how many properties are included in it's primary key
690  std::pair<std::string, int> dsProps;
691  te::da::GetOIDDatasetProps(dataType, dsProps);
692 
693  //A map containg the summarized values used to buil d the histogram
694  std::map<std::string, std::vector<te::da::ObjectId*> > oidsToSummarize;
695  std::map<std::string, std::vector<std::pair<double, double> > > valuesToSummarize;
696 
698  task.setTotalSteps(static_cast<int>(dataset->getNumProperties()));
699  task.setMessage("Scatter creation");
700 
701  while(dataset->moveNext())
702  {
703 
704  if(!task.isActive())
705  {
706  break;
707  }
708 
709  double x_doubleValue = 0.;
710  double y_doubleValue = 0.;
711 
712  if(xType >= te::dt::INT16_TYPE && xType <= te::dt::NUMERIC_TYPE)
713  {
714  if(dataset->isNull(static_cast<size_t>(propX)))
715  continue;
716 
717  x_doubleValue = getDouble(dataset, propX);
718  }
719  else if(xType == te::dt::DATETIME_TYPE)
720  {
721  if(dataset->isNull(static_cast<size_t>(propX)))
722  continue;
723 
724  std::unique_ptr<te::dt::DateTime> dateTime = dataset->getDateTime(static_cast<size_t>(propX));
725  x_doubleValue = getDouble(dateTime.release());
726  }
727 
728  //======treat the Y value
729  if(yType >= te::dt::INT16_TYPE && yType <= te::dt::NUMERIC_TYPE)
730  {
731  if(dataset->isNull(static_cast<size_t>(propY)))
732  continue;
733  y_doubleValue = getDouble(dataset, propY);
734  }
735  else if(yType == te::dt::DATETIME_TYPE)
736  {
737  if(dataset->isNull(static_cast<size_t>(propY)))
738  continue;
739 
740  std::unique_ptr<te::dt::DateTime> dateTime = dataset->getDateTime(static_cast<size_t>(propY));
741  y_doubleValue = getDouble(dateTime.release());
742  }
743 
744  //insert values into the vectors
745  te::da::ObjectId* currentOid = getObjectId(dataset, objIdIdx);
746 
747  if(stat == -1)
748  {
749  newScatter->addData(x_doubleValue, y_doubleValue, currentOid);
750  }
751  else
752  {
753  oidsToSummarize[te::da::getBasePkey(currentOid, dsProps)].push_back(currentOid);
754  valuesToSummarize[te::da::getBasePkey(currentOid, dsProps)].push_back(std::make_pair(x_doubleValue, y_doubleValue));
755  }
756  task.pulse();
757  } //end of the data set
758  if(stat != -1)
759  buildSummarizedScatter(stat, oidsToSummarize, valuesToSummarize, newScatter);
760  }
761 
762  newScatter->calculateMinMaxValues();
763  return newScatter;
764 }
765 
767 {
768  //Creating the scatter and it's chart with the given dataset
769  te::qt::widgets::ScatterChart* chart = new te::qt::widgets::ScatterChart(te::qt::widgets::createScatter(dataset, dataType, propX, propY, stat));
770 
771  //Creating and adjusting the chart Display's style.
773  chartStyle->setTitle(QString::fromUtf8("Scatter"));
774  chartStyle->setAxisX(QString::fromUtf8(dataset->getPropertyName(static_cast<size_t>(propX)).c_str()));
775  chartStyle->setAxisY(QString::fromUtf8(dataset->getPropertyName(static_cast<size_t>(propY)).c_str()));
776 
777  //Creating and adjusting the chart Display
778  te::qt::widgets::ChartDisplay* chartDisplay = new te::qt::widgets::ChartDisplay(nullptr, QString::fromUtf8("Scatter"), chartStyle);
779  chartDisplay->adjustDisplay();
780  chart->attach(chartDisplay);
781 
782  //Adjusting the chart widget
784  displayWidget->show();
785  displayWidget->setWindowTitle("Scatter");
786  return displayWidget;
787 }
788 
789 te::qt::widgets::Histogram* te::qt::widgets::createHistogram(te::map::AbstractLayerPtr layer, int propId, int slices, int stat, bool readall)
790 {
792  std::unique_ptr<te::da::DataSet> dataset = layer->getData();
793  std::unique_ptr<te::da::DataSetType> dataType = layer->getSchema();
794 
795  std::vector<std::size_t> objIdIdx;
796  te::da::GetOIDPropertyPos(dataType.get() , objIdIdx);
797 
798  if(dataType->hasRaster())
799  {
800  std::unique_ptr<te::rst::Raster> rstptr (te::map::GetRaster(layer.get()));
801  double dummy = rstptr->getBand(static_cast<size_t>(propId))->getProperty()->m_noDataValue;
802  std::map<double, unsigned int> histogram;
803 
804  if(readall)
805  {
806  histogram = rstptr->getBand(static_cast<size_t>(propId))->getHistogramR(0, 0, 0, 0, static_cast<unsigned int>(slices));
807  }
808  else
809  {
810  // read values from raster
811  const unsigned int nCol = rstptr->getNumberOfColumns();
812  const unsigned int nLin = rstptr->getNumberOfRows();
813  const unsigned int maxInputPoints = static_cast<unsigned int>( ((double)nCol) * ((double)nLin) * 0.10);
814  const std::vector<te::gm::Point*> randomPoints = te::rst::GetRandomPointsInRaster(*rstptr, maxInputPoints);
816  const te::rst::PointSetIterator<double> pItEnd = te::rst::PointSetIterator<double>::end(rstptr.get(), randomPoints);
817  std::vector< double > values;
818  double value = 0;
819  std::size_t valuesIdx = 0;
820  double valuesMin = std::numeric_limits< double >::max();
821  double valuesMax = -1.0 * std::numeric_limits< double >::max();
822 
823  while(pIt != pItEnd)
824  {
825  rstptr->getValue(pIt.getColumn(), pIt.getRow(), value, static_cast<size_t>(propId));
826 
827  if( value != dummy )
828  {
829  values.push_back( value );
830 
831  if( value > valuesMax ) valuesMax = value;
832  if( value < valuesMin ) valuesMin = value;
833  }
834 
835  ++valuesIdx;
836  ++pIt;
837  }
838 
839  // create histogram with bins
840 
841  const double delta = (valuesMax - valuesMin) / ( (double)( slices - 1 ) );
842  if( delta == 0 )
843  {
844  if( !values.empty() )
845  {
846  histogram[ valuesMax ] = (unsigned int)values.size();
847  }
848  }
849  else
850  {
851  const std::size_t valuesSize = values.size();
852 
853  for ( int sliceIdx = 0 ; sliceIdx < slices ; ++sliceIdx )
854  {
855  histogram[ valuesMin + ( ((double)sliceIdx) * delta ) ] = 0;
856  }
857 
858  std::map<double, unsigned int>::iterator histogramIt;
859  const std::map<double, unsigned int>::iterator histogramItEnd = histogram.end();
860 
861  for ( std::size_t valuesIdx = 0 ; valuesIdx < valuesSize ; ++valuesIdx )
862  {
863  histogramIt = histogram.lower_bound( values[ valuesIdx ] );
864  assert( histogramIt != histogramItEnd );
865 
866  ++( histogramIt->second );
867  }
868  }
869  }
870 
871  const double min = histogram.begin()->first;
872  const double max = histogram.rbegin()->first;
873 
874  for(std::map<double, unsigned int>::iterator it = histogram.begin(); it != histogram.end(); ++it)
875  {
876  newHistogram->insert(std::make_pair(new te::dt::Double(it->first), it->second));
877  }
878 
879  newHistogram->setMinValue(min);
880  if (slices != 0)
881  newHistogram->setInterval( (max - min) / ((double)( slices - 1 )) );
882  newHistogram->setSummarized(false);
883  }
884  else
885  {
886 
887  if(slices <=1)
888  slices = 2;
889 
890  int propType = dataset->getPropertyDataType(static_cast<size_t>(propId));
891  newHistogram->setType(propType);
892 
893  if((propType >= te::dt::INT16_TYPE && propType <= te::dt::UINT64_TYPE) ||
894  (propType >= te::dt::FLOAT_TYPE && propType <= te::dt::NUMERIC_TYPE))
895  {
896  //Acquiring the name of the base dataset and how many of it's properties are included in it's primary key
897  std::pair<std::string, int> dsProps;
898  te::da::GetOIDDatasetProps(dataType.get(), dsProps);
899 
900  //A map containg the summarized values used to buil d the histogram
901  std::map<std::string, std::vector<std::pair<double, te::da::ObjectId*> > > valuesToSummarize;
902 
904  task.setMessage("Histogram creation");
905  task.setTotalSteps((static_cast<int>(dataset->getNumProperties())) * 2);
906 
907  dataset->moveBeforeFirst();
908 
909  //Adjusting the Histogram's values
910  while(dataset->moveNext())
911  {
912 
913  if(dataset->isNull(static_cast<size_t>(propId)))
914  continue;
915 
916  if(!task.isActive())
917  {
918  break;
919  }
920 
921  double currentValue = getDouble(dataset.get(), propId);
922  te::da::ObjectId* currentOid = getObjectId(dataset.get(), objIdIdx);
923  valuesToSummarize[te::da::getBasePkey(currentOid, dsProps)].push_back(std::make_pair(currentValue, currentOid));
924 
925  task.pulse();
926  }
927 
928  //The minimum value
929  double minValue = std::numeric_limits<double>::max();
930 
931  //The interval
932  double interval = std::numeric_limits<double>::max();
933 
934  //A vector containing the intervals
935  std::vector<double> intervals;
936 
937  //The vector containing the frequency of each interval, will be used to every property type
938  std::vector< unsigned int> frequencies;
939 
940  //A map containing the intervals and their objecIds
941  std::map<double, std::vector<te::da::ObjectId*> > intervalToOIds;
942 
943  //Populating the frequencies, intervals and their respective objectIds with the results of the chosen summary function
944  buildNumericFrequencies(slices, stat, valuesToSummarize, intervals, intervalToOIds, frequencies, minValue, interval);
945 
946  //With both the intervals and frequencies ready, the map can be populated
947  for (unsigned int i= 0; i<intervals.size(); ++i)
948  {
949  te::dt::Double* data = new te::dt::Double(intervals[i]);
950  newHistogram->insert(std::make_pair(data, frequencies[i]), intervalToOIds.at(intervals[i]));
951  }
952 
953  newHistogram->setMinValue(minValue);
954  newHistogram->setInterval(interval);
955  newHistogram->setSummarized(stat != -1);
956  dataset->moveBeforeFirst();
957  }
958  }
959  return newHistogram;
960 }
961 
963 {
965  std::unique_ptr<te::da::DataSet> dataset = layer->getData();
966  std::unique_ptr<te::da::DataSetType> dataType = layer->getSchema();
967 
968  std::vector<std::size_t> objIdIdx;
969  te::da::GetOIDPropertyPos(dataType.get(), objIdIdx);
970 
972  task.setMessage("Histogram creation");
973 
974  if(dataType->hasRaster())
975  {
976  std::unique_ptr<te::rst::Raster> rstptr (te::map::GetRaster(layer.get()));
977  std::map<double, unsigned int> values = rstptr->getBand(static_cast<size_t>(propId))->getHistogramR();
978 
979  for(std::map<double, unsigned int>::iterator it = values.begin(); it != values.end(); ++it)
980  {
981  task.pulse();
982  newHistogram->insert(std::make_pair(new te::dt::Double(it->first), it->second));
983  }
984 
986  const std::complex<double>* cmin = rsMin->at(static_cast<size_t>(propId)).m_minVal;
987 
988  newHistogram->setMinValue(cmin->real());
989  newHistogram->setSummarized(false);
990  }
991  else
992  {
993  int propType = dataset->getPropertyDataType(static_cast<size_t>(propId));
994  newHistogram->setType(propType);
995 
996  //The vector containing the frequency of each interval, will be used to every property type
997  std::vector< unsigned int> frequencies;
998 
999  if(propType == te::dt::DATETIME_TYPE || propType == te::dt::STRING_TYPE)
1000  {
1001  std::set <std::string> intervals;
1002  std::set <std::string>::iterator intervalsIt;
1003  std::map<std::string, std::vector<te::da::ObjectId*> > valuesIdsByinterval;
1004  std::vector<te::da::ObjectId*> valuesOIds;
1005 
1006  //Acquiring the name of the base dataset and how many properties are included in it's primary key
1007  std::pair<std::string, int> dsProps;
1008  te::da::GetOIDDatasetProps(dataType.get(), dsProps);
1009 
1010  //A map containg the summarized values used to build the histogram
1011  std::map<std::string, std::vector<std::pair<std::string, te::da::ObjectId*> > > valuesToSummarize;
1012 
1013  //Adjusting the histogram's intervals
1014  dataset->moveBeforeFirst();
1015  while(dataset->moveNext())
1016  {
1017 
1018  if(dataset->isNull(static_cast<size_t>(propId)))
1019  continue;
1020 
1021  if(!task.isActive())
1022  {
1023  break;
1024  }
1025 
1026  std::string interval = dataset->getString(static_cast<size_t>(propId));
1027 
1028  //Every unique string will be an interval
1029  intervals.insert(interval);
1030  task.pulse();
1031  }
1032 
1033  for (intervalsIt = intervals.begin(); intervalsIt != intervals.end(); ++intervalsIt)
1034  {
1035  valuesIdsByinterval.insert(make_pair((*intervalsIt), valuesOIds));
1036  }
1037 
1038  frequencies.resize(intervals.size(), 0);
1039  dataset->moveBeforeFirst();
1040  newHistogram->setStringInterval(intervals);
1041 
1042  //Adjusting the Histogram's values
1043  while(dataset->moveNext())
1044  {
1045 
1046  if(dataset->isNull(static_cast<size_t>(propId)))
1047  continue;
1048 
1049  if(!task.isActive())
1050  {
1051  break;
1052  }
1053 
1054  std::string currentValue = dataset->getString(static_cast<size_t>(propId));
1055  te::da::ObjectId* currentOid = getObjectId(dataset.get(), objIdIdx);
1056  valuesToSummarize[te::da::getBasePkey(currentOid, dsProps)].push_back(std::make_pair(currentValue, currentOid));
1057 
1058  task.pulse();
1059  }
1060 
1061  buildStringFrequencies(stat, valuesToSummarize, valuesIdsByinterval, frequencies);
1062 
1063  //With both the intervals and values ready, the map can be populated
1064  int i;
1065  for (i= 0, intervalsIt = intervals.begin(); intervalsIt != intervals.end(); ++intervalsIt,++i)
1066  {
1067  te::dt::String* data = new te::dt::String(*intervalsIt);
1068  newHistogram->insert(std::make_pair(data, frequencies[static_cast<size_t>(i)]), valuesIdsByinterval.at(*intervalsIt));
1069  }
1070 
1071  dataset->moveBeforeFirst();
1072  }
1073  }
1074  newHistogram->setSummarized(stat != -1);
1075  return newHistogram;
1076 }
1077 
1079 {
1081  std::unique_ptr<te::da::DataSet> dataset = layer->getData();
1082  int propType = dataset->getPropertyDataType(static_cast<size_t>(propId));
1083 
1084  if(slices <=1)
1085  slices = 2;
1086 
1087  //Creating the histogram and it's chart with the given dataset
1088  if(propType == te::dt::DATETIME_TYPE || propType == te::dt::STRING_TYPE)
1089  chart = new te::qt::widgets::HistogramChart(te::qt::widgets::createHistogram(layer, propId, stat));
1090  else
1091  chart = new te::qt::widgets::HistogramChart(te::qt::widgets::createHistogram(layer, propId, slices, stat));
1092 
1093  //Creating and adjusting the chart Display's style.
1095  chartStyle->setTitle(QString::fromUtf8("Histogram"));
1096  chartStyle->setAxisX(QString::fromUtf8(dataset->getPropertyName(static_cast<size_t>(propId)).c_str()));
1097  chartStyle->setAxisY(QString::fromUtf8("Frequency"));
1098 
1099  //Creating and adjusting the chart Display
1100  te::qt::widgets::ChartDisplay* chartDisplay = new te::qt::widgets::ChartDisplay(nullptr, QString::fromUtf8("Histogram"), chartStyle);
1101  chartDisplay->adjustDisplay();
1102  chart->attach(chartDisplay);
1103 
1104  //Adjusting the chart widget
1106  displayWidget->show();
1107  displayWidget->setWindowTitle("Histogram");
1108  return displayWidget;
1109 }
1110 
1112 {
1114  chart = new te::qt::widgets::HistogramChart(histogram);
1115  std::unique_ptr<te::da::DataSet> dataset = layer->getData();
1116 
1117  //Creating and adjusting the chart Display's style.
1119  chartStyle->setTitle(QString::fromUtf8("Histogram"));
1120  chartStyle->setAxisX(QString::fromUtf8((summary + ": " + dataset->getPropertyName(static_cast<size_t>(propId))).c_str()));
1121  chartStyle->setAxisY(QString::fromUtf8("Frequency"));
1122 
1123  //Creating and adjusting the chart Display
1124  te::qt::widgets::ChartDisplay* chartDisplay = new te::qt::widgets::ChartDisplay(nullptr, QString::fromUtf8("Histogram"), chartStyle);
1125  chartDisplay->adjustDisplay();
1126  chart->attach(chartDisplay);
1127 
1128  //Adjusting the chart widget
1130  displayWidget->show();
1131  displayWidget->setWindowTitle("Histogram");
1132  return displayWidget;
1133 }
1134 
1135 void te::qt::widgets::exportChart(QwtPlotItem* plotItem, te::qt::widgets::ChartStyle* style, std::string filepath)
1136 {
1137  try {
1138  //Data to be exported
1139  std::unique_ptr<te::mem::DataSet> memDs;
1140  std::unique_ptr<te::da::DataSetType> dt;
1141 
1142  //Checking the type of data to export
1143  if (plotItem->rtti() == te::qt::widgets::HISTOGRAM_CHART)
1144  {
1145  te::qt::widgets::Histogram* histogram = static_cast<te::qt::widgets::HistogramChart*>(plotItem)->getHistogram();
1146  int propType = histogram->getType();
1147 
1148  if (propType == te::dt::DATETIME_TYPE || propType == te::dt::STRING_TYPE)
1149  {
1150  //Values to export
1151  std::map<std::string, unsigned int> histValues;
1152  histValues = histogram->getStringValues();
1153 
1154  dt.reset(new te::da::DataSetType(style->getTitle().toStdString()));
1155  te::dt::SimpleProperty* xProp = new te::dt::SimpleProperty(style->getAxisX().toStdString(), te::dt::STRING_TYPE, true);
1156  te::dt::SimpleProperty* yProp = new te::dt::SimpleProperty(style->getAxisY().toStdString(), te::dt::INT32_TYPE, true);
1157  dt->add(xProp);
1158  dt->add(yProp);
1159 
1160  memDs.reset(new te::mem::DataSet(dt.get()));
1161  std::map<std::string, unsigned int>::iterator histIt = histValues.begin();
1162  std::map<std::string, unsigned int>::iterator histItEndt = histValues.end();
1163 
1164  while (histIt != histItEndt)
1165  {
1166  te::mem::DataSetItem* dsItem = new te::mem::DataSetItem(memDs.get());
1167  dsItem->setString(0, histIt->first); //x
1168  dsItem->setInt32(1, static_cast<boost::int32_t>(histIt->second)); //y
1169  memDs->add(dsItem);
1170  histIt++;
1171  }
1172  }
1173  else
1174  {
1175  //Values to export
1176  std::map<double, unsigned int> histValues;
1177  histValues = histogram->getValues();
1178 
1179  dt.reset(new te::da::DataSetType(style->getTitle().toStdString()));
1180  te::dt::SimpleProperty* xProp = new te::dt::SimpleProperty(style->getAxisX().toStdString(), te::dt::DOUBLE_TYPE, true);
1181  te::dt::SimpleProperty* yProp = new te::dt::SimpleProperty(style->getAxisY().toStdString(), te::dt::INT32_TYPE, true);
1182  dt->add(xProp);
1183  dt->add(yProp);
1184 
1185  memDs.reset(new te::mem::DataSet(dt.get()));
1186  std::map<double, unsigned int>::iterator histIt = histValues.begin();
1187  std::map<double, unsigned int>::iterator histItEndt = histValues.end();
1188 
1189  while (histIt != histItEndt)
1190  {
1191  te::mem::DataSetItem* dsItem = new te::mem::DataSetItem(memDs.get());
1192  dsItem->setDouble(0, histIt->first); //x
1193  dsItem->setInt32(1, static_cast<boost::int32_t>(histIt->second)); //y
1194  memDs->add(dsItem);
1195  histIt++;
1196  }
1197  }
1198 
1199  std::unique_ptr<te::da::DataSource> dsOGR = te::da::DataSourceFactory::make("OGR", ("file://" + filepath));
1200  te::da::Create(dsOGR.get(), dt.get(), memDs.get());
1201  }
1202  else if (plotItem->rtti() == te::qt::widgets::SCATTER_CHART)
1203  {
1204  //Values to export
1205  std::vector<double> scatXValues, scatYValues;
1206 
1207  scatXValues = static_cast<te::qt::widgets::ScatterChart*>(plotItem)->getScatter()->getXValues();
1208  scatYValues = static_cast<te::qt::widgets::ScatterChart*>(plotItem)->getScatter()->getYValues();
1209 
1210  std::unique_ptr<te::da::DataSetType> dt(new te::da::DataSetType(style->getTitle().toStdString()));
1211  te::dt::SimpleProperty* xProp = new te::dt::SimpleProperty(style->getAxisX().toStdString(), te::dt::DOUBLE_TYPE, true);
1212  te::dt::SimpleProperty* yProp = new te::dt::SimpleProperty(style->getAxisY().toStdString(), te::dt::DOUBLE_TYPE, true);
1213  dt->add(xProp);
1214  dt->add(yProp);
1215 
1216  std::unique_ptr<te::mem::DataSet> memDs((new te::mem::DataSet(dt.get())));
1217  for (size_t i = 0; i < scatXValues.size(); ++i)
1218  {
1219  te::mem::DataSetItem* dsItem = new te::mem::DataSetItem(memDs.get());
1220  dsItem->setDouble(0, scatXValues[i]); //x
1221  dsItem->setDouble(1, scatYValues[i]); //y
1222  memDs->add(dsItem);
1223  }
1224 
1225  std::unique_ptr<te::da::DataSource> dsOGR = te::da::DataSourceFactory::make("OGR", ("file://" + filepath));
1226  te::da::Create(dsOGR.get(), dt.get(), memDs.get());
1227  }
1228  else
1229  throw te::common::Exception(TE_TR("This function is not supported on this chart type."));
1230  }
1231  catch (te::common::Exception& e)
1232  {
1233  throw e;
1234  }
1235  catch (const std::exception& e)
1236  {
1237  throw e;
1238  }
1239  catch (...)
1240  {
1241  throw te::common::Exception(TE_TR("Unknown error occurred."));
1242  }
1243 }
1244 
1245 QwtText* te::qt::widgets::Terralib2Qwt(const std::string& text)
1246 {
1247  QwtText* result = new QwtText(text.c_str());
1248  result->setBackgroundBrush(QBrush(QColor(0, 255, 0)));
1249  result->setBorderPen(QPen(Qt::red, 3, Qt::SolidLine));
1250  return result;
1251 }
1252 
1253 QwtText* te::qt::widgets::Terralib2Qwt(const std::string& text, te::color::RGBAColor* /*color*/,
1254  te::se::Font* /*font*/, te::se::Fill* /*backFill*/,
1255  te::se::Stroke* /*backStroke*/)
1256 {
1257  QwtText* result = new QwtText(QString(text.c_str()));
1258 
1259  return result;
1260 }
1261 
1263 {
1264  //Default symbol used in case the Graphic is not completely populated.
1265  QwtSymbol* symbol = new QwtSymbol( QwtSymbol::Ellipse, QBrush( Qt::yellow ), QPen( Qt::red, 2 ), QSize( 8, 8 ));
1266 
1267  //Default size and width for the symbols
1268  size_t height = 8, width = 8;
1269 
1270  //Adjusting the size if the user changed it
1271  if(graphic->getSize())
1272  {
1273  height = static_cast<size_t>(te::se::GetInt(graphic->getSize()));
1274  width = height;
1275  }
1276 
1277  /*Image that will be used to generate the symbol's pixmap,
1278  it can be either from a mark or from an external graphic, whichever is valid.
1279  */
1280  te::color::RGBAColor** image;
1281  QImage* qimg;
1282  QPixmap pixmap;
1283 
1284  if (!graphic->getMarks().empty())
1285  {
1286  image = te::map::MarkRendererManager::getInstance().render(graphic->getMarks()[0], height);
1287  qimg = te::qt::widgets::GetImage(image, static_cast<int>(height), static_cast<int>(width));
1288  }
1289  else
1290  {
1291  image = te::map::ExternalGraphicRendererManager::getInstance().render(graphic->getExternalGraphics()[0], height, width);
1292  qimg = new QImage(static_cast<int>(width), static_cast<int>(height), QImage::Format_ARGB32);
1293 
1294  for (int i = 0; i < static_cast<int>(height); ++i)
1295  {
1296  unsigned char* u = qimg->scanLine(i);
1297 
1298  for (int j = 0; j < static_cast<int>(width); ++j)
1299  {
1300  te::color::RGBAColor c = image[i][j];
1301  QRgb val = qRgba(c.getRed(), c.getGreen(), c.getBlue(), c.getAlpha());
1302  QRgb* v = reinterpret_cast<QRgb*>(u + j * 4);
1303  *v = val;
1304  }
1305  }
1306  }
1307 
1308  pixmap = QPixmap::fromImage(*qimg);
1309 
1310  //Adjusting the symbol
1311  symbol->setPixmap(pixmap);
1312  symbol->setSize(static_cast<int>(width), static_cast<int>(height));
1313 
1314  delete image;
1315  delete qimg;
1316 
1317  return symbol;
1318 }
1319 
1321 {
1323  task.setMessage("Histogram creation");
1324  task.setTotalSteps(static_cast<int>(dataset->getNumProperties()));
1325 
1326  QwtPlotCurve *baseCurve = new QwtPlotCurve("Base Values");
1327  baseCurve->setOrientation( Qt::Horizontal );
1328 
1329  QwtPlotCurve *normalCurve = new QwtPlotCurve("Normalizeed Values");
1330  normalCurve->setOrientation( Qt::Horizontal );
1331 
1332  int propType = dataset->getPropertyDataType(static_cast<size_t>(propId));
1333  if(propType >= te::dt::INT16_TYPE && propType <= te::dt::NUMERIC_TYPE)
1334  {
1336  std::vector<double> xValues = te::stat::GetNumericData(dataset, dataset->getPropertyName(static_cast<size_t>(propId)));
1337  std::vector<double> yValues;
1339 
1340  // Normalize the selected variable
1341  for(int i = 0; i < nss.m_count; ++i)
1342  {
1343  double curXValue = xValues[static_cast<size_t>(i)];
1344  curXValue = (curXValue - nss.m_mean) / nss.m_stdDeviation;
1345  xValues[static_cast<size_t>(i)] = curXValue;
1346  }
1347  std::sort(xValues.begin(), xValues.end());
1348 
1349  //// Fill the vector of the probability
1350  for(int i = 0; i < nss.m_count; ++i)
1351  {
1352  double curYValue = xValues[static_cast<size_t>(i)];
1353  if (curYValue > 0.)
1354  curYValue = 0.5 + (errFunction ((float)(curYValue/std::sqrt(2.)))/2.);
1355  else
1356  {
1357  curYValue = -curYValue;
1358  curYValue = 0.5 - (errFunction ((float)(curYValue/std::sqrt(2.)))/2.);
1359  }
1360  yValues.push_back(curYValue);
1361  }
1362 
1363  QVector<QPointF> samples, normalSamples;
1364  for (int i = 0; i < nss.m_count; ++i)
1365  {
1366  double val = (static_cast<double>(i)+static_cast<double>(1.0))/static_cast<double>(nss.m_count);
1367  normalSamples += QPointF( val, val);
1368  samples += QPointF( val, yValues[static_cast<size_t>(i)]);
1369  }
1370 
1371  baseCurve->setSamples(samples);
1372  normalCurve->setSamples(normalSamples);
1373  }
1374 
1375  QPen normalCurvePen;
1376  normalCurvePen.setColor(QColor(Qt::green));
1377  normalCurvePen.setStyle(Qt::SolidLine);
1378  normalCurvePen.setWidth(0);
1379  baseCurve->setPen(normalCurvePen);
1380 
1381  QPen normalProbCurvePen;
1382  normalProbCurvePen.setColor(QColor(Qt::red));
1383  normalProbCurvePen.setStyle(Qt::SolidLine);
1384  normalProbCurvePen.setWidth(0);
1385  normalCurve->setPen(normalProbCurvePen);
1386 
1387  //Creating and adjusting the chart Display's style.
1389  chartStyle->setTitle(QString::fromUtf8(("Normal Probability: " + dataset->getPropertyName(static_cast<size_t>(propId))).c_str()));
1390  chartStyle->setAxisX(QString::fromUtf8(dataset->getPropertyName(static_cast<size_t>(propId)).c_str()));
1391  chartStyle->setAxisY(QString::fromUtf8("Probability"));
1392  chartStyle->setGridChecked(true);
1393 
1394  //Creating and adjusting the chart Display
1395  te::qt::widgets::ChartDisplay* chartDisplay = new te::qt::widgets::ChartDisplay(nullptr, QString::fromUtf8("Normal Distribution"), chartStyle);
1396  chartDisplay->adjustDisplay();
1397  baseCurve->attach(chartDisplay);
1398  normalCurve->attach(chartDisplay);
1399 
1400  //Adjusting the chart widget
1401  te::qt::widgets::ChartDisplayWidget* displayWidget = new te::qt::widgets::ChartDisplayWidget(normalCurve, normalCurve->rtti(), chartDisplay);
1402  displayWidget->setWindowTitle("Normal Distribution");
1403  return displayWidget;
1404 }
te::da::ObjectId * getObjectId(te::da::DataSet *dataset, std::vector< std::size_t > pkeys)
TEQTWIDGETSEXPORT ChartDisplayWidget * createNormalDistribution(te::da::DataSet *dataset, int propId)
TEQTWIDGETSEXPORT Scatter * createScatter(te::da::DataSet *dataset, te::da::DataSetType *dataType, int propX, int propY, int stat, bool readall=true)
Scatter Creator.
QString & getAxisX()
Returns a reference to the style&#39;s x axis label.
Definition: ChartStyle.cpp:86
static std::unique_ptr< DataSource > make(const std::string &driver, const te::core::URI &connInfo)
SimpleData< std::string, STRING_TYPE > String
Definition: SimpleData.h:229
A structure to hold the set of statistics from a set of numerical values.
void setMessage(const std::string &message)
Set the task message.
virtual double getDouble(std::size_t i) const =0
Method for retrieving a double attribute value.
void adjustDisplay()
Updates the general display settings according to the ChartStyle. The adjusted properties are: Title;...
void setDouble(std::size_t i, double value)
It sets the value of the i-th property.
An atomic property like an integer or double.
void addY(double &yValue)
It adds a new value to the vector containing the Y axis values.
Definition: Scatter.cpp:177
TEDATAACCESSEXPORT ObjectId * GenerateOID(DataSet *dataset, const std::vector< std::string > &names)
This is the base class for layers.
Definition: AbstractLayer.h:77
void buildStringFrequencies(int stat, std::map< std::string, std::vector< std::pair< std::string, te::da::ObjectId * > > > valuestoSummarize, std::map< std::string, std::vector< te::da::ObjectId * > > &intervalToOIds, std::vector< unsigned int > &frequencies)
int getRed() const
It returns the red component color value (a value from 0 to 255).
Definition: RGBAColor.h:307
QString & getAxisY()
Returns a reference to the style&#39;s y axis label.
Definition: ChartStyle.cpp:96
const std::vector< ExternalGraphic * > getExternalGraphics() const
Definition: Graphic.cpp:76
virtual std::unique_ptr< te::rst::Raster > getRaster(std::size_t i) const =0
Method for retrieving a raster attribute value.
TEQTWIDGETSEXPORT QwtText * Terralib2Qwt(const std::string &title)
A class that models the description of a dataset.
Definition: DataSetType.h:72
void attach(QwtPlot *plot)
It atttaches a QwtPlot to this Cahrt.
virtual std::string getNumeric(std::size_t i) const =0
Method for retrieving a numeric attribute value.
virtual float getFloat(std::size_t i) const =0
Method for retrieving a float attribute value.
std::string getStatisticalValue(int stat, te::stat::StringStatisticalSummary &sss)
TEQTWIDGETSEXPORT Histogram * createHistogram(te::map::AbstractLayerPtr layer, int propId, int slices, int stat, bool readall=true)
Histogram Creator.
virtual DateTimeType getDateTimeType() const =0
It returns the subtype of the date and time type.
unsigned int getColumn() const
Returns the current column in iterator.
void setGridChecked(bool newGridChecked)
It sets the boolean used to decided weather to display the grid or not.
Definition: ChartStyle.cpp:155
TEQTWIDGETSEXPORT ChartDisplayWidget * createHistogramDisplay(te::map::AbstractLayer *layer, int propId, int slices=10, int stat=-1)
Histogram Creator.
This class can be used to inform the progress of a task.
Definition: TaskProgress.h:53
TEQTWIDGETSEXPORT void exportChart(QwtPlotItem *plotItem, te::qt::widgets::ChartStyle *style, std::string filepath)
Function that exports a chart&#39;s data to a .csv file.
int getBlue() const
It returns the blue component color value (a value from 0 to 255).
Definition: RGBAColor.h:317
int getGreen() const
It returns the green component color value (a value from 0 to 255).
Definition: RGBAColor.h:312
static PointSetIterator end(const te::rst::Raster *r, const std::vector< te::gm::Point * > p)
Returns an iterator referring to after the end of the iterator.
#define TE_TR(message)
It marks a string in order to get translated.
Definition: Translator.h:242
A Graphic is a graphic symbol with an inherent shape, color(s), and possibly size.
Definition: Graphic.h:66
A class to represent a Histogram.
Definition: Histogram.h:56
TEDATAACCESSEXPORT void GetOIDDatasetProps(const DataSetType *type, std::pair< std::string, int > &dsProps)
void buildNumericFrequencies(int slices, int stat, std::map< std::string, std::vector< std::pair< double, te::da::ObjectId * > > > valuestoSummarize, std::vector< double > &intervals, std::map< double, std::vector< te::da::ObjectId * > > &intervalToOIds, std::vector< unsigned int > &frequencies, double &minValue, double &interval)
void gser(float *gamser, float a, float x, float *gln)
void setTitle(QString newTitle)
It sets the style&#39;s title.
Definition: ChartStyle.cpp:71
QString & getTitle()
Returns a reference to the style&#39;s Title.
Definition: ChartStyle.cpp:66
bool isActive() const
Verify if the task is active.
This class implements the strategy to iterate with spatial restriction, the iteration occurs inside a...
void setTotalSteps(int value)
Set the task total stepes.
TESTATEXPORT std::vector< double > GetNumericData(te::da::DataSet *dataSet, const std::string propName)
Returns the values of a numeric type property in a vector of values.
A class to represent a histogram.
float errFunction(float x)
void setStringInterval(std::set< std::string > new_Interval)
It sets the histogram&#39;s string set of intervals.
Definition: Histogram.cpp:120
TEQTWIDGETSEXPORT ChartDisplayWidget * createScatterDisplay(te::da::DataSet *dataset, te::da::DataSetType *dataType, int propX, int propY, int stat=-1)
Scatter Creator.
void setInt32(std::size_t i, boost::int32_t value)
It sets the value of the i-th property.
virtual bool moveNext()=0
It moves the internal pointer to the next item of the collection.
Implementation of a random-access dataset class for the TerraLib In-Memory Data Access driver...
void buildSummarizedScatter(int stat, std::map< std::string, std::vector< te::da::ObjectId * > > oidsToSummarize, std::map< std::string, std::vector< std::pair< double, double > > > valuesToSummarize, te::qt::widgets::Scatter *scatter)
A class to represent a scatter.
Definition: Scatter.h:51
virtual boost::int16_t getInt16(std::size_t i) const =0
Method for retrieving a 16-bit integer attribute value (2 bytes long).
static RasterSummaryManager & getInstance()
It returns a reference to the singleton instance.
virtual int getPropertyDataType(std::size_t i) const =0
It returns the underlying data type of the property at position pos.
float gammp(float a, float x)
TEDATAACCESSEXPORT void Create(DataSource *ds, DataSetType *dt, DataSet *d, std::size_t limit=0)
It creates the dataset definition in a data source and then fill it with data from the input dataset...
void setAxisY(QString newAxisY)
It sets the style&#39;s y axis label.
Definition: ChartStyle.cpp:101
This class represents an unique id for a data set element.
void addX(double &xValue)
It adds a new value to the vector containing the X axis values.
Definition: Scatter.cpp:172
virtual boost::int32_t getInt32(std::size_t i) const =0
Method for retrieving a 32-bit integer attribute value (4 bytes long).
void setSummarized(bool summarized)
It sets the property that holds whether the histogram has been created from summarized values or not...
Definition: Histogram.cpp:57
static te::dt::DateTime d(2010, 8, 9, 15, 58, 39)
static te::dt::TimeDuration dt(20, 30, 50, 11)
A Font specifies the text font to use in a text symbolizer.
Definition: Font.h:63
int getAlpha() const
It returns the alpha component color value (a value from 0 to 255).
Definition: RGBAColor.h:322
A class to represent a chart display.
Definition: ChartDisplay.h:65
void getObjectIds(te::da::DataSet *dataset, std::vector< std::size_t > pkeys, std::vector< te::da::ObjectId * > &valuesOIDs)
std::map< std::string, unsigned int > getStringValues()
It returns the map containing the histogram String values. The key is a unique string that represents...
Definition: Histogram.cpp:86
boost::ptr_vector< BandSummary > RasterSummary
RasterSummary is just a typedef of a boost::ptr_vector.
Definition: RasterSummary.h:44
void setAxisX(QString newAxisX)
It sets the style&#39;s x axis label.
Definition: ChartStyle.cpp:91
TESTATEXPORT void GetNumericStatisticalSummary(std::vector< double > &values, te::stat::NumericStatisticalSummary &ss, double nullValue)
A class to represent a histogram chart.
void pulse()
Calls setCurrentStep() function using getCurrentStep() + 1.
A Fill specifies the pattern for filling an area geometry.
Definition: Fill.h:59
void setInterval(double new_Interval)
It sets the histogram&#39;s interval.
Definition: Histogram.cpp:110
A class to represent a scatter chart.
Definition: ScatterChart.h:55
Utility functions for the data access module.
A class to represent a scatter&#39;s chart.
This class is designed to declare objects to be thrown as exceptions by TerraLib. ...
A class to represent a scatter.
std::map< double, unsigned int > getValues()
It returns the map containing the histogram values. The key is the minimum values of the histogram&#39;s ...
Definition: Histogram.cpp:62
virtual std::unique_ptr< te::dt::DateTime > getDateTime(std::size_t i) const =0
Method for retrieving a date and time attribute value.
TESTATEXPORT void GetStringStatisticalSummary(std::vector< std::string > &values, te::stat::StringStatisticalSummary &ss, const std::string &nullValue)
An implementation of the DatasetItem class for the TerraLib In-Memory Data Access driver...
TEMAPEXPORT te::rst::Raster * GetRaster(AbstractLayer *layer)
It gets the raster referenced by the given data set layer.
A dataset is the unit of information manipulated by the data access module of TerraLib.
A wdiget used to display a chart.
const std::vector< Mark * > getMarks() const
Definition: Graphic.cpp:98
TEDATAACCESSEXPORT void GetOIDPropertyPos(const DataSetType *type, std::vector< std::size_t > &ppos)
virtual std::unique_ptr< te::da::DataSet > getData(te::common::TraverseType travType=te::common::FORWARDONLY, const te::common::AccessPolicy accessPolicy=te::common::RAccess) const =0
It gets the dataset identified by the layer name.
double getDouble(const std::string &value, std::vector< std::string > &sVector)
TEQTWIDGETSEXPORT QImage * GetImage(te::color::RGBAColor **img, int width, int height)
It creates a QImage from an RGBA color array.
void gcf(float *gammcf, float a, float x, float *gln)
A Stroke specifies the appearance of a linear geometry.
Definition: Stroke.h:67
A structure to hold the set of statistics from a set of categorical (sample) values.
SimpleData< double, DOUBLE_TYPE > Double
Definition: SimpleData.h:227
void setMinValue(double new_minValue)
It sets the histogram&#39;s minimum value.
Definition: Histogram.cpp:100
A helper class for 32-bit RGBA (Red-Green-Blue-Alpha channel) color.
Definition: RGBAColor.h:57
TESEEXPORT int GetInt(const te::se::ParameterValue *param)
It gets the parameter value as an integer.
float gammln(float xx)
void calculateMinMaxValues()
Calculates the minimum and maximum values for both the X and Y axis.
Definition: Scatter.cpp:59
TEDATAACCESSEXPORT std::string getBasePkey(te::da::ObjectId *oid, std::pair< std::string, int > &dsProps)
A widget used to display a set of charts.
TERASTEREXPORT std::vector< te::gm::Point * > GetRandomPointsInRaster(const te::rst::Raster &inputRaster, unsigned int numberOfPoints=1000)
Creates a vector of random positions (points) inside the raster.
void insert(std::pair< te::dt::AbstractData *, unsigned int > new_value, std::vector< te::da::ObjectId * > valuesOIds)
It adds a new value to the map containing the histogram values.
Definition: Histogram.cpp:125
virtual bool isNull(std::size_t i) const =0
It checks if the attribute value is NULL.
A class used to define a chartDisplay&#39;s style.
virtual boost::int64_t getInt64(std::size_t i) const =0
Method for retrieving a 64-bit integer attribute value (8 bytes long).
TEDATAACCESSEXPORT std::size_t GetFirstPropertyPos(const te::da::DataSet *dataset, int datatype)
A template for atomic data types (integers, floats, strings and others).
Definition: SimpleData.h:59
void setString(std::size_t i, const std::string &value)
It sets the value of the i-th property.
virtual std::size_t getNumProperties() const =0
It returns the number of properties that composes an item of the dataset.
virtual std::string getPropertyName(std::size_t i) const =0
It returns the property name at position pos.
Calculate the min value.
void addData(double &xValue, double &yValue, te::da::ObjectId *oid)
It adds the x and Y axis values to the scatter&#39;s vectors and the associeted objectId to the scatter&#39;s...
Definition: Scatter.cpp:182
A class to represent a chart display.
boost::intrusive_ptr< AbstractLayer > AbstractLayerPtr
int & getType()
It returns the histogram&#39;s type.
Definition: Histogram.cpp:42
const ParameterValue * getSize() const
Definition: Graphic.cpp:120
unsigned int getRow() const
Returns the current row in iterator.
void setType(int new_type)
It sets the histogram&#39;s type.
Definition: Histogram.cpp:47
static PointSetIterator begin(const te::rst::Raster *r, const std::vector< te::gm::Point * > p)
Returns an iterator referring to the first value of the band.