Added README.md
[clueless-kmeans.git] / misc.h
1 /*
2  *  clueless-kmeans is a variant of k-means which enforces balanced
3  *  distribution of classes in every cluster
4  *
5  *  Copyright (c) 2013 Idiap Research Institute, http://www.idiap.ch/
6  *  Written by Francois Fleuret <francois.fleuret@idiap.ch>
7  *
8  *  This file is part of clueless-kmeans.
9  *
10  *  clueless-kmeans is free software: you can redistribute it and/or
11  *  modify it under the terms of the GNU General Public License
12  *  version 3 as published by the Free Software Foundation.
13  *
14  *  clueless-kmeans is distributed in the hope that it will be useful,
15  *  but WITHOUT ANY WARRANTY; without even the implied warranty of
16  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
17  *  General Public License for more details.
18  *
19  *  You should have received a copy of the GNU General Public License
20  *  along with selector.  If not, see <http://www.gnu.org/licenses/>.
21  *
22  */
23
24 #ifndef MISC_H
25 #define MISC_H
26
27 #include <iostream>
28 #include <cmath>
29 #include <fstream>
30 #include <cfloat>
31 #include <stdlib.h>
32 #include <string.h>
33
34 using namespace std;
35
36 typedef double scalar_t;
37 // typedef float scalar_t;
38
39 const int buffer_size = 1024;
40
41 using namespace std;
42
43 #ifdef DEBUG
44 #define ASSERT(x) if(!(x)) { \
45   std::cerr << "ASSERT FAILED IN " << __FILE__ << ":" << __LINE__ << endl; \
46   abort(); \
47 }
48 #else
49 #define ASSERT(x)
50 #endif
51
52 template<class T>
53 T smooth_min(T x, T y) {
54   T z = exp(x - y);
55   return 0.5 * (x + y - (x - y)/(1 + 1/z) - (y - x)/(1 + z));
56 }
57
58 template <class T>
59 void write_var(ostream *os, const T *x) { os->write((char *) x, sizeof(T)); }
60
61 template <class T>
62 void read_var(istream *is, T *x) { is->read((char *) x, sizeof(T)); }
63
64 template <class T>
65 void grow(int *nb_max, int nb, T** current, int factor) {
66   ASSERT(*nb_max > 0);
67   if(nb == *nb_max) {
68     T *tmp = new T[*nb_max * factor];
69     memcpy(tmp, *current, *nb_max * sizeof(T));
70     delete[] *current;
71     *current = tmp;
72     *nb_max *= factor;
73   }
74 }
75
76 template <class T>
77 inline T sq(T x) {
78   return x * x;
79 }
80
81 inline scalar_t log2(scalar_t x) {
82   return log(x)/log(2.0);
83 }
84
85 inline scalar_t xi(scalar_t x) {
86   if(x <= 0.0) return 0.0;
87   else         return - x * log(x)/log(2.0);
88 }
89
90 scalar_t discrete_entropy(int *n, int nb);
91
92 char *basename(char *name);
93
94 char *next_word(char *buffer, char *r, int buffer_size);
95
96 void random_permutation(int *val, int nb);
97 void tag_subset(bool *val, int nb_total, int nb_to_tag);
98
99 struct Couple {
100   int index;
101   scalar_t value;
102 };
103
104 int compare_couple(const void *a, const void *b);
105
106 #endif