File: TestOrderStatistics.cxx

package info (click to toggle)
vtk7 7.1.1%2Bdfsg1-12
  • links: PTS, VCS
  • area: main
  • in suites: buster
  • size: 125,776 kB
  • sloc: cpp: 1,539,582; ansic: 106,521; 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: 122; objc: 83
file content (623 lines) | stat: -rw-r--r-- 19,199 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
/*
 * Copyright 2008 Sandia Corporation.
 * Under the terms of Contract DE-AC04-94AL85000, there is a non-exclusive
 * license for use of this work by or on behalf of the
 * U.S. Government. Redistribution and use in source and binary forms, with
 * or without modification, are permitted provided that this Notice and any
 * statement of authorship are reproduced on all copies.
 */
// .SECTION Thanks
// Thanks to Philippe Pebay from Sandia National Laboratories
// for implementing this test.

#include "vtkDoubleArray.h"
#include "vtkInformation.h"
#include "vtkStringArray.h"
#include "vtkMath.h"
#include "vtkTable.h"
#include "vtkOrderStatistics.h"
#include "vtkMultiBlockDataSet.h"

#include <vector>
#include <map>

//=============================================================================
int TestOrderStatistics( int, char *[] )
{
  int testStatus = 0;

  double mingledData[] =
    {
    46,
    45,
    47,
    49,
    46,
    47,
    46,
    46,
    47,
    46,
    47,
    49,
    49,
    49,
    47,
    45,
    50,
    50,
    46,
    46,
    51,
    50,
    48,
    48,
    52,
    54,
    48,
    47,
    52,
    52,
    49,
    49,
    53,
    54,
    50,
    50,
    53,
    54,
    50,
    52,
    53,
    53,
    50,
    51,
    54,
    54,
    49,
    49,
    52,
    52,
    50,
    51,
    52,
    52,
    49,
    47,
    48,
    48,
    48,
    50,
    46,
    48,
    47,
    47,
    };
  int nVals = 32;

  vtkDoubleArray* dataset1Arr = vtkDoubleArray::New();
  dataset1Arr->SetNumberOfComponents( 1 );
  dataset1Arr->SetName( "Metric 0" );

  vtkDoubleArray* dataset2Arr = vtkDoubleArray::New();
  dataset2Arr->SetNumberOfComponents( 1 );
  dataset2Arr->SetName( "Metric 1" );

  vtkDoubleArray* dataset3Arr = vtkDoubleArray::New();
  dataset3Arr->SetNumberOfComponents( 1 );
  dataset3Arr->SetName( "Metric 2" );

  for ( int i = 0; i < nVals; ++ i )
  {
    int ti = i << 1;
    dataset1Arr->InsertNextValue( mingledData[ti] );
    dataset2Arr->InsertNextValue( mingledData[ti + 1] );
    dataset3Arr->InsertNextValue( static_cast<double>( i ) );
  }

  vtkTable* datasetTable = vtkTable::New();
  datasetTable->AddColumn( dataset1Arr );
  dataset1Arr->Delete();
  datasetTable->AddColumn( dataset2Arr );
  dataset2Arr->Delete();
  datasetTable->AddColumn( dataset3Arr );
  dataset3Arr->Delete();

  int nMetrics = 3;
  vtkStdString columns[] = { "Metric 1", "Metric 2", "Metric 0" };

  // Set order statistics algorithm and its input data port
  vtkOrderStatistics* os = vtkOrderStatistics::New();

  // First verify that absence of input does not cause trouble
  cout << "## Verifying that absence of input does not cause trouble... ";
  os->Update();
  cout << "done.\n";

  // Prepare first test with data
  os->SetInputData( vtkStatisticsAlgorithm::INPUT_DATA, datasetTable );
  datasetTable->Delete();

  // Select Columns of Interest
  os->AddColumn( "Metric 3" ); // Include invalid Metric 3
  for ( int i = 0; i< nMetrics; ++ i )
  {  // Try to add all valid indices once more
    os->AddColumn( columns[i] );
  }

  // Test Learn, Derive, and Test operations
  os->SetLearnOption( true );
  os->SetDeriveOption( true );
  os->SetTestOption( true );
  os->SetAssessOption( true );
  os->Update();

  // Offset between baseline values for each variable
  int valsOffset = 5;

  double valsTest1 [] =
    {
      46., 47., 49., 51.5, 54.,
      45., 47., 49., 52., 54.,
      0., 7.5, 15.5, 23.5, 31.,
    };

  // Get output data and meta tables
  vtkTable* outputData = os->GetOutput( vtkStatisticsAlgorithm::OUTPUT_DATA );
  vtkMultiBlockDataSet* outputModelDS = vtkMultiBlockDataSet::SafeDownCast( os->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  unsigned nbq = outputModelDS->GetNumberOfBlocks() - 1;
  vtkTable* outputQuantiles = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq ) );
  vtkTable* outputCard = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq - 1 ) );
  vtkTable* outputTest = os->GetOutput( vtkStatisticsAlgorithm::OUTPUT_TEST );

  cout << "## Calculated the following quartiles with InverseCDFAveragedSteps quantile definition:\n";
  outputQuantiles->Dump();
  for ( vtkIdType c = 1; c < outputQuantiles->GetNumberOfColumns(); ++ c )
  {
    vtkStdString colName = outputQuantiles->GetColumnName( c );
    cout << "   Variable="
         << colName
         << "\n";

    // Check some results of the Derive operation
    for ( int r = 0; r < outputQuantiles->GetNumberOfRows(); ++ r )
    {
      double Qp = outputQuantiles->GetValue( r, c ).ToDouble();
      int i = ( c - 1 ) * valsOffset + r;

      if ( fabs( Qp - valsTest1[i] ) > 1.e-6 )
      {
        vtkGenericWarningMacro("Incorrect quartiles: "
                               << Qp
                               << " != "
                               << valsTest1[i]
                               << ".");
        testStatus = 1;
      }
    }

    // Check some results of the Assess operation
    vtkStdString quantColName = "Quantile(" + colName + ")";
    vtkAbstractArray* absQuantArr = outputData->GetColumnByName( quantColName );
    if ( ! absQuantArr )
    {
      vtkGenericWarningMacro("Cannot retrieve quartile array for variable: "
                             << colName
                             << ".");
      testStatus = 1;
    }
    else
    {
      vtkDataArray* dataQuantArr = vtkArrayDownCast<vtkDoubleArray>( absQuantArr );
      if ( ! dataQuantArr )
      {
        vtkGenericWarningMacro("Quartile array for variable: "
                               << colName
                               << " is not a data array.");
        testStatus = 1;
      }

      std::map<int,int> histoQuantiles;
      for ( vtkIdType r = 0; r < dataQuantArr->GetNumberOfTuples(); ++ r )
      {
        int qIdx = static_cast<int>( vtkMath::Round( dataQuantArr->GetTuple1( r ) ) );
        ++ histoQuantiles[qIdx];
      }

      int totalHist = 0;
      for ( std::map<int,int>::iterator hit = histoQuantiles.begin();
            hit != histoQuantiles.end() ; ++ hit )
      {
        cout << "    IQR "
             << hit->first
             << ": "
             << hit->second
             << " observations\n";

        totalHist += hit->second;
      }
      cout << "    Total: "
           << totalHist
           << " observations\n";

      if ( nVals != totalHist )
      {
        vtkGenericWarningMacro("Quartile-based histogram size "
                               << totalHist
                               << " != "
                               << nVals
                               << ", the data set cardinality.");
        testStatus = 1;
      }
    }

    cout << "\n";
  }

  cout << "## Calculated the following histograms:\n";
  for ( unsigned b = 0; b < outputModelDS->GetNumberOfBlocks() - 2; ++ b )
  {
    vtkStdString varName = outputModelDS->GetMetaData( b )->Get( vtkCompositeDataSet::NAME() );
    cout << "   Variable="
         << varName
         << "\n";

    vtkTable* histoTab = vtkTable::SafeDownCast( outputModelDS->GetBlock( b ) );
    histoTab->Dump();
  }

  // Check cardinalities
  cout << "\n## Calculated the following cardinalities:\n";
  for ( vtkIdType r = 0; r < outputCard->GetNumberOfRows(); ++ r )
  {
    cout << "   ";
    for ( int i = 0; i < outputCard->GetNumberOfColumns(); ++ i )
    {
      cout << outputCard->GetColumnName( i )
           << "="
           << outputCard->GetValue( r, i ).ToString()
           << "  ";
    }

    // Check whether total cardinality is correct
    int testIntValue = outputCard->GetValueByName( r, "Cardinality" ).ToInt();
    if ( testIntValue != outputData->GetNumberOfRows() )
    {
      vtkGenericWarningMacro("Incorrect histogram count: "
                             << testIntValue
                             << " != "
                             << outputData->GetNumberOfRows()
                             << ".");
      testStatus = 1;
    }

    cout << "\n";
  }

  // Check some results of the Test operation
  cout << "\n## Calculated the following Kolmogorov-Smirnov statistics:\n";
  for ( vtkIdType r = 0; r < outputTest->GetNumberOfRows(); ++ r )
  {
    cout << "   ";
    for ( int i = 0; i < outputTest->GetNumberOfColumns(); ++ i )
    {
      cout << outputTest->GetColumnName( i )
           << "="
           << outputTest->GetValue( r, i ).ToString()
           << "  ";
    }

    cout << "\n";
  }

  // Select Columns of Interest (no more bogus columns)
  os->ResetAllColumnStates();
  os->ResetRequests();
  for ( int i = 0; i< nMetrics; ++ i )
  {  // Try to add all valid indices once more
    os->AddColumn( columns[i] );
  }

  // Test Learn, Derive, and Test operations with InverseCDF quantile definition
  os->SetQuantileDefinition( vtkOrderStatistics::InverseCDF );
  os->SetLearnOption( true );
  os->SetDeriveOption( true );
  os->SetTestOption( true );
  os->SetAssessOption( false );
  os->Update();

  double valsTest2 [] =
    {
      46., 47., 49., 51., 54.,
      45., 47., 49., 52., 54.,
      0., 7., 15., 23., 31.,
    };

  // Get calculated model
  outputModelDS = vtkMultiBlockDataSet::SafeDownCast( os->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  nbq = outputModelDS->GetNumberOfBlocks() - 1;
  outputQuantiles = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq ) );

  cout << "\n## Calculated the following quartiles with InverseCDFAveragedSteps quantile definition:\n";
  outputQuantiles->Dump();
  for ( vtkIdType c = 1; c < outputQuantiles->GetNumberOfColumns(); ++ c )
  {
    // Verify some of the calculated quartiles
    for ( int r = 0; r < outputQuantiles->GetNumberOfRows(); ++ r )
    {
      double Qp = outputQuantiles->GetValue( r, c ).ToDouble();
      int i = ( c - 1 ) * valsOffset + r;

      if ( fabs( Qp - valsTest2[i] ) > 1.e-6 )
      {
        vtkGenericWarningMacro("Incorrect quartiles for variable "
                               << outputQuantiles->GetColumnName( c )
                               << ": "
                               << Qp
                               << " != "
                               << valsTest2[i]
                               << ".");
        testStatus = 1;
      }
    }
  }

  // Check some results of the Test operation
  cout << "\n## Calculated the following Kolmogorov-Smirnov statistics:\n";
  for ( vtkIdType r = 0; r < outputTest->GetNumberOfRows(); ++ r )
  {
    cout << "   ";
    for ( int i = 0; i < outputTest->GetNumberOfColumns(); ++ i )
    {
      cout << outputTest->GetColumnName( i )
           << "="
           << outputTest->GetValue( r, i ).ToString()
           << "  ";
    }

    cout << "\n";
  }

  // Test Learn, Derive, and Test operation for deciles with InverseCDF quantile definition (as with Octave)
  os->SetQuantileDefinition( 0 ); // 0: vtkOrderStatistics::InverseCDF
  os->SetNumberOfIntervals( 10 );
  os->Update();

  // Get calculated model
  outputModelDS = vtkMultiBlockDataSet::SafeDownCast( os->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  nbq = outputModelDS->GetNumberOfBlocks() - 1;
  outputQuantiles = vtkTable::SafeDownCast( outputModelDS->GetBlock( nbq ) );

  cout << "\n## Calculated the following deciles with InverseCDF quantile definition:\n";
  outputQuantiles->Dump();

  // Check some results of the Test operation
  cout << "\n## Calculated the following Kolmogorov-Smirnov statistics:\n";
  for ( vtkIdType r = 0; r < outputTest->GetNumberOfRows(); ++ r )
  {
    cout << "   ";
    for ( int i = 0; i < outputTest->GetNumberOfColumns(); ++ i )
    {
      cout << outputTest->GetColumnName( i )
           << "="
           << outputTest->GetValue( r, i ).ToString()
           << "  ";
    }

    cout << "\n";
  }

  // Clean up
  os->Delete();

  // Test Learn operation for quartiles with non-numeric ordinal data
  vtkStdString text(
    "an ordinal scale defines a total preorder of objects the scale values themselves have a total order names may be used like bad medium good if numbers are used they are only relevant up to strictly monotonically increasing transformations also known as order isomorphisms" );
  std::vector<int>::size_type textLength = text.size();

  vtkStringArray* textArr = vtkStringArray::New();
  textArr->SetNumberOfComponents( 1 );
  textArr->SetName( "Text" );

  for ( std::vector<int>::size_type i = 0; i < textLength; ++ i )
  {
    vtkStdString s( "" );
    s += text.at(i);
    textArr->InsertNextValue( s );
  }

  vtkTable* textTable = vtkTable::New();
  textTable->AddColumn( textArr );
  textArr->Delete();

  // Set order statistics engine
  vtkOrderStatistics* os2 = vtkOrderStatistics::New();

  os2->SetInputData( vtkStatisticsAlgorithm::INPUT_DATA, textTable );
  textTable->Delete();
  os2->AddColumn( "Text" ); // Add column of interest
  os2->RequestSelectedColumns();

  // Learn, Derive, Test, and Assess with 12 intervals
  os2->SetParameter( "QuantileDefinition", 0, 1 ); // Should be ignored as type is not numeric
  os2->SetParameter( "NumberOfIntervals", 0, 12 );
  os2->SetLearnOption( true );
  os2->SetDeriveOption( true );
  os2->SetTestOption( true );
  os2->SetAssessOption( true );
  os2->Update();

  // Get output data and meta tables
  vtkTable* outputData2 = os2->GetOutput( vtkStatisticsAlgorithm::OUTPUT_DATA );
  vtkMultiBlockDataSet* outputModelDS2 = vtkMultiBlockDataSet::SafeDownCast( os2->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  nbq = outputModelDS2->GetNumberOfBlocks() - 1;
  vtkTable* outputCard2 = vtkTable::SafeDownCast( outputModelDS2->GetBlock( nbq - 1 ) );
  vtkTable* outputQuantiles2 = vtkTable::SafeDownCast( outputModelDS2->GetBlock( nbq ) );

  cout << "\n## Input text (punctuation omitted):\n   "
       << text
       << "\n";

  cout << "\n## Calculated the following histogram:\n";
  for ( unsigned b = 0; b < outputModelDS2->GetNumberOfBlocks() - 2; ++ b )
  {
    vtkStdString varName = outputModelDS2->GetMetaData( b )->Get( vtkCompositeDataSet::NAME() );
    cout << "   Variable="
         << varName
         << "\n";

    vtkTable* histoTab = vtkTable::SafeDownCast( outputModelDS2->GetBlock( b ) );
    histoTab->Dump();

    // Check whether total cardinality is correct
    int testIntValue2 = outputCard2->GetValueByName( 0, "Cardinality" ).ToInt();
    if ( testIntValue2 != outputData2->GetNumberOfRows() )
    {
      vtkGenericWarningMacro("Incorrect histogram count: "
                             << testIntValue2
                             << " != "
                             << outputData2->GetNumberOfRows()
                             << ".");
      testStatus = 1;
    }
  }

  // Calculate quantile-based histogram
  std::map<int,int> histo12Text;
  for ( vtkIdType r = 0; r < outputData2->GetNumberOfRows(); ++ r )
  {
    ++ histo12Text[outputData2->GetValueByName( r, "Quantile(Text)" ).ToInt()];
  }

  int sum12 = 0;
  cout << "\n## Calculated the following quantization from "
       << os2->GetNumberOfIntervals()
       << "-quantiles:\n";

  // Calculate representatives
  std::map<int,char> histo12Repr;
  for ( std::map<int,int>::iterator it = histo12Text.begin(); it != histo12Text.end(); ++ it )
  {
    int quantIdx = it->first;
    int prevqIdx = ( it->first ? it->first - 1 : 0 );
    int frequVal = it->second;
    sum12 += frequVal;

    const char* lowerVal = outputQuantiles2->GetValueByName( prevqIdx, "Text" ).ToString();
    const char* upperVal = outputQuantiles2->GetValueByName( quantIdx, "Text" ).ToString();
    char midVal = ( *lowerVal + *upperVal + 1 ) / 2 ;
    histo12Repr[quantIdx] = midVal;

    cout << "   interval "
         << quantIdx
         << ( quantIdx > 1 ? ": ]" : ": [" )
         << *lowerVal
         << " - "
         << *upperVal
         << "] represented by "
         << midVal
         << " with frequency "
         << frequVal
         << "\n";
  }

  // Verify that we retrieve the total count
  if ( sum12 != outputData2->GetNumberOfRows() )
  {
    vtkGenericWarningMacro("Incorrect histogram count: " << sum12 << " != " << outputData2->GetNumberOfRows() << ".");
    testStatus = 1;
  }

  // Quantize text and print it
  cout << "\n## Quantized text with "
       << histo12Text.size()
       << " quantizers based on "
       << os2->GetNumberOfIntervals()
       << "-quantiles :\n   ";
  for ( vtkIdType r = 0; r < outputData2->GetNumberOfRows(); ++ r )
  {
    cout << histo12Repr[outputData2->GetValueByName( r, "Quantile(Text)" ).ToInt()];
  }
  cout << "\n";

  // Learn, Derive, Assess, and Test again but with with 100 intervals this time
  os2->SetParameter( "QuantileDefinition", 0, 0 ); // Does not matter and should be ignored by the engine as the column contains strings
  os2->SetParameter( "NumberOfIntervals", 0, 100 );
  os2->SetLearnOption( true );
  os2->SetDeriveOption( true );
  os2->SetTestOption( true );
  os2->SetAssessOption( true );
  os2->Update();

  // Get calculated model
  outputModelDS2 = vtkMultiBlockDataSet::SafeDownCast( os2->GetOutputDataObject( vtkStatisticsAlgorithm::OUTPUT_MODEL ) );
  nbq = outputModelDS2->GetNumberOfBlocks() - 1;
  outputQuantiles2 = vtkTable::SafeDownCast( outputModelDS2->GetBlock( nbq ) );

  cout << "\n## Input text (punctuation omitted):\n   "
       << text
       << "\n";

  // Calculate quantile-based histogram
  std::map<int,int> histo100Text;
  for ( vtkIdType r = 0; r < outputData2->GetNumberOfRows(); ++ r )
  {
    ++ histo100Text[outputData2->GetValueByName( r, "Quantile(Text)" ).ToInt()];
  }

  int sum100 = 0;
  cout << "\n## Calculated the following quantization with "
       << os2->GetNumberOfIntervals()
       << "-quantiles:\n";

  // Calculate representatives
  std::map<int,char> histo100Repr;
  for ( std::map<int,int>::iterator it = histo100Text.begin(); it != histo100Text.end(); ++ it )
  {
    int quantIdx = it->first;
    int prevqIdx = ( it->first ? it->first - 1 : 0 );
    int frequVal = it->second;
    sum100 += frequVal;

    const char* lowerVal = outputQuantiles2->GetValueByName( prevqIdx, "Text" ).ToString();
    const char* upperVal = outputQuantiles2->GetValueByName( quantIdx, "Text" ).ToString();
    char midVal = ( *lowerVal + *upperVal + 1 ) / 2 ;
    histo100Repr[quantIdx] = midVal;

    cout << "   interval "
         << quantIdx
         << ( quantIdx > 1 ? ": ]" : ": [" )
         << *lowerVal
         << " - "
         << *upperVal
         << "] represented by "
         << midVal
         << " with frequency "
         << frequVal
         << "\n";
  }

  // Verify that we retrieve the total count
  if ( sum100 != outputData2->GetNumberOfRows() )
  {
    vtkGenericWarningMacro("Incorrect histogram count: " << sum100 << " != " << outputData2->GetNumberOfRows() << ".");
    testStatus = 1;
  }

  // Quantize text and print it
  cout << "\n## Quantized text with "
       << histo100Text.size()
       << " quantizers based on "
       << os2->GetNumberOfIntervals()
       << "-quantiles :\n   ";
  for ( vtkIdType r = 0; r < outputData2->GetNumberOfRows(); ++ r )
  {
    cout << histo100Repr[outputData2->GetValueByName( r, "Quantile(Text)" ).ToInt()];
  }
  cout << "\n";

  // Clean up
  os2->Delete();

  return testStatus;
}