-
Notifications
You must be signed in to change notification settings - Fork 8
Expand file tree
/
Copy pathbase.py
More file actions
2721 lines (2141 loc) · 97.7 KB
/
base.py
File metadata and controls
2721 lines (2141 loc) · 97.7 KB
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
# Copyright (c) 2011-2024, Roger Lew [see LICENSE.txt]
# This software is funded in part by NIH Grant P20 RR016454.
import csv
import math
import sqlite3
import warnings
from copy import copy
from collections import OrderedDict, Counter
import numpy as np
from .misc import pystaggrelite3
from .misc.dictset import DictSet
from .misc.texttable import Texttable as TextTable
from .misc.support import *
from . import plotting
# base.py holds DataFrame and Pyvttbl
# this file is a bit long but they can't be split without
# running into circular import complications
def float_try_parse(x):
try:
v = float(x)
except:
v = float('nan')
return v
class DataFrame(OrderedDict):
"""holds the data in a dummy-coded group format"""
def __init__(self, *args, **kwds):
"""
initialize a :class:`DataFrame` object.
| Subclass of :mod:`collections`. :class:`OrderedDict`.
| Understands the typical initialization :class:`dict` signatures.
| Keys must be hashable.
| Values become numpy.arrays or numpy.ma.MaskedArrays.
"""
super(DataFrame, self).__init__()
#: sqlite3 connection
self.conn = sqlite3.connect(':memory:')
#: sqlite3 cursor
self.cur = self.conn.cursor()
#: list of sqlite3 aggregates
self.aggregates = tuple('avg count count group_concat ' \
'group_concat max min sum total tolist' \
.split())
# Bind pystaggrelite3 aggregators to sqlite3
for n, a, f in pystaggrelite3.getaggregators():
self.bind_aggregate(n, a, f)
#: prints the sqlite3 queries to stdout before
#: executing them for debugging purposes
self.PRINTQUERIES = False
#: controls whether plot functions return the test dictionaries
self.TESTMODE = False
#: holds the factors conditions in a DictSet Singleton
self.conditions = DictSet()
#: dict to map keys to sqlite3 types
self._sqltypesdict = {}
super(DataFrame, self).update(*args, **kwds)
def bind_aggregate(self, name, arity, func):
"""
binds a sqlite3 aggregator to :class:`DataFrame`
args:
name: string to be associated with the aggregator
arity: the number of inputs required by the aggregator
func: the aggregator class
returns:
None
| :class:`DataFrame`.aggregates is a list of the available aggregators.
| For information on rolling your own aggregators see:
http://docs.python.org/library/sqlite3.html
"""
self.conn.create_aggregate(name, arity, func)
self.aggregates = list(self.aggregates)
self.aggregates.append(name)
self.aggregates = tuple(self.aggregates)
def _get_sqltype(self, key):
"""
returns the sqlite3 type associated with the provided key
args:
key: key in :class:`DataFrame` (raises KeyError if key not in self)
returns:
a string specifiying the sqlite3 type associated with the data in self[key]:
{ 'null', 'integer', 'real', 'text'}
"""
return self._sqltypesdict[key]
def _get_nptype(self, key):
"""
returns the numpy type object associated with the provided key
args:
key: key in :class:`DataFrame` (raises KeyError if key not in self)
returns:
a numpy object specifiying the type associated with the data in self[key]:
========= ================
sql type numpy type
========= ================
'null' np.dtype(object)
'integer' np.dtype(int)
'real' np.dtype(float)
'text' np.dtype(str)
========= ================
"""
return {'null' : np.dtype(object),
'integer' : np.dtype(int),
'real' : np.dtype(float),
'text' : np.dtype(str)}[self._sqltypesdict[key]]
def _get_mafillvalue(self, key):
"""
returns the default fill value for invalid data associated with the provided key.
args:
key: key in :class:`DataFrame` (raises KeyError if key not in self)
returns:
string, float, or int associated with the data in self[key]
========= ============
sql type default
========= ============
'null' '?'
'integer' 999999
'real' 1e20
'text' 'N/A'
========= ============
| returned values match the defaults associated with np.ma.MaskedArray
"""
return {'null' : '?',
'integer' : 999999,
'real' : 1e20,
'text' : 'N/A'}[self._sqltypesdict[key]]
def read_tbl(self, fname, skip=0, delimiter=',',labels=True):
"""
loads tabulated data from a plain text file
args:
fname: path and name of datafile
kwds:
skip: number of lines to skip before looking for column labels. (default = 0)
delimiter: string to seperate values (default = "'")
labels: bool specifiying whether first row (after skip) contains labels.
(default = True)
returns:
None
| Checks and renames duplicate column labels as well as checking
| for missing cells. readTbl will warn and skip over missing lines.
"""
# open and read dummy coded data results file to data dictionary
fid = open(fname, 'r')
csv_reader = csv.reader(fid, delimiter=delimiter)
data = OrderedDict()
mask = {}
colnames = []
for i, row in enumerate(csv_reader):
# skip requested rows
if i < skip:
pass
# read column labels from ith+1 line
elif i == skip and labels:
colnameCounter = Counter()
for k, colname in enumerate(row):
colname = colname.strip()#.replace(' ','_')
colnameCounter[colname] += 1
if colnameCounter[colname] > 1:
warnings.warn("Duplicate label '%s' found"
%colname,
RuntimeWarning)
colname += '_%i'%colnameCounter[colname]
colnames.append(colname)
data[colname] = []
mask[colname] = []
# if labels is false we need to make labels
elif i == skip and not labels:
colnames = ['COL_%s'%(k+1) for k in range(len(row))]
for j,colname in enumerate(colnames):
if _isfloat(row[j]):
data[colname] = [float(row[j])]
mask[colname] = [0]
else:
data[colname] = [row[i]]
if row[i] == '':
mask[colname] = [1]
else:
mask[colname] = [0]
# for remaining lines where i>skip...
else:
if len(row) != len(colnames):
warnings.warn('Skipping line %i of file. '
'Expected %i cells found %i'\
%(i+1, len(colnames), len(row)),
RuntimeWarning)
else:
for j, colname in enumerate(colnames):
colname = colname.strip()
if _isfloat(row[j]):
data[colname].append(float(row[j]))
mask[colname].append(0)
else:
data[colname].append(row[j])
if row[j] == '':
mask[colname].append(1)
else:
mask[colname].append(0)
# close data file
fid.close()
self.clear()
for k, v in data.items():
## In __setitem__ the conditions DictSet and datatype are set
self.__setitem__(k, v, mask[k])
del data
def __setitem__(self, key, item, mask=None):
"""
assign a column in the table
args:
key: hashable object to associate with item
item: an iterable that is put in an np.array or np.ma.array
kwds:
mask: mask value passed to np.ma.MaskedArray.__init__()
returns:
None
| df.__setitem__(key, item) <==> df[key] = item
| The assigned item must be iterable. To add a single row use
the insert method. To another table to this one use
the attach method.
example:
>>> ...
>>> print(df)
first last age gender
==================================
Roger Lew 28 male
Bosco Robinson 5 male
Megan Whittington 26 female
John Smith 51 male
Jane Doe 49 female
>>> import numpy as np
>>> df['log10(age)'] = np.log10(df['age'])
>>> print(df)
first last age gender log10(age)
===============================================
Roger Lew 28 male 1.447
Bosco Robinson 5 male 0.699
Megan Whittington 26 female 1.415
John Smith 51 male 1.708
Jane Doe 49 female 1.690
>>>
"""
# check item
if not hasattr(item, '__iter__'):
raise TypeError("'%s' object is not iterable"%type(item).__name__)
if key in self.keys():
del self[key]
# a mask was provided
if mask is not None:
# data contains invalid entries and a masked array should be created
# this needs to be nested incase mask is not None
if not all([m==0 for m in mask]):
# figure out the datatype of the valid entries
self._sqltypesdict[key] = \
self._determine_sqlite3_type([d for d, m in zip(item,mask) if not m])
# replace invalid values
fill_val = self._get_mafillvalue(key)
x = np.array([(d, fill_val)[m] for d, m in zip(item,mask)])
# call super.__setitem__
super(DataFrame, self).\
__setitem__(key, \
np.ma.array(x, mask=mask, dtype=self._get_nptype(key)))
# set or update self.conditions DictSet
self.conditions[key] = self[key]
# return if successful
return
# no mask provided or mask is all true
self._sqltypesdict[key] = self._determine_sqlite3_type(item)
super(DataFrame, self).\
__setitem__(key, np.array(item, dtype=self._get_nptype(key)))
self.conditions[key] = self[key]
## def __iter__(self):
## raise NotImplementedError('use .keys() to iterate')
def __delitem__(self, key):
"""
delete a column from the table
args:
key: associated with the item to delete
returns:
None
| df.__delitem__(key) <==> del df[key]
example:
>>> ...
>>> print(df)
first last age gender log10(age)
===============================================
Roger Lew 28 male 1.447
Bosco Robinson 5 male 0.699
Megan Whittington 26 female 1.415
John Smith 51 male 1.708
Jane Doe 49 female 1.690
>>> del df['log10(age)']
>>> print(df)
first last age gender
==================================
Roger Lew 28 male
Bosco Robinson 5 male
Megan Whittington 26 female
John Smith 51 male
Jane Doe 49 female
>>>
"""
del self._sqltypesdict[key]
del self.conditions[key]
super(DataFrame, self).__delitem__(key)
def __str__(self):
"""
returns human friendly string representation of object
args:
None
returns:
string with easy to read representation of table
| df.__str__() <==> str(df)
"""
if self == {}:
return '(table is empty)'
tt = TextTable(max_width=100000000)
dtypes = [t[0] for t in self.types()]
dtypes = list(''.join(dtypes).replace('r', 'f'))
tt.set_cols_dtype(dtypes)
aligns = [('l','r')[dt in 'fi'] for dt in dtypes]
tt.set_cols_align(aligns)
tt.header(list(self.keys()))
if self.shape()[1] > 0:
tt.add_rows(list(zip(*list(self.values()))), header=False)
tt.set_deco(TextTable.HEADER)
# output the table
return tt.draw()
def row_iter(self):
"""
iterate over the rows in table
args:
None
returns:
iterator that yields OrderedDict objects with (key,value) pairs
cooresponding to the data in each row
example:
>>> print(df)
first last age gender
==================================
Roger Lew 28 male
Bosco Robinson 5 male
Megan Whittington 26 male
John Smith 51 female
Jane Doe 49 female
>>> for case in df.row_iter():
print(case)
OrderedDict([('first', 'Roger'), ('last', 'Lew'), ('age', 28), ('gender', 'male')])
OrderedDict([('first', 'Bosco'), ('last', 'Robinson'), ('age', 5), ('gender', 'male')])
OrderedDict([('first', 'Megan'), ('last', 'Whittington'), ('age', 26), ('gender', 'male')])
OrderedDict([('first', 'John'), ('last', 'Smith'), ('age', 51), ('gender', 'female')])
OrderedDict([('first', 'Jane'), ('last', 'Doe'), ('age', 49), ('gender', 'female')])
>>>
"""
for i in range(self.shape()[1]):
yield OrderedDict([(k, self[k][i]) for k in self])
def types(self):
"""
returns a list of the sqlite3 datatypes of the columns
args:
None
returns:
an ordered list of sqlite3 types.
| order matches self.keys()
"""
if len(self) == 0:
return []
return [self._sqltypesdict[k] for k in self]
def shape(self):
"""
returns the size of the data in the table as a tuple
args:
None
returns:
tuple (number of columns, number of rows)
"""
if len(self) == 0:
return (0, 0)
return (len(self), len(list(self.values())[0]))
def _are_col_lengths_equal(self):
"""
private method to check if the items in self have equal lengths
args:
None
returns:
returns True if all the items are equal
returns False otherwise
"""
if len(self) < 2:
return True
# if self is not empty
counts = [len(c) for c in self.values()]
if all(c - counts[0] + 1 == 1 for c in counts):
return True
else:
return False
def _determine_sqlite3_type(self, iterable):
"""
determine the sqlite3 datatype of iterable
args:
iterable: a 1-d iterable (list, tuple, np.array, etc.)
returns:
sqlite3 type as string: 'null', 'integer', 'real', or 'text'
"""
if len(iterable) == 0:
return 'null'
elif all(map(_isint, iterable)):
return 'integer'
elif all(map(_isfloat, iterable)):
return 'real'
else:
return 'text'
def _execute(self, query, t=None):
"""
private method to execute sqlite3 query
| When the PRINTQUERIES bool is true it prints the queries
before executing them
"""
if t is None:
t=tuple()
if self.PRINTQUERIES:
print(query)
if len(t) > 0:
print(' ', t)
print()
self.cur.execute(query, t)
def _executemany(self, query, tlist):
"""
private method to execute sqlite3 queries
| When the PRINTQUERIES bool is true it prints the queries
before executing them. The execute many method is about twice
as fast for building tables as the execute method.
"""
if self.PRINTQUERIES:
print(query)
print(' ', tlist[0])
print(' ...\n')
self.cur.executemany(query, tlist)
def _get_indices_where(self, where):
"""
determines the indices cooresponding to the conditions specified by the where
argument.
args:
where: a string criterion without the 'where'
returns:
a list of indices
"""
# preprocess where
tokens = []
nsubset2 = set()
names = self.keys()
for w in where.split():
print(w)
if w in names:
tokens.append(_sha1(w))
nsubset2.add(w)
else:
tokens.append(w)
where = ' '.join(tokens)
super(DataFrame, self).__setitem__(('INDICES','integer'),
list(range(self.shape()[1])))
nsubset2.add('INDICES')
# build the table
self.conn.commit()
self._execute('drop table if exists GTBL')
self.conn.commit()
query = 'create temp table GTBL\n ('
query += ', '.join('%s %s'%(_sha1(n), self._get_sqltype(n)) for n in nsubset2)
query += ')'
self._execute(query)
# build insert query
query = 'insert into GTBL values ('
query += ','.join('?' for n in nsubset2) + ')'
self._executemany(query, list(zip(*[self[n] for n in nsubset2])))
self.conn.commit()
super(DataFrame, self).__delitem__(('INDICES','integer'))
# get the indices
query = 'select %s from GTBL where %s'%(_sha1('INDICES'), where)
self._execute(query)
def _build_sqlite3_tbl(self, nsubset, where=None):
"""
build or rebuild sqlite table with columns in nsubset based on
the where list.
args:
nsubset: a list of keys to include in the table
where: criterion the entries in the table must satisfy
returns:
None
| where can be a list of tuples. Each tuple should have three
elements. The first should be a column key (label). The second
should be an operator: in, =, !=, <, >. The third element
should contain value for the operator.
| where can also be a list of strings. or a single string.
| sqlite3 table is built in memory and has the id TBL
"""
if where is None:
where = []
if isinstance(where, str):
where = [where]
# 1. Perform some checking
##############################################################
if not hasattr(where, '__iter__'):
raise TypeError( "'%s' object is not iterable"
% type(where).__name__)
# 2. Figure out which columns need to go into the table
# to be able to filter the data
##############################################################
nsubset2 = set(nsubset)
for item in where:
if isinstance(item, str):
tokens = item.split()
if tokens[0] not in self.keys():
raise KeyError(tokens[0])
nsubset2.update(w for w in tokens if w in self.keys())
else: # tuple
if item[0] in self.keys():
nsubset2.add(item[0])
# orders nsubset2 to match the order in self.keys()
nsubset2 = [n for n in self if n in nsubset2]
# 3. Build a table
##############################################################
self.conn.commit()
self._execute('drop table if exists TBL2')
if len(nsubset2) == 0:
return
self.conn.commit()
query = 'create temp table TBL2\n ('
query += ', '.join('%s %s'%(_sha1(n), self._get_sqltype(n)) for n in nsubset2)
query += ')'
self._execute(query)
# build insert query
query = 'insert into TBL2 values ('
query += ','.join('?' for n in nsubset2) + ')'
# because sqlite3 does not understand numpy datatypes we need to recast them
# using astype to numpy.object
self._executemany(query, list(zip(*[self[n].astype(object) for n in nsubset2])))
self.conn.commit()
# 4. If where is None then we are done. Otherwise we need
# to build query to filter the rows
##############################################################
if where == []:
self._execute('drop table if exists TBL')
self.conn.commit()
self._execute('alter table TBL2 rename to TBL')
self.conn.commit()
else:
# Initialize another temporary table
self._execute('drop table if exists TBL')
self.conn.commit()
query = []
for n in nsubset:
query.append('%s %s'%(_sha1(n), self._get_sqltype(n)))
query = ', '.join(query)
query = 'create temp table TBL\n (' + query + ')'
self._execute(query)
# build filter query
query = []
for item in where:
# process item as a string
if isinstance(item, str):
tokens = []
for word in item.split():
if word in self.keys():
tokens.append(_sha1(word))
else:
tokens.append(word)
query.append(' '.join(tokens))
# process item as a tuple
else:
try:
(k,op,value) = item
except:
raise Exception('could not upack tuple from where')
if _isfloat(value):
query.append(' %s %s %s'%(_sha1(k), op, value))
elif isinstance(value,list):
if _isfloat(value[0]):
args = ', '.join(str(v) for v in value)
else:
args = ', '.join('"%s"'%v for v in value)
query.append(' %s %s (%s)'%(_sha1(k), op, args))
else:
query.append(' %s %s "%s"'%(_sha1(str(k)), op, value))
query = ' and '.join(query)
nstr = ', '.join(_sha1(n) for n in nsubset)
query = 'insert into TBL select %s from TBL2\n where '%nstr + query
# run query
self._execute(query)
self.conn.commit()
# delete TBL2
self._execute('drop table if exists TBL2')
self.conn.commit()
def _get_sqlite3_tbl_info(self):
"""
private method to get a list of tuples containing information
relevant to the current sqlite3 table
args:
None
returns:
list of tuples:
| Each tuple cooresponds to a column.
| Tuples include the column name, data type, whether or not the
| column can be NULL, and the default value for the column.
"""
self.conn.commit()
self._execute('PRAGMA table_info(TBL)')
return list(self.cur)
def pivot(self, val, rows=None, cols=None, aggregate='avg',
where=None, attach_rlabels=False, method='valid'):
"""
produces a contingency table according to the arguments and keywords
provided.
args:
val: the colname to place as the data in the table
kwds:
rows: list of colnames whos combinations will become rows
in the table if left blank their will be one row
cols: list of colnames whos combinations will become cols
in the table if left blank their will be one col
aggregate: function applied across data going into each cell
of the table <http://www.sqlite.org/lang_aggfunc.html>_
where: list of tuples or list of strings for filtering data
method:
'valid': only returns rows or columns with valid entries.
'full': return full factorial combinations of the
conditions specified by rows and cols
returns:
:class:`PyvtTbl` object
"""
if rows is None:
rows = []
if cols is None:
cols = []
if where is None:
where = []
##############################################################
# pivot programmatic flow #
##############################################################
# 1. Check to make sure the table can be pivoted with the #
# specified parameters #
# 2. Create a sqlite table with only the data in columns #
# specified by val, rows, and cols. Also eliminate #
# rows that meet the exclude conditions #
# 3. Build rnames and cnames lists #
# 4. Build query based on val, rows, and cols #
# 5. Run query #
# 6. Read data to from cursor into a list of lists #
# 7. Query grand, row, and column totals #
# 8. Clean up #
# 9. flatten if specified #
# 10. Initialize and return PyvtTbl Object #
##############################################################
# 1. Check to make sure the table can be pivoted with the
# specified parameters
##############################################################
# This may seem excessive but it provides better feedback
# to the user if the errors can be parsed out before had
# instead of crashing on confusing looking code segments
# check to see if data columns have equal lengths
if not self._are_col_lengths_equal():
raise Exception('columns have unequal lengths')
# check the supplied arguments
if val not in self.keys():
raise KeyError(val)
if not hasattr(rows, '__iter__'):
raise TypeError( "'%s' object is not iterable"
% type(cols).__name__)
if not hasattr(cols, '__iter__'):
raise TypeError( "'%s' object is not iterable"
% type(cols).__name__)
for k in rows:
if k not in self.keys():
raise KeyError(k)
for k in cols:
if k not in self.keys():
raise KeyError(k)
# check for duplicate names
dup = Counter([val] + rows + cols)
del dup[None]
if not all(count == 1 for count in dup.values()):
raise Exception('duplicate labels specified')
# check aggregate function
aggregate = aggregate.lower()
if aggregate not in self.aggregates:
raise ValueError("supplied aggregate '%s' is not valid"%aggregate)
# check to make sure where is properly formatted
# todo
# 2. Create a sqlite table with only the data in columns
# specified by val, rows, and cols. Also eliminate
# rows that meet the exclude conditions
##############################################################
self._build_sqlite3_tbl([val] + rows + cols, where)
# 3. Build rnames and cnames lists
##############################################################
# Refresh conditions list so we can build row and col list
self._execute('select %s from TBL'
%', '.join(_sha1(n) for n in [val] + rows + cols))
Zconditions = DictSet(list(zip([val]+rows+cols, list(zip(*list(self.cur))))))
# rnames_mask and cnanes_mask specify which unique combinations of
# factor conditions have valid entries in the table.
# 1 = valid
# 0 = not_valid
# Build rnames
if rows == []:
rnames = [1]
rnames_mask = [1]
else:
rnames = []
rnames_mask = []
conditions_set = set(zip(*[self[n] for n in rows]))
for vals in Zconditions.unique_combinations(rows):
rnames_mask.append(tuple(vals) in conditions_set)
rnames.append(list(zip(rows,vals)))
# Build cnames
if cols == []:
cnames = [1]
cnames_mask = [1]
else:
cnames = []
cnames_mask = []
conditions_set = set(zip(*[self[n] for n in cols]))
for vals in Zconditions.unique_combinations(cols):
cnames_mask.append(tuple(vals) in conditions_set)
cnames.append(list(zip(cols,vals)))
# 4. Build query based on val, rows, and cols
##############################################################
# Here we are using string formatting to build the query.
# This method is generally discouraged for security, but
# in this circumstance I think it should be okay. The column
# labels are protected with leading and trailing underscores.
# The rest of the query is set by the logic.
#
# When we pass the data in we use the (?) tuple format
if aggregate == 'tolist':
agg = 'group_concat'
else:
agg = aggregate
query = ['select ']
if rnames == [1] and cnames == [1]:
query.append('%s( %s ) from TBL'%(agg, _sha1(val)))
else:
if rnames == [1]:
query.append(_sha1(val))
else:
query.append(', '.join(_sha1(r) for r in rows))
if cnames == [1]:
query.append('\n , %s( %s )'%(agg, _sha1(val)))
else:
for cs in cnames:
query.append('\n , %s( case when '%agg)
if all(map(_isfloat, list(zip(*cols))[1])):
query.append(
' and '.join(('%s=%s'%(_sha1(k), v) for k, v in cs)))
else:
query.append(
' and '.join(('%s="%s"'%(_sha1(k) ,v) for k, v in cs)))
query.append(' then %s end )'%_sha1(val))
if rnames == [1]:
query.append('\nfrom TBL')
else:
query.append('\nfrom TBL group by ')
for i, r in enumerate(rows):
if i != 0:
query.append(', ')
query.append(_sha1(r))
# 5. Run Query
##############################################################
self._execute(''.join(query))
# 6. Read data from cursor into a list of lists
##############################################################
data, mask = [],[]
val_type = self._get_sqltype(val)
fill_val = self._get_mafillvalue(val)
# keep the columns with the row labels
if attach_rlabels:
cnames = [(r, '') for r in rows].extend(cnames)
cnames_mask = [1 for i in range(len(rows))].extend(cnames_mask)
if aggregate == 'tolist':
if method=='full':
i=0
for row in self.cur:
while not rnames_mask[i]:
data.append([[fill_val] for j in range(len(cnames))])
mask.append([[True] for j in range(len(cnames))])
i+=1
data.append([])
mask.append([])
for cell, _mask in zip(list(row)[-len(cnames):], cnames_mask):
if cell is None or not _mask:
data[-1].append([fill_val])
mask[-1].append([True])
else:
if val_type == 'real' or val_type == 'integer':
split =cell.split(',')
data[-1].append([float(v) for v in split])
mask[-1].append([False for j in range(len(split))])
else:
split =cell.split(',')
data[-1].append(split)
mask[-1].append([False for j in range(len(split))])
i+=1
else:
for row in self.cur:
data.append([])