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;
159 yaz_log(YLOG_LOG,"Got score for %d/%d : %f ",
160 norm->num, record->position, rp->score );
161 if ( norm->count == 1 )
163 norm->max = rp->score;
164 norm->min = rp->score;
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
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)
179 for ( ; rp; rp = rp->next )
181 double target = 1.0 / rp->record->position;
182 double normscore = rp->score * a + b;
183 double diff = target - normscore;
189 // For each client, normalize scores
190 static void normalize_scores(struct relevance *rel)
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 )
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
201 if ( norm->scorefield != scorefield_none &&
202 norm->scorefield != scorefield_position )
203 { // have something to normalize
204 double range = norm->max - norm->min;
206 double a,b; // params to optimize
207 double as,bs; // step sizes
210 // initial guesses for the parameters
211 if ( range < 1e-6 ) // practically zero
217 chi = squaresum( norm->records, a,b);
218 while (it++ < maxiterations) // safeguard against things not converging
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)
228 yaz_log(YLOG_LOG,"Fitting aplus it=%d: a=%f / %f b=%f / %f chi = %f",
229 it, a, as, b, bs, chi );
231 else if ( aminus < chi && aminus < aplus && aminus < bplus && aminus < bminus)
235 yaz_log(YLOG_LOG,"Fitting aminus it=%d: a=%f / %f b=%f / %f chi = %f",
236 it, a, as, b, bs, chi );
238 else if ( bplus < chi && bplus < aplus && bplus < aminus && bplus < bminus)
242 yaz_log(YLOG_LOG,"Fitting bplus it=%d: a=%f / %f b=%f / %f chi = %f",
243 it, a, as, b, bs, chi );
245 else if ( bminus < chi && bminus < aplus && bminus < bplus && bminus < aminus)
249 yaz_log(YLOG_LOG,"Fitting bminus it=%d: a=%f / %f b=%f / %f chi = %f",
250 it, a, as, b, bs, chi );
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 );
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 );
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
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)) );
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
303 static struct word_entry *word_entry_match(struct relevance *r,
304 const char *norm_str,
305 const char *rank, int *weight)
308 struct word_entry *entries = r->entries;
309 for (; entries; entries = entries->next, i++)
311 if (*norm_str && !strcmp(norm_str, entries->norm_str))
315 sscanf(rank, "%d%n", weight, &no_read);
319 if (no_read > 0 && (cp = strchr(rank, ' ')))
321 if ((cp - rank) == strlen(entries->ccl_field) &&
322 memcmp(entries->ccl_field, rank, cp - rank) == 0)
323 *weight = atoi(cp + 1);
331 int relevance_snippet(struct relevance *r,
332 const char *words, const char *name,
336 const char *norm_str;
339 pp2_charset_token_first(r->prt, words, 0);
340 while ((norm_str = pp2_charset_token_next(r->prt)))
342 size_t org_start, org_len;
343 struct word_entry *entries = r->entries;
346 pp2_get_org(r->prt, &org_start, &org_len);
347 for (; entries; entries = entries->next, i++)
349 if (*norm_str && !strcmp(norm_str, entries->norm_str))
357 wrbuf_puts(w_snippet, "<match>");
366 wrbuf_puts(w_snippet, "</match>");
369 wrbuf_xmlputs_n(w_snippet, words + org_start, org_len);
372 wrbuf_puts(w_snippet, "</match>");
375 yaz_log(YLOG_DEBUG, "SNIPPET match: %s", wrbuf_cstr(w_snippet));
380 void relevance_countwords(struct relevance *r, struct record_cluster *cluster,
381 const char *words, const char *rank,
384 int *w = r->term_frequency_vec_tmp;
385 const char *norm_str;
387 double lead_decay = r->lead_decay;
388 struct word_entry *e;
389 WRBUF wr = cluster->relevance_explain1;
390 int printed_about_field = 0;
392 pp2_charset_token_first(r->prt, words, 0);
393 for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
400 while ((norm_str = pp2_charset_token_next(r->prt)))
402 int local_weight = 0;
403 e = word_entry_match(r, norm_str, rank, &local_weight);
409 if (!printed_about_field)
411 printed_about_field = 1;
412 wrbuf_printf(wr, "field=%s content=", name);
413 if (strlen(words) > 50)
415 wrbuf_xmlputs_n(wr, words, 49);
416 wrbuf_puts(wr, " ...");
419 wrbuf_xmlputs(wr, words);
420 wrbuf_puts(wr, ";\n");
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);
428 if (j > 0 && r->term_pos[j])
430 int d = length + 1 - r->term_pos[j];
431 wrbuf_printf(wr, "%s: w[%d] += w[%d](%d) * follow(%f) / "
433 e->display_str, res, res, w[res],
434 r->follow_factor, d);
435 w[res] += w[res] * r->follow_factor / (1 + log2(d));
437 for (j = 0; j < r->vec_len; j++)
438 r->term_pos[j] = j < res ? 0 : length + 1;
443 for (e = r->entries, i = 1; i < r->vec_len; i++, e = e->next)
445 if (length == 0 || w[i] == 0)
447 wrbuf_printf(wr, "%s: tf[%d] += w[%d](%d)", e->display_str, i, i, w[i]);
448 switch (r->length_divide)
451 cluster->term_frequency_vecf[i] += (double) w[i];
454 wrbuf_printf(wr, " / log2(1+length(%d))", length);
455 cluster->term_frequency_vecf[i] +=
456 (double) w[i] / log2(1 + length);
459 wrbuf_printf(wr, " / length(%d)", length);
460 cluster->term_frequency_vecf[i] += (double) w[i] / length;
462 cluster->term_frequency_vec[i] += w[i];
463 wrbuf_printf(wr, " (%f);\n", cluster->term_frequency_vecf[i]);
466 cluster->term_frequency_vec[0] += length;
469 static void pull_terms(struct relevance *res, struct ccl_rpn_node *n)
482 pull_terms(res, n->u.p[0]);
483 pull_terms(res, n->u.p[1]);
486 nmem_strsplit(res->nmem, " ", n->u.t.term, &words, &numwords);
487 for (i = 0; i < numwords; i++)
489 const char *norm_str;
491 ccl_field = nmem_strdup_null(res->nmem, n->u.t.qual);
493 pp2_charset_token_first(res->prt, words[i], 0);
494 while ((norm_str = pp2_charset_token_next(res->prt)))
496 struct word_entry **e = &res->entries;
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]);
512 void relevance_clear(struct relevance *r)
517 for (i = 0; i < r->vec_len; i++)
518 r->doc_frequency_vec[i] = 0;
522 struct relevance *relevance_create_ccl(pp2_charset_fact_t pft,
523 struct ccl_rpn_node *query,
525 double follow_factor, double lead_decay,
528 NMEM nmem = nmem_create();
529 struct relevance *res = nmem_malloc(nmem, sizeof(*res));
534 res->rank_cluster = rank_cluster;
535 res->follow_factor = follow_factor;
536 res->lead_decay = lead_decay;
537 res->length_divide = length_divide;
539 res->prt = pp2_charset_token_create(pft, "relevance");
541 pull_terms(res, query);
543 res->doc_frequency_vec = nmem_malloc(nmem, res->vec_len * sizeof(int));
546 res->term_frequency_vec_tmp =
547 nmem_malloc(res->nmem,
548 res->vec_len * sizeof(*res->term_frequency_vec_tmp));
551 nmem_malloc(res->nmem, res->vec_len * sizeof(*res->term_pos));
553 relevance_clear(res);
557 void relevance_destroy(struct relevance **rp)
561 pp2_charset_token_destroy((*rp)->prt);
562 nmem_destroy((*rp)->nmem);
567 void relevance_mergerec(struct relevance *r, struct record_cluster *dst,
568 const struct record_cluster *src)
572 for (i = 0; i < r->vec_len; i++)
573 dst->term_frequency_vec[i] += src->term_frequency_vec[i];
575 for (i = 0; i < r->vec_len; i++)
576 dst->term_frequency_vecf[i] += src->term_frequency_vecf[i];
579 void relevance_newrec(struct relevance *r, struct record_cluster *rec)
583 // term frequency [1,..] . [0] is total length of all fields
584 rec->term_frequency_vec =
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;
590 // term frequency divided by length of field [1,...]
591 rec->term_frequency_vecf =
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;
598 void relevance_donerecord(struct relevance *r, struct record_cluster *cluster)
602 for (i = 1; i < r->vec_len; i++)
603 if (cluster->term_frequency_vec[i] > 0)
604 r->doc_frequency_vec[i]++;
606 r->doc_frequency_vec[0]++;
611 // Prepare for a relevance-sorted read
612 void relevance_prepare_read(struct relevance *rel, struct reclist *reclist)
615 float *idfvec = xmalloc(rel->vec_len * sizeof(float));
617 reclist_enter(reclist);
619 // Calculate document frequency vector for each term.
620 for (i = 1; i < rel->vec_len; i++)
622 if (!rel->doc_frequency_vec[i])
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]);
631 // Calculate relevance for each document
636 struct word_entry *e = rel->entries;
637 struct record_cluster *rec = reclist_read_record(reclist);
640 w = rec->relevance_explain2;
642 wrbuf_puts(w, "relevance = 0;\n");
643 for (i = 1; i < rel->vec_len; i++)
645 float termfreq = (float) rec->term_frequency_vecf[i];
646 int add = 100000 * termfreq * idfvec[i];
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);
657 if (!rel->rank_cluster)
659 struct record *record;
660 int cluster_size = 0;
662 for (record = rec->records; record; record = record->next)
665 wrbuf_printf(w, "score = relevance(%d)/cluster_size(%d);\n",
666 relevance, cluster_size);
667 relevance /= cluster_size;
671 wrbuf_printf(w, "score = relevance(%d);\n", relevance);
673 rec->relevance_score = relevance;
675 // Build the normalizing structures
676 // List of (sub)records for each target
677 setup_norm_record( rel, rec );
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?
684 normalize_scores(rel);
686 reclist_leave(reclist);
694 * c-file-style: "Stroustrup"
695 * indent-tabs-mode: nil
697 * vim: shiftwidth=4 tabstop=8 expandtab