Debian Codegraph @

src/uk/me/parabola/imgfmt/app/net/NETFile.java

raw symbols SCIP
1 /*
2 * Copyright (C) 2007 Steve Ratcliffe
3 *
4 * This program is free software; you can redistribute it and/or modify
5 * it under the terms of the GNU General Public License version 2 as
6 * published by the Free Software Foundation.
7 *
8 * This program is distributed in the hope that it will be useful,
9 * but WITHOUT ANY WARRANTY; without even the implied warranty of
10 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
11 * GNU General Public License for more details.
12 *
13 *
14 * Author: Steve Ratcliffe
15 * Create date: Jan 5, 2008
16 */
17 package uk.me.parabola.imgfmt.app.net;
18
19 import java.util.ArrayList;
20 import java.util.BitSet;
21 import java.util.Comparator;
22 import java.util.HashMap;
23 import java.util.List;
24 import java.util.Map;
25
26 import uk.me.parabola.imgfmt.Utils;
27 import uk.me.parabola.imgfmt.app.BufferedImgFileWriter;
28 import uk.me.parabola.imgfmt.app.ImgFile;
29 import uk.me.parabola.imgfmt.app.ImgFileWriter;
30 import uk.me.parabola.imgfmt.app.Label;
31 import uk.me.parabola.imgfmt.app.lbl.City;
32 import uk.me.parabola.imgfmt.app.lbl.Zip;
33 import uk.me.parabola.imgfmt.app.srt.DoubleSortKey;
34 import uk.me.parabola.imgfmt.app.srt.IntegerSortKey;
35 import uk.me.parabola.imgfmt.app.srt.MultiSortKey;
36 import uk.me.parabola.imgfmt.app.srt.Sort;
37 import uk.me.parabola.imgfmt.app.srt.SortKey;
38 import uk.me.parabola.imgfmt.fs.ImgChannel;
39
40 /**
41 * The NET file. This consists of information about roads. It is not clear
42 * what this file brings on its own (without NOD) but may allow some better
43 * searching, street addresses etc.
44 *
45 * @author Steve Ratcliffe
46 */
47 public class NETFile extends ImgFile {
48 private final NETHeader netHeader = new NETHeader();
49 private List<RoadDef> roads;
50 private Sort sort;
51
52 public NETFile(ImgChannel chan) {
53 setHeader(netHeader);
54 setWriter(new BufferedImgFileWriter(chan, "NET"));
55 position(NETHeader.HEADER_LEN);
56 }
57
58 /**
59 * Write out NET1.
60 * @param numCities The number of cities in the map. Needed for the size of the written fields.
61 * @param numZips The number of zips in the map. Needed for the size of the written fields.
62 */
63 public void write(int numCities, int numZips) {
64 // Write out the actual file body.
65 ImgFileWriter writer = netHeader.makeRoadWriter(getWriter());
66 try {
67 for (RoadDef rd : roads)
68 rd.writeNet1(writer, numCities, numZips);
69
70 } finally {
71 Utils.closeFile(writer);
72 }
73 }
74
75 /**
76 * Final writing out of net sections.
77 *
78 * We patch the NET offsets into the RGN file and create the sorted roads section.
79 *
80 * @param rgn The region file, this has to be patched with the calculated net offsets.
81 */
82 public void writePost(ImgFileWriter rgn) {
83 for (RoadDef rd : roads)
84 rd.writeRgnOffsets(rgn);
85
86 ImgFileWriter writer = netHeader.makeSortedRoadWriter(getWriter());
87 try {
88 List<LabeledRoadDef> labeledRoadDefs = deDupRoads();
89 sortByName(labeledRoadDefs);
90 for (LabeledRoadDef labeledRoadDef : labeledRoadDefs)
91 labeledRoadDef.roadDef.putSortedRoadEntry(writer, labeledRoadDef.label);
92 } finally {
93 Utils.closeFile(writer);
94 }
95
96 getHeader().writeHeader(getWriter());
97 }
98
99 /**
100 * Sort the roads by name and remove duplicates.
101 * <p>
102 * We want a list of roads such that every entry in the list is a different
103 * road. In some areas we have multiple roads with the same name, typically
104 * connected to each other. For each group we find networks of connected
105 * roads. We must store all roads with house numbers, else some numbers are
106 * not found. For networks without any road with numbers we store only one
107 * to reduce NET size.
108 * <p>
109 * Special case: With OSM data and certain styles all normally unnamed roads
110 * get a name describing the type of road, e.g. all ways with tag
111 * highway=footway get the name "fw". This can produce large groups of roads
112 * with equal names.
113 *
114 * @return A list of road labels that identify all the different roads
115 */
116 private List<LabeledRoadDef> deDupRoads() {
117 List<SortKey<LabeledRoadDef>> sortKeys = createSortKeysByNameAndCity();
118 sortKeys.sort(null);
119
120 List<LabeledRoadDef> out = new ArrayList<>(sortKeys.size());
121
122 List<LabeledRoadDef> dupes = new ArrayList<>();
123 SortKey<LabeledRoadDef> lastKey = null;
124
125 // Since they are sorted we can easily remove the duplicates.
126 // The duplicates are saved to the dupes list.
127 for (SortKey<LabeledRoadDef> key : sortKeys) {
128 if (lastKey == null || key.compareTo(lastKey) != 0) {
129 analyseRoadsOfCity(dupes, out);
130 dupes.clear();
131 lastKey = key;
132 }
133 dupes.add(key.getObject());
134 }
135 // Finish off the final set of duplicates.
136 analyseRoadsOfCity(dupes, out);
137 return out;
138 }
139
140 private List<SortKey<LabeledRoadDef>> createSortKeysByNameAndCity() {
141 List<SortKey<LabeledRoadDef>> sortKeys = new ArrayList<>(roads.size());
142
143 for (RoadDef rd : roads) {
144 Label[] labels = rd.getLabels();
145 for (int i = 0; i < labels.length && labels[i] != null; ++i) {
146 Label label = labels[i];
147 if (label.getLength() == 0)
148 continue;
149
150 // Sort by name, city, region/country and subdivision number.
151 LabeledRoadDef lrd = new LabeledRoadDef(label, rd);
152 SortKey<LabeledRoadDef> nameKey = new IntegerSortKey<>(lrd, label.getOffset(), 0);
153
154 // If there is a city add it to the sort.
155 City city = (rd.getCities().isEmpty() ? null : rd.getCities().get(0));
156 SortKey<LabeledRoadDef> cityKey;
157 if (city != null) {
158 int region = city.getRegionNumber();
159 int country = city.getCountryNumber();
160 cityKey = sort.createSortKey(null, city.getLabel(), (region & 0xffff) << 16 | (country & 0xffff));
161 } else {
162 cityKey = sort.createSortKey(null, Label.NULL_OUT_LABEL, 0);
163 }
164
165 // If there is a zip code add it to the sort.
166 Zip zip = (rd.getZips().isEmpty() ? null : rd.getZips().get(0));
167 Label zipLabel = zip == null ? Label.NULL_OUT_LABEL: zip.getLabel();
168 SortKey<LabeledRoadDef> zipKey = sort.createSortKey(null, zipLabel);
169
170 sortKeys.add(new MultiSortKey<>(nameKey, cityKey, zipKey));
171 }
172 }
173 return sortKeys;
174 }
175
176 /**
177 * Sort by partial name first, then by full name.
178 * @param roads list of labeled roads
179 */
180 private void sortByName(List<LabeledRoadDef> roads) {
181 List<SortKey<LabeledRoadDef>> sortKeys = new ArrayList<>(roads.size());
182 Map<Label, byte[]> cachePartial = new HashMap<>();
183 Map<Label, byte[]> cacheFull = new HashMap<>();
184 // we have to use two different caches, as both use the label as key
185 for (LabeledRoadDef lrd : roads) {
186 SortKey<LabeledRoadDef> sk1 = sort.createSortKeyPartial(lrd, lrd.label, 0, cachePartial);
187 SortKey<LabeledRoadDef> sk2 = sort.createSortKey(null, lrd.label, 0, cacheFull);
188 sortKeys.add(new DoubleSortKey<>(sk1, sk2));
189 }
190 sortKeys.sort(null);
191 roads.clear();
192 for (SortKey<LabeledRoadDef> key : sortKeys) {
193 roads.add(key.getObject());
194 }
195 }
196
197 /**
198 * Take a set of roads with the same name/city etc and find sets of roads that do not
199 * connect with each other. One of the members of each set is added to the road list.
200 *
201 * @param in A list of duplicate roads.
202 * @param out The list of sorted roads. Any new road is added to this.
203 */
204 private static void analyseRoadsOfCity(List<LabeledRoadDef> in, List<LabeledRoadDef> out) {
205 // switch out to different routines depending on the input size. A normal number of
206 // roads with the same name in the same city is a few tens.
207 if (in.size() > 200) {
208 analyseRoadsOfCityLarge(in, out);
209 } else {
210 analyseRoadsOfCitySmall(in, out);
211 }
212 }
213
214 /**
215 * Split the input set of roads into disconnected groups and output one member from each group.
216 *
217 * This is done in an accurate manner which is slow for large numbers (eg thousands) of items in the
218 * input.
219 *
220 * @param in Input set of roads with the same name and city.
221 * @param out List to add the discovered groups.
222 */
223 private static void analyseRoadsOfCitySmall(List<LabeledRoadDef> in, List<LabeledRoadDef> out) {
224 if (in.size() < 2) {
225 out.addAll(in);
226 } else {
227 // sort so that roads with numbers and those with more than one city appear first
228 in.sort((o1, o2) -> Boolean.compare(needed(o2), needed(o1)));
229
230 // write all roads with numbers or multiple cities so that they are found in address search
231 int posOther = -1;
232 for (int i = 0; i < in.size(); i++) {
233 if (needed(in.get(i))) {
234 out.add(in.get(i));
235 } else {
236 posOther = i;
237 break;
238 }
239 }
240 if (posOther >= 0) {
241 findRoadNetworks(in, posOther, out);
242 }
243 }
244 }
245
246 /**
247 * Split the input set of roads into disconnected groups and output one member from each group.
248 *
249 * This is an modified algorithm for large numbers in the input set (eg thousands).
250 * First sort into groups by subdivision and then call {@link #analyseRoadsOfCitySmall} on each
251 * one. Since roads in the same subdivision are near each other this finds most connected roads, but
252 * since there is a maximum number of roads in a subdivision, the test can be done very quickly.
253 * You will get a few extra duplicate entries in the index.
254 *
255 * In normal cases this routine gives almost the same results as {@link #analyseRoadsOfCitySmall}.
256 *
257 * @param in Input set of roads with the same name.
258 * @param out List to add the discovered groups.
259 */
260 private static void analyseRoadsOfCityLarge(List<LabeledRoadDef> in, List<LabeledRoadDef> out) {
261 in.sort(Comparator.comparingInt(lr -> lr.roadDef.getStartSubdivNumber()));
262
263 int lastDiv = 0;
264 List<LabeledRoadDef> dupes = new ArrayList<>();
265 for (LabeledRoadDef lrd : in) {
266 int sd = lrd.roadDef.getStartSubdivNumber();
267 if (sd != lastDiv) {
268 analyseRoadsOfCitySmall(dupes, out);
269 dupes.clear();
270 lastDiv = sd;
271 }
272 dupes.add(lrd);
273 }
274 // the rest
275 analyseRoadsOfCitySmall(dupes, out);
276 }
277
278 private static boolean needed (LabeledRoadDef lr) {
279 return lr.roadDef.hasHouseNumbers() || lr.roadDef.getCities().size() > 1;
280 }
281
282 /**
283 * Find road networks which are not connected to the roads with numbers, write one of each.
284 * @param in Input set of roads with the same name, sorted so that roads with numbers appear first
285 * @param posOther position of first road without numbers or multiple cities in input
286 * @param out List to add the discovered groups with roads not connected to the roads with numbers
287 */
288 private static void findRoadNetworks(List<LabeledRoadDef> in, int posOther, List<LabeledRoadDef> out) {
289 // Each road starts out with a different group number
290 int inSize = in.size();
291 int[] groups = new int[inSize];
292 for (int i = 0; i < groups.length; i++)
293 groups[i] = i;
294
295 // cache for results of RoadDef#connectedTo(RoadDef) where result was false.
296 BitSet unconnected = new BitSet(inSize * inSize);
297
298 // Go through pairs of roads, any that are connected we mark with the same (lowest) group number.
299 boolean done;
300 do {
301 done = true;
302 for (int current = 0; current < groups.length; current++) {
303 RoadDef first = in.get(current).roadDef;
304
305 for (int i = current + 1; i < groups.length; i++) {
306 // If the groups are already the same or roads are known to be unconnected, then no need to test
307 if (groups[current] != groups[i] && !unconnected.get(current * inSize + i)) {
308 // we have to do the costly connectedTo() test
309 if (first.connectedTo(in.get(i).roadDef)) {
310 groups[current] = groups[i] = Math.min(groups[current], groups[i]);
311 done = false;
312 } else {
313 unconnected.set(current * inSize + i);
314 }
315 }
316 }
317 }
318 } while (!done);
319
320 // Output the first road in each group that was not yet added
321 int last = posOther - 1;
322 for (int i = posOther; i < groups.length; i++) {
323 if (groups[i] > last) {
324 LabeledRoadDef lrd = in.get(i);
325 out.add(lrd);
326 last = groups[i];
327 }
328 }
329 }
330
331 public void setNetwork(List<RoadDef> roads) {
332 this.roads = roads;
333 }
334
335 public void setSort(Sort sort) {
336 this.sort = sort;
337 }
338
339 /**
340 * A road can have several names. Keep an association between a road def
341 * and one of its names.
342 */
343 class LabeledRoadDef {
344 private final Label label;
345 private final RoadDef roadDef;
346
347 LabeledRoadDef(Label label, RoadDef roadDef) {
348 this.label = label;
349 this.roadDef = roadDef;
350 }
351 }
352 }