This file is indexed.

/usr/share/vtk/Infovis/Python/haruspex.py is in vtk-examples 5.8.0-17.5.

This file is owned by root:root, with mode 0o644.

The actual contents of the file can be viewed below.

  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
############################################################
# Copyright 2010 Sandia Corporation.
# Under the terms of Contract DE-AC04-94AL85000 with Sandia Corporation,
# the U.S. Government retains certain rights in this software.
############################################################
# Contact: Philippe Pebay, Sandia National Laboratories, pppebay@sandia.gov
############################################################

############################################################
from vtk import *
import sys
import getopt
############################################################

############################################################
# Global variable for convenience
verbosity = 0
############################################################

############################################################
# Usage function
def Usage( outModelPrefix, outDataName ):
    print "Usage:"
    print "\t [-h]             Help: print this message and exit"
    print "\t -d <filename>    name of CSV input data file"
    print "\t [-c <filename>]  name of CSV file specifying columns of interest. Default: all columns are of interest"
    print "\t -e <engine>      Type of statistics engine. Available engines are:"
    print "\t                    descriptive"
    print "\t                    order"
    print "\t                    contingency"
    print "\t                    correlative"
    print "\t                    multicorrelative"
    print "\t                    pca"
    print "\t                    kmeans"
    print "\t [-o <bitcode>]   Engine options bitcode. Default is 0. Available bits are:"
    print "\t                    1st bit: assess"
    print "\t                    2nd bit: test"
    print "\t [-m <prefix>]    prefix of CSV input model file(s). Default: calculate model from scratch"
    print "\t [-u]             update input model (if data are provided as well). NB: update happens before assessment"
    print "\t [-s <prefix>]    prefix of CSV output model (statistics) file(s)"
    print "\t [-a <filename>]  name of CSV output data (annotated) file"
    print "\t [-t <filename>]  name of CSV statistical test results file"
    print "\t [-v]             Increase verbosity (from no flag = silent to -vvv = print all tables)"
    sys.exit( 1 )
############################################################

############################################################
# Parse command line
def ParseCommandLine():
    # Declare use of global variable
    global verbosity

    # Default values
    options = 0
    inDataName = ""
    inModelPrefix = ""
    updateModel = False
    haruspexName = ""
    outModelPrefix = ""
    outDataName = ""
    outTestName = ""
    columnsListName =""
    
    # Try to hash command line with respect to allowable flags
    try:
        opts,args = getopt.getopt(sys.argv[1:], 'hd:e:o:m:us:a:t:c:v')
    except getopt.GetoptError:
        Usage( outModelPrefix, outDataName )
        sys.exit( 1 )

    # First verify that the helper has not been requested (supersedes everything else)
    # NB: handled first and separately so default values cannot be altered in helper message
    for o,a in opts:
        if o == "-h":
            Usage( outModelPrefix, outDataName )

    # Parse arguments and assign corresponding variables
    for o,a in opts:
        if o == "-d":
            inDataName = a
        elif o == "-e":
            haruspexName = a
        elif o == "-o":
            options = a
        elif o == "-m":
            inModelPrefix = a
        elif o == "-u":
            updateModel = True
        elif o == "-s":
            outModelPrefix = a
        elif o == "-a":
            outDataName = a
        elif o == "-t":
            outTestName = a
        elif o == "-c":
            columnsListName = a
        elif o == "-v":
            verbosity += 1

    if not inDataName:
        print "ERROR: a data file name required!"
        sys.exit( 1 )
        
    if not haruspexName:
        print "ERROR: a statistics engine name is required!"
        sys.exit( 1 )

    if verbosity > 0:
        print "# Parsed command line:"

        print "  Input data file:", inDataName
        if inModelPrefix != "":
            print "  Input model file prefix:", inModelPrefix
        else:
            print "  No input model"

        print "  Statistics:", haruspexName
        if columnsListName != "":
            print "  Columns of interest in file:", columnsListName
        else:
            print "  Columns of interest: all"

        print "  Output data file:", outDataName
        print "  Output model file prefix:", outModelPrefix

        print

    return [ inDataName, \
             inModelPrefix, \
             updateModel, \
             columnsListName, \
             haruspexName, \
             options, \
             outDataName, \
             outTestName, \
             outModelPrefix ]
