github.com/weaviate/weaviate@v1.24.6/entities/autocut/autocut.go (about)

     1  //                           _       _
     2  // __      _____  __ ___   ___  __ _| |_ ___
     3  // \ \ /\ / / _ \/ _` \ \ / / |/ _` | __/ _ \
     4  //  \ V  V /  __/ (_| |\ V /| | (_| | ||  __/
     5  //   \_/\_/ \___|\__,_| \_/ |_|\__,_|\__\___|
     6  //
     7  //  Copyright © 2016 - 2024 Weaviate B.V. All rights reserved.
     8  //
     9  //  CONTACT: hello@weaviate.io
    10  //
    11  
    12  package autocut
    13  
    14  func Autocut(yValues []float32, cutOff int) int {
    15  	if len(yValues) <= 1 {
    16  		return len(yValues)
    17  	}
    18  
    19  	diff := make([]float32, len(yValues))
    20  	step := 1. / (float32(len(yValues)) - 1.)
    21  
    22  	for i := range yValues {
    23  		xValue := 0. + float32(i)*step
    24  		yValueNorm := (yValues[i] - yValues[0]) / (yValues[len(yValues)-1] - yValues[0])
    25  		diff[i] = yValueNorm - xValue
    26  	}
    27  
    28  	extremaCount := 0
    29  	for i := range diff {
    30  		if i == 0 {
    31  			continue // we want the index _before_ the extrema
    32  		}
    33  
    34  		if i == len(diff)-1 && len(diff) > 1 { // for last element there is no "next" point
    35  			if diff[i] > diff[i-1] && diff[i] > diff[i-2] {
    36  				extremaCount += 1
    37  				if extremaCount >= cutOff {
    38  					return i
    39  				}
    40  			}
    41  		} else {
    42  			if diff[i] > diff[i-1] && diff[i] > diff[i+1] {
    43  				extremaCount += 1
    44  				if extremaCount >= cutOff {
    45  					return i
    46  				}
    47  			}
    48  		}
    49  	}
    50  	return len(yValues)
    51  }