File: vtkHeatmapItem.cxx

package info (click to toggle)
vtk7 7.1.1%2Bdfsg2-8
  • links: PTS, VCS
  • area: main
  • in suites: bullseye
  • size: 127,396 kB
  • sloc: cpp: 1,539,584; ansic: 124,382; python: 78,038; tcl: 47,013; xml: 8,142; yacc: 5,040; java: 4,439; perl: 3,132; lex: 1,926; sh: 1,500; makefile: 126; objc: 83
file content (1280 lines) | stat: -rw-r--r-- 38,594 bytes parent folder | download | duplicates (3)
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
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkHeatmapItem.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 "vtkHeatmapItem.h"

#include "vtkBitArray.h"
#include "vtkBrush.h"
#include "vtkCategoryLegend.h"
#include "vtkColorLegend.h"
#include "vtkColorSeries.h"
#include "vtkContext2D.h"
#include "vtkContextMouseEvent.h"
#include "vtkContextScene.h"
#include "vtkFieldData.h"
#include "vtkIntArray.h"
#include "vtkLookupTable.h"
#include "vtkNew.h"
#include "vtkObjectFactory.h"
#include "vtkPen.h"
#include "vtkRect.h"
#include "vtkStringArray.h"
#include "vtkTable.h"
#include "vtkTextProperty.h"
#include "vtkTooltipItem.h"
#include "vtkTransform2D.h"
#include "vtkVariantArray.h"

#include <sstream>

vtkStandardNewMacro(vtkHeatmapItem);

//-----------------------------------------------------------------------------
vtkHeatmapItem::vtkHeatmapItem() : PositionVector(0, 0)
{
  this->Position = this->PositionVector.GetData();
  this->Interactive = true;
  this->HeatmapBuildTime = 0;
  this->Table = vtkSmartPointer<vtkTable>::New();
  this->NameColumn = "name";
  this->RowNames = NULL;

  this->CollapsedRowsArray = NULL;
  this->CollapsedColumnsArray = NULL;

  /* initialize bounds so that the mouse cursor is never considered
   * "inside" the heatmap */
  this->MinX = 1.0;
  this->MinY = 1.0;
  this->MaxX = 0.0;
  this->MaxY = 0.0;

  this->RowLabelWidth = 0.0;
  this->ColumnLabelWidth = 0.0;

  this->CellHeight = 18.0;
  this->CellWidth = this->CellHeight * 2.0;

  this->CategoryLegend->SetVisible(false);
  this->CategoryLegend->CacheBoundsOff();
  this->AddItem(this->CategoryLegend.GetPointer());

  this->ColorLegend->SetVisible(false);
  this->ColorLegend->DrawBorderOn();
  this->ColorLegend->CacheBoundsOff();
  this->AddItem(this->ColorLegend.GetPointer());

  this->LegendPositionSet = false;

  this->Tooltip->SetVisible(false);
  this->AddItem(this->Tooltip.GetPointer());
}

