b08d217706bb047a6b318fc35c31101c46474cd6
[pazpar2-moved-to-github.git] / src / relevance.c
1 /* This file is part of Pazpar2.
2    Copyright (C) 2006-2013 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 #ifdef WIN32
32 #define log2(x) (log(x)/log(2))
33 #endif
34
35 struct relevance
36 {
37     int *doc_frequency_vec;
38     int *term_frequency_vec_tmp;
39     int *term_pos;
40     int vec_len;
41     struct word_entry *entries;
42     pp2_charset_token_t prt;
43     int rank_cluster;
44     double follow_factor;
45     double lead_decay;
46     int length_divide;
47     NMEM nmem;
48 };
49
50 struct word_entry {
51     const char *norm_str;
52     const char *display_str;
53     int termno;
54     char *ccl_field;
55     struct word_entry *next;
56 };
57
58 static struct word_entry *word_entry_match(struct relevance *r,
59                                            const char *norm_str,
60                                            const char *rank, int *weight)
61 {
62     int i = 1;
63     struct word_entry *entries = r->entries;
64     for (; entries; entries = entries->next, i++)
65     {
66         if (*norm_str && !strcmp(norm_str, entries->norm_str))
67         {
68             const char *cp = 0;
69             int no_read = 0;
70             sscanf(rank, "%d%n", weight, &no_read);
71             rank += no_read;
72             while (*rank == ' ')
73                 rank++;
74             if (no_read > 0 && (cp = strchr(rank, ' ')))
75             {
76                 if ((cp - rank) == strlen(entries->ccl_field) &&
77                     memcmp(entries->ccl_field, rank, cp - rank) == 0)
78                     *weight = atoi(cp + 1);
79             }
80             return entries;
81         }
82     }
83     return 0;
84 }
85
86 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
87                           const char *words, const char *rank,
88                           const char *name)
89 {
90     int *w = r->term_frequency_vec_tmp;
91     const char *norm_str;
92     int i, length = 0;
93     double lead_decay = r->lead_decay;
94     struct word_entry *e;
95     WRBUF wr = cluster->relevance_explain1;
96     int printed_about_field = 0;
97
98     pp2_charset_token_first(r->prt, words, 0);
99     for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
100     {
101         w[i] = 0;
102         r->term_pos[i] = 0;
103     }
104
105     assert(rank);
106     while ((norm_str = pp2_charset_token_next(r->prt)))
107     {
108         int local_weight = 0;
109         e = word_entry_match(r, norm_str, rank, &local_weight);
110         if (e)
111         {
112             int res = e->termno;
113             int j;
114
115             if (!printed_about_field)
116             {
117                 printed_about_field = 1;
118                 wrbuf_printf(wr, "field=%s content=", name);
119                 if (strlen(words) > 50)
120                 {
121                     wrbuf_xmlputs_n(wr, words, 49);
122                     wrbuf_puts(wr, " ...");
123                 }
124                 else
125                     wrbuf_xmlputs(wr, words);
126                 wrbuf_puts(wr, ";\n");
127             }
128             assert(res < r->vec_len);
129             w[res] += local_weight / (1 + log2(1 + lead_decay * length));
130             wrbuf_printf(wr, "%s: w[%d] += w(%d) / "
131                          "(1+log2(1+lead_decay(%f) * length(%d)));\n",
132                          e->display_str, res, local_weight, lead_decay, length);
133             j = res - 1;
134             if (j > 0 && r->term_pos[j])
135             {
136                 int d = length + 1 - r->term_pos[j];
137                 wrbuf_printf(wr, "%s: w[%d] += w[%d](%d) * follow(%f) / "
138                              "(1+log2(d(%d));\n",
139                              e->display_str, res, res, w[res],
140                              r->follow_factor, d);
141                 w[res] += w[res] * r->follow_factor / (1 + log2(d));
142             }
143             for (j = 0; j < r->vec_len; j++)
144                 r->term_pos[j] = j < res ? 0 : length + 1;
145         }
146         length++;
147     }
148
149     for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
150     {
151         if (length == 0 || w[i] == 0)
152             continue;
153         wrbuf_printf(wr, "%s: tf[%d] += w[%d](%d)", e->display_str, i, i, w[i]);
154         switch (r->length_divide)
155         {
156         case 0:
157             cluster->term_frequency_vecf[i] += (double) w[i];
158             break;
159         case 1:
160             wrbuf_printf(wr, " / log2(1+length(%d))", length);
161             cluster->term_frequency_vecf[i] +=
162                 (double) w[i] / log2(1 + length);
163             break;
164         case 2:
165             wrbuf_printf(wr, " / length(%d)", length);
166             cluster->term_frequency_vecf[i] += (double) w[i] / length;
167         }
168         cluster->term_frequency_vec[i] += w[i];
169         wrbuf_printf(wr, " (%f);\n", cluster->term_frequency_vecf[i]);
170     }
171
172     cluster->term_frequency_vec[0] += length;
173 }
174
175 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
176 {
177     char **words;
178     int numwords;
179     char *ccl_field;
180     int i;
181
182     switch (n->kind)
183     {
184     case CCL_RPN_AND:
185     case CCL_RPN_OR:
186     case CCL_RPN_NOT:
187     case CCL_RPN_PROX:
188         pull_terms(res, n->u.p[0]);
189         pull_terms(res, n->u.p[1]);
190         break;
191     case CCL_RPN_TERM:
192         nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
193         for (i = 0; i < numwords; i++)
194         {
195             const char *norm_str;
196
197             ccl_field = nmem_strdup_null(res->nmem, n->u.t.qual);
198
199             pp2_charset_token_first(res->prt, words[i], 0);
200             while ((norm_str = pp2_charset_token_next(res->prt)))
201             {
202                 struct word_entry **e = &res->entries;
203                 while (*e)
204                     e = &(*e)->next;
205                 *e = nmem_malloc(res->nmem, sizeof(**e));
206                 (*e)->norm_str = nmem_strdup(res->nmem, norm_str);
207                 (*e)->ccl_field = ccl_field;
208                 (*e)->termno = res->vec_len++;
209                 (*e)->display_str = nmem_strdup(res->nmem, words[i]);
210                 (*e)->next = 0;
211             }
212         }
213         break;
214     default:
215         break;
216     }
217 }
218
219 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
220                                        struct ccl_rpn_node *query,
221                                        int rank_cluster,
222                                        double follow_factor, double lead_decay,
223                                        int length_divide)
224 {
225     NMEM nmem = nmem_create();
226     struct relevance *res = nmem_malloc(nmem, sizeof(*res));
227     int i;
228
229     res->nmem = nmem;
230     res->entries = 0;
231     res->vec_len = 1;
232     res->rank_cluster = rank_cluster;
233     res->follow_factor = follow_factor;
234     res->lead_decay = lead_decay;
235     res->length_divide = length_divide;
236     res->prt = pp2_charset_token_create(pft, "relevance");
237
238     pull_terms(res, query);
239
240     res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
241     for (i = 0; i < res->vec_len; i++)
242         res->doc_frequency_vec[i] = 0;
243
244     // worker array
245     res->term_frequency_vec_tmp =
246         nmem_malloc(res->nmem,
247                     res->vec_len * sizeof(*res->term_frequency_vec_tmp));
248
249     res->term_pos =
250         nmem_malloc(res->nmem, res->vec_len * sizeof(*res->term_pos));
251
252     return res;
253 }
254
255 void relevance_destroy(struct relevance **rp)
256 {
257     if (*rp)
258     {
259         pp2_charset_token_destroy((*rp)->prt);
260         nmem_destroy((*rp)->nmem);
261         *rp = 0;
262     }
263 }
264
265 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
266 {
267     if (!rec->term_frequency_vec)
268     {
269         int i;
270
271         // term frequency [1,..] . [0] is total length of all fields
272         rec->term_frequency_vec =
273             nmem_malloc(r->nmem,
274                         r->vec_len * sizeof(*rec->term_frequency_vec));
275         for (i = 0; i < r->vec_len; i++)
276             rec->term_frequency_vec[i] = 0;
277
278         // term frequency divided by length of field [1,...]
279         rec->term_frequency_vecf =
280             nmem_malloc(r->nmem,
281                         r->vec_len * sizeof(*rec->term_frequency_vecf));
282         for (i = 0; i < r->vec_len; i++)
283             rec->term_frequency_vecf[i] = 0.0;
284     }
285 }
286
287 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
288 {
289     int i;
290
291     for (i = 1; i < r->vec_len; i++)
292         if (cluster->term_frequency_vec[i] > 0)
293             r->doc_frequency_vec[i]++;
294
295     r->doc_frequency_vec[0]++;
296 }
297
298 // Prepare for a relevance-sorted read
299 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
300 {
301     int i;
302     float *idfvec = xmalloc(rel->vec_len * sizeof(float));
303
304     reclist_enter(reclist);
305     // Calculate document frequency vector for each term.
306     for (i = 1; i < rel->vec_len; i++)
307     {
308         if (!rel->doc_frequency_vec[i])
309             idfvec[i] = 0;
310         else
311         {
312             /* add one to nominator idf(t,D) to ensure a value > 0 */
313             idfvec[i] = log((float) (1 + rel->doc_frequency_vec[0]) /
314                             rel->doc_frequency_vec[i]);
315         }
316     }
317     // Calculate relevance for each document
318     while (1)
319     {
320         int relevance = 0;
321         WRBUF w;
322         struct word_entry *e = rel->entries;
323         struct record_cluster *rec = reclist_read_record(reclist);
324         if (!rec)
325             break;
326         w = rec->relevance_explain2;
327         wrbuf_rewind(w);
328         wrbuf_puts(w, "relevance = 0;\n");
329         for (i = 1; i < rel->vec_len; i++)
330         {
331             float termfreq = (float) rec->term_frequency_vecf[i];
332             int add = 100000 * termfreq * idfvec[i];
333
334             wrbuf_printf(w, "idf[%d] = log(((1 + total(%d))/termoccur(%d));\n",
335                          i, rel->doc_frequency_vec[0],
336                          rel->doc_frequency_vec[i]);
337             wrbuf_printf(w, "%s: relevance += 100000 * tf[%d](%f) * "
338                          "idf[%d](%f) (%d);\n",
339                          e->display_str, i, termfreq, i, idfvec[i], add);
340             relevance += add;
341             e = e->next;
342         }
343         if (!rel->rank_cluster)
344         {
345             struct record *record;
346             int cluster_size = 0;
347
348             for (record = rec->records; record; record = record->next)
349                 cluster_size++;
350
351             wrbuf_printf(w, "score = relevance(%d)/cluster_size(%d);\n",
352                          relevance, cluster_size);
353             relevance /= cluster_size;
354         }
355         else
356         {
357             wrbuf_printf(w, "score = relevance(%d);\n", relevance);
358         }
359         rec->relevance_score = relevance;
360     }
361     reclist_leave(reclist);
362     xfree(idfvec);
363 }
364
365 /*
366  * Local variables:
367  * c-basic-offset: 4
368  * c-file-style: "Stroustrup"
369  * indent-tabs-mode: nil
370  * End:
371  * vim: shiftwidth=4 tabstop=8 expandtab
372  */
373