vtkPlotBag.cxx 13.4 KB
Newer Older
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
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkPlotBag.cxx

  Copyright (c) Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/

#include "vtkBrush.h"
#include "vtkContext2D.h"
#include "vtkContextMapper2D.h"
#include "vtkDataArray.h"
#include "vtkDoubleArray.h"
#include "vtkObjectFactory.h"
#include "vtkPen.h"
#include "vtkPlotBag.h"
#include "vtkPoints.h"
#include "vtkPoints2D.h"
#include "vtkPointsProjectedHull.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTimeStamp.h"
Joachim Pouderoux's avatar
Joachim Pouderoux committed
30
#include "vtkMath.h"
31 32

#include <algorithm>
Joachim Pouderoux's avatar
Joachim Pouderoux committed
33
#include <sstream>
34 35 36 37

//-----------------------------------------------------------------------------
vtkStandardNewMacro(vtkPlotBag);

38 39
vtkSetObjectImplementationMacro(vtkPlotBag, LinePen, vtkPen);

40 41 42 43 44
//-----------------------------------------------------------------------------
vtkPlotBag::vtkPlotBag()
{
  this->MedianPoints = vtkPoints2D::New();
  this->Q3Points = vtkPoints2D::New();
Joachim Pouderoux's avatar
Joachim Pouderoux committed
45
  this->TooltipDefaultLabelFormat = "%C, %l (%x, %y): %z";
Julien Finet's avatar
Julien Finet committed
46
  this->BagVisible = true;
47 48 49 50 51 52 53
  this->Brush->SetColor(255, 0, 0);
  this->Brush->SetOpacity(255);
  this->Pen->SetColor(0, 0, 0);
  this->Pen->SetWidth(5.f);
  this->LinePen = vtkPen::New();
  this->LinePen->SetColor(0, 0, 0);
  this->LinePen->SetWidth(1.f);
54 55 56 57 58 59 60 61 62 63 64 65 66 67 68
}

//-----------------------------------------------------------------------------
vtkPlotBag::~vtkPlotBag()
{
  if (this->MedianPoints)
    {
    this->MedianPoints->Delete();
    this->MedianPoints = 0;
    }
  if (this->Q3Points)
    {
    this->Q3Points->Delete();
    this->Q3Points = 0;
    }
69 70 71 72 73
  if (this->LinePen)
    {
    this->LinePen->Delete();
    this->LinePen = 0;
    }
74 75 76 77 78 79 80 81 82 83 84 85
}

//-----------------------------------------------------------------------------
void vtkPlotBag::Update()
{
  if (!this->Visible)
    {
    return;
    }

  // Check if we have an input
  vtkTable *table = this->Data->GetInput();
86
  vtkDataArray *density = vtkArrayDownCast<vtkDataArray>(
87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106
    this->Data->GetInputAbstractArrayToProcess(2, this->GetInput()));
  if (!table || !density)
    {
    vtkDebugMacro(<< "Update event called with no input table or density column set.");
    return;
    }
  bool update = (this->Data->GetMTime() > this->BuildTime ||
    table->GetMTime() > this->BuildTime ||
    this->MTime > this->BuildTime);

  this->Superclass::Update();

  if (update)
    {
    vtkDebugMacro(<< "Updating cached values.");
    this->UpdateTableCache(density);
    }
}

//-----------------------------------------------------------------------------
Joachim Pouderoux's avatar
Joachim Pouderoux committed
107
class DensityVal
108 109
{
public:
Joachim Pouderoux's avatar
Joachim Pouderoux committed
110 111
  DensityVal(double d, vtkIdType cid) : Density(d), Id(cid) {}
  bool operator<(const DensityVal& b) const
112
  {
Joachim Pouderoux's avatar
Joachim Pouderoux committed
113
    return this->Density > b.Density;
114
  }
Joachim Pouderoux's avatar
Joachim Pouderoux committed
115 116
  double Density;
  vtkIdType Id;
117 118 119 120 121 122 123 124 125 126 127 128
};

