~launchpad-p-s/sofastatistics/main

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
import tree
import numpy
from operator import itemgetter
import pprint
import getdata

"""
v1.1 - shifted getHTML settings for header and footer into separate methods
    to simplify interface when more complex setup.
    Can now select css on a table-by-table basis.
"""
ROWDIM = "row" #double as labels
COLDIM = "column"
#actual options selected ...
SORT_NONE = "None" #double as labels
SORT_LABEL = "By Label"
SORT_FREQ_ASC = "By Freq (Asc)"
SORT_FREQ_DESC = "By Freq (Desc)"

# can use content of constant as a short label
FREQ = "Freq"
ROWPCT = "Row %"
COLPCT = "Col %"
SUM = "Sum"
MEAN = "Mean"
MEDIAN = "Median"
SUMM_N = "N" # N used in Summary tables
STD_DEV = "Std Dev"
measures_long_label_dic = {FREQ: "Frequency", 
                           ROWPCT: "Row %",
                           COLPCT: "Column %",
                           SUM: "Sum", 
                           MEAN: "Mean",
                           MEDIAN: "Median", 
                           SUMM_N: "N",
                           STD_DEV: "Standard Deviation"}
# content of constant and constant (ready to include in exported script)
# e.g. "dimtables.%s" "ROWPCT"
script_export_measures_dic = {FREQ: "FREQ", 
                              ROWPCT: "ROWPCT",
                              COLPCT: "COLPCT",
                              SUM: "SUM", 
                              MEAN: "MEAN",
                              MEDIAN: "MEDIAN", 
                              SUMM_N: "SUMM_N",
                              STD_DEV: "STD_DEV"}
#NOTNULL = " NOT ISNULL(%s) "
NOTNULL = " %s IS NOT NULL "

DEF_CSS = r"c:\mypy\tbl_css\css_default.txt"

def pct_1_dec(num):
    return "%s%%" % round(num,1)
def pct_2_dec(num):
    return "%s%%" % round(num,2)
data_format_dic = {FREQ: str, ROWPCT: pct_1_dec, COLPCT: pct_1_dec}

class DimNodeTree(tree.NodeTree):
    """
    A specialist tree for storing dimension nodes.
    Sets the root node up as a DimNode.
    """    
    def __init__(self, measures=None):
        ""
        self.root_node = DimNode(label="Root", measures=measures)
        self.root_node.level = 0

    def addChild(self, child_node):
        "Update filt_flds to cover all fields in ancestral line"
        #super(tree.NodeTree, self).addChild(child_node)
        tree.NodeTree.addChild(self, child_node)
        child_node.filt_flds = [child_node.fld] #may be None

class LabelNodeTree(tree.NodeTree):
    """
    A specialist tree for storing label nodes.
    Sets the root node up as a LabelNode.
    """    
    def __init__(self):
        ""
        self.root_node = LabelNode(label="Root")
        self.root_node.level = 0
        
class DimNode(tree.Node):
    """
    A specialist node for recording table dimension (row or column)
    data.
    fld is optional for use in columns because sometimes we just want 
        measures there e.g. freq, or summary measures such as mean, 
        median etc.
    label - will use fld if no label supplied (and fld available) - e.g.
        fld=gender, fld.title() = Gender.
    labels - a dictionary of labels e.g. {"1": "Male", "2": "Female"}
    measures - e.g. FREQ
    has_tot - boolean
    sort_order - dimtables.SORT_NONE, dimtables.SORT_LABEL, 
        dimtables.SORT_FREQ_ASC, dimtables.SORT_FREQ_DESC
    bolnumeric - so can set up filters correctly e.g. gender = "1" or 
        gender = 1 as appropriate
    """
    def __init__(self, fld=None, label="", labels=None, measures=None, 
                 has_tot=False, sort_order=SORT_NONE, bolnumeric=False):
        ""
        self.fld = fld
        self.filt_flds = [] #only built up when added as a child to another DimNode
        if not label and fld != None:
            self.label = fld.title()
        else:
            self.label = label
        if not labels:
            self.labels = {}
        else:
            self.labels = labels
        if not measures:
            self.measures = []
        else:
            self.measures = measures
        self.has_tot = has_tot
        self.sort_order = sort_order
        self.bolnumeric = bolnumeric
        tree.Node.__init__(self, dets_dic=None, label=self.label)

    def addChild(self, child_node):
        "Update filt_flds to cover all fields in ancestral line"
        #super(tree.Node, self).addChild(child_node)
        tree.Node.addChild(self, child_node)
        child_node.filt_flds = self.filt_flds + [child_node.fld]

class LabelNode(tree.Node):
    """
    A specialist node for recording table label data for a given dimension 
    (row or column).
    label - the most important data of all - what to display for this node
    filts - a list of all the filter clauses inherited from the ancestral 
        line e.g. gender=1, eth=3
    measure - if this is a terminal node, a single measure must be 
        specified e.g. FREQ
    is_coltot - used for calculations of data values
    """
    
    def __init__(self, label="", filts=None, measure=None, 
                 is_coltot=False):
        ""
        """filt_flds is only filled if this is a terminal node.  
        It is filled when the label nodes tree is being built 
        from the dim node tree node (which is where we get it from)"""
        self.filt_flds = [] 
        if not filts:
            self.filts = []
        else:
            self.filts = filts
        self.measure = measure
        self.is_coltot = is_coltot
        #super(tree.Node, self).__init__(dets_dic=None, label=self.label)
        tree.Node.__init__(self, dets_dic=None, label=label)

    def __str__(self):
        return self.level*2*" " + "Level: " + str(self.level) + \
            "; Label: " + self.label + \
            "; Measure: " + (self.measure if self.measure else "None") + \
            "; Col Total?: " + ("Yes" if self.is_coltot else "No") + \
            "; Child labels: " + ", ".join([x.label for x in self.children])

