1 /* This file is part of Pazpar2.
2 Copyright (C) 2006-2013 Index Data
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
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
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
28 #include "relevance.h"
34 #define log2(x) (log(x)/log(2))
39 int *doc_frequency_vec;
40 int *term_frequency_vec_tmp;
43 struct word_entry *entries;
44 pp2_charset_token_t prt;
50 struct norm_client *norm;
55 const char *display_str;
58 struct word_entry *next;
61 // Structure to keep data for norm_client scores from one client
64 int num; // number of the client
68 const char *native_score;
70 float a,b; // Rn = a*R + b
71 struct client *client;
72 struct norm_client *next;
73 struct norm_record *records;
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
81 // A structure for each (sub)record. There is one list for each client
84 struct record *record;
86 struct record_cluster *clust;
87 struct norm_record *next;
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)
93 struct norm_client *n = rel->norm;
94 struct session_database *sdb;
96 if (n->client == client )
100 n = nmem_malloc(rel->nmem, sizeof(struct norm_client) );
102 n->num = rel->norm->num +1;
111 sdb = client_get_database(client);
112 n->native_score = session_setting_oneval(sdb, PZ_NATIVE_SCORE);
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;
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);
127 yaz_log(YLOG_LOG,"Normalizing: Client %d uses '%s' = %d",
128 n->num, n->native_score, n->scorefield );
133 // Add all records from a cluster into the list for that client, for normalizing later
134 static void setup_norm_record( struct relevance *rel, struct record_cluster *clust)
136 struct record *record;
137 for (record = clust->records; record; record = record->next)
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) );
145 rp->next = norm->records;
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!
156 struct record_metadata *md = record->metadata[norm->scorefield];
157 rp->score = md->data.fnumber;
159 yaz_log(YLOG_LOG,"Got score for %d/%d : %f ",
160 norm->num, record->position, rp->score );
161 record -> score = rp->score;
162 if ( norm->count == 1 )
164 norm->max = rp->score;
165 norm->min = rp->score;
167 if ( rp->score > norm->max )
168 norm->max = rp->score;
169 if ( rp->score < norm->min )
170 norm->min = rp->score;
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)
180 for ( ; rp; rp = rp->next )
182 double target = 1.0 / rp->record->position;
183 double normscore = rp->score * a + b;
184 double diff = target - normscore;
190 // For each client, normalize scores
191 static void normalize_scores(struct relevance *rel)
193 const int maxiterations = 1000;
194 const double enough = 100.0; // sets the number of decimals we are happy with
195 const double stepchange = 0.5; // reduction of the step size when finding middle
196 // 0.5 sems to be magical, much better than 0.4 or 0.6
197 struct norm_client *norm;
198 for ( norm = rel->norm; norm; norm = norm->next )
200 yaz_log(YLOG_LOG,"Normalizing client %d: scorefield=%d count=%d range=%f %f = %f",
201 norm->num, norm->scorefield, norm->count, norm->min,
202 norm->max, norm->max-norm->min);
203 norm->a = 1.0; // default normalizing factors, no change
205 if ( norm->scorefield != scorefield_none &&
206 norm->scorefield != scorefield_position )
207 { // have something to normalize
208 double range = norm->max - norm->min;
210 double a,b; // params to optimize
211 double as,bs; // step sizes
214 // initial guesses for the parameters
215 // Rmax = a * rmax + b # want to be 1.0
216 // Rmin = a * rmin + b # want to be 0.0
217 // Rmax - Rmin = a ( rmax - rmin ) # subtracting equations
218 // 1.0 - 0.0 = a ( rmax - rmin )
220 // Rmin = a * rmin + b
221 // b = Rmin - a * rmin
222 // = 0.0 - 1/range * rmin
225 if ( range < 1e-6 ) // practically zero
228 b = -1.0 * norm->min / range;
229 // b = fabs(norm->min) / range;
232 chi = squaresum( norm->records, a,b);
233 yaz_log(YLOG_LOG,"Initial done: it=%d: a=%f / %f b=%f / %f chi = %f",
234 0, a, as, b, bs, chi );
235 while (it++ < maxiterations) // safeguard against things not converging
237 double aplus = squaresum(norm->records, a+as, b);
238 double aminus= squaresum(norm->records, a-as, b);
239 double bplus = squaresum(norm->records, a, b+bs);
240 double bminus= squaresum(norm->records, a, b-bs);
241 double prevchi = chi;
242 if ( aplus < chi && aplus < aminus && aplus < bplus && aplus < bminus)
246 as = as * (1.0 + stepchange);
249 else if ( aminus < chi && aminus < aplus && aminus < bplus && aminus < bminus)
253 as = as * (1.0 + stepchange);
256 else if ( bplus < chi && bplus < aplus && bplus < aminus && bplus < bminus)
260 bs = bs * (1.0 + stepchange);
263 else if ( bminus < chi && bminus < aplus && bminus < bplus && bminus < aminus)
268 bs = bs * (1.0+stepchange);
271 { // a,b is the best so far, adjust one step size
272 // which one? The one that has the greatest effect to chi
273 // That is, the average of plus and minus is further away from chi
274 double adif = 0.5 * ( aplus + aminus ) - prevchi;
275 double bdif = 0.5 * ( bplus + bminus ) - prevchi;
276 if ( fabs(adif) > fabs(bdif) )
278 as = as * ( 1.0 - stepchange);
283 bs = bs * ( 1.0 - stepchange);
287 yaz_log(YLOG_LOG,"Fitting %s it=%d: a=%g %g b=%g %g chi=%g ap=%g am=%g, bp=%g bm=%g p=%g",
288 branch, it, a, as, b, bs, chi,
289 aplus, aminus, bplus, bminus, prevchi );
292 if ( fabs(as) * enough < fabs(a) &&
293 fabs(bs) * enough < fabs(b) ) {
294 break; // not changing much any more
298 yaz_log(YLOG_LOG,"Fitting done: it=%d: a=%g / %g b=%g / %g chi = %g",
299 it-1, a, as, b, bs, chi );
302 if ( norm->scorefield != scorefield_none )
303 { // distribute the normalized scores to the records
304 struct norm_record *nr = norm->records;
305 for ( ; nr ; nr = nr->next ) {
306 double r = nr->score;
307 r = norm->a * r + norm -> b;
308 nr->clust->relevance_score = 10000 * r;
309 nr->record->score = r;
310 yaz_log(YLOG_LOG,"Normalized %f * %f + %f = %f",
311 nr->score, norm->a, norm->b, r );
312 // TODO - This keeps overwriting the cluster score in random order!
313 // Need to merge results better
320 static struct word_entry *word_entry_match(struct relevance *r,
321 const char *norm_str,
322 const char *rank, int *weight)
325 struct word_entry *entries = r->entries;
326 for (; entries; entries = entries->next, i++)
328 if (*norm_str && !strcmp(norm_str, entries->norm_str))
332 sscanf(rank, "%d%n", weight, &no_read);
336 if (no_read > 0 && (cp = strchr(rank, ' ')))
338 if ((cp - rank) == strlen(entries->ccl_field) &&
339 memcmp(entries->ccl_field, rank, cp - rank) == 0)
340 *weight = atoi(cp + 1);
348 int relevance_snippet(struct relevance *r,
349 const char *words, const char *name,
353 const char *norm_str;
356 pp2_charset_token_first(r->prt, words, 0);
357 while ((norm_str = pp2_charset_token_next(r->prt)))
359 size_t org_start, org_len;
360 struct word_entry *entries = r->entries;
363 pp2_get_org(r->prt, &org_start, &org_len);
364 for (; entries; entries = entries->next, i++)
366 if (*norm_str && !strcmp(norm_str, entries->norm_str))
374 wrbuf_puts(w_snippet, "<match>");
383 wrbuf_puts(w_snippet, "</match>");
386 wrbuf_xmlputs_n(w_snippet, words + org_start, org_len);
389 wrbuf_puts(w_snippet, "</match>");
392 yaz_log(YLOG_DEBUG, "SNIPPET match: %s", wrbuf_cstr(w_snippet));
397 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
398 const char *words, const char *rank,
401 int *w = r->term_frequency_vec_tmp;
402 const char *norm_str;
404 double lead_decay = r->lead_decay;
405 struct word_entry *e;
406 WRBUF wr = cluster->relevance_explain1;
407 int printed_about_field = 0;
409 pp2_charset_token_first(r->prt, words, 0);
410 for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
417 while ((norm_str = pp2_charset_token_next(r->prt)))
419 int local_weight = 0;
420 e = word_entry_match(r, norm_str, rank, &local_weight);
426 if (!printed_about_field)
428 printed_about_field = 1;
429 wrbuf_printf(wr, "field=%s content=", name);
430 if (strlen(words) > 50)
432 wrbuf_xmlputs_n(wr, words, 49);
433 wrbuf_puts(wr, " ...");
436 wrbuf_xmlputs(wr, words);
437 wrbuf_puts(wr, ";\n");
439 assert(res < r->vec_len);
440 w[res] += local_weight / (1 + log2(1 + lead_decay * length));
441 wrbuf_printf(wr, "%s: w[%d] += w(%d) / "
442 "(1+log2(1+lead_decay(%f) * length(%d)));\n",
443 e->display_str, res, local_weight, lead_decay, length);
445 if (j > 0 && r->term_pos[j])
447 int d = length + 1 - r->term_pos[j];
448 wrbuf_printf(wr, "%s: w[%d] += w[%d](%d) * follow(%f) / "
450 e->display_str, res, res, w[res],
451 r->follow_factor, d);
452 w[res] += w[res] * r->follow_factor / (1 + log2(d));
454 for (j = 0; j < r->vec_len; j++)
455 r->term_pos[j] = j < res ? 0 : length + 1;
460 for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
462 if (length == 0 || w[i] == 0)
464 wrbuf_printf(wr, "%s: tf[%d] += w[%d](%d)", e->display_str, i, i, w[i]);
465 switch (r->length_divide)
468 cluster->term_frequency_vecf[i] += (double) w[i];
471 wrbuf_printf(wr, " / log2(1+length(%d))", length);
472 cluster->term_frequency_vecf[i] +=
473 (double) w[i] / log2(1 + length);
476 wrbuf_printf(wr, " / length(%d)", length);
477 cluster->term_frequency_vecf[i] += (double) w[i] / length;
479 cluster->term_frequency_vec[i] += w[i];
480 wrbuf_printf(wr, " (%f);\n", cluster->term_frequency_vecf[i]);
483 cluster->term_frequency_vec[0] += length;
486 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
499 pull_terms(res, n->u.p[0]);
500 pull_terms(res, n->u.p[1]);
503 nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
504 for (i = 0; i < numwords; i++)
506 const char *norm_str;
508 ccl_field = nmem_strdup_null(res->nmem, n->u.t.qual);
510 pp2_charset_token_first(res->prt, words[i], 0);
511 while ((norm_str = pp2_charset_token_next(res->prt)))
513 struct word_entry **e = &res->entries;
516 *e = nmem_malloc(res->nmem, sizeof(**e));
517 (*e)->norm_str = nmem_strdup(res->nmem, norm_str);
518 (*e)->ccl_field = ccl_field;
519 (*e)->termno = res->vec_len++;
520 (*e)->display_str = nmem_strdup(res->nmem, words[i]);
529 void relevance_clear(struct relevance *r)
534 for (i = 0; i < r->vec_len; i++)
535 r->doc_frequency_vec[i] = 0;
539 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
540 struct ccl_rpn_node *query,
542 double follow_factor, double lead_decay,
545 NMEM nmem = nmem_create();
546 struct relevance *res = nmem_malloc(nmem, sizeof(*res));
551 res->rank_cluster = rank_cluster;
552 res->follow_factor = follow_factor;
553 res->lead_decay = lead_decay;
554 res->length_divide = length_divide;
556 res->prt = pp2_charset_token_create(pft, "relevance");
558 pull_terms(res, query);
560 res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
563 res->term_frequency_vec_tmp =
564 nmem_malloc(res->nmem,
565 res->vec_len * sizeof(*res->term_frequency_vec_tmp));
568 nmem_malloc(res->nmem, res->vec_len * sizeof(*res->term_pos));
570 relevance_clear(res);
574 void relevance_destroy(struct relevance **rp)
578 pp2_charset_token_destroy((*rp)->prt);
579 nmem_destroy((*rp)->nmem);
584 void relevance_mergerec(struct relevance *r, struct record_cluster *dst,
585 const struct record_cluster *src)
589 for (i = 0; i < r->vec_len; i++)
590 dst->term_frequency_vec[i] += src->term_frequency_vec[i];
592 for (i = 0; i < r->vec_len; i++)
593 dst->term_frequency_vecf[i] += src->term_frequency_vecf[i];
596 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
600 // term frequency [1,..] . [0] is total length of all fields
601 rec->term_frequency_vec =
603 r->vec_len * sizeof(*rec->term_frequency_vec));
604 for (i = 0; i < r->vec_len; i++)
605 rec->term_frequency_vec[i] = 0;
607 // term frequency divided by length of field [1,...]
608 rec->term_frequency_vecf =
610 r->vec_len * sizeof(*rec->term_frequency_vecf));
611 for (i = 0; i < r->vec_len; i++)
612 rec->term_frequency_vecf[i] = 0.0;
615 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
619 for (i = 1; i < r->vec_len; i++)
620 if (cluster->term_frequency_vec[i] > 0)
621 r->doc_frequency_vec[i]++;
623 r->doc_frequency_vec[0]++;
628 // Prepare for a relevance-sorted read
629 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
632 float *idfvec = xmalloc(rel->vec_len * sizeof(float));
634 reclist_enter(reclist);
636 // Calculate document frequency vector for each term.
637 for (i = 1; i < rel->vec_len; i++)
639 if (!rel->doc_frequency_vec[i])
643 /* add one to nominator idf(t,D) to ensure a value > 0 */
644 idfvec[i] = log((float) (1 + rel->doc_frequency_vec[0]) /
645 rel->doc_frequency_vec[i]);
648 // Calculate relevance for each document (cluster)
653 struct word_entry *e = rel->entries;
654 struct record_cluster *rec = reclist_read_record(reclist);
657 w = rec->relevance_explain2;
659 wrbuf_puts(w, "relevance = 0;\n");
660 for (i = 1; i < rel->vec_len; i++)
662 float termfreq = (float) rec->term_frequency_vecf[i];
663 int add = 100000 * termfreq * idfvec[i];
665 wrbuf_printf(w, "idf[%d] = log(((1 + total(%d))/termoccur(%d));\n",
666 i, rel->doc_frequency_vec[0],
667 rel->doc_frequency_vec[i]);
668 wrbuf_printf(w, "%s: relevance += 100000 * tf[%d](%f) * "
669 "idf[%d](%f) (%d);\n",
670 e->display_str, i, termfreq, i, idfvec[i], add);
674 if (!rel->rank_cluster)
676 struct record *record;
677 int cluster_size = 0;
679 for (record = rec->records; record; record = record->next)
682 wrbuf_printf(w, "score = relevance(%d)/cluster_size(%d);\n",
683 relevance, cluster_size);
684 relevance /= cluster_size;
688 wrbuf_printf(w, "score = relevance(%d);\n", relevance);
690 rec->relevance_score = relevance;
692 // Build the normalizing structures
693 // List of (sub)records for each target
694 setup_norm_record( rel, rec );
698 normalize_scores(rel);
700 // TODO - Calculate the cluster scores from individual records
701 // At the moment the record scoring puts one of them in the cluster...
702 reclist_rewind(reclist);
704 reclist_leave(reclist);
712 * c-file-style: "Stroustrup"
713 * indent-tabs-mode: nil
715 * vim: shiftwidth=4 tabstop=8 expandtab