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.net.URLConnection;
45 import java.security.KeyManagementException;
46 import java.security.NoSuchAlgorithmException;
47 import java.text.DateFormat;
48 import java.text.DecimalFormat;
49 import java.text.DecimalFormatSymbols;
50 import java.text.NumberFormat;
51 import java.text.ParseException;
52 import java.text.SimpleDateFormat;
53 import java.util.ArrayList;
54 import java.util.Collection;
55 import java.util.Date;
56 import java.util.List;
58 import java.util.Map.Entry;
60 import java.util.SortedMap;
61 import java.util.SortedSet;
62 import java.util.TreeMap;
63 import java.util.TreeSet;
64 import java.util.regex.Matcher;
65 import java.util.regex.Pattern;
67 import org.forester.archaeopteryx.AptxConstants;
68 import org.forester.io.parsers.PhylogenyParser;
69 import org.forester.phylogeny.Phylogeny;
70 import org.forester.phylogeny.PhylogenyNode;
71 import org.forester.phylogeny.data.Distribution;
72 import org.forester.phylogeny.data.Sequence;
73 import org.forester.phylogeny.data.Taxonomy;
74 import org.forester.phylogeny.factories.ParserBasedPhylogenyFactory;
75 import org.forester.protein.BasicProtein;
76 import org.forester.protein.Domain;
77 import org.forester.protein.Protein;
78 import org.forester.sequence.MolecularSequence;
79 import org.forester.sequence.MolecularSequence.TYPE;
80 import org.forester.surfacing.SurfacingUtil;
82 public final class ForesterUtil {
84 public final static String FILE_SEPARATOR = System.getProperty( "file.separator" );
85 public static final NumberFormat FORMATTER_06;
86 public static final NumberFormat FORMATTER_3;
87 public static final NumberFormat FORMATTER_6;
88 public static final NumberFormat FORMATTER_9;
89 public final static String JAVA_VENDOR = System.getProperty( "java.vendor" );
90 public final static String JAVA_VERSION = System.getProperty( "java.version" );
91 public final static String LINE_SEPARATOR = System.getProperty( "line.separator" );
92 public static final String NCBI_GI = "http://www.ncbi.nlm.nih.gov/protein/gi:";
93 public static final String NCBI_NUCCORE = "http://www.ncbi.nlm.nih.gov/nuccore/";
94 public static final String NCBI_PROTEIN = "http://www.ncbi.nlm.nih.gov/protein/";
95 public static final BigDecimal NULL_BD = new BigDecimal( 0 );
96 public final static String OS_ARCH = System.getProperty( "os.arch" );
97 public final static String OS_NAME = System.getProperty( "os.name" );
98 public final static String OS_VERSION = System.getProperty( "os.version" );
99 public static final String PDB = "http://www.pdb.org/pdb/explore/explore.do?pdbId=";
100 public final static String UNIPROT_KB = "http://www.uniprot.org/uniprot/";
101 public final static double ZERO_DIFF = 1.0E-9;
102 private static final Pattern PARANTHESESABLE_NH_CHARS_PATTERN = Pattern.compile( "[(),;\\s:\\[\\]]" );
104 final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
105 dfs.setDecimalSeparator( '.' );
106 // dfs.setGroupingSeparator( ( char ) 0 );
107 FORMATTER_9 = new DecimalFormat( "#.#########", dfs );
108 FORMATTER_6 = new DecimalFormat( "#.######", dfs );
109 FORMATTER_06 = new DecimalFormat( "0.######", dfs );
110 FORMATTER_3 = new DecimalFormat( "#.###", dfs );
113 final public static void appendSeparatorIfNotEmpty( final StringBuffer sb, final char separator ) {
114 if ( sb.length() > 0 ) {
115 sb.append( separator );
120 * This calculates a color. If value is equal to min the returned color is
121 * minColor, if value is equal to max the returned color is maxColor,
122 * otherwise a color 'proportional' to value is returned.
136 final public static Color calcColor( double value,
139 final Color minColor,
140 final Color maxColor ) {
147 final double x = ForesterUtil.calculateColorFactor( value, max, min );
148 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), maxColor.getRed(), x );
149 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), maxColor.getGreen(), x );
150 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), maxColor.getBlue(), x );
151 return new Color( red, green, blue );
155 * This calculates a color. If value is equal to min the returned color is
156 * minColor, if value is equal to max the returned color is maxColor, if
157 * value is equal to mean the returned color is meanColor, otherwise a color
158 * 'proportional' to value is returned -- either between min-mean or
168 * the mean/median value
177 final public static Color calcColor( double value,
181 final Color minColor,
182 final Color maxColor,
183 final Color meanColor ) {
190 if ( value < mean ) {
191 final double x = ForesterUtil.calculateColorFactor( value, mean, min );
192 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), meanColor.getRed(), x );
193 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), meanColor.getGreen(), x );
194 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), meanColor.getBlue(), x );
195 return new Color( red, green, blue );
197 else if ( value > mean ) {
198 final double x = ForesterUtil.calculateColorFactor( value, max, mean );
199 final int red = ForesterUtil.calculateColorComponent( meanColor.getRed(), maxColor.getRed(), x );
200 final int green = ForesterUtil.calculateColorComponent( meanColor.getGreen(), maxColor.getGreen(), x );
201 final int blue = ForesterUtil.calculateColorComponent( meanColor.getBlue(), maxColor.getBlue(), x );
202 return new Color( red, green, blue );
210 * Helper method for calcColor methods.
212 * @param smallercolor_component_x
213 * color component the smaller color
214 * @param largercolor_component_x
215 * color component the larger color
218 * @return an int representing a color component
220 final private static int calculateColorComponent( final double smallercolor_component_x,
221 final double largercolor_component_x,
223 return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
227 * Helper method for calcColor methods.
236 * @return a normalized value between larger and smaller
238 final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
239 return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
242 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
243 int overlap_count = 0;
244 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
245 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
249 return overlap_count;
252 final public static String collapseWhiteSpace( final String s ) {
253 return s.replaceAll( "[\\s]+", " " );
256 final public static void collection2file( final File file, final Collection<?> data, final String separator )
258 final Writer writer = new BufferedWriter( new FileWriter( file ) );
259 collection2writer( writer, data, separator );
263 final public static void collection2writer( final Writer writer, final Collection<?> data, final String separator )
265 boolean first = true;
266 for( final Object object : data ) {
268 writer.write( separator );
273 writer.write( object.toString() );
277 final public static String colorToHex( final Color color ) {
278 final String rgb = Integer.toHexString( color.getRGB() );
279 return rgb.substring( 2, rgb.length() );
282 synchronized public static void copyFile( final File in, final File out ) throws IOException {
283 final FileInputStream in_s = new FileInputStream( in );
284 final FileOutputStream out_s = new FileOutputStream( out );
286 final byte[] buf = new byte[ 1024 ];
288 while ( ( i = in_s.read( buf ) ) != -1 ) {
289 out_s.write( buf, 0, i );
292 catch ( final IOException e ) {
296 if ( in_s != null ) {
299 if ( out_s != null ) {
305 final public static int countChars( final String str, final char c ) {
307 for( int i = 0; i < str.length(); ++i ) {
308 if ( str.charAt( i ) == c ) {
315 final public static BufferedWriter createBufferedWriter( final File file ) throws IOException {
316 if ( file.exists() ) {
317 throw new IOException( "[" + file + "] already exists" );
319 return new BufferedWriter( new FileWriter( file ) );
322 final public static BufferedWriter createBufferedWriter( final String name ) throws IOException {
323 return new BufferedWriter( new FileWriter( createFileForWriting( name ) ) );
326 final public static EasyWriter createEasyWriter( final File file ) throws IOException {
327 return new EasyWriter( createBufferedWriter( file ) );
330 final public static BufferedWriter createEasyWriter( final String name ) throws IOException {
331 return createEasyWriter( createFileForWriting( name ) );
334 final public static File createFileForWriting( final String name ) throws IOException {
335 final File file = new File( name );
336 if ( file.exists() ) {
337 throw new IOException( "[" + name + "] already exists" );
342 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
343 if ( !node.getNodeData().isHasDate() ) {
344 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
348 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
349 if ( !node.getNodeData().isHasDistribution() ) {
350 node.getNodeData().setDistribution( new Distribution( "" ) );
354 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
355 if ( !node.getNodeData().isHasSequence() ) {
356 node.getNodeData().setSequence( new Sequence() );
360 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
361 if ( !node.getNodeData().isHasTaxonomy() ) {
362 node.getNodeData().setTaxonomy( new Taxonomy() );
366 public static void fatalError( final String message ) {
367 System.err.println();
368 System.err.println( "error: " + message );
369 System.err.println();
373 public static void fatalError( final String prg_name, final String message ) {
374 System.err.println();
375 System.err.println( "[" + prg_name + "] > " + message );
376 System.err.println();
380 public static void fatalErrorIfFileNotReadable( final File file ) {
381 final String error = isReadableFile( file );
382 if ( !isEmpty( error ) ) {
383 System.err.println();
384 System.err.println( "error: " + error );
385 System.err.println();
390 public static void fatalErrorIfFileNotReadable( final String prg_name, final File file ) {
391 final String error = isReadableFile( file );
392 if ( !isEmpty( error ) ) {
393 System.err.println();
394 System.err.println( "[" + prg_name + "] > " + error );
395 System.err.println();
400 public static String[][] file22dArray( final File file ) throws IOException {
401 final List<String> list = new ArrayList<String>();
402 final BufferedReader in = new BufferedReader( new FileReader( file ) );
404 while ( ( str = in.readLine() ) != null ) {
406 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
411 final String[][] ary = new String[ list.size() ][ 2 ];
412 final Pattern pa = Pattern.compile( "(\\S+)\\s+(\\S+)" );
414 for( final String s : list ) {
415 final Matcher m = pa.matcher( s );
417 ary[ i ][ 0 ] = m.group( 1 );
418 ary[ i ][ 1 ] = m.group( 2 );
422 throw new IOException( "unexpcted format: " + s );
428 public static String[] file2array( final File file ) throws IOException {
429 final List<String> list = file2list( file );
430 final String[] ary = new String[ list.size() ];
432 for( final String s : list ) {
438 final public static List<String> file2list( final File file ) throws IOException {
439 final List<String> list = new ArrayList<String>();
440 final BufferedReader in = new BufferedReader( new FileReader( file ) );
442 while ( ( str = in.readLine() ) != null ) {
444 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
445 for( final String s : splitString( str ) ) {
454 final public static SortedSet<String> file2set( final File file ) throws IOException {
455 final SortedSet<String> set = new TreeSet<String>();
456 final BufferedReader in = new BufferedReader( new FileReader( file ) );
458 while ( ( str = in.readLine() ) != null ) {
460 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
461 for( final String s : splitString( str ) ) {
470 final public static String getCurrentDateTime() {
471 final DateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
472 return format.format( new Date() );
475 final public static String getFileSeparator() {
476 return ForesterUtil.FILE_SEPARATOR;
479 final public static String getFirstLine( final Object source ) throws FileNotFoundException, IOException {
480 BufferedReader reader = null;
481 if ( source instanceof File ) {
482 final File f = ( File ) source;
484 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
486 else if ( !f.isFile() ) {
487 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
489 else if ( !f.canRead() ) {
490 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
492 reader = new BufferedReader( new FileReader( f ) );
494 else if ( source instanceof InputStream ) {
495 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
497 else if ( source instanceof String ) {
498 reader = new BufferedReader( new StringReader( ( String ) source ) );
500 else if ( source instanceof StringBuffer ) {
501 reader = new BufferedReader( new StringReader( source.toString() ) );
503 else if ( source instanceof URL ) {
504 final URLConnection url_connection = ( ( URL ) source ).openConnection();
505 url_connection.setDefaultUseCaches( false );
506 reader = new BufferedReader( new InputStreamReader( url_connection.getInputStream() ) );
509 throw new IllegalArgumentException( "dont know how to read [" + source.getClass() + "]" );
512 while ( ( line = reader.readLine() ) != null ) {
514 if ( !ForesterUtil.isEmpty( line ) ) {
515 if ( reader != null ) {
521 if ( reader != null ) {
527 final public static String getForesterLibraryInformation() {
528 return "forester " + ForesterConstants.FORESTER_VERSION + " (" + ForesterConstants.FORESTER_DATE + ")";
531 final public static String getLineSeparator() {
532 return ForesterUtil.LINE_SEPARATOR;
535 final public static MolecularSequence.TYPE guessMolecularSequenceType( final String mol_seq ) {
536 if ( mol_seq.contains( "L" ) || mol_seq.contains( "I" ) || mol_seq.contains( "E" ) || mol_seq.contains( "H" )
537 || mol_seq.contains( "D" ) || mol_seq.contains( "Q" ) ) {
541 if ( mol_seq.contains( "T" ) ) {
544 else if ( mol_seq.contains( "U" ) ) {
551 final public static void increaseCountingMap( final Map<String, Integer> counting_map, final String item_name ) {
552 if ( !counting_map.containsKey( item_name ) ) {
553 counting_map.put( item_name, 1 );
556 counting_map.put( item_name, counting_map.get( item_name ) + 1 );
560 final public static boolean isEmpty( final List<?> l ) {
561 if ( ( l == null ) || l.isEmpty() ) {
564 for( final Object o : l ) {
572 final public static boolean isEmpty( final Set<?> s ) {
573 if ( ( s == null ) || s.isEmpty() ) {
576 for( final Object o : s ) {
584 final public static boolean isEmpty( final String s ) {
585 return ( ( s == null ) || ( s.length() < 1 ) );
589 * Returns true is Domain domain falls in an uninterrupted stretch of
593 * @param covered_positions
596 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
597 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
598 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
605 final public static boolean isEqual( final double a, final double b ) {
606 return ( ( Math.abs( a - b ) ) < ZERO_DIFF );
609 final public static boolean isEven( final int n ) {
610 return ( n % 2 ) == 0;
614 * This determines whether String[] a and String[] b have at least one
615 * String in common (intersect). Returns false if at least one String[] is
619 * a String[] b a String[]
620 * @return true if both a and b or not empty or null and contain at least
621 * one element in common false otherwise
623 final public static boolean isIntersecting( final String[] a, final String[] b ) {
624 if ( ( a == null ) || ( b == null ) ) {
627 if ( ( a.length < 1 ) || ( b.length < 1 ) ) {
630 for( final String ai : a ) {
631 for( final String element : b ) {
632 if ( ( ai != null ) && ( element != null ) && ai.equals( element ) ) {
640 final public static double isLargerOrEqualToZero( final double d ) {
649 public final static boolean isMac() {
651 return OS_NAME.toLowerCase().startsWith( "mac" );
653 catch ( final Exception e ) {
654 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, "minor error: " + e );
659 final public static boolean isNull( final BigDecimal s ) {
660 return ( ( s == null ) || ( s.compareTo( NULL_BD ) == 0 ) );
663 final public static String isReadableFile( final File f ) {
665 return "file [" + f + "] does not exist";
667 if ( f.isDirectory() ) {
668 return "[" + f + "] is a directory";
671 return "[" + f + "] is not a file";
673 if ( !f.canRead() ) {
674 return "file [" + f + "] is not readable";
676 if ( f.length() < 1 ) {
677 return "file [" + f + "] is empty";
682 final public static String isReadableFile( final String s ) {
683 return isReadableFile( new File( s ) );
686 public final static boolean isWindows() {
688 return OS_NAME.toLowerCase().indexOf( "win" ) > -1;
690 catch ( final Exception e ) {
691 ForesterUtil.printWarningMessage( AptxConstants.PRG_NAME, "minor error: " + e );
696 final public static String isWritableFile( final File f ) {
697 if ( f.isDirectory() ) {
698 return "[" + f + "] is a directory";
701 return "[" + f + "] already exists";
707 * Helper for method "stringToColor".
709 * (Last modified: 12/20/03)
711 final public static int limitRangeForColor( int i ) {
721 final public static SortedMap<Object, Integer> listToSortedCountsMap( final List<?> list ) {
722 final SortedMap<Object, Integer> map = new TreeMap<Object, Integer>();
723 for( final Object key : list ) {
724 if ( !map.containsKey( key ) ) {
728 map.put( key, map.get( key ) + 1 );
734 final public static void map2file( final File file,
735 final Map<?, ?> data,
736 final String entry_separator,
737 final String data_separator ) throws IOException {
738 final Writer writer = new BufferedWriter( new FileWriter( file ) );
739 map2writer( writer, data, entry_separator, data_separator );
743 final public static void map2writer( final Writer writer,
744 final Map<?, ?> data,
745 final String entry_separator,
746 final String data_separator ) throws IOException {
747 boolean first = true;
748 for( final Entry<?, ?> entry : data.entrySet() ) {
750 writer.write( data_separator );
755 writer.write( entry.getKey().toString() );
756 writer.write( entry_separator );
757 writer.write( entry.getValue().toString() );
761 final public static StringBuffer mapToStringBuffer( final Map<Object, Object> map, final String key_value_separator ) {
762 final StringBuffer sb = new StringBuffer();
763 for( final Object key : map.keySet() ) {
764 sb.append( key.toString() );
765 sb.append( key_value_separator );
766 sb.append( map.get( key ).toString() );
767 sb.append( ForesterUtil.getLineSeparator() );
772 final public static String normalizeString( final String s,
774 final boolean left_pad,
775 final char pad_char ) {
776 if ( s.length() > length ) {
777 return s.substring( 0, length );
780 final StringBuffer pad = new StringBuffer( length - s.length() );
781 for( int i = 0; i < ( length - s.length() ); ++i ) {
782 pad.append( pad_char );
793 public final static Color obtainColorDependingOnTaxonomyGroup( final String tax_group ) {
794 if ( !ForesterUtil.isEmpty( tax_group ) ) {
795 if ( tax_group.equals( TaxonomyGroups.DEUTEROSTOMIA ) ) {
796 return TaxonomyColors.DEUTEROSTOMIA_COLOR;
798 else if ( tax_group.equals( TaxonomyGroups.PROTOSTOMIA ) ) {
799 return TaxonomyColors.PROTOSTOMIA_COLOR;
801 else if ( tax_group.equals( TaxonomyGroups.CNIDARIA ) ) {
802 return TaxonomyColors.CNIDARIA_COLOR;
804 else if ( tax_group.equals( TaxonomyGroups.PLACOZOA ) ) {
805 return TaxonomyColors.PLACOZOA_COLOR;
807 else if ( tax_group.equals( TaxonomyGroups.CTENOPHORA ) ) {
808 return TaxonomyColors.CTENOPHORA_COLOR;
810 else if ( tax_group.equals( TaxonomyGroups.PORIFERA ) ) {
811 return TaxonomyColors.PORIFERA_COLOR;
813 else if ( tax_group.equals( TaxonomyGroups.CHOANOFLAGELLIDA ) ) {
814 return TaxonomyColors.CHOANOFLAGELLIDA;
816 else if ( tax_group.equals( TaxonomyGroups.ICHTHYOPHONIDA_FILASTEREA ) ) {
817 return TaxonomyColors.ICHTHYOSPOREA_AND_FILASTEREA;
819 else if ( tax_group.equals( TaxonomyGroups.DIKARYA ) ) {
820 return TaxonomyColors.DIKARYA_COLOR;
822 else if ( tax_group.equalsIgnoreCase( TaxonomyGroups.FUNGI )
823 || tax_group.equalsIgnoreCase( TaxonomyGroups.OTHER_FUNGI ) ) {
824 return TaxonomyColors.OTHER_FUNGI_COLOR;
826 else if ( tax_group.equals( TaxonomyGroups.NUCLEARIIDAE_AND_FONTICULA_GROUP ) ) {
827 return TaxonomyColors.NUCLEARIIDAE_AND_FONTICULA_GROUP_COLOR;
829 else if ( tax_group.equals( TaxonomyGroups.AMOEBOZOA ) ) {
830 return TaxonomyColors.AMOEBOZOA_COLOR;
832 else if ( tax_group.equals( TaxonomyGroups.EMBRYOPHYTA ) ) {
833 return TaxonomyColors.EMBRYOPHYTA_COLOR;
835 else if ( tax_group.equals( TaxonomyGroups.CHLOROPHYTA ) ) {
836 return TaxonomyColors.CHLOROPHYTA_COLOR;
838 else if ( tax_group.equals( TaxonomyGroups.RHODOPHYTA ) ) {
839 return TaxonomyColors.RHODOPHYTA_COLOR;
841 else if ( tax_group.equals( TaxonomyGroups.HACROBIA ) ) {
842 return TaxonomyColors.HACROBIA_COLOR;
844 else if ( tax_group.equals( TaxonomyGroups.GLAUCOCYSTOPHYCEAE ) ) {
845 return TaxonomyColors.GLAUCOPHYTA_COLOR;
847 else if ( tax_group.equals( TaxonomyGroups.STRAMENOPILES ) ) {
848 return TaxonomyColors.STRAMENOPILES_COLOR;
850 else if ( tax_group.equals( TaxonomyGroups.ALVEOLATA ) ) {
851 return TaxonomyColors.ALVEOLATA_COLOR;
853 else if ( tax_group.equals( TaxonomyGroups.RHIZARIA ) ) {
854 return TaxonomyColors.RHIZARIA_COLOR;
856 else if ( tax_group.equals( TaxonomyGroups.EXCAVATA ) ) {
857 return TaxonomyColors.EXCAVATA_COLOR;
859 else if ( tax_group.equals( TaxonomyGroups.APUSOZOA ) ) {
860 return TaxonomyColors.APUSOZOA_COLOR;
862 else if ( tax_group.equals( TaxonomyGroups.ARCHAEA ) ) {
863 return TaxonomyColors.ARCHAEA_COLOR;
865 else if ( tax_group.equals( TaxonomyGroups.BACTERIA ) ) {
866 return TaxonomyColors.BACTERIA_COLOR;
872 public final static String obtainNormalizedTaxonomyGroup( final String tax ) {
873 if ( tax.equalsIgnoreCase( TaxonomyGroups.DEUTEROSTOMIA ) ) {
874 return TaxonomyGroups.DEUTEROSTOMIA;
876 else if ( tax.equalsIgnoreCase( TaxonomyGroups.PROTOSTOMIA ) ) {
877 return TaxonomyGroups.PROTOSTOMIA;
879 else if ( tax.equalsIgnoreCase( TaxonomyGroups.CNIDARIA ) ) {
880 return TaxonomyGroups.CNIDARIA;
882 else if ( tax.toLowerCase().startsWith( "trichoplax" ) || tax.equalsIgnoreCase( TaxonomyGroups.PLACOZOA ) ) {
883 return TaxonomyGroups.PLACOZOA;
885 else if ( tax.toLowerCase().startsWith( "mnemiopsis" ) || tax.equalsIgnoreCase( TaxonomyGroups.CTENOPHORA ) ) {
886 return TaxonomyGroups.CTENOPHORA;
888 else if ( tax.toLowerCase().startsWith( "amphimedon" ) || tax.equalsIgnoreCase( TaxonomyGroups.PORIFERA ) ) {
889 return TaxonomyGroups.PORIFERA;
891 else if ( tax.equalsIgnoreCase( "codonosigidae" ) || tax.equalsIgnoreCase( TaxonomyGroups.CHOANOFLAGELLIDA ) ) {
892 return TaxonomyGroups.CHOANOFLAGELLIDA;
894 else if ( tax.toLowerCase().startsWith( TaxonomyGroups.ICHTHYOPHONIDA_FILASTEREA )
895 || tax.toLowerCase().startsWith( "ichthyophonida and filasterea" )
896 || tax.toLowerCase().startsWith( "ichthyosporea & filasterea" )
897 || tax.toLowerCase().startsWith( "ichthyosporea and filasterea" ) ) {
898 return TaxonomyGroups.ICHTHYOPHONIDA_FILASTEREA;
900 else if ( tax.equalsIgnoreCase( TaxonomyGroups.DIKARYA ) ) {
901 return TaxonomyGroups.DIKARYA;
903 else if ( tax.equalsIgnoreCase( TaxonomyGroups.FUNGI ) || tax.equalsIgnoreCase( TaxonomyGroups.OTHER_FUNGI ) ) {
904 return TaxonomyGroups.OTHER_FUNGI;
906 else if ( tax.toLowerCase().startsWith( "nucleariidae and fonticula" ) ) {
907 return TaxonomyGroups.NUCLEARIIDAE_AND_FONTICULA_GROUP;
909 else if ( tax.equalsIgnoreCase( TaxonomyGroups.AMOEBOZOA ) ) {
910 return TaxonomyGroups.AMOEBOZOA;
912 else if ( tax.equalsIgnoreCase( TaxonomyGroups.EMBRYOPHYTA ) ) {
913 return TaxonomyGroups.EMBRYOPHYTA;
915 else if ( tax.equalsIgnoreCase( TaxonomyGroups.CHLOROPHYTA ) ) {
916 return TaxonomyGroups.CHLOROPHYTA;
918 else if ( tax.equalsIgnoreCase( TaxonomyGroups.RHODOPHYTA ) ) {
919 return TaxonomyGroups.RHODOPHYTA;
921 else if ( tax.toLowerCase().startsWith( TaxonomyGroups.HACROBIA ) ) {
922 return TaxonomyGroups.HACROBIA;
924 else if ( tax.equalsIgnoreCase( TaxonomyGroups.GLAUCOCYSTOPHYCEAE ) || tax.equalsIgnoreCase( "glaucophyta" ) ) {
925 return TaxonomyGroups.GLAUCOCYSTOPHYCEAE;
927 else if ( tax.equalsIgnoreCase( TaxonomyGroups.STRAMENOPILES ) ) {
928 return TaxonomyGroups.STRAMENOPILES;
930 else if ( tax.equalsIgnoreCase( TaxonomyGroups.ALVEOLATA ) ) {
931 return TaxonomyGroups.ALVEOLATA;
933 else if ( tax.equalsIgnoreCase( TaxonomyGroups.RHIZARIA ) ) {
934 return TaxonomyGroups.RHIZARIA;
936 else if ( tax.equalsIgnoreCase( TaxonomyGroups.EXCAVATA ) ) {
937 return TaxonomyGroups.EXCAVATA;
939 else if ( tax.equalsIgnoreCase( TaxonomyGroups.APUSOZOA ) ) {
940 return TaxonomyGroups.APUSOZOA;
942 else if ( tax.equalsIgnoreCase( TaxonomyGroups.ARCHAEA ) ) {
943 return TaxonomyGroups.ARCHAEA;
945 else if ( tax.equalsIgnoreCase( TaxonomyGroups.BACTERIA ) ) {
946 return TaxonomyGroups.BACTERIA;
951 final public static BufferedReader obtainReader( final Object source ) throws IOException, FileNotFoundException {
952 BufferedReader reader = null;
953 if ( source instanceof File ) {
954 final File f = ( File ) source;
956 throw new IOException( "\"" + f.getAbsolutePath() + "\" does not exist" );
958 else if ( !f.isFile() ) {
959 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a file" );
961 else if ( !f.canRead() ) {
962 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a readable" );
964 reader = new BufferedReader( new FileReader( f ) );
966 else if ( source instanceof InputStream ) {
967 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
969 else if ( source instanceof String ) {
970 reader = new BufferedReader( new StringReader( ( String ) source ) );
972 else if ( source instanceof StringBuffer ) {
973 reader = new BufferedReader( new StringReader( source.toString() ) );
976 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
977 + "] (can only parse objects of type File, InputStream, String, or StringBuffer)" );
982 public final static void outOfMemoryError( final OutOfMemoryError e ) {
983 System.err.println();
984 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
985 System.err.println();
986 e.printStackTrace( System.err );
987 System.err.println();
991 final public static StringBuffer pad( final double number, final int size, final char pad, final boolean left_pad ) {
992 return pad( new StringBuffer( number + "" ), size, pad, left_pad );
995 final public static StringBuffer pad( final String string, final int size, final char pad, final boolean left_pad ) {
996 return pad( new StringBuffer( string ), size, pad, left_pad );
999 final public static StringBuffer pad( final StringBuffer string,
1002 final boolean left_pad ) {
1003 final StringBuffer padding = new StringBuffer();
1004 final int s = size - string.length();
1006 return new StringBuffer( string.substring( 0, size ) );
1008 for( int i = 0; i < s; ++i ) {
1009 padding.append( pad );
1012 return padding.append( string );
1015 return string.append( padding );
1019 final public static double parseDouble( final String str ) throws ParseException {
1020 if ( ForesterUtil.isEmpty( str ) ) {
1023 return Double.parseDouble( str );
1026 final public static int parseInt( final String str ) throws ParseException {
1027 if ( ForesterUtil.isEmpty( str ) ) {
1030 return Integer.parseInt( str );
1033 final public static void printArray( final Object[] a ) {
1034 for( int i = 0; i < a.length; ++i ) {
1035 System.out.println( "[" + i + "]=" + a[ i ] );
1039 final public static void printCountingMap( final Map<String, Integer> counting_map ) {
1040 for( final String key : counting_map.keySet() ) {
1041 System.out.println( key + ": " + counting_map.get( key ) );
1045 final public static void printErrorMessage( final String prg_name, final String message ) {
1046 System.err.println( "[" + prg_name + "] > error: " + message );
1049 final public static void printProgramInformation( final String prg_name, final String prg_version, final String date ) {
1050 final int l = prg_name.length() + prg_version.length() + date.length() + 4;
1051 System.out.println();
1052 System.out.println( prg_name + " " + prg_version + " (" + date + ")" );
1053 for( int i = 0; i < l; ++i ) {
1054 System.out.print( "_" );
1056 System.out.println();
1059 final public static void printProgramInformation( final String prg_name,
1060 final String prg_version,
1063 final String www ) {
1064 printProgramInformation( prg_name, null, prg_version, date, email, www, null );
1067 final public static void printProgramInformation( final String prg_name,
1069 final String prg_version,
1073 final String based_on ) {
1074 String my_prg_name = new String( prg_name );
1075 if ( !ForesterUtil.isEmpty( desc ) ) {
1076 my_prg_name += ( " - " + desc );
1078 final int l = my_prg_name.length() + prg_version.length() + date.length() + 4;
1079 System.out.println();
1080 System.out.println( my_prg_name + " " + prg_version + " (" + date + ")" );
1081 for( int i = 0; i < l; ++i ) {
1082 System.out.print( "_" );
1084 System.out.println();
1085 System.out.println();
1086 System.out.println( "WWW : " + www );
1087 System.out.println( "Contact : " + email );
1088 if ( !ForesterUtil.isEmpty( based_on ) ) {
1089 System.out.println( "Based on: " + based_on );
1091 if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) {
1092 System.out.println();
1093 System.out.println( "[running on Java " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]" );
1095 System.out.println();
1098 final public static void printWarningMessage( final String prg_name, final String message ) {
1099 System.out.println( "[" + prg_name + "] > warning: " + message );
1102 final public static void programMessage( final String prg_name, final String message ) {
1103 System.out.println( "[" + prg_name + "] > " + message );
1106 public static List<String> readUrl( final String url_str ) throws IOException {
1107 final URL url = new URL( url_str );
1108 final URLConnection urlc = url.openConnection();
1109 //urlc.setRequestProperty( "User-Agent", "" );
1110 final BufferedReader in = new BufferedReader( new InputStreamReader( urlc.getInputStream() ) );
1112 final List<String> result = new ArrayList<String>();
1113 while ( ( line = in.readLine() ) != null ) {
1122 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1123 * domain with 0.3 is ignored
1125 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1128 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1131 * @param max_allowed_overlap
1132 * maximal allowed overlap (inclusive) to be still considered not
1133 * overlapping (zero or negative value to allow any overlap)
1134 * @param remove_engulfed_domains
1135 * to remove domains which are completely engulfed by coverage of
1136 * domains with better support
1140 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1141 final boolean remove_engulfed_domains,
1142 final Protein protein ) {
1143 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1144 .getSpeciesId(), protein.getLength() );
1145 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1146 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1147 for( final Domain domain : sorted ) {
1148 if ( ( ( max_allowed_overlap < 0 ) || ( ForesterUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1149 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1150 final int covered_positions_size = covered_positions.size();
1151 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1152 covered_positions.add( false );
1154 final int new_covered_positions_size = covered_positions.size();
1155 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1156 if ( i < new_covered_positions_size ) {
1157 covered_positions.set( i, true );
1160 covered_positions.add( true );
1163 pruned_protein.addProteinDomain( domain );
1166 return pruned_protein;
1169 final public static String removeSuffix( final String file_name ) {
1170 final int i = file_name.lastIndexOf( '.' );
1172 return file_name.substring( 0, i );
1178 * Removes all white space from String s.
1180 * @return String s with white space removed
1182 final public static String removeWhiteSpace( String s ) {
1184 for( i = 0; i <= ( s.length() - 1 ); i++ ) {
1185 if ( ( s.charAt( i ) == ' ' ) || ( s.charAt( i ) == '\t' ) || ( s.charAt( i ) == '\n' )
1186 || ( s.charAt( i ) == '\r' ) ) {
1187 s = s.substring( 0, i ) + s.substring( i + 1 );
1194 final public static String replaceIllegalNhxCharacters( final String nhx ) {
1195 if ( nhx == null ) {
1198 return nhx.trim().replaceAll( "[\\[\\]']+", "_" );
1201 final public static double round( final double value, final int decimal_place ) {
1202 BigDecimal bd = new BigDecimal( value );
1203 bd = bd.setScale( decimal_place, BigDecimal.ROUND_HALF_UP );
1204 return bd.doubleValue();
1208 * Rounds d to an int.
1210 final public static int roundToInt( final double d ) {
1211 return ( int ) ( d + 0.5 );
1214 final public static int roundToInt( final float f ) {
1215 return ( int ) ( f + 0.5f );
1218 final public static short roundToShort( final double d ) {
1219 return ( short ) ( d + 0.5 );
1222 final public static String sanitizeString( final String s ) {
1231 public final static StringBuilder santitizeStringForNH( String data ) {
1232 data = data.replaceAll( "\\s+", " " ).trim();
1233 final StringBuilder sb = new StringBuilder();
1234 if ( data.length() > 0 ) {
1235 final boolean single_pars = data.indexOf( '\'' ) > -1;
1236 final boolean double_pars = data.indexOf( '"' ) > -1;
1237 if ( single_pars && double_pars ) {
1238 data = data.replace( '\'', '`' );
1243 else if ( single_pars ) {
1248 else if ( PARANTHESESABLE_NH_CHARS_PATTERN.matcher( data ).find() ) {
1260 public static boolean seqIsLikelyToBeAa( final String s ) {
1261 final String seq = s.toLowerCase();
1262 if ( ( seq.indexOf( 'r' ) > -1 ) || ( seq.indexOf( 'd' ) > -1 ) || ( seq.indexOf( 'e' ) > -1 )
1263 || ( seq.indexOf( 'q' ) > -1 ) || ( seq.indexOf( 'h' ) > -1 ) || ( seq.indexOf( 'k' ) > -1 )
1264 || ( seq.indexOf( 'w' ) > -1 ) || ( seq.indexOf( 's' ) > -1 ) || ( seq.indexOf( 'm' ) > -1 )
1265 || ( seq.indexOf( 'p' ) > -1 ) || ( seq.indexOf( 'v' ) > -1 ) ) {
1271 final private static String[] splitString( final String str ) {
1272 final String regex = "[\\s;,]+";
1273 return str.split( regex );
1276 final public static String stringArrayToString( final String[] a ) {
1277 return stringArrayToString( a, ", " );
1280 final public static String stringArrayToString( final String[] a, final String separator ) {
1281 final StringBuilder sb = new StringBuilder();
1282 if ( ( a != null ) && ( a.length > 0 ) ) {
1283 for( int i = 0; i < ( a.length - 1 ); ++i ) {
1284 sb.append( a[ i ] + separator );
1286 sb.append( a[ a.length - 1 ] );
1288 return sb.toString();
1291 final public static String[] stringListToArray( final List<String> list ) {
1292 if ( list != null ) {
1293 final String[] str = new String[ list.size() ];
1295 for( final String l : list ) {
1303 final public static String stringListToString( final List<String> l, final String separator ) {
1304 final StringBuilder sb = new StringBuilder();
1305 if ( ( l != null ) && ( l.size() > 0 ) ) {
1306 for( int i = 0; i < ( l.size() - 1 ); ++i ) {
1307 sb.append( l.get( i ) + separator );
1309 sb.append( l.get( l.size() - 1 ) );
1311 return sb.toString();
1314 final public static String[] stringSetToArray( final Set<String> strings ) {
1315 final String[] str_array = new String[ strings.size() ];
1317 for( final String e : strings ) {
1318 str_array[ i++ ] = e;
1323 final public static void unexpectedFatalError( final Error e ) {
1324 System.err.println();
1325 System.err.println( "unexpected error: should not have occured! Please contact program author(s)." );
1326 e.printStackTrace( System.err );
1327 System.err.println();
1331 final public static void unexpectedFatalError( final Exception e ) {
1332 System.err.println();
1333 System.err.println( "unexpected exception: should not have occured! Please contact program author(s)." );
1334 e.printStackTrace( System.err );
1335 System.err.println();
1339 final public static void unexpectedFatalError( final String message ) {
1340 System.err.println();
1341 System.err.println( "unexpected error: should not have occured! Please contact program author(s)." );
1342 System.err.println( message );
1343 System.err.println();
1347 final public static void unexpectedFatalError( final String prg_name, final Exception e ) {
1348 System.err.println();
1349 System.err.println( "[" + prg_name
1350 + "] > unexpected error; should not have occured! Please contact program author(s)." );
1351 e.printStackTrace( System.err );
1352 System.err.println();
1356 final public static void unexpectedFatalError( final String prg_name, final String message ) {
1357 System.err.println();
1358 System.err.println( "[" + prg_name
1359 + "] > unexpected error: should not have occured! Please contact program author(s)." );
1360 System.err.println( message );
1361 System.err.println();
1365 final public static void unexpectedFatalError( final String prg_name, final String message, final Exception e ) {
1366 System.err.println();
1367 System.err.println( "[" + prg_name
1368 + "] > unexpected error: should not have occured! Please contact program author(s)." );
1369 System.err.println( message );
1370 e.printStackTrace( System.err );
1371 System.err.println();
1375 public final static void updateProgress( final double progress_percentage ) {
1376 final int width = 50;
1377 System.out.print( "\r[" );
1379 for( ; i <= ForesterUtil.roundToInt( progress_percentage * width ); i++ ) {
1380 System.out.print( "." );
1382 for( ; i < width; i++ ) {
1383 System.out.print( " " );
1385 System.out.print( "]" );
1388 public final static void updateProgress( final int i, final DecimalFormat f ) {
1389 System.out.print( "\r[" + f.format( i ) + "]" );
1392 public final static String wordWrap( final String str, final int width ) {
1393 final StringBuilder sb = new StringBuilder( str );
1397 while ( i < sb.length() ) {
1398 if ( sb.charAt( i ) == ' ' ) {
1401 if ( sb.charAt( i ) == '\n' ) {
1405 if ( i > ( ( start + width ) - 1 ) ) {
1407 sb.setCharAt( ls, '\n' );
1412 sb.insert( i, '\n' );
1418 return sb.toString();
1422 public final static Phylogeny[] readPhylogeniesFromUrl( final URL url,
1423 final PhylogenyParser parser )
1424 throws NoSuchAlgorithmException, IOException, KeyManagementException {
1425 if ( url == null ) {
1426 throw new IllegalArgumentException( "URL to read from must not be null" );
1428 else if ( parser == null ) {
1429 throw new IllegalArgumentException( "parser to use to read from URL must not be null" );
1431 final URLConnection con;
1432 if ( url.toString().startsWith( "https:" ) ) {
1433 con = TrustManager.makeHttpsURLConnection( url );
1435 else if ( url.toString().startsWith( "http:" ) ) {
1436 con = url.openConnection();
1439 throw new IllegalArgumentException( "Cannot deal with URL: " + url );
1441 if ( con == null ) {
1442 throw new IOException( "could not create connection from " + url );
1444 con.setDefaultUseCaches( false );
1445 final InputStream is = con.getInputStream();
1447 throw new IOException( "could not create input stream from " + url );
1449 final Phylogeny[] trees = ParserBasedPhylogenyFactory.getInstance().create( is, parser );
1453 catch ( final Exception e ) {
1459 private ForesterUtil() {