class DimTable(object):
    """
    Functionality that applies to both demo and live tables
    """
    def processHdrTree(self, tree_col_labels, row_label_cols_n):
        """
        Set up titles, subtitles, and col labels into table header.
        """
        #print tree_col_labels #debug
        col_label_rows_n = tree_col_labels.getDepth()
        col_label_rows_lst = [["<tr>"] for x in range(col_label_rows_n)]
        #title/subtitle etc share their own row
        titles_html = "\n<p class='tbltitle'>"
        for title in self.titles:
            titles_html += "%s<br>" % title
        titles_html += "</p>"
        if self.subtitles != [""]:
            subtitles_html = "\n<p class='tblsubtitle'>"
            for subtitle in self.subtitles:
                subtitles_html += "%s<br>" % subtitle
            subtitles_html += "</p>"
        else:
            subtitles_html = ""
        title_dets_html = titles_html + subtitles_html
        col_label_rows_lst[0].append("<th class='tbltitlecell' " + \
                                     "colspan='%s'>%s</th>" % \
            (len(tree_col_labels.getTerminalNodes()) + row_label_cols_n, 
             title_dets_html))
        #start off with spaceholder heading cell
        col_label_rows_lst[1].append("<th class='spaceholder' rowspan='%s' " % \
            (tree_col_labels.getDepth() - 1) + "colspan='%s'>&nbsp;&nbsp;</th>" % \
            row_label_cols_n)
        col_label_rows_lst = self.colLabelRowBuilder(\
                        node=tree_col_labels.root_node,
                        col_label_rows_lst=col_label_rows_lst, 
                        col_label_rows_n=col_label_rows_n, row_offset=0)
        
        hdr_html = "\n<thead>"
        for row in col_label_rows_lst:
            #flatten row list
            hdr_html += "\n" + "".join(row) + "</tr>"
        hdr_html += "\n</thead>"
        #print tree_col_labels
        return (tree_col_labels, hdr_html)
      
    def processRowTree(self, tree_row_labels):
        "Turn row label tree into labels"
        #print tree_row_labels #debug
        row_label_cols_n = tree_row_labels.getDepth() - 1 #exclude root node
        row_label_rows_n = len(tree_row_labels.getTerminalNodes())
        row_label_rows_lst = [["<tr>"] for x in range(row_label_rows_n)]
        row_offset_dic = {}
        for i in range(row_label_cols_n):
            row_offset_dic[i]=0
        row_label_rows_lst = self.rowLabelRowBuilder(\
                        node=tree_row_labels.root_node,
                        row_label_rows_lst=row_label_rows_lst, 
                        row_label_cols_n=row_label_cols_n, 
                        row_offset_dic=row_offset_dic, col_offset=0)
        return (row_label_rows_lst, tree_row_labels, row_label_cols_n)       

    def rowLabelRowBuilder(self, node, row_label_rows_lst, row_label_cols_n, 
                           row_offset_dic, col_offset=0):
        """
        Adds cells to the row label rows list as it goes through all nodes.
            NB nodes are not processed level by level but from from 
            parent to child.
        Which row do we add a cell to?  It depends entirely on the 
            row offset for the level concerned.  (NB colspanning doesn't 
            affect the which row a cell goes in, or in which order it appears 
            in the row.)
        So we need a row_offset_dic with a key for each level and a value
            which represents the offset (which is updated as we pass through 
            siblings).  If a cell for level X needs to span Y rows
            we add Y to the value for row_offset_dic[X].
        As for colspanning, we need to know how many cols have been
            filled already, and how many cols there are to come to the right.
        If there is a gap, colspan the cell to cover it, and increase the
            col_offset being passed down the subtree.
        node - the node we are adding a cell to the table based upon.
        row_label_rows_lst - one row per row in row label section        
        row_label_cols_n - number of cols in row label section        
        row_offset_dic - keeps track of row position for sibling cells
            according to how much its previous siblings have spanned.
            Zero-based index with as many items as the depth of tree 
            (including root).  Index 0 is never used.
        col_offset - amount of colspanning which has occurred prior
            to the cell.  Need to know so terminal nodes all appear
            at same rightwards position regardless of subtree depth.
        Format cells according to whether variable or value.  Even level
            = value, odd level = variable.
        """
        #print node #debug
        level = node.level
        if level > 0: # skip adding cells for root node itself
            row_offset = level - 1 # e.g. first row level is 0
            row_idx = row_offset_dic[row_offset]
            rowspan_n = len(node.getTerminalNodes())
            row_offset_dic[row_offset] = row_idx + rowspan_n # leave for next sibling
            # cell dimensions
            if rowspan_n > 1:
                rowspan = " rowspan='%s' " % rowspan_n
            else:
                rowspan = "" 
            cols_filled = level + col_offset
            cols_to_fill = row_label_cols_n - cols_filled
            cols_to_right = node.getDepth() - 1 # exclude self
            gap = cols_to_fill - cols_to_right            
            col_offset += gap
            if gap > 0:
                colspan = " colspan='%s' " % (1 + gap,)
            else:
                colspan = ""
            # styling
            if cols_to_right % 2 > 0: #odd
                if cols_filled == 1:
                    cellclass="class='firstrowvar'"
                else:
                    cellclass="class='rowvar'"
            else:
                cellclass="class='rowval'"
            row_label_rows_lst[row_idx].append("<td %s %s %s>%s</td>" % \
                                (cellclass, rowspan, colspan, node.label))
        for child in node.children:
            row_label_rows_lst = self.rowLabelRowBuilder(child, 
                                    row_label_rows_lst, row_label_cols_n, 
                                    row_offset_dic, col_offset)
        # finish level, set all child levels to start with this one's final offset
        # Otherwise Gender, Gender->Asst problem (whereas Gender->Asst, Gender is fine)
        if level > 0: # don't do this on the root
            for i in range(row_offset + 1, row_label_cols_n):
                row_offset_dic[i] = row_offset_dic[row_offset]
        return row_label_rows_lst
    
    def colLabelRowBuilder(self, node, col_label_rows_lst, col_label_rows_n, 
                           row_offset=0):
        """
        Adds cells to the column label rows list as it goes through all nodes.
        Add cells to the correct row which means that the first cell
        in a subtree which is shorter than the maximum for the table
        must have an increased rowspan + pass on a row offset to all its
        children.
        
        node - the node we are adding a cell to the table based upon.
        col_label_rows_lst - one row per row in column label header        
        col_label_rows_n - number of rows in column label header        
        row_offset - number of rows downwards to be put so terminal nodes
            all appear at same level regardless of subtree depth.

        Add cell for node.
        Any gap between rows in table header below (which we are filling)
        and depth of nodes below (with which we fill the table header)?
        If so, increase rowspan of this cell + increase row offset by 
        appropriate amount so that the subsequent cells are added
        to the correct col label row.
        
        Format cells according to whether variable or value.  
        For General Tables, odd number of levels below = value, 
        even = variable.  For Summary Tables, vv.
        """
        rows_filled = node.level + 1 + row_offset
        rows_to_fill = col_label_rows_n - rows_filled
        rows_below = node.getDepth() - 1 # exclude self
        gap = rows_to_fill - rows_below
        # styling
        if self.has_col_measures:
            if rows_below == 0:
                cellclass="class='measure'"
            elif rows_below % 2 > 0: # odd
                cellclass="class='colval'"
            else:
                if rows_filled == 2:
                    cellclass="class='firstcolvar'"
                else:
                    cellclass="class='colvar'"
        else:
            if rows_below % 2 == 0: # even
                cellclass="class='colval'"
            else:
                if rows_filled == 2:
                    cellclass="class='firstcolvar'"
                else:
                    cellclass="class='colvar'"
        # cell dimensions
        if gap > 0:
            rowspan = " rowspan='%s' " % (1 + gap,)
        else:
            rowspan = ""
        colspan_n = len(node.getTerminalNodes())
        if colspan_n > 1:
            colspan = " colspan='%s' " % colspan_n
        else:
            colspan = ""
        if node.level > 0: # skip root (we use that row for the title
            col_label_rows_lst[rows_filled - 1].append(\
                "<th %s %s %s>%s</th>" % (cellclass, rowspan, colspan, 
                                          node.label))
        row_offset += gap
        for child in node.children:
            col_label_rows_lst = self.colLabelRowBuilder(child, 
                                col_label_rows_lst, col_label_rows_n, 
                                row_offset)
        return col_label_rows_lst
    
    