//-----------------------------------------------------------------------------
void vtkPlotBag::UpdateTableCache(vtkDataArray* density)
{
  this->MedianPoints->Reset();
  this->Q3Points->Reset();

  if (!this->Points)
    {
    return;
    }
Joachim Pouderoux's avatar
Joachim Pouderoux committed
129 130
  vtkDataArray* d = density;
  vtkPoints2D* points = this->Points;
131

Joachim Pouderoux's avatar
Joachim Pouderoux committed
132 133 134 135 136 137
  vtkIdType nbPoints = d->GetNumberOfTuples();

  // Fetch and sort arrays according their density
  std::vector<DensityVal> ids;
  ids.reserve(nbPoints);
  for (int i = 0; i < nbPoints; i++)
138
    {
Joachim Pouderoux's avatar
Joachim Pouderoux committed
139
    ids.push_back(DensityVal(d->GetTuple1(i), i));
140
    }
Joachim Pouderoux's avatar
Joachim Pouderoux committed
141
  std::sort(ids.begin(), ids.end());
142 143 144 145 146 147

  vtkNew<vtkPointsProjectedHull> q3Points;
  q3Points->Allocate(nbPoints);
  vtkNew<vtkPointsProjectedHull> medianPoints;
  medianPoints->Allocate(nbPoints);

Joachim Pouderoux's avatar
Joachim Pouderoux committed
148 149 150 151 152 153 154 155
  // Compute total density sum
  double densitySum = 0.0;
  for (vtkIdType i = 0; i < nbPoints; i++)
    {
    densitySum += d->GetTuple1(i);
    }

  double sum = 0.0;
156 157 158
  for (vtkIdType i = 0; i < nbPoints; i++)
    {
    double x[3];
Joachim Pouderoux's avatar
Joachim Pouderoux committed
159 160 161
    points->GetPoint(ids[i].Id, x);
    sum += ids[i].Density;
    if (sum < 0.5 * densitySum)
162 163 164
      {
      medianPoints->InsertNextPoint(x);
      }
Joachim Pouderoux's avatar
Joachim Pouderoux committed
165
    if (sum < 0.99 * densitySum)
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
      {
      q3Points->InsertNextPoint(x);
      }
    else
      {
      break;
      }
    }

  // Compute the convex hull for the median points
  vtkIdType nbMedPoints = medianPoints->GetNumberOfPoints();
  if (nbMedPoints > 2)
    {
    int size = medianPoints->GetSizeCCWHullZ();
    this->MedianPoints->SetDataTypeToFloat();
    this->MedianPoints->SetNumberOfPoints(size+1);
    medianPoints->GetCCWHullZ(
      static_cast<float*>(this->MedianPoints->GetData()->GetVoidPointer(0)), size);
    double x[3];
    this->MedianPoints->GetPoint(0, x);
    this->MedianPoints->SetPoint(size, x);
    }
  else if (nbMedPoints > 0)
    {
    this->MedianPoints->SetNumberOfPoints(nbMedPoints);
    for (int j = 0; j < nbMedPoints; j++)
      {
      double x[3];
      medianPoints->GetPoint(j, x);
      this->MedianPoints->SetPoint(j, x);
      }
    }

  // Compute the convex hull for the first quartile points
  vtkIdType nbQ3Points = q3Points->GetNumberOfPoints();
  if (nbQ3Points > 2)
    {
    int size = q3Points->GetSizeCCWHullZ();
    this->Q3Points->SetDataTypeToFloat();
    this->Q3Points->SetNumberOfPoints(size+1);
    q3Points->GetCCWHullZ(
      static_cast<float*>(this->Q3Points->GetData()->GetVoidPointer(0)), size);
    double x[3];
    this->Q3Points->GetPoint(0, x);
    this->Q3Points->SetPoint(size, x);
    }
  else if (nbQ3Points > 0)
    {
    this->Q3Points->SetNumberOfPoints(nbQ3Points);
    for (int j = 0; j < nbQ3Points; j++)
      {
      double x[3];
      q3Points->GetPoint(j, x);
      this->Q3Points->SetPoint(j, x);
      }
    }

  this->BuildTime.Modified();
}

