Chromium Code Reviews
chromiumcodereview-hr@appspot.gserviceaccount.com (chromiumcodereview-hr) | Please choose your nickname with Settings | Help | Chromium Project | Gerrit Changes | Sign out
(92)

Side by Side Diff: chrome/browser/history/scored_history_match.cc

Issue 10541045: Move ScoredHistoryMatch into Its Own Set of Files (Closed) Base URL: svn://svn.chromium.org/chrome/trunk/src/
Patch Set: Created 8 years, 6 months ago
Use n/p to move between diff chunks; N/P to move between comments. Draft comments are only viewable by you.
Jump to:
View unified diff | Download patch | Annotate | Revision Log
Property Changes:
Added: svn:eol-style
+ LF
OLDNEW
(Empty)
1 // Copyright (c) 2012 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
4
5 #include "chrome/browser/history/scored_history_match.h"
6
7 #include <algorithm>
8 #include <functional>
9 #include <iterator>
10 #include <numeric>
11 #include <set>
12
13 #include <math.h>
14
15 #include "base/command_line.h"
16 #include "base/i18n/case_conversion.h"
17 #include "base/string_util.h"
18 #include "base/utf_string_conversions.h"
19 #include "chrome/browser/autocomplete/url_prefix.h"
20 #include "chrome/common/chrome_switches.h"
21 #include "content/public/browser/browser_thread.h"
22
23 namespace history {
24
25 // The maximum score any candidate result can achieve.
26 const int kMaxTotalScore = 1425;
27
28 // Score ranges used to get a 'base' score for each of the scoring factors
29 // (such as recency of last visit, times visited, times the URL was typed,
30 // and the quality of the string match). There is a matching value range for
31 // each of these scores for each factor. Note that the top score is greater
32 // than |kMaxTotalScore|. The score for each candidate will be capped in the
33 // final calculation.
34 const int kScoreRank[] = { 1450, 1200, 900, 400 };
35
36 // ScoredHistoryMatch ----------------------------------------------------------
37
38 bool ScoredHistoryMatch::initialized = false;
39 bool ScoredHistoryMatch::use_new_scoring = false;
40
41 ScoredHistoryMatch::ScoredHistoryMatch()
42 : raw_score(0),
43 can_inline(false) {
44 if (!initialized) {
45 const std::string switch_value = CommandLine::ForCurrentProcess()->
46 GetSwitchValueASCII(switches::kOmniboxHistoryQuickProviderNewScoring);
47 if (switch_value == switches::kOmniboxHistoryQuickProviderNewScoringEnabled)
48 use_new_scoring = true;
49 initialized = true;
50 }
51 }
52
53 ScoredHistoryMatch::ScoredHistoryMatch(const URLRow& row,
54 const string16& lower_string,
55 const String16Vector& terms,
56 const RowWordStarts& word_starts,
57 const base::Time now)
58 : HistoryMatch(row, 0, false, false),
59 raw_score(0),
60 can_inline(false) {
61 if (!initialized) {
62 const std::string switch_value = CommandLine::ForCurrentProcess()->
63 GetSwitchValueASCII(switches::kOmniboxHistoryQuickProviderNewScoring);
64 if (switch_value == switches::kOmniboxHistoryQuickProviderNewScoringEnabled)
65 use_new_scoring = true;
66 initialized = true;
67 }
68
69 GURL gurl = row.url();
70 if (!gurl.is_valid())
71 return;
72
73 // Figure out where each search term appears in the URL and/or page title
74 // so that we can score as well as provide autocomplete highlighting.
75 string16 url = base::i18n::ToLower(UTF8ToUTF16(gurl.spec()));
76 string16 title = base::i18n::ToLower(row.title());
77 int term_num = 0;
78 for (String16Vector::const_iterator iter = terms.begin(); iter != terms.end();
79 ++iter, ++term_num) {
80 string16 term = *iter;
81 TermMatches url_term_matches = MatchTermInString(term, url, term_num);
82 TermMatches title_term_matches = MatchTermInString(term, title, term_num);
83 if (url_term_matches.empty() && title_term_matches.empty())
84 return; // A term was not found in either URL or title - reject.
85 url_matches.insert(url_matches.end(), url_term_matches.begin(),
86 url_term_matches.end());
87 title_matches.insert(title_matches.end(), title_term_matches.begin(),
88 title_term_matches.end());
89 }
90
91 // Sort matches by offset and eliminate any which overlap.
92 // TODO(mpearson): Investigate whether this has any meaningful
93 // effect on scoring. (It's necessary at some point: removing
94 // overlaps and sorting is needed to decide what to highlight in the
95 // suggestion string. But this sort and de-overlap doesn't have to
96 // be done before scoring.)
97 url_matches = SortAndDeoverlapMatches(url_matches);
98 title_matches = SortAndDeoverlapMatches(title_matches);
99
100 // We can inline autocomplete a result if:
101 // 1) there is only one search term
102 // 2) AND EITHER:
103 // 2a) the first match starts at the beginning of the candidate URL, OR
104 // 2b) the candidate URL starts with one of the standard URL prefixes with
105 // the URL match immediately following that prefix.
106 // 3) AND the search string does not end in whitespace (making it look to
107 // the IMUI as though there is a single search term when actually there
108 // is a second, empty term).
109 can_inline = !url_matches.empty() &&
110 terms.size() == 1 &&
111 (url_matches[0].offset == 0 ||
112 URLPrefix::IsURLPrefix(url.substr(0, url_matches[0].offset))) &&
113 !IsWhitespace(*(lower_string.rbegin()));
114 match_in_scheme = can_inline && url_matches[0].offset == 0;
115
116 if (use_new_scoring) {
117 const float topicality_score = GetTopicalityScore(
118 terms.size(), url, url_matches, title_matches, word_starts);
119 const float recency_score = GetRecencyScore(
120 (now - row.last_visit()).InDays());
121 const float popularity_score = GetPopularityScore(
122 row.typed_count(), row.visit_count());
123
124 // Combine recency, popularity, and topicality scores into one.
125 // Example of how this functions: Suppose the omnibox has one
126 // input term. Suppose we have a URL that has 4 typed visits with
127 // the most recent being within a day and the omnibox input term
128 // has a single URL hostname hit at a word boundary. Then this
129 // URL will score 1400 ( = 4 * 350), which is exactly the value of
130 // search what you type. That is, it's the boundary of what might
131 // end up being inlined.
132 raw_score = 350 * topicality_score * recency_score * popularity_score;
133 raw_score =
134 (raw_score <= kint32max) ? static_cast<int>(raw_score) : kint32max;
135 } else { // "old" scoring
136 // Get partial scores based on term matching. Note that the score for
137 // each of the URL and title are adjusted by the fraction of the
138 // terms appearing in each.
139 int url_score = ScoreComponentForMatches(url_matches, url.length()) *
140 std::min(url_matches.size(), terms.size()) / terms.size();
141 int title_score =
142 ScoreComponentForMatches(title_matches, title.length()) *
143 std::min(title_matches.size(), terms.size()) / terms.size();
144 // Arbitrarily pick the best.
145 // TODO(mrossetti): It might make sense that a term which appears in both
146 // the URL and the Title should boost the score a bit.
147 int term_score = std::max(url_score, title_score);
148 if (term_score == 0)
149 return;
150
151 // Determine scoring factors for the recency of visit, visit count and typed
152 // count attributes of the URLRow.
153 const int kDaysAgoLevel[] = { 1, 10, 20, 30 };
154 int days_ago_value = ScoreForValue((base::Time::Now() -
155 row.last_visit()).InDays(), kDaysAgoLevel);
156 const int kVisitCountLevel[] = { 50, 30, 10, 5 };
157 int visit_count_value = ScoreForValue(row.visit_count(), kVisitCountLevel);
158 const int kTypedCountLevel[] = { 50, 30, 10, 5 };
159 int typed_count_value = ScoreForValue(row.typed_count(), kTypedCountLevel);
160
161 // The final raw score is calculated by:
162 // - multiplying each factor by a 'relevance'
163 // - calculating the average.
164 // Note that visit_count is reduced by typed_count because both are bumped
165 // when a typed URL is recorded thus giving visit_count too much weight.
166 const int kTermScoreRelevance = 4;
167 const int kDaysAgoRelevance = 2;
168 const int kVisitCountRelevance = 2;
169 const int kTypedCountRelevance = 5;
170 int effective_visit_count_value =
171 std::max(0, visit_count_value - typed_count_value);
172 raw_score = term_score * kTermScoreRelevance +
173 days_ago_value * kDaysAgoRelevance +
174 effective_visit_count_value * kVisitCountRelevance +
175 typed_count_value * kTypedCountRelevance;
176 raw_score /= (kTermScoreRelevance + kDaysAgoRelevance +
177 kVisitCountRelevance + kTypedCountRelevance);
178 raw_score = std::min(kMaxTotalScore, raw_score);
179 }
180 }
181
182 ScoredHistoryMatch::~ScoredHistoryMatch() {}
183
184 // std::accumulate helper function to add up TermMatches' lengths as used in
185 // ScoreComponentForMatches
186 int AccumulateMatchLength(int total, const TermMatch& match) {
187 return total + match.length;
188 }
189
190 // static
191 int ScoredHistoryMatch::ScoreComponentForMatches(const TermMatches& matches,
192 size_t max_length) {
193 if (matches.empty())
194 return 0;
195
196 // Score component for whether the input terms (if more than one) were found
197 // in the same order in the match. Start with kOrderMaxValue points divided
198 // equally among (number of terms - 1); then discount each of those terms that
199 // is out-of-order in the match.
200 const int kOrderMaxValue = 1000;
201 int order_value = kOrderMaxValue;
202 if (matches.size() > 1) {
203 int max_possible_out_of_order = matches.size() - 1;
204 int out_of_order = 0;
205 for (size_t i = 1; i < matches.size(); ++i) {
206 if (matches[i - 1].term_num > matches[i].term_num)
207 ++out_of_order;
208 }
209 order_value = (max_possible_out_of_order - out_of_order) * kOrderMaxValue /
210 max_possible_out_of_order;
211 }
212
213 // Score component for how early in the match string the first search term
214 // appears. Start with kStartMaxValue points and discount by
215 // kStartMaxValue/kMaxSignificantChars points for each character later than
216 // the first at which the term begins. No points are earned if the start of
217 // the match occurs at or after kMaxSignificantChars.
218 const int kStartMaxValue = 1000;
219 int start_value = (kMaxSignificantChars -
220 std::min(kMaxSignificantChars, matches[0].offset)) * kStartMaxValue /
221 kMaxSignificantChars;
222
223 // Score component for how much of the matched string the input terms cover.
224 // kCompleteMaxValue points times the fraction of the URL/page title string
225 // that was matched.
226 size_t term_length_total = std::accumulate(matches.begin(), matches.end(),
227 0, AccumulateMatchLength);
228 const size_t kMaxSignificantLength = 50;
229 size_t max_significant_length =
230 std::min(max_length, std::max(term_length_total, kMaxSignificantLength));
231 const int kCompleteMaxValue = 1000;
232 int complete_value =
233 term_length_total * kCompleteMaxValue / max_significant_length;
234
235 const int kOrderRelevance = 1;
236 const int kStartRelevance = 6;
237 const int kCompleteRelevance = 3;
238 int raw_score = order_value * kOrderRelevance +
239 start_value * kStartRelevance +
240 complete_value * kCompleteRelevance;
241 raw_score /= (kOrderRelevance + kStartRelevance + kCompleteRelevance);
242
243 // Scale the raw score into a single score component in the same manner as
244 // used in ScoredMatchForURL().
245 const int kTermScoreLevel[] = { 1000, 750, 500, 200 };
246 return ScoreForValue(raw_score, kTermScoreLevel);
247 }
248
249 // static
250 int ScoredHistoryMatch::ScoreForValue(int value, const int* value_ranks) {
251 int i = 0;
252 int rank_count = arraysize(kScoreRank);
253 while ((i < rank_count) && ((value_ranks[0] < value_ranks[1]) ?
254 (value > value_ranks[i]) : (value < value_ranks[i])))
255 ++i;
256 if (i >= rank_count)
257 return 0;
258 int score = kScoreRank[i];
259 if (i > 0) {
260 score += (value - value_ranks[i]) *
261 (kScoreRank[i - 1] - kScoreRank[i]) /
262 (value_ranks[i - 1] - value_ranks[i]);
263 }
264 return score;
265 }
266
267 // Comparison function for sorting ScoredMatches by their scores.
268 bool ScoredHistoryMatch::MatchScoreGreater(const ScoredHistoryMatch& m1,
269 const ScoredHistoryMatch& m2) {
270 return m1.raw_score > m2.raw_score;
271 }
272
273 // static
274 float ScoredHistoryMatch::GetTopicalityScore(
275 const int num_terms,
276 const string16& url,
277 const TermMatches& url_matches,
278 const TermMatches& title_matches,
279 const RowWordStarts& word_starts) {
280 // Because the below thread is not thread safe, we check that we're
281 // only calling it from one thread: the UI thread. Specifically,
282 // we check "if we've heard of the UI thread then we'd better
283 // be on it." The first part is necessary so unit tests pass. (Many
284 // unit tests don't set up the threading naming system; hence
285 // CurrentlyOn(UI thread) will fail.)
286 DCHECK(
287 !content::BrowserThread::IsWellKnownThread(content::BrowserThread::UI) ||
288 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
289 if (raw_term_score_to_topicality_score == NULL) {
290 raw_term_score_to_topicality_score = new float[kMaxRawTermScore];
291 FillInTermScoreToTopicalityScoreArray();
292 }
293 // A vector that accumulates per-term scores. The strongest match--a
294 // match in the hostname at a word boundary--is worth 10 points.
295 // Everything else is less. In general, a match that's not at a word
296 // boundary is worth about 1/4th or 1/5th of a match at the word boundary
297 // in the same part of the URL/title.
298 std::vector<int> term_scores(num_terms, 0);
299 std::vector<size_t>::const_iterator next_word_starts =
300 word_starts.url_word_starts_.begin();
301 std::vector<size_t>::const_iterator end_word_starts =
302 word_starts.url_word_starts_.end();
303 const size_t question_mark_pos = url.find('?');
304 const size_t colon_pos = url.find(':');
305 // The + 3 skips the // that probably appears in the protocol
306 // after the colon. If the protocol doesn't have two slashes after
307 // the colon, that's okay--all this ends up doing is starting our
308 // search for the next / a few characters into the hostname. The
309 // only times this can cause problems is if we have a protocol without
310 // a // after the colon and the hostname is only one or two characters.
311 // This isn't worth worrying about.
312 const size_t end_of_hostname_pos = (colon_pos != std::string::npos) ?
313 url.find('/', colon_pos + 3) : url.find('/');
314 // Loop through all URL matches and score them appropriately.
315 for (TermMatches::const_iterator iter = url_matches.begin();
316 iter != url_matches.end(); ++iter) {
317 // Advance next_word_starts until it's >= the position of the term
318 // we're considering.
319 while ((next_word_starts != end_word_starts) &&
320 (*next_word_starts < iter->offset)) {
321 ++next_word_starts;
322 }
323 const bool at_word_boundary = (next_word_starts != end_word_starts) &&
324 (*next_word_starts == iter->offset);
325 if ((question_mark_pos != std::string::npos) &&
326 (iter->offset > question_mark_pos)) {
327 // match in CGI ?... fragment
328 term_scores[iter->term_num] += at_word_boundary ? 5 : 0;
329 } else if ((end_of_hostname_pos != std::string::npos) &&
330 (iter->offset > end_of_hostname_pos)) {
331 // match in path
332 term_scores[iter->term_num] += at_word_boundary ? 8 : 1;
333 } else if ((colon_pos == std::string::npos) ||
334 (iter->offset > colon_pos)) {
335 // match in hostname
336 term_scores[iter->term_num] += at_word_boundary ? 10 : 2;
337 } // else: match in protocol. Do not count this match for scoring.
338 }
339 // Now do the analogous loop over all matches in the title.
340 next_word_starts = word_starts.title_word_starts_.begin();
341 end_word_starts = word_starts.title_word_starts_.end();
342 int word_num = 0;
343 for (TermMatches::const_iterator iter = title_matches.begin();
344 iter != title_matches.end(); ++iter) {
345 // Advance next_word_starts until it's >= the position of the term
346 // we're considering.
347 while ((next_word_starts != end_word_starts) &&
348 (*next_word_starts < iter->offset)) {
349 ++next_word_starts;
350 ++word_num;
351 }
352 if (word_num >= 10) break; // only count the first ten words
353 const bool at_word_boundary = (next_word_starts != end_word_starts) &&
354 (*next_word_starts == iter->offset);
355 term_scores[iter->term_num] += at_word_boundary ? 8 : 2;
356 }
357 // TODO(mpearson): Restore logic for penalizing out-of-order matches.
358 // (Perhaps discount them by 0.8?)
359 // TODO(mpearson): Consider: if the earliest match occurs late in the string,
360 // should we discount it?
361 // TODO(mpearson): Consider: do we want to score based on how much of the
362 // input string the input covers? (I'm leaning toward no.)
363
364 // Compute the topicality_score as the sum of transformed term_scores.
365 float topicality_score = 0;
366 for (size_t i = 0; i < term_scores.size(); ++i) {
367 topicality_score += raw_term_score_to_topicality_score[
368 (term_scores[i] >= kMaxRawTermScore)? kMaxRawTermScore - 1:
369 term_scores[i]];
370 }
371 // TODO(mpearson): If there are multiple terms, consider taking the
372 // geometric mean of per-term scores rather than sum as we're doing now
373 // (which is equivalent to the arthimatic mean).
374
375 return topicality_score;
376 }
377
378 // static
379 float* ScoredHistoryMatch::raw_term_score_to_topicality_score = NULL;
380
381 // static
382 void ScoredHistoryMatch::FillInTermScoreToTopicalityScoreArray() {
383 for (int term_score = 0; term_score < kMaxRawTermScore; ++term_score) {
384 float topicality_score;
385 if (term_score < 10) {
386 // If the term scores less than 10 points (no full-credit hit, or
387 // no combination of hits that score that well), then the topicality
388 // score is linear in the term score.
389 topicality_score = 0.1 * term_score;
390 } else {
391 // For term scores of at least ten points, pass them through a log
392 // function so a score of 10 points gets a 1.0 (to meet up exactly
393 // with the linear component) and increases logarithmically until
394 // maxing out at 30 points, with computes to a score around 2.1.
395 topicality_score = (1.0 + 2.25 * log10(0.1 *
396 ((term_score <= 30) ? term_score : 30)));
397 }
398 raw_term_score_to_topicality_score[term_score] = topicality_score;
399 }
400 }
401
402 // static
403 float* ScoredHistoryMatch::days_ago_to_recency_score = NULL;
404
405 // static
406 float ScoredHistoryMatch::GetRecencyScore(int last_visit_days_ago) {
407 // Because the below thread is not thread safe, we check that we're
408 // only calling it from one thread: the UI thread. Specifically,
409 // we check "if we've heard of the UI thread then we'd better
410 // be on it." The first part is necessary so unit tests pass. (Many
411 // unit tests don't set up the threading naming system; hence
412 // CurrentlyOn(UI thread) will fail.)
413 DCHECK(
414 !content::BrowserThread::IsWellKnownThread(content::BrowserThread::UI) ||
415 content::BrowserThread::CurrentlyOn(content::BrowserThread::UI));
416 if (days_ago_to_recency_score == NULL) {
417 days_ago_to_recency_score = new float[kDaysToPrecomputeRecencyScoresFor];
418 FillInDaysAgoToRecencyScoreArray();
419 }
420 // Lookup the score in days_ago_to_recency_score, treating
421 // everything older than what we've precomputed as the oldest thing
422 // we've precomputed. The std::max is to protect against corruption
423 // in the database (in case last_visit_days_ago is negative).
424 return days_ago_to_recency_score[
425 std::max(
426 std::min(last_visit_days_ago, kDaysToPrecomputeRecencyScoresFor - 1),
427 0)];
428 }
429
430 void ScoredHistoryMatch::FillInDaysAgoToRecencyScoreArray() {
431 for (int days_ago = 0; days_ago < kDaysToPrecomputeRecencyScoresFor;
432 days_ago++) {
433 int unnormalized_recency_score;
434 if (days_ago <= 1) {
435 unnormalized_recency_score = 100;
436 } else if (days_ago <= 7) {
437 // Linearly extrapolate between 1 and 7 days so 7 days has a score of 70.
438 unnormalized_recency_score = 70 + (7 - days_ago) * (100 - 70) / (7 - 1);
439 } else if (days_ago <= 30) {
440 // Linearly extrapolate between 7 and 30 days so 30 days has a score
441 // of 50.
442 unnormalized_recency_score = 50 + (30 - days_ago) * (70 - 50) / (30 - 7);
443 } else if (days_ago <= 90) {
444 // Linearly extrapolate between 30 and 90 days so 90 days has a score
445 // of 20.
446 unnormalized_recency_score = 20 + (90 - days_ago) * (50 - 20) / (90 - 30);
447 } else if (days_ago <= 365) {
448 // Linearly extrapolate between 90 and 365 days so 365 days has a score
449 // of 10.
450 unnormalized_recency_score =
451 10 + (365 - days_ago) * (20 - 10) / (365 - 90);
452 } else {
453 // greater than a year.
454 unnormalized_recency_score = 10;
455 }
456 days_ago_to_recency_score[days_ago] = unnormalized_recency_score / 100.0;
457 if (days_ago > 0) {
458 DCHECK_LE(days_ago_to_recency_score[days_ago],
459 days_ago_to_recency_score[days_ago - 1]);
460 }
461 }
462 }
463
464 // static
465 float ScoredHistoryMatch::GetPopularityScore(int typed_count,
466 int visit_count) {
467 // The max()s are to guard against database corruption.
468 return (std::max(typed_count, 0) * 5.0 + std::max(visit_count, 0) * 3.0) /
469 (5.0 + 3.0);
470 }
471
472 } // namespace history
OLDNEW
« no previous file with comments | « chrome/browser/history/scored_history_match.h ('k') | chrome/browser/history/scored_history_match_unittest.cc » ('j') | no next file with comments »

Powered by Google App Engine
This is Rietveld 408576698