Happy new year
[pazpar2-moved-to-github.git] / src / relevance.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2012 Index Data
3
4 Pazpar2 is free software; you can redistribute it and/or modify it under
5 the terms of the GNU General Public License as published by the Free
6 Software Foundation; either version 2, or (at your option) any later
7 version.
8
9 Pazpar2 is distributed in the hope that it will be useful, but WITHOUT ANY
10 WARRANTY; without even the implied warranty of MERCHANTABILITY or
11 FITNESS FOR A PARTICULAR PURPOSE.  See the GNU General Public License
12 for more details.
13
14 You should have received a copy of the GNU General Public License
15 along with this program; if not, write to the Free Software
16 Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA  02110-1301  USA
17
18 */
19
20 #if HAVE_CONFIG_H
21 #include <config.h>
22 #endif
23
24 #include <assert.h>
25 #include <math.h>
26 #include <stdlib.h>
27
28 #include "relevance.h"
29 #include "session.h"
30
31 struct relevance
32 {
33     int *doc_frequency_vec;
34     int vec_len;
35     struct word_entry *entries;
36     pp2_charset_token_t prt;
37     NMEM nmem;
38 };
39
40
41 struct word_entry {
42     const char *norm_str;
43     int termno;
44     struct word_entry *next;
45 };
46
47 static void add_word_entry(NMEM nmem, 
48                            struct word_entry **entries,
49                            const char *norm_str,
50                            int term_no)
51 {
52     struct word_entry *ne = nmem_malloc(nmem, sizeof(*ne));
53     ne->norm_str = nmem_strdup(nmem, norm_str);
54     ne->termno = term_no;
55     
56     ne->next = *entries;
57     *entries = ne;
58 }
59
60
61 int word_entry_match(struct word_entry *entries, const char *norm_str)
62 {
63     for (; entries; entries = entries->next)
64     {
65         if (!strcmp(norm_str, entries->norm_str))
66             return entries->termno;
67     }
68     return 0;
69 }
70
71 static struct word_entry *build_word_entries(pp2_charset_token_t prt,
72                                              NMEM nmem,
73                                              const char **terms)
74 {
75     int termno = 1; /* >0 signals THERE is an entry */
76     struct word_entry *entries = 0;
77     const char **p = terms;
78
79     for (; *p; p++)
80     {
81         const char *norm_str;
82
83         pp2_charset_token_first(prt, *p, 0);
84         while ((norm_str = pp2_charset_token_next(prt)))
85             add_word_entry(nmem, &entries, norm_str, termno);
86         termno++;
87     }
88     return entries;
89 }
90
91 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
92                           const char *words, int multiplier, const char *name)
93 {
94     int *mult = cluster->term_frequency_vec_tmp;
95     const char *norm_str;
96     int i, length = 0;
97
98     pp2_charset_token_first(r->prt, words, 0);
99     for (i = 1; i < r->vec_len; i++)
100         mult[i] = 0;
101
102     while ((norm_str = pp2_charset_token_next(r->prt)))
103     {
104         int res = word_entry_match(r->entries, norm_str);
105         if (res)
106         {
107             assert(res < r->vec_len);
108             mult[res] += multiplier;
109         }
110         length++;
111     }
112
113     for (i = 1; i < r->vec_len; i++)
114     {
115         if (length > 0) /* only add if non-empty */
116             cluster->term_frequency_vecf[i] += (double) mult[i] / length;
117         cluster->term_frequency_vec[i] += mult[i];
118     }
119
120     cluster->term_frequency_vec[0] += length;
121 }
122
123 static struct relevance *relevance_create(pp2_charset_fact_t pft,
124                                           NMEM nmem, const char **terms)
125 {
126     struct relevance *res = nmem_malloc(nmem, sizeof(struct relevance));
127     const char **p;
128     int i;
129
130     for (p = terms, i = 0; *p; p++, i++)
131         ;
132     res->vec_len = ++i;
133     res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
134     memset(res->doc_frequency_vec, 0, res->vec_len * sizeof(int));
135     res->nmem = nmem;
136     res->prt = pp2_charset_token_create(pft, "relevance");
137     res->entries = build_word_entries(res->prt, nmem, terms);
138     return res;
139 }
140
141 // Recursively traverse query structure to extract terms.
142 static void pull_terms(NMEM nmem, struct ccl_rpn_node *n,
143                        char **termlist, int *num, int max_terms)
144 {
145     char **words;
146     int numwords;
147     int i;
148
149     switch (n->kind)
150     {
151     case CCL_RPN_AND:
152     case CCL_RPN_OR:
153     case CCL_RPN_NOT:
154     case CCL_RPN_PROX:
155         pull_terms(nmem, n->u.p[0], termlist, num, max_terms);
156         pull_terms(nmem, n->u.p[1], termlist, num, max_terms);
157         break;
158     case CCL_RPN_TERM:
159         nmem_strsplit(nmem, " ", n->u.t.term, &words, &numwords);
160         for (i = 0; i < numwords; i++)
161         {
162             if (*num < max_terms)
163                 termlist[(*num)++] = words[i];
164         }
165         break;
166     default: // NOOP
167         break;
168     }
169 }
170
171 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
172                                        NMEM nmem, struct ccl_rpn_node *query)
173 {
174     char *termlist[512];
175     int num = 0;
176
177     pull_terms(nmem, query, termlist, &num, sizeof(termlist)/sizeof(*termlist));
178     termlist[num] = 0;
179     return relevance_create(pft, nmem, (const char **) termlist);
180 }
181
182 void relevance_destroy(struct relevance **rp)
183 {
184     if (*rp)
185     {
186         pp2_charset_token_destroy((*rp)->prt);
187         *rp = 0;
188     }
189 }
190
191 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
192 {
193     if (!rec->term_frequency_vec)
194     {
195         int i;
196
197         // term frequency [1,..] . [0] is total length of all fields
198         rec->term_frequency_vec =
199             nmem_malloc(r->nmem,
200                         r->vec_len * sizeof(*rec->term_frequency_vec));
201         for (i = 0; i < r->vec_len; i++)
202             rec->term_frequency_vec[i] = 0;
203         
204         // term frequency divided by length of field [1,...]
205         rec->term_frequency_vecf =
206             nmem_malloc(r->nmem,
207                         r->vec_len * sizeof(*rec->term_frequency_vecf));
208         for (i = 0; i < r->vec_len; i++)
209             rec->term_frequency_vecf[i] = 0.0;
210         
211         // for relevance_countwords (so we don't have to xmalloc/xfree)
212         rec->term_frequency_vec_tmp =
213             nmem_malloc(r->nmem,
214                         r->vec_len * sizeof(*rec->term_frequency_vec_tmp));
215     }
216 }
217
218
219 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
220 {
221     int i;
222
223     for (i = 1; i < r->vec_len; i++)
224         if (cluster->term_frequency_vec[i] > 0)
225             r->doc_frequency_vec[i]++;
226
227     r->doc_frequency_vec[0]++;
228 }
229
230 // Prepare for a relevance-sorted read
231 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
232 {
233     int i;
234     float *idfvec = xmalloc(rel->vec_len * sizeof(float));
235
236     reclist_enter(reclist);
237     // Calculate document frequency vector for each term.
238     for (i = 1; i < rel->vec_len; i++)
239     {
240         if (!rel->doc_frequency_vec[i])
241             idfvec[i] = 0;
242         else
243         {
244             // This conditional may be terribly wrong
245             // It was there to address the situation where vec[0] == vec[i]
246             // which leads to idfvec[i] == 0... not sure about this
247             // Traditional TF-IDF may assume that a word that occurs in every
248             // record is irrelevant, but this is actually something we will
249             // see a lot
250             if ((idfvec[i] = log((float) rel->doc_frequency_vec[0] /
251                             rel->doc_frequency_vec[i])) < 0.0000001)
252                 idfvec[i] = 1;
253         }
254     }
255     // Calculate relevance for each document
256
257     while (1)
258     {
259         int t;
260         int relevance = 0;
261         struct record_cluster *rec = reclist_read_record(reclist);
262         if (!rec)
263             break;
264         for (t = 1; t < rel->vec_len; t++)
265         {
266             float termfreq;
267 #if 1
268             termfreq = (float) rec->term_frequency_vecf[t];
269 #else
270             if (rec->term_frequency_vec[0])
271             {
272                 termfreq = (float)
273                     rec->term_frequency_vec[t] / rec->term_frequency_vec[0] ;
274             }
275             else
276                 termfreq = 0.0;
277 #endif
278             relevance += 100000 * (termfreq * idfvec[t] + 0.0000005);  
279         }
280         rec->relevance_score = relevance;
281     }
282     reclist_leave(reclist);
283     xfree(idfvec);
284 }
285
286 /*
287  * Local variables:
288  * c-basic-offset: 4
289  * c-file-style: "Stroustrup"
290  * indent-tabs-mode: nil
291  * End:
292  * vim: shiftwidth=4 tabstop=8 expandtab
293  */
294