github.com/weaviate/weaviate@v1.24.6/adapters/repos/db/vector/hnsw/distancer/cosine_dist.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 distancer
    13  
    14  import (
    15  	"github.com/pkg/errors"
    16  )
    17  
    18  type CosineDistance struct {
    19  	a []float32
    20  }
    21  
    22  func (d *CosineDistance) Distance(b []float32) (float32, bool, error) {
    23  	if len(d.a) != len(b) {
    24  		return 0, false, errors.Errorf("vector lengths don't match: %d vs %d",
    25  			len(d.a), len(b))
    26  	}
    27  
    28  	dist := 1 - dotProductImplementation(d.a, b)
    29  	return dist, true, nil
    30  }
    31  
    32  type CosineDistanceProvider struct{}
    33  
    34  func NewCosineDistanceProvider() CosineDistanceProvider {
    35  	return CosineDistanceProvider{}
    36  }
    37  
    38  func (d CosineDistanceProvider) SingleDist(a, b []float32) (float32, bool, error) {
    39  	if len(a) != len(b) {
    40  		return 0, false, errors.Errorf("vector lengths don't match: %d vs %d",
    41  			len(a), len(b))
    42  	}
    43  
    44  	prod := 1 - dotProductImplementation(a, b)
    45  
    46  	return prod, true, nil
    47  }
    48  
    49  func (d CosineDistanceProvider) Type() string {
    50  	return "cosine-dot"
    51  }
    52  
    53  func (d CosineDistanceProvider) New(a []float32) Distancer {
    54  	return &CosineDistance{a: a}
    55  }
    56  
    57  func (d CosineDistanceProvider) Step(x, y []float32) float32 {
    58  	var sum float32
    59  	for i := range x {
    60  		sum += x[i] * y[i]
    61  	}
    62  
    63  	return sum
    64  }
    65  
    66  func (d CosineDistanceProvider) Wrap(x float32) float32 {
    67  	return 1 - x
    68  }