This repository has been archived by the owner on Jul 23, 2022. It is now read-only.
/
column_type.py
824 lines (696 loc) · 25 KB
/
column_type.py
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
# -*- coding: utf-8 -*-
"""
@file
@brief Classes which defines column for class @see cl IterRow
"""
from inspect import isfunction
from .iter_exceptions import IterException, NotAllowedOperation
from .others_types import long, NA, EmptyGroup, GroupByContainer
from .column_operator import OperatorId, OperatorMul, ColumnOperator, OperatorAdd
from .column_operator import OperatorDiv, OperatorPow, OperatorSub, OperatorDivN, OperatorMod
from .column_operator import OperatorEq, OperatorNe, OperatorGe, OperatorLe, OperatorGt, OperatorLt
from .column_operator import OperatorNot, OperatorOr, OperatorAnd
from .column_operator import OperatorFunc
from .column_group_operator import OperatorGroupLen, OperatorGroupAvg
def private_function_type():
"no documentation"
pass
class ColumnType:
"""
Defines a column of a table.
"""
_default_name = "__unk__"
_str_type = {int: 'int', long: 'long', NA: 'NA',
float: 'float', str: 'str',
type(private_function_type): 'func',
}
def IsColumnType(self):
"""
checks it is a column type which used by an operator
"""
return True
@property
def ShortName(self):
"""
a short name (tells the column type)
"""
return "any"
@property
def Name(self):
"""
property
"""
return self._name
@property
def Type(self):
"""
property
"""
return self._type
@property
def Parent(self):
"""
property
"""
return self._parent
@property
def Func(self):
"""
property
"""
return self._func
def __init__(
self, name, typ, func=None, parent=tuple(), op=None, owner=None):
"""
initiates the column
@param name name of the column
@param typ type of the data it will contain (can be None)
@param func a function, if None, if will be the identity
@param parent precise a list of parents if this column was part of a formula
@param op operator to apply between the column
@param owner table which contains the column (only for further validation)
function is a function: ``f: x --> y``
"""
self._name = name
self._type = typ
self._value = None
self._parent = parent
self._op = op
self._owner = owner
if not isinstance(op, ColumnOperator):
raise IterException(
"op should be a ColumnOperator not: {0}".format(
type(op)))
if not isinstance(parent, tuple):
raise TypeError("we expect a tuple for parameter parent")
for p in parent:
p.IsColumnType()
if typ not in [int, float, long, str, None, NA,
type(private_function_type)]:
raise IterException(
"type should in [int,float,str,long,function]: " +
str(typ))
if isfunction(func):
self._func = func
elif func is None:
self._func = None
else:
raise IterException(
"type of func should in [int,float,str,long,function]: {0}".format(
str(func)))
if "_func" not in self.__dict__:
raise IterException("this column is missing a function")
def __str__(self):
"""
usual
"""
ps = "|".join([_.ShortName for _ in self._parent])
if self._value is not None:
return "CT({0},<{1}>,op:{2},#P={3})={4}".format(
self._name, ColumnType._str_type[self._type], str(self._op), ps, self())
else:
return "CT({0},<{1}>,op:{2},#P={3}) [no loop started]".format(
self._name, ColumnType._str_type[self._type], str(self._op), ps)
def __call__(self):
"""
returns func(value)
"""
if self._func is None:
if len(self._parent) == 0:
if self._value is None:
raise ValueError(
"method set must be called before for column {0}".format(
str(self)))
else:
res = self._value
elif self._op is None:
raise ValueError(
"there are parents but no operator for column {0}\nParents:\n{1}".format(
str(self),
self.print_parent()))
else:
try:
res = self._op(self._parent)
except TypeError as e:
raise IterException(
"unable(1) to apply an operator for column op=<{0}>, col={1}, TYPE={2} TYPE_OP={3} TYPE_PARENT={4}".format(
str(
self._op), str(self), type(self), type(
self._op), type(
self._parent))) from e
except AttributeError as ee:
raise IterException(
"unable(2) to apply an operator for column op=<{0}>, col={1}, TYPE={2} TYPE_OP={3} TYPE_PARENT={4}".format(
str(
self._op), str(self), type(self), type(
self._op), type(
self._parent))) from ee
if isinstance(res, ColumnType):
raise IterException(
"this evaluation(*) cannot return a ColumnType for this column: {0}".format(str(self)))
else:
# we use a shortcut
try:
res = self._func(self._value)
except TypeError as e:
raise IterException(
"unable to compute the value of {0}\n{1}".format(
str(self),
self.print_parent())) from e
if isinstance(res, ColumnType):
raise IterException(
"this evaluation cannot return a ColumnType for this column: {0}".format(
str(self)))
self.set(res)
return res
def set(self, value):
"""
Sets a value for this column.
@param value anything in ``[int, float, long, str, function]``
"""
if isinstance(value, (int, str, float, long, NA)):
self._value = value
elif isinstance(value, EmptyGroup):
# for an empty group
self._value = value
elif isinstance(value, list):
# for a group
self._value = value
else:
raise IterException(
"type of value should be in [int,float,str,long] not {0} for the column {1}".format(
type(value),
str(self)))
def set_none(self):
"""
After a loop on a database, we should put None back as a value.
"""
for p in self._parent:
p.set_none()
self._value = None
def set_name(self, new_name):
"""
Changes the name of the column.
@param newname new name
"""
self._name = new_name
def set_owner(self, new_owner):
"""
Changes the owner of the column.
@param newname new name
"""
self._owner = new_owner
def print_parent(self):
"""
Returns a string showing the dependencies of this columns.
Example:
@code
this_columns
parent1
parent11
parent12
parent2
@endcode
"""
if self._parent is None:
return self.__str__()
else:
rows = [self.__str__()]
for p in self._parent:
rs = [" " + _ for _ in p.print_parent().split("\n")]
rows.extend(rs)
return "\n".join(rows)
######################################
# functions which create other columns
######################################
def copy(self, new_owner):
"""
Returns a copy of this class.
@param new_owner new owner
@return ColumnType
"""
return ColumnType(self._name, self._type, func=None, parent=(
self,), op=OperatorId(), owner=new_owner)
#######################################
# operations
#######################################
def __mul__(self, column):
"""
These operators should be able to translate an expression
into function operating on the values.
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorMul())
else:
return self.__mul__(ColumnConstantType(column))
def __add__(self, column):
"""
These operators should be able to translate an expression
into function operating on the values.
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorAdd())
else:
return self.__add__(ColumnConstantType(column))
def __sub__(self, column):
"""
These operators should be able to translate an expression
into function operating on the values.
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorSub())
else:
return self.__sub__(ColumnConstantType(column))
def __truediv__(self, column):
"""
These operators should be able to translate an expression
into function operating on the values.
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorDiv())
else:
return self.__truediv__(ColumnConstantType(column))
def __floordiv__(self, column):
"""
These operators should be able to translate an expression
into function operating on the values.
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorDivN())
else:
return self.__floordiv__(ColumnConstantType(column))
def __mod__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorMod())
else:
return self.__mod__(ColumnConstantType(column))
def __pow__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorPow())
else:
return self.__pow__(ColumnConstantType(column))
#######################################
# test
#######################################
def __eq__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorEq())
else:
return self.__eq__(ColumnConstantType(column))
def __lt__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorLt())
else:
return self.__lt__(ColumnConstantType(column))
def __le__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorLe())
else:
return self.__le__(ColumnConstantType(column))
def __gt__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorGt())
else:
return self.__gt__(ColumnConstantType(column))
def __ge__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorGe())
else:
return self.__ge__(ColumnConstantType(column))
def __ne__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorNe())
else:
return self.__ne__(ColumnConstantType(column))
#######################################
# logical
#######################################
def Not(self):
"""
``not`` cannot be overriden
"""
return self.__not__()
def __not__(self):
"""
these operators should be able to translate an expression
into function operating on the values
@return a ColumnType
"""
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self,), op=OperatorNot())
def Or(self, column):
"""
``or`` cannot be overriden
"""
return self.__or__(column)
def __or__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorOr())
else:
return self.__or__(ColumnConstantType(column))
def And(self, column):
"""
``and`` cannot be overriden
"""
return self.__and__(column)
def __and__(self, column):
"""
these operators should be able to translate an expression
into function operating on the values
@param column a function or an int or a float or a long or a str or a ColumnType
@return a ColumnType
"""
if isinstance(column, ColumnType):
return ColumnType(ColumnType._default_name, self._type, func=None, parent=(
self, column), op=OperatorAnd())
else:
return self.__and__(ColumnConstantType(column))
#######################################
# group function
#######################################
def len(self):
"""
returns a group columns to count the number of observations
"""
return ColumnGroupType(
ColumnType._default_name, int, parent=(self,), op=OperatorGroupLen())
def count(self):
"""
returns a group columns to count the number of observations
"""
return self.len()
def avg(self):
"""
returns a group columns to return an average
"""
return ColumnGroupType(
ColumnType._default_name, float, parent=(self,), op=OperatorGroupAvg())
class ColumnConstantType(ColumnType):
"""
defines a constant as a column
"""
def __init__(self, const):
self._value = const
self._func = lambda x, c=self._value: c
self._parent = None
self._op = None
self._type = type(const)
self._const = const
self._owner = None
if isinstance(const, (int, float, long, str, NA)):
pass
else:
raise ValueError(
"this value is not a constant: {0}".format(
str(const)))
@property
def ShortName(self):
"""
a short name (tells the column type)
"""
return "cst"
def set_none(self):
"""
do nothing (it is a constant)
"""
pass
def set(self, value):
"""
do nothing (it is a constant)
@param value anything in [int,float,long,str, function ]
"""
pass
def __call__(self):
"""
return the constant
"""
return self._const
def __str__(self):
"""
usual
"""
return "cst({0})".format(self())
class ColumnTableType(ColumnType):
"""
defines a table column (not coming from an expression)
"""
def __init__(self, name, typ, owner):
"""
constructor
@param name name of the column
@param typ type of the column
@param owner owner of this column
"""
self._name = name
self._func = None
self._parent = None
self._op = None
self._type = typ
self._owner = owner
@property
def ShortName(self):
"""
a short name (tells the column type)
"""
return "col"
def set_none(self):
"""
after a loop on a database, we should put None back as a value
"""
self._value = None
def __call__(self):
"""
returns the content
"""
if self._value is None:
raise IterException(
"this column should contain a value: {0}".format(
str(self)))
return self._value
def __str__(self):
"""
usual
"""
return "col({0},{1})".format(
self._name, ColumnType._str_type[self._type])
class ColumnGroupType(ColumnType):
"""
defines a column which processes a group of rows (after a groupby)
"""
def __init__(self, name, typ, parent, op):
"""
constructor
@param name name of the column
@param typ type of the column
@param owner owner of this column
@param op operator
"""
self._name = name
self._value = None
self._parent = parent
self._opgr = op
self._op = OperatorId()
self._type = typ
self._owner = None
self._func = None
@property
def ShortName(self):
"""
a short name (tells the column type)
"""
return "group"
def set_none(self):
"""
after a loop on a database, we should put None back as a value
"""
self._value = None
def __call__(self):
"""
returns the content
"""
if isinstance(self._value, GroupByContainer):
try:
return self._opgr(self._value)
except TypeError as e:
raise IterException(
"unable(1) to apply an operator for column op=<{0}>, col={1}, TYPE={2} TYPE_OP={3}".format(
str(
self._op), str(self), type(self), type(
self._op))) from e
except AttributeError as ee:
raise IterException(
"unable(2) to apply an operator for column op=<{0}>, col={1}, TYPE={2} TYPE_OP={3}".format(
str(
self._op), str(self), type(self), type(
self._op))) from ee
else:
return super().__call__()
def __str__(self):
"""
usual
"""
return "CGT[{0}]({1})".format(str(self._opgr), self._name)
def set(self, value):
"""
sets a value for this column
@param value anything in [int,float,long,str, function ]
"""
self._value = value
if hasattr(value, "__iter__") and \
not isinstance(value, str) and \
not isinstance(value, GroupByContainer):
raise IterException(
"type of value should be GroupByContainer not {0} for the column {1}".format(
type(value),
str(self)))
def __mul__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
def __add__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
def __sub__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
def __truediv__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
def __floordiv__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
def __mod__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
def __pow__(self, column):
"""
forbidden
"""
raise NotAllowedOperation()
class CFT(ColumnType):
"""
defines a function
"""
def __init__(self, func, *l):
"""
constructor (a function cannot accept keywords)
@param func contained function
@param l list of ColumnType
"""
self._name = None
self._func = None
self._parent = None
self._op = OperatorFunc(func)
self._type = type(private_function_type)
self._owner = None
self._thisfunc = func
self._parent = tuple(l)
for _ in l:
if not isinstance(_, ColumnType):
raise TypeError("expecting a column type, not " + str(type(_)))
@property
def ShortName(self):
"""
a short name (tells the column type)
"""
return "func"
def set_none(self):
"""
after a loop on a database, we should put None back as a value
"""
self._value = None
def __str__(self):
"""
usual
"""
return "func({0},{1})".format(
self._name, ColumnType._str_type[self._type])