//-----------------------------------------------------------------------------
bool vtkPlotBag::Paint(vtkContext2D *painter)
{
  vtkDebugMacro(<< "Paint event called in vtkPlotBag.");

  vtkTable *table = this->Data->GetInput();

  if (!this->Visible || !this->Points || !table)
    {
    return false;
    }

Julien Finet's avatar
Julien Finet committed
238
  if (this->BagVisible)
239
    {
Julien Finet's avatar
Julien Finet committed
240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255
    unsigned char bcolor[4];
    this->Brush->GetColor(bcolor);

    // Draw the 2 bags
    this->Brush->SetOpacity(255);
    this->Brush->SetColor(bcolor[0] / 2, bcolor[1] / 2, bcolor[2] / 2);
    painter->ApplyPen(this->LinePen);
    painter->ApplyBrush(this->Brush);
    if (this->Q3Points->GetNumberOfPoints() > 2)
      {
      painter->DrawPolygon(this->Q3Points);
      }
    else if (this->Q3Points->GetNumberOfPoints() == 2)
      {
      painter->DrawLine(this->Q3Points);
      }
256

Julien Finet's avatar
Julien Finet committed
257 258 259
    this->Brush->SetColor(bcolor);
    this->Brush->SetOpacity(128);
    painter->ApplyBrush(this->Brush);
260

Julien Finet's avatar
Julien Finet committed
261 262 263 264 265 266 267 268
    if (this->MedianPoints->GetNumberOfPoints() > 2)
      {
      painter->DrawPolygon(this->MedianPoints);
      }
    else if (this->MedianPoints->GetNumberOfPoints() == 2)
      {
      painter->DrawLine(this->MedianPoints);
      }
269 270
    }

271
  painter->ApplyPen(this->Pen);
272 273 274 275 276 277 278 279

  // Let PlotPoints draw the points as usual
  return this->Superclass::Paint(painter);
}

//-----------------------------------------------------------------------------
bool vtkPlotBag::PaintLegend(vtkContext2D *painter, const vtkRectf& rect, int)
{
280 281 282 283
  painter->ApplyPen(this->LinePen);
  unsigned char bcolor[4];
  this->Brush->GetColor(bcolor);
  unsigned char opacity = this->Brush->GetOpacity();
284 285

  this->Brush->SetOpacity(255);
286
  this->Brush->SetColor(bcolor[0] / 2, bcolor[1] / 2, bcolor[2] / 2);
287
  painter->ApplyBrush(this->Brush);
288
  painter->DrawRect(rect[0], rect[1], rect[2], rect[3]);
289

290 291
  this->Brush->SetColor(bcolor);
  this->Brush->SetOpacity(128);
292 293
  painter->ApplyBrush(this->Brush);
  painter->DrawRect(rect[0] + rect[2] / 2.f, rect[1], rect[2]/2, rect[3]);
294
  this->Brush->SetOpacity(opacity);
295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313

  return true;
}

//-----------------------------------------------------------------------------
vtkStringArray* vtkPlotBag::GetLabels()
{
  // If the label string is empty, return the y column name
  if (this->Labels)
    {
    return this->Labels;
    }
  else if (this->AutoLabels)
    {
    return this->AutoLabels;
    }
  else if (this->Data->GetInput())
    {
    this->AutoLabels = vtkSmartPointer<vtkStringArray>::New();
314
    vtkDataArray *density = vtkArrayDownCast<vtkDataArray>(
315
      this->Data->GetInputAbstractArrayToProcess(2, this->GetInput()));
316 317 318 319
    if (density)
      {
      this->AutoLabels->InsertNextValue(density->GetName());
      }
320 321 322 323 324 325 326 327 328 329 330 331 332 333 334
    return this->AutoLabels;
    }
  return NULL;
}

