Smaller, better relevance code
[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 struct word_entry {
41     const char *norm_str;
42     int termno;
43     struct word_entry *next;
44 };
45
46 int word_entry_match(struct word_entry *entries, const char *norm_str)
47 {
48     for (; entries; entries = entries->next)
49     {
50         if (!strcmp(norm_str, entries->norm_str))
51             return entries->termno;
52     }
53     return 0;
54 }
55
56 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
57                           const char *words, int multiplier, const char *name)
58 {
59     int *mult = cluster->term_frequency_vec_tmp;
60     const char *norm_str;
61     int i, length = 0;
62
63     pp2_charset_token_first(r->prt, words, 0);
64     for (i = 1; i < r->vec_len; i++)
65         mult[i] = 0;
66
67     while ((norm_str = pp2_charset_token_next(r->prt)))
68     {
69         int res = word_entry_match(r->entries, norm_str);
70         if (res)
71         {
72             assert(res < r->vec_len);
73             mult[res] += multiplier;
74         }
75         length++;
76     }
77
78     for (i = 1; i < r->vec_len; i++)
79     {
80         if (length > 0) /* only add if non-empty */
81             cluster->term_frequency_vecf[i] += (double) mult[i] / length;
82         cluster->term_frequency_vec[i] += mult[i];
83     }
84
85     cluster->term_frequency_vec[0] += length;
86 }
87
88 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
89 {
90     char **words;
91     int numwords;
92     int i;
93
94     switch (n->kind)
95     {
96     case CCL_RPN_AND:
97     case CCL_RPN_OR:
98     case CCL_RPN_NOT:
99     case CCL_RPN_PROX:
100         pull_terms(res, n->u.p[0]);
101         pull_terms(res, n->u.p[1]);
102         break;
103     case CCL_RPN_TERM:
104         nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
105         for (i = 0; i < numwords; i++)
106         {
107             const char *norm_str;
108
109             pp2_charset_token_first(res->prt, words[i], 0);
110             while ((norm_str = pp2_charset_token_next(res->prt)))
111             {
112                 struct word_entry **e = &res->entries;
113                 while (*e)
114                     e = &(*e)->next;
115                 *e = nmem_malloc(res->nmem, sizeof(**e));
116                 (*e)->norm_str = nmem_strdup(res->nmem, norm_str);
117                 (*e)->termno = res->vec_len++;
118                 (*e)->next = 0;
119             }
120         }
121         break;
122     default:
123         break;
124     }
125 }
126
127 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
128                                        NMEM nmem, struct ccl_rpn_node *query)
129 {
130     struct relevance *res = nmem_malloc(nmem, sizeof(*res));
131     int i;
132
133     res->nmem = nmem;
134     res->entries = 0;
135     res->vec_len = 1;
136     res->prt = pp2_charset_token_create(pft, "relevance");
137     
138     pull_terms(res, query);
139
140     res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
141     for (i = 0; i < res->vec_len; i++)
142         res->doc_frequency_vec[i] = 0;        
143     return res;
144 }
145
146 void relevance_destroy(struct relevance **rp)
147 {
148     if (*rp)
149     {
150         pp2_charset_token_destroy((*rp)->prt);
151         *rp = 0;
152     }
153 }
154
155 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
156 {
157     if (!rec->term_frequency_vec)
158     {
159         int i;
160
161         // term frequency [1,..] . [0] is total length of all fields
162         rec->term_frequency_vec =
163             nmem_malloc(r->nmem,
164                         r->vec_len * sizeof(*rec->term_frequency_vec));
165         for (i = 0; i < r->vec_len; i++)
166             rec->term_frequency_vec[i] = 0;
167         
168         // term frequency divided by length of field [1,...]
169         rec->term_frequency_vecf =
170             nmem_malloc(r->nmem,
171                         r->vec_len * sizeof(*rec->term_frequency_vecf));
172         for (i = 0; i < r->vec_len; i++)
173             rec->term_frequency_vecf[i] = 0.0;
174         
175         // for relevance_countwords (so we don't have to xmalloc/xfree)
176         rec->term_frequency_vec_tmp =
177             nmem_malloc(r->nmem,
178                         r->vec_len * sizeof(*rec->term_frequency_vec_tmp));
179     }
180 }
181
182 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
183 {
184     int i;
185
186     for (i = 1; i < r->vec_len; i++)
187         if (cluster->term_frequency_vec[i] > 0)
188             r->doc_frequency_vec[i]++;
189
190     r->doc_frequency_vec[0]++;
191 }
192
193 // Prepare for a relevance-sorted read
194 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
195 {
196     int i;
197     float *idfvec = xmalloc(rel->vec_len * sizeof(float));
198
199     reclist_enter(reclist);
200     // Calculate document frequency vector for each term.
201     for (i = 1; i < rel->vec_len; i++)
202     {
203         if (!rel->doc_frequency_vec[i])
204             idfvec[i] = 0;
205         else
206         {
207             // This conditional may be terribly wrong
208             // It was there to address the situation where vec[0] == vec[i]
209             // which leads to idfvec[i] == 0... not sure about this
210             // Traditional TF-IDF may assume that a word that occurs in every
211             // record is irrelevant, but this is actually something we will
212             // see a lot
213             if ((idfvec[i] = log((float) rel->doc_frequency_vec[0] /
214                             rel->doc_frequency_vec[i])) < 0.0000001)
215                 idfvec[i] = 1;
216         }
217     }
218     // Calculate relevance for each document
219     while (1)
220     {
221         int t;
222         int relevance = 0;
223         struct record_cluster *rec = reclist_read_record(reclist);
224         if (!rec)
225             break;
226         for (t = 1; t < rel->vec_len; t++)
227         {
228             float termfreq = (float) rec->term_frequency_vecf[t];
229             relevance += 100000 * (termfreq * idfvec[t] + 0.0000005);  
230         }
231         rec->relevance_score = relevance;
232     }
233     reclist_leave(reclist);
234     xfree(idfvec);
235 }
236
237 /*
238  * Local variables:
239  * c-basic-offset: 4
240  * c-file-style: "Stroustrup"
241  * indent-tabs-mode: nil
242  * End:
243  * vim: shiftwidth=4 tabstop=8 expandtab
244  */
245