-
Notifications
You must be signed in to change notification settings - Fork 1
/
QGramIndex.java
executable file
·292 lines (229 loc) · 8.32 KB
/
QGramIndex.java
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
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
// Copyright 2016, University of Freiburg,
// Chair of Algorithms and Data Structures.
// Authors: Hannah Bast <bast@cs.uni-freiburg.de>, Bhashitha Gamage<gamage25@gmail.com>
import java.io.FileReader;
import java.io.BufferedReader;
import java.io.IOException;
import java.util.TreeMap;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
/**
* First steps towards a q-gram index, written during class.
*/
public class QGramIndex {
/**
* Create an empty QGramIndex.
*/
public QGramIndex(int q) {
this.invertedLists = new TreeMap<String, ArrayList<Integer>>();
this.q = q;
this.padding = new String(new char[q - 1]).replace("\u0000", "$");
this.words = new ArrayList<String>();
this.scores = new ArrayList<Integer>();
this.latitudes = new ArrayList<Double>();
this.longititudes = new ArrayList<Double>();
}
/**
* Build index from given list of entites (one line per entity, columns are:
* entity name, score, ...).
*/
public void buildFromFile(String fileName) throws IOException {
FileReader fileReader = new FileReader(fileName);
BufferedReader bufferedReader = new BufferedReader(fileReader);
String line;
int entityId = 0;
while ((line = bufferedReader.readLine()) != null) {
String name = line.split("\t")[0];
int score = Integer.parseInt(line.split("\t")[1]);
double latitude = Double.parseDouble(line.split("\t")[2]);
double longitude = Double.parseDouble(line.split("\t")[3]);
words.add(name);
scores.add(score);
latitudes.add(latitude);
longititudes.add(longitude);
for (String qGram : getQGrams(name)) {
if (!invertedLists.containsKey(qGram)) {
invertedLists.put(qGram, new ArrayList<Integer>());
}
invertedLists.get(qGram).add(entityId);
}
entityId += 1;
}
}
/**
* Compute q-grams for padded, normalized version of given string.
*/
public ArrayList<String> getQGrams(String name) {
name = padding + name.toLowerCase().replaceAll("\\W", "");
ArrayList<String> result = new ArrayList<String>();
for (int i = 0; i < name.length() - q + 1; i++) {
result.add(name.substring(i, i + q));
}
return result;
};
public int checkPrefixEditDistance(String prefix, String string, int delta) {
int rows = prefix.length() + 1;
// int coloumns = string.length() + 1;
// configuring sequence modified lenghths.
int importantColumns = prefix.length() + delta + 1;
if (string.length() < importantColumns) {
importantColumns = string.length() + 1;
}
int[][] distanceMatrix = new int[rows][importantColumns];
for (int i = 0; i < rows; i++) {
for (int j = 0; j < importantColumns; j++) {
if (i == 0) {
distanceMatrix[i][j] = j;
} else if (j == 0) {
distanceMatrix[i][j] = i;
} else {
// no penalty
int penalty = 0;
int minimumValue =
Math.min(distanceMatrix[i][j - 1], distanceMatrix[i - 1][j - 1]);
minimumValue = Math.min(minimumValue, distanceMatrix[i - 1][j]);
if (prefix.charAt(i - 1) == string.charAt(j - 1)) {
// if minimum value doesnt come form diagonal, then add one as
// penalty.
if (minimumValue != distanceMatrix[i - 1][j - 1]) {
penalty = 1;
}
} else {
penalty = 1;
}
distanceMatrix[i][j] = minimumValue + penalty;
}
}
}
int ped = Integer.MAX_VALUE;
for (int i = 0; i < importantColumns; i++) {
if (distanceMatrix[rows - 1][i] < ped) {
ped = distanceMatrix[rows - 1][i];
}
}
if (ped > (delta + 1)) {
ped = delta + 1;
}
return ped;
}
public String findMatches(String query, int delta) {
query = normalizeString(query);
// Need to iterate through all entries to get the matching entities
ArrayList<String> queryQgrams = getQGrams(query);
ArrayList<Integer> appendInvertedList = new ArrayList<Integer>();
// retrieve the inverted lists for query qgrams and append all together,
for (int i = 0; i < queryQgrams.size(); i++) {
if (invertedLists.get(queryQgrams.get(i)) != null) {
appendInvertedList.addAll(invertedLists.get(queryQgrams.get(i)));
}
}
int benchmarkValue = query.length() - (q * delta);
HashMap<Integer, Integer> mergedInvertedList =
computeUnion(appendInvertedList);
for (Iterator<Map.Entry<Integer, Integer>> it =
mergedInvertedList.entrySet().iterator(); it.hasNext();) {
Map.Entry<Integer, Integer> entry = it.next();
if (entry.getValue().intValue() < benchmarkValue) {
it.remove();
}
}
// get PED of candidate docemnts.
ArrayList<Document> results = new ArrayList<Document>();
for (Entry<Integer, Integer> entry : mergedInvertedList.entrySet()) {
int ped = checkPrefixEditDistance(query,
normalizeString(words.get(entry.getKey())), delta);
if (ped <= delta) {
Document doc =
new Document(entry.getKey(), ped, scores.get(entry.getKey()),
latitudes.get(entry.getKey()), longititudes.get(entry.getKey()));
results.add(doc);
}
}
// sorting result, first by PED and then by score.
results = sortResults(results);
String jsonFormattedResponse;
if (results.size() == 0) {
jsonFormattedResponse =
"{\"query\":" + "\"" + query + "\",\"results\":[]}";
} else {
jsonFormattedResponse = "{\"query\":" + "\"" + query + "\",\"results\":[";
int maximumResults = results.size() < 10 ? results.size() : 10;
for (int i = 0; i < maximumResults; i++) {
jsonFormattedResponse += "{\"city\":" + "\""
+ jsonStringEscape(words.get(results.get(i).id)) + "\",";
jsonFormattedResponse += "\"score\":" + results.get(i).score + ",";
jsonFormattedResponse += "\"lat\":" + results.get(i).lat + ",";
jsonFormattedResponse += "\"lon\":" + results.get(i).lon + ",";
jsonFormattedResponse += "\"ped\":" + results.get(i).ped + "}";
System.out.println(words.get(results.get(i).id));
if (i + 1 < maximumResults) {
jsonFormattedResponse += ",";
} else {
System.out.println("");
}
}
jsonFormattedResponse += "]}";
System.out.println("@@ total PED seraches: " + mergedInvertedList.size());
System.out.println(".\n");
System.out.println("@@ total number of results: " + results.size());
}
return jsonFormattedResponse;
}
public HashMap<Integer, Integer>
computeUnion(ArrayList<Integer> documentList) {
// The inverted lists.
HashMap<Integer, Integer> union = new HashMap<>();
for (Integer doc : documentList) {
// Integer docID = new Integer(doc.id);
if (!union.containsKey(doc)) {
union.put(doc, 1);
} else {
union.put(doc, new Integer(union.get(doc).intValue() + 1));
}
}
return union;
}
public ArrayList<Document> sortResults(ArrayList<Document> results) {
Collections.sort(results, new Comparator<Document>() {
@Override
public int compare(Document doc1, Document doc2) {
return Integer.compare(doc1.ped, doc2.ped);
}
}.thenComparing(new Comparator<Document>() {
@Override
public int compare(Document doc1, Document doc2) {
return Integer.compare(doc2.score, doc1.score);
}
}));
return results;
}
public String normalizeString(String input) {
return input.toLowerCase().replaceAll("\\W", "");
}
String jsonStringEscape(String unescaped) {
String string1 = null;
String string2 = null;
if (unescaped.contains("\\") || unescaped.contains("\"")) {
string1 = unescaped.replaceAll("\\\\", "\\\\\\\\");
string2 = string1.replaceAll("\"", "\\\\\"");
} else {
string2 = unescaped;
}
return string2;
}
// The value of q.
protected int q;
// The padding (q - 1 times $).
protected String padding;
// The inverted lists.
protected TreeMap<String, ArrayList<Integer>> invertedLists;
ArrayList<String> words;
ArrayList<Integer> scores;
ArrayList<Double> latitudes;
ArrayList<Double> longititudes;
};