//-----------------------------------------------------------------------------
vtkStdString vtkPlotBag::GetTooltipLabel(const vtkVector2d &plotPos,
                                         vtkIdType seriesIndex,
                                         vtkIdType)
{
  vtkStdString tooltipLabel;
  vtkStdString &format = this->TooltipLabelFormat.empty() ?
        this->TooltipDefaultLabelFormat : this->TooltipLabelFormat;
  // Parse TooltipLabelFormat and build tooltipLabel
  bool escapeNext = false;
335
  vtkDataArray *density = vtkArrayDownCast<vtkDataArray>(
336 337 338 339 340 341 342 343 344 345 346 347 348 349 350
    this->Data->GetInputAbstractArrayToProcess(2, this->GetInput()));
  for (size_t i = 0; i < format.length(); ++i)
    {
    if (escapeNext)
      {
      switch (format[i])
        {
        case 'x':
          tooltipLabel += this->GetNumber(plotPos.GetX(), this->XAxis);
          break;
        case 'y':
          tooltipLabel += this->GetNumber(plotPos.GetY(), this->YAxis);
          break;
        case 'z':
          tooltipLabel += density ?
351 352
            density->GetVariantValue(seriesIndex).ToString() :
            vtkStdString("?");
353 354 355 356 357 358 359 360 361 362 363 364 365
          break;
        case 'i':
          if (this->IndexedLabels &&
              seriesIndex >= 0 &&
              seriesIndex < this->IndexedLabels->GetNumberOfTuples())
            {
            tooltipLabel += this->IndexedLabels->GetValue(seriesIndex);
            }
          break;
        case 'l':
          // GetLabel() is GetLabel(0) in this implementation
          tooltipLabel += this->GetLabel();
          break;
Joachim Pouderoux's avatar
Joachim Pouderoux committed
366 367 368 369 370 371 372 373 374
        case 'c':
          {
          std::stringstream ss;
          ss << seriesIndex;
          tooltipLabel += ss.str();
          }
          break;
        case 'C':
          {
375
          vtkAbstractArray *colName = vtkArrayDownCast<vtkAbstractArray>(
Joachim Pouderoux's avatar
Joachim Pouderoux committed
376 377
            this->GetInput()->GetColumnByName("ColName"));
          std::stringstream ss;
378 379 380 381 382 383 384 385
          if (colName)
            {
            ss << colName->GetVariantValue(seriesIndex).ToString();
            }
          else
            {
            ss << "?";
            }
Joachim Pouderoux's avatar
Joachim Pouderoux committed
386 387 388
          tooltipLabel += ss.str();
          }
          break;
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
        default: // If no match, insert the entire format tag
          tooltipLabel += "%";
          tooltipLabel += format[i];
          break;
        }
      escapeNext = false;
      }
    else
      {
      if (format[i] == '%')
        {
        escapeNext = true;
        }
      else
        {
        tooltipLabel += format[i];
        }
      }
    }
  return tooltipLabel;
}

//-----------------------------------------------------------------------------
void vtkPlotBag::SetInputData(vtkTable *table)
{
  this->Data->SetInputData(table);
  this->Modified();
}

//-----------------------------------------------------------------------------
void vtkPlotBag::SetInputData(vtkTable *table, const vtkStdString &yColumn,
                              const vtkStdString &densityColumn)
{
  vtkDebugMacro(<< "Setting input, Y column = \"" << yColumn.c_str() << "\", "
                << "Density column = \"" << densityColumn.c_str() << "\"");

  if (table->GetColumnByName(densityColumn.c_str())->GetNumberOfTuples()
    != table->GetColumnByName(yColumn.c_str())->GetNumberOfTuples())
    {
    vtkErrorMacro(<< "Input table not correctly initialized!");
    return;
    }

  this->SetInputData(table, yColumn, yColumn, densityColumn);
  this->UseIndexForXSeries = true;
}

//-----------------------------------------------------------------------------
void vtkPlotBag::SetInputData(vtkTable *table, const vtkStdString &xColumn,
                              const vtkStdString &yColumn,
                              const vtkStdString &densityColumn)
{
  vtkDebugMacro(<< "Setting input, X column = \"" << xColumn.c_str()
                << "\", " << "Y column = \""
                << yColumn.c_str() << "\""
                << "\", " << "Density column = \""
                << densityColumn.c_str() << "\"");

  this->Data->SetInputData(table);
  this->Data->SetInputArrayToProcess(0, 0, 0,
    vtkDataObject::FIELD_ASSOCIATION_ROWS, xColumn.c_str());
  this->Data->SetInputArrayToProcess(1, 0, 0,
    vtkDataObject::FIELD_ASSOCIATION_ROWS, yColumn.c_str());
  this->Data->SetInputArrayToProcess(2, 0, 0,
    vtkDataObject::FIELD_ASSOCIATION_ROWS, densityColumn.c_str());
Joachim Pouderoux's avatar
Joachim Pouderoux committed
454 455 456 457
  if (this->AutoLabels)
    {
    this->AutoLabels = 0;
    }
458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475
}

//-----------------------------------------------------------------------------
void vtkPlotBag::SetInputData(vtkTable *table, vtkIdType xColumn,
                              vtkIdType yColumn,
                              vtkIdType densityColumn)
{
  this->SetInputData(table,
    table->GetColumnName(xColumn),
    table->GetColumnName(yColumn),
    table->GetColumnName(densityColumn));
}

//-----------------------------------------------------------------------------
void vtkPlotBag::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
}