SHOGUN
v3.2.0
|
00001 /* 00002 * This program is free software; you can redistribute it and/or modify 00003 * it under the terms of the GNU General Public License as published by 00004 * the Free Software Foundation; either version 3 of the License, or 00005 * (at your option) any later version. 00006 * 00007 * Written (W) 2007-2009 Soeren Sonnenburg 00008 * Copyright (C) 2007-2009 Fraunhofer Institute FIRST and Max-Planck-Society 00009 */ 00010 00011 #include <shogun/lib/common.h> 00012 #include <shogun/io/SGIO.h> 00013 #include <shogun/distance/SparseEuclideanDistance.h> 00014 #include <shogun/features/Features.h> 00015 #include <shogun/features/SparseFeatures.h> 00016 00017 using namespace shogun; 00018 00019 CSparseEuclideanDistance::CSparseEuclideanDistance() 00020 : CSparseDistance<float64_t>() 00021 { 00022 init(); 00023 } 00024 00025 CSparseEuclideanDistance::CSparseEuclideanDistance( 00026 CSparseFeatures<float64_t>* l, CSparseFeatures<float64_t>* r) 00027 : CSparseDistance<float64_t>() 00028 { 00029 init(); 00030 init(l, r); 00031 } 00032 00033 CSparseEuclideanDistance::~CSparseEuclideanDistance() 00034 { 00035 cleanup(); 00036 } 00037 00038 bool CSparseEuclideanDistance::init(CFeatures* l, CFeatures* r) 00039 { 00040 CSparseDistance<float64_t>::init(l, r); 00041 00042 cleanup(); 00043 00044 sq_lhs=SG_MALLOC(float64_t, lhs->get_num_vectors()); 00045 sq_lhs=((CSparseFeatures<float64_t>*) lhs)->compute_squared(sq_lhs); 00046 00047 if (lhs==rhs) 00048 sq_rhs=sq_lhs; 00049 else 00050 { 00051 sq_rhs=SG_MALLOC(float64_t, rhs->get_num_vectors()); 00052 sq_rhs=((CSparseFeatures<float64_t>*) rhs)->compute_squared(sq_rhs); 00053 } 00054 00055 return true; 00056 } 00057 00058 void CSparseEuclideanDistance::cleanup() 00059 { 00060 if (sq_lhs != sq_rhs) 00061 SG_FREE(sq_rhs); 00062 sq_rhs = NULL; 00063 00064 SG_FREE(sq_lhs); 00065 sq_lhs = NULL; 00066 } 00067 00068 float64_t CSparseEuclideanDistance::compute(int32_t idx_a, int32_t idx_b) 00069 { 00070 float64_t result=((CSparseFeatures<float64_t>*) lhs)->compute_squared_norm( 00071 (CSparseFeatures<float64_t>*) lhs, sq_lhs, idx_a, 00072 (CSparseFeatures<float64_t>*) rhs, sq_rhs, idx_b); 00073 00074 return CMath::sqrt(result); 00075 } 00076 00077 void CSparseEuclideanDistance::init() 00078 { 00079 sq_lhs=NULL; 00080 sq_rhs=NULL; 00081 }