//-----------------------------------------------------------------------------
vtkHeatmapItem::~vtkHeatmapItem()
{
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::SetPosition(const vtkVector2f &pos)
{
  this->PositionVector = pos;
}

//-----------------------------------------------------------------------------
vtkVector2f vtkHeatmapItem::GetPositionVector()
{
  return this->PositionVector;
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::SetTable(vtkTable *table)
{
  if (table == NULL || table->GetNumberOfRows() == 0)
  {
    this->Table = vtkSmartPointer<vtkTable>::New();
    return;
  }
  this->Table = table;

  // get the row names for this table
  vtkStringArray *rowNames = vtkArrayDownCast<vtkStringArray>(
    this->Table->GetColumnByName(this->NameColumn));
  if (rowNames == NULL)
  {
    rowNames = vtkArrayDownCast<vtkStringArray>(
      this->Table->GetColumn(0));
  }
  if (rowNames == NULL)
  {
    vtkWarningMacro("Could not determine row name column."
      "Try calling vtkHeatmapItem::SetNameColumn(vtkStdString)");
    this->RowNames = NULL;
  }
  else
  {
    this->RowNames = rowNames;
  }
}

//-----------------------------------------------------------------------------
vtkTable * vtkHeatmapItem::GetTable()
{
  return this->Table;
}

//-----------------------------------------------------------------------------
vtkStringArray * vtkHeatmapItem::GetRowNames()
{
  return this->RowNames;
}

//-----------------------------------------------------------------------------
bool vtkHeatmapItem::Paint(vtkContext2D *painter)
{
  if (this->Table->GetNumberOfRows() == 0)
  {
    return true;
  }

  if (this->IsDirty())
  {
    this->RebuildBuffers();
  }

  this->PaintBuffers(painter);
  this->PaintChildren(painter);
  return true;
}

//-----------------------------------------------------------------------------
bool vtkHeatmapItem::IsDirty()
{
  if (this->Table->GetNumberOfRows() == 0)
  {
    return false;
  }
  if (this->Table->GetMTime() > this->HeatmapBuildTime)
  {
    return true;
  }
  return false;
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::RebuildBuffers()
{
  if (this->Table->GetNumberOfRows() == 0)
  {
    return;
  }

  this->InitializeLookupTables();

  this->CollapsedRowsArray = vtkArrayDownCast<vtkBitArray>(
    this->Table->GetFieldData()->GetArray("collapsed rows"));
  this->CollapsedColumnsArray = vtkArrayDownCast<vtkBitArray>(
    this->Table->GetFieldData()->GetArray("collapsed columns"));

  this->HeatmapBuildTime = this->Table->GetMTime();
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::InitializeLookupTables()
{
  this->ColumnRanges.clear();
  this->CategoricalDataValues->Reset();

  for (vtkIdType column = 0; column < this->Table->GetNumberOfColumns();
       ++column)
  {
    if (this->Table->GetColumn(column) == this->GetRowNames())
    {
      continue;
    }
    if (this->Table->GetValue(0, column).IsString())
    {
      this->AccumulateProminentCategoricalDataValues(column);
      continue;
    }
    double min = VTK_DOUBLE_MAX;
    double max = VTK_DOUBLE_MIN;
    for (vtkIdType row = 0; row < this->Table->GetNumberOfRows(); ++row)
    {
      double value = this->Table->GetValue(row, column).ToDouble();
      if (value > max)
      {
        max = value;
      }
      if (value < min)
      {
        min = value;
      }
    }
    this->ColumnRanges[column] = std::pair<double, double>(min, max);
  }

  this->GenerateCategoricalDataLookupTable();
  this->GenerateContinuousDataLookupTable();
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::GenerateContinuousDataLookupTable()
{
  this->ContinuousDataLookupTable->SetNumberOfTableValues(255);
  this->ContinuousDataLookupTable->Build();
  this->ContinuousDataLookupTable->SetRange(0, 255);
  this->ContinuousDataLookupTable->SetNanColor(0.75, 0.75, 0.75, 1.0);

  // black to red
  for (int i = 0; i < 85; ++i)
  {
    float f = static_cast<float>(i) / 84.0;
    this->ContinuousDataLookupTable->SetTableValue(i, f, 0, 0);
  }

 // red to yellow
  for (int i = 0; i < 85; ++i)
  {
    float f = static_cast<float>(i) / 84.0;
    this->ContinuousDataLookupTable->SetTableValue(85 + i, 1.0, f, 0);
  }

 // yellow to white
  for (int i = 0; i < 85; ++i)
  {
    float f = static_cast<float>(i) / 84.0;
    this->ContinuousDataLookupTable->SetTableValue(170 + i, 1.0, 1.0, f);
  }

  this->ColorLegendLookupTable->DeepCopy(
    this->ContinuousDataLookupTable.GetPointer());
  this->ColorLegend->SetTransferFunction(
    this->ColorLegendLookupTable.GetPointer());
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::AccumulateProminentCategoricalDataValues(vtkIdType column)
{
  vtkStringArray *stringColumn = vtkArrayDownCast<vtkStringArray>(
    this->Table->GetColumn(column));

  // search for values that occur more than once
  vtkNew<vtkStringArray> repeatedValues;
  std::map<std::string, int> CountMap;
  std::map<std::string, int>::iterator mapItr;
  for (int i = 0; i < stringColumn->GetNumberOfTuples(); ++i)
  {
    CountMap[stringColumn->GetValue(i)]++;
  }

  for (mapItr = CountMap.begin(); mapItr != CountMap.end(); ++mapItr)
  {
    if (mapItr->second > 1)
    {
      repeatedValues->InsertNextValue(mapItr->first);
    }
  }

  // add each distinct, repeated value from this column to our master list
  for (int i = 0; i < repeatedValues->GetNumberOfTuples(); ++i)
  {
    vtkVariant v = repeatedValues->GetVariantValue(i);
    if (this->CategoricalDataValues->LookupValue(v) == -1)
    {
      this->CategoricalDataValues->InsertNextValue(v.ToString());
    }
  }
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::GenerateCategoricalDataLookupTable()
{
  this->CategoricalDataLookupTable->ResetAnnotations();
  this->CategoricalDataLookupTable->SetNanColor(0.75, 0.75, 0.75, 1.0);

  // make each distinct categorical value an index into our lookup table
  for (int i = 0; i < this->CategoricalDataValues->GetNumberOfTuples(); ++i)
  {
    this->CategoricalDataLookupTable->SetAnnotation(
      this->CategoricalDataValues->GetValue(i),
      this->CategoricalDataValues->GetValue(i));
  }

  vtkNew<vtkColorSeries> colorSeries;
  colorSeries->SetColorScheme(vtkColorSeries::BREWER_QUALITATIVE_SET3);
  colorSeries->BuildLookupTable(this->CategoricalDataLookupTable.GetPointer());

  this->CategoryLegend->SetScalarsToColors(
    this->CategoricalDataLookupTable.GetPointer());
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::PaintBuffers(vtkContext2D *painter)
{
  // Calculate the extent of the data that is visible within the window.
  this->UpdateVisibleSceneExtent(painter);

  // Compute the bounds of the heatmap (excluding text labels)
  this->ComputeBounds();

  // leave a small amount of space between the heatmap and the row/column
  // labels
  double spacing = this->CellWidth * 0.25;

  // variables used to calculate the positions of elements drawn on screen.
  double cellStartX = 0.0;
  double cellStartY = 0.0;
  double labelStartX = 0.0;
  double labelStartY = 0.0;

  bool currentlyCollapsingRows = false;

  bool currentlyCollapsingColumns = false;

  // this map helps us display information about the correct row & column
  // in our tooltips
  this->SceneRowToTableRowMap.clear();
  this->SceneRowToTableRowMap.assign(this->Table->GetNumberOfRows(), -1);
  this->SceneColumnToTableColumnMap.clear();
  this->SceneColumnToTableColumnMap.assign(
    this->Table->GetNumberOfColumns(), -1);

  // Setup text property & calculate an appropriate font size for this zoom
  // level.  "Igq" was selected for the range of height of its characters.
  painter->GetTextProp()->SetColor(0.0, 0.0, 0.0);
  painter->GetTextProp()->SetVerticalJustificationToCentered();
  painter->GetTextProp()->SetJustificationToLeft();
  painter->GetTextProp()->SetOrientation(0.0);
  int fontSize = painter->ComputeFontSizeForBoundedString("Igq", VTK_FLOAT_MAX,
                                                          this->CellHeight);

  //canDrawText is set to false if we're too zoomed out to draw legible text.
  bool canDrawText = true;
  if (fontSize < 8)
  {
    canDrawText = false;
  }
  bool drawRowLabels = canDrawText;
  bool drawColumnLabels = canDrawText;

  int orientation = this->GetOrientation();

  // Detect if our row or column labels would be currently visible on screen.
  if (canDrawText)
  {
    switch (orientation)
    {
      case vtkHeatmapItem::DOWN_TO_UP:
        if (this->SceneBottomLeft[1] > this->MaxY + spacing ||
            this->SceneTopRight[1] < this->MaxY + spacing)
        {
          drawRowLabels = false;
        }
        if (this->SceneBottomLeft[0] > this->MaxX + spacing ||
            this->SceneTopRight[0] < this->MaxX + spacing)
        {
          drawColumnLabels = false;
        }
        break;

      case vtkHeatmapItem::RIGHT_TO_LEFT:
        if (this->SceneBottomLeft[0] > this->MinX - spacing ||
            this->SceneTopRight[0] < this->MinX - spacing)
        {
          drawRowLabels = false;
        }
        else
        {
          painter->GetTextProp()->SetJustificationToRight();
        }
        if (this->SceneBottomLeft[1] > this->MaxY + spacing &&
            this->SceneTopRight[1] < this->MaxY + spacing)
        {
          drawColumnLabels = false;
        }
        break;

      case vtkHeatmapItem::UP_TO_DOWN:
        if (this->SceneBottomLeft[1] > this->MinY - spacing ||
            this->SceneTopRight[1] < this->MinY - spacing)
        {
          drawRowLabels = false;
        }
        else
        {
          painter->GetTextProp()->SetJustificationToRight();
        }
        if (this->SceneBottomLeft[0] > this->MaxX + spacing ||
            this->SceneTopRight[0] < this->MaxX + spacing)
        {
          drawColumnLabels = false;
        }
        break;

      case vtkHeatmapItem::LEFT_TO_RIGHT:
      default:
        if (this->SceneBottomLeft[0] > this->MaxX + spacing ||
            this->SceneTopRight[0] < this->MaxX + spacing)
        {
          drawRowLabels = false;
        }
        if (this->SceneBottomLeft[1] > this->MaxY + spacing &&
            this->SceneTopRight[1] < this->MaxY + spacing)
        {
          drawColumnLabels = false;
        }
        break;
    }
  }

  // set the orientation of our text property to draw row names
  if (drawRowLabels)
  {
    painter->GetTextProp()->SetOrientation(
      this->GetTextAngleForOrientation(orientation));
  }

  // keep track of what row & column we're drawing next
  vtkIdType rowToDraw = 0;
  vtkIdType columnToDraw = 0;
  bool columnMapSet = false;

  for (vtkIdType row = 0; row != this->Table->GetNumberOfRows(); ++row)
  {
    // check if this row has been collapsed or not
    if (this->CollapsedRowsArray && this->CollapsedRowsArray->GetValue(row) == 1)
    {
      // a contiguous block of collapsed rows is represented as a single blank
      // row by this item.
      if (!currentlyCollapsingRows)
      {
        this->SceneRowToTableRowMap[rowToDraw] = -1;
        ++rowToDraw;
        currentlyCollapsingRows = true;
      }
      continue;
    }
    currentlyCollapsingRows = false;

    // get the name of this row
    std::string name = "";
    if (this->RowNames)
    {
      name = this->RowNames->GetValue(row);
    }

    // only draw the cells of this row if it isn't explicitly marked as blank
    if (this->BlankRows.find(name) == this->BlankRows.end())
    {
      columnToDraw = 0;
      for (vtkIdType column = 0; column < this->Table->GetNumberOfColumns();
           ++column)
      {
        // don't draw the name column as part of the heatmap
        // (it's used later to label the rows instead)
        if (this->Table->GetColumn(column) == this->GetRowNames())
        {
          continue;
        }

        // check if this column has been collapsed or not
        if (this->CollapsedColumnsArray &&
            this->CollapsedColumnsArray->GetValue(column) == 1)
        {
          // a contiguous block of collapsed columns is represented as a single blank
          // column by this item.
          if (!currentlyCollapsingColumns)
          {
            this->SceneColumnToTableColumnMap[columnToDraw] = -1;
            ++columnToDraw;
            currentlyCollapsingColumns = true;
          }
          continue;
        }
        currentlyCollapsingColumns = false;

        // get the color for this cell from the lookup table
        double color[4];
        vtkVariant value = this->Table->GetValue(row, column);
        if (value.IsString())
        {
          this->CategoricalDataLookupTable->GetAnnotationColor(value, color);
        }
        else
        {
          // set the range on our continuous lookup table for this column
          this->ContinuousDataLookupTable->SetRange(
            this->ColumnRanges[column].first,
            this->ColumnRanges[column].second);

          // get the color for this value
          this->ContinuousDataLookupTable->GetColor(value.ToDouble(), color);
        }
        painter->GetBrush()->SetColorF(color[0], color[1], color[2]);

        // draw this cell of the table
        double w = 0.0;
        double h = 0.0;
        switch(orientation)
        {
          case vtkHeatmapItem::DOWN_TO_UP:
            cellStartX = this->Position[0] + this->CellHeight * rowToDraw;
            cellStartY = this->MinY + this->CellWidth * columnToDraw;
            h = this->CellWidth;
            w = this->CellHeight;
            break;

          case vtkHeatmapItem::RIGHT_TO_LEFT:
            cellStartX = this->MinX + this->CellWidth * columnToDraw;
            cellStartY = this->Position[1] + this->CellHeight * rowToDraw;
            w = this->CellWidth;
            h = this->CellHeight;
            break;

          case vtkHeatmapItem::UP_TO_DOWN:
            cellStartX = this->Position[0] + this->CellHeight * rowToDraw;
            cellStartY = this->MinY + this->CellWidth * columnToDraw;
            h = this->CellWidth;
            w = this->CellHeight;
            break;

          case vtkHeatmapItem::LEFT_TO_RIGHT:
          default:
            cellStartX = this->MinX + this->CellWidth * columnToDraw;
            cellStartY = this->Position[1] + this->CellHeight * rowToDraw;
            w = this->CellWidth;
            h = this->CellHeight;
            break;
        }

        if (this->LineIsVisible(cellStartX, cellStartY,
                                cellStartX + this->CellWidth,
                                cellStartY + this->CellHeight) ||
            this->LineIsVisible(cellStartX, cellStartY + this->CellHeight,
                                cellStartX + this->CellWidth, cellStartY))
        {
          painter->DrawRect(cellStartX, cellStartY, w, h);
        }

        if (!columnMapSet)
        {
          this->SceneColumnToTableColumnMap[columnToDraw] = column;
        }

        ++columnToDraw;
      }
      columnMapSet = true;
    }

    this->SceneRowToTableRowMap[rowToDraw] = row;
    ++rowToDraw;

    // draw this row's label if it would be visible
    if (!drawRowLabels)
    {
      continue;
    }

    switch (orientation)
    {
      case vtkHeatmapItem::DOWN_TO_UP:
        labelStartX = cellStartX + this->CellHeight / 2.0;
        labelStartY = this->MaxY + spacing;
        break;
      case vtkHeatmapItem::RIGHT_TO_LEFT:
        labelStartX = this->MinX - spacing;
        labelStartY = cellStartY + this->CellHeight / 2.0;
        break;
      case vtkHeatmapItem::UP_TO_DOWN:
        labelStartX = cellStartX + this->CellHeight / 2.0;
        labelStartY = this->MinY - spacing;
        break;
      case vtkHeatmapItem::LEFT_TO_RIGHT:
      default:
        labelStartX = this->MaxX + spacing;
        labelStartY = cellStartY + this->CellHeight / 2.0;
        break;
    }

    if (name != "" &&
        this->SceneBottomLeft[0] < labelStartX &&
        this->SceneTopRight[0] > labelStartX   &&
        this->SceneBottomLeft[1] < labelStartY &&
        this->SceneTopRight[1] > labelStartY)
    {
      painter->DrawString(labelStartX, labelStartY, name);
    }
  }

  // draw column labels
  if (!canDrawText)
  {
    this->RowLabelWidth = 0.0;
    this->ColumnLabelWidth = 0.0;
    return;
  }

  if (!drawColumnLabels)
  {
    this->ComputeLabelWidth(painter);
    this->ColumnLabelWidth = 0.0;
    return;
  }

  // set up our text property to draw column labels appropriately for
  // the current orientation.
  switch (orientation)
  {
    case vtkHeatmapItem::DOWN_TO_UP:
    case vtkHeatmapItem::UP_TO_DOWN:
      painter->GetTextProp()->SetOrientation(0);
      break;

    case vtkHeatmapItem::RIGHT_TO_LEFT:
    case vtkHeatmapItem::LEFT_TO_RIGHT:
    default:
      painter->GetTextProp()->SetOrientation(90);
      break;
  }

  painter->GetTextProp()->SetJustificationToLeft();

  columnToDraw = 1;
  for (vtkIdType column = 0; column < this->Table->GetNumberOfColumns();
       ++column)
  {
    // don't draw the name column as part of the heatmap
    // (it's used later to label the rows instead)
    if (this->Table->GetColumn(column) == this->GetRowNames())
    {
      continue;
    }

    // check if this column has been collapsed or not
    if (this->CollapsedColumnsArray &&
        this->CollapsedColumnsArray->GetValue(column) == 1)
    {
      // a contiguous block of collapsed columns is represented as a single blank
      // column by this item.
      if (!currentlyCollapsingColumns)
      {
        ++columnToDraw;
        currentlyCollapsingColumns = true;
      }
      continue;
    }
    currentlyCollapsingColumns = false;

    switch(orientation)
    {
      case vtkHeatmapItem::DOWN_TO_UP:
      case vtkHeatmapItem::UP_TO_DOWN:
        labelStartX = this->MaxX + spacing;
        labelStartY =
          this->MinY + this->CellWidth * columnToDraw - this->CellWidth / 2;
        break;

      case vtkHeatmapItem::RIGHT_TO_LEFT:
      case vtkHeatmapItem::LEFT_TO_RIGHT:
      default:
        labelStartX =
          this->MinX + this->CellWidth * columnToDraw - this->CellWidth / 2;
        labelStartY = this->MaxY + spacing;
        break;
    }

    std::string columnName = this->Table->GetColumn(column)->GetName();
    if (this->SceneBottomLeft[0] < labelStartX &&
        this->SceneTopRight[0] > labelStartX &&
        this->SceneBottomLeft[1] < labelStartY &&
        this->SceneTopRight[1] > labelStartY)
    {
      painter->DrawString(labelStartX, labelStartY, columnName);
    }
    ++columnToDraw;
  }

  // update the size of our labels
  this->ComputeLabelWidth(painter);
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::UpdateVisibleSceneExtent(vtkContext2D *painter)
{
  float position[2];
  painter->GetTransform()->GetPosition(position);
  this->SceneBottomLeft[0] = -position[0];
  this->SceneBottomLeft[1] = -position[1];
  this->SceneBottomLeft[2] = 0.0;

  this->SceneTopRight[0] =
    static_cast<double>(this->GetScene()->GetSceneWidth() - position[0]);
  this->SceneTopRight[1] =
    static_cast<double>(this->GetScene()->GetSceneHeight() - position[1]);
  this->SceneTopRight[2] = 0.0;
  vtkNew<vtkMatrix3x3> inverse;
  painter->GetTransform()->GetInverse(inverse.GetPointer());
  inverse->MultiplyPoint(this->SceneBottomLeft, this->SceneBottomLeft);
  inverse->MultiplyPoint(this->SceneTopRight, this->SceneTopRight);
}

//-----------------------------------------------------------------------------
bool vtkHeatmapItem::LineIsVisible(double x0, double y0,
                                        double x1, double y1)
{
  // use local variables to improve readibility
  double xMinScene = this->SceneBottomLeft[0];
  double yMinScene = this->SceneBottomLeft[1];
  double xMaxScene = this->SceneTopRight[0];
  double yMaxScene = this->SceneTopRight[1];

  // if either end point of the line segment falls within the screen,
  // then the line segment is visible.
  if ( (xMinScene <= x0 && xMaxScene >= x0 &&
        yMinScene <= y0 && yMaxScene >= y0) ||
       (xMinScene <= x1 && xMaxScene >= x1 &&
        yMinScene <= y1 && yMaxScene >= y1) )
  {
    return true;
  }

  // figure out which end point is "greater" than the other in both dimensions
  double xMinLine, xMaxLine, yMinLine, yMaxLine;
  if (x0 < x1)
  {
    xMinLine = x0;
    xMaxLine = x1;
  }
  else
  {
    xMinLine = x1;
    xMaxLine = x0;
  }
  if (y0 < y1)
  {
    yMinLine = y0;
    yMaxLine = y1;
  }
  else
  {
    yMinLine = y1;
    yMaxLine = y0;
  }

  // case where the Y range of the line falls within the visible scene
  // and the X range of the line contains the entire visible scene
  if (yMinScene <= yMinLine && yMaxScene >= yMinLine &&
      yMinScene <= yMaxLine && yMaxScene >= yMaxLine &&
      xMinLine <= xMinScene && xMaxLine >= xMaxScene)
  {
    return true;
  }

  // case where the X range of the line falls within the visible scene
  // and the Y range of the line contains the entire visible scene
  if (xMinScene <= xMinLine && xMaxScene >= xMinLine &&
      xMinScene <= xMaxLine && xMaxScene >= xMaxLine &&
      yMinLine <= yMinScene && yMaxLine >= yMaxScene)
  {
    return true;
  }

  return false;
}

//-----------------------------------------------------------------------------
bool vtkHeatmapItem::MouseMoveEvent(const vtkContextMouseEvent &event)
{
  if (event.GetButton() == vtkContextMouseEvent::NO_BUTTON)
  {
    float pos[3];
    vtkNew<vtkMatrix3x3> inverse;
    pos[0] = event.GetPos().GetX();
    pos[1] = event.GetPos().GetY();
    pos[2] = 0;
    this->GetScene()->GetTransform()->GetInverse(inverse.GetPointer());
    inverse->MultiplyPoint(pos, pos);
    if (pos[0] <= this->MaxX && pos[0] >= this->MinX &&
        pos[1] <= this->MaxY && pos[1] >= this->MinY)
    {
      this->Tooltip->SetPosition(pos[0], pos[1]);

      std::string tooltipText = this->GetTooltipText(pos[0], pos[1]);
      if (tooltipText.compare("") != 0)
      {
        this->Tooltip->SetText(tooltipText);
        this->Tooltip->SetVisible(true);
        this->Scene->SetDirty(true);
        return true;
      }
    }
    bool shouldRepaint = this->Tooltip->GetVisible();
    this->Tooltip->SetVisible(false);
    if (shouldRepaint)
    {
      this->Scene->SetDirty(true);
    }
  }
  return false;
}

//-----------------------------------------------------------------------------
std::string vtkHeatmapItem::GetTooltipText(float x, float y)
{
  int sceneRow = 0;
  int sceneColumn = 0;
  int orientation = this->GetOrientation();
  if (orientation == vtkHeatmapItem::UP_TO_DOWN ||
      orientation == vtkHeatmapItem::DOWN_TO_UP)
  {
    sceneRow = static_cast<int>(floor(fabs(x - this->Position[0]) / this->CellHeight));
    sceneColumn = static_cast<int>(floor((y - this->MinY) / this->CellWidth));
  }
  else
  {
    sceneRow = static_cast<int>(floor(fabs(y - this->Position[1]) / this->CellHeight));
    sceneColumn = static_cast<int>(floor((x - this->MinX) / this->CellWidth));
  }

  vtkIdType row = -1;
  if (static_cast<unsigned int>(sceneRow) < this->SceneRowToTableRowMap.size())
  {
    row = this->SceneRowToTableRowMap[sceneRow];
  }
  vtkIdType column = -1;
  if (static_cast<unsigned int>(sceneColumn) <
      this->SceneColumnToTableColumnMap.size())
  {
    column = this->SceneColumnToTableColumnMap[sceneColumn];
  }

  if (row > -1 && column > -1)
  {
    std::string rowName;
    if (this->RowNames)
    {
      rowName = this->RowNames->GetValue(row);
    }
    else
    {
      std::stringstream ss;
      ss << row;
      rowName = ss.str();
    }
    if (this->BlankRows.find(rowName) != this->BlankRows.end())
    {
      return "";
    }

    std::string columnName = this->Table->GetColumn(column)->GetName();

    std::string tooltipText = "(";
    tooltipText += rowName;
    tooltipText += ", ";
    tooltipText += columnName;
    tooltipText += ")\n";
    tooltipText += this->Table->GetValue(row, column).ToString();

    return tooltipText;
  }
  return "";
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::SetOrientation(int orientation)
{
  vtkIntArray *existingArray = vtkArrayDownCast<vtkIntArray>(
    this->Table->GetFieldData()->GetArray("orientation"));
  if (existingArray)
  {
    existingArray->SetValue(0, orientation);
  }
  else
  {
    vtkSmartPointer<vtkIntArray> orientationArray =
      vtkSmartPointer<vtkIntArray>::New();
    orientationArray->SetNumberOfComponents(1);
    orientationArray->SetName("orientation");
    orientationArray->InsertNextValue(orientation);
    this->Table->GetFieldData()->AddArray(orientationArray);
  }

  //reposition the legends
  this->PositionLegends(orientation);
}

//-----------------------------------------------------------------------------
int vtkHeatmapItem::GetOrientation()
{
  vtkIntArray *orientationArray = vtkArrayDownCast<vtkIntArray>(
    this->Table->GetFieldData()->GetArray("orientation"));
  if (orientationArray)
  {
    return orientationArray->GetValue(0);
  }
  return vtkHeatmapItem::LEFT_TO_RIGHT;
}

//-----------------------------------------------------------------------------
double vtkHeatmapItem::GetTextAngleForOrientation(int orientation)
{
  switch(orientation)
  {
    case vtkHeatmapItem::DOWN_TO_UP:
      return 90.0;

    case vtkHeatmapItem::RIGHT_TO_LEFT:
      return 0.0;

    case vtkHeatmapItem::UP_TO_DOWN:
      return 270.0;

    case vtkHeatmapItem::LEFT_TO_RIGHT:
    default:
      return 0.0;
  }
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::ComputeLabelWidth(vtkContext2D *painter)
{
  this->RowLabelWidth = 0.0;
  this->ColumnLabelWidth = 0.0;

  int fontSize = painter->ComputeFontSizeForBoundedString("Igq", VTK_FLOAT_MAX,
                                                          this->CellHeight);
  if (fontSize < 8)
  {
    return;
  }

  // temporarily set text to default orientation
  double orientation = painter->GetTextProp()->GetOrientation();
  painter->GetTextProp()->SetOrientation(0.0);

  float bounds[4];
  // find the longest row label
  if (this->RowNames)
  {

    for (vtkIdType row = 0; row != this->Table->GetNumberOfRows(); ++row)
    {
      if (this->CollapsedRowsArray &&
          this->CollapsedRowsArray->GetValue(row) == 1)
      {
        continue;
      }
      std::string name = this->RowNames->GetValue(row);
      painter->ComputeStringBounds(name, bounds);
      if (bounds[2] > this->RowLabelWidth)
      {
        this->RowLabelWidth = bounds[2];
      }
    }
  }

  // find the longest column label
  for (vtkIdType col = 0; col != this->Table->GetNumberOfColumns(); ++col)
  {
    if (this->Table->GetColumn(col) == this->GetRowNames())
    {
      continue;
    }
    if (this->CollapsedColumnsArray &&
        this->CollapsedColumnsArray->GetValue(col) == 1)
    {
      continue;
    }
    std::string name = this->Table->GetColumn(col)->GetName();
    painter->ComputeStringBounds(name, bounds);
    if (bounds[2] > this->ColumnLabelWidth)
    {
      this->ColumnLabelWidth = bounds[2];
    }
  }

  // restore orientation
  painter->GetTextProp()->SetOrientation(orientation);
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::ComputeBounds()
{
  // figure out how many actual rows will be drawn
  bool currentlyCollapsingRows = false;
  int numRows = 0;
  for (vtkIdType row = 0; row != this->Table->GetNumberOfRows(); ++row)
  {
    if (this->CollapsedRowsArray &&
        this->CollapsedRowsArray->GetValue(row) == 1)
    {
      // a contiguous block of collapsed rows is represented as a single blank
      // row by this item.
      if (!currentlyCollapsingRows)
      {
        ++numRows;
        currentlyCollapsingRows = true;
      }
      continue;
    }
    currentlyCollapsingRows = false;
    ++numRows;
  }

  // figure out how many actual columns will be drawn
  bool currentlyCollapsingColumns = false;
  int numColumns = 0;
  for (vtkIdType col = 0; col != this->Table->GetNumberOfColumns(); ++col)
  {
    if (this->Table->GetColumn(col) == this->GetRowNames())
    {
      continue;
    }
    if (this->CollapsedColumnsArray &&
        this->CollapsedColumnsArray->GetValue(col) == 1)
    {
      // a contiguous block of collapsed columns is represented as a single blank
      // column by this item.
      if (!currentlyCollapsingColumns)
      {
        ++numColumns;
        currentlyCollapsingColumns = true;
      }
      continue;
    }
    currentlyCollapsingColumns = false;
    ++numColumns;
  }

  this->MinX = this->Position[0];
  this->MinY = this->Position[1];
  switch (this->GetOrientation())
  {
    case vtkHeatmapItem::RIGHT_TO_LEFT:
    case vtkHeatmapItem::LEFT_TO_RIGHT:
    default:
      this->MaxX = this->MinX + this->CellWidth * numColumns;
      this->MaxY = this->MinY + this->CellHeight * numRows;
      break;

    case vtkHeatmapItem::UP_TO_DOWN:
    case vtkHeatmapItem::DOWN_TO_UP:
      this->MaxX = this->MinX + this->CellHeight * numRows;
      this->MaxY = this->MinY + this->CellWidth * numColumns;
      break;
  }
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::GetBounds(double bounds[4])
{
  bounds[0] = this->MinX;
  bounds[1] = this->MaxX;
  bounds[2] = this->MinY;
  bounds[3] = this->MaxY;

  if (this->RowLabelWidth == 0.0 && this->ColumnLabelWidth == 0.0)
  {
    return;
  }

  double spacing = this->CellWidth * 0.25;

  switch (this->GetOrientation())
  {
    case vtkHeatmapItem::LEFT_TO_RIGHT:
    default:
      bounds[1] += spacing + this->RowLabelWidth;
      bounds[3] += spacing + this->ColumnLabelWidth;
      break;

    case vtkHeatmapItem::UP_TO_DOWN:
      bounds[1] += spacing + this->ColumnLabelWidth;
      bounds[2] -= spacing + this->RowLabelWidth;
      break;

    case vtkHeatmapItem::RIGHT_TO_LEFT:
      bounds[0] -= spacing + this->RowLabelWidth;
      bounds[3] += spacing + this->ColumnLabelWidth;
      break;

    case vtkHeatmapItem::DOWN_TO_UP:
      bounds[1] += spacing + this->ColumnLabelWidth;
      bounds[3] += spacing + this->RowLabelWidth;
      break;
  }
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::MarkRowAsBlank(std::string rowName)
{
  this->BlankRows.insert(rowName);
}

//-----------------------------------------------------------------------------
bool vtkHeatmapItem::MouseDoubleClickEvent(const vtkContextMouseEvent &event)
{
  // get the position of the double click and convert it to scene coordinates
  double pos[3];
  vtkNew<vtkMatrix3x3> inverse;
  pos[0] = event.GetPos().GetX();
  pos[1] = event.GetPos().GetY();
  pos[2] = 0;
  this->GetScene()->GetTransform()->GetInverse(inverse.GetPointer());
  inverse->MultiplyPoint(pos, pos);
  if (pos[0] <= this->MaxX && pos[0] >= this->MinX &&
      pos[1] <= this->MaxY && pos[1] >= this->MinY)
  {
    vtkIdType column = 0;
    int orientation = this->GetOrientation();
    if (orientation == vtkHeatmapItem::UP_TO_DOWN ||
        orientation == vtkHeatmapItem::DOWN_TO_UP)
    {
      column = static_cast<vtkIdType>(floor((pos[1] - this->MinY) / this->CellWidth));
    }
    else
    {
      column = static_cast<vtkIdType>(floor((pos[0] - this->MinX) / this->CellWidth));
    }
    ++column;

    if (!this->LegendPositionSet)
    {
      this->PositionLegends(this->GetOrientation());
    }

    if (this->Table->GetValue(0, column).IsString())
    {
      // categorical data
      // generate an array of distinct values from this column
      vtkStringArray *stringColumn = vtkArrayDownCast<vtkStringArray>(
        this->Table->GetColumn(column));
      this->CategoryLegendValues->Reset();
      this->CategoryLegendValues->Squeeze();
      stringColumn->SetMaxDiscreteValues(stringColumn->GetNumberOfTuples() - 1);
      stringColumn->GetProminentComponentValues(
        0, this->CategoryLegendValues.GetPointer());
      this->CategoryLegendValues->Modified();

      // these distinct values become the the input to our categorical legend
      this->CategoryLegend->SetValues(this->CategoryLegendValues.GetPointer());
      this->CategoryLegend->SetTitle(this->Table->GetColumn(column)->GetName());
      this->CategoryLegend->SetVisible(true);
      this->ColorLegend->SetVisible(false);
      this->Scene->SetDirty(true);
      return true;
    }
    else
    {
      // continuous data
      // set up the scalar bar legend
      this->ColorLegend->GetTransferFunction()->SetRange(
        this->ColumnRanges[column].first,
        this->ColumnRanges[column].second);

      this->ColorLegend->SetTitle(this->Table->GetColumn(column)->GetName());

      this->ColorLegend->Update();
      this->ColorLegend->SetVisible(true);
      this->CategoryLegend->SetVisible(false);
      this->Scene->SetDirty(true);
      return true;
    }
  }
  bool shouldRepaint = this->ColorLegend->GetVisible() ||
                       this->CategoryLegend->GetVisible();
  this->CategoryLegend->SetVisible(false);
  this->ColorLegend->SetVisible(false);
  if (shouldRepaint)
  {
    this->Scene->SetDirty(true);
  }

  return false;
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::PositionLegends(int orientation)
{
  // bail out early if we don't have meaningful bounds yet.
  if (this->MinX > this->MaxX || this->MinY > this->MaxY)
  {
    return;
  }

  switch(orientation)
  {
    case vtkHeatmapItem::DOWN_TO_UP:
    case vtkHeatmapItem::UP_TO_DOWN:

      this->CategoryLegend->SetHorizontalAlignment(vtkChartLegend::RIGHT);
      this->CategoryLegend->SetVerticalAlignment(vtkChartLegend::CENTER);
      this->CategoryLegend->SetPoint(
        this->MinX - this->CellHeight,
        this->MinY + (this->MaxY - this->MinY) / 2.0);

      this->ColorLegend->SetHorizontalAlignment(vtkChartLegend::RIGHT);
      this->ColorLegend->SetVerticalAlignment(vtkChartLegend::CENTER);
      this->ColorLegend->SetOrientation(vtkColorLegend::VERTICAL);
      this->ColorLegend->SetPoint(
        this->MinX - this->CellHeight,
        this->MinY + (this->MaxY - this->MinY) / 2.0);
      this->ColorLegend->SetTextureSize(
        this->ColorLegend->GetSymbolWidth(),
       this->MaxY - this->MinY);
      break;

    case vtkHeatmapItem::RIGHT_TO_LEFT:
    case vtkHeatmapItem::LEFT_TO_RIGHT:
    default:

      this->CategoryLegend->SetHorizontalAlignment(vtkChartLegend::CENTER);
      this->CategoryLegend->SetVerticalAlignment(vtkChartLegend::TOP);
      this->CategoryLegend->SetPoint(
        this->MinX + (this->MaxX - this->MinX) / 2.0,
        this->MinY - this->CellHeight);

      this->ColorLegend->SetHorizontalAlignment(vtkChartLegend::CENTER);
      this->ColorLegend->SetVerticalAlignment(vtkChartLegend::TOP);
      this->ColorLegend->SetOrientation(vtkColorLegend::HORIZONTAL);
      this->ColorLegend->SetPoint(
        this->MinX + (this->MaxX - this->MinX) / 2.0,
        this->MinY - this->CellHeight);
      this->ColorLegend->SetTextureSize(
        this->MaxX - this->MinX,
        this->ColorLegend->GetSymbolWidth());
      break;
  }
  this->LegendPositionSet = true;
}

//-----------------------------------------------------------------------------
bool vtkHeatmapItem::Hit(const vtkContextMouseEvent &vtkNotUsed(mouse))
{
  // If we are interactive, we want to catch anything that propagates to the
  // background, otherwise we do not want any mouse events.
  return this->Interactive;
}

//-----------------------------------------------------------------------------
void vtkHeatmapItem::PrintSelf(ostream &os, vtkIndent indent)
{
  this->Superclass::PrintSelf(os, indent);
  os << "Table: " << (this->Table ? "" : "(null)") << std::endl;
  if (this->Table->GetNumberOfRows() > 0)
  {
    this->Table->PrintSelf(os, indent.GetNextIndent());
  }
}