forked from tobgu/qframe
-
Notifications
You must be signed in to change notification settings - Fork 0
/
qframe.go
1277 lines (1092 loc) · 35.7 KB
/
qframe.go
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
package qframe
import (
"database/sql"
stdcsv "encoding/csv"
"fmt"
"io"
"reflect"
"sort"
"strings"
"github.com/tobgu/qframe/config/rolling"
"github.com/tobgu/qframe/config/csv"
"github.com/tobgu/qframe/config/eval"
"github.com/tobgu/qframe/config/groupby"
"github.com/tobgu/qframe/config/newqf"
qsql "github.com/tobgu/qframe/config/sql"
"github.com/tobgu/qframe/filter"
"github.com/tobgu/qframe/internal/bcolumn"
"github.com/tobgu/qframe/internal/column"
"github.com/tobgu/qframe/internal/ecolumn"
"github.com/tobgu/qframe/internal/fcolumn"
"github.com/tobgu/qframe/internal/grouper"
"github.com/tobgu/qframe/internal/icolumn"
"github.com/tobgu/qframe/internal/index"
qfio "github.com/tobgu/qframe/internal/io"
qfsqlio "github.com/tobgu/qframe/internal/io/sql"
"github.com/tobgu/qframe/internal/math/integer"
"github.com/tobgu/qframe/internal/scolumn"
qfsort "github.com/tobgu/qframe/internal/sort"
qfstrings "github.com/tobgu/qframe/internal/strings"
"github.com/tobgu/qframe/qerrors"
"github.com/tobgu/qframe/types"
// This dependency has been been added just to make sure that "go get" installs it.
_ "github.com/mauricelam/genny/generic"
)
type namedColumn struct {
column.Column
name string
pos int
}
func (ns namedColumn) ByteSize() int {
return ns.Column.ByteSize() + 2*8 + 8 + len(ns.name)
}
// QFrame holds a number of columns together and offers methods for filtering,
// group+aggregate and data manipulation.
type QFrame struct {
columns []namedColumn
columnsByName map[string]namedColumn
index index.Int
// Err indicates that an error has occurred while running an operation.
// If Err is set it will prevent any further operations from being executed
// on the QFrame.
Err error
}
func (qf QFrame) withErr(err error) QFrame {
return QFrame{Err: err, columns: qf.columns, columnsByName: qf.columnsByName, index: qf.index}
}
func (qf QFrame) withIndex(ix index.Int) QFrame {
return QFrame{Err: qf.Err, columns: qf.columns, columnsByName: qf.columnsByName, index: ix}
}
// ConstString describes a string column with only one value. It can be used
// during during construction of new QFrames.
type ConstString struct {
Val *string
Count int
}
// ConstInt describes a string column with only one value. It can be used
// during during construction of new QFrames.
type ConstInt struct {
Val int
Count int
}
// ConstFloat describes a string column with only one value. It can be used
// during during construction of new QFrames.
type ConstFloat struct {
Val float64
Count int
}
// ConstBool describes a string column with only one value. It can be used
// during during construction of new QFrames.
type ConstBool struct {
Val bool
Count int
}
func createColumn(name string, data interface{}, config *newqf.Config) (column.Column, error) {
var localS column.Column
if sc, ok := data.([]string); ok {
// Convenience conversion to support string slices in addition
// to string pointer slices.
sp := make([]*string, len(sc))
for i := range sc {
sp[i] = &sc[i]
}
data = sp
}
var err error
switch t := data.(type) {
case []int:
localS = icolumn.New(t)
case ConstInt:
localS = icolumn.NewConst(t.Val, t.Count)
case []float64:
localS = fcolumn.New(t)
case ConstFloat:
localS = fcolumn.NewConst(t.Val, t.Count)
case []*string:
if values, ok := config.EnumColumns[name]; ok {
localS, err = ecolumn.New(t, values)
if err != nil {
return nil, qerrors.Propagate(fmt.Sprintf("New columns %s", name), err)
}
// Book keeping
delete(config.EnumColumns, name)
} else {
localS = scolumn.New(t)
}
case ConstString:
if values, ok := config.EnumColumns[name]; ok {
localS, err = ecolumn.NewConst(t.Val, t.Count, values)
if err != nil {
return nil, qerrors.Propagate(fmt.Sprintf("New columns %s", name), err)
}
// Book keeping
delete(config.EnumColumns, name)
} else {
localS = scolumn.NewConst(t.Val, t.Count)
}
case []bool:
localS = bcolumn.New(t)
case ConstBool:
localS = bcolumn.NewConst(t.Val, t.Count)
case ecolumn.Column:
localS = t
case qfstrings.StringBlob:
localS = scolumn.NewBytes(t.Pointers, t.Data)
case column.Column:
localS = t
default:
return nil, qerrors.New("createColumn", `unknown column data type "%s" for column "%s"`, reflect.TypeOf(t), name)
}
return localS, nil
}
// New creates a new QFrame with column content from data.
//
// Time complexity O(m * n) where m = number of columns, n = number of rows.
func New(data map[string]types.DataSlice, fns ...newqf.ConfigFunc) QFrame {
config := newqf.NewConfig(fns)
for colName := range data {
if err := qfstrings.CheckName(colName); err != nil {
return QFrame{Err: qerrors.Propagate("New", err)}
}
}
if len(config.ColumnOrder) == 0 {
config.ColumnOrder = make([]string, 0, len(data))
for name := range data {
config.ColumnOrder = append(config.ColumnOrder, name)
sort.Strings(config.ColumnOrder)
}
}
if len(config.ColumnOrder) != len(data) {
return QFrame{Err: qerrors.New("New", "number of columns and columns order length do not match, %d, %d", len(config.ColumnOrder), len(data))}
}
for _, name := range config.ColumnOrder {
if _, ok := data[name]; !ok {
return QFrame{Err: qerrors.New("New", `column "%s" in column order does not exist`, name)}
}
}
columns := make([]namedColumn, len(data))
colByName := make(map[string]namedColumn, len(data))
firstLen, currentLen := 0, 0
for i, name := range config.ColumnOrder {
col := data[name]
localCol2, err := createColumn(name, col, config)
if err != nil {
return QFrame{Err: err}
}
columns[i] = namedColumn{name: name, Column: localCol2, pos: i}
colByName[name] = columns[i]
currentLen = localCol2.Len()
if firstLen == 0 {
firstLen = currentLen
}
if firstLen != currentLen {
return QFrame{Err: qerrors.New("New", "different lengths on columns not allowed")}
}
}
if len(config.EnumColumns) > 0 {
colNames := make([]string, 0)
for k := range config.EnumColumns {
colNames = append(colNames, k)
}
return QFrame{Err: qerrors.New("New", "unknown enum columns: %v", colNames)}
}
return QFrame{columns: columns, columnsByName: colByName, index: index.NewAscending(uint32(currentLen)), Err: nil}
}
// Contains reports if a columns with colName is present in the frame.
//
// Time complexity is O(1).
func (qf QFrame) Contains(colName string) bool {
_, ok := qf.columnsByName[colName]
return ok
}
// Filter filters the frame according to the filters in clause.
//
// Filters are applied via depth first traversal of the provided filter clause from left
// to right. Use the following rules of thumb for best performance when constructing filters:
//
// 1. Cheap filters (eg. integer comparisons, ...) should go to the left of more
// expensive ones (eg. string regex, ...).
// 2. High impact filters (eg. filters that you expect will drop a lot of data) should go to
// the left of low impact filters.
//
// Time complexity O(m * n) where m = number of columns to filter by, n = number of rows.
func (qf QFrame) Filter(clause FilterClause) QFrame {
if qf.Err != nil {
return qf
}
return clause.filter(qf)
}
func unknownCol(c string) string {
return fmt.Sprintf(`unknown column: "%s"`, c)
}
func (qf QFrame) filter(filters ...filter.Filter) QFrame {
if qf.Err != nil {
return qf
}
bIndex := index.NewBool(qf.index.Len())
for _, f := range filters {
s, ok := qf.columnsByName[f.Column]
if !ok {
return qf.withErr(qerrors.New("Filter", unknownCol(f.Column)))
}
if name, ok := f.Arg.(types.ColumnName); ok {
argC, ok := qf.columnsByName[string(name)]
if !ok {
return qf.withErr(qerrors.New("Filter", `unknown argument column: "%s"`, name))
}
// Allow comparison of int and float columns by temporarily promoting int column to float.
// This is expensive compared to a comparison between columns of the same type and should be avoided
// if performance is critical.
if ic, ok := s.Column.(icolumn.Column); ok {
if _, ok := argC.Column.(fcolumn.Column); ok {
s.Column = fcolumn.New(ic.FloatSlice())
}
} else if _, ok := s.Column.(fcolumn.Column); ok {
if ic, ok := argC.Column.(icolumn.Column); ok {
argC.Column = fcolumn.New(ic.FloatSlice())
}
} // else: No conversions for other combinations
f.Arg = argC.Column
}
var err error
if f.Inverse {
// This is a small optimization, if the inverse operation is implemented
// as built in on the columns use that directly to avoid building an inverse boolean
// index further below.
done := false
if sComp, ok := f.Comparator.(string); ok {
if inverse, ok := filter.Inverse[sComp]; ok {
err = s.Filter(qf.index, inverse, f.Arg, bIndex)
// Assume inverse not implemented in case of error here
if err == nil {
done = true
}
}
}
if !done {
// TODO: This branch needs proper testing
invBIndex := index.NewBool(bIndex.Len())
err = s.Filter(qf.index, f.Comparator, f.Arg, invBIndex)
if err == nil {
for i, x := range bIndex {
if !x {
bIndex[i] = !invBIndex[i]
}
}
}
}
} else {
err = s.Filter(qf.index, f.Comparator, f.Arg, bIndex)
}
if err != nil {
return qf.withErr(qerrors.Propagate(fmt.Sprintf("Filter column '%s'", f.Column), err))
}
}
return qf.withIndex(qf.index.Filter(bIndex))
}
// Equals compares this QFrame to another QFrame.
// If the QFrames are equal (true, "") will be returned else (false, <string describing why>) will be returned.
//
// Time complexity O(m * n) where m = number of columns to group by, n = number of rows.
func (qf QFrame) Equals(other QFrame) (equal bool, reason string) {
if len(qf.index) != len(other.index) {
return false, "Different length"
}
if len(qf.columns) != len(other.columns) {
return false, "Different number of columns"
}
for i, s := range qf.columns {
otherCol := other.columns[i]
if s.name != otherCol.name {
return false, fmt.Sprintf("Column name difference at %d, %s != %s", i, s.name, otherCol.name)
}
if !s.Equals(qf.index, otherCol.Column, other.index) {
return false, fmt.Sprintf("Content of columns %s differ", s.name)
}
}
return true, ""
}
// Len returns the number of rows in the QFrame.
//
// Time complexity O(1).
func (qf QFrame) Len() int {
if qf.Err != nil {
return -1
}
return qf.index.Len()
}
// Order is used to specify how sorting should be performed.
type Order struct {
// Column is the name of the column to sort by.
Column string
// Reverse specifies if sorting should be performed ascending (false, default) or descending (true)
Reverse bool
// NullLast specifies if null values should go last (true) or first (false, default) for columns that support null.
NullLast bool
}
// Sort returns a new QFrame sorted according to the orders specified.
//
// Time complexity O(m * n * log(n)) where m = number of columns to sort by, n = number of rows in QFrame.
func (qf QFrame) Sort(orders ...Order) QFrame {
if qf.Err != nil {
return qf
}
if len(orders) == 0 {
return qf
}
comparables := make([]column.Comparable, 0, len(orders))
for _, o := range orders {
s, ok := qf.columnsByName[o.Column]
if !ok {
return qf.withErr(qerrors.New("Sort", unknownCol(o.Column)))
}
comparables = append(comparables, s.Comparable(o.Reverse, false, o.NullLast))
}
newDf := qf.withIndex(qf.index.Copy())
sorter := qfsort.New(newDf.index, comparables)
sorter.Sort()
return newDf
}
// ColumnNames returns the names of all columns in the QFrame.
//
// Time complexity O(n) where n = number of columns.
func (qf QFrame) ColumnNames() []string {
result := make([]string, len(qf.columns))
for i, s := range qf.columns {
result[i] = s.name
}
return result
}
// ColumnTypes returns all underlying column types.DataType
//
// Time complexity O(n) where n = number of columns.
func (qf QFrame) ColumnTypes() []types.DataType {
types := make([]types.DataType, len(qf.columns))
for i, col := range qf.columns {
types[i] = col.DataType()
}
return types
}
// ColumnTypeMap returns a map of each underlying column with
// the column name as a key and it's types.DataType as a value.
//
// Time complexity O(n) where n = number of columns.
func (qf QFrame) ColumnTypeMap() map[string]types.DataType {
types := map[string]types.DataType{}
for name, col := range qf.columnsByName {
types[name] = col.DataType()
}
return types
}
func (qf QFrame) columnsOrAll(columns []string) []string {
if len(columns) == 0 {
return qf.ColumnNames()
}
return columns
}
func (qf QFrame) orders(columns []string) []Order {
orders := make([]Order, len(columns))
for i, col := range columns {
orders[i] = Order{Column: col}
}
return orders
}
func (qf QFrame) comparables(columns []string, orders []Order, groupByNull bool) []column.Comparable {
result := make([]column.Comparable, 0, len(columns))
for i := 0; i < len(columns); i++ {
result = append(result, qf.columnsByName[orders[i].Column].Comparable(false, groupByNull, false))
}
return result
}
// Distinct returns a new QFrame that only contains unique rows with respect to the specified columns.
// If no columns are given Distinct will return rows where allow columns are unique.
//
// The order of the returned rows in undefined.
//
// Time complexity O(m * n) where m = number of columns to compare for distinctness, n = number of rows.
func (qf QFrame) Distinct(configFns ...groupby.ConfigFunc) QFrame {
if qf.Err != nil {
return qf
}
if qf.Len() == 0 {
return qf
}
config := groupby.NewConfig(configFns)
for _, col := range config.Columns {
if _, ok := qf.columnsByName[col]; !ok {
return qf.withErr(qerrors.New("Distinct", unknownCol(col)))
}
}
columns := qf.columnsOrAll(config.Columns)
orders := qf.orders(columns)
comparables := qf.comparables(columns, orders, config.GroupByNull)
newIx := grouper.Distinct(qf.index, comparables)
return qf.withIndex(newIx)
}
func (qf QFrame) checkColumns(operation string, columns []string) error {
for _, col := range columns {
if _, ok := qf.columnsByName[col]; !ok {
return qerrors.New(operation, unknownCol(col))
}
}
return nil
}
// Drop creates a new projection of te QFrame without the specified columns.
//
// Time complexity O(1).
func (qf QFrame) Drop(columns ...string) QFrame {
if qf.Err != nil || len(columns) == 0 {
return qf
}
sSet := qfstrings.NewStringSet(columns)
selectColumns := make([]string, 0)
for _, c := range qf.columns {
if !sSet.Contains(c.name) {
selectColumns = append(selectColumns, c.name)
}
}
return qf.Select(selectColumns...)
}
// Select creates a new projection of the QFrame containing only the specified columns.
//
// Time complexity O(1).
func (qf QFrame) Select(columns ...string) QFrame {
if qf.Err != nil {
return qf
}
if err := qf.checkColumns("Select", columns); err != nil {
return qf.withErr(err)
}
if len(columns) == 0 {
return QFrame{}
}
newColumnsByName := make(map[string]namedColumn, len(columns))
newColumns := make([]namedColumn, len(columns))
for i, col := range columns {
s := qf.columnsByName[col]
s.pos = i
newColumnsByName[col] = s
newColumns[i] = s
}
return QFrame{columns: newColumns, columnsByName: newColumnsByName, index: qf.index}
}
// GroupBy groups rows together for which the values of specified columns are the same.
// Aggregations on the groups can be executed on the returned Grouper object.
// Leaving out columns to group by will make one large group over which aggregations can be done.
//
// The order of the rows in the Grouper is undefined.
//
// Time complexity O(m * n) where m = number of columns to group by, n = number of rows.
func (qf QFrame) GroupBy(configFns ...groupby.ConfigFunc) Grouper {
if qf.Err != nil {
return Grouper{Err: qf.Err}
}
config := groupby.NewConfig(configFns)
if err := qf.checkColumns("Columns", config.Columns); err != nil {
return Grouper{Err: err}
}
g := Grouper{columns: qf.columns, columnsByName: qf.columnsByName, groupedColumns: config.Columns}
if qf.Len() == 0 {
return g
}
if len(config.Columns) == 0 {
g.indices = []index.Int{qf.index}
return g
}
orders := qf.orders(config.Columns)
comparables := qf.comparables(config.Columns, orders, config.GroupByNull)
indices, stats := grouper.GroupBy(qf.index, comparables)
g.indices = indices
g.Stats = GroupStats(stats)
return g
}
func (qf QFrame) Rolling(fn types.SliceFuncOrBuiltInId, dstCol, srcCol string, configFns ...rolling.ConfigFunc) QFrame {
if qf.Err != nil {
return qf
}
conf, err := rolling.NewConfig(configFns)
if err != nil {
return qf.withErr(err)
}
namedColumn, ok := qf.columnsByName[srcCol]
if !ok {
return qf.withErr(qerrors.New("Rolling", unknownCol(srcCol)))
}
srcColumn := namedColumn.Column
resultColumn, err := srcColumn.Rolling(fn, qf.index, conf)
if err != nil {
return qf.withErr(qerrors.Propagate("Rolling", err))
}
return qf.setColumn(dstCol, resultColumn)
}
func fixLengthString(s string, pad string, desiredLen int) string {
// NB: Assumes desiredLen to be >= 3
if len(s) > desiredLen {
return s[:desiredLen-3] + "..."
}
padCount := desiredLen - len(s)
if padCount > 0 {
return strings.Repeat(pad, padCount) + s
}
return s
}
// String returns a simple string representation of the table.
// Column type is indicated in parenthesis following the column name. The initial
// letter in the type name is used for this.
// Output is currently capped to 50 rows. Use Slice followed by String if you want
// to print rows that are not among the first 50.
func (qf QFrame) String() string {
// There are a lot of potential improvements to this function at the moment:
// - Limit output, both columns and rows
// - Configurable output widths, potentially per columns
// - Configurable alignment
if qf.Err != nil {
return qf.Err.Error()
}
result := make([]string, 0, len(qf.index))
row := make([]string, len(qf.columns))
colWidths := make([]int, len(qf.columns))
minColWidth := 5
for i, s := range qf.columns {
colHeader := s.name + "(" + string(s.DataType())[:1] + ")"
colWidths[i] = integer.Max(len(colHeader), minColWidth)
row[i] = fixLengthString(colHeader, " ", colWidths[i])
}
result = append(result, strings.Join(row, " "))
for i := range qf.columns {
row[i] = fixLengthString("", "-", colWidths[i])
}
result = append(result, strings.Join(row, " "))
maxRowCount := 50
for i := 0; i < integer.Min(qf.Len(), maxRowCount); i++ {
for j, s := range qf.columns {
row[j] = fixLengthString(s.StringAt(qf.index[i], "null"), " ", colWidths[j])
}
result = append(result, strings.Join(row, " "))
}
if qf.Len() > maxRowCount {
result = append(result, "... printout truncated ...")
}
result = append(result, fmt.Sprintf("\nDims = %d x %d", len(qf.columns), qf.Len()))
return strings.Join(result, "\n")
}
// Slice returns a new QFrame consisting of rows [start, end[.
// Note that the underlying storage is kept. Slicing a frame will not release memory used to store the columns.
//
// Time complexity O(1).
func (qf QFrame) Slice(start, end int) QFrame {
if qf.Err != nil {
return qf
}
if start < 0 {
return qf.withErr(qerrors.New("Slice", "start must be non negative"))
}
if start > end {
return qf.withErr(qerrors.New("Slice", "start must not be greater than end"))
}
if end > qf.Len() {
return qf.withErr(qerrors.New("Slice", "end must not be greater than qframe length"))
}
return qf.withIndex(qf.index[start:end])
}
func (qf QFrame) setColumn(name string, c column.Column) QFrame {
if err := qfstrings.CheckName(name); err != nil {
return qf.withErr(qerrors.Propagate("setColumn", err))
}
newF := qf.withIndex(qf.index)
existingCol, overwrite := qf.columnsByName[name]
newColCount := len(qf.columns)
pos := newColCount
if overwrite {
pos = existingCol.pos
} else {
newColCount++
}
newF.columns = make([]namedColumn, newColCount)
newF.columnsByName = make(map[string]namedColumn, newColCount)
copy(newF.columns, qf.columns)
for k, v := range qf.columnsByName {
newF.columnsByName[k] = v
}
newS := namedColumn{Column: c, name: name, pos: pos}
newF.columnsByName[name] = newS
newF.columns[pos] = newS
return newF
}
// Copy copies the content of dstCol into srcCol.
//
// dstCol - Name of the column to copy to.
// srcCol - Name of the column to copy from.
//
// Time complexity O(1). Under the hood no actual copy takes place. The columns
// will share the underlying data. Since the frame is immutable this is safe.
func (qf QFrame) Copy(dstCol, srcCol string) QFrame {
if qf.Err != nil {
return qf
}
namedColumn, ok := qf.columnsByName[srcCol]
if !ok {
return qf.withErr(qerrors.New("Copy", unknownCol(srcCol)))
}
if dstCol == srcCol {
// NOP
return qf
}
return qf.setColumn(dstCol, namedColumn.Column)
}
// apply0 is a helper function for zero argument applies.
func (qf QFrame) apply0(fn types.DataFuncOrBuiltInId, dstCol string) QFrame {
if qf.Err != nil {
return qf
}
colLen := 0
if len(qf.columns) > 0 {
colLen = qf.columns[0].Len()
}
var data interface{}
switch t := fn.(type) {
case func() int:
lData := make([]int, colLen)
for _, i := range qf.index {
lData[i] = t()
}
data = lData
case int:
data = ConstInt{Val: t, Count: colLen}
case func() float64:
lData := make([]float64, colLen)
for _, i := range qf.index {
lData[i] = t()
}
data = lData
case float64:
data = ConstFloat{Val: t, Count: colLen}
case func() bool:
lData := make([]bool, colLen)
for _, i := range qf.index {
lData[i] = t()
}
data = lData
case bool:
data = ConstBool{Val: t, Count: colLen}
case func() *string:
lData := make([]*string, colLen)
for _, i := range qf.index {
lData[i] = t()
}
data = lData
case *string:
data = ConstString{Val: t, Count: colLen}
case string:
data = ConstString{Val: &t, Count: colLen}
case types.ColumnName:
return qf.Copy(dstCol, string(t))
default:
return qf.withErr(qerrors.New("apply0", "unknown apply type: %v", reflect.TypeOf(fn)))
}
c, err := createColumn(dstCol, data, newqf.NewConfig(nil))
if err != nil {
return qf.withErr(err)
}
return qf.setColumn(dstCol, c)
}
// apply1 is a helper function for single argument applies.
func (qf QFrame) apply1(fn types.DataFuncOrBuiltInId, dstCol, srcCol string) QFrame {
if qf.Err != nil {
return qf
}
namedColumn, ok := qf.columnsByName[srcCol]
if !ok {
return qf.withErr(qerrors.New("apply1", unknownCol(srcCol)))
}
srcColumn := namedColumn.Column
sliceResult, err := srcColumn.Apply1(fn, qf.index)
if err != nil {
return qf.withErr(qerrors.Propagate("apply1", err))
}
var resultColumn column.Column
switch t := sliceResult.(type) {
case []int:
resultColumn = icolumn.New(t)
case []float64:
resultColumn = fcolumn.New(t)
case []bool:
resultColumn = bcolumn.New(t)
case []*string:
resultColumn = scolumn.New(t)
case column.Column:
resultColumn = t
default:
return qf.withErr(qerrors.New("apply1", "unexpected type of new columns %#v", t))
}
return qf.setColumn(dstCol, resultColumn)
}
// apply2 is a helper function for zero argument applies.
func (qf QFrame) apply2(fn types.DataFuncOrBuiltInId, dstCol, srcCol1, srcCol2 string) QFrame {
if qf.Err != nil {
return qf
}
namedSrcColumn1, ok := qf.columnsByName[srcCol1]
if !ok {
return qf.withErr(qerrors.New("apply2", unknownCol(srcCol1)))
}
srcColumn1 := namedSrcColumn1.Column
namedSrcColumn2, ok := qf.columnsByName[srcCol2]
if !ok {
return qf.withErr(qerrors.New("apply2", unknownCol(srcCol2)))
}
srcColumn2 := namedSrcColumn2.Column
resultColumn, err := srcColumn1.Apply2(fn, srcColumn2, qf.index)
if err != nil {
return qf.withErr(qerrors.Propagate("apply2", err))
}
return qf.setColumn(dstCol, resultColumn)
}
// Instruction describes an operation that will be applied to a row in the QFrame.
type Instruction struct {
// Fn is the function to apply.
//
// IMPORTANT: For pointer and reference types you must not assume that the data passed argument
// to this function is valid after the function returns. If you plan to keep it around you need
// to take a copy of the data.
Fn types.DataFuncOrBuiltInId
// DstCol is the name of the column that the result of applying Fn should be stored in.
DstCol string
// SrcCol1 is the first column to take arguments to Fn from.
// This field is optional and must only be set if Fn takes one or more arguments.
SrcCol1 string
// SrcCol2 is the second column to take arguments to Fn from.
// This field is optional and must only be set if Fn takes two arguments.
SrcCol2 string
}
// Apply applies instructions to each row in the QFrame.
//
// Time complexity O(m * n), where m = number of instructions, n = number of rows.
func (qf QFrame) Apply(instructions ...Instruction) QFrame {
result := qf
for _, a := range instructions {
if a.SrcCol1 == "" {
result = result.apply0(a.Fn, a.DstCol)
} else if a.SrcCol2 == "" {
result = result.apply1(a.Fn, a.DstCol, a.SrcCol1)
} else {
result = result.apply2(a.Fn, a.DstCol, a.SrcCol1, a.SrcCol2)
}
}
return result
}
// WithRowNums returns a new QFrame with a new column added which
// contains the row numbers. Row numbers start at 0.
//
// Time complexity O(n), where n = number of rows.
func (qf QFrame) WithRowNums(colName string) QFrame {
i := -1
return qf.Apply(Instruction{
DstCol: colName,
Fn: func() int {
i++
return i
},
})
}
// FilteredApply works like Apply but allows adding a filter which limits the
// rows to which the instructions are applied to. Any rows not matching the filter
// will be assigned the zero value of the column type.
//
// Time complexity O(m * n), where m = number of instructions, n = number of rows.
func (qf QFrame) FilteredApply(clause FilterClause, instructions ...Instruction) QFrame {
filteredQf := qf.Filter(clause)
if filteredQf.Err != nil {
return filteredQf
}
// Use the filtered index when applying instructions then restore it to the original index.
newQf := qf
newQf.index = filteredQf.index
newQf = newQf.Apply(instructions...)
newQf.index = qf.index
return newQf
}
// Eval evaluates an expression assigning the result to dstCol.
//
// Eval can be considered an abstraction over Apply. For example it handles management
// of intermediate/temporary columns that are needed as part of evaluating more complex
// expressions.
//
// Time complexity O(m*n) where m = number of clauses in the expression, n = number of rows.
func (qf QFrame) Eval(dstCol string, expr Expression, ff ...eval.ConfigFunc) QFrame {
if qf.Err != nil {
return qf
}
conf := eval.NewConfig(ff)
result, col := expr.execute(qf, conf.Ctx)
colName := string(col)
// colName is often just a temporary name of a column created as a result of
// executing the expression. We want to rename this column to the requested
// destination columns name. Remove colName from the result if not present in
// the original frame to avoid polluting the frame with intermediate results.
result = result.Copy(dstCol, colName)
if !qf.Contains(colName) {
result = result.Drop(colName)
}
return result
}
func (qf QFrame) functionType(name string) (types.FunctionType, error) {
namedColumn, ok := qf.columnsByName[name]
if !ok {
return types.FunctionTypeUndefined, qerrors.New("functionType", unknownCol(name))
}
return namedColumn.FunctionType(), nil
}
// Append appends all supplied QFrames, in order, to the current one and returns
// a new QFrame with the result.
// Column count, names and types must be the same for all involved QFrames.
//
// NB! This functionality is very much work in progress and should not be used yet.
//
// A lot of the implementation is still missing and what is currently there will be rewritten.
//
// Time complexity: ???
func (qf QFrame) Append(qff ...QFrame) QFrame {
// TODO: Check error status on all involved QFrames
// TODO: Check that all columns have the same length? This should always be true.