Towards normalized rankings (PAZ-909)
[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 #include "client.h"
31 #include "settings.h"
32
33 #ifdef WIN32
34 #define log2(x) (log(x)/log(2))
35 #endif
36
37 struct relevance
38 {
39     int *doc_frequency_vec;
40     int *term_frequency_vec_tmp;
41     int *term_pos;
42     int vec_len;
43     struct word_entry *entries;
44     pp2_charset_token_t prt;
45     int rank_cluster;
46     double follow_factor;
47     double lead_decay;
48     int length_divide;
49     NMEM nmem;
50     struct norm_client *norm;
51 };
52
53 struct word_entry {
54     const char *norm_str;
55     const char *display_str;
56     int termno;
57     char *ccl_field;
58     struct word_entry *next;
59 };
60
61 // Structure to keep data for norm_client scores from one client
62 struct norm_client
63 {
64     int num; // number of the client
65     float max;
66     float min;
67     int count;
68     const char *native_score;
69     int scorefield;
70     float a,b; // Rn = a*R + b
71     struct client *client;
72     struct norm_client *next;
73     struct norm_record *records;
74 };
75
76 const int scorefield_none = -1;  // Do not normalize anything, use tf/idf as is
77   // This is the old behavior, and the default
78 const int scorefield_internal = -2;  // use our tf/idf, but normalize it
79 const int scorefield_position = -3;  // fake a score based on the position
80
81 // A structure for each (sub)record. There is one list for each client
82 struct norm_record
83 {
84     struct record *record;
85     float score;
86     struct record_cluster *clust;
87     struct norm_record *next;
88 };
89
90 // Find the norm_client entry for this client, or create one if not there
91 struct norm_client *findnorm( struct relevance *rel, struct client* client)
92 {
93     struct norm_client *n = rel->norm;
94     struct session_database *sdb;
95     while (n) {
96         if (n->client == client )
97             return n;
98         n = n->next;
99     }
100     n = nmem_malloc(rel->nmem, sizeof(struct norm_client) );
101     if ( rel->norm )
102         n->num = rel->norm->num +1;
103     else
104         n->num = 1;
105     n->count = 0;
106     n->max = 0.0;
107     n->min = 0.0;
108     n->client = client;
109     n->next = rel->norm;
110     rel->norm = n;
111     sdb = client_get_database(client);
112     n->native_score = session_setting_oneval(sdb, PZ_NATIVE_SCORE);
113     n->records = 0;
114     n->scorefield = scorefield_none;
115     yaz_log(YLOG_LOG,"Normalizing: Client %d uses '%s'", n->num, n->native_score );
116     if ( ! n->native_score  || ! *n->native_score )  // not specified
117         n->scorefield = scorefield_none; 
118     else if ( strcmp(n->native_score,"position") == 0 )
119         n->scorefield = scorefield_position;
120     else if ( strcmp(n->native_score,"internal") == 0 )
121         n->scorefield = scorefield_internal;
122     else
123     { // Get the field index for the score
124         struct session *se = client_get_session(client);
125         n->scorefield = conf_service_metadata_field_id(se->service, n->native_score);
126     }
127     yaz_log(YLOG_LOG,"Normalizing: Client %d uses '%s' = %d",
128             n->num, n->native_score, n->scorefield );
129     return n;
130 }
131
132
133 // Add a record in the list for that client, for normalizing later
134 static void setup_norm_record( struct relevance *rel,  struct record_cluster *clust)
135 {
136     struct record *record;
137     for (record = clust->records; record; record = record->next)
138     {
139         struct norm_client *norm = findnorm(rel, record->client);
140         struct norm_record *rp;
141         if ( norm->scorefield == scorefield_none)
142             break;  // not interested in normalizing this client
143         rp = nmem_malloc(rel->nmem, sizeof(struct norm_record) );
144         norm->count ++;
145         rp->next = norm->records;
146         norm->records = rp;
147         rp->clust = clust;
148         rp->record = record;
149         if ( norm->scorefield == scorefield_position )
150             rp->score = 1.0 / record->position;
151         else if ( norm->scorefield == scorefield_internal )
152             rp->score = clust->relevance_score; // the tf/idf for the whole cluster
153               // TODO - Get them for each record, merge later!
154         else
155         {
156             struct record_metadata *md = record->metadata[norm->scorefield];
157             rp->score = md->data.fnumber;
158             assert(rp->score>0); // ###
159         }
160         yaz_log(YLOG_LOG,"Got score for %d/%d : %f ",
161                 norm->num, record->position, rp->score );
162         if ( norm->count == 1 )
163         {
164             norm->max = rp->score;
165             norm->min = rp->score;
166         } else {
167             if ( rp->score > norm->max )
168                 norm->max = rp->score;
169             if ( rp->score < norm->min && abs(rp->score) < 1e-6 )
170                 norm->min = rp->score;  // skip zeroes
171         }
172     }
173 }
174
175 // Calculate the squared sum of residuals, that is the difference from
176 // normalized values to the target curve, which is 1/n 
177 static double squaresum( struct norm_record *rp, double a, double b)
178 {
179     double sum = 0.0;
180     for ( ; rp; rp = rp->next )
181     {
182         double target = 1.0 / rp->record->position;
183         double normscore = rp->score * a + b;
184         double diff = target - normscore;
185         sum += diff * diff;
186     }
187     return sum;
188 }
189
190 static void normalize_scores(struct relevance *rel)
191 {
192     // For each client, normalize scores
193     struct norm_client *norm;
194     for ( norm = rel->norm; norm; norm = norm->next )
195     {
196         yaz_log(YLOG_LOG,"Normalizing client %d: scorefield=%d count=%d",
197                 norm->num, norm->scorefield, norm->count);
198         norm->a = 1.0; // default normalizing factors, no change
199         norm->b = 0.0;
200         if ( norm->scorefield != scorefield_none &&
201              norm->scorefield != scorefield_position )
202         { // have something to normalize
203             double range = norm->max - norm->min;
204             int it = 0;
205             double a,b;  // params to optimize
206             double as,bs; // step sizes
207             double chi;
208             // initial guesses for the parameters
209             if ( range < 1e-6 ) // practically zero
210                 range = norm->max;
211             a = 1.0 / range;
212             b = abs(norm->min);
213             as = a / 3;
214             bs = b / 3;
215             chi = squaresum( norm->records, a,b);
216             while (it++ < 100)  // safeguard against things not converging
217             {
218                 // optimize a
219                 double plus = squaresum(norm->records, a+as, b);
220                 double minus= squaresum(norm->records, a-as, b);
221                 if ( plus < chi && plus < minus )
222                 {
223                     a = a + as;
224                     chi = plus;
225                 }
226                 else if ( minus < chi && minus < plus )
227                 {
228                     a = a - as;
229                     chi = minus;
230                 }
231                 else
232                     as = as / 2;  
233                 // optimize b
234                 plus = squaresum(norm->records, a, b+bs);
235                 minus= squaresum(norm->records, a, b-bs);
236                 if ( plus < chi && plus < minus )
237                 {
238                     b = b + bs;
239                     chi = plus;
240                 }
241                 else if ( minus < chi && minus < plus )
242                 {
243                     b = b - bs;
244                     chi = minus;
245                 }
246                 else
247                     bs = bs / 2;
248                 yaz_log(YLOG_LOG,"Fitting it=%d: a=%f / %f  b=%f / %f  chi = %f",
249                         it, a, as, b, bs, chi );
250                 norm->a = a;
251                 norm->b = b;
252                 if ( abs(as) * 1000.0 < abs(a) &&
253                      abs(bs) * 1000.0 < abs(b) )
254                     break;  // not changing much any more
255             }
256         }
257         
258         if ( norm->scorefield != scorefield_none )
259         { // distribute the normalized scores to the records
260             struct norm_record *nr = norm->records;
261             for ( ; nr ; nr = nr->next ) {
262                 double r = nr->score;
263                 r = norm->a * r + norm -> b;
264                 nr->clust->relevance_score = 10000 * r;
265                 yaz_log(YLOG_LOG,"Normalized %f * %f + %f = %f",
266                         nr->score, norm->a, norm->b, r );
267                 // TODO - This keeps overwriting the cluster score in random order!
268                 // Need to merge results better
269             }
270
271         }
272
273     } // client loop
274 }
275
276
277 static struct word_entry *word_entry_match(struct relevance *r,
278                                            const char *norm_str,
279                                            const char *rank, int *weight)
280 {
281     int i = 1;
282     struct word_entry *entries = r->entries;
283     for (; entries; entries = entries->next, i++)
284     {
285         if (*norm_str && !strcmp(norm_str, entries->norm_str))
286         {
287             const char *cp = 0;
288             int no_read = 0;
289             sscanf(rank, "%d%n", weight, &no_read);
290             rank += no_read;
291             while (*rank == ' ')
292                 rank++;
293             if (no_read > 0 && (cp = strchr(rank, ' ')))
294             {
295                 if ((cp - rank) == strlen(entries->ccl_field) &&
296                     memcmp(entries->ccl_field, rank, cp - rank) == 0)
297                     *weight = atoi(cp + 1);
298             }
299             return entries;
300         }
301     }
302     return 0;
303 }
304
305 int relevance_snippet(struct relevance *r,
306                       const char *words, const char *name,
307                       WRBUF w_snippet)
308 {
309     int no = 0;
310     const char *norm_str;
311     int highlight = 0;
312
313     pp2_charset_token_first(r->prt, words, 0);
314     while ((norm_str = pp2_charset_token_next(r->prt)))
315     {
316         size_t org_start, org_len;
317         struct word_entry *entries = r->entries;
318         int i;
319
320         pp2_get_org(r->prt, &org_start, &org_len);
321         for (; entries; entries = entries->next, i++)
322         {
323             if (*norm_str && !strcmp(norm_str, entries->norm_str))
324                 break;
325         }
326         if (entries)
327         {
328             if (!highlight)
329             {
330                 highlight = 1;
331                 wrbuf_puts(w_snippet, "<match>");
332                 no++;
333             }
334         }
335         else
336         {
337             if (highlight)
338             {
339                 highlight = 0;
340                 wrbuf_puts(w_snippet, "</match>");
341             }
342         }
343         wrbuf_xmlputs_n(w_snippet, words + org_start, org_len);
344     }
345     if (highlight)
346         wrbuf_puts(w_snippet, "</match>");
347     if (no)
348     {
349         yaz_log(YLOG_DEBUG, "SNIPPET match: %s", wrbuf_cstr(w_snippet));
350     }
351     return no;
352 }
353
354 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
355                           const char *words, const char *rank,
356                           const char *name)
357 {
358     int *w = r->term_frequency_vec_tmp;
359     const char *norm_str;
360     int i, length = 0;
361     double lead_decay = r->lead_decay;
362     struct word_entry *e;
363     WRBUF wr = cluster->relevance_explain1;
364     int printed_about_field = 0;
365
366     pp2_charset_token_first(r->prt, words, 0);
367     for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
368     {
369         w[i] = 0;
370         r->term_pos[i] = 0;
371     }
372
373     assert(rank);
374     while ((norm_str = pp2_charset_token_next(r->prt)))
375     {
376         int local_weight = 0;
377         e = word_entry_match(r, norm_str, rank, &local_weight);
378         if (e)
379         {
380             int res = e->termno;
381             int j;
382
383             if (!printed_about_field)
384             {
385                 printed_about_field = 1;
386                 wrbuf_printf(wr, "field=%s content=", name);
387                 if (strlen(words) > 50)
388                 {
389                     wrbuf_xmlputs_n(wr, words, 49);
390                     wrbuf_puts(wr, " ...");
391                 }
392                 else
393                     wrbuf_xmlputs(wr, words);
394                 wrbuf_puts(wr, ";\n");
395             }
396             assert(res < r->vec_len);
397             w[res] += local_weight / (1 + log2(1 + lead_decay * length));
398             wrbuf_printf(wr, "%s: w[%d] += w(%d) / "
399                          "(1+log2(1+lead_decay(%f) * length(%d)));\n",
400                          e->display_str, res, local_weight, lead_decay, length);
401             j = res - 1;
402             if (j > 0 && r->term_pos[j])
403             {
404                 int d = length + 1 - r->term_pos[j];
405                 wrbuf_printf(wr, "%s: w[%d] += w[%d](%d) * follow(%f) / "
406                              "(1+log2(d(%d));\n",
407                              e->display_str, res, res, w[res],
408                              r->follow_factor, d);
409                 w[res] += w[res] * r->follow_factor / (1 + log2(d));
410             }
411             for (j = 0; j < r->vec_len; j++)
412                 r->term_pos[j] = j < res ? 0 : length + 1;
413         }
414         length++;
415     }
416
417     for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
418     {
419         if (length == 0 || w[i] == 0)
420             continue;
421         wrbuf_printf(wr, "%s: tf[%d] += w[%d](%d)", e->display_str, i, i, w[i]);
422         switch (r->length_divide)
423         {
424         case 0:
425             cluster->term_frequency_vecf[i] += (double) w[i];
426             break;
427         case 1:
428             wrbuf_printf(wr, " / log2(1+length(%d))", length);
429             cluster->term_frequency_vecf[i] +=
430                 (double) w[i] / log2(1 + length);
431             break;
432         case 2:
433             wrbuf_printf(wr, " / length(%d)", length);
434             cluster->term_frequency_vecf[i] += (double) w[i] / length;
435         }
436         cluster->term_frequency_vec[i] += w[i];
437         wrbuf_printf(wr, " (%f);\n", cluster->term_frequency_vecf[i]);
438     }
439
440     cluster->term_frequency_vec[0] += length;
441 }
442
443 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
444 {
445     char **words;
446     int numwords;
447     char *ccl_field;
448     int i;
449
450     switch (n->kind)
451     {
452     case CCL_RPN_AND:
453     case CCL_RPN_OR:
454     case CCL_RPN_NOT:
455     case CCL_RPN_PROX:
456         pull_terms(res, n->u.p[0]);
457         pull_terms(res, n->u.p[1]);
458         break;
459     case CCL_RPN_TERM:
460         nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
461         for (i = 0; i < numwords; i++)
462         {
463             const char *norm_str;
464
465             ccl_field = nmem_strdup_null(res->nmem, n->u.t.qual);
466
467             pp2_charset_token_first(res->prt, words[i], 0);
468             while ((norm_str = pp2_charset_token_next(res->prt)))
469             {
470                 struct word_entry **e = &res->entries;
471                 while (*e)
472                     e = &(*e)->next;
473                 *e = nmem_malloc(res->nmem, sizeof(**e));
474                 (*e)->norm_str = nmem_strdup(res->nmem, norm_str);
475                 (*e)->ccl_field = ccl_field;
476                 (*e)->termno = res->vec_len++;
477                 (*e)->display_str = nmem_strdup(res->nmem, words[i]);
478                 (*e)->next = 0;
479             }
480         }
481         break;
482     default:
483         break;
484     }
485 }
486 void relevance_clear(struct relevance *r)
487 {
488     if (r)
489     {
490         int i;
491         for (i = 0; i < r->vec_len; i++)
492             r->doc_frequency_vec[i] = 0;
493     }
494 }
495
496 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
497                                        struct ccl_rpn_node *query,
498                                        int rank_cluster,
499                                        double follow_factor, double lead_decay,
500                                        int length_divide)
501 {
502     NMEM nmem = nmem_create();
503     struct relevance *res = nmem_malloc(nmem, sizeof(*res));
504
505     res->nmem = nmem;
506     res->entries = 0;
507     res->vec_len = 1;
508     res->rank_cluster = rank_cluster;
509     res->follow_factor = follow_factor;
510     res->lead_decay = lead_decay;
511     res->length_divide = length_divide;
512     res->norm = 0;
513     res->prt = pp2_charset_token_create(pft, "relevance");
514
515     pull_terms(res, query);
516
517     res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
518
519     // worker array
520     res->term_frequency_vec_tmp =
521         nmem_malloc(res->nmem,
522                     res->vec_len * sizeof(*res->term_frequency_vec_tmp));
523
524     res->term_pos =
525         nmem_malloc(res->nmem, res->vec_len * sizeof(*res->term_pos));
526
527     relevance_clear(res);
528     return res;
529 }
530
531 void relevance_destroy(struct relevance **rp)
532 {
533     if (*rp)
534     {
535         pp2_charset_token_destroy((*rp)->prt);
536         nmem_destroy((*rp)->nmem);
537         *rp = 0;
538     }
539 }
540
541 void relevance_mergerec(struct relevance *r, struct record_cluster *dst,
542                         const struct record_cluster *src)
543 {
544     int i;
545
546     for (i = 0; i < r->vec_len; i++)
547         dst->term_frequency_vec[i] += src->term_frequency_vec[i];
548
549     for (i = 0; i < r->vec_len; i++)
550         dst->term_frequency_vecf[i] += src->term_frequency_vecf[i];
551 }
552
553 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
554 {
555     int i;
556
557     // term frequency [1,..] . [0] is total length of all fields
558     rec->term_frequency_vec =
559         nmem_malloc(r->nmem,
560                     r->vec_len * sizeof(*rec->term_frequency_vec));
561     for (i = 0; i < r->vec_len; i++)
562         rec->term_frequency_vec[i] = 0;
563
564     // term frequency divided by length of field [1,...]
565     rec->term_frequency_vecf =
566         nmem_malloc(r->nmem,
567                     r->vec_len * sizeof(*rec->term_frequency_vecf));
568     for (i = 0; i < r->vec_len; i++)
569         rec->term_frequency_vecf[i] = 0.0;
570 }
571
572 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
573 {
574     int i;
575
576     for (i = 1; i < r->vec_len; i++)
577         if (cluster->term_frequency_vec[i] > 0)
578             r->doc_frequency_vec[i]++;
579
580     r->doc_frequency_vec[0]++;
581 }
582
583
584
585 // Prepare for a relevance-sorted read
586 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
587 {
588     int i;
589     float *idfvec = xmalloc(rel->vec_len * sizeof(float));
590
591     reclist_enter(reclist);
592
593     // Calculate document frequency vector for each term.
594     for (i = 1; i < rel->vec_len; i++)
595     {
596         if (!rel->doc_frequency_vec[i])
597             idfvec[i] = 0;
598         else
599         {
600             /* add one to nominator idf(t,D) to ensure a value > 0 */
601             idfvec[i] = log((float) (1 + rel->doc_frequency_vec[0]) /
602                             rel->doc_frequency_vec[i]);
603         }
604     }
605     // Calculate relevance for each document
606     while (1)
607     {
608         int relevance = 0;
609         WRBUF w;
610         struct word_entry *e = rel->entries;
611         struct record_cluster *rec = reclist_read_record(reclist);
612         if (!rec)
613             break;
614         w = rec->relevance_explain2;
615         wrbuf_rewind(w);
616         wrbuf_puts(w, "relevance = 0;\n");
617         for (i = 1; i < rel->vec_len; i++)
618         {
619             float termfreq = (float) rec->term_frequency_vecf[i];
620             int add = 100000 * termfreq * idfvec[i];
621
622             wrbuf_printf(w, "idf[%d] = log(((1 + total(%d))/termoccur(%d));\n",
623                          i, rel->doc_frequency_vec[0],
624                          rel->doc_frequency_vec[i]);
625             wrbuf_printf(w, "%s: relevance += 100000 * tf[%d](%f) * "
626                          "idf[%d](%f) (%d);\n",
627                          e->display_str, i, termfreq, i, idfvec[i], add);
628             relevance += add;
629             e = e->next;
630         }
631         if (!rel->rank_cluster)
632         {
633             struct record *record;
634             int cluster_size = 0;
635
636             for (record = rec->records; record; record = record->next)
637                 cluster_size++;
638
639             wrbuf_printf(w, "score = relevance(%d)/cluster_size(%d);\n",
640                          relevance, cluster_size);
641             relevance /= cluster_size;
642         }
643         else
644         {
645             wrbuf_printf(w, "score = relevance(%d);\n", relevance);
646         }
647         rec->relevance_score = relevance;
648
649         // Build the normalizing structures
650         // List of (sub)records for each target
651         setup_norm_record( rel, rec );
652         
653         // TODO - Loop again, merge individual record scores into clusters
654         // Can I reset the reclist, or can I leave and enter without race conditions?
655         
656     } // cluster loop
657
658     normalize_scores(rel);
659     
660     reclist_leave(reclist);
661     xfree(idfvec);
662
663 }
664
665 /*
666  * Local variables:
667  * c-basic-offset: 4
668  * c-file-style: "Stroustrup"
669  * indent-tabs-mode: nil
670  * End:
671  * vim: shiftwidth=4 tabstop=8 expandtab
672  */
673