2 // FORESTER -- software libraries and applications
3 // for evolutionary biology research and applications.
5 // Copyright (C) 2008-2009 Christian M. Zmasek
6 // Copyright (C) 2008-2009 Burnham Institute for Medical Research
9 // This library is free software; you can redistribute it and/or
10 // modify it under the terms of the GNU Lesser General Public
11 // License as published by the Free Software Foundation; either
12 // version 2.1 of the License, or (at your option) any later version.
14 // This library is distributed in the hope that it will be useful,
15 // but WITHOUT ANY WARRANTY; without even the implied warranty of
16 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 // Lesser General Public License for more details.
19 // You should have received a copy of the GNU Lesser General Public
20 // License along with this library; if not, write to the Free Software
21 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 // Contact: phylosoft @ gmail . com
24 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26 package org.forester.util;
28 import java.awt.Color;
29 import java.io.BufferedReader;
30 import java.io.BufferedWriter;
32 import java.io.FileInputStream;
33 import java.io.FileNotFoundException;
34 import java.io.FileOutputStream;
35 import java.io.FileReader;
36 import java.io.FileWriter;
37 import java.io.IOException;
38 import java.io.InputStream;
39 import java.io.InputStreamReader;
40 import java.io.StringReader;
41 import java.io.Writer;
42 import java.math.BigDecimal;
44 import java.text.DateFormat;
45 import java.text.DecimalFormat;
46 import java.text.DecimalFormatSymbols;
47 import java.text.NumberFormat;
48 import java.text.ParseException;
49 import java.text.SimpleDateFormat;
50 import java.util.ArrayList;
51 import java.util.Collection;
52 import java.util.Date;
53 import java.util.Iterator;
54 import java.util.List;
56 import java.util.Map.Entry;
58 import java.util.SortedMap;
59 import java.util.SortedSet;
60 import java.util.TreeMap;
61 import java.util.TreeSet;
62 import java.util.regex.Matcher;
63 import java.util.regex.Pattern;
65 import org.forester.archaeopteryx.Constants;
66 import org.forester.phylogeny.PhylogenyNode;
67 import org.forester.phylogeny.data.Distribution;
68 import org.forester.phylogeny.data.Sequence;
69 import org.forester.phylogeny.data.Taxonomy;
70 import org.forester.protein.BasicProtein;
71 import org.forester.protein.Domain;
72 import org.forester.protein.Protein;
73 import org.forester.surfacing.SurfacingUtil;
75 public final class ForesterUtil {
77 public final static String FILE_SEPARATOR = System.getProperty( "file.separator" );
78 public final static String LINE_SEPARATOR = System.getProperty( "line.separator" );
79 public final static String JAVA_VENDOR = System.getProperty( "java.vendor" );
80 public final static String JAVA_VERSION = System.getProperty( "java.version" );
81 public final static String OS_ARCH = System.getProperty( "os.arch" );
82 public final static String OS_NAME = System.getProperty( "os.name" );
83 public final static String OS_VERSION = System.getProperty( "os.version" );
84 public final static Pattern PARANTHESESABLE_NH_CHARS_PATTERN = Pattern.compile( "[(),;\\s]" );
85 public final static double ZERO_DIFF = 1.0E-9;
86 public static final BigDecimal NULL_BD = new BigDecimal( 0 );
87 public static final NumberFormat FORMATTER_9;
88 public static final NumberFormat FORMATTER_6;
89 public static final NumberFormat FORMATTER_06;
90 public static final NumberFormat FORMATTER_3;
91 public static final String NCBI_PROTEIN = "http://www.ncbi.nlm.nih.gov/protein/";
92 public static final String NCBI_NUCCORE = "http://www.ncbi.nlm.nih.gov/nuccore/";
93 public final static String UNIPROT_KB = "http://www.uniprot.org/uniprot/";
94 public static final String NCBI_GI = "http://www.ncbi.nlm.nih.gov/protein/gi:";
95 public final static Color DEUTEROSTOMIA_COLOR = new Color( 255, 0, 0 );
96 public final static Color PROTOSTOMIA_COLOR = new Color( 204, 0, 0 );
97 public final static Color METAZOA_COLOR = new Color( 204, 0, 102 );
98 public final static Color HOLOZOA_COLOR = new Color( 127, 0, 255 );
99 public final static Color FUNGI_COLOR = new Color( 255, 128, 0 );
100 public final static Color HOLOMYCOTA_COLOR = new Color( 204, 102, 0 );
101 public final static Color AMOEBOZOA_COLOR = new Color( 255, 0, 255 );
102 public final static Color VIRIDPLANTAE_COLOR = new Color( 0, 255, 0 );
103 public final static Color RHODOPHYTA_COLOR = new Color( 0, 153, 76 );
104 public final static Color HACROBIA_COLOR = new Color( 0, 102, 51 );
105 public final static Color STRAMENOPILES_COLOR = new Color( 0, 0, 255 );
106 public final static Color ALVEOLATA_COLOR = new Color( 0, 128, 255 );
107 public final static Color RHIZARIA_COLOR = new Color( 0, 255, 255 );
108 public final static Color EXCAVATA_COLOR = new Color( 204, 204, 0 );
109 public final static Color ARCHAEA_COLOR = new Color( 160, 160, 160 );
110 public final static Color BACTERIA_COLOR = new Color( 64, 64, 64 );
112 final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
113 dfs.setDecimalSeparator( '.' );
114 // dfs.setGroupingSeparator( ( char ) 0 );
115 FORMATTER_9 = new DecimalFormat( "#.#########", dfs );
116 FORMATTER_6 = new DecimalFormat( "#.######", dfs );
117 FORMATTER_06 = new DecimalFormat( "0.######", dfs );
118 FORMATTER_3 = new DecimalFormat( "#.###", dfs );
121 private ForesterUtil() {
124 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
125 int overlap_count = 0;
126 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
127 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
131 return overlap_count;
134 final public static void appendSeparatorIfNotEmpty( final StringBuffer sb, final char separator ) {
135 if ( sb.length() > 0 ) {
136 sb.append( separator );
142 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
143 * domain with 0.3 is ignored
145 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
148 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
151 * @param max_allowed_overlap
152 * maximal allowed overlap (inclusive) to be still considered not
153 * overlapping (zero or negative value to allow any overlap)
154 * @param remove_engulfed_domains
155 * to remove domains which are completely engulfed by coverage of
156 * domains with better support
160 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
161 final boolean remove_engulfed_domains,
162 final Protein protein ) {
163 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
164 .getSpeciesId(), protein.getLength() );
165 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
166 final List<Boolean> covered_positions = new ArrayList<Boolean>();
167 for( final Domain domain : sorted ) {
168 if ( ( ( max_allowed_overlap < 0 ) || ( ForesterUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
169 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
170 final int covered_positions_size = covered_positions.size();
171 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
172 covered_positions.add( false );
174 final int new_covered_positions_size = covered_positions.size();
175 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
176 if ( i < new_covered_positions_size ) {
177 covered_positions.set( i, true );
180 covered_positions.add( true );
183 pruned_protein.addProteinDomain( domain );
186 return pruned_protein;
190 * Returns true is Domain domain falls in an uninterrupted stretch of
194 * @param covered_positions
197 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
198 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
199 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
207 * This calculates a color. If value is equal to min the returned color is
208 * minColor, if value is equal to max the returned color is maxColor,
209 * otherwise a color 'proportional' to value is returned.
223 final public static Color calcColor( double value,
226 final Color minColor,
227 final Color maxColor ) {
234 final double x = ForesterUtil.calculateColorFactor( value, max, min );
235 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), maxColor.getRed(), x );
236 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), maxColor.getGreen(), x );
237 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), maxColor.getBlue(), x );
238 return new Color( red, green, blue );
242 * This calculates a color. If value is equal to min the returned color is
243 * minColor, if value is equal to max the returned color is maxColor, if
244 * value is equal to mean the returned color is meanColor, otherwise a color
245 * 'proportional' to value is returned -- either between min-mean or
255 * the mean/median value
264 final public static Color calcColor( double value,
268 final Color minColor,
269 final Color maxColor,
270 final Color meanColor ) {
277 if ( value < mean ) {
278 final double x = ForesterUtil.calculateColorFactor( value, mean, min );
279 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), meanColor.getRed(), x );
280 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), meanColor.getGreen(), x );
281 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), meanColor.getBlue(), x );
282 return new Color( red, green, blue );
284 else if ( value > mean ) {
285 final double x = ForesterUtil.calculateColorFactor( value, max, mean );
286 final int red = ForesterUtil.calculateColorComponent( meanColor.getRed(), maxColor.getRed(), x );
287 final int green = ForesterUtil.calculateColorComponent( meanColor.getGreen(), maxColor.getGreen(), x );
288 final int blue = ForesterUtil.calculateColorComponent( meanColor.getBlue(), maxColor.getBlue(), x );
289 return new Color( red, green, blue );
296 final public static String collapseWhiteSpace( final String s ) {
297 return s.replaceAll( "[\\s]+", " " );
300 final public static void collection2file( final File file, final Collection<?> data, final String separator )
302 final Writer writer = new BufferedWriter( new FileWriter( file ) );
303 collection2writer( writer, data, separator );
307 final public static void collection2writer( final Writer writer, final Collection<?> data, final String separator )
309 boolean first = true;
310 for( final Object object : data ) {
312 writer.write( separator );
317 writer.write( object.toString() );
321 final public static String colorToHex( final Color color ) {
322 final String rgb = Integer.toHexString( color.getRGB() );
323 return rgb.substring( 2, rgb.length() );
326 synchronized public static void copyFile( final File in, final File out ) throws IOException {
327 final FileInputStream in_s = new FileInputStream( in );
328 final FileOutputStream out_s = new FileOutputStream( out );
330 final byte[] buf = new byte[ 1024 ];
332 while ( ( i = in_s.read( buf ) ) != -1 ) {
333 out_s.write( buf, 0, i );
336 catch ( final IOException e ) {
340 if ( in_s != null ) {
343 if ( out_s != null ) {
349 final public static int countChars( final String str, final char c ) {
351 for( int i = 0; i < str.length(); ++i ) {
352 if ( str.charAt( i ) == c ) {
359 final public static BufferedWriter createBufferedWriter( final File file ) throws IOException {
360 if ( file.exists() ) {
361 throw new IOException( "[" + file + "] already exists" );
363 return new BufferedWriter( new FileWriter( file ) );
366 final public static BufferedWriter createBufferedWriter( final String name ) throws IOException {
367 return new BufferedWriter( new FileWriter( createFileForWriting( name ) ) );
370 final public static EasyWriter createEasyWriter( final File file ) throws IOException {
371 return new EasyWriter( createBufferedWriter( file ) );
374 final public static BufferedWriter createEasyWriter( final String name ) throws IOException {
375 return createEasyWriter( createFileForWriting( name ) );
378 final public static File createFileForWriting( final String name ) throws IOException {
379 final File file = new File( name );
380 if ( file.exists() ) {
381 throw new IOException( "[" + name + "] already exists" );
386 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
387 if ( !node.getNodeData().isHasDate() ) {
388 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
392 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
393 if ( !node.getNodeData().isHasDistribution() ) {
394 node.getNodeData().setDistribution( new Distribution( "" ) );
398 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
399 if ( !node.getNodeData().isHasSequence() ) {
400 node.getNodeData().setSequence( new Sequence() );
404 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
405 if ( !node.getNodeData().isHasTaxonomy() ) {
406 node.getNodeData().setTaxonomy( new Taxonomy() );
410 public static void fatalError( final String message ) {
411 System.err.println();
412 System.err.println( "error: " + message );
413 System.err.println();
417 public static void fatalError( final String prg_name, final String message ) {
418 System.err.println();
419 System.err.println( "[" + prg_name + "] > " + message );
420 System.err.println();
424 public static void fatalErrorIfFileNotReadable( final File file ) {
425 final String error = isReadableFile( file );
426 if ( !isEmpty( error ) ) {
427 System.err.println();
428 System.err.println( "error: " + error );
429 System.err.println();
434 public static void fatalErrorIfFileNotReadable( final String prg_name, final File file ) {
435 final String error = isReadableFile( file );
436 if ( !isEmpty( error ) ) {
437 System.err.println();
438 System.err.println( "[" + prg_name + "] > " + error );
439 System.err.println();
444 public static String[] file2array( final File file ) throws IOException {
445 final List<String> list = file2list( file );
446 final String[] ary = new String[ list.size() ];
448 for( final String s : list ) {
454 public static String[][] file22dArray( final File file ) throws IOException {
455 final List<String> list = new ArrayList<String>();
456 final BufferedReader in = new BufferedReader( new FileReader( file ) );
458 while ( ( str = in.readLine() ) != null ) {
460 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
465 final String[][] ary = new String[ list.size() ][ 2 ];
466 final Pattern pa = Pattern.compile( "(\\S+)\\s+(\\S+)" );
468 for( final String s : list ) {
469 final Matcher m = pa.matcher( s );
471 ary[ i ][ 0 ] = m.group( 1 );
472 ary[ i ][ 1 ] = m.group( 2 );
476 throw new IOException( "unexpcted format: " + s );
482 final public static List<String> file2list( final File file ) throws IOException {
483 final List<String> list = new ArrayList<String>();
484 final BufferedReader in = new BufferedReader( new FileReader( file ) );
486 while ( ( str = in.readLine() ) != null ) {
488 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
489 for( final String s : splitString( str ) ) {
498 final public static SortedSet<String> file2set( final File file ) throws IOException {
499 final SortedSet<String> set = new TreeSet<String>();
500 final BufferedReader in = new BufferedReader( new FileReader( file ) );
502 while ( ( str = in.readLine() ) != null ) {
504 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
505 for( final String s : splitString( str ) ) {
514 final public static String getCurrentDateTime() {
515 final DateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
516 return format.format( new Date() );
519 final public static String getFileSeparator() {
520 return ForesterUtil.FILE_SEPARATOR;
523 final public static String getFirstLine( final Object source ) throws FileNotFoundException, IOException {
524 BufferedReader reader = null;
525 if ( source instanceof File ) {
526 final File f = ( File ) source;
528 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
530 else if ( !f.isFile() ) {
531 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
533 else if ( !f.canRead() ) {
534 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
536 reader = new BufferedReader( new FileReader( f ) );
538 else if ( source instanceof InputStream ) {
539 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
541 else if ( source instanceof String ) {
542 reader = new BufferedReader( new StringReader( ( String ) source ) );
544 else if ( source instanceof StringBuffer ) {
545 reader = new BufferedReader( new StringReader( source.toString() ) );
547 else if ( source instanceof URL ) {
548 reader = new BufferedReader( new InputStreamReader( ( ( URL ) source ).openStream() ) );
551 throw new IllegalArgumentException( "dont know how to read [" + source.getClass() + "]" );
554 while ( ( line = reader.readLine() ) != null ) {
556 if ( !ForesterUtil.isEmpty( line ) ) {
557 if ( reader != null ) {
563 if ( reader != null ) {
569 final public static String getForesterLibraryInformation() {
570 return "forester " + ForesterConstants.FORESTER_VERSION + " (" + ForesterConstants.FORESTER_DATE + ")";
573 final public static String getLineSeparator() {
574 return ForesterUtil.LINE_SEPARATOR;
577 final public static void increaseCountingMap( final Map<String, Integer> counting_map, final String item_name ) {
578 if ( !counting_map.containsKey( item_name ) ) {
579 counting_map.put( item_name, 1 );
582 counting_map.put( item_name, counting_map.get( item_name ) + 1 );
586 final public static boolean isContainsParanthesesableNhCharacter( final String nh ) {
587 return PARANTHESESABLE_NH_CHARS_PATTERN.matcher( nh ).find();
590 final public static boolean isEmpty( final List<?> l ) {
591 if ( ( l == null ) || l.isEmpty() ) {
594 for( final Object o : l ) {
602 final public static boolean isEmpty( final Set<?> s ) {
603 if ( ( s == null ) || s.isEmpty() ) {
606 for( final Object o : s ) {
614 final public static boolean isEmpty( final String s ) {
615 return ( ( s == null ) || ( s.length() < 1 ) );
618 final public static boolean isEqual( final double a, final double b ) {
619 return ( ( Math.abs( a - b ) ) < ZERO_DIFF );
622 final public static boolean isEven( final int n ) {
623 return ( n % 2 ) == 0;
627 * This determines whether String[] a and String[] b have at least one
628 * String in common (intersect). Returns false if at least one String[] is
632 * a String[] b a String[]
633 * @return true if both a and b or not empty or null and contain at least
634 * one element in common false otherwise
636 final public static boolean isIntersecting( final String[] a, final String[] b ) {
637 if ( ( a == null ) || ( b == null ) ) {
640 if ( ( a.length < 1 ) || ( b.length < 1 ) ) {
643 for( final String ai : a ) {
644 for( final String element : b ) {
645 if ( ( ai != null ) && ( element != null ) && ai.equals( element ) ) {
653 final public static double isLargerOrEqualToZero( final double d ) {
662 final public static boolean isNull( final BigDecimal s ) {
663 return ( ( s == null ) || ( s.compareTo( NULL_BD ) == 0 ) );
666 final public static String isReadableFile( final File f ) {
668 return "file [" + f + "] does not exist";
670 if ( f.isDirectory() ) {
671 return "[" + f + "] is a directory";
674 return "[" + f + "] is not a file";
676 if ( !f.canRead() ) {
677 return "file [" + f + "] is not readable";
679 if ( f.length() < 1 ) {
680 return "file [" + f + "] is empty";
685 final public static String isReadableFile( final String s ) {
686 return isReadableFile( new File( s ) );
689 public final static boolean isWindows() {
691 return OS_NAME.toLowerCase().indexOf( "win" ) > -1;
693 catch ( final Exception e ) {
694 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
699 public final static boolean isMac() {
701 return OS_NAME.toLowerCase().startsWith( "mac" );
703 catch ( final Exception e ) {
704 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
709 final public static String isWritableFile( final File f ) {
710 if ( f.isDirectory() ) {
711 return "[" + f + "] is a directory";
714 return "[" + f + "] already exists";
720 * Helper for method "stringToColor".
722 * (Last modified: 12/20/03)
724 final public static int limitRangeForColor( int i ) {
734 final public static SortedMap<Object, Integer> listToSortedCountsMap( final List list ) {
735 final SortedMap<Object, Integer> map = new TreeMap<Object, Integer>();
736 for( final Object key : list ) {
737 if ( !map.containsKey( key ) ) {
741 map.put( key, map.get( key ) + 1 );
747 final public static void map2file( final File file,
748 final Map<?, ?> data,
749 final String entry_separator,
750 final String data_separator ) throws IOException {
751 final Writer writer = new BufferedWriter( new FileWriter( file ) );
752 map2writer( writer, data, entry_separator, data_separator );
756 final public static void map2writer( final Writer writer,
757 final Map<?, ?> data,
758 final String entry_separator,
759 final String data_separator ) throws IOException {
760 boolean first = true;
761 for( final Entry<?, ?> entry : data.entrySet() ) {
763 writer.write( data_separator );
768 writer.write( entry.getKey().toString() );
769 writer.write( entry_separator );
770 writer.write( entry.getValue().toString() );
774 final public static StringBuffer mapToStringBuffer( final Map map, final String key_value_separator ) {
775 final StringBuffer sb = new StringBuffer();
776 for( final Iterator iter = map.keySet().iterator(); iter.hasNext(); ) {
777 final Object key = iter.next();
778 sb.append( key.toString() );
779 sb.append( key_value_separator );
780 sb.append( map.get( key ).toString() );
781 sb.append( ForesterUtil.getLineSeparator() );
786 final public static String normalizeString( final String s,
788 final boolean left_pad,
789 final char pad_char ) {
790 if ( s.length() > length ) {
791 return s.substring( 0, length );
794 final StringBuffer pad = new StringBuffer( length - s.length() );
795 for( int i = 0; i < ( length - s.length() ); ++i ) {
796 pad.append( pad_char );
807 final public static BufferedReader obtainReader( final Object source ) throws IOException, FileNotFoundException {
808 BufferedReader reader = null;
809 if ( source instanceof File ) {
810 final File f = ( File ) source;
812 throw new IOException( "\"" + f.getAbsolutePath() + "\" does not exist" );
814 else if ( !f.isFile() ) {
815 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a file" );
817 else if ( !f.canRead() ) {
818 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a readable" );
820 reader = new BufferedReader( new FileReader( f ) );
822 else if ( source instanceof InputStream ) {
823 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
825 else if ( source instanceof String ) {
826 reader = new BufferedReader( new StringReader( ( String ) source ) );
828 else if ( source instanceof StringBuffer ) {
829 reader = new BufferedReader( new StringReader( source.toString() ) );
832 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
833 + "] (can only parse objects of type File, InputStream, String, or StringBuffer)" );
838 final public static StringBuffer pad( final double number, final int size, final char pad, final boolean left_pad ) {
839 return pad( new StringBuffer( number + "" ), size, pad, left_pad );
842 final public static StringBuffer pad( final String string, final int size, final char pad, final boolean left_pad ) {
843 return pad( new StringBuffer( string ), size, pad, left_pad );
846 final public static StringBuffer pad( final StringBuffer string,
849 final boolean left_pad ) {
850 final StringBuffer padding = new StringBuffer();
851 final int s = size - string.length();
853 return new StringBuffer( string.substring( 0, size ) );
855 for( int i = 0; i < s; ++i ) {
856 padding.append( pad );
859 return padding.append( string );
862 return string.append( padding );
866 final public static double parseDouble( final String str ) throws ParseException {
867 if ( ForesterUtil.isEmpty( str ) ) {
870 return Double.parseDouble( str );
873 final public static int parseInt( final String str ) throws ParseException {
874 if ( ForesterUtil.isEmpty( str ) ) {
877 return Integer.parseInt( str );
880 final public static void printArray( final Object[] a ) {
881 for( int i = 0; i < a.length; ++i ) {
882 System.out.println( "[" + i + "]=" + a[ i ] );
886 final public static void printCountingMap( final Map<String, Integer> counting_map ) {
887 for( final String key : counting_map.keySet() ) {
888 System.out.println( key + ": " + counting_map.get( key ) );
892 final public static void printErrorMessage( final String prg_name, final String message ) {
893 System.err.println( "[" + prg_name + "] > error: " + message );
896 final public static void printProgramInformation( final String prg_name, final String prg_version, final String date ) {
897 final int l = prg_name.length() + prg_version.length() + date.length() + 4;
898 System.out.println();
899 System.out.println( prg_name + " " + prg_version + " (" + date + ")" );
900 for( int i = 0; i < l; ++i ) {
901 System.out.print( "_" );
903 System.out.println();
906 final public static void printProgramInformation( final String prg_name,
907 final String prg_version,
911 printProgramInformation( prg_name, null, prg_version, date, email, www, null );
914 final public static void printProgramInformation( final String prg_name,
916 final String prg_version,
920 final String based_on ) {
921 String my_prg_name = new String( prg_name );
922 if ( !ForesterUtil.isEmpty( desc ) ) {
923 my_prg_name += ( " - " + desc );
925 final int l = my_prg_name.length() + prg_version.length() + date.length() + 4;
926 System.out.println();
927 System.out.println( my_prg_name + " " + prg_version + " (" + date + ")" );
928 for( int i = 0; i < l; ++i ) {
929 System.out.print( "_" );
931 System.out.println();
932 System.out.println();
933 System.out.println( "WWW : " + www );
934 System.out.println( "Contact : " + email );
935 if ( !ForesterUtil.isEmpty( based_on ) ) {
936 System.out.println( "Based on: " + based_on );
938 if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) {
939 System.out.println();
940 System.out.println( "[running on Java " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]" );
942 System.out.println();
945 final public static void printWarningMessage( final String prg_name, final String message ) {
946 System.out.println( "[" + prg_name + "] > warning: " + message );
949 final public static void programMessage( final String prg_name, final String message ) {
950 System.out.println( "[" + prg_name + "] > " + message );
953 final public static String removeSuffix( final String file_name ) {
954 final int i = file_name.lastIndexOf( '.' );
956 return file_name.substring( 0, i );
962 * Removes all white space from String s.
964 * @return String s with white space removed
966 final public static String removeWhiteSpace( String s ) {
968 for( i = 0; i <= ( s.length() - 1 ); i++ ) {
969 if ( ( s.charAt( i ) == ' ' ) || ( s.charAt( i ) == '\t' ) || ( s.charAt( i ) == '\n' )
970 || ( s.charAt( i ) == '\r' ) ) {
971 s = s.substring( 0, i ) + s.substring( i + 1 );
978 final public static String replaceIllegalNhCharacters( final String nh ) {
982 return nh.trim().replaceAll( "[\\[\\]:]+", "_" );
985 final public static String replaceIllegalNhxCharacters( final String nhx ) {
989 return nhx.trim().replaceAll( "[\\[\\](),:;\\s]+", "_" );
992 final public static double round( final double value, final int decimal_place ) {
993 BigDecimal bd = new BigDecimal( value );
994 bd = bd.setScale( decimal_place, BigDecimal.ROUND_HALF_UP );
995 return bd.doubleValue();
999 * Rounds d to an int.
1001 final public static int roundToInt( final double d ) {
1002 return ( int ) ( d + 0.5 );
1005 final public static int roundToInt( final float f ) {
1006 return ( int ) ( f + 0.5f );
1009 final public static short roundToShort( final double d ) {
1010 return ( short ) ( d + 0.5 );
1013 final public static String sanitizeString( final String s ) {
1022 public static boolean seqIsLikelyToBeAa( final String s ) {
1023 final String seq = s.toLowerCase();
1024 if ( ( seq.indexOf( 'r' ) > -1 ) || ( seq.indexOf( 'd' ) > -1 ) || ( seq.indexOf( 'e' ) > -1 )
1025 || ( seq.indexOf( 'q' ) > -1 ) || ( seq.indexOf( 'h' ) > -1 ) || ( seq.indexOf( 'k' ) > -1 )
1026 || ( seq.indexOf( 'w' ) > -1 ) || ( seq.indexOf( 's' ) > -1 ) || ( seq.indexOf( 'm' ) > -1 )
1027 || ( seq.indexOf( 'p' ) > -1 ) || ( seq.indexOf( 'v' ) > -1 ) ) {
1033 final public static String stringArrayToString( final String[] a ) {
1034 return stringArrayToString( a, ", " );
1037 final public static String stringArrayToString( final String[] a, final String separator ) {
1038 final StringBuilder sb = new StringBuilder();
1039 if ( ( a != null ) && ( a.length > 0 ) ) {
1040 for( int i = 0; i < ( a.length - 1 ); ++i ) {
1041 sb.append( a[ i ] + separator );
1043 sb.append( a[ a.length - 1 ] );
1045 return sb.toString();
1048 final public static String[] stringListToArray( final List<String> list ) {
1049 if ( list != null ) {
1050 final String[] str = new String[ list.size() ];
1052 for( final String l : list ) {
1060 final public static String stringListToString( final List<String> l, final String separator ) {
1061 final StringBuilder sb = new StringBuilder();
1062 if ( ( l != null ) && ( l.size() > 0 ) ) {
1063 for( int i = 0; i < ( l.size() - 1 ); ++i ) {
1064 sb.append( l.get( i ) + separator );
1066 sb.append( l.get( l.size() - 1 ) );
1068 return sb.toString();
1071 final public static String[] stringSetToArray( final Set<String> strings ) {
1072 final String[] str_array = new String[ strings.size() ];
1074 for( final String e : strings ) {
1075 str_array[ i++ ] = e;
1080 final public static void unexpectedFatalError( final Exception e ) {
1081 System.err.println();
1082 System.err.println( "unexpected exception: should not have occured! Please contact program author(s)." );
1083 e.printStackTrace( System.err );
1084 System.err.println();
1088 final public static void unexpectedFatalError( final Error e ) {
1089 System.err.println();
1090 System.err.println( "unexpected error: should not have occured! Please contact program author(s)." );
1091 e.printStackTrace( System.err );
1092 System.err.println();
1096 final public static void unexpectedFatalError( final String message ) {
1097 System.err.println();
1098 System.err.println( "unexpected error: should not have occured! Please contact program author(s)." );
1099 System.err.println( message );
1100 System.err.println();
1104 final public static void unexpectedFatalError( final String prg_name, final Exception e ) {
1105 System.err.println();
1106 System.err.println( "[" + prg_name
1107 + "] > unexpected error; should not have occured! Please contact program author(s)." );
1108 e.printStackTrace( System.err );
1109 System.err.println();
1113 final public static void unexpectedFatalError( final String prg_name, final String message ) {
1114 System.err.println();
1115 System.err.println( "[" + prg_name
1116 + "] > unexpected error: should not have occured! Please contact program author(s)." );
1117 System.err.println( message );
1118 System.err.println();
1122 final public static void unexpectedFatalError( final String prg_name, final String message, final Exception e ) {
1123 System.err.println();
1124 System.err.println( "[" + prg_name
1125 + "] > unexpected error: should not have occured! Please contact program author(s)." );
1126 System.err.println( message );
1127 e.printStackTrace( System.err );
1128 System.err.println();
1132 public final static void updateProgress( final double progress_percentage ) {
1133 final int width = 50;
1134 System.out.print( "\r[" );
1136 for( ; i <= ForesterUtil.roundToInt( progress_percentage * width ); i++ ) {
1137 System.out.print( "." );
1139 for( ; i < width; i++ ) {
1140 System.out.print( " " );
1142 System.out.print( "]" );
1145 public final static void updateProgress( final int i, final DecimalFormat f ) {
1146 System.out.print( "\r[" + f.format( i ) + "]" );
1149 public final static String wordWrap( final String str, final int width ) {
1150 final StringBuilder sb = new StringBuilder( str );
1154 while ( i < sb.length() ) {
1155 if ( sb.charAt( i ) == ' ' ) {
1158 if ( sb.charAt( i ) == '\n' ) {
1162 if ( i > ( ( start + width ) - 1 ) ) {
1164 sb.setCharAt( ls, '\n' );
1169 sb.insert( i, '\n' );
1175 return sb.toString();
1179 * Helper method for calcColor methods.
1181 * @param smallercolor_component_x
1182 * color component the smaller color
1183 * @param largercolor_component_x
1184 * color component the larger color
1187 * @return an int representing a color component
1189 final private static int calculateColorComponent( final double smallercolor_component_x,
1190 final double largercolor_component_x,
1192 return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
1196 * Helper method for calcColor methods.
1204 * the smallest value
1205 * @return a normalized value between larger and smaller
1207 final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
1208 return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
1211 final private static String[] splitString( final String str ) {
1212 final String regex = "[\\s;,]+";
1213 return str.split( regex );
1216 public final static void outOfMemoryError( final OutOfMemoryError e ) {
1217 System.err.println();
1218 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
1219 System.err.println();
1220 e.printStackTrace( System.err );
1221 System.err.println();