SlideIO 2.0.0
Open-source library for reading of medical images
Loading...
Searching...
No Matches
similaritytools.hpp
1// This file is part of slideio project.
2// It is subject to the license terms in the LICENSE file found in the top-level directory
3// of this distribution and at http://slideio.com/license.html.
4#pragma once
5#pragma
6
7#include <vector>
8
9namespace slideio
10{
11 class SimilarityTools
12 {
13 public:
14 template <typename Type>
15 static double dotProduct(const std::vector<Type>& a, const std::vector<Type>& b) {
16 // Assuming arrays are of equal length
17 double result = 0.0;
18 for (std::size_t i = 0; i < a.size(); ++i) {
19 result += a[i] * b[i];
20 }
21 return result;
22 }
23
24 template <typename Type>
25 static double magnitude(const std::vector<Type>& v) {
26 double result = 0.0;
27 for (double value : v) {
28 result += value * value;
29 }
30 return sqrt(result);
31 }
32
33 template <typename Type>
34 static double cosineSimilarity(const std::vector<Type>& a, const std::vector<Type>& b) {
35 double dotProd = dotProduct(a, b);
36 double magA = magnitude(a);
37 double magB = magnitude(b);
38 if(magA == 0 && magB == 0) {
39 return 1.0;
40 }
41 else if (magA == 0 || magB == 0) {
42 // Handle division by zero
43 return 0.0;
44 }
45 return dotProd / (magA * magB);
46 }
47 };
48}
Definition: exceptions.hpp:15