class LiveTable(DimTable):
    """
    A Table with the ability to nest rows and columns, add totals to any 
    node, have multiple measures per terminal node e.g. freq, rowpct, 
    and colpct, etc etc.
    """
    
    def __init__(self, titles, dbe, datasource, cur, tree_rows, tree_cols, 
                 subtitles=None):
        """
        cur - must return tuples, not dictionaries
        """
        self.titles = titles
        if subtitles:
            self.subtitles = subtitles
        else:
            self.subtitles = []
        self.dbe = dbe
        self.if_clause, self.abs_wrapper_l, self.abs_wrapper_r = \
            getdata.getDbeSyntaxElements(self.dbe)
        self.datasource = datasource
        self.cur = cur
        self.tree_rows = tree_rows
        self.tree_cols = tree_cols
    
    def getDataCellN(self, tree_col_labels, tree_row_labels):
        ""
        col_term_nodes = tree_col_labels.getTerminalNodes()
        row_term_nodes = tree_row_labels.getTerminalNodes()
        data_cell_n = len(row_term_nodes) * len(col_term_nodes)
        return data_cell_n
    
    def prepTable(self):
        "Prepare table setup information towards generation of final html."
        (self.row_label_rows_lst, self.tree_row_labels, row_label_cols_n) = \
            self.getRowDets()
        self.tree_col_labels, self.hdr_html = self.getHdrDets(row_label_cols_n)
    
    def getCellNOk(self, max_cells=5000):
        """
        Returns False if too many cells to proceed (according to max_cells).
        Used to determine whether to proceed with table or not.
        """
        data_cell_n = self.getDataCellN(self.tree_col_labels, 
                                        self.tree_row_labels)
        return max_cells >= data_cell_n
    
    def getHTML(self, page_break_after=False):
        """
        Get HTML for table.
        """
        html = ""
        html += "<table cellspacing='0'>\n" # IE6 doesn't support CSS borderspacing
        (row_label_rows_lst, tree_row_labels, row_label_cols_n) = \
            self.getRowDets()
        (tree_col_dets, hdr_html) = self.getHdrDets(row_label_cols_n)
        row_label_rows_lst = self.getBodyHtmlRows(row_label_rows_lst,
                                                  tree_row_labels, 
                                                  tree_col_dets)
        body_html = "\n\n<tbody>"
        for row in row_label_rows_lst:
            #flatten row list
            body_html += "\n" + "".join(row) + "</tr>"
        body_html += "\n</tbody>"
        html += hdr_html
        html += body_html
        html += "\n</table>"
        return html
    
    def getRowDets(self):
        """
        Return row_label_rows_lst - need combination of row and col filters
            to add the data cells to the table body rows.
        tree_row_labels - we collect row filters from this.
        row_label_cols_n - needed to set up header (need to span the 
            row labels).
        """
        tree_row_labels = LabelNodeTree()
        for child in self.tree_rows.root_node.children:
            self.addSubtreeToLabelTree(tree_dims_node=child, 
                                tree_labels_node=tree_row_labels.root_node,
                                dim=ROWDIM, 
                                oth_dim_root=self.tree_cols.root_node)
        return self.processRowTree(tree_row_labels)        
    
    def addSubtreesToColLabelTree(self, tree_col_labels):
        """
        Add subtrees to column label tree.
        If coltree has no children, must add a subtree underneath.
        """
        if self.tree_cols.root_node.children:
            for child in self.tree_cols.root_node.children:
                self.addSubtreeToLabelTree(tree_dims_node=child, 
                            tree_labels_node=tree_col_labels.root_node,
                            dim=COLDIM, 
                            oth_dim_root=self.tree_rows.root_node)
        else:
            self.addSubtreeToLabelTree(tree_dims_node=\
                               self.tree_cols.root_node, 
                               tree_labels_node=tree_col_labels.root_node,
                               dim=COLDIM, 
                               oth_dim_root=self.tree_rows.root_node)
        return tree_col_labels
          
    def addSubtreeToLabelTree(self, tree_dims_node, tree_labels_node, 
                              dim, oth_dim_root):
        """
        Based on information from the variable node, add a subtree
        to the node supplied from the labels tree (if appropriate).
        """
        has_fld = tree_dims_node.fld #None or a string        
        filt_flds = tree_dims_node.filt_flds
        if dim == ROWDIM:
            if not has_fld:
                raise Exception, "All row nodes must have a variable " + \
                    "field specified"
            if self.has_row_vals:
                self.addSubtreeIfVals(tree_dims_node, tree_labels_node, 
                                  oth_dim_root, dim, filt_flds)
            else:
                self.addSubtreeMeasuresOnly(tree_dims_node, 
                                            tree_labels_node, 
                                            filt_flds)            
        elif dim == COLDIM:
            if has_fld:
                self.addSubtreeIfVals(tree_dims_node, tree_labels_node, 
                                  oth_dim_root, dim, filt_flds)            
            else:
                if self.has_col_measures:
                    self.addColMeasuresSubtreeIfNoFld(tree_dims_node, 
                                                  tree_labels_node)                

    def addSubtreeIfVals(self, tree_dims_node, tree_labels_node, 
                         oth_dim_root, dim, filt_flds):
        """
        If the var node has values to display (if any found in data)
        (i.e. must have a field not be a summary table row), 
        the subtree will have two initial 
        levels - 1) a node for the variable itself
        (storing labels in its dets_dic),
        and 2) a set of values nodes - one for each value plus
        one for the total (if appropriate).
        Then we need to follow the subtree down a level below each 
        of the values nodes (assuming the tree_dims_node has any children).        
        
        To display a cell, we must know that there will be at least 
        one descendant cell to show underneath it.              
        We do this by filtering the raw data by the appropriate row 
        and column filters.  If any records remain, we can show the 
        cell.
        """
        val_labels = tree_dims_node.labels
        bolnumeric = tree_dims_node.bolnumeric
        fld = tree_dims_node.fld
        #print tree_dims_node #debug        
        final_filt_clause = self.getValsFiltClause(tree_dims_node, 
                                                   tree_labels_node,
                                                   oth_dim_root)
        SQL_get_vals = "SELECT " + fld + ", COUNT(*)" + \
            " FROM " + self.datasource + \
            " WHERE " + final_filt_clause + \
            " GROUP BY " + fld
        #print SQL_get_vals #debug
        self.cur.execute(SQL_get_vals)
        #get vals and their frequency (across all the other dimension)
        val_freq_label_lst = [(val, val_freq, \
                              val_labels.get(val, str(val))) \
                              for (val, val_freq) in self.cur.fetchall()]
        # [(val, freq, val_label), ...]  
        #http://www.python.org/dev/peps/pep-0265/
        if tree_dims_node.sort_order == SORT_FREQ_ASC:
            val_freq_label_lst.sort(key=itemgetter(1)) #sort asc by freq
        elif tree_dims_node.sort_order == SORT_FREQ_DESC:
            val_freq_label_lst.sort(key=itemgetter(1), reverse=True) #desc
        elif tree_dims_node.sort_order == SORT_LABEL:
            val_freq_label_lst.sort(key=itemgetter(2)) #sort by label
        if not val_freq_label_lst:
            return #do not add subtree - no values
        else:
            #add level 1 to data tree - the var
            node_lev1 = tree_labels_node.addChild(LabelNode(label=\
                                                tree_dims_node.label))
            if tree_dims_node.has_tot:
                #freq not needed now that sorting has already occurred
                val_freq_label_lst.append(("_tot_", 0, "TOTAL"))
            terminal_var = not tree_dims_node.children
            if terminal_var:
                var_measures = tree_dims_node.measures
                if not var_measures:
                    var_measures = [FREQ]
            for val, val_freq, val_label in val_freq_label_lst:
                """add level 2 to the data tree - the value nodes 
                (plus total?); pass on and extend filtering from 
                higher level in data tree"""
                val_node_filts = tree_labels_node.filts[:]
                is_tot = (val == "_tot_")
                if is_tot:
                    val_node_filts.append(NOTNULL % fld)
                else:
                    if bolnumeric:
                        val_node_filts.append("%s = %s" % (fld, val))
                    else:
                        val_node_filts.append("%s = \"%s\"" % (fld, val))
                is_coltot=(is_tot and dim == COLDIM)
                val_node = \
                    node_lev1.addChild(LabelNode(label = val_label,
                        filts=val_node_filts))
                #if tree_dims_node has children, send through again 
                # to add further subtree
                if terminal_var: #a terminal node - add measures
                    #only gen table cols and summ table rows can 
                    #  have measures
                    if (dim == COLDIM and self.has_col_measures) or \
                            (dim == ROWDIM and self.has_row_measures):
                        self.addMeasures(label_node=val_node, 
                                         measures=var_measures, 
                                         is_coltot=is_coltot, 
                                         filt_flds=filt_flds,
                                         filts=val_node_filts) 
                    else:
                        val_node.filt_flds = filt_flds
                else:
                    for child in tree_dims_node.children:
                        self.addSubtreeToLabelTree(\
                                        tree_dims_node=child, 
                                        tree_labels_node=val_node,
                                        dim=dim, 
                                        oth_dim_root=oth_dim_root)
                                    
    def addSubtreeMeasuresOnly(self, tree_dims_node, tree_labels_node, 
                               filt_flds):
        """
        For summary table row trees (NB no nesting) we always 
        display data cells so there is no need to evaluate
        values etc.  The row will be shown even if they are all 
        missing symbols. 
        Instead of value nodes there is a node per measure.
        """
        #add level 1 to data tree - the var
        node_lev1 = tree_labels_node.addChild(LabelNode(label=\
                                            tree_dims_node.label))
        self.addMeasures(label_node=node_lev1, 
                         measures=tree_dims_node.measures, 
                         is_coltot=False, filt_flds=filt_flds,
                         filts=[])
    
    def addColMeasuresSubtreeIfNoFld(self, tree_dims_node, 
                                     tree_labels_node):
        """
        Add subtree in case where no field.
        First check that it is OK to add.
        """
        if tree_dims_node.level > 1:
            raise Exception, "If the col field has not " + \
                "been set, a node without a field specified " + \
                "must be immediately under the root node"
        self.addMeasures(label_node=tree_labels_node, 
                     measures=tree_dims_node.measures, 
                     is_coltot=False, filt_flds=[], filts=[])

    def addMeasures(self, label_node, measures, is_coltot, filt_flds, 
                    filts):
        "Add measure label nodes under label node"
        for measure in measures:
            measure_node = LabelNode(label=measure, 
                                  filts=filts,
                                  measure=measure,
                                  is_coltot=is_coltot)
            measure_node.filt_flds = filt_flds
            label_node.addChild(measure_node)
    
    def getValsFiltClause(self, tree_dims_node, tree_labels_node, 
                          oth_dim_root):
        """
        To display a cell, we must know that there will be at least 
        one descendant cell to show underneath it. We do this by 
        filtering the raw data by the appropriate row 
        and column filters.  If any records remain, we can show the 
        cell. As to showing the values beneath the variable, we should 
        work from the same filtered dataset. For the cell, we only look 
        at variable subtrees under the cell and all variable subtrees 
        under the root of the other dimension.
        
        E.g. cols:
                          gender
           eth                            agegp
                                nation            religion
                                region
                                
        and rows:
                year                    year
                month
       
        Should we show gender? E.g.
        SELECT gender
        FROM datasource
        WHERE NOT ISNULL(gender)
            AND ( 
            (NOT ISNULL(agegp) AND NOT ISNULL(nation) AND NOT ISNULL(region))
                OR
            (NOT ISNULL(agegp) AND NOT ISNULL(religion))
            )
            AND (
            (NOT ISNULL(year) AND NOT ISNULL(month)) 
                OR
            (NOT ISNULL(year))
            )
        GROUP BY gender                
        1) parent filters must all be true (none in example above)
        2) self field cannot be null
        3) for each subtree, no fields in subtree can be null
        4) In the other dimension, for each subtree, 
        none of the fields can have a Null value.
        """
        #1) e.g. []
        if tree_labels_node.filts:
            parent_filts = " AND ".join(tree_labels_node.filts)
        else:
            parent_filts = ""
        #2) e.g. " NOT ISNULL(gender) "
        self_filt = NOTNULL % tree_dims_node.fld
        #3 Identify fields already filtered in 1) or 2) already
        #we will remove them from field lists of subtree term nodes
        flds_done = len(tree_dims_node.filt_flds)
        #get subtree term node field lists (with already done fields sliced out)
        #e.g. gender>eth, gender>agegp>nation>region, agegp>religion
        # becomes [[eth],[agegp,nation,region],[agegp,religion]]
        subtree_term_nodes = []
        for child in tree_dims_node.children:            
            subtree_term_nodes += child.getTerminalNodes()
        if subtree_term_nodes:
            subtree_filt_fld_lsts = [x.filt_flds[flds_done:] for x \
                                     in subtree_term_nodes]
            dim_clause = self.treeFldLstsToClause(tree_fld_lsts=\
                                             subtree_filt_fld_lsts)
        else:
            dim_clause = ""
        #4 - get all subtree term node field lists (no slicing this time)
        #  e.g. year>month, year becomes [[year,month],[year]]
        oth_subtree_term_nodes = []
        for child in oth_dim_root.children:
            oth_subtree_term_nodes += child.getTerminalNodes()
        if oth_subtree_term_nodes:
            #NB the other dimension could be fieldless e.g. 
            #  we are a row dim and the oth dim has col measures
            #  and no field set
            oth_subtree_filt_fld_lsts = [x.filt_flds for x \
                                     in oth_subtree_term_nodes \
                                     if x.filt_flds != [None]]
            oth_dim_clause = self.treeFldLstsToClause(tree_fld_lsts=\
                                             oth_subtree_filt_fld_lsts)
        else:
            oth_dim_clause = ""
        #assemble
        main_clauses = []
        for clause in [parent_filts, self_filt, dim_clause, 
                       oth_dim_clause]:
            if clause:
                main_clauses.append(clause)
        final_filt_clause = " AND ".join(main_clauses)
        return final_filt_clause
    
    def treeFldLstsToClause(self, tree_fld_lsts):
        """
        [[eth],[agegp,nation,region],[agegp,religion]]
        becomes
        "((NOT ISNULL(eth)) 
            OR (NOT ISNULL(agegp) AND NOT ISNULL(nation) AND NOT ISNULL(region)) 
            OR (NOT ISNULL(agegp) AND NOT ISNULL(religion)))"
        """
        if not tree_fld_lsts:
            return None
        else:
            subtree_clauses_lst = [] #each subtree needs a parenthesised clause
            #e.g. "( NOT ISNULL(agegp) AND NOT ISNULL(religion) )"
            for subtree_lst in tree_fld_lsts:
                subtree_clauses = [NOTNULL % fld for fld \
                                            in subtree_lst]
                #e.g. " NOT ISNULL(agegp) ", " NOT ISNULL(religion) "
                #use AND within subtrees because every field must be filled
                subtree_clauses_lst.append("(" + \
                                           " AND ".join(subtree_clauses) + \
                                           ")")
            #join subtree clauses with OR because a value in any is enough to
            #  retain label 
            clause = "(" + " OR ".join(subtree_clauses_lst) + ")"
            #e.g. see method documentation at top
            return clause

        
