Debian Codegraph @

src/footleg/cavesurvey/tools/UtilityFunctions.java

raw symbols SCIP
1 /**
2 * Copyright (C) 2009-2017 Paul Fretwell - aka 'Footleg' ([email protected])
3 *
4 * This file is part of Cave Converter.
5 *
6 * Cave Converter is free software: you can redistribute it and/or modify
7 * it under the terms of the GNU General Public License as published by
8 * the Free Software Foundation, either version 3 of the License, or
9 * (at your option) any later version.
10 *
11 * Cave Converter is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with Cave Converter. If not, see <http://www.gnu.org/licenses/>.
18 */
19 package footleg.cavesurvey.tools;
20
21 import java.io.BufferedReader;
22 import java.io.BufferedWriter;
23 import java.io.File;
24 import java.io.FileInputStream;
25 import java.io.FileNotFoundException;
26 import java.io.FileOutputStream;
27 import java.io.IOException;
28 import java.io.InputStreamReader;
29 import java.io.OutputStreamWriter;
30 import java.io.Writer;
31 import java.text.ParseException;
32 import java.text.SimpleDateFormat;
33 import java.util.ArrayList;
34 import java.util.Arrays;
35 import java.util.Calendar;
36 import java.util.Date;
37 import java.util.Iterator;
38 import java.util.List;
39 import java.util.ListIterator;
40 import java.util.TimeZone;
41
42 import footleg.cavesurvey.converter.CaveConverter.BearingUnit;
43 import footleg.cavesurvey.converter.CaveConverter.GradientUnit;
44 import footleg.cavesurvey.converter.CaveConverter.LengthUnit;
45 import footleg.cavesurvey.converter.CaveConverter.SurveyDataInputFormats;
46 import footleg.cavesurvey.converter.CaveConverter.SurveyDataOutputFormats;
47 import footleg.cavesurvey.converter.Logger;
48 import footleg.cavesurvey.data.model.CaveSurvey;
49 import footleg.cavesurvey.data.model.Equate;
50 import footleg.cavesurvey.data.model.SurveyLeg;
51 import footleg.cavesurvey.data.model.SurveySeries;
52 import footleg.cavesurvey.data.model.SurveyStation;
53
54 /**
55 * Utility class for functions shared with other code in application.
56 *
57 * @author Footleg
58 * @version 2017.01.09 (ISO 8601 YYYY.MM.DD)
59 * @since 1.6 (The Java version used)
60 */
61 public final class UtilityFunctions {
62 private static final double feetPerMetre = 3.280839895;
63
64 private static final char compassFormat = 'c';
65 private static final char dxfFormat = 'd';
66 private static final char pocketTopoFormat = 'p';
67 private static final char survexFormat = 's';
68 private static final char toporobotFormat = 't';
69
70 public static final String POCKETTOPO_DATE_FORMAT = "yyyy/MM/dd";
71 public static final String SURVEXDATE_FORMAT = "yyyy.MM.dd";
72
73 /**
74 * Convert cave survey data input format codes to enum values
75 *
76 * @param letterCode Single character indicating a cave survey data format
77 * @return Survey format value which the given letter code represents
78 * @throws ParseException raised if the letter code character does not match a supported survey input format
79 */
80 public static SurveyDataInputFormats inputDataFormatFromLetterCode( char letterCode ) throws ParseException {
81 SurveyDataInputFormats format = null;
82
83 switch (letterCode) {
84 case compassFormat:
85 format = SurveyDataInputFormats.Compass;
86 break;
87 case dxfFormat:
88 format = SurveyDataInputFormats.DXF;
89 break;
90 case pocketTopoFormat:
91 format = SurveyDataInputFormats.PocketTopo;
92 break;
93 case survexFormat:
94 format = SurveyDataInputFormats.Survex;
95 break;
96 default:
97 //Error: Unknown format code
98 ParseException e = new ParseException("Unknown data format letter code: " +
99 letterCode + "'.", 1);
100 throw e;
101 }
102
103 return format;
104 }
105
106 /**
107 * Convert cave survey data output format codes to enum values
108 *
109 * @param letterCode Single character indicating a cave survey data format
110 * @return Survey format value which the given letter code represents
111 * @throws ParseException raised if the letter code character does not match a supported survey output format
112 */
113 public static SurveyDataOutputFormats outputDataFormatFromLetterCode( char letterCode ) throws ParseException {
114 SurveyDataOutputFormats format = null;
115
116 switch (letterCode) {
117 case survexFormat:
118 format = SurveyDataOutputFormats.Survex;
119 break;
120 case toporobotFormat:
121 format = SurveyDataOutputFormats.Toporobot;
122 break;
123 default:
124 //Error: Unknown format code
125 ParseException e = new ParseException("Unknown data format letter code: " +
126 letterCode + "'.", 1);
127 throw e;
128 }
129
130 return format;
131 }
132
133
134 /**
135 * Math function to calculate the average compass bearing from a set
136 * of compass readings. The calculation used determines the sum of the
137 * vectors. This is the equivalent of converting the bearings from unit
138 * vectors each with a polar coordinate to x and y components, averaging
139 * the x and y components to produce a resulting vector, and then taking
140 * the polar coordinate bearing of that vector as the result. For a pair
141 * of compass readings this average represents the mean direction of the
142 * two survey legs. For a set of two or more readings it represents to
143 * mean direction of all the bearings giving them equal weight. This is
144 * different to the numerical average of several repeated readings of an
145 * instrument (like 3 DistoX shots from PocketTopo), but the results are
146 * the same (at a precision of two decimal places) for either averaging
147 * method for sets of bearings with no more than 2 degrees variation
148 * between the readings.
149 *
150 * @param bearings Array of compass bearings to calculate average from
151 * @return Mean compass bearing in range 0-360 degrees
152 */
153 public static double averageCompassBearings( double[] bearings ) {
154 double meanBearing = 0.0;
155
156 double accumulatorCos = 0.0;
157 double accumulatorSin = 0.0;
158
159 //Loop through all bearings
160 for ( int bearingIdx = 0; bearingIdx < bearings.length; bearingIdx++ ) {
161 //Convert bearing to radians
162 Double bearing = Math.toRadians( bearings[bearingIdx] );
163
164 //Accumulate sum of sin and cos of bearings
165 accumulatorCos += Math.cos(bearing);
166 accumulatorSin += Math.sin(bearing);
167 }
168
169 double average_angle_atan2 = Math.atan2(accumulatorSin, accumulatorCos);
170 meanBearing = Math.toDegrees(average_angle_atan2);
171
172 //Adjust bearing to within range of 0-360 degrees
173 return adjustBearingWithinDegreesRange( meanBearing, 0, 360 );
174 }
175
176 /**
177 * Adjusts a bearing in degrees to a value within the range given
178 * @param bearing The bearing to adjust
179 * @param min The minimum value to allow
180 * @param max The lowest value to adjust down (adjusted bearing must be less than this value)
181 * @return Bearing adjusted to within range given
182 */
183 public static double adjustBearingWithinDegreesRange(double bearing, double min, double max) {
184 double adjustedBearing = bearing;
185
186 while ( adjustedBearing < min ) {
187 adjustedBearing += 360;
188 }
189 while ( adjustedBearing >= max ) {
190 adjustedBearing -= 360;
191 }
192
193 return adjustedBearing;
194 }
195
196 /**
197 * Math function to calculate the difference between two compass bearings
198 * @param angle1 First compass bearing
199 * @param angle2 Second compass bearing
200 * @return difference in degrees between the two bearings
201 */
202 public static double bearingDifferenceDegrees( double angle1, double angle2) {
203 double dif = Math.abs( angle1 - angle2 ) % 360;
204
205 if (dif > 180)
206 dif = 360 - dif;
207 return dif;
208 }
209
210 /**
211 * Creates a new survey station for a series using a given name for the station.
212 *
213 * The name is mapped to a numerical station id using the series, and the station
214 * is created with that id. If the name is already in use then the id will be the
215 * same id as that used for the matching station in the series.
216 *
217 * @param stnName The name to give the new survey station
218 * @param series The survey series which this station is going to be added to
219 * @return New survey station object with an id mapped to the name for this series
220 */
221 public static SurveyStation createStationFromNameForSeries( String stnName, SurveySeries series ) {
222 SurveyStation stn = new SurveyStation( 0 );
223 stn.setName( stnName );
224 series.setStationIdFromName(stn);
225
226 return stn;
227 }
228
229 /**
230 * Date string parsing function to return a date type from a text representation of the date.
231 *
232 * @param dateString Text representation of a date
233 * @param dateFormat Defines the format for the text representation of the date
234 * @throws ParseException if the string is not a valid date
235 * @return The date parsed from the string parameter
236 */
237 public static Date stringToDate( String dateString, String dateFormat ) throws ParseException {
238 Date dateVal;
239
240 SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
241 sdf.setTimeZone(TimeZone.getDefault());
242
243 dateVal = sdf.parse(dateString);
244
245 return dateVal;
246 }
247
248 /**
249 * Method which generates a string representing a given date.
250 *
251 * @param date The date to be converted to text
252 * @param dateFormat Defines the format for the text representation of the date
253 * @return Text representation of the date in the format requested
254 */
255 public static String dateToString( Date date, String dateFormat ) {
256 SimpleDateFormat sdf = new SimpleDateFormat(dateFormat);
257 sdf.setTimeZone(TimeZone.getDefault());
258
259 return sdf.format( date );
260 }
261
262 /**
263 * Generates a string representing the date on the day the method
264 * is called.
265 *
266 * @param dateFormat Defines the format for the text representation of the date
267 * @return Text representation of today's date in the format requested
268 */
269 public static String todaysDateAsString( String dateFormat ) {
270 Calendar cal = Calendar.getInstance(TimeZone.getDefault());
271 Date dateTimeNow = cal.getTime();
272
273 return dateToString( dateTimeNow, dateFormat );
274 }
275
276 /**
277 * Converts a string list into a string of items from the list
278 * separated with a given string
279 *
280 * @param list String list of items to convert to a string
281 * @param separator String to separate items with in the output
282 * @return Dot separated string of the items from the input list
283 */
284 public static String stringListToDotSeparatedString( List<String> list, String separator) {
285 String items = "";
286
287 ListIterator<String> primaryIterator = list.listIterator();
288 if ( primaryIterator.hasNext() ) {
289 //First item
290 items += primaryIterator.next();
291 }
292 while ( primaryIterator.hasNext() ) {
293 items += separator + primaryIterator.next();
294 }
295
296 return items;
297 }
298
299 /**
300 * Splits a string of data items separated by whitespace into an array of
301 * individual data items. Tab and space characters are treated as
302 * separators unless enclosed in quotes.
303 *
304 * @param dataString String of data items separated by white space
305 * @return Array of data items extracted from the input data string
306 */
307 public static List<String> parseDataStringIntoDataItems( String dataString ) {
308 List<String> dataItems = new ArrayList<String>();
309 String currItem = "";
310 boolean insideQuotes = false;
311
312 //Parse input string character by character
313 for (int i = 0; i < dataString.length(); i++) {
314 //Check if inside quotes
315 if ( insideQuotes ) {
316 //Check for ending quotes
317 if ( dataString.charAt(i) == '\"' ) {
318 //End of item, so update array with data for this item
319 dataItems.add( currItem );
320 //Reset for next item
321 currItem = "";
322 insideQuotes = false;
323 }
324 else {
325 //Non-quote, and non-whitespace character, so add to end of current item
326 currItem += dataString.charAt(i);
327 }
328 }
329 else if ( dataString.charAt(i) == '\"' ) {
330 //Found start of new quoted data item
331 insideQuotes = true;
332 }
333 else if ( dataString.charAt(i) == ' ' || dataString.charAt(i) == '\t' ) {
334 //Found whitespace, check if this is the end of a data item
335 if ( currItem.length() > 0 ) {
336 //End of item, so update array with data for this item
337 dataItems.add( currItem );
338 //Reset for next item
339 currItem = "";
340 }
341 }
342 else {
343 //Non-quote, and non-whitespace character, so add to end of current item
344 currItem += dataString.charAt(i);
345 }
346 }
347
348 //End of data, check if the last item was added
349 if ( currItem.length() > 0 ) {
350 //Last item, so update array with data for this item
351 dataItems.add( currItem );
352 }
353
354 return dataItems;
355 }
356
357 /**
358 * Splits a comment string into comment lines, splitting at line separator
359 * characters and removing enclosing quotes.
360 *
361 * @param comment Comment string to be parsed
362 * @return Array of comment line from the input comment string
363 */
364 public static String[] parseTripComment( String comment ) {
365 String dataString = comment.replace("\\r", "\r");
366 String[] dataItems = dataString.split("\r");
367
368 return dataItems;
369 }
370
371 /**
372 * Converts a list of equates gathered during file parsing into series links in the survey.
373 *
374 * A helper function shared by some of the data readers, which generate a list
375 * of equate classes from equivalent stations in the input files. This method
376 * matches these equates to series in the survey, and creates a series link in the
377 * appropriate series to link the series to another series in the survey.
378 *
379 * @param equates ArrayList of equates to be processed
380 * @param allSeries The cave survey to add the series links into
381 */
382 public static void processEquates( List<Equate> equates, CaveSurvey allSeries ) {
383 //Process each of the equates in turn
384 Iterator<Equate> equateIterator = equates.listIterator();
385 while ( equateIterator.hasNext() ) {
386 Equate equate = equateIterator.next();
387
388 //Find the series path in common between the equates and determine which is the inner series if nested
389 String innerSeries;
390 String outerSeries;
391 String innerSeriesStn;
392 String outerSeriesStn;
393
394 if ( equate.getSeries1().length() > equate.getSeries2().length() ) {
395 //First series is inner series to second series
396 outerSeries = equate.getSeries2();
397 outerSeriesStn = equate.getStn2();
398 innerSeries = equate.getSeries1();
399 innerSeriesStn = equate.getStn1();
400 }
401 else {
402 //First series is same as or outer series to second series
403 outerSeries = equate.getSeries1();
404 outerSeriesStn = equate.getStn1();
405 innerSeries = equate.getSeries2();
406 innerSeriesStn = equate.getStn2();
407 }
408
409 //Find parent series, and remove path to it from the two series paths
410 List<String> outerHierarchy = new ArrayList<String>(Arrays.asList(outerSeries.split("[.]")));
411 List<String> innerHierarchy = new ArrayList<String>(Arrays.asList(innerSeries.split("[.]")));
412 List<String> parentHierarchy = new ArrayList<String>();
413
414 boolean matching = true;
415 while ( matching && (outerHierarchy.size() > 0 ) ) {
416 if (outerHierarchy.get(0).equalsIgnoreCase( innerHierarchy.get(0) ) ) {
417 //Common series name to both series in equate, so move to parent
418 parentHierarchy.add( outerHierarchy.remove(0) );
419 innerHierarchy.remove(0);
420 }
421 else {
422 matching = false;
423 }
424 }
425
426 //Find innermost series which is a parent of the equates series
427 SurveySeries liveSeries = null;
428 // boolean dealtWithUnmatchedSeries = false;
429
430 if ( parentHierarchy.size() > 0 ) {
431 //Iterate over series names in parent path looking for matching inner most series
432 ListIterator<String> pathIterator = parentHierarchy.listIterator();
433 String liveName = pathIterator.next();
434
435 //First find the outer series for the outer path name
436 ListIterator<SurveySeries> primaryIterator = allSeries.listIterator();
437 while ( primaryIterator.hasNext() ) {
438 SurveySeries outermostSeries = primaryIterator.next();
439 if ( outermostSeries.getSeriesName().equalsIgnoreCase( liveName ) ) {
440 //Go to next level in path
441 liveSeries = outermostSeries;
442 break;
443 }
444 else {
445 //Not found, so keep looking
446 matching = false; //Just here to allow breakpoint debugging
447 }
448 }
449
450 //Did we find outer series?
451 if ( liveSeries != null ) {
452 //Now iterate over path looking for matching inner series for each level
453 if ( pathIterator.hasNext() ) {
454 liveSeries = findInnerSeriesByName( liveSeries, pathIterator);
455 }
456
457 //If we got here without any exceptions being thrown then we should have the correct parent series
458 matching = true; //Just here to allow breakpoint debugging
459
460 }
461 else {
462 //Failed to find matching outer series
463 throw new RuntimeException( "Equate series outer name '" +
464 liveName + "' did not match any cave name." );
465 }
466
467 }
468 else {
469 //No parent in common which indicates that the link is invalid as one of
470 //the series is not in the cave survey at all.
471 //TODO Fix this for pockettopo imports where only part of a cave is present. Need a dummy link in this case.
472 //This is no longer where the PocketTopo files raise an error.
473 throw new RuntimeException( "Series in equate did not match any series name. Series1: '" +
474 equate.getSeries1() + "'. Series2: '" + equate.getSeries2() + "'." );
475 //Check that at least one of the series matches a series name
476 // int series1Idx = lookupSeriesIndexFromSeriesName( equate.getSeries1(), allSeries );
477 // if ( series1Idx >= 0 ) {
478 // //Add link to series 1
479 // SurveyStation stn = createStationFromNameForSeries( equate.getStn1(), allSeries.get( series1Idx ) );
480 // SurveyStation fake = new SurveyStation( 0 );
481 // fake.setName( equate.getStn2() );
482 // allSeries.get( series1Idx ).addLink( equate.getSeries1(), stn, equate.getSeries2(), fake );
483 // dealtWithUnmatchedSeries = true;
484 // }
485 // else {
486 // int series2Idx = lookupSeriesIndexFromSeriesName( equate.getSeries2(), allSeries );
487 // if ( series2Idx >= 0 ) {
488 // //Add link to series 2
489 // SurveyStation stn = createStationFromNameForSeries( equate.getStn2(), allSeries.get( series2Idx ) );
490 // SurveyStation fake = new SurveyStation( 0 );
491 // fake.setName( equate.getStn1() );
492 // allSeries.get( series2Idx ).addLink( equate.getSeries1(), fake, equate.getSeries2(), stn );
493 // dealtWithUnmatchedSeries = true;
494 // }
495 // }
496 }
497
498 //By here, live series is the parent series for both equates.
499 //The outer and inner hierarchies indicate the paths to the inner series from this point
500
501 if ( liveSeries != null ) {
502 String equatePart1;
503 SurveySeries part1Series;
504 SurveyStation stn1 = null;
505 if ( outerHierarchy.isEmpty() ) {
506 equatePart1 = "";
507 part1Series = liveSeries;
508 stn1 = createStationFromNameForSeries( outerSeriesStn, part1Series );
509 }
510 else {
511 equatePart1 = stringListToDotSeparatedString( outerHierarchy, ".");
512 try {
513 part1Series = findInnerSeriesByName( liveSeries, outerHierarchy.listIterator() );
514 stn1 = createStationFromNameForSeries( outerSeriesStn, part1Series );
515 }
516 catch (RuntimeException ex) {
517 //PocketTopo files often have equates to stations in series not in the file
518 stn1 = new SurveyStation( 0 );
519 stn1.setName( equate.getStn1() );
520 }
521 }
522
523 String equatePart2;
524 SurveySeries part2Series;
525 SurveyStation stn2 = null;
526 if ( innerHierarchy.isEmpty() ) {
527 equatePart2 = "";
528 part2Series = liveSeries;
529 stn2 = createStationFromNameForSeries( innerSeriesStn, part2Series );
530 }
531 else {
532 equatePart2 = stringListToDotSeparatedString( innerHierarchy, ".");
533 try {
534 part2Series = findInnerSeriesByName( liveSeries, innerHierarchy.listIterator() );
535 stn2 = createStationFromNameForSeries( innerSeriesStn, part2Series );
536 }
537 catch (RuntimeException ex) {
538 //PocketTopo files often have equates to stations in series not in the file
539 stn2 = new SurveyStation( 0 );
540 stn2.setName( equate.getStn2() );
541 }
542 }
543
544 //Put link into the parent series of the two linked series
545 liveSeries.addLink(equatePart1, stn1, equatePart2, stn2);
546 }
547 else {
548 //No parent series found for this equate
549 throw new RuntimeException( "Equate series are not inside same series. Series1: '" +
550 equate.getSeries1() + "'. Series2: '" + equate.getSeries2() + "'." );
551 }
552 }
553
554 }
555
556 /**
557 *
558 * @param outerSeries
559 * @param pathIterator
560 * @return
561 */
562 private static SurveySeries findInnerSeriesByName( SurveySeries outerSeries, ListIterator<String> pathIterator) {
563 SurveySeries liveSeries = outerSeries;
564 //Now iterate over path looking for matching inner series for each level
565 while ( pathIterator.hasNext() ) {
566 String liveName = pathIterator.next();
567 liveSeries = liveSeries.findInnerSeriesByName( liveName );
568 if (liveSeries == null ) {
569 //Failed to match a series at this level
570 throw new RuntimeException( "Equate series name '" +
571 liveName + "' did not match any inner series name." );
572 }
573 }
574
575 return liveSeries;
576 }
577
578 public static void logSurveyDebugData( CaveSurvey allSeries, Logger logger ) {
579 //Debug dump
580 logger.logMessage("============================ Cave Survey Data Summary ============================");
581 logger.logMessage("Survey contains " + allSeries.size() + " top level series.");
582 for (int i = 0; i < allSeries.size(); i++ ) {
583 logSurveySeriesSummary( allSeries.get(i), "", logger );
584 }
585 }
586
587 private static void logSurveySeriesSummary( SurveySeries series, String seriesParent, Logger logger ) {
588 String fullSeriesPath = seriesParent + series.getSeriesName();
589 String message = "Series: " + fullSeriesPath;
590 if ( series.legCount() > 0 ) {
591 message += " (" + series.legCount() + " legs)";
592 }
593 if ( series.innerSeriesCount() > 0 ) {
594 message += " (contains " + series.innerSeriesCount() + " child series)";
595 }
596 logger.logMessage( message );
597 //Recursively log details of inner series
598 for (int i = 0; i < series.innerSeriesCount(); i++ ) {
599 logSurveySeriesSummary( series.getInnerSeries(i), fullSeriesPath + "/", logger );
600 }
601 }
602
603 /**
604 * Reads a text file and builds an ArrayList of strings, one for each line
605 * of the file. If the multi-file option is set then file lines will be checked
606 * for include statements referencing other files, and if found these files contents
607 * will be inserted into the output in place of the include statement lines.
608 *
609 * @param inputFile File to be read
610 * @param characterSetEncoding Character set encoding to use when reading the text file
611 * @param multiFile If set to true then file lines are checked for includes for other files to be inserted
612 * @param multifileLineRefs Used to output an ArrayList of strings indicating the original file and line
613 * number for each data line in the output data. Requires an empty list to be passed in.
614 * @param logger Logging class to output information, warning and error messages to
615 * @return ArrayList of strings, one for each line of the input filename
616 */
617 public static List<String> readTextFile( File inputFile, String characterSetEncoding,
618 boolean multiFile, List<String> multifileLineRefs, Logger logger ) {
619 List<String> dataLines = new ArrayList<String>();
620
621 BufferedReader bufferedReader = null;
622
623 try {
624 FileInputStream fis = new FileInputStream( inputFile );
625 InputStreamReader isr = new InputStreamReader( fis, characterSetEncoding );
626 bufferedReader = new BufferedReader ( isr );
627
628 String text;
629 int lineNo = 0;
630 while ( ( text = bufferedReader.readLine() ) != null) {
631 lineNo++;
632 boolean addLine = true;
633
634 if ( multiFile ) {
635 //Check line for include statement
636 String line = text.trim();
637 if ( line.toLowerCase().startsWith( "*include" ) ) {
638 //Extract path to include file
639 String pathAddn = "";
640 for ( int i = 8; i < line.length(); i++ ) {
641 //Take all characters after *include up to comment char or line end
642 if ( line.charAt(i) == ';' ) {
643 break;
644 }
645 else {
646 pathAddn += line.charAt(i);
647 }
648 }
649 pathAddn = pathAddn.trim();
650 //Check for quotes around pathAddn and remove them if found
651 if ( pathAddn.charAt(0) == '"' && pathAddn.charAt( pathAddn.length() - 1 ) == '"' ) {
652 pathAddn = pathAddn.substring(1, pathAddn.length() - 1 );
653 }
654 boolean extPresent = (pathAddn.lastIndexOf('.') >= 0)
655 && pathAddn.substring( pathAddn.lastIndexOf('.') ).toLowerCase().equals(".svx");
656 String nextFilePath = folderFromFile( inputFile );
657 File nextFile = new File( nextFilePath + File.separatorChar + pathAddn );
658 if ( extPresent == false && nextFile.exists() == false ) {
659 //Include statement potentially needs file extension adding, try lower case first
660 nextFile = new File( nextFilePath + File.separatorChar + pathAddn + ".svx" );
661 if ( nextFile.exists() == false ) {
662 //Still not found, try upper case first
663 nextFile = new File( nextFilePath + File.separatorChar + pathAddn + ".SVX" );
664 }
665 }
666 logger.logMessage( "Including file: " + nextFile.getPath() );
667 List<String> fileData = UtilityFunctions.readTextFile( nextFile, characterSetEncoding, multiFile,
668 multifileLineRefs, logger );
669 dataLines.addAll(fileData);
670 addLine = false;
671 }
672 else {
673 //Not an include line in a multifile read, so store line ref
674 multifileLineRefs.add( inputFile.getPath() + ":" + lineNo );
675 }
676 }
677 if ( addLine ) {
678 dataLines.add( text );
679 }
680 }
681 }
682 catch (FileNotFoundException ex) {
683 logger.logError( ex.getMessage() );
684 }
685 catch (IOException ex) {
686 logger.logError( ex.getMessage() );
687 }
688 finally {
689 if ( bufferedReader != null ) {
690 try {
691 bufferedReader.close();
692 } catch (IOException ex) {
693 logger.logError( ex.getMessage() );
694 }
695 }
696 }
697
698 return dataLines;
699 }
700
701 /**
702 * Write a text file from the data in an ArrayList of strings, one line
703 * in the file per string in the List.
704 *
705 * @param fileContents ArrayList of strings, one for each line of the input filename
706 * @param fileName Full path and name of file to be written
707 * @param characterSetEncoding Character set encoding to use when writing the text file
708 * @return Error message if write failed, or empty string if success
709 */
710 public static String writeTextFile (List<String> fileContents, String fileName, String characterSetEncoding ) {
711 String error = "";
712
713 BufferedWriter textWriter = null;
714 try {
715 //Create file writer
716 FileOutputStream fos = new FileOutputStream( fileName );
717 Writer out = new OutputStreamWriter(fos, characterSetEncoding);
718 textWriter = new BufferedWriter(out);
719
720 //Write strings from list to the file
721 Iterator<String> iterator = fileContents.listIterator();
722 while ( iterator.hasNext() ) {
723 String line = iterator.next();
724 if ( iterator.hasNext() ) {
725 textWriter.write( line + System.getProperty("line.separator") );
726 }
727 else {
728 textWriter.write( line );
729 }
730 }
731 }
732 catch (IOException ex) {
733 error = "Error writing file: " + ex.getLocalizedMessage();
734 }
735 finally {
736 if ( textWriter != null ) {
737 try {
738 textWriter.close();
739 }
740 catch (IOException ex) {
741 error = "Error closing file: " + ex.getLocalizedMessage();
742 }
743 }
744 }
745
746 return error;
747 }
748
749 /**
750 * Checks for station in the series being built. If found then adding this leg would mean the
751 * series looped back onto itself, which we cannot do in Toporobot format.
752 * @param iter Iterator for the list of stations already added to the series
753 * @param checkStn The station to check for in the series being built up
754 * @return True if station is found in the list cache
755 */
756 private static boolean checkForLoopback( ListIterator<SurveyStation> iter, SurveyStation checkStn ) {
757 boolean loopDetected = false;
758
759 while ( iter.hasNext() ) {
760 if ( checkStn.getId() == iter.next().getId() ) {
761 loopDetected = true;
762 break;
763 }
764
765 }
766 return loopDetected;
767 }
768 /**
769 * Checks for a station in all the series so far, to avoid series crossing other series in
770 * the middle of each other, as TopoRobot format cannot support links of this sort.
771 * @param caveSoFar
772 * @param checkStn
773 * @return
774 */
775 private static boolean checkForCrossover( SurveySeries caveSoFar, SurveyStation checkStn ) {
776 boolean crossingDetected = false;
777
778 ListIterator<SurveySeries> seriesIter = caveSoFar.getInnerSeriesList().listIterator();
779 while ( seriesIter.hasNext() ) {
780 //Check for station in all legs bar the final one in this series
781 SurveySeries series = seriesIter.next();
782 for ( int i=0; i < series.legCount() - 1; i++ ) {
783 SurveyLeg leg = series.getLegRaw(i);
784 //Check leg to station as from station in first leg starts series
785 //so not a crossover, and all other from stations are also to stations
786 if ( checkStn.getId() == leg.getToStn().getId() ) {
787 crossingDetected = true;
788 i = series.legCount();
789 }
790 }
791 if ( crossingDetected == true ) {
792 break;
793 }
794 }
795 return crossingDetected;
796 }
797
798 /**
799 * Splits a single survey series into a list of series without branches or loops.
800 * The input series must not contain any nested series. The output series will
801 * contain one or more inner series and the links between them, but no legs itself.
802 * This method requires that any survey station can be identified by it's ID alone,
803 * so stations with different names but the same ID are assumed to be the same station.
804 *
805 * TODO Somewhere in here is a bug which allows series to be linked together in unconnected
806 * groups. It happens when two series are linked to each other via the same station. The
807 * link is in effect duplicated, rather than one of the series being linked to another part of
808 * the cave. There is also an issue that both ends of the series do not get linked to the
809 * rest of the cave. Sometimes both the start and end stations are linked to another series
810 * but only one of these links is created in the toporobot file.
811 *
812 * @param seriesIn A survey series which contains branches
813 * @param logger Logging class to output information, warning and error messages to
814 * @return A series containing one or more inner series, all linked by their first
815 * stations to one of the other series. All series will be linear chains.
816 */
817 public static SurveySeries convertToLinearSeries( SurveySeries seriesIn, Logger logger ) {
818
819
820 SurveySeries outputSeries = new SurveySeries( seriesIn.getSeriesName() );
821
822 //Check the input series contain no inner series
823 if ( seriesIn.innerSeriesCount() > 0 ) {
824 throw new RuntimeException( "Nested series cannot be converted to linear chains." );
825 }
826
827 //Loop through all the legs creating inner series of linear chains until all legs are
828 //handled or remaining legs cannot be linked to any other legs.
829 boolean legsRemain = true;
830 while (legsRemain) {
831 //Create a new series to start building a new linear chain
832 SurveySeries series = new SurveySeries( seriesIn.getSeriesName() );
833 series.setCalibrationFromAnotherSeries( seriesIn );
834
835 //Create cache of all stations used to check for loops back onto stations already used
836 List<SurveyStation> seriesStns = new ArrayList<SurveyStation>();
837
838 //Initialise last station flag to invalid id
839 int lastStnId = -999;
840
841 //Loop through all remaining legs and add connected legs to new series
842 int addedLegsCount = 0;
843 boolean legsAdded = true; //Initialise true to get into first pass of loops
844 //Keep looping over all remaining legs until no more are being added to this series
845 while ( legsAdded ) {
846 legsAdded = false; //Reset
847
848 int i = 0;
849 while ( i < seriesIn.legCount() ) {
850 int initialInnerAddedLegCount = addedLegsCount;
851 SurveyLeg curLeg = seriesIn.getLegRaw(i);
852
853 //Check if first leg for new series (always add), or leg follows last leg added
854 if ( ( series.legCount() == 0 ) || ( lastStnId == curLeg.getFromStn().getId() ) ) {
855 //Check that 'to' station has not already been used in the series
856 boolean loopDetected = checkForLoopback( seriesStns.listIterator(), curLeg.getToStn() );
857 if (loopDetected == false) {
858 boolean crossDetected = false;
859 if ( series.legCount() > 0 ) {
860 //Only check for cross over if not first station in a new series
861 crossDetected = checkForCrossover( outputSeries, curLeg.getFromStn() );
862 }
863 if (crossDetected == false) {
864 //Add leg to end of series
865 series.addLeg(curLeg);
866 //Update last stn
867 lastStnId = curLeg.getToStn().getId();
868 //Increment added legs count
869 addedLegsCount++;
870 //Add new station from this leg into stations cache
871 seriesStns.add( curLeg.getToStn() );
872 }
873 }
874 }
875 else if ( curLeg.getToStn().getId() == series.getLegRaw(0).getFromStn().getId() ) {
876 //Leg fits on start of series, so insert at beginning if not looping back onto series
877
878 //Check that 'from' station has not already been used in the series
879 boolean loopDetected = checkForLoopback( seriesStns.listIterator(), curLeg.getFromStn() );
880 if (loopDetected == false) {
881 boolean crossDetected = checkForCrossover( outputSeries, curLeg.getToStn() );
882 if (crossDetected == false) {
883 series.addLeg(curLeg, 0);
884 //Increment added legs count
885 addedLegsCount++;
886 //Add new station from this leg into stations cache
887 seriesStns.add( curLeg.getFromStn() );
888 }
889 }
890 }
891
892 if (initialInnerAddedLegCount < addedLegsCount ) {
893 //Leg was added, so remove from input series
894 seriesIn.removeLeg(i);
895 //Update flag to indicate a leg has been added
896 legsAdded = true;
897 }
898 else {
899 //Leg was not used, so increment index to test next leg
900 i++;
901 }
902 }
903 }
904
905 //Check whether any legs were added to this series (if not then exit)
906 if ( series.legCount() > 0 ) {
907 /*
908 * New series created, set name from to station of first leg (fromStn name has often been changed by equating)
909 * up to the last dot, and add the series index to ensure series name is unique
910 */
911 String originalSeriesStn2Name = seriesIn.getMappedStnName( series.getLegRaw(0).getToStn().getId() );
912 //Base new series name on parent series and station name
913 String originalSeriesName = seriesIn.getSeriesName() + "-" + originalSeriesStn2Name;
914 int dotPos = originalSeriesStn2Name.lastIndexOf(".");
915 if ( dotPos > 0 ) {
916 //Station name has a series name prefix, so use this in preference to parent series name
917 originalSeriesName = originalSeriesStn2Name.substring(0, dotPos );
918 }
919 series.setSeriesName( (outputSeries.innerSeriesCount() + 1) + "-" + originalSeriesName );
920 //Add to list
921 outputSeries.addSeries(series);
922 }
923 else {
924 //No legs were processed on last pass, so exit the loop
925 legsRemain = false;
926 }
927 }
928
929 //Check that all legs were moved into output series
930 if ( seriesIn.legCount() > 0 ) {
931 throw new RuntimeException( "Some legs could not be linked to other legs in the series." );
932 }
933
934 //Now loop through all the series and for each one match the start
935 //station to a station in another series
936 logger.logMessage( "Linking series:" );
937 for ( int searchIdx = 0; searchIdx < outputSeries.innerSeriesCount(); searchIdx++ ) {
938 SurveySeries seriesToLink = outputSeries.getInnerSeries(searchIdx);
939
940 //Get first and last stns
941 SurveyStation firstStn = seriesToLink.getLegRaw(0).getFromStn();
942 SurveyStation endStn = seriesToLink.getLegRaw( seriesToLink.legCount() - 1 ).getToStn();
943
944 //Check all the other series for station matching the start station for this series
945 int matchingIdx = findStationMatchingIdInInnerSeries(firstStn.getId(), searchIdx, outputSeries);
946 if ( matchingIdx > -1 ){
947 logger.logMessage( "Series: " + outputSeries.getInnerSeries(searchIdx).getSeriesName() +
948 " start stn linked to " + outputSeries.getInnerSeries(matchingIdx).getSeriesName() );
949 //Found match, so add link to parent series
950 outputSeries.addLink(outputSeries.getInnerSeries(searchIdx).getSeriesName(), firstStn,
951 outputSeries.getInnerSeries(matchingIdx).getSeriesName(), firstStn);
952 }
953 // else {
954 /*
955 * Need to check for end stn matches even if a start station link was found or loops are never closed
956 * and sets of series can be created which are not connected to other sets.
957 * TODO The commented out else block fixes the links not being set, but now a series which
958 * starts where another series ends is linked twice, once in each direction. We should add a method
959 * to the series class to check if a link already exists, and only add these links if not already defined
960 * in the reverse direction.
961 */
962 //No links to start of this series, so check if end station matches
963 matchingIdx = findStationMatchingIdInInnerSeries(endStn.getId(), searchIdx, outputSeries);
964 if ( matchingIdx > -1 ){
965 logger.logMessage( "Series: " + outputSeries.getInnerSeries(searchIdx).getSeriesName() +
966 " end stn linked to " + outputSeries.getInnerSeries(matchingIdx).getSeriesName() );
967 //Found match, so need to reverse this series and add a link for it
968 //No need to reverse as we now support end links outputSeries.getInnerSeries(searchIdx).reverseSeries();
969 outputSeries.addLink(outputSeries.getInnerSeries(searchIdx).getSeriesName(), endStn,
970 outputSeries.getInnerSeries(matchingIdx).getSeriesName(), endStn);
971 }
972 // }
973 }
974
975 return outputSeries;
976 }
977
978 /**
979 * Looks for an inner series with a station which matches the id given, and if found
980 * then returns the index of that inner series. An index of an inner series to
981 * exclude can be provided, to prevent a series being matched to itself.
982 */
983 private static int findStationMatchingIdInInnerSeries(int id, int excludeSeriesIdx, SurveySeries series){
984 int matchingIdx = -1;
985
986 ListIterator<SurveySeries> innerItr = series.getInnerSeriesList().listIterator();
987 int checkIdx = -1;
988 while ( matchingIdx == -1 && innerItr.hasNext() ) {
989 SurveySeries check = innerItr.next();
990 checkIdx++;
991 //Do not check against the same series as ourself
992 if ( excludeSeriesIdx != checkIdx ) {
993 //Loop through legs in check series
994 for ( int legIdx = 0; legIdx < check.legCount(); legIdx++ ) {
995 SurveyLeg leg = check.getLegRaw(legIdx);
996 //Looking for matching stations
997 if ( id == leg.getFromStn().getId() ) {
998 //Found match to a from station
999 matchingIdx = checkIdx;
1000 break;
1001 }
1002 else if ( id == leg.getToStn().getId() ) {
1003 //Found match to a to stn
1004 matchingIdx = checkIdx;
1005 break;
1006 }
1007 }
1008 }
1009 }
1010
1011 return matchingIdx;
1012 }
1013
1014 /**
1015 * Removes whitespace and splits a line into items separated by whitespace
1016 * Returns and array of items from the input data line
1017 *
1018 * @param dataIn Data string to convert into data items
1019 * @return Array of data strings split at white space from the input data line
1020 */
1021 public static String[] cleanAndSplitDataLine( String dataIn ) {
1022 //Process all white space down to single space chars
1023 String dataLine = dataIn.replace('\t', ' ').trim();
1024 while ( dataLine.contains(" ") ) {
1025 dataLine = dataLine.replaceAll(" ", " ");
1026 }
1027 return dataLine.split(" ");
1028 }
1029
1030 /**
1031 * Formats a message including the line number for file parsing messages
1032 *
1033 * @param message Message to append line number to
1034 * @param lineNo Line number to append to message text
1035 * @return Message text with line number appended
1036 */
1037 public static String formatFileParserMsg( String message, int lineNo ) {
1038 String msg = message;
1039
1040 msg += " (Line: " + lineNo + ")";
1041 return msg;
1042 }
1043
1044 /**
1045 * Formats a message including a string line reference for file parsing messages
1046 *
1047 * @param message Message to append line number to
1048 * @param lineRef Line reference to append to message text
1049 * @return Message text with line number appended
1050 */
1051 public static String formatFileParserMsg( String message, String lineRef ) {
1052 String msg = message;
1053
1054 msg += " (Line ref: " + lineRef + ")";
1055 return msg;
1056 }
1057
1058 /**
1059 * Generates a data format line suitable for Survex and Therion format files
1060 *
1061 * @param series Survey series to generate the data format line for
1062 * @param legIsDiving Flag to indicate whether the leg following this format header is a diving leg
1063 * @return Data format line without prefix character (i.e. no * needed for Survex)
1064 */
1065 public static String dataFormatLineForSeries( SurveySeries series, boolean legIsDiving ) {
1066 List<String> dataOrder = series.getDataOrder();
1067 List<String> dataOrder2 = series.getDataOrder2();
1068
1069 //Determine if correct data order item for normal or diving in case of mixed data series
1070 if ( dataOrder2.size() > 0 ) {
1071 if ( dataOrderIsDiving( dataOrder ) != legIsDiving ) {
1072 //Primary data order does not match required type, so use secondary order
1073 dataOrder = dataOrder2;
1074 }
1075 }
1076
1077 String dataOrderLine = "";
1078 boolean diving = false;
1079
1080 //Check for diving
1081 for (int i = 0; i < dataOrder.size(); i++) {
1082 String item = dataOrder.get(i);
1083 dataOrderLine += " " + item.toLowerCase();
1084 if ( item.contains("DEPTH") ) {
1085 diving = true;
1086 }
1087 }
1088
1089 if ( diving == true ) {
1090 dataOrderLine = "diving" + dataOrderLine;
1091 }
1092 else {
1093 dataOrderLine = "normal" + dataOrderLine;
1094 }
1095
1096 //Prefix with data keyword, or return empty string if there was no data order specified in the series
1097 if ( dataOrderLine.length() > 7 ) {
1098 dataOrderLine = "data " + dataOrderLine;
1099 }
1100 else {
1101 dataOrderLine = "";
1102 }
1103
1104 return dataOrderLine;
1105 }
1106
1107 /**
1108 * Compares the strings in two string lists, and returns true if they are all identical
1109 * @param list1 One of the pair of string lists to compare
1110 * @param list2 One of the pair of string lists to compare
1111 * @return True if string lists are identical, otherwise false
1112 */
1113 public static boolean compareStringLists( List<String> list1, List<String> list2 ) {
1114 boolean match = true;
1115
1116 if ( list1.size() == list2.size() ) {
1117 for ( int i = 0; i < list1.size(); i++ ) {
1118 if ( list1.get(i).compareTo( list2.get(i) ) != 0 ) {
1119 match = false;
1120 break;
1121 }
1122 }
1123 }
1124 else {
1125 match = false;
1126 }
1127
1128 return match;
1129 }
1130
1131 /**
1132 * Converts a length measurement to a length in metres.
1133 *
1134 * @param length Length measurement to be converted
1135 * @param units Units of the length measurement as provided
1136 * @return Length in units of metres
1137 */
1138 public static double lengthToMetres(double length, LengthUnit units) {
1139 double metreLength = 0;
1140
1141 switch (units) {
1142 case Metres :
1143 metreLength = length;
1144 break;
1145 case Feet :
1146 metreLength = length / feetPerMetre;
1147 break;
1148 case Yards :
1149 metreLength = length * 3 / feetPerMetre;
1150 break;
1151 default:
1152 //In case other units are added to enum, but not coded yet; return zero
1153 break;
1154 }
1155
1156 return metreLength;
1157 }
1158
1159 /**
1160 * Converts the length measurement to a specified unit from specified value in metres.
1161 *
1162 * @param metrelength Length measurement in metres to convert to different units
1163 * @param units Units to convert length to
1164 * @return Length in units specified
1165 */
1166 public static double lengthFromMetres(double metrelength, LengthUnit units) {
1167 double convertedLength = 0;
1168
1169 switch (units) {
1170 case Metres :
1171 convertedLength = metrelength;
1172 break;
1173 case Feet :
1174 convertedLength = metrelength * feetPerMetre;
1175 break;
1176 case Yards :
1177 convertedLength = metrelength * feetPerMetre / 3;
1178 break;
1179 default:
1180 //In case other units are added to enum, but not coded yet; return zero
1181 break;
1182 }
1183
1184 return convertedLength;
1185 }
1186
1187 /**
1188 * Converts a bearing measurement to a bearing in degrees.
1189 * @param bearing Bearing measurement to be converted
1190 * @param units Units of the bearing measurement as provided
1191 * @return Bearing in units of degrees
1192 */
1193 public static double bearingToDegrees(double bearing, BearingUnit units) {
1194 double degrees = -999;
1195
1196 switch (units) {
1197 case Degrees :
1198 degrees = bearing;
1199 break;
1200 case Grads :
1201 degrees = gradsToDegrees( bearing );
1202 break;
1203 case Minutes :
1204 degrees = bearing / 60;
1205 break;
1206 default:
1207 //In case other units are added to enum, but not coded yet; return -999
1208 break;
1209 }
1210
1211 return degrees;
1212 }
1213
1214 /**
1215 * Converts the bearing measurement to a specified unit from specified value in degrees.
1216 *
1217 * @param bearingDegrees Bearing measurement in degrees to convert to different units
1218 * @param units Units to convert bearing to
1219 * @return Bearing in units specified
1220 */
1221 public static double bearingFromDegrees(double bearingDegrees, BearingUnit units) {
1222 double convertedBearing = -999;
1223
1224 switch (units) {
1225 case Degrees :
1226 convertedBearing = bearingDegrees;
1227 break;
1228 case Grads :
1229 convertedBearing = degreesToGrads( bearingDegrees );
1230 break;
1231 case Minutes :
1232 convertedBearing = bearingDegrees * 60;
1233 break;
1234 default:
1235 //In case other units are added to enum, but not coded yet; return -999
1236 break;
1237 }
1238
1239 return convertedBearing;
1240 }
1241
1242 /**
1243 * Converts a gradient (inclination) measurement to an angle in degrees.
1244 * @param gradient Inclination measurement to be converted
1245 * @param units Units of the inclination measurement as provided
1246 * @return Inclination in units of degrees
1247 */
1248 public static double gradientToDegrees(double gradient, GradientUnit units) {
1249 double degrees = -999;
1250
1251 switch (units) {
1252 case Degrees :
1253 degrees = bearingToDegrees( gradient, BearingUnit.Degrees );
1254 break;
1255 case Grads :
1256 degrees = bearingToDegrees( gradient, BearingUnit.Grads );
1257 break;
1258 case Minutes :
1259 degrees = bearingToDegrees( gradient, BearingUnit.Minutes );
1260 break;
1261 case Percent :
1262 degrees = 180 * ( Math.atan( gradient / 100 ) ) / Math.PI;
1263 break;
1264 default:
1265 //In case other units are added to enum, but not coded yet; return -999
1266 break;
1267 }
1268
1269 return degrees;
1270 }
1271
1272 /**
1273 * Converts the bearing measurement to a specified unit from specified value in degrees.
1274 *
1275 * @param gradientDegrees Inclination measurement in degrees to convert to different units
1276 * @param units Units to convert bearing to
1277 * @return Bearing in units specified
1278 */
1279 public static double gradientFromDegrees(double gradientDegrees, GradientUnit units) {
1280 double convertedGradient = -999;
1281
1282 switch (units) {
1283 case Degrees :
1284 convertedGradient = bearingFromDegrees( gradientDegrees, BearingUnit.Degrees );
1285 break;
1286 case Grads :
1287 convertedGradient = bearingFromDegrees( gradientDegrees, BearingUnit.Grads );
1288 break;
1289 case Minutes :
1290 convertedGradient = bearingFromDegrees( gradientDegrees, BearingUnit.Minutes );
1291 break;
1292 case Percent :
1293 convertedGradient = 100.0 * Math.tan(Math.PI * gradientDegrees / 180.0);
1294 break;
1295 default:
1296 //In case other units are added to enum, but not coded yet; return -999
1297 break;
1298 }
1299
1300 return convertedGradient;
1301 }
1302
1303 /**
1304 * Determines if a data order list is for diving data or normal
1305 * @param checkDataOrder Data order list from a SurveySeries
1306 * @return True if the data order list is for diving data, other wise false for normal data
1307 */
1308 public static boolean dataOrderIsDiving(List<String> checkDataOrder) {
1309 boolean isDiving = false;
1310 if ( checkDataOrder != null &&
1311 ( checkDataOrder.contains("DEPTHCHANGE") || checkDataOrder.contains("FROMDEPTH") ) ) {
1312 isDiving = true;
1313 }
1314 return isDiving;
1315
1316 }
1317
1318 private static double gradsToDegrees(double grads) {
1319 double tmp = 360.0 * grads / 400.0;
1320 return tmp;
1321 }
1322
1323 private static double degreesToGrads(double degrees) {
1324 return 400.0 * degrees / 360.0;
1325 }
1326
1327 /**
1328 * Returns the folder location of a file
1329 * @param file File to get the folder path from
1330 * @return Path to the folder containing the file
1331 */
1332 private static String folderFromFile( File file ) {
1333 String path = file.getPath();
1334 String folderPath = ".";
1335 String folderSep = File.separator;
1336
1337 int splitPos = path.lastIndexOf( folderSep );
1338 if ( splitPos >= 0 ) {
1339 folderPath = path.substring( 0, splitPos );
1340 }
1341
1342 return folderPath;
1343 }
1344
1345 }