Automatic commit
[svrt.git] / misc.cc
1 /*
2  *  svrt is the ``Synthetic Visual Reasoning Test'', an image
3  *  generator for evaluating classification performance of machine
4  *  learning systems, humans and primates.
5  *
6  *  Copyright (c) 2009 Idiap Research Institute, http://www.idiap.ch/
7  *  Written by Francois Fleuret <francois.fleuret@idiap.ch>
8  *
9  *  This file is part of svrt.
10  *
11  *  svrt is free software: you can redistribute it and/or modify it
12  *  under the terms of the GNU General Public License version 3 as
13  *  published by the Free Software Foundation.
14  *
15  *  svrt is distributed in the hope that it will be useful, but
16  *  WITHOUT ANY WARRANTY; without even the implied warranty of
17  *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
18  *  General Public License for more details.
19  *
20  *  You should have received a copy of the GNU General Public License
21  *  along with selector.  If not, see <http://www.gnu.org/licenses/>.
22  *
23  */
24
25 #include <fstream>
26
27 using namespace std;
28
29 #include "misc.h"
30
31 char *next_word(char *buffer, char *r, int buffer_size) {
32   char *s;
33   s = buffer;
34
35   if(r != 0) {
36     while((*r == ' ') || (*r == '\t') || (*r == ',')) r++;
37     if(*r == '"') {
38       r++;
39       while((*r != '"') && (*r != '\0') &&
40             (s<buffer+buffer_size-1))
41         *s++ = *r++;
42       if(*r == '"') r++;
43     } else {
44       while((*r != '\r') && (*r != '\n') && (*r != '\0') &&
45             (*r != '\t') && (*r != ' ') && (*r != ',')) {
46         if(s == buffer + buffer_size) {
47           cerr << "Buffer overflow in next_word." << endl;
48           exit(1);
49         }
50         *s++ = *r++;
51       }
52     }
53
54     while((*r == ' ') || (*r == '\t') || (*r == ',')) r++;
55     if((*r == '\0') || (*r=='\r') || (*r=='\n')) r = 0;
56   }
57   *s = '\0';
58
59   return r;
60 }
61
62 scalar_t discrete_entropy(int *n, int nb) {
63   scalar_t s = 0, t = 0;
64   for(int k = 0; k < nb; k++) if(n[k] > 0) {
65     s += n[k] * log(scalar_t(n[k]));
66     t += n[k];
67   }
68   return (log(t) - s/scalar_t(t))/log(2.0);
69 }
70
71 void random_permutation(int *val, int nb) {
72   for(int k = 0; k < nb; k++) val[k] = k;
73   int i, t;
74   for(int k = 0; k < nb - 1; k++) {
75     i = int(drand48() * (nb - k)) + k;
76     t = val[i];
77     val[i] = val[k];
78     val[k] = t;
79   }
80 }
81
82 void tag_subset(bool *val, int nb_total, int nb_to_tag) {
83   ASSERT(nb_to_tag <= nb_total);
84   int index[nb_total];
85   random_permutation(index, nb_total);
86   for(int n = 0; n < nb_total; n++) val[n] = false;
87   for(int n = 0; n < nb_to_tag; n++) val[index[n]] = true;
88 }
89
90 int compare_couple(const void *a, const void *b) {
91   if(((Couple *) a)->value < ((Couple *) b)->value) return -1;
92   else if(((Couple *) a)->value > ((Couple *) b)->value) return 1;
93   else return 0;
94 }