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 a record in 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;
158 assert(rp->score>0); // ###
160 yaz_log(YLOG_LOG,"Got score for %d/%d : %f ",
161 norm->num, record->position, 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 && abs(rp->score) < 1e-6 )
170 norm->min = rp->score; // skip zeroes
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 static void normalize_scores(struct relevance *rel)
192 // For each client, normalize scores
193 struct norm_client *norm;
194 for ( norm = rel->norm; norm; norm = norm->next )
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
200 if ( norm->scorefield != scorefield_none &&
201 norm->scorefield != scorefield_position )
202 { // have something to normalize
203 double range = norm->max - norm->min;
205 double a,b; // params to optimize
206 double as,bs; // step sizes
208 // initial guesses for the parameters
209 if ( range < 1e-6 ) // practically zero
215 chi = squaresum( norm->records, a,b);
216 while (it++ < 100) // safeguard against things not converging
219 double plus = squaresum(norm->records, a+as, b);
220 double minus= squaresum(norm->records, a-as, b);
221 if ( plus < chi && plus < minus )
226 else if ( minus < chi && minus < plus )
234 plus = squaresum(norm->records, a, b+bs);
235 minus= squaresum(norm->records, a, b-bs);
236 if ( plus < chi && plus < minus )
241 else if ( minus < chi && minus < plus )
248 yaz_log(YLOG_LOG,"Fitting it=%d: a=%f / %f b=%f / %f chi = %f",
249 it, a, as, b, bs, chi );
252 if ( abs(as) * 1000.0 < abs(a) &&
253 abs(bs) * 1000.0 < abs(b) )
254 break; // not changing much any more
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
277 static struct word_entry *word_entry_match(struct relevance *r,
278 const char *norm_str,
279 const char *rank, int *weight)
282 struct word_entry *entries = r->entries;
283 for (; entries; entries = entries->next, i++)
285 if (*norm_str && !strcmp(norm_str, entries->norm_str))
289 sscanf(rank, "%d%n", weight, &no_read);
293 if (no_read > 0 && (cp = strchr(rank, ' ')))
295 if ((cp - rank) == strlen(entries->ccl_field) &&
296 memcmp(entries->ccl_field, rank, cp - rank) == 0)
297 *weight = atoi(cp + 1);
305 int relevance_snippet(struct relevance *r,
306 const char *words, const char *name,
310 const char *norm_str;
313 pp2_charset_token_first(r->prt, words, 0);
314 while ((norm_str = pp2_charset_token_next(r->prt)))
316 size_t org_start, org_len;
317 struct word_entry *entries = r->entries;
320 pp2_get_org(r->prt, &org_start, &org_len);
321 for (; entries; entries = entries->next, i++)
323 if (*norm_str && !strcmp(norm_str, entries->norm_str))
331 wrbuf_puts(w_snippet, "<match>");
340 wrbuf_puts(w_snippet, "</match>");
343 wrbuf_xmlputs_n(w_snippet, words + org_start, org_len);
346 wrbuf_puts(w_snippet, "</match>");
349 yaz_log(YLOG_DEBUG, "SNIPPET match: %s", wrbuf_cstr(w_snippet));
354 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
355 const char *words, const char *rank,
358 int *w = r->term_frequency_vec_tmp;
359 const char *norm_str;
361 double lead_decay = r->lead_decay;
362 struct word_entry *e;
363 WRBUF wr = cluster->relevance_explain1;
364 int printed_about_field = 0;
366 pp2_charset_token_first(r->prt, words, 0);
367 for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
374 while ((norm_str = pp2_charset_token_next(r->prt)))
376 int local_weight = 0;
377 e = word_entry_match(r, norm_str, rank, &local_weight);
383 if (!printed_about_field)
385 printed_about_field = 1;
386 wrbuf_printf(wr, "field=%s content=", name);
387 if (strlen(words) > 50)
389 wrbuf_xmlputs_n(wr, words, 49);
390 wrbuf_puts(wr, " ...");
393 wrbuf_xmlputs(wr, words);
394 wrbuf_puts(wr, ";\n");
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);
402 if (j > 0 && r->term_pos[j])
404 int d = length + 1 - r->term_pos[j];
405 wrbuf_printf(wr, "%s: w[%d] += w[%d](%d) * follow(%f) / "
407 e->display_str, res, res, w[res],
408 r->follow_factor, d);
409 w[res] += w[res] * r->follow_factor / (1 + log2(d));
411 for (j = 0; j < r->vec_len; j++)
412 r->term_pos[j] = j < res ? 0 : length + 1;
417 for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
419 if (length == 0 || w[i] == 0)
421 wrbuf_printf(wr, "%s: tf[%d] += w[%d](%d)", e->display_str, i, i, w[i]);
422 switch (r->length_divide)
425 cluster->term_frequency_vecf[i] += (double) w[i];
428 wrbuf_printf(wr, " / log2(1+length(%d))", length);
429 cluster->term_frequency_vecf[i] +=
430 (double) w[i] / log2(1 + length);
433 wrbuf_printf(wr, " / length(%d)", length);
434 cluster->term_frequency_vecf[i] += (double) w[i] / length;
436 cluster->term_frequency_vec[i] += w[i];
437 wrbuf_printf(wr, " (%f);\n", cluster->term_frequency_vecf[i]);
440 cluster->term_frequency_vec[0] += length;
443 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
456 pull_terms(res, n->u.p[0]);
457 pull_terms(res, n->u.p[1]);
460 nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
461 for (i = 0; i < numwords; i++)
463 const char *norm_str;
465 ccl_field = nmem_strdup_null(res->nmem, n->u.t.qual);
467 pp2_charset_token_first(res->prt, words[i], 0);
468 while ((norm_str = pp2_charset_token_next(res->prt)))
470 struct word_entry **e = &res->entries;
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]);
486 void relevance_clear(struct relevance *r)
491 for (i = 0; i < r->vec_len; i++)
492 r->doc_frequency_vec[i] = 0;
496 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
497 struct ccl_rpn_node *query,
499 double follow_factor, double lead_decay,
502 NMEM nmem = nmem_create();
503 struct relevance *res = nmem_malloc(nmem, sizeof(*res));
508 res->rank_cluster = rank_cluster;
509 res->follow_factor = follow_factor;
510 res->lead_decay = lead_decay;
511 res->length_divide = length_divide;
513 res->prt = pp2_charset_token_create(pft, "relevance");
515 pull_terms(res, query);
517 res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
520 res->term_frequency_vec_tmp =
521 nmem_malloc(res->nmem,
522 res->vec_len * sizeof(*res->term_frequency_vec_tmp));
525 nmem_malloc(res->nmem, res->vec_len * sizeof(*res->term_pos));
527 relevance_clear(res);
531 void relevance_destroy(struct relevance **rp)
535 pp2_charset_token_destroy((*rp)->prt);
536 nmem_destroy((*rp)->nmem);
541 void relevance_mergerec(struct relevance *r, struct record_cluster *dst,
542 const struct record_cluster *src)
546 for (i = 0; i < r->vec_len; i++)
547 dst->term_frequency_vec[i] += src->term_frequency_vec[i];
549 for (i = 0; i < r->vec_len; i++)
550 dst->term_frequency_vecf[i] += src->term_frequency_vecf[i];
553 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
557 // term frequency [1,..] . [0] is total length of all fields
558 rec->term_frequency_vec =
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;
564 // term frequency divided by length of field [1,...]
565 rec->term_frequency_vecf =
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;
572 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
576 for (i = 1; i < r->vec_len; i++)
577 if (cluster->term_frequency_vec[i] > 0)
578 r->doc_frequency_vec[i]++;
580 r->doc_frequency_vec[0]++;
585 // Prepare for a relevance-sorted read
586 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
589 float *idfvec = xmalloc(rel->vec_len * sizeof(float));
591 reclist_enter(reclist);
593 // Calculate document frequency vector for each term.
594 for (i = 1; i < rel->vec_len; i++)
596 if (!rel->doc_frequency_vec[i])
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]);
605 // Calculate relevance for each document
610 struct word_entry *e = rel->entries;
611 struct record_cluster *rec = reclist_read_record(reclist);
614 w = rec->relevance_explain2;
616 wrbuf_puts(w, "relevance = 0;\n");
617 for (i = 1; i < rel->vec_len; i++)
619 float termfreq = (float) rec->term_frequency_vecf[i];
620 int add = 100000 * termfreq * idfvec[i];
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);
631 if (!rel->rank_cluster)
633 struct record *record;
634 int cluster_size = 0;
636 for (record = rec->records; record; record = record->next)
639 wrbuf_printf(w, "score = relevance(%d)/cluster_size(%d);\n",
640 relevance, cluster_size);
641 relevance /= cluster_size;
645 wrbuf_printf(w, "score = relevance(%d);\n", relevance);
647 rec->relevance_score = relevance;
649 // Build the normalizing structures
650 // List of (sub)records for each target
651 setup_norm_record( rel, rec );
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?
658 normalize_scores(rel);
660 reclist_leave(reclist);
668 * c-file-style: "Stroustrup"
669 * indent-tabs-mode: nil
671 * vim: shiftwidth=4 tabstop=8 expandtab