aboutsummaryrefslogtreecommitdiffstats
path: root/src/libs/3rdparty/sqlite/okapi_bm25.h
blob: d527012c19bf8cce2b664c74a290884f1ea078e8 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
#include <math.h>
#include <assert.h>
#include "sqlite3.h"


static void okapi_bm25(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal) {
    assert(sizeof(int) == 4);

    const unsigned int *matchinfo = (const unsigned int *)sqlite3_value_blob(apVal[0]);
    int searchTextCol = sqlite3_value_int(apVal[1]);

    double K1 = ((nVal >= 3) ? sqlite3_value_double(apVal[2]) : 1.2);
    double B = ((nVal >= 4) ? sqlite3_value_double(apVal[3]) : 0.75);

    int P_OFFSET = 0;
    int C_OFFSET = 1;
    int X_OFFSET = 2;

    int termCount = matchinfo[P_OFFSET];
    int colCount = matchinfo[C_OFFSET];

    int N_OFFSET = X_OFFSET + 3*termCount*colCount;
    int A_OFFSET = N_OFFSET + 1;
    int L_OFFSET = (A_OFFSET + colCount);


    double totalDocs = matchinfo[N_OFFSET];
    double avgLength = matchinfo[A_OFFSET + searchTextCol];
    double docLength = matchinfo[L_OFFSET + searchTextCol];

    double sum = 0.0;

    for (int i = 0; i < termCount; i++) {
        int currentX = X_OFFSET + (3 * searchTextCol * (i + 1));
        double termFrequency = matchinfo[currentX];
        double docsWithTerm = matchinfo[currentX + 2];

        double idf = log(
            (totalDocs - docsWithTerm + 0.5) /
            (docsWithTerm + 0.5)
        );

        double rightSide = (
            (termFrequency * (K1 + 1)) /
            (termFrequency + (K1 * (1 - B + (B * (docLength / avgLength)))))
        );

        sum += (idf * rightSide);
    }

    sqlite3_result_double(pCtx, sum);
}

//
//  Created by Joshua Wilson on 27/05/14.
//  Copyright (c) 2014 Joshua Wilson. All rights reserved.
//  https://github.com/neozenith/sqlite-okapi-bm25
//
// This is an extension to the work of "Radford 'rads' Smith"
// found at: https://github.com/rads/sqlite-okapi-bm25
// which is covered by the MIT License
// http://opensource.org/licenses/MIT
// the following code shall also be covered by the same MIT License

static void okapi_bm25f(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal) {
    assert(sizeof(int) == 4);

    const unsigned int *matchinfo = (const unsigned int *)sqlite3_value_blob(apVal[0]);


    //Setting the default values and ignoring argument based inputs so the extra
    //arguments can be the column weights instead.
    double K1 = 1.2;// ((nVal >= 3) ? sqlite3_value_double(apVal[2]) : 1.2);
    double B = 0.75;// ((nVal >= 4) ? sqlite3_value_double(apVal[3]) : 0.75);

    //For a good explanation fo the maths and how to choose these variables
    //http://stackoverflow.com/a/23161886/622276

    //NOTE: the rearranged order of parameters to match the order presented on
    //SQLite3 FTS3 documentation 'pcxnals' (http://www.sqlite.org/fts3.html#matchinfo)

    int P_OFFSET = 0;
    int C_OFFSET = 1;
    int X_OFFSET = 2;

    int termCount = matchinfo[P_OFFSET];
    int colCount = matchinfo[C_OFFSET];

    int N_OFFSET = X_OFFSET + 3*termCount*colCount;
    int A_OFFSET = N_OFFSET + 1;
    int L_OFFSET = (A_OFFSET + colCount);
//    int S_OFFSET = (L_OFFSET + colCount); //useful as a pseudo proximity weighting per field/column

    double totalDocs = matchinfo[N_OFFSET];

    double avgLength = 0.0;
    double docLength = 0.0;

    for (int col = 0; col < colCount; col++)
    {
        avgLength +=  matchinfo[A_OFFSET + col];
        docLength +=  matchinfo[L_OFFSET + col];
    }

    double epsilon = 1.0 / (totalDocs*avgLength);
    double sum = 0.0;

    for (int t = 0; t < termCount; t++) {
        for (int col = 0 ; col < colCount; col++)
        {
            int currentX = X_OFFSET + (3 * col * (t + 1));


            double termFrequency = matchinfo[currentX];
            double docsWithTerm = matchinfo[currentX + 2];

            double idf = log(
                             (totalDocs - docsWithTerm + 0.5) /
                             (docsWithTerm + 0.5)
                             );
            // "...terms appearing in more than half of the corpus will provide negative contributions to the final document score."
            //http://en.wikipedia.org/wiki/Okapi_BM25

            idf = (idf < 0) ? epsilon : idf; //common terms could have no effect (\epsilon=0.0) or a very small effect (\epsilon=1/NoOfTokens which asymptotes to 0.0)

            double rightSide = (
                                (termFrequency * (K1 + 1)) /
                                (termFrequency + (K1 * (1 - B + (B * (docLength / avgLength)))))
                                );

            rightSide += 1.0;
            //To comply with BM25+ that solves a lower bounding issue where large documents that match are unfairly scored as
            //having similar relevancy as short documents that do not contain as many terms
            //Yuanhua Lv and ChengXiang Zhai. 'Lower-bounding term frequency normalization.' In Proceedings of CIKM'2011, pages 7-16.
            //http://sifaka.cs.uiuc.edu/~ylv2/pub/cikm11-lowerbound.pdf

            double weight = ((nVal > col+1) ? sqlite3_value_double(apVal[col+1]) : 1.0);

//            double subsequence = matchinfo[S_OFFSET + col];

            sum += (idf * rightSide) * weight; // * subsequence; //useful as a pseudo proximty weighting
        }
    }

    sqlite3_result_double(pCtx, sum);
}