############################################################

############################################################
# Turn haruspex name into vtkStatistics object and ancillary parameters
def InstantiateStatistics( haruspexName ):
    # Declare use of global variable
    global verbosity

    if haruspexName == "descriptive":
        haruspex = vtkDescriptiveStatistics()

    elif haruspexName == "order":
        haruspex = vtkOrderStatistics()

    elif haruspexName == "contingency":
        haruspex = vtkContingencyStatistics()

    elif haruspexName == "correlative":
        haruspex = vtkCorrelativeStatistics()

    elif haruspexName == "multicorrelative":
        haruspex = vtkMultiCorrelativeStatistics()

    elif haruspexName == "pca":
        haruspex = vtkPCAStatistics()

    elif haruspexName == "kmeans":
        haruspex = vtkKMeansStatistics()

    else:
        print "ERROR: Invalid statistics engine:", haruspexName
        sys.exit( 1 )

    if verbosity > 0:
        print "# Instantiated a", haruspex.GetClassName(), "object"
        print

    return haruspex
############################################################

############################################################
# Read input CSV model table as input port
def ReadInModelTable( inModelPrefix, tabIndex ):
    # Declare use of global variable
    global verbosity

    if verbosity > 0:
        print "# Reading input model table", tabIndex

    # Set CSV reader parameters
    inTableReader = vtkDelimitedTextReader()
    inTableReader.SetFieldDelimiterCharacters(",")
    inTableReader.SetHaveHeaders( True )
    inTableReader.SetDetectNumericColumns( True )
    inTableReader.SetFileName( inModelPrefix + "-" + str( tabIndex ) + ".csv" )
    inTableReader.Update()

    if verbosity > 0:
        table = inTableReader.GetOutput()
        print "  Number of columns:", table.GetNumberOfColumns()
        print "  Number of rows:", table.GetNumberOfRows()
        if verbosity > 1:
            inTableReader.GetOutput().Dump( 16 )
        print

    return inTableReader
############################################################

############################################################
# Read input CSV data as input port
def ReadInData( inDataName ):
    # Declare use of global variable
    global verbosity

    if verbosity > 0:
        print "# Reading input data"

    # Set CSV reader parameters
    inDataReader = vtkDelimitedTextReader()
    inDataReader.SetFieldDelimiterCharacters(",")
    inDataReader.SetHaveHeaders( True )
    inDataReader.SetDetectNumericColumns( True )
    inDataReader.SetFileName( inDataName )
    inDataReader.Update()

    if verbosity > 0:
        table = inDataReader.GetOutput()
        print "  Number of columns:", table.GetNumberOfColumns()
        print "  Number of rows:", table.GetNumberOfRows()
        print
        if verbosity > 2:
            print "# Input data:"
            inDataReader.GetOutput().Dump( 16 )
            print
    
    return inDataReader
############################################################

############################################################
# Read list of columns of interest
def ReadColumnsList( columnsListName ):
    # Declare use of global variable
    global verbosity

    if verbosity > 0:
        print "# Reading list of columns of interest:"

    # Set CSV reader parameters
    columnsListReader = vtkDelimitedTextReader()
    columnsListReader.SetFieldDelimiterCharacters(",")
    columnsListReader.SetHaveHeaders( False )
    columnsListReader.SetDetectNumericColumns( True )
    columnsListReader.SetFileName( columnsListName )
    columnsListReader.Update()

    # Figure number of columns of interest
    table = columnsListReader.GetOutput()
    n = table.GetNumberOfColumns()
    if verbosity > 0:
        print "  Number of columns of interest:", n

    # Now construct list of colums of interest
    columnsList = []
    for i in range( 0, n ):
        columnsList.append( table.GetColumn( i ).GetValue( 0 ) )
    if verbosity > 1:
        print "  Columns of interest are:", columnsList

    if verbosity > 0:
        print

    return columnsList
############################################################

