SHOGUN  v3.0.0
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Groups Pages
EuclideanDistance.cpp
Go to the documentation of this file.
1 /*
2  * This program is free software; you can redistribute it and/or modify
3  * it under the terms of the GNU General Public License as published by
4  * the Free Software Foundation; either version 3 of the License, or
5  * (at your option) any later version.
6  *
7  * Written (W) 2007-2009 Soeren Sonnenburg
8  * Copyright (C) 2007-2009 Fraunhofer Institute FIRST and Max-Planck-Society
9  */
10 
11 #include <shogun/lib/common.h>
12 #include <shogun/io/SGIO.h>
14 
15 using namespace shogun;
16 
18 {
19  init();
20 }
21 
23 : CRealDistance()
24 {
25  init();
26  init(l, r);
27 }
28 
30 {
31  cleanup();
32 }
33 
34 bool CEuclideanDistance::init(CFeatures* l, CFeatures* r)
35 {
36  CRealDistance::init(l, r);
37 
38  return true;
39 }
40 
42 {
43 }
44 
45 float64_t CEuclideanDistance::compute(int32_t idx_a, int32_t idx_b)
46 {
47  int32_t alen, blen;
48  bool afree, bfree;
49  float64_t result=0;
50 
52  get_feature_vector(idx_a, alen, afree);
54  get_feature_vector(idx_b, blen, bfree);
55  ASSERT(alen==blen)
56 
57  for (int32_t i=0; i<alen; i++)
58  result+=CMath::sq(avec[i] - bvec[i]);
59 
60  ((CDenseFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
61  ((CDenseFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
62 
63  if (disable_sqrt)
64  return result;
65 
66  return CMath::sqrt(result);
67 }
68 
69 void CEuclideanDistance::init()
70 {
71  disable_sqrt=false;
72 
73  m_parameters->add(&disable_sqrt, "disable_sqrt", "If sqrt shall not be applied.");
74 }
75 
76 float64_t CEuclideanDistance::distance_upper_bounded(int32_t idx_a, int32_t idx_b, float64_t upper_bound)
77 {
78  int32_t alen, blen;
79  bool afree, bfree;
80  float64_t result=0;
81 
82  upper_bound *= upper_bound;
83 
85  get_feature_vector(idx_a, alen, afree);
87  get_feature_vector(idx_b, blen, bfree);
88  ASSERT(alen==blen)
89 
90  for (int32_t i=0; i<alen; i++)
91  {
92  result+=CMath::sq(avec[i] - bvec[i]);
93 
94  if (result > upper_bound)
95  {
97  free_feature_vector(avec, idx_a, afree);
99  free_feature_vector(bvec, idx_b, bfree);
100 
101  if (disable_sqrt)
102  return result;
103  else
104  return CMath::sqrt(result);
105  }
106  }
107 
108  ((CDenseFeatures<float64_t>*) lhs)->free_feature_vector(avec, idx_a, afree);
109  ((CDenseFeatures<float64_t>*) rhs)->free_feature_vector(bvec, idx_b, bfree);
110 
111  if (disable_sqrt)
112  return result;
113  else
114  return CMath::sqrt(result);
115 }

SHOGUN Machine Learning Toolbox - Documentation