Curve fitting that converges somewhat better
[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         }
159         yaz_log(YLOG_LOG,"Got score for %d/%d : %f ",
160                 norm->num, record->position, rp->score );
161         if ( norm->count == 1 )
162         {
163             norm->max = rp->score;
164             norm->min = rp->score;
165         } else {
166             if ( rp->score > norm->max )
167                 norm->max = rp->score;
168             if ( rp->score < norm->min && abs(rp->score) < 1e-6 )
169                 norm->min = rp->score;  // skip zeroes
170         }
171     }
172 }
173
174 // Calculate the squared sum of residuals, that is the difference from
175 // normalized values to the target curve, which is 1/n 
176 static double squaresum( struct norm_record *rp, double a, double b)
177 {
178     double sum = 0.0;
179     for ( ; rp; rp = rp->next )
180     {
181         double target = 1.0 / rp->record->position;
182         double normscore = rp->score * a + b;
183         double diff = target - normscore;
184         sum += diff * diff;
185     }
186     return sum;
187 }
188
189 // For each client, normalize scores
190 static void normalize_scores(struct relevance *rel)
191 {
192     const int maxiterations = 100;
193     const double enough = 100.0;  // sets the number of decimals we are happy with
194     struct norm_client *norm;
195     for ( norm = rel->norm; norm; norm = norm->next )
196     {
197         yaz_log(YLOG_LOG,"Normalizing client %d: scorefield=%d count=%d",
198                 norm->num, norm->scorefield, norm->count);
199         norm->a = 1.0; // default normalizing factors, no change
200         norm->b = 0.0;
201         if ( norm->scorefield != scorefield_none &&
202              norm->scorefield != scorefield_position )
203         { // have something to normalize
204             double range = norm->max - norm->min;
205             int it = 0;
206             double a,b;  // params to optimize
207             double as,bs; // step sizes
208             double chi;
209             char dir = 'a';
210             // initial guesses for the parameters
211             if ( range < 1e-6 ) // practically zero
212                 range = norm->max;
213             a = 1.0 / range;
214             b = abs(norm->min);
215             as = a / 10;
216             bs = b / 10;
217             chi = squaresum( norm->records, a,b);
218             while (it++ < maxiterations)  // safeguard against things not converging
219             {
220                 double aplus = squaresum(norm->records, a+as, b);
221                 double aminus= squaresum(norm->records, a-as, b);
222                 double bplus = squaresum(norm->records, a, b+bs);
223                 double bminus= squaresum(norm->records, a, b-bs);
224                 if ( aplus < chi && aplus < aminus && aplus < bplus && aplus < bminus)
225                 {
226                     a = a + as;
227                     chi = aplus;
228                     yaz_log(YLOG_LOG,"Fitting aplus it=%d: a=%f / %f  b=%f / %f  chi = %f",
229                         it, a, as, b, bs, chi );
230                 }
231                 else if ( aminus < chi && aminus < aplus && aminus < bplus && aminus < bminus)
232                 {
233                     a = a - as;
234                     chi = aminus;
235                     yaz_log(YLOG_LOG,"Fitting aminus it=%d: a=%f / %f  b=%f / %f  chi = %f",
236                         it, a, as, b, bs, chi );
237                 }
238                 else if ( bplus < chi && bplus < aplus && bplus < aminus && bplus < bminus)
239                 {
240                     b = b + bs;
241                     chi = bplus;
242                     yaz_log(YLOG_LOG,"Fitting bplus it=%d: a=%f / %f  b=%f / %f  chi = %f",
243                         it, a, as, b, bs, chi );
244                 }
245                 else if ( bminus < chi && bminus < aplus && bminus < bplus && bminus < aminus)
246                 {
247                     b = b - bs;
248                     chi = bminus;
249                     yaz_log(YLOG_LOG,"Fitting bminus it=%d: a=%f / %f  b=%f / %f  chi = %f",
250                         it, a, as, b, bs, chi );
251                 }
252                 else
253                 {
254                     if ( as > bs )
255                     {
256                         as = as / 2;
257                         yaz_log(YLOG_LOG,"Fitting step a it=%d: a=%f / %f  b=%f / %f  chi = %f",
258                             it, a, as, b, bs, chi );
259                     }
260                     else
261                     {
262                         bs = bs / 2;
263                         yaz_log(YLOG_LOG,"Fitting step b it=%d: a=%f / %f  b=%f / %f  chi = %f",
264                             it, a, as, b, bs, chi );
265                     }
266                 }
267                 norm->a = a;
268                 norm->b = b;
269                 if ( fabs(as) * enough < fabs(a) &&
270                      fabs(bs) * enough < fabs(b) ) {
271                     yaz_log(YLOG_LOG,"Fitting done: stopping loop at %d" , it );
272                     break;  // not changing much any more
273
274                 }
275             }
276             yaz_log(YLOG_LOG,"Fitting done: it=%d: a=%f / %f  b=%f / %f  chi = %f",
277                         it-1, a, as, b, bs, chi );
278             yaz_log(YLOG_LOG,"  a: %f < %f %d",
279                     fabs(as)*enough, fabs(a), (fabs(as) * enough < fabs(a)) );
280             yaz_log(YLOG_LOG,"  b: %f < %f %d",
281                     fabs(bs)*enough, fabs(b), (fabs(bs) * enough < fabs(b)) );
282         }
283
284         if ( norm->scorefield != scorefield_none )
285         { // distribute the normalized scores to the records
286             struct norm_record *nr = norm->records;
287             for ( ; nr ; nr = nr->next ) {
288                 double r = nr->score;
289                 r = norm->a * r + norm -> b;
290                 nr->clust->relevance_score = 10000 * r;
291                 yaz_log(YLOG_LOG,"Normalized %f * %f + %f = %f",
292                         nr->score, norm->a, norm->b, r );
293                 // TODO - This keeps overwriting the cluster score in random order!
294                 // Need to merge results better
295             }
296
297         }
298
299     } // client loop
300 }
301
302
303 static struct word_entry *word_entry_match(struct relevance *r,
304                                            const char *norm_str,
305                                            const char *rank, int *weight)
306 {
307     int i = 1;
308     struct word_entry *entries = r->entries;
309     for (; entries; entries = entries->next, i++)
310     {
311         if (*norm_str && !strcmp(norm_str, entries->norm_str))
312         {
313             const char *cp = 0;
314             int no_read = 0;
315             sscanf(rank, "%d%n", weight, &no_read);
316             rank += no_read;
317             while (*rank == ' ')
318                 rank++;
319             if (no_read > 0 && (cp = strchr(rank, ' ')))
320             {
321                 if ((cp - rank) == strlen(entries->ccl_field) &&
322                     memcmp(entries->ccl_field, rank, cp - rank) == 0)
323                     *weight = atoi(cp + 1);
324             }
325             return entries;
326         }
327     }
328     return 0;
329 }
330
331 int relevance_snippet(struct relevance *r,
332                       const char *words, const char *name,
333                       WRBUF w_snippet)
334 {
335     int no = 0;
336     const char *norm_str;
337     int highlight = 0;
338
339     pp2_charset_token_first(r->prt, words, 0);
340     while ((norm_str = pp2_charset_token_next(r->prt)))
341     {
342         size_t org_start, org_len;
343         struct word_entry *entries = r->entries;
344         int i;
345
346         pp2_get_org(r->prt, &org_start, &org_len);
347         for (; entries; entries = entries->next, i++)
348         {
349             if (*norm_str && !strcmp(norm_str, entries->norm_str))
350                 break;
351         }
352         if (entries)
353         {
354             if (!highlight)
355             {
356                 highlight = 1;
357                 wrbuf_puts(w_snippet, "<match>");
358                 no++;
359             }
360         }
361         else
362         {
363             if (highlight)
364             {
365                 highlight = 0;
366                 wrbuf_puts(w_snippet, "</match>");
367             }
368         }
369         wrbuf_xmlputs_n(w_snippet, words + org_start, org_len);
370     }
371     if (highlight)
372         wrbuf_puts(w_snippet, "</match>");
373     if (no)
374     {
375         yaz_log(YLOG_DEBUG, "SNIPPET match: %s", wrbuf_cstr(w_snippet));
376     }
377     return no;
378 }
379
380 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
381                           const char *words, const char *rank,
382                           const char *name)
383 {
384     int *w = r->term_frequency_vec_tmp;
385     const char *norm_str;
386     int i, length = 0;
387     double lead_decay = r->lead_decay;
388     struct word_entry *e;
389     WRBUF wr = cluster->relevance_explain1;
390     int printed_about_field = 0;
391
392     pp2_charset_token_first(r->prt, words, 0);
393     for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
394     {
395         w[i] = 0;
396         r->term_pos[i] = 0;
397     }
398
399     assert(rank);
400     while ((norm_str = pp2_charset_token_next(r->prt)))
401     {
402         int local_weight = 0;
403         e = word_entry_match(r, norm_str, rank, &local_weight);
404         if (e)
405         {
406             int res = e->termno;
407             int j;
408
409             if (!printed_about_field)
410             {
411                 printed_about_field = 1;
412                 wrbuf_printf(wr, "field=%s content=", name);
413                 if (strlen(words) > 50)
414                 {
415                     wrbuf_xmlputs_n(wr, words, 49);
416                     wrbuf_puts(wr, " ...");
417                 }
418                 else
419                     wrbuf_xmlputs(wr, words);
420                 wrbuf_puts(wr, ";\n");
421             }
422             assert(res < r->vec_len);
423             w[res] += local_weight / (1 + log2(1 + lead_decay * length));
424             wrbuf_printf(wr, "%s: w[%d] += w(%d) / "
425                          "(1+log2(1+lead_decay(%f) * length(%d)));\n",
426                          e->display_str, res, local_weight, lead_decay, length);
427             j = res - 1;
428             if (j > 0 && r->term_pos[j])
429             {
430                 int d = length + 1 - r->term_pos[j];
431                 wrbuf_printf(wr, "%s: w[%d] += w[%d](%d) * follow(%f) / "
432                              "(1+log2(d(%d));\n",
433                              e->display_str, res, res, w[res],
434                              r->follow_factor, d);
435                 w[res] += w[res] * r->follow_factor / (1 + log2(d));
436             }
437             for (j = 0; j < r->vec_len; j++)
438                 r->term_pos[j] = j < res ? 0 : length + 1;
439         }
440         length++;
441     }
442
443     for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
444     {
445         if (length == 0 || w[i] == 0)
446             continue;
447         wrbuf_printf(wr, "%s: tf[%d] += w[%d](%d)", e->display_str, i, i, w[i]);
448         switch (r->length_divide)
449         {
450         case 0:
451             cluster->term_frequency_vecf[i] += (double) w[i];
452             break;
453         case 1:
454             wrbuf_printf(wr, " / log2(1+length(%d))", length);
455             cluster->term_frequency_vecf[i] +=
456                 (double) w[i] / log2(1 + length);
457             break;
458         case 2:
459             wrbuf_printf(wr, " / length(%d)", length);
460             cluster->term_frequency_vecf[i] += (double) w[i] / length;
461         }
462         cluster->term_frequency_vec[i] += w[i];
463         wrbuf_printf(wr, " (%f);\n", cluster->term_frequency_vecf[i]);
464     }
465
466     cluster->term_frequency_vec[0] += length;
467 }
468
469 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
470 {
471     char **words;
472     int numwords;
473     char *ccl_field;
474     int i;
475
476     switch (n->kind)
477     {
478     case CCL_RPN_AND:
479     case CCL_RPN_OR:
480     case CCL_RPN_NOT:
481     case CCL_RPN_PROX:
482         pull_terms(res, n->u.p[0]);
483         pull_terms(res, n->u.p[1]);
484         break;
485     case CCL_RPN_TERM:
486         nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
487         for (i = 0; i < numwords; i++)
488         {
489             const char *norm_str;
490
491             ccl_field = nmem_strdup_null(res->nmem, n->u.t.qual);
492
493             pp2_charset_token_first(res->prt, words[i], 0);
494             while ((norm_str = pp2_charset_token_next(res->prt)))
495             {
496                 struct word_entry **e = &res->entries;
497                 while (*e)
498                     e = &(*e)->next;
499                 *e = nmem_malloc(res->nmem, sizeof(**e));
500                 (*e)->norm_str = nmem_strdup(res->nmem, norm_str);
501                 (*e)->ccl_field = ccl_field;
502                 (*e)->termno = res->vec_len++;
503                 (*e)->display_str = nmem_strdup(res->nmem, words[i]);
504                 (*e)->next = 0;
505             }
506         }
507         break;
508     default:
509         break;
510     }
511 }
512 void relevance_clear(struct relevance *r)
513 {
514     if (r)
515     {
516         int i;
517         for (i = 0; i < r->vec_len; i++)
518             r->doc_frequency_vec[i] = 0;
519     }
520 }
521
522 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
523                                        struct ccl_rpn_node *query,
524                                        int rank_cluster,
525                                        double follow_factor, double lead_decay,
526                                        int length_divide)
527 {
528     NMEM nmem = nmem_create();
529     struct relevance *res = nmem_malloc(nmem, sizeof(*res));
530
531     res->nmem = nmem;
532     res->entries = 0;
533     res->vec_len = 1;
534     res->rank_cluster = rank_cluster;
535     res->follow_factor = follow_factor;
536     res->lead_decay = lead_decay;
537     res->length_divide = length_divide;
538     res->norm = 0;
539     res->prt = pp2_charset_token_create(pft, "relevance");
540
541     pull_terms(res, query);
542
543     res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
544
545     // worker array
546     res->term_frequency_vec_tmp =
547         nmem_malloc(res->nmem,
548                     res->vec_len * sizeof(*res->term_frequency_vec_tmp));
549
550     res->term_pos =
551         nmem_malloc(res->nmem, res->vec_len * sizeof(*res->term_pos));
552
553     relevance_clear(res);
554     return res;
555 }
556
557 void relevance_destroy(struct relevance **rp)
558 {
559     if (*rp)
560     {
561         pp2_charset_token_destroy((*rp)->prt);
562         nmem_destroy((*rp)->nmem);
563         *rp = 0;
564     }
565 }
566
567 void relevance_mergerec(struct relevance *r, struct record_cluster *dst,
568                         const struct record_cluster *src)
569 {
570     int i;
571
572     for (i = 0; i < r->vec_len; i++)
573         dst->term_frequency_vec[i] += src->term_frequency_vec[i];
574
575     for (i = 0; i < r->vec_len; i++)
576         dst->term_frequency_vecf[i] += src->term_frequency_vecf[i];
577 }
578
579 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
580 {
581     int i;
582
583     // term frequency [1,..] . [0] is total length of all fields
584     rec->term_frequency_vec =
585         nmem_malloc(r->nmem,
586                     r->vec_len * sizeof(*rec->term_frequency_vec));
587     for (i = 0; i < r->vec_len; i++)
588         rec->term_frequency_vec[i] = 0;
589
590     // term frequency divided by length of field [1,...]
591     rec->term_frequency_vecf =
592         nmem_malloc(r->nmem,
593                     r->vec_len * sizeof(*rec->term_frequency_vecf));
594     for (i = 0; i < r->vec_len; i++)
595         rec->term_frequency_vecf[i] = 0.0;
596 }
597
598 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
599 {
600     int i;
601
602     for (i = 1; i < r->vec_len; i++)
603         if (cluster->term_frequency_vec[i] > 0)
604             r->doc_frequency_vec[i]++;
605
606     r->doc_frequency_vec[0]++;
607 }
608
609
610
611 // Prepare for a relevance-sorted read
612 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
613 {
614     int i;
615     float *idfvec = xmalloc(rel->vec_len * sizeof(float));
616
617     reclist_enter(reclist);
618
619     // Calculate document frequency vector for each term.
620     for (i = 1; i < rel->vec_len; i++)
621     {
622         if (!rel->doc_frequency_vec[i])
623             idfvec[i] = 0;
624         else
625         {
626             /* add one to nominator idf(t,D) to ensure a value > 0 */
627             idfvec[i] = log((float) (1 + rel->doc_frequency_vec[0]) /
628                             rel->doc_frequency_vec[i]);
629         }
630     }
631     // Calculate relevance for each document
632     while (1)
633     {
634         int relevance = 0;
635         WRBUF w;
636         struct word_entry *e = rel->entries;
637         struct record_cluster *rec = reclist_read_record(reclist);
638         if (!rec)
639             break;
640         w = rec->relevance_explain2;
641         wrbuf_rewind(w);
642         wrbuf_puts(w, "relevance = 0;\n");
643         for (i = 1; i < rel->vec_len; i++)
644         {
645             float termfreq = (float) rec->term_frequency_vecf[i];
646             int add = 100000 * termfreq * idfvec[i];
647
648             wrbuf_printf(w, "idf[%d] = log(((1 + total(%d))/termoccur(%d));\n",
649                          i, rel->doc_frequency_vec[0],
650                          rel->doc_frequency_vec[i]);
651             wrbuf_printf(w, "%s: relevance += 100000 * tf[%d](%f) * "
652                          "idf[%d](%f) (%d);\n",
653                          e->display_str, i, termfreq, i, idfvec[i], add);
654             relevance += add;
655             e = e->next;
656         }
657         if (!rel->rank_cluster)
658         {
659             struct record *record;
660             int cluster_size = 0;
661
662             for (record = rec->records; record; record = record->next)
663                 cluster_size++;
664
665             wrbuf_printf(w, "score = relevance(%d)/cluster_size(%d);\n",
666                          relevance, cluster_size);
667             relevance /= cluster_size;
668         }
669         else
670         {
671             wrbuf_printf(w, "score = relevance(%d);\n", relevance);
672         }
673         rec->relevance_score = relevance;
674
675         // Build the normalizing structures
676         // List of (sub)records for each target
677         setup_norm_record( rel, rec );
678         
679         // TODO - Loop again, merge individual record scores into clusters
680         // Can I reset the reclist, or can I leave and enter without race conditions?
681         
682     } // cluster loop
683
684     normalize_scores(rel);
685     
686     reclist_leave(reclist);
687     xfree(idfvec);
688
689 }
690
691 /*
692  * Local variables:
693  * c-basic-offset: 4
694  * c-file-style: "Stroustrup"
695  * indent-tabs-mode: nil
696  * End:
697  * vim: shiftwidth=4 tabstop=8 expandtab
698  */
699