############################################################
# Write table from haruspex output port (i.e., for data or tests)
def WriteOutTable( haruspex, outPort, outFileName, outPortName, threshold ):
    # Declare use of global variable
    global verbosity

    if outFileName == "":
        if verbosity > 0:
            print "# No output table of", outPortName, "required"
            print
        return

    if verbosity > 0:
        print "# Saving output table of", outPortName

    # Set CSV writer parameters
    outTableWriter = vtkDelimitedTextWriter()
    outTableWriter.SetFieldDelimiter(",")
    outTableWriter.SetFileName( outFileName )
    outTableWriter.SetInputConnection( haruspex.GetOutputPort( outPort ) )
    outTableWriter.Update()

    if verbosity > 0:
        print "  Wrote", outPortName
        if verbosity > threshold:
            haruspex.GetOutput( outPort ).Dump( 16 )
        print
############################################################

############################################################
# Write haruspex output model
def WriteOutModel( haruspex, outModelPrefix ):
    # Declare use of global variable
    global verbosity

    if outModelPrefix == "":
        if verbosity > 0:
            print "# No output model (statistics) required"
            print
        return

    if verbosity > 0:
        print "# Saving output model (statistics):"
        
    # Set CSV writer parameters
    outModelWriter = vtkDelimitedTextWriter()
    outModelWriter.SetFieldDelimiter(",")

    # Verify that model is a vtkMultiBlockDataSet, error out otherwise
    outModelType = haruspex.GetOutputDataObject( 1 ).GetClassName()
    if outModelType != "vtkMultiBlockDataSet":
        print "ERROR: unsupported type of output model!"
        sys.exit( 1 )

    # Must iterate over all blocks of the vtkMultiBlockDataSet
    outModel = haruspex.GetOutputDataObject( 1 )
    n = outModel.GetNumberOfBlocks()
    for i in range( 0, n ):
        # Straightforward CSV file dump of a vtkTable
        outModelName = outModelPrefix + "-" + str( i )+ ".csv"
        outModelWriter.SetFileName( outModelName )
        table = outModel.GetBlock( i )
        outModelWriter.SetInput( table )
        outModelWriter.Update()
            
        if verbosity > 0:
            print "  Wrote", outModelName
            if verbosity > 1:
                table.Dump( 16 )
                print
############################################################

