-
Notifications
You must be signed in to change notification settings - Fork 4
/
Copy pathdatalist.go
1890 lines (1644 loc) · 46.2 KB
/
datalist.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 insyra
import (
"fmt"
"math"
"runtime"
"sort"
"strings"
"sync"
"sync/atomic"
"time"
"github.com/HazelnutParadise/Go-Utils/asyncutil"
"github.com/HazelnutParadise/Go-Utils/conv"
"github.com/HazelnutParadise/Go-Utils/sliceutil"
"golang.org/x/text/cases"
"golang.org/x/text/language"
)
// DataList is a generic dynamic data list.
type DataList struct {
data []interface{}
name string
creationTimestamp int64
lastModifiedTimestamp atomic.Int64
mu sync.Mutex
}
// IDataList defines the behavior expected from a DataList.
type IDataList interface {
isFragmented() bool
GetCreationTimestamp() int64
GetLastModifiedTimestamp() int64
updateTimestamp()
GetName() string
SetName(string) *DataList
Data() []interface{}
Append(values ...interface{})
Get(index int) interface{}
Clone() *DataList
Count(value interface{}) int
Counter() map[interface{}]int
Update(index int, value interface{})
InsertAt(index int, value interface{})
FindFirst(interface{}) interface{}
FindLast(interface{}) interface{}
FindAll(interface{}) []int
Filter(func(interface{}) bool) *DataList
ReplaceFirst(interface{}, interface{})
ReplaceLast(interface{}, interface{})
ReplaceAll(interface{}, interface{})
ReplaceOutliers(float64, float64) *DataList
Pop() interface{}
Drop(index int) *DataList
DropAll(...interface{}) *DataList
DropIfContains(interface{}) *DataList
Clear() *DataList
ClearStrings() *DataList
ClearNumbers() *DataList
ClearNaNs() *DataList
ClearOutliers(float64) *DataList
Normalize() *DataList
Standardize() *DataList
FillNaNWithMean() *DataList
MovingAverage(int) *DataList
WeightedMovingAverage(int, interface{}) *DataList
ExponentialSmoothing(float64) *DataList
DoubleExponentialSmoothing(float64, float64) *DataList
MovingStdev(int) *DataList
Len() int
Sort(acending ...bool) *DataList
Rank() *DataList
Reverse() *DataList
Upper() *DataList
Lower() *DataList
Capitalize() *DataList
// Statistics
Sum() float64
Max() float64
Min() float64
Mean() float64
WeightedMean(weights interface{}) float64
GMean() float64
Median() float64
Mode() float64
MAD() float64
Stdev() float64
StdevP() float64
Var() float64
VarP() float64
Range() float64
Quartile(int) float64
IQR() float64
Percentile(float64) float64
Difference() *DataList
// comparison
IsEqualTo(*DataList) bool
IsTheSameAs(*DataList) bool
// conversion
ParseNumbers() *DataList
ParseStrings() *DataList
ToF64Slice() []float64
ToStringSlice() []string
// Interpolation
LinearInterpolation(float64) float64
QuadraticInterpolation(float64) float64
LagrangeInterpolation(float64) float64
NearestNeighborInterpolation(float64) float64
NewtonInterpolation(float64) float64
HermiteInterpolation(float64, []float64) float64
}
// Data returns the data stored in the DataList.
func (dl *DataList) Data() []interface{} {
defer func() {
go reorganizeMemory(dl)
}()
return dl.data
}
// NewDataList creates a new DataList, supporting both slice and variadic inputs,
// and flattens the input before storing it.
func NewDataList(values ...interface{}) *DataList {
var flatData []interface{}
flatData, _ = sliceutil.Flatten[interface{}](values)
LogDebug("NewDataList(): Flattened data:", flatData)
continuousMemData := make([]interface{}, len(flatData))
copy(continuousMemData, flatData)
timestamp := time.Now().Unix()
dl := &DataList{
data: continuousMemData,
creationTimestamp: timestamp,
}
dl.lastModifiedTimestamp.Store(timestamp)
return dl
}
// Append adds a new values to the DataList.
// The value can be of any type.
// The value is appended to the end of the DataList.
func (dl *DataList) Append(values ...interface{}) {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
// Append data and update timestamp
dl.data = append(dl.data, values...)
go dl.updateTimestamp()
}
// Get retrieves the value at the specified index in the DataList.
// Supports negative indexing.
// Returns nil if the index is out of bounds.
// Returns the value at the specified index.
func (dl *DataList) Get(index int) interface{} {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
// 支持負索引
if index < 0 {
index += len(dl.data)
}
if index < 0 || index >= len(dl.data) {
LogWarning("DataList.Get(): Index out of bounds, returning nil.")
return nil
}
return dl.data[index]
}
// Clone creates a deep copy of the DataList.
func (dl *DataList) Clone() *DataList {
defer func() {
dl.mu.Unlock()
}()
dl.mu.Lock()
newDL := NewDataList(dl.data)
newDL.SetName(dl.name)
return newDL
}
// Count returns the number of occurrences of the specified value in the DataList.
func (dl *DataList) Count(value interface{}) int {
found := dl.FindAll(value)
if found == nil {
return 0
}
return len(found)
}
// Counter returns a map of the number of occurrences of each value in the DataList.
func (dl *DataList) Counter() map[interface{}]int {
counter := make(map[interface{}]int)
for _, value := range dl.Data() {
counter[value]++
}
return counter
}
// Update replaces the value at the specified index with the new value.
func (dl *DataList) Update(index int, newValue interface{}) {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
if index < 0 {
index += len(dl.data)
}
if index < 0 || index >= len(dl.data) {
LogWarning("ReplaceAtIndex(): Index %d out of bounds", index)
}
dl.data[index] = newValue
go dl.updateTimestamp()
}
// InsertAt inserts a value at the specified index in the DataList.
// If the index is out of bounds, the value is appended to the end of the list.
func (dl *DataList) InsertAt(index int, value interface{}) {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
// Handle negative index
if index < 0 {
index += len(dl.data) + 1
}
// If index is out of bounds, append the value to the end
if index < 0 || index > len(dl.data) {
LogWarning("InsertAt(): Index out of bounds, appending value to the end.")
dl.data = append(dl.data, value)
} else {
var err error
dl.data, err = sliceutil.InsertAt(dl.data, index, value)
if err != nil {
LogWarning("InsertAt(): Failed to insert value at index:", err)
return
}
}
go dl.updateTimestamp()
}
// FindFirst returns the index of the first occurrence of the specified value in the DataList.
// If the value is not found, it returns nil.
func (dl *DataList) FindFirst(value interface{}) interface{} {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
for i, v := range dl.data {
if v == value {
return i
}
}
LogWarning("FindFirst(): Value not found, returning nil.")
return nil
}
// FindLast returns the index of the last occurrence of the specified value in the DataList.
// If the value is not found, it returns nil.
func (dl *DataList) FindLast(value interface{}) interface{} {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
for i := len(dl.data) - 1; i >= 0; i-- {
if dl.data[i] == value {
return i
}
}
LogWarning("FindLast(): Value not found, returning nil.")
return nil
}
// FindAll returns a slice of all the indices where the specified value is found in the DataList using parallel processing.
// If the value is not found, it returns an empty slice.
func (dl *DataList) FindAll(value interface{}) []int {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
length := len(dl.data)
if length == 0 {
LogWarning("FindAll(): DataList is empty, returning an empty slice.")
return []int{}
}
var indices []int
for i, v := range dl.data {
if v == value {
indices = append(indices, i)
}
}
return indices
}
// Filter filters the DataList based on a custom filter function provided by the user.
// The filter function should return true for elements that should be included in the result.
func (dl *DataList) Filter(filterFunc func(interface{}) bool) *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
filteredData := []interface{}{}
for _, v := range dl.data {
if filterFunc(v) {
filteredData = append(filteredData, v)
}
}
return NewDataList(filteredData...)
}
// ReplaceFirst replaces the first occurrence of oldValue with newValue.
func (dl *DataList) ReplaceFirst(oldValue, newValue interface{}) {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
for i, v := range dl.data {
if v == oldValue {
dl.data[i] = newValue
go dl.updateTimestamp()
return
}
}
LogWarning("ReplaceFirst(): value not found.")
}
// ReplaceLast replaces the last occurrence of oldValue with newValue.
func (dl *DataList) ReplaceLast(oldValue, newValue interface{}) {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
for i := len(dl.data) - 1; i >= 0; i-- {
if dl.data[i] == oldValue {
dl.data[i] = newValue
go dl.updateTimestamp()
return
}
}
LogWarning("ReplaceLast(): value not found.")
}
// ReplaceAll replaces all occurrences of oldValue with newValue in the DataList.
// If oldValue is not found, no changes are made.
func (dl *DataList) ReplaceAll(oldValue, newValue interface{}) {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
length := len(dl.data)
if length == 0 {
LogWarning("ReplaceAll(): DataList is empty, no replacements made.")
return
}
// 單線程處理資料替換
for i, v := range dl.data {
if v == oldValue {
dl.data[i] = newValue
}
}
go dl.updateTimestamp()
}
// ReplaceOutliers replaces outliers in the DataList with the specified replacement value (e.g., mean, median).
func (dl *DataList) ReplaceOutliers(stdDevs float64, replacement float64) *DataList {
mean := dl.Mean()
stddev := dl.Stdev()
threshold := stdDevs * stddev
for i, v := range dl.Data() {
val := conv.ParseF64(v)
if math.Abs(val-mean) > threshold {
dl.data[i] = replacement
}
}
return dl
}
// Pop removes and returns the last element from the DataList.
// Returns the last element.
// Returns nil if the DataList is empty.
func (dl *DataList) Pop() interface{} {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
n, err := sliceutil.Drt_PopFrom(&dl.data)
if err != nil {
LogWarning("DataList.Pop(): DataList is empty, returning nil.")
return nil
}
go dl.updateTimestamp()
return n
}
// Drop removes the element at the specified index from the DataList and updates the timestamp.
// Returns an error if the index is out of bounds.
func (dl *DataList) Drop(index int) *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
if index < 0 {
index += len(dl.data)
}
if index >= len(dl.data) {
LogWarning("DataList.Drop(): Index out of bounds, returning.")
return dl
}
dl.data = append(dl.data[:index], dl.data[index+1:]...)
go dl.updateTimestamp()
return dl
}
// DropAll removes all occurrences of the specified values from the DataList.
// Supports multiple values to drop.
func (dl *DataList) DropAll(toDrop ...interface{}) *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
length := len(dl.data)
if length == 0 {
return dl
}
// 決定要開多少個線程
numGoroutines := runtime.NumCPU()
if numGoroutines == 0 {
numGoroutines = 1
}
chunkSize := length / numGoroutines
if length%numGoroutines != 0 {
chunkSize++
}
// 儲存所有的 Awaitable
var awaitables []*asyncutil.Awaitable
// 啟動 Awaitables 處理每個部分
for i := 0; i < numGoroutines; i++ {
start := i * chunkSize
end := start + chunkSize
if end > length {
end = length
}
awaitable := asyncutil.Async(func(dataChunk []interface{}) []interface{} {
var result []interface{}
for _, v := range dataChunk {
shouldDrop := false
for _, drop := range toDrop {
if v == drop {
shouldDrop = true
break
}
}
if !shouldDrop {
result = append(result, v)
}
}
return result
}, dl.data[start:end])
awaitables = append(awaitables, awaitable)
}
// 收集所有結果並合併
var finalResult []interface{}
for _, awaitable := range awaitables {
results, err := awaitable.Await()
if err != nil {
LogWarning("DropAll(): Error in async task:", err)
continue
}
if len(results) > 0 {
finalResult = append(finalResult, results[0].([]interface{})...)
}
}
// 更新 DataList
dl.data = finalResult
go dl.updateTimestamp()
return dl
}
// DropIfContains removes all elements from the DataList that contain the specified value.
func (dl *DataList) DropIfContains(value interface{}) *DataList {
dl.mu.Lock()
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
// 創建一個臨時切片存放保留的元素
var newData []interface{}
for _, v := range dl.data {
if str, ok := v.(string); ok {
// 如果當前元素不包含指定的值,將其添加到 newData 中
if !strings.Contains(str, value.(string)) {
newData = append(newData, v)
}
} else {
// 如果元素不是字符串類型,也將其保留
newData = append(newData, v)
}
}
// 將新的數據賦值回 dl.data
dl.data = newData
go dl.updateTimestamp()
return dl
}
// Clear removes all elements from the DataList and updates the timestamp.
func (dl *DataList) Clear() *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
dl.data = []interface{}{}
go dl.updateTimestamp()
return dl
}
func (dl *DataList) Len() int {
return len(dl.data)
}
// ClearStrings removes all string elements from the DataList and updates the timestamp.
func (dl *DataList) ClearStrings() *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
length := len(dl.data)
if length == 0 {
return dl
}
// 獲取可用的 CPU 核心數量
numGoroutines := min(runtime.NumCPU(), length)
// 決定每個線程處理的數據量
chunkSize := length / numGoroutines
if length%numGoroutines != 0 {
chunkSize++
}
// 構建任務切片
var tasks []asyncutil.Task
for i := 0; i < numGoroutines; i++ {
start := i * chunkSize
end := start + chunkSize
if end > length {
end = length
}
task := asyncutil.Task{
ID: fmt.Sprintf("Task-%d", i),
Fn: func(dataChunk []interface{}) []interface{} {
var result []interface{}
for _, v := range dataChunk {
if _, ok := v.(string); !ok {
result = append(result, v)
}
}
return result
},
Args: []interface{}{dl.data[start:end]},
}
tasks = append(tasks, task)
}
// 使用 ParallelProcess 進行平行處理
taskResults := asyncutil.ParallelProcess(tasks)
// 合併所有的結果
var finalResult []interface{}
for _, taskResult := range taskResults {
finalResult = append(finalResult, taskResult.Results[0].([]interface{})...)
}
// 更新 DataList
dl.data = finalResult
go dl.updateTimestamp()
return dl
}
// ++++ 此處之後尚未提升性能 ++++
// ClearNumbers removes all numeric elements (int, float, etc.) from the DataList and updates the timestamp.
func (dl *DataList) ClearNumbers() *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
filteredData := dl.data[:0] // Create a new slice with the same length as the original
for _, v := range dl.data {
// If the element is not a number, keep it
switch v.(type) {
case int, int8, int16, int32, int64:
case uint, uint8, uint16, uint32, uint64:
case float32, float64:
default:
filteredData = append(filteredData, v)
}
}
dl.data = filteredData
go dl.updateTimestamp()
return dl
}
// ClearNaNs removes all NaN values from the DataList and updates the timestamp.
func (dl *DataList) ClearNaNs() *DataList {
defer func() {
go reorganizeMemory(dl)
go dl.updateTimestamp()
}()
for i, v := range dl.Data() {
if math.IsNaN(v.(float64)) {
dl.Drop(i)
}
}
return dl
}
// ClearOutliers removes values from the DataList that are outside the specified number of standard deviations.
// This method modifies the original DataList and returns it.
func (dl *DataList) ClearOutliers(stdDevs float64) *DataList {
defer func() {
r := recover()
if r != nil {
LogWarning("DataList.ClearOutliers(): Data types cannot be compared.")
}
go dl.updateTimestamp()
}()
mean := dl.Mean()
stddev := dl.Stdev()
threshold := stdDevs * stddev
// 打印調試信息,確保計算值與 R 相同
LogDebug("Mean: %f\n", mean)
LogDebug("Standard Deviation: %f\n", stddev)
LogDebug("Threshold: %f\n", threshold)
for i := dl.Len() - 1; i >= 0; i-- {
val := conv.ParseF64(dl.Data()[i])
LogDebug("Checking value: %f\n", val) // 打印每個檢查的值
if math.Abs(val-mean) > threshold {
LogDebug("Removing outlier: %f\n", val) // 打印要移除的異常值
dl.Drop(i)
}
}
return dl
}
// Normalize normalizes the data in the DataList, skipping NaN values.
// Directly modifies the DataList.
func (dl *DataList) Normalize() *DataList {
defer func() {
r := recover()
if r != nil {
LogWarning("Normalize: Data types cannot be compared, returning nil.")
}
go reorganizeMemory(dl)
go dl.updateTimestamp()
}()
min, max := dl.Min(), dl.Max()
if math.IsNaN(min) || math.IsNaN(max) {
LogWarning("Normalize: Cannot normalize due to invalid Min/Max values.")
return nil
}
for i, v := range dl.Data() {
vfloat := conv.ParseF64(v)
dl.data[i] = (vfloat - min) / (max - min)
}
return dl
}
// Standardize standardizes the data in the DataList.
// Directly modifies the DataList.
func (dl *DataList) Standardize() *DataList {
defer func() {
r := recover()
if r != nil {
LogWarning("Standardize(): Data types cannot be compared, returning nil.")
}
dl.mu.Unlock()
go reorganizeMemory(dl)
go dl.updateTimestamp()
}()
mean := dl.Mean()
stddev := dl.Stdev()
dl.mu.Lock()
for i, v := range dl.Data() {
vfloat := conv.ParseF64(v)
dl.data[i] = (vfloat - mean) / stddev
}
return dl
}
// FillNaNWithMean replaces all NaN values in the DataList with the mean value.
// Directly modifies the DataList.
func (dl *DataList) FillNaNWithMean() *DataList {
defer func() {
r := recover()
if r != nil {
LogWarning("FillNaNWithMean(): Data types cannot be compared, returning nil.")
}
dl.mu.Unlock()
go reorganizeMemory(dl)
go dl.updateTimestamp()
}()
dlclone := dl.Clone()
dlNoNaN := dlclone.ClearNaNs()
mean := dlNoNaN.Mean()
dl.mu.Lock()
for i, v := range dl.Data() {
vfloat := conv.ParseF64(v)
if math.IsNaN(vfloat) {
dl.data[i] = mean
} else {
dl.data[i] = vfloat
}
}
return dl
}
// MovingAverage calculates the moving average of the DataList using a specified window size.
// Returns a new DataList containing the moving average values.
func (dl *DataList) MovingAverage(windowSize int) *DataList {
if windowSize <= 0 || windowSize > dl.Len() {
return nil
}
movingAverageData := make([]float64, dl.Len()-windowSize+1)
for i := 0; i < len(movingAverageData); i++ {
windowSum := 0.0
for j := 0; j < windowSize; j++ {
windowSum += dl.Data()[i+j].(float64)
}
movingAverageData[i] = windowSum / float64(windowSize)
}
return NewDataList(movingAverageData)
}
// WeightedMovingAverage applies a weighted moving average to the DataList with a given window size.
// The weights parameter should be a slice or a DataList of the same length as the window size.
// Returns a new DataList containing the weighted moving average values.
func (dl *DataList) WeightedMovingAverage(windowSize int, weights interface{}) *DataList {
weightsSlice, sliceLen := ProcessData(weights)
if windowSize <= 0 || windowSize > dl.Len() || sliceLen != windowSize {
LogWarning("DataList.WeightedMovingAverage(): Invalid window size or weights length.")
return nil
}
// 計算權重總和,避免直接除以 windowSize
weightsSum := 0.0
for _, w := range weightsSlice {
weightsSum += w.(float64)
}
movingAvgData := make([]float64, dl.Len()-windowSize+1)
for i := 0; i < len(movingAvgData); i++ {
window := dl.Data()[i : i+windowSize]
sum := 0.0
for j := 0; j < windowSize; j++ {
sum += window[j].(float64) * weightsSlice[j].(float64)
}
movingAvgData[i] = sum / weightsSum // 使用權重總和
}
return NewDataList(movingAvgData)
}
// ExponentialSmoothing applies exponential smoothing to the DataList.
// The alpha parameter controls the smoothing factor.
// Returns a new DataList containing the smoothed values.
func (dl *DataList) ExponentialSmoothing(alpha float64) *DataList {
if alpha < 0 || alpha > 1 {
LogWarning("ExponentialSmoothing: Invalid alpha value.")
return nil
}
smoothedData := make([]float64, dl.Len())
smoothedData[0] = dl.Data()[0].(float64) // 使用初始值作為第一個平滑值
for i := 1; i < dl.Len(); i++ {
smoothedData[i] = alpha*dl.Data()[i].(float64) + (1-alpha)*smoothedData[i-1]
}
return NewDataList(smoothedData)
}
// DoubleExponentialSmoothing applies double exponential smoothing to the DataList.
// The alpha parameter controls the level smoothing, and the beta parameter controls the trend smoothing.
// Returns a new DataList containing the smoothed values.
func (dl *DataList) DoubleExponentialSmoothing(alpha, beta float64) *DataList {
if alpha < 0 || alpha > 1 || beta < 0 || beta > 1 {
LogWarning("DoubleExponentialSmoothing: Invalid alpha or beta value.")
return nil
}
smoothedData := make([]float64, dl.Len())
trend := 0.0
level := dl.Data()[0].(float64)
smoothedData[0] = level
for i := 1; i < dl.Len(); i++ {
prevLevel := level
level = alpha*dl.Data()[i].(float64) + (1-alpha)*(level+trend)
trend = beta*(level-prevLevel) + (1-beta)*trend
smoothedData[i] = level + trend
}
return NewDataList(smoothedData)
}
// MovingStdDev calculates the moving standard deviation for the DataList using a specified window size.
func (dl *DataList) MovingStdev(windowSize int) *DataList {
if windowSize <= 0 || windowSize > dl.Len() {
LogWarning("MovingStdDev: Invalid window size.")
return nil
}
movingStdDevData := make([]float64, dl.Len()-windowSize+1)
for i := 0; i < len(movingStdDevData); i++ {
window := NewDataList(dl.Data()[i : i+windowSize])
movingStdDevData[i] = window.Stdev()
}
return NewDataList(movingStdDevData)
}
// Sort sorts the DataList using a mixed sorting logic.
// It handles string, numeric (including all integer and float types), and time data types.
// If sorting fails, it restores the original order.
func (dl *DataList) Sort(ascending ...bool) *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
if len(dl.data) == 0 {
LogWarning("DataList.Sort(): DataList is empty, returning.")
return dl
}
// Save the original order
originalData := make([]interface{}, len(dl.data))
copy(originalData, dl.data)
defer func() {
if r := recover(); r != nil {
LogWarning("DataList.Sort(): Sorting failed, restoring original order:", r)
dl.data = originalData
}
}()
ascendingOrder := true
if len(ascending) > 0 {
ascendingOrder = ascending[0]
}
if len(ascending) > 1 {
LogWarning("DataList.Sort(): Too many arguments, returning.")
return dl
}
// Mixed sorting
sort.SliceStable(dl.data, func(i, j int) bool {
v1 := dl.data[i]
v2 := dl.data[j]
switch v1 := v1.(type) {
case string:
if v2, ok := v2.(string); ok {
return (v1 < v2) == ascendingOrder
}
case int, int8, int16, int32, int64:
v1Float := ToFloat64(v1)
if v2Float, ok := ToFloat64Safe(v2); ok {
return (v1Float < v2Float) == ascendingOrder
}
case uint, uint8, uint16, uint32, uint64:
v1Float := ToFloat64(v1)
if v2Float, ok := ToFloat64Safe(v2); ok {
return (v1Float < v2Float) == ascendingOrder
}
case float32, float64:
v1Float := ToFloat64(v1)
if v2Float, ok := ToFloat64Safe(v2); ok {
return (v1Float < v2Float) == ascendingOrder
}
case time.Time:
if v2, ok := v2.(time.Time); ok {
return v1.Before(v2) == ascendingOrder
}
}
// Fallback: compare as strings
return fmt.Sprint(v1) < fmt.Sprint(v2)
})
go dl.updateTimestamp()
return dl
}
// Rank assigns ranks to the elements in the DataList.
func (dl *DataList) Rank() *DataList {
data := dl.ToF64Slice()
ranked := make([]float64, len(data))
// 建立一個索引來追蹤原始位置
indexes := make([]int, len(data))
for i := range data {
indexes[i] = i
}
// 根據數據排序,並追蹤索引
sort.Slice(indexes, func(i, j int) bool {
return data[indexes[i]] < data[indexes[j]]
})
// 分配秩次,處理重複值的情況
for i := 0; i < len(indexes); {
sumRank := 0.0
count := 0
val := data[indexes[i]]
for j := i; j < len(indexes) && data[indexes[j]] == val; j++ {
sumRank += float64(j + 1)
count++
}
avgRank := sumRank / float64(count) // 計算平均秩次
for j := 0; j < count; j++ {
ranked[indexes[i+j]] = avgRank
}
i += count
}
return NewDataList(ranked)
}
// Reverse reverses the order of the elements in the DataList.
func (dl *DataList) Reverse() *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
go dl.updateTimestamp()
}()
dl.mu.Lock()
sliceutil.Reverse(dl.data)
return dl
}
// Upper converts all string elements in the DataList to uppercase.
func (dl *DataList) Upper() *DataList {
defer func() {
dl.mu.Unlock()
go reorganizeMemory(dl)
}()
dl.mu.Lock()
for i, v := range dl.data {
if str, ok := v.(string); ok {