static void okapi_bm25f_kb(sqlite3_context *pCtx, int nVal, sqlite3_value **apVal) {
    assert(sizeof(int) == 4);

    const unsigned int *matchinfo = (const unsigned int *)sqlite3_value_blob(apVal[0]);


    //Setting the default values and ignoring argument based inputs so the extra
    //arguments can be the column weights instead.
    if (nVal < 2) sqlite3_result_error(pCtx, "wrong number of arguments to function okapi_bm25_kb(), expected k1 parameter", -1);
    if (nVal < 3) sqlite3_result_error(pCtx, "wrong number of arguments to function okapi_bm25_kb(), expected b parameter", -1);
    double K1 = sqlite3_value_double(apVal[1]);
    double B = sqlite3_value_double(apVal[2]);

    //For a good explanation fo the maths and how to choose these variables
    //http://stackoverflow.com/a/23161886/622276

    //NOTE: the rearranged order of parameters to match the order presented on
    //SQLite3 FTS3 documentation 'pcxnals' (http://www.sqlite.org/fts3.html#matchinfo)

    int P_OFFSET = 0;
    int C_OFFSET = 1;
    int X_OFFSET = 2;

    int termCount = matchinfo[P_OFFSET];
    int colCount = matchinfo[C_OFFSET];

    int N_OFFSET = X_OFFSET + 3*termCount*colCount;
    int A_OFFSET = N_OFFSET + 1;
    int L_OFFSET = (A_OFFSET + colCount);
    //    int S_OFFSET = (L_OFFSET + colCount); //useful as a pseudo proximity weighting per field/column

    double totalDocs = matchinfo[N_OFFSET];

    double avgLength = 0.0;
    double docLength = 0.0;

    for (int col = 0; col < colCount; col++)
    {
        avgLength +=  matchinfo[A_OFFSET + col];
        docLength +=  matchinfo[L_OFFSET + col];
    }

    double epsilon = 1.0 / (totalDocs*avgLength);
    double sum = 0.0;

    for (int t = 0; t < termCount; t++) {
        for (int col = 0 ; col < colCount; col++)
        {
            int currentX = X_OFFSET + (3 * col * (t + 1));


            double termFrequency = matchinfo[currentX];
            double docsWithTerm = matchinfo[currentX + 2];

            double idf = log(
                             (totalDocs - docsWithTerm + 0.5) /
                             (docsWithTerm + 0.5)
                             );
            // "...terms appearing in more than half of the corpus will provide negative contributions to the final document score."
            //http://en.wikipedia.org/wiki/Okapi_BM25

            idf = (idf < 0) ? epsilon : idf; //common terms could have no effect (\epsilon=0.0) or a very small effect (\epsilon=1/NoOfTokens which asymptotes to 0.0)

            double rightSide = (
                                (termFrequency * (K1 + 1)) /
                                (termFrequency + (K1 * (1 - B + (B * (docLength / avgLength)))))
                                );

            rightSide += 1.0;
            //To comply with BM25+ that solves a lower bounding issue where large documents that match are unfairly scored as
            //having similar relevancy as short documents that do not contain as many terms
            //Yuanhua Lv and ChengXiang Zhai. 'Lower-bounding term frequency normalization.' In Proceedings of CIKM'2011, pages 7-16.
            //http://sifaka.cs.uiuc.edu/~ylv2/pub/cikm11-lowerbound.pdf

            double weight = ((nVal > col+3) ? sqlite3_value_double(apVal[col+3]) : 1.0);

            //            double subsequence = matchinfo[S_OFFSET + col];

            sum += (idf * rightSide) * weight; // * subsequence; //useful as a pseudo proximty weighting
        }
    }

    sqlite3_result_double(pCtx, sum);
}