| 115 | } |
| 116 | |
| 117 | double QueryVec::Similarity(IdfMap & docIdfs, DocVec const & rhs) |
| 118 | { |
| 119 | size_t kInvalidIndex = numeric_limits<size_t>::max(); |
| 120 | |
| 121 | if (Empty() && rhs.Empty()) |
| 122 | return 1.0; |
| 123 | |
| 124 | if (Empty() || rhs.Empty()) |
| 125 | return 0.0; |
| 126 | |
| 127 | vector<size_t> rsMatchTo(rhs.GetNumTokens(), kInvalidIndex); |
| 128 | |
| 129 | double dot = 0; |
| 130 | { |
| 131 | size_t i = 0, j = 0; |
| 132 | |
| 133 | while (i < m_tfs.size() && j < rhs.GetNumTokens()) |
| 134 | { |
| 135 | auto const & lt = m_tfs[i].m_token; |
| 136 | auto const & rt = rhs.GetToken(j); |
| 137 | |
| 138 | if (lt < rt) |
| 139 | { |
| 140 | ++i; |
| 141 | } |
| 142 | else if (lt > rt) |
| 143 | { |
| 144 | ++j; |
| 145 | } |
| 146 | else |
| 147 | { |
| 148 | dot += GetFullTokenWeight(i) * rhs.GetWeight(docIdfs, j); |
| 149 | rsMatchTo[j] = i; |
| 150 | ++i; |
| 151 | ++j; |
| 152 | } |
| 153 | } |
| 154 | } |
| 155 | |
| 156 | auto const ln = Norm(); |
| 157 | auto const rn = rhs.Norm(docIdfs); |
| 158 | |
| 159 | // This similarity metric assumes that prefix is not matched in the document. |
| 160 | double const similarityNoPrefix = ln > 0 && rn > 0 ? dot / sqrt(ln) / sqrt(rn) : 0; |
| 161 | |
| 162 | if (!m_prefix) |
| 163 | return similarityNoPrefix; |
| 164 | |
| 165 | double similarityWithPrefix = 0; |
| 166 | auto const & prefix = *m_prefix; |
| 167 | |
| 168 | // Let's try to match prefix token with all tokens in the |
| 169 | // document, and compute the best cosine distance. |
| 170 | for (size_t j = 0; j < rhs.GetNumTokens(); ++j) |
| 171 | { |
| 172 | auto const & t = rhs.GetToken(j); |
| 173 | if (!strings::StartsWith(t.begin(), t.end(), prefix.begin(), prefix.end())) |
| 174 | continue; |