forked from go-gota/gota
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathseries.go
842 lines (753 loc) · 20.1 KB
/
series.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
package series
import (
"fmt"
"reflect"
"sort"
"strings"
"math"
"gonum.org/v1/gonum/stat"
)
// Series is a data structure designed for operating on arrays of elements that
// should comply with a certain type structure. They are flexible enough that can
// be transformed to other Series types and account for missing or non valid
// elements. Most of the power of Series resides on the ability to compare and
// subset Series of different types.
type Series struct {
Name string // The name of the series
elements Elements // The values of the elements
t Type // The type of the series
// deprecated: use Error() instead
Err error
}
// Elements is the interface that represents the array of elements contained on
// a Series.
type Elements interface {
Elem(int) Element
Len() int
}
// Element is the interface that defines the types of methods to be present for
// elements of a Series
type Element interface {
// Setter method
Set(interface{})
// Comparation methods
Eq(Element) bool
Neq(Element) bool
Less(Element) bool
LessEq(Element) bool
Greater(Element) bool
GreaterEq(Element) bool
// Accessor/conversion methods
Copy() Element // FIXME: Returning interface is a recipe for pain
Val() ElementValue // FIXME: Returning interface is a recipe for pain
String() string
Int() (int, error)
Float() float64
Bool() (bool, error)
// Information methods
IsNA() bool
Type() Type
}
// intElements is the concrete implementation of Elements for Int elements.
type intElements []intElement
func (e intElements) Len() int { return len(e) }
func (e intElements) Elem(i int) Element { return &e[i] }
// stringElements is the concrete implementation of Elements for String elements.
type stringElements []stringElement
func (e stringElements) Len() int { return len(e) }
func (e stringElements) Elem(i int) Element { return &e[i] }
// floatElements is the concrete implementation of Elements for Float elements.
type floatElements []floatElement
func (e floatElements) Len() int { return len(e) }
func (e floatElements) Elem(i int) Element { return &e[i] }
// boolElements is the concrete implementation of Elements for Bool elements.
type boolElements []boolElement
func (e boolElements) Len() int { return len(e) }
func (e boolElements) Elem(i int) Element { return &e[i] }
// ElementValue represents the value that can be used for marshaling or
// unmarshaling Elements.
type ElementValue interface{}
type MapFunction func(Element) Element
// Comparator is a convenience alias that can be used for a more type safe way of
// reason and use comparators.
type Comparator string
// Supported Comparators
const (
Eq Comparator = "==" // Equal
Neq Comparator = "!=" // Non equal
Greater Comparator = ">" // Greater than
GreaterEq Comparator = ">=" // Greater or equal than
Less Comparator = "<" // Lesser than
LessEq Comparator = "<=" // Lesser or equal than
In Comparator = "in" // Inside
CompFunc Comparator = "func" // user-defined comparison function
)
// compFunc defines a user-defined comparator function. Used internally for type assertions
type compFunc = func(el Element) bool
// Type is a convenience alias that can be used for a more type safe way of
// reason and use Series types.
type Type string
// Supported Series Types
const (
String Type = "string"
Int Type = "int"
Float Type = "float"
Bool Type = "bool"
)
// Indexes represent the elements that can be used for selecting a subset of
// elements within a Series. Currently supported are:
//
// int // Matches the given index number
// []int // Matches all given index numbers
// []bool // Matches all elements in a Series marked as true
// Series [Int] // Same as []int
// Series [Bool] // Same as []bool
type Indexes interface{}
// New is the generic Series constructor
func New(values interface{}, t Type, name string) Series {
ret := Series{
Name: name,
t: t,
}
// Pre-allocate elements
preAlloc := func(n int) {
switch t {
case String:
ret.elements = make(stringElements, n)
case Int:
ret.elements = make(intElements, n)
case Float:
ret.elements = make(floatElements, n)
case Bool:
ret.elements = make(boolElements, n)
default:
panic(fmt.Sprintf("unknown type %v", t))
}
}
if values == nil {
preAlloc(1)
ret.elements.Elem(0).Set(nil)
return ret
}
switch v := values.(type) {
case []string:
l := len(v)
preAlloc(l)
for i := 0; i < l; i++ {
ret.elements.Elem(i).Set(v[i])
}
case []float64:
l := len(v)
preAlloc(l)
for i := 0; i < l; i++ {
ret.elements.Elem(i).Set(v[i])
}
case []int:
l := len(v)
preAlloc(l)
for i := 0; i < l; i++ {
ret.elements.Elem(i).Set(v[i])
}
case []bool:
l := len(v)
preAlloc(l)
for i := 0; i < l; i++ {
ret.elements.Elem(i).Set(v[i])
}
case Series:
l := v.Len()
preAlloc(l)
for i := 0; i < l; i++ {
ret.elements.Elem(i).Set(v.elements.Elem(i))
}
default:
switch reflect.TypeOf(values).Kind() {
case reflect.Slice:
v := reflect.ValueOf(values)
l := v.Len()
preAlloc(v.Len())
for i := 0; i < l; i++ {
val := v.Index(i).Interface()
ret.elements.Elem(i).Set(val)
}
default:
preAlloc(1)
v := reflect.ValueOf(values)
val := v.Interface()
ret.elements.Elem(0).Set(val)
}
}
return ret
}
// Strings is a constructor for a String Series
func Strings(values interface{}) Series {
return New(values, String, "")
}
// Ints is a constructor for an Int Series
func Ints(values interface{}) Series {
return New(values, Int, "")
}
// Floats is a constructor for a Float Series
func Floats(values interface{}) Series {
return New(values, Float, "")
}
// Bools is a constructor for a Bool Series
func Bools(values interface{}) Series {
return New(values, Bool, "")
}
// Empty returns an empty Series of the same type
func (s Series) Empty() Series {
return New([]int{}, s.t, s.Name)
}
// Returns Error or nil if no error occured
func (s *Series) Error() error {
return s.Err
}
// Append adds new elements to the end of the Series. When using Append, the
// Series is modified in place.
func (s *Series) Append(values interface{}) {
if err := s.Err; err != nil {
return
}
news := New(values, s.t, s.Name)
switch s.t {
case String:
s.elements = append(s.elements.(stringElements), news.elements.(stringElements)...)
case Int:
s.elements = append(s.elements.(intElements), news.elements.(intElements)...)
case Float:
s.elements = append(s.elements.(floatElements), news.elements.(floatElements)...)
case Bool:
s.elements = append(s.elements.(boolElements), news.elements.(boolElements)...)
}
}
// Concat concatenates two series together. It will return a new Series with the
// combined elements of both Series.
func (s Series) Concat(x Series) Series {
if err := s.Err; err != nil {
return s
}
if err := x.Err; err != nil {
s.Err = fmt.Errorf("concat error: argument has errors: %v", err)
return s
}
y := s.Copy()
y.Append(x)
return y
}
// Subset returns a subset of the series based on the given Indexes.
func (s Series) Subset(indexes Indexes) Series {
if err := s.Err; err != nil {
return s
}
idx, err := parseIndexes(s.Len(), indexes)
if err != nil {
s.Err = err
return s
}
ret := Series{
Name: s.Name,
t: s.t,
}
switch s.t {
case String:
elements := make(stringElements, len(idx))
for k, i := range idx {
elements[k] = s.elements.(stringElements)[i]
}
ret.elements = elements
case Int:
elements := make(intElements, len(idx))
for k, i := range idx {
elements[k] = s.elements.(intElements)[i]
}
ret.elements = elements
case Float:
elements := make(floatElements, len(idx))
for k, i := range idx {
elements[k] = s.elements.(floatElements)[i]
}
ret.elements = elements
case Bool:
elements := make(boolElements, len(idx))
for k, i := range idx {
elements[k] = s.elements.(boolElements)[i]
}
ret.elements = elements
default:
panic("unknown series type")
}
return ret
}
// Set sets the values on the indexes of a Series and returns the reference
// for itself. The original Series is modified.
func (s Series) Set(indexes Indexes, newvalues Series) Series {
if err := s.Err; err != nil {
return s
}
if err := newvalues.Err; err != nil {
s.Err = fmt.Errorf("set error: argument has errors: %v", err)
return s
}
idx, err := parseIndexes(s.Len(), indexes)
if err != nil {
s.Err = err
return s
}
if len(idx) != newvalues.Len() {
s.Err = fmt.Errorf("set error: dimensions mismatch")
return s
}
for k, i := range idx {
if i < 0 || i >= s.Len() {
s.Err = fmt.Errorf("set error: index out of range")
return s
}
s.elements.Elem(i).Set(newvalues.elements.Elem(k))
}
return s
}
// HasNaN checks whether the Series contain NaN elements.
func (s Series) HasNaN() bool {
for i := 0; i < s.Len(); i++ {
if s.elements.Elem(i).IsNA() {
return true
}
}
return false
}
// IsNaN returns an array that identifies which of the elements are NaN.
func (s Series) IsNaN() []bool {
ret := make([]bool, s.Len())
for i := 0; i < s.Len(); i++ {
ret[i] = s.elements.Elem(i).IsNA()
}
return ret
}
// Compare compares the values of a Series with other elements. To do so, the
// elements with are to be compared are first transformed to a Series of the same
// type as the caller.
func (s Series) Compare(comparator Comparator, comparando interface{}) Series {
if err := s.Err; err != nil {
return s
}
compareElements := func(a, b Element, c Comparator) (bool, error) {
var ret bool
switch c {
case Eq:
ret = a.Eq(b)
case Neq:
ret = a.Neq(b)
case Greater:
ret = a.Greater(b)
case GreaterEq:
ret = a.GreaterEq(b)
case Less:
ret = a.Less(b)
case LessEq:
ret = a.LessEq(b)
default:
return false, fmt.Errorf("unknown comparator: %v", c)
}
return ret, nil
}
bools := make([]bool, s.Len())
// CompFunc comparator comparison
if comparator == CompFunc {
f, ok := comparando.(compFunc)
if !ok {
panic("comparando is not a comparison function of type func(el Element) bool")
}
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
bools[i] = f(e)
}
return Bools(bools)
}
comp := New(comparando, s.t, "")
// In comparator comparison
if comparator == In {
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
b := false
for j := 0; j < comp.Len(); j++ {
m := comp.elements.Elem(j)
c, err := compareElements(e, m, Eq)
if err != nil {
s = s.Empty()
s.Err = err
return s
}
if c {
b = true
break
}
}
bools[i] = b
}
return Bools(bools)
}
// Single element comparison
if comp.Len() == 1 {
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
c, err := compareElements(e, comp.elements.Elem(0), comparator)
if err != nil {
s = s.Empty()
s.Err = err
return s
}
bools[i] = c
}
return Bools(bools)
}
// Multiple element comparison
if s.Len() != comp.Len() {
s := s.Empty()
s.Err = fmt.Errorf("can't compare: length mismatch")
return s
}
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
c, err := compareElements(e, comp.elements.Elem(i), comparator)
if err != nil {
s = s.Empty()
s.Err = err
return s
}
bools[i] = c
}
return Bools(bools)
}
// Copy will return a copy of the Series.
func (s Series) Copy() Series {
name := s.Name
t := s.t
err := s.Err
var elements Elements
switch s.t {
case String:
elements = make(stringElements, s.Len())
copy(elements.(stringElements), s.elements.(stringElements))
case Float:
elements = make(floatElements, s.Len())
copy(elements.(floatElements), s.elements.(floatElements))
case Bool:
elements = make(boolElements, s.Len())
copy(elements.(boolElements), s.elements.(boolElements))
case Int:
elements = make(intElements, s.Len())
copy(elements.(intElements), s.elements.(intElements))
}
ret := Series{
Name: name,
t: t,
elements: elements,
Err: err,
}
return ret
}
// Records returns the elements of a Series as a []string
func (s Series) Records() []string {
ret := make([]string, s.Len())
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
ret[i] = e.String()
}
return ret
}
// Float returns the elements of a Series as a []float64. If the elements can not
// be converted to float64 or contains a NaN returns the float representation of
// NaN.
func (s Series) Float() []float64 {
ret := make([]float64, s.Len())
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
ret[i] = e.Float()
}
return ret
}
// Int returns the elements of a Series as a []int or an error if the
// transformation is not possible.
func (s Series) Int() ([]int, error) {
ret := make([]int, s.Len())
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
val, err := e.Int()
if err != nil {
return nil, err
}
ret[i] = val
}
return ret, nil
}
// Bool returns the elements of a Series as a []bool or an error if the
// transformation is not possible.
func (s Series) Bool() ([]bool, error) {
ret := make([]bool, s.Len())
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
val, err := e.Bool()
if err != nil {
return nil, err
}
ret[i] = val
}
return ret, nil
}
// Type returns the type of a given series
func (s Series) Type() Type {
return s.t
}
// Len returns the length of a given Series
func (s Series) Len() int {
return s.elements.Len()
}
// String implements the Stringer interface for Series
func (s Series) String() string {
return fmt.Sprint(s.elements)
}
// Str prints some extra information about a given series
func (s Series) Str() string {
var ret []string
// If name exists print name
if s.Name != "" {
ret = append(ret, "Name: "+s.Name)
}
ret = append(ret, "Type: "+fmt.Sprint(s.t))
ret = append(ret, "Length: "+fmt.Sprint(s.Len()))
if s.Len() != 0 {
ret = append(ret, "Values: "+fmt.Sprint(s))
}
return strings.Join(ret, "\n")
}
// Val returns the value of a series for the given index. Will panic if the index
// is out of bounds.
func (s Series) Val(i int) interface{} {
return s.elements.Elem(i).Val()
}
// Elem returns the element of a series for the given index. Will panic if the
// index is out of bounds.
func (s Series) Elem(i int) Element {
return s.elements.Elem(i)
}
// parseIndexes will parse the given indexes for a given series of length `l`. No
// out of bounds checks is performed.
func parseIndexes(l int, indexes Indexes) ([]int, error) {
var idx []int
switch idxs := indexes.(type) {
case []int:
idx = idxs
case int:
idx = []int{idxs}
case []bool:
bools := idxs
if len(bools) != l {
return nil, fmt.Errorf("indexing error: index dimensions mismatch")
}
for i, b := range bools {
if b {
idx = append(idx, i)
}
}
case Series:
s := idxs
if err := s.Err; err != nil {
return nil, fmt.Errorf("indexing error: new values has errors: %v", err)
}
if s.HasNaN() {
return nil, fmt.Errorf("indexing error: indexes contain NaN")
}
switch s.t {
case Int:
return s.Int()
case Bool:
bools, err := s.Bool()
if err != nil {
return nil, fmt.Errorf("indexing error: %v", err)
}
return parseIndexes(l, bools)
default:
return nil, fmt.Errorf("indexing error: unknown indexing mode")
}
default:
return nil, fmt.Errorf("indexing error: unknown indexing mode")
}
return idx, nil
}
// Order returns the indexes for sorting a Series. NaN elements are pushed to the
// end by order of appearance.
func (s Series) Order(reverse bool) []int {
var ie indexedElements
var nasIdx []int
for i := 0; i < s.Len(); i++ {
e := s.elements.Elem(i)
if e.IsNA() {
nasIdx = append(nasIdx, i)
} else {
ie = append(ie, indexedElement{i, e})
}
}
var srt sort.Interface
srt = ie
if reverse {
srt = sort.Reverse(srt)
}
sort.Stable(srt)
var ret []int
for _, e := range ie {
ret = append(ret, e.index)
}
return append(ret, nasIdx...)
}
type indexedElement struct {
index int
element Element
}
type indexedElements []indexedElement
func (e indexedElements) Len() int { return len(e) }
func (e indexedElements) Less(i, j int) bool { return e[i].element.Less(e[j].element) }
func (e indexedElements) Swap(i, j int) { e[i], e[j] = e[j], e[i] }
// StdDev calculates the standard deviation of a series
func (s Series) StdDev() float64 {
stdDev := stat.StdDev(s.Float(), nil)
return stdDev
}
// Mean calculates the average value of a series
func (s Series) Mean() float64 {
stdDev := stat.Mean(s.Float(), nil)
return stdDev
}
// Median calculates the middle or median value, as opposed to
// mean, and there is less susceptible to being affected by outliers.
func (s Series) Median() float64 {
if s.elements.Len() == 0 ||
s.Type() == String ||
s.Type() == Bool {
return math.NaN()
}
ix := s.Order(false)
newElem := make([]Element, len(ix))
for newpos, oldpos := range ix {
newElem[newpos] = s.elements.Elem(oldpos)
}
// When length is odd, we just take length(list)/2
// value as the median.
if len(newElem)%2 != 0 {
return newElem[len(newElem)/2].Float()
}
// When length is even, we take middle two elements of
// list and the median is an average of the two of them.
return (newElem[(len(newElem)/2)-1].Float() +
newElem[len(newElem)/2].Float()) * 0.5
}
// Max return the biggest element in the series
func (s Series) Max() float64 {
if s.elements.Len() == 0 || s.Type() == String {
return math.NaN()
}
max := s.elements.Elem(0)
for i := 1; i < s.elements.Len(); i++ {
elem := s.elements.Elem(i)
if elem.Greater(max) {
max = elem
}
}
return max.Float()
}
// MaxStr return the biggest element in a series of type String
func (s Series) MaxStr() string {
if s.elements.Len() == 0 || s.Type() != String {
return ""
}
max := s.elements.Elem(0)
for i := 1; i < s.elements.Len(); i++ {
elem := s.elements.Elem(i)
if elem.Greater(max) {
max = elem
}
}
return max.String()
}
// Min return the lowest element in the series
func (s Series) Min() float64 {
if s.elements.Len() == 0 || s.Type() == String {
return math.NaN()
}
min := s.elements.Elem(0)
for i := 1; i < s.elements.Len(); i++ {
elem := s.elements.Elem(i)
if elem.Less(min) {
min = elem
}
}
return min.Float()
}
// MinStr return the lowest element in a series of type String
func (s Series) MinStr() string {
if s.elements.Len() == 0 || s.Type() != String {
return ""
}
min := s.elements.Elem(0)
for i := 1; i < s.elements.Len(); i++ {
elem := s.elements.Elem(i)
if elem.Less(min) {
min = elem
}
}
return min.String()
}
// Quantile returns the sample of x such that x is greater than or
// equal to the fraction p of samples.
// Note: gonum/stat panics when called with strings
func (s Series) Quantile(p float64) float64 {
if s.Type() == String || s.Len() == 0 {
return math.NaN()
}
ordered := s.Subset(s.Order(false)).Float()
return stat.Quantile(p, stat.Empirical, ordered, nil)
}
// Map applies a function matching MapFunction signature, which itself
// allowing for a fairly flexible MAP implementation, intended for mapping
// the function over each element in Series and returning a new Series object.
// Function must be compatible with the underlying type of data in the Series.
// In other words it is expected that when working with a Float Series, that
// the function passed in via argument `f` will not expect another type, but
// instead expects to handle Element(s) of type Float.
func (s Series) Map(f MapFunction) Series {
mappedValues := make([]Element, s.Len())
for i := 0; i < s.Len(); i++ {
value := f(s.elements.Elem(i))
mappedValues[i] = value
}
return New(mappedValues, s.Type(), s.Name)
}
// Sum calculates the sum value of a series
func (s Series) Sum() float64 {
if s.elements.Len() == 0 || s.Type() == String || s.Type() == Bool {
return math.NaN()
}
sFloat := s.Float()
sum := sFloat[0]
for i := 1; i < len(sFloat); i++ {
elem := sFloat[i]
sum += elem
}
return sum
}
// Slice slices Series from j to k-1 index.
func (s Series) Slice(j, k int) Series {
if s.Err != nil {
return s
}
if j > k || j < 0 || k >= s.Len() {
empty := s.Empty()
empty.Err = fmt.Errorf("slice index out of bounds")
return empty
}
idxs := make([]int, k-j)
for i := 0; j+i < k; i++ {
idxs[i] = j + i
}
return s.Subset(idxs)
}