github.com/m3db/m3@v1.5.0/src/query/functions/linear/round.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 linear 22 23 import ( 24 "fmt" 25 "math" 26 27 "github.com/m3db/m3/src/query/block" 28 "github.com/m3db/m3/src/query/functions/lazy" 29 "github.com/m3db/m3/src/query/parser" 30 ) 31 32 // RoundType rounds each datapoint in the series. 33 // Ties are resolved by rounding up. The optional to_nearest argument allows 34 // specifying the nearest multiple to which the timeseries values should be 35 // rounded (default=1). This variable may be a fraction. 36 // Special cases are: round(_, 0) = NaN 37 const RoundType = "round" 38 39 type roundOp struct { 40 toNearest float64 41 } 42 43 func parseArgs(args []interface{}) (float64, error) { 44 // NB: if no args passed; this should use default value of `1`. 45 if len(args) == 0 { 46 return 1, nil 47 } 48 49 if len(args) > 1 { 50 return 0, fmt.Errorf("invalid number of args for round: %d", len(args)) 51 } 52 53 // Attempt to parse a single arg. 54 if nearest, ok := args[0].(float64); ok { 55 return nearest, nil 56 } 57 58 return 0, fmt.Errorf("unable to cast to to_nearest argument: %v", args[0]) 59 } 60 61 func roundFn(roundTo float64) block.ValueTransform { 62 if roundTo == 0 { 63 return func(float64) float64 { return math.NaN() } 64 } 65 66 roundToInverse := 1.0 / roundTo 67 return func(v float64) float64 { 68 return math.Floor(v*roundToInverse+0.5) / roundToInverse 69 } 70 } 71 72 // NewRoundOp creates a new round op based on the type and arguments. 73 func NewRoundOp(args []interface{}) (parser.Params, error) { 74 toNearest, err := parseArgs(args) 75 if err != nil { 76 return nil, err 77 } 78 79 lazyOpts := block.NewLazyOptions().SetValueTransform(roundFn(toNearest)) 80 return lazy.NewLazyOp(RoundType, lazyOpts) 81 }