############################################################
# Calculate statistics
def CalculateStatistics( inDataReader, inModelReader, updateModel, columnsList, haruspex, options ):
    # Declare use of global variable
    global verbosity

    if verbosity > 0:
        print "# Calculating statistics:"

    # Output port of data reader becomes input connection of haruspex
    haruspex.AddInputConnection( inDataReader.GetOutputPort() )

    # Get the output table of the data reader, which becomes the input data
    inData = inDataReader.GetOutput()

    # Figure number of columns of interest. If no list was provided, use them all
    if columnsList == []:
        columnsList = range( 0, inData.GetNumberOfColumns() )
    n = len( columnsList )
    
    # Generate list of columns of interest, depending on number of variables
    if haruspex.IsA( "vtkUnivariateStatisticsAlgorithm" ):
        # Univariate case: one request for each columns
        for i in range( 0, n ):
            colName = inData.GetColumnName( columnsList[i] )
            if verbosity > 0:
                print "  Requesting column", colName
            haruspex.AddColumn( colName )

    elif haruspex.IsA( "vtkBivariateStatisticsAlgorithm" ):
        # Bivariate case: generate all possible pairs
        for i in range( 0, n ):
            colNameX = inData.GetColumnName( columnsList[i] )
            for j in range( i+1, n ):
                colNameY = inData.GetColumnName( columnsList[j] )
                if verbosity > 0:
                    print "  Requesting column pair (", colNameX, ",", colNameY, ")"
                haruspex.AddColumnPair( colNameX, colNameY )

    else:
        # Multivariate case: generate single request containing all columns
        for i in range( 0, n ):
            colName = inData.GetColumnName( columnsList[i] )
            haruspex.SetColumnStatus( colName, 1 )
            if verbosity > 0:
                print "  Adding column", colName, "to the request"

    # Complete column selection request
    haruspex.RequestSelectedColumns()
    
    # Figure which options were requested
    if int( options ) % 2:
        assessOption = True
        if verbosity > 0:
            print "  Assess option is on"
    else:
        assessOption = False
        if verbosity > 0:
            print "  Assess option is off"
    options = int( options ) >> 1
    if int( options ) % 2:
        haruspex.SetTestOption( True )
        if verbosity > 0:
            print "  Test option is on"
    else:
        haruspex.SetTestOption( False )
        if verbosity > 0:
            print "  Test option is off"

    if verbosity > 0:
        print

    # If an input model was provided, then update it first, otherwise run in a single pass
    if inModelReader == None:
        # No model reader: then Learn, Derive, and possibly Assess in a single pass
        haruspex.SetLearnOption( True )
        haruspex.SetDeriveOption( True )
        haruspex.SetAssessOption( assessOption )
        haruspex.Update()
    else:
        # Model readers are available: decide how many tables will be fetched
        nPrimaryTables = haruspex.GetNumberOfPrimaryTables()

        # Then create vtkMultiBlockDataSet with correspondingly many blocks
        inModel = vtkMultiBlockDataSet()
        inModel.SetNumberOfBlocks( nPrimaryTables )

        # Now iterate over all readers to obtain tables
        for t in range( 0, nPrimaryTables ):
            inTableReader = inModelReader[t]
            inTable = inTableReader.GetOutput()

            # Handle special case of second table of order statistics
            if ( t > 0 and haruspex.GetClassName() == "vtkOrderStatistics" ):
                if verbosity > 0:
                    print "# Converting input order table to appropriate column types"

                # Create a programmable filter whose input is the order table
                convertOrderTab = vtkProgrammableFilter()
                convertOrderTab.SetInput( inTable )

                # Define table converter callback for programmable filter
                def ConvertOrderTableCallback():
                    readTable = convertOrderTab.GetInput()
                    convTable = convertOrderTab.GetOutput()

                    # Create columns with appropriate names and formats
                    kCol = vtkIdTypeArray()
                    kCol.SetName( "Key" )
                    convTable.AddColumn( kCol )
                    xCol = vtkStringArray()
                    xCol.SetName( "Value" )
                    convTable.AddColumn( xCol )
                    cCol = vtkIdTypeArray()
                    cCol.SetName( "Cardinality" )
                    convTable.AddColumn( cCol )

                    # Loop over all input rows and create output rows
                    nRow = readTable.GetNumberOfRows()
                    row = vtkVariantArray()
                    row.SetNumberOfValues( 3 )
                    for r in range( 0, nRow ):
                        # Retrieve primary statistics and convert to correct type
                        k = readTable.GetValueByName( r, "Key" ).ToInt()
                        row.SetValue( 0, k )
                        x = readTable.GetValueByName( r, "Value" ).ToString()
                        row.SetValue( 1, x )
                        c = readTable.GetValueByName( r, "Cardinality" ).ToInt()
                        row.SetValue( 2, c )

                        convTable.InsertNextRow( row )

                # Set callback and run programmable filer
                convertOrderTab.SetExecuteMethod( ConvertOrderTableCallback )
                convertOrderTab.Update()

                # Retrieve converted table from filter output
                inTable = convertOrderTab.GetOutput()
                if verbosity > 1:
                    inTable.Dump( 16 )

            # Handle special case of second table of contingency statistics
            if ( t > 0 and haruspex.GetClassName() == "vtkContingencyStatistics" ):
                if verbosity > 0:
                    print "# Converting input contingency table to appropriate column types"

                # Create a programmable filter whose input is the contingency table
                convertContingencyTab = vtkProgrammableFilter()
                convertContingencyTab.SetInput( inTable )

                # Define table converter callback for programmable filter
                def ConvertContingencyTableCallback():
                    readTable = convertContingencyTab.GetInput()
                    convTable = convertContingencyTab.GetOutput()

                    # Create columns with appropriate names and formats
                    kCol = vtkIdTypeArray()
                    kCol.SetName( "Key" )
                    convTable.AddColumn( kCol )
                    xCol = vtkStringArray()
                    xCol.SetName( "x" )
                    convTable.AddColumn( xCol )
                    yCol = vtkStringArray()
                    yCol.SetName( "y" )
                    convTable.AddColumn( yCol )
                    cCol = vtkIdTypeArray()
                    cCol.SetName( "Cardinality" )
                    convTable.AddColumn( cCol )

                    # Loop over all input rows and create output rows
                    nRow = readTable.GetNumberOfRows()
                    row = vtkVariantArray()
                    row.SetNumberOfValues( 4 )
                    for r in range( 0, nRow ):
                        # Retrieve primary statistics and convert to correct type
                        k = readTable.GetValueByName( r, "Key" ).ToInt()
                        row.SetValue( 0, k )
                        x = readTable.GetValueByName( r, "x" ).ToString()
                        row.SetValue( 1, x )
                        y = readTable.GetValueByName( r, "y" ).ToString()
                        row.SetValue( 2, y )
                        c = readTable.GetValueByName( r, "Cardinality" ).ToInt()
                        row.SetValue( 3, c )

                        convTable.InsertNextRow( row )

                # Set callback and run programmable filer
                convertContingencyTab.SetExecuteMethod( ConvertContingencyTableCallback )
                convertContingencyTab.Update()

                # Retrieve converted table from filter output
                inTable = convertContingencyTab.GetOutput()
                if verbosity > 1:
                    inTable.Dump( 16 )

            # Set retrieved table to corresponding model block
            inModel.SetBlock( t, inTable )

        # If model update is required, then learn new model and aggregate, otherwise assess directly
        if updateModel == True:
            # Store model it for subsequent aggregation
            collection = vtkDataObjectCollection()
            collection.AddItem( inModel )
            
            # Then learn a new primary model (do not derive nor assess)
            haruspex.SetLearnOption( True )
            haruspex.SetDeriveOption( False )
            haruspex.SetAssessOption( False )
            haruspex.Update()
            
            # Aggregate old and new models
            collection.AddItem( haruspex.GetOutputDataObject( 1 ) )
            aggregated = vtkMultiBlockDataSet()
            haruspex.Aggregate( collection, aggregated )

            # Finally, derive and possibly assess using the aggregated model (do not learn)
            haruspex.SetInput( 2, aggregated )
            haruspex.SetLearnOption( False )
            haruspex.SetDeriveOption( True )
            haruspex.SetAssessOption( assessOption )
            haruspex.Update()
        else:
            # Only derive and possibly assess using the input model (do not aggregate)
            haruspex.SetInput( 2, inModel )
            haruspex.SetLearnOption( False )
            haruspex.SetDeriveOption( True )
            haruspex.SetAssessOption( assessOption )
            haruspex.Update()
            
        print
