lib/vsm: access to non-existing keys return 0.0
[nit.git] / lib / vsm / vsm.nit
1 # This file is part of NIT ( http://www.nitlanguage.org ).
2 #
3 # Licensed under the Apache License, Version 2.0 (the "License");
4 # you may not use this file except in compliance with the License.
5 # You may obtain a copy of the License at
6 #
7 # http://www.apache.org/licenses/LICENSE-2.0
8 #
9 # Unless required by applicable law or agreed to in writing, software
10 # distributed under the License is distributed on an "AS IS" BASIS,
11 # WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 # See the License for the specific language governing permissions and
13 # limitations under the License.
14
15 # Vector Space Model
16 #
17 # Vector Space Model (VSM) is an algebraic model for representing text documents
18 # (and any objects, in general) as vectors of identifiers, such as, for example,
19 # index terms.
20 #
21 # It is used in information filtering, information retrieval, indexing and
22 # relevancy rankings.
23 module vsm
24
25 import counter
26
27 # A n-dimensions vector
28 #
29 # *n-dimensions* vectors are used to represent a text document or an object.
30 class Vector
31 super HashMap[nullable Object, Float]
32
33 # Cosine similarity of `self` and `other`.
34 #
35 # Gives the proximity in the range `[0.0 .. 1.0]` where 0.0 means that the
36 # two vectors are orthogonal and 1.0 means that they are identical.
37 #
38 # ~~~
39 # var v1 = new Vector
40 # v1["x"] = 1.0
41 # v1["y"] = 2.0
42 # v1["z"] = 3.0
43 #
44 # var v2 = new Vector
45 # v2["x"] = 1.0
46 # v2["y"] = 2.0
47 # v2["z"] = 3.0
48 #
49 # var v3 = new Vector
50 # v3["a"] = 1.0
51 # v3["b"] = 2.0
52 # v3["c"] = 3.0
53 #
54 # print v1.cosine_similarity(v2)
55 # assert v1.cosine_similarity(v2) == 1.0
56 # print v1.cosine_similarity(v3)
57 # assert v1.cosine_similarity(v3) == 0.0
58 # ~~~
59 fun cosine_similarity(other: SELF): Float do
60 # Collect terms
61 var terms = new HashSet[nullable Object]
62 for k in self.keys do terms.add k
63 for k in other.keys do terms.add k
64
65 # Get dot product of two vectors
66 var dot = 0.0
67 for term in terms do
68 dot += self.get_or_default(term, 0.0) * other.get_or_default(term, 0.0)
69 end
70 var cos = dot.to_f / (self.norm * other.norm)
71 if cos.is_nan then return 0.0
72 return cos
73 end
74
75 redef fun [](k) do
76 if not has_key(k) then return 0.0
77 return super
78 end
79
80 # The norm of the vector.
81 #
82 # `||x|| = (x1 ** 2 ... + xn ** 2).sqrt`
83 #
84 # ~~~
85 # var v = new Vector
86 # v["x"] = 1.0
87 # v["y"] = 1.0
88 # v["z"] = 1.0
89 # v["t"] = 1.0
90 # assert v.norm.is_approx(2.0, 0.001)
91 #
92 # v["x"] = 1.0
93 # v["y"] = 2.0
94 # v["z"] = 3.0
95 # v["t"] = 0.0
96 # assert v.norm.is_approx(3.742, 0.001)
97 # ~~~
98 fun norm: Float do
99 var sum = 0.0
100 for v in self.values do sum += v.pow(2.0)
101 return sum.to_f.sqrt
102 end
103
104 redef fun to_s do
105 return "[{join(", ", ":")}]"
106 end
107 end
108
109 # A Document index based on VSM
110 #
111 # Using VSMIndex you can index documents associated with their vector.
112 # Documents can then be matched to query vectors.
113 class VSMIndex
114
115 # Documents index
116 #
117 # TODO use a more efficient representation.
118 var documents = new HashSet[Document]
119
120 # Count for all terms in all indexed documents
121 #
122 # Used to compute the `inverse_doc_frequency`.
123 var terms_doc_count = new Vector
124
125 # Inverse document frequency
126 #
127 # The inverse document frequency is a measure of how much information a term
128 # provides, that is, whether the term is common or rare across all documents.
129 var inverse_doc_frequency = new Vector
130
131 # Used to sort matches
132 #
133 # See `IndexMatch`.
134 var sorter = new IndexMatchSorter
135
136 # Match `query` vector to all index document vectors
137 #
138 # Returns an `IndexMatch` for each indexed document.
139 # Results are ordered by descending similarity.
140 fun match_vector(query: Vector): Array[IndexMatch] do
141 var matches = new Array[IndexMatch]
142 for doc in documents do
143 var sim = query.cosine_similarity(doc.tfidf)
144 if sim == 0.0 then continue
145 matches.add new IndexMatch(doc, sim)
146 end
147 sorter.sort(matches)
148 return matches
149 end
150
151 # Index a document
152 #
153 # With each new document, the `inverse_doc_frequency` must be updated.
154 # By default, the method `update_index` is called after each call to
155 # `index_document`.
156 #
157 # When processing batch documents, use `auto_update = false` to disable
158 # the auto update of the index.
159 fun index_document(doc: Document, auto_update: nullable Bool) do
160 for term, count in doc.terms_count do
161 if not terms_doc_count.has_key(term) then
162 terms_doc_count[term] = 1.0
163 else
164 terms_doc_count[term] += 1.0
165 end
166 end
167 documents.add doc
168 if auto_update == null or auto_update then update_index
169 end
170
171 # Update the index
172 #
173 # Recompute the `inverse_doc_frequency` values.
174 # Must be called manually after indexing new document with the option
175 # `auto_update = false`.
176 fun update_index do
177 for doc in documents do
178 for term, ccount in doc.terms_count do
179 inverse_doc_frequency[term] = (documents.length.to_f / terms_doc_count[term]).log
180 end
181 end
182 for doc in documents do
183 for term, freq in doc.terms_frequency do
184 doc.tfidf[term] = freq * inverse_doc_frequency[term]
185 end
186 end
187 end
188 end
189
190 # A VSM index to store strings
191 class StringIndex
192 super VSMIndex
193
194 # Index a new Document from `title`, `uri` and string `string`.
195 #
196 # Return the Document created.
197 #
198 # See `index_document`.
199 fun index_string(title, uri, string: String, auto_update: nullable Bool): Document do
200 var vector = parse_string(string)
201 var doc = new Document(title, uri, vector)
202 index_document(doc, auto_update)
203 return doc
204 end
205
206 # Match the `query` string against all indexed documents
207 #
208 # See `match_vector`.
209 fun match_string(query: String): Array[IndexMatch] do
210 var vector = parse_string(query)
211 return match_vector(vector)
212 end
213
214 # Parse the `string` as a Vector
215 #
216 # Returns a vector containing the terms of `string`.
217 fun parse_string(string: String): Vector do
218 var reader = new StringReader(string)
219 var vector = new Vector
220 loop
221 var token = reader.read_word
222 if token == "" then break
223
224 if not vector.has_key(token) then
225 vector[token] = 1.0
226 else
227 vector[token] += 1.0
228 end
229 end
230 return vector
231 end
232 end
233
234 # A VSMIndex to index files
235 class FileIndex
236 super StringIndex
237
238 # Index a file from its `path`.
239 #
240 # Return the created document or null if `path` is not accepted by `accept_file`.
241 #
242 # See `index_document`.
243 fun index_file(path: String, auto_update: nullable Bool): nullable Document do
244 if not accept_file(path) then return null
245 var vector = parse_file(path)
246 var doc = new Document(path, path, vector)
247 index_document(doc, auto_update)
248 return doc
249 end
250
251 # Index multiple files
252 #
253 # The recursive method `index_dir` will be called for each directory found
254 # in `paths`.
255 #
256 # See `index_file`
257 fun index_files(paths: Collection[String], auto_update: nullable Bool) do
258 for path in paths do
259 if path.to_path.is_dir then
260 index_dir(path, false)
261 else
262 index_file(path, false)
263 end
264 end
265 if auto_update != null and auto_update then update_index
266 end
267
268 # Index all files in `dir` recursively
269 #
270 # See `index_file`.
271 fun index_dir(dir: String, auto_update: nullable Bool) do
272 if not dir.to_path.is_dir then return
273 for file in dir.files do
274 var path = dir / file
275 if path.to_path.is_dir then
276 index_dir(path, false)
277 else
278 index_file(path, false)
279 end
280 end
281 if auto_update != null and auto_update then update_index
282 end
283
284 # Is `path` accepted depending on `whitelist_exts` and `blacklist_exts`?
285 fun accept_file(path: String): Bool do
286 var ext = path.file_extension
287 if ext != null then
288 ext = ext.to_lower
289 if blacklist_exts.has(ext) then return false
290 if whitelist_exts.not_empty and not whitelist_exts.has(ext) then return false
291 end
292 return whitelist_exts.is_empty
293 end
294
295 # Parse the `file` content as a Vector
296 #
297 # See `parse_string`.
298 fun parse_file(file: String): Vector do
299 return parse_string(file.to_path.read_all)
300 end
301
302 # File extensions white list
303 #
304 # If not empty, only files with these extensions will be indexed.
305 #
306 # If an extension is in both `whitelist_exts` and `blacklist_exts`, the
307 # blacklist will prevail and the file will be ignored.
308 var whitelist_exts = new Array[String] is writable
309
310 # File extensions black list
311 #
312 # Files with these extensions will not be indexed.
313 var blacklist_exts = new Array[String] is writable
314 end
315
316 # A Document to add in a VSMIndex
317 class Document
318
319 # Document title
320 var title: String
321
322 # Document URI
323 var uri: String
324
325 # Count of all terms found in the document
326 #
327 # Used to compute the document `terms_frequency`.
328 var terms_count: Vector
329
330 # Frequency of each term found in the document
331 #
332 # Used to match the document against the `VSMIndex::inverse_doc_frequency`.
333 var terms_frequency: Vector is lazy do
334 var all_terms = 0.0
335 for t, c in terms_count do all_terms += c
336
337 var vector = new Vector
338 for t, c in terms_count do
339 vector[t] = c / all_terms
340 end
341 return vector
342 end
343
344 # Term frequency–Inverse document frequency for each term
345 #
346 # A high weight in tf–idf is reached by a high term frequency
347 # (in the given document) and a low document frequency of the term in the
348 # whole collection of documents
349 var tfidf = new Vector
350
351 redef fun to_s do return "{title}"
352 end
353
354 # A match to a `request` in an `Index`
355 class IndexMatch
356 super Comparable
357
358 # Document matching the `request_vector`
359 var document: Document
360
361 # Similarity between the `request` and the `doc`.
362 #
363 # Result is in the range 0.0 .. 1.1 where 0.0 means no similarity and 1.0
364 # means perfect similarity.
365 var similarity: Float
366
367 redef fun to_s do return "{document} ({similarity})"
368 end
369
370 # Sort matches by similarity
371 class IndexMatchSorter
372 super DefaultComparator
373
374 redef type COMPARED: IndexMatch
375
376 redef fun compare(a, b) do
377 return b.similarity <=> a.similarity
378 end
379 end