github.com/m3db/m3@v1.5.1-0.20231129193456-75a402aa583b/src/query/functions/temporal/holt_winters.go (about)

     1  // Copyright (c) 2018 Uber Technologies, Inc.
     2  //
     3  // Permission is hereby granted, free of charge, to any person obtaining a copy
     4  // of this software and associated documentation files (the "Software"), to deal
     5  // in the Software without restriction, including without limitation the rights
     6  // to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
     7  // copies of the Software, and to permit persons to whom the Software is
     8  // furnished to do so, subject to the following conditions:
     9  //
    10  // The above copyright notice and this permission notice shall be included in
    11  // all copies or substantial portions of the Software.
    12  //
    13  // THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
    14  // IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
    15  // FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
    16  // AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
    17  // LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
    18  // OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
    19  // THE SOFTWARE.
    20  
    21  package temporal
    22  
    23  import (
    24  	"fmt"
    25  	"math"
    26  	"time"
    27  
    28  	"github.com/m3db/m3/src/query/executor/transform"
    29  )
    30  
    31  const (
    32  	// HoltWintersType produces a smoothed value for time series based on the specified interval.
    33  	// The algorithm used comes from https://en.wikipedia.org/wiki/Exponential_smoothing#Double_exponential_smoothing.
    34  	// Holt-Winters should only be used with gauges.
    35  	HoltWintersType = "holt_winters"
    36  )
    37  
    38  // NewHoltWintersOp creates a new base Holt-Winters transform with a specified node.
    39  func NewHoltWintersOp(args []interface{}) (transform.Params, error) {
    40  	// todo(braskin): move this logic to the parser.
    41  	if len(args) != 3 {
    42  		return emptyOp, fmt.Errorf("invalid number of args for %s: %d", HoltWintersType, len(args))
    43  	}
    44  
    45  	duration, ok := args[0].(time.Duration)
    46  	if !ok {
    47  		return emptyOp, fmt.Errorf("unable to cast to scalar argument: %v for %s", args[0], HoltWintersType)
    48  	}
    49  
    50  	sf, ok := args[1].(float64)
    51  	if !ok {
    52  		return emptyOp, fmt.Errorf("unable to cast to scalar argument: %v for %s", args[1], HoltWintersType)
    53  	}
    54  
    55  	tf, ok := args[2].(float64)
    56  	if !ok {
    57  		return emptyOp, fmt.Errorf("unable to cast to scalar argument: %v for %s", args[2], HoltWintersType)
    58  	}
    59  
    60  	// Sanity check the input.
    61  	if sf <= 0 || sf >= 1 {
    62  		return emptyOp, fmt.Errorf("invalid smoothing factor. Expected: 0 < sf < 1, got: %f", sf)
    63  	}
    64  
    65  	if tf <= 0 || tf >= 1 {
    66  		return emptyOp, fmt.Errorf("invalid trend factor. Expected: 0 < tf < 1, got: %f", tf)
    67  	}
    68  
    69  	aggregationFunc := makeHoltWintersFn(sf, tf)
    70  	a := aggProcessor{
    71  		aggFunc: aggregationFunc,
    72  	}
    73  
    74  	return newBaseOp(duration, HoltWintersType, a)
    75  }
    76  
    77  func makeHoltWintersFn(sf, tf float64) aggFunc {
    78  	return func(vals []float64) float64 {
    79  		var (
    80  			foundFirst, foundSecond         bool
    81  			secondVal                       float64
    82  			trendVal                        float64
    83  			scaledSmoothVal, scaledTrendVal float64
    84  			prev, curr                      float64
    85  			idx                             int
    86  		)
    87  
    88  		for _, val := range vals {
    89  			if math.IsNaN(val) {
    90  				continue
    91  			}
    92  
    93  			if !foundFirst {
    94  				foundFirst = true
    95  				curr = val
    96  				idx++
    97  				continue
    98  			}
    99  
   100  			if !foundSecond {
   101  				foundSecond = true
   102  				secondVal = val
   103  				trendVal = secondVal - curr
   104  			}
   105  
   106  			// scale the raw value against the smoothing factor.
   107  			scaledSmoothVal = sf * val
   108  
   109  			// scale the last smoothed value with the trend at this point.
   110  			trendVal = calcTrendValue(idx-1, sf, tf, prev, curr, trendVal)
   111  			scaledTrendVal = (1 - sf) * (curr + trendVal)
   112  
   113  			prev, curr = curr, scaledSmoothVal+scaledTrendVal
   114  			idx++
   115  		}
   116  
   117  		// need at least two values to apply a smoothing operation.
   118  		if !foundSecond {
   119  			return math.NaN()
   120  		}
   121  
   122  		return curr
   123  	}
   124  }
   125  
   126  // Calculate the trend value at the given index i in raw data d.
   127  // This is somewhat analogous to the slope of the trend at the given index.
   128  // The argument "s" is the set of computed smoothed values.
   129  // The argument "b" is the set of computed trend factors.
   130  // The argument "d" is the set of raw input values.
   131  func calcTrendValue(i int, sf, tf, s0, s1, b float64) float64 {
   132  	if i == 0 {
   133  		return b
   134  	}
   135  
   136  	x := tf * (s1 - s0)
   137  	y := (1 - tf) * b
   138  
   139  	return x + y
   140  }