############################################################

############################################################
# Main function
def main():
    # Parse command line
    [ inDataName, \
      inModelPrefix, \
      updateModel, \
      columnsListName, \
      haruspexName, \
      options, \
      outDataName, \
      outTestName, \
      outModelPrefix ] = ParseCommandLine()

    # Verify that haruspex name makes sense and if so instantiate accordingly
    haruspex = InstantiateStatistics( haruspexName )

    # Set input data reader
    inDataReader = ReadInData( inDataName )

    # Set input model readers if prefix was provided
    if inModelPrefix != "":
        inModelReader = []
        nPrimaryTables = haruspex.GetNumberOfPrimaryTables()
        for t in range( 0, nPrimaryTables ):
            tableReader = ReadInModelTable( inModelPrefix, t )
            inModelReader.append( tableReader )

    else:
        inModelReader = None
        
    # Read list of columns of interest
    if columnsListName:
        columnsList = ReadColumnsList( columnsListName )
    else:
        columnsList = []
        
    # Calculate statistics
    CalculateStatistics( inDataReader, inModelReader, updateModel, columnsList, haruspex, options )

    # Save output (annotated) data
    WriteOutTable( haruspex, 0, outDataName, "annotated data", 2 )

    # Save output of statistical tests
    WriteOutTable( haruspex, 2, outTestName, "statistical test results", 1 )

    # Save output model (statistics)
    WriteOutModel( haruspex, outModelPrefix )
############################################################

############################################################
if __name__ == "__main__":
    main()
############################################################