class GenTable(LiveTable):
    "A general table (not a summary table)"

    has_row_measures = False
    has_row_vals = True
    has_col_measures = True

    def getHdrDets(self, row_label_cols_n):
        """
        Return tree_col_labels and the table header HTML.
        For HTML provide everything from <thead> to </thead>.
        """
        tree_col_labels = LabelNodeTree()
        tree_col_labels = self.addSubtreesToColLabelTree(tree_col_labels)
        return self.processHdrTree(tree_col_labels, row_label_cols_n)
        
    def getBodyHtmlRows(self, row_label_rows_lst, tree_row_labels,
                        tree_col_labels):
        """
        Make table body rows based on contents of row_label_rows_lst:
        e.g. [["<tr>", "<td class='firstrowvar' rowspan='8'>Gender</td>" ...],
        ...]
        It already contains row label data - we need to add the data cells 
        into the appropriate row list within row_label_rows_lst before
        concatenating and appending "</tr>".
        """
        col_term_nodes = tree_col_labels.getTerminalNodes()
        row_term_nodes = tree_row_labels.getTerminalNodes()
        col_filters_lst = [x.filts for x in col_term_nodes]
        col_filt_flds_lst = [x.filt_flds for x in col_term_nodes]
        col_tots_lst = [x.is_coltot for x in col_term_nodes]
        col_measures_lst = [x.measure for x in col_term_nodes]
        row_filters_lst = [x.filts for x in row_term_nodes]
        row_filt_flds_lst = [x.filt_flds for x in row_term_nodes]
        data_cells_n = len(row_term_nodes) * len(col_term_nodes)
        print "%s data cells in table" % data_cells_n
        row_label_rows_lst = self.getRowLabelsRowLst(row_filters_lst, 
            row_filt_flds_lst, col_measures_lst, col_filters_lst, 
            col_tots_lst, col_filt_flds_lst, row_label_rows_lst, 
            data_cells_n, col_term_nodes)
        return row_label_rows_lst
                
    def getRowLabelsRowLst(self, row_filters_lst, row_filt_flds_lst, 
                           col_measures_lst, col_filters_lst, 
                           col_tots_lst, col_filt_flds_lst, 
                           row_label_rows_lst, data_cells_n,
                           col_term_nodes):
        """
        Get list of row data.  Each row in the list is represented
        by a row of strings to concatenate, one per data point.
        """
        
        """Build lists of data item HTML (data_item_presn_lst)
            and data item values (results) ready to combine.
        data_item_presn_lst is a list of tuples with left and right HTML 
            wrappers for data ("<td class='%s'>" % cellclass, "</td>").  
            As each data point is processed, a tuple is added to the list.
        results is built once per batch of data points for database 
            efficiency reasons.  Each call returns multiple values."""
        i=0
        data_item_presn_lst = []
        results = ()
        SQL_table_select_clauses_lst = []
        max_select_vars = 50 #same speed between about 30 and 100 but
        #twice as slow if much smaller or larger
        for (row_filter, row_filt_flds) in zip(row_filters_lst,
                                               row_filt_flds_lst):
            #row-derived inputs for clause function
            if len(row_filter) == 1:
                all_but_last_row_filters_lst = []
            elif len(row_filter) > 1:
                all_but_last_row_filters_lst = row_filter[:]
                del all_but_last_row_filters_lst[-1] #all but the last row 
            last_row_filter = NOTNULL % row_filt_flds[-1] #for colpct
            #for styling
            first = True
            for (colmeasure, col_filter, coltot, col_filt_flds) in \
                        zip(col_measures_lst, col_filters_lst, 
                            col_tots_lst, col_filt_flds_lst):
                #get column-derived clause function inputs
                cols_not_null_lst = [NOTNULL % x for x in \
                                     col_filt_flds]
                if len(col_filter) <= 1:
                    all_but_last_col_filters_lst = []
                elif len(col_filter) > 1:
                    all_but_last_col_filters_lst = col_filter[:]
                    del all_but_last_col_filters_lst[-1] #all but the last col
                if col_filt_flds:
                    last_col_filter = NOTNULL % col_filt_flds[-1] #for rowpct
                else:
                    last_col_filter = ""
                #styling
                if first:
                    cellclass = "firstdatacell"
                    first = False
                else:
                    cellclass = "datacell"
                #build data row list
                data_item_presn_lst.append(("<td class='%s'>" % cellclass, 
                                           colmeasure, "</td>"))
                #build SQL clauses for next SQL query
                clause = self.getFuncClause(measure=colmeasure,
                          row_filters_lst=row_filter, 
                          col_filters_lst=col_filter, 
                          all_but_last_row_filters_lst=\
                              all_but_last_row_filters_lst, #needed for colpct
                          last_row_filter=last_row_filter, #needed for colpct
                          all_but_last_col_filters_lst=\
                              all_but_last_col_filters_lst, #needed for rowpct
                          last_col_filter=last_col_filter, #needed for colpct
                          cols_not_null_lst=cols_not_null_lst, #needed for rowpct
                          is_coltot=coltot
                          )
                SQL_table_select_clauses_lst.append(clause)
                #process SQL queries when number of clauses reaches certain threshold
                if len(SQL_table_select_clauses_lst) == max_select_vars \
                    or i == data_cells_n - 1:
                    SQL_select_results = "SELECT " + \
                             ", ".join(SQL_table_select_clauses_lst) + \
                             " FROM " + self.datasource
                    #print SQL_select_results #debug but reset max_select... low first
                    self.cur.execute(SQL_select_results)
                    results += self.cur.fetchone()
                    SQL_table_select_clauses_lst = []
                i=i+1
        i=0
        #using the data item HTML tuples and the results data, 
        # build the body row html
        for row in row_label_rows_lst:
            for j in range(len(col_term_nodes)):
                data_format = data_format_dic[data_item_presn_lst[i][1]]
                data_val = data_format(results[i])
                row.append(data_item_presn_lst[i][0] + \
                           data_val + data_item_presn_lst[i][2])
                i=i+1
        return row_label_rows_lst
    
    def getFuncClause(self, measure, row_filters_lst, col_filters_lst, 
                      all_but_last_row_filters_lst, last_row_filter,
                      all_but_last_col_filters_lst, last_col_filter,
                      cols_not_null_lst, is_coltot):
        """
        measure - e.g. FREQ
        row_filters_lst - effectively applies filtering to
            the total source data by setting some values to 0 or NULL
            if not a datapoint defined by the row.
        col_filters_lst - effectively applies filtering to
            the total source data by setting some values to 0 or NULL
            if not a datapoint defined by the column(s).
        all_but_last_row_filters_lst - used for colpct filtering to get 
            denominator
        last_row_filter - last row filter used for colpct filtering
            to get denominator
        all_but_last_col_filters_lst - used for rowpct filtering to get 
            denominator
        last_col_filter - last col filter used for rowpct filtering
            to get denominator
        cols_not_null_lst - used for rowpct filtering
        is_coltot - boolean
        """
        #To get freq, evaluate matching values to 1 (otherwise 0) then sum
        # 
        freq = self.abs_wrapper_l + "SUM(" + " AND ".join(\
                                row_filters_lst + col_filters_lst) + ")" + \
                                self.abs_wrapper_r
        col_freq = self.abs_wrapper_l + "SUM(" + " AND ".join(\
                    row_filters_lst + all_but_last_col_filters_lst) + ")" + \
                    self.abs_wrapper_r
        #pprint.pprint(freq) # debug
        if measure == FREQ:
            if not is_coltot:
                return freq
            else:
                return col_freq
        elif measure == COLPCT:
            if not is_coltot:
                numerator = freq
                #we want to divide by all values where all the rows but the last match.
                #the last row cannot be null.  And all column values must match.
                denom_filters_lst = []
                colpct_filter_lst = []
                colpct_filter_lst.append(" AND ".join(all_but_last_row_filters_lst))
                colpct_filter_lst.append(last_row_filter)
                colpct_filter_lst.append(" AND ".join(col_filters_lst))
            else:
                numerator = col_freq
                #we want to divide by all values where all the rows but the last match.
                #the last row cannot be null. And the col values cannot be null.
                denom_filters_lst = []
                colpct_filter_lst = []
                colpct_filter_lst.append(" AND ".join(all_but_last_row_filters_lst))
                colpct_filter_lst.append(last_row_filter)
                colpct_filter_lst.append(" AND ".join(all_but_last_col_filters_lst))                
            for filter in colpct_filter_lst:
                if filter != "":
                    denom_filters_lst.append(filter)
            denominator = self.abs_wrapper_l + "SUM(" + \
                " AND ".join(denom_filters_lst) + ")" + self.abs_wrapper_r
            perc = "100*(%s)/%s" % (numerator, denominator)
            template = self.if_clause % (NOTNULL % perc, perc, 0)
            #print template #debug
            return template
        elif measure == ROWPCT:
            if not is_coltot:
                numerator = freq
                #we want to divide by all values where all the rows match
                # and all the cols but the last one match.  The last column 
                # cannot be null.
                denom_filters_lst = []
                rowpct_filter_lst = []
                rowpct_filter_lst.append(" AND ".join(row_filters_lst))
                rowpct_filter_lst.append(" AND ".join(all_but_last_col_filters_lst))
                rowpct_filter_lst.append(last_col_filter) 
                for filter in rowpct_filter_lst:
                    if filter != "":
                        denom_filters_lst.append(filter)
                denominator = self.abs_wrapper_l + "SUM(" + \
                    " AND ".join(denom_filters_lst) + ")" + self.abs_wrapper_r
                perc = "100*(%s)/%s" % (numerator, denominator)
                template = self.if_clause % (NOTNULL % perc, perc, 0)
                #print numerator, denominator
                return template
            else:
                return "100"
        else:
            raise Exception, "Measure %s not available" % measure
        
                    
