source: josm/trunk/test/unit/org/openstreetmap/josm/data/projection/ProjectionRefTest.java@ 13703

Last change on this file since 13703 was 13703, checked in by Don-vip, 6 years ago

see #16129 - escape quotes on Windows

  • Property svn:eol-style set to native
File size: 16.6 KB
Line 
1// License: GPL. For details, see LICENSE file.
2package org.openstreetmap.josm.data.projection;
3
4import java.io.BufferedReader;
5import java.io.BufferedWriter;
6import java.io.File;
7import java.io.FileInputStream;
8import java.io.FileOutputStream;
9import java.io.IOException;
10import java.io.InputStream;
11import java.io.InputStreamReader;
12import java.io.OutputStream;
13import java.io.OutputStreamWriter;
14import java.nio.charset.StandardCharsets;
15import java.security.SecureRandom;
16import java.util.ArrayList;
17import java.util.Arrays;
18import java.util.Collection;
19import java.util.HashMap;
20import java.util.HashSet;
21import java.util.LinkedHashSet;
22import java.util.List;
23import java.util.Map;
24import java.util.Objects;
25import java.util.Random;
26import java.util.Set;
27import java.util.TreeMap;
28import java.util.TreeSet;
29import java.util.regex.Matcher;
30import java.util.regex.Pattern;
31
32import org.junit.Assert;
33import org.junit.Rule;
34import org.junit.Test;
35import org.openstreetmap.josm.Main;
36import org.openstreetmap.josm.data.Bounds;
37import org.openstreetmap.josm.data.coor.EastNorth;
38import org.openstreetmap.josm.data.coor.LatLon;
39import org.openstreetmap.josm.gui.preferences.projection.CodeProjectionChoice;
40import org.openstreetmap.josm.testutils.JOSMTestRules;
41import org.openstreetmap.josm.tools.Pair;
42import org.openstreetmap.josm.tools.Utils;
43
44import edu.umd.cs.findbugs.annotations.SuppressFBWarnings;
45
46/**
47 * Test projections using reference data from external program.
48 *
49 * To update the reference data file <code>data_nodist/projection/projection-reference-data</code>,
50 * run the main method of this class. For this, you need to have the cs2cs
51 * program from the proj.4 library in path (or use <code>CS2CS_EXE</code> to set
52 * the full path of the executable). Make sure the required *.gsb grid files
53 * can be accessed, i.e. copy them from <code>data_nodist/projection</code> to <code>/usr/share/proj</code> or
54 * wherever cs2cs expects them to be placed.
55 *
56 * The input parameter for the external library is <em>not</em> the projection code
57 * (e.g. "EPSG:25828"), but the entire definition, (e.g. "+proj=utm +zone=28 +ellps=GRS80 +nadgrids=null").
58 * This means the test does not verify our definitions, but the correctness
59 * of the algorithm, given a certain definition.
60 */
61public class ProjectionRefTest {
62
63 private static final String CS2CS_EXE = "cs2cs";
64
65 private static final String REFERENCE_DATA_FILE = "data_nodist/projection/projection-reference-data";
66 private static final String PROJ_LIB_DIR = "data_nodist/projection";
67
68 private static final int MAX_LENGTH = 524288;
69
70 private static class RefEntry {
71 String code;
72 String def;
73 List<Pair<LatLon, EastNorth>> data;
74
75 RefEntry(String code, String def) {
76 this.code = code;
77 this.def = def;
78 this.data = new ArrayList<>();
79 }
80 }
81
82 static Random rand = new SecureRandom();
83
84 static boolean debug;
85 static List<String> forcedCodes;
86
87 /**
88 * Setup test.
89 */
90 @Rule
91 @SuppressFBWarnings(value = "URF_UNREAD_PUBLIC_OR_PROTECTED_FIELD")
92 public JOSMTestRules test = new JOSMTestRules().platform().projectionNadGrids().timeout(90_000);
93
94 /**
95 * Program entry point.
96 * @param args optional comma-separated list of projections to update. If set, only these projections will be updated
97 * @throws IOException in case of I/O error
98 */
99 public static void main(String[] args) throws IOException {
100 if (args.length > 0) {
101 debug = "debug".equals(args[0]);
102 if (args[args.length - 1].startsWith("EPSG:")) {
103 forcedCodes = Arrays.asList(args[args.length - 1].split(","));
104 }
105 }
106 Main.determinePlatformHook();
107 Collection<RefEntry> refs = readData();
108 refs = updateData(refs);
109 writeData(refs);
110 }
111
112 /**
113 * Reads data from the reference file.
114 * @return the data
115 * @throws IOException if any I/O error occurs
116 */
117 private static Collection<RefEntry> readData() throws IOException {
118 Collection<RefEntry> result = new ArrayList<>();
119 if (!new File(REFERENCE_DATA_FILE).exists()) {
120 System.err.println("Warning: refrence file does not exist.");
121 return result;
122 }
123 try (BufferedReader in = new BufferedReader(new InputStreamReader(
124 new FileInputStream(REFERENCE_DATA_FILE), StandardCharsets.UTF_8))) {
125 String line;
126 Pattern projPattern = Pattern.compile("<(.+?)>(.*)<>");
127 RefEntry curEntry = null;
128 while ((line = in.readLine()) != null) {
129 if (line.startsWith("#") || line.trim().isEmpty()) {
130 continue;
131 }
132 if (line.startsWith("<")) {
133 Matcher m = projPattern.matcher(line);
134 if (!m.matches()) {
135 Assert.fail("unable to parse line: " + line);
136 }
137 String code = m.group(1);
138 String def = m.group(2).trim();
139 curEntry = new RefEntry(code, def);
140 result.add(curEntry);
141 } else if (curEntry != null) {
142 String[] f = line.trim().split(",");
143 double lon = Double.parseDouble(f[0]);
144 double lat = Double.parseDouble(f[1]);
145 double east = Double.parseDouble(f[2]);
146 double north = Double.parseDouble(f[3]);
147 curEntry.data.add(Pair.create(new LatLon(lat, lon), new EastNorth(east, north)));
148 }
149 }
150 }
151 return result;
152 }
153
154 /**
155 * Generates new reference data by calling external program cs2cs.
156 *
157 * Old data is kept, as long as the projection definition is still the same.
158 *
159 * @param refs old data
160 * @return updated data
161 */
162 private static Collection<RefEntry> updateData(Collection<RefEntry> refs) {
163 Set<String> failed = new LinkedHashSet<>();
164 final int N_POINTS = 8;
165
166 Map<String, RefEntry> refsMap = new HashMap<>();
167 for (RefEntry ref : refs) {
168 refsMap.put(ref.code, ref);
169 }
170
171 List<RefEntry> refsNew = new ArrayList<>();
172
173 Set<String> codes = new TreeSet<>(new CodeProjectionChoice.CodeComparator());
174 codes.addAll(Projections.getAllProjectionCodes());
175 for (String code : codes) {
176 String def = Projections.getInit(code);
177
178 RefEntry ref = new RefEntry(code, def);
179 RefEntry oldRef = refsMap.get(code);
180
181 if (oldRef != null && Objects.equals(def, oldRef.def)) {
182 for (int i = 0; i < N_POINTS && i < oldRef.data.size(); i++) {
183 ref.data.add(oldRef.data.get(i));
184 }
185 }
186 boolean forced = forcedCodes != null && forcedCodes.contains(code);
187 if (forced || ref.data.size() < N_POINTS) {
188 System.out.print(code);
189 System.out.flush();
190 Projection proj = Projections.getProjectionByCode(code);
191 Bounds b = proj.getWorldBoundsLatLon();
192 for (int i = forced ? 0 : ref.data.size(); i < N_POINTS; i++) {
193 System.out.print(".");
194 System.out.flush();
195 LatLon ll = forced ? ref.data.get(i).a : getRandom(b);
196 EastNorth en = latlon2eastNorthProj4(def, ll);
197 if (en != null) {
198 if (forced) {
199 ref.data.get(i).b = en;
200 } else {
201 ref.data.add(Pair.create(ll, en));
202 }
203 } else {
204 System.err.println("Warning: cannot convert "+code+" at "+ll);
205 failed.add(code);
206 }
207 }
208 System.out.println();
209 }
210 refsNew.add(ref);
211 }
212 if (!failed.isEmpty()) {
213 System.err.println("Error: the following " + failed.size() + " entries had errors: " + failed);
214 }
215 return refsNew;
216 }
217
218 /**
219 * Get random LatLon value within the bounds.
220 * @param b the bounds
221 * @return random LatLon value within the bounds
222 */
223 private static LatLon getRandom(Bounds b) {
224 double lat, lon;
225 lat = b.getMin().lat() + rand.nextDouble() * (b.getMax().lat() - b.getMin().lat());
226 double minlon = b.getMinLon();
227 double maxlon = b.getMaxLon();
228 if (b.crosses180thMeridian()) {
229 maxlon += 360;
230 }
231 lon = minlon + rand.nextDouble() * (maxlon - minlon);
232 lon = LatLon.toIntervalLon(lon);
233 return new LatLon(lat, lon);
234 }
235
236 /**
237 * Run external cs2cs command from the PROJ.4 library to convert lat/lon to east/north value.
238 * @param def the proj.4 projection definition string
239 * @param ll the LatLon
240 * @return projected EastNorth or null in case of error
241 */
242 @SuppressFBWarnings(value = "COMMAND_INJECTION")
243 private static EastNorth latlon2eastNorthProj4(String def, LatLon ll) {
244 List<String> args = new ArrayList<>();
245 args.add(CS2CS_EXE);
246 args.addAll(Arrays.asList("-f %.9f +proj=longlat +datum=WGS84 +to".split(" ")));
247 // proj.4 cannot read our ntf_r93_b.gsb file
248 // possibly because it is big endian. Use equivalent
249 // little endian file shipped with proj.4.
250 // see http://geodesie.ign.fr/contenu/fichiers/documentation/algorithmes/notice/NT111_V1_HARMEL_TransfoNTF-RGF93_FormatGrilleNTV2.pdf
251 def = def.replace("ntf_r93_b.gsb", "ntf_r93.gsb");
252 if (Main.isPlatformWindows()) {
253 def = def.replace("'", "\\'").replace("\"", "\\\"");
254 }
255 args.addAll(Arrays.asList(def.split(" ")));
256 ProcessBuilder pb = new ProcessBuilder(args);
257 pb.environment().put("PROJ_LIB", new File(PROJ_LIB_DIR).getAbsolutePath());
258
259 String output = "";
260 try {
261 Process process = pb.start();
262 OutputStream stdin = process.getOutputStream();
263 InputStream stdout = process.getInputStream();
264 InputStream stderr = process.getErrorStream();
265 try (BufferedWriter writer = new BufferedWriter(new OutputStreamWriter(stdin, StandardCharsets.UTF_8))) {
266 String s = String.format("%s %s%n",
267 LatLon.cDdHighPecisionFormatter.format(ll.lon()),
268 LatLon.cDdHighPecisionFormatter.format(ll.lat()));
269 if (debug) {
270 System.out.println("\n" + String.join(" ", args) + "\n" + s);
271 }
272 writer.write(s);
273 }
274 try (BufferedReader reader = new BufferedReader(new InputStreamReader(stdout, StandardCharsets.UTF_8))) {
275 String line;
276 while (null != (line = reader.readLine())) {
277 if (debug) {
278 System.out.println("> " + line);
279 }
280 output = line;
281 }
282 }
283 try (BufferedReader reader = new BufferedReader(new InputStreamReader(stderr, StandardCharsets.UTF_8))) {
284 String line;
285 while (null != (line = reader.readLine())) {
286 System.err.println("! " + line);
287 }
288 }
289 } catch (IOException e) {
290 System.err.println("Error: Running external command failed: " + e + "\nCommand was: "+Utils.join(" ", args));
291 return null;
292 }
293 Pattern p = Pattern.compile("(\\S+)\\s+(\\S+)\\s.*");
294 Matcher m = p.matcher(output);
295 if (!m.matches()) {
296 System.err.println("Error: Cannot parse cs2cs output: '" + output + "'");
297 return null;
298 }
299 String es = m.group(1);
300 String ns = m.group(2);
301 if ("*".equals(es) || "*".equals(ns)) {
302 System.err.println("Error: cs2cs is unable to convert coordinates.");
303 return null;
304 }
305 try {
306 return new EastNorth(Double.parseDouble(es), Double.parseDouble(ns));
307 } catch (NumberFormatException nfe) {
308 System.err.println("Error: Cannot parse cs2cs output: '" + es + "', '" + ns + "'" + "\nCommand was: "+Utils.join(" ", args));
309 return null;
310 }
311 }
312
313 /**
314 * Writes data to file.
315 * @param refs the data
316 * @throws IOException if any I/O error occurs
317 */
318 private static void writeData(Collection<RefEntry> refs) throws IOException {
319 Map<String, RefEntry> refsMap = new TreeMap<>(new CodeProjectionChoice.CodeComparator());
320 for (RefEntry ref : refs) {
321 refsMap.put(ref.code, ref);
322 }
323 try (BufferedWriter out = new BufferedWriter(new OutputStreamWriter(
324 new FileOutputStream(REFERENCE_DATA_FILE), StandardCharsets.UTF_8))) {
325 for (Map.Entry<String, RefEntry> e : refsMap.entrySet()) {
326 RefEntry ref = e.getValue();
327 out.write("<" + ref.code + "> " + ref.def + " <>\n");
328 for (Pair<LatLon, EastNorth> p : ref.data) {
329 LatLon ll = p.a;
330 EastNorth en = p.b;
331 out.write(" " + ll.lon() + "," + ll.lat() + "," + en.east() + "," + en.north() + "\n");
332 }
333 }
334 }
335 }
336
337 /**
338 * Test projections.
339 * @throws IOException if any I/O error occurs
340 */
341 @Test
342 public void testProjections() throws IOException {
343 StringBuilder fail = new StringBuilder();
344 Set<String> allCodes = new HashSet<>(Projections.getAllProjectionCodes());
345 Collection<RefEntry> refs = readData();
346
347 for (RefEntry ref : refs) {
348 String def0 = Projections.getInit(ref.code);
349 if (def0 == null) {
350 Assert.fail("unknown code: "+ref.code);
351 }
352 if (!ref.def.equals(def0)) {
353 fail.append("definitions for ").append(ref.code).append(" do not match\n");
354 } else {
355 Projection proj = Projections.getProjectionByCode(ref.code);
356 double scale = ((CustomProjection) proj).getToMeter();
357 for (Pair<LatLon, EastNorth> p : ref.data) {
358 LatLon ll = p.a;
359 EastNorth enRef = p.b;
360 enRef = new EastNorth(enRef.east() * scale, enRef.north() * scale); // convert to meter
361
362 EastNorth en = proj.latlon2eastNorth(ll);
363 if (proj.switchXY()) {
364 en = new EastNorth(en.north(), en.east());
365 }
366 en = new EastNorth(en.east() * scale, en.north() * scale); // convert to meter
367 final double EPSILON_EN = 1e-2; // 1cm
368 if (!isEqual(enRef, en, EPSILON_EN, true)) {
369 String errorEN = String.format("%s (%s): Projecting latlon(%s,%s):%n" +
370 " expected: eastnorth(%s,%s),%n" +
371 " but got: eastnorth(%s,%s)!%n",
372 proj.toString(), proj.toCode(), ll.lat(), ll.lon(), enRef.east(), enRef.north(), en.east(), en.north());
373 fail.append(errorEN);
374 }
375 }
376 }
377 allCodes.remove(ref.code);
378 }
379 if (!allCodes.isEmpty()) {
380 Assert.fail("no reference data for following projections: "+allCodes);
381 }
382 if (fail.length() > 0) {
383 String s = fail.toString();
384 if (s.length() > MAX_LENGTH) {
385 // SonarQube/Surefire can't parse XML attributes longer than 524288 characters
386 s = s.substring(0, MAX_LENGTH - 4) + "...";
387 }
388 System.err.println(s);
389 throw new AssertionError(s);
390 }
391 }
392
393 /**
394 * Check if two EastNorth objects are equal.
395 * @param en1 first value
396 * @param en2 second value
397 * @param epsilon allowed tolerance
398 * @param abs true if absolute value is compared; this is done as long as
399 * advanced axis configuration is not supported in JOSM
400 * @return true if both are considered equal
401 */
402 private static boolean isEqual(EastNorth en1, EastNorth en2, double epsilon, boolean abs) {
403 double east1 = en1.east();
404 double north1 = en1.north();
405 double east2 = en2.east();
406 double north2 = en2.north();
407 if (abs) {
408 east1 = Math.abs(east1);
409 north1 = Math.abs(north1);
410 east2 = Math.abs(east2);
411 north2 = Math.abs(north2);
412 }
413 return Math.abs(east1 - east2) < epsilon && Math.abs(north1 - north2) < epsilon;
414 }
415}
Note: See TracBrowser for help on using the repository browser.