class SummTable(LiveTable):
    "A summary table - e.g. Median, Mean etc"
    
    has_row_measures = True
    has_row_vals = False
    has_col_measures = False

    def getHdrDets(self, row_label_cols_n):
        """
        Return tree_col_labels and the table header HTML.
        For HTML provide everything from <thead> to </thead>.
        If no column variables, make a special column node.
        """
        tree_col_labels = LabelNodeTree()
        tree_col_labels = self.addSubtreesToColLabelTree(tree_col_labels)
        if tree_col_labels.getDepth() == 1:
            tree_col_labels.addChild(LabelNode(label="Measures"))
        return self.processHdrTree(tree_col_labels, row_label_cols_n)
        
    def getBodyHtmlRows(self, row_label_rows_lst, tree_row_labels,
                        tree_col_labels):
        """
        Make table body rows based on contents of row_label_rows_lst:
        e.g. [["<tr>", "<td class='firstrowvar' rowspan='8'>Gender</td>" ...],
        ...]
        It already contains row label data - we need to add the data cells 
        into the appropriate row list within row_label_rows_lst before
        concatenating and appending "</tr>".
        """
        col_term_nodes = tree_col_labels.getTerminalNodes()
        row_term_nodes = tree_row_labels.getTerminalNodes()
        row_measures_lst = [x.measure for x in row_term_nodes]
        col_filters_lst = [x.filts for x in col_term_nodes] #can be [[],[],[], ...]
        row_filt_flds_lst = [x.filt_flds for x in row_term_nodes]
        col_filt_flds_lst = [x.filt_flds for x in col_term_nodes]
        col_tots_lst = [x.is_coltot for x in col_term_nodes]
        data_cells_n = len(row_term_nodes) * len(col_term_nodes)
        print "%s data cells in table" % data_cells_n
        row_label_rows_lst = self.getRowLabelsRowLst(row_filt_flds_lst, 
                                row_measures_lst, col_filters_lst, 
                                row_label_rows_lst, col_term_nodes)
        return row_label_rows_lst
    
    def getRowLabelsRowLst(self, row_flds_lst,  
                           row_measures_lst, col_filters_lst, 
                           row_label_rows_lst, col_term_nodes):
        """
        Get list of row data.  Each row in the list is represented
        by a row of strings to concatenate, one per data point.
        Get data values one at a time (no batches unlike Gen Tables).
        """
        data_item_lst = []
        for (rowmeasure, row_fld_lst) in zip(row_measures_lst, 
                                             row_flds_lst):
            first = True
            for col_filter_lst in col_filters_lst:
                #styling
                if first:
                    cellclass = "firstdatacell"
                    first = False
                else:
                    cellclass = "datacell"
                data_val = self.getDataVal(rowmeasure, row_fld_lst[0], 
                                             col_filter_lst)
                data_item_lst.append("<td class='%s'>%s</td>" % \
                                     (cellclass, data_val))
        i=0
        for row in row_label_rows_lst:
            for j in range(len(col_term_nodes)):
                row.append(data_item_lst[i])
                i=i+1
        return row_label_rows_lst
    
    def getDataVal(self, measure, row_fld, col_filter_lst):
        """
        measure - e.g. MEAN
        row_fld - the numeric field we are calculating the summary of.
        col_filter - so we only look at values in the column.
        """
        col_filt_clause = " AND ".join(col_filter_lst)
        if col_filt_clause:
            filter = " WHERE " + col_filt_clause
        else: 
            filter = ""
        sql_for_raw_only = [MEDIAN, STD_DEV]
        if measure in sql_for_raw_only:
            SQL_get_raw_vals = "SELECT " + row_fld + """
                FROM """ + self.datasource + filter
            self.cur.execute(SQL_get_raw_vals)
            data = [x[0] for x in self.cur.fetchall() if x[0]]
            #print data #debug
        if measure == SUM:
            SQL_get_sum = "SELECT SUM(%s) " % row_fld + \
                "FROM " + self.datasource + filter
            self.cur.execute(SQL_get_sum)
            data_val = self.cur.fetchone()[0]
        elif measure == MEAN:
            SQL_get_mean = "SELECT AVG(" + row_fld + """
                ) FROM """ + self.datasource + filter
            self.cur.execute(SQL_get_mean)
            data_val =  round(self.cur.fetchone()[0],2)
        elif measure == MEDIAN:
            data_val =  round(numpy.median(data),2)
        elif measure == SUMM_N:
            SQL_get_n = "SELECT COUNT(" + row_fld + """)
                FROM """ + self.datasource + filter
            self.cur.execute(SQL_get_n)
            data_val =  "N=%s" % self.cur.fetchone()[0]
        elif measure == STD_DEV:
            data_val =  round(numpy.std(data),2)
        else:
            raise Exception, "Measure not available"
        return data_val