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.text.DateFormat;
46 import java.text.DecimalFormat;
47 import java.text.DecimalFormatSymbols;
48 import java.text.NumberFormat;
49 import java.text.ParseException;
50 import java.text.SimpleDateFormat;
51 import java.util.ArrayList;
52 import java.util.Collection;
53 import java.util.Date;
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 static final NumberFormat FORMATTER_06;
79 public static final NumberFormat FORMATTER_3;
80 public static final NumberFormat FORMATTER_6;
81 public static final NumberFormat FORMATTER_9;
82 public final static String JAVA_VENDOR = System.getProperty( "java.vendor" );
83 public final static String JAVA_VERSION = System.getProperty( "java.version" );
84 public final static String LINE_SEPARATOR = System.getProperty( "line.separator" );
85 public static final String NCBI_GI = "http://www.ncbi.nlm.nih.gov/protein/gi:";
86 public static final String NCBI_NUCCORE = "http://www.ncbi.nlm.nih.gov/nuccore/";
87 public static final String NCBI_PROTEIN = "http://www.ncbi.nlm.nih.gov/protein/";
88 public static final BigDecimal NULL_BD = new BigDecimal( 0 );
89 public final static String OS_ARCH = System.getProperty( "os.arch" );
90 public final static String OS_NAME = System.getProperty( "os.name" );
91 public final static String OS_VERSION = System.getProperty( "os.version" );
92 public static final String PDB = "http://www.pdb.org/pdb/explore/explore.do?pdbId=";
93 public final static String UNIPROT_KB = "http://www.uniprot.org/uniprot/";
94 public final static double ZERO_DIFF = 1.0E-9;
95 private static final Pattern PARANTHESESABLE_NH_CHARS_PATTERN = Pattern.compile( "[(),;\\s:\\[\\]]" );
97 final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
98 dfs.setDecimalSeparator( '.' );
99 // dfs.setGroupingSeparator( ( char ) 0 );
100 FORMATTER_9 = new DecimalFormat( "#.#########", dfs );
101 FORMATTER_6 = new DecimalFormat( "#.######", dfs );
102 FORMATTER_06 = new DecimalFormat( "0.######", dfs );
103 FORMATTER_3 = new DecimalFormat( "#.###", dfs );
106 private ForesterUtil() {
109 final public static void appendSeparatorIfNotEmpty( final StringBuffer sb, final char separator ) {
110 if ( sb.length() > 0 ) {
111 sb.append( separator );
116 * This calculates a color. If value is equal to min the returned color is
117 * minColor, if value is equal to max the returned color is maxColor,
118 * otherwise a color 'proportional' to value is returned.
132 final public static Color calcColor( double value,
135 final Color minColor,
136 final Color maxColor ) {
143 final double x = ForesterUtil.calculateColorFactor( value, max, min );
144 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), maxColor.getRed(), x );
145 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), maxColor.getGreen(), x );
146 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), maxColor.getBlue(), x );
147 return new Color( red, green, blue );
151 * This calculates a color. If value is equal to min the returned color is
152 * minColor, if value is equal to max the returned color is maxColor, if
153 * value is equal to mean the returned color is meanColor, otherwise a color
154 * 'proportional' to value is returned -- either between min-mean or
164 * the mean/median value
173 final public static Color calcColor( double value,
177 final Color minColor,
178 final Color maxColor,
179 final Color meanColor ) {
186 if ( value < mean ) {
187 final double x = ForesterUtil.calculateColorFactor( value, mean, min );
188 final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), meanColor.getRed(), x );
189 final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), meanColor.getGreen(), x );
190 final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), meanColor.getBlue(), x );
191 return new Color( red, green, blue );
193 else if ( value > mean ) {
194 final double x = ForesterUtil.calculateColorFactor( value, max, mean );
195 final int red = ForesterUtil.calculateColorComponent( meanColor.getRed(), maxColor.getRed(), x );
196 final int green = ForesterUtil.calculateColorComponent( meanColor.getGreen(), maxColor.getGreen(), x );
197 final int blue = ForesterUtil.calculateColorComponent( meanColor.getBlue(), maxColor.getBlue(), x );
198 return new Color( red, green, blue );
205 public static int calculateOverlap( final Domain domain, final List<Boolean> covered_positions ) {
206 int overlap_count = 0;
207 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
208 if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
212 return overlap_count;
215 final public static String collapseWhiteSpace( final String s ) {
216 return s.replaceAll( "[\\s]+", " " );
219 final public static void collection2file( final File file, final Collection<?> data, final String separator )
221 final Writer writer = new BufferedWriter( new FileWriter( file ) );
222 collection2writer( writer, data, separator );
226 final public static void collection2writer( final Writer writer, final Collection<?> data, final String separator )
228 boolean first = true;
229 for( final Object object : data ) {
231 writer.write( separator );
236 writer.write( object.toString() );
240 final public static String colorToHex( final Color color ) {
241 final String rgb = Integer.toHexString( color.getRGB() );
242 return rgb.substring( 2, rgb.length() );
245 synchronized public static void copyFile( final File in, final File out ) throws IOException {
246 final FileInputStream in_s = new FileInputStream( in );
247 final FileOutputStream out_s = new FileOutputStream( out );
249 final byte[] buf = new byte[ 1024 ];
251 while ( ( i = in_s.read( buf ) ) != -1 ) {
252 out_s.write( buf, 0, i );
255 catch ( final IOException e ) {
259 if ( in_s != null ) {
262 if ( out_s != null ) {
268 final public static int countChars( final String str, final char c ) {
270 for( int i = 0; i < str.length(); ++i ) {
271 if ( str.charAt( i ) == c ) {
278 final public static BufferedWriter createBufferedWriter( final File file ) throws IOException {
279 if ( file.exists() ) {
280 throw new IOException( "[" + file + "] already exists" );
282 return new BufferedWriter( new FileWriter( file ) );
285 final public static BufferedWriter createBufferedWriter( final String name ) throws IOException {
286 return new BufferedWriter( new FileWriter( createFileForWriting( name ) ) );
289 final public static EasyWriter createEasyWriter( final File file ) throws IOException {
290 return new EasyWriter( createBufferedWriter( file ) );
293 final public static BufferedWriter createEasyWriter( final String name ) throws IOException {
294 return createEasyWriter( createFileForWriting( name ) );
297 final public static File createFileForWriting( final String name ) throws IOException {
298 final File file = new File( name );
299 if ( file.exists() ) {
300 throw new IOException( "[" + name + "] already exists" );
305 final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
306 if ( !node.getNodeData().isHasDate() ) {
307 node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
311 final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
312 if ( !node.getNodeData().isHasDistribution() ) {
313 node.getNodeData().setDistribution( new Distribution( "" ) );
317 public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
318 if ( !node.getNodeData().isHasSequence() ) {
319 node.getNodeData().setSequence( new Sequence() );
323 public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
324 if ( !node.getNodeData().isHasTaxonomy() ) {
325 node.getNodeData().setTaxonomy( new Taxonomy() );
329 public static void fatalError( final String message ) {
330 System.err.println();
331 System.err.println( "error: " + message );
332 System.err.println();
336 public static void fatalError( final String prg_name, final String message ) {
337 System.err.println();
338 System.err.println( "[" + prg_name + "] > " + message );
339 System.err.println();
343 public static void fatalErrorIfFileNotReadable( final File file ) {
344 final String error = isReadableFile( file );
345 if ( !isEmpty( error ) ) {
346 System.err.println();
347 System.err.println( "error: " + error );
348 System.err.println();
353 public static void fatalErrorIfFileNotReadable( final String prg_name, final File file ) {
354 final String error = isReadableFile( file );
355 if ( !isEmpty( error ) ) {
356 System.err.println();
357 System.err.println( "[" + prg_name + "] > " + error );
358 System.err.println();
363 public static String[][] file22dArray( final File file ) throws IOException {
364 final List<String> list = new ArrayList<String>();
365 final BufferedReader in = new BufferedReader( new FileReader( file ) );
367 while ( ( str = in.readLine() ) != null ) {
369 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
374 final String[][] ary = new String[ list.size() ][ 2 ];
375 final Pattern pa = Pattern.compile( "(\\S+)\\s+(\\S+)" );
377 for( final String s : list ) {
378 final Matcher m = pa.matcher( s );
380 ary[ i ][ 0 ] = m.group( 1 );
381 ary[ i ][ 1 ] = m.group( 2 );
385 throw new IOException( "unexpcted format: " + s );
391 public static String[] file2array( final File file ) throws IOException {
392 final List<String> list = file2list( file );
393 final String[] ary = new String[ list.size() ];
395 for( final String s : list ) {
401 final public static List<String> file2list( final File file ) throws IOException {
402 final List<String> list = new ArrayList<String>();
403 final BufferedReader in = new BufferedReader( new FileReader( file ) );
405 while ( ( str = in.readLine() ) != null ) {
407 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
408 for( final String s : splitString( str ) ) {
417 final public static SortedSet<String> file2set( final File file ) throws IOException {
418 final SortedSet<String> set = new TreeSet<String>();
419 final BufferedReader in = new BufferedReader( new FileReader( file ) );
421 while ( ( str = in.readLine() ) != null ) {
423 if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
424 for( final String s : splitString( str ) ) {
433 final public static String getCurrentDateTime() {
434 final DateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
435 return format.format( new Date() );
438 final public static String getFileSeparator() {
439 return ForesterUtil.FILE_SEPARATOR;
442 final public static String getFirstLine( final Object source ) throws FileNotFoundException, IOException {
443 BufferedReader reader = null;
444 if ( source instanceof File ) {
445 final File f = ( File ) source;
447 throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
449 else if ( !f.isFile() ) {
450 throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
452 else if ( !f.canRead() ) {
453 throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
455 reader = new BufferedReader( new FileReader( f ) );
457 else if ( source instanceof InputStream ) {
458 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
460 else if ( source instanceof String ) {
461 reader = new BufferedReader( new StringReader( ( String ) source ) );
463 else if ( source instanceof StringBuffer ) {
464 reader = new BufferedReader( new StringReader( source.toString() ) );
466 else if ( source instanceof URL ) {
467 final URLConnection url_connection = ( ( URL ) source ).openConnection();
468 url_connection.setDefaultUseCaches( false );
469 reader = new BufferedReader( new InputStreamReader( url_connection.getInputStream() ) );
472 throw new IllegalArgumentException( "dont know how to read [" + source.getClass() + "]" );
475 while ( ( line = reader.readLine() ) != null ) {
477 if ( !ForesterUtil.isEmpty( line ) ) {
478 if ( reader != null ) {
484 if ( reader != null ) {
490 final public static String getForesterLibraryInformation() {
491 return "forester " + ForesterConstants.FORESTER_VERSION + " (" + ForesterConstants.FORESTER_DATE + ")";
494 final public static String getLineSeparator() {
495 return ForesterUtil.LINE_SEPARATOR;
498 final public static void increaseCountingMap( final Map<String, Integer> counting_map, final String item_name ) {
499 if ( !counting_map.containsKey( item_name ) ) {
500 counting_map.put( item_name, 1 );
503 counting_map.put( item_name, counting_map.get( item_name ) + 1 );
507 final public static boolean isEmpty( final List<?> l ) {
508 if ( ( l == null ) || l.isEmpty() ) {
511 for( final Object o : l ) {
519 final public static boolean isEmpty( final Set<?> s ) {
520 if ( ( s == null ) || s.isEmpty() ) {
523 for( final Object o : s ) {
531 final public static boolean isEmpty( final String s ) {
532 return ( ( s == null ) || ( s.length() < 1 ) );
536 * Returns true is Domain domain falls in an uninterrupted stretch of
540 * @param covered_positions
543 public static boolean isEngulfed( final Domain domain, final List<Boolean> covered_positions ) {
544 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
545 if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
552 final public static boolean isEqual( final double a, final double b ) {
553 return ( ( Math.abs( a - b ) ) < ZERO_DIFF );
556 final public static boolean isEven( final int n ) {
557 return ( n % 2 ) == 0;
561 * This determines whether String[] a and String[] b have at least one
562 * String in common (intersect). Returns false if at least one String[] is
566 * a String[] b a String[]
567 * @return true if both a and b or not empty or null and contain at least
568 * one element in common false otherwise
570 final public static boolean isIntersecting( final String[] a, final String[] b ) {
571 if ( ( a == null ) || ( b == null ) ) {
574 if ( ( a.length < 1 ) || ( b.length < 1 ) ) {
577 for( final String ai : a ) {
578 for( final String element : b ) {
579 if ( ( ai != null ) && ( element != null ) && ai.equals( element ) ) {
587 final public static double isLargerOrEqualToZero( final double d ) {
596 public final static boolean isMac() {
598 return OS_NAME.toLowerCase().startsWith( "mac" );
600 catch ( final Exception e ) {
601 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
606 final public static boolean isNull( final BigDecimal s ) {
607 return ( ( s == null ) || ( s.compareTo( NULL_BD ) == 0 ) );
610 final public static String isReadableFile( final File f ) {
612 return "file [" + f + "] does not exist";
614 if ( f.isDirectory() ) {
615 return "[" + f + "] is a directory";
618 return "[" + f + "] is not a file";
620 if ( !f.canRead() ) {
621 return "file [" + f + "] is not readable";
623 if ( f.length() < 1 ) {
624 return "file [" + f + "] is empty";
629 final public static String isReadableFile( final String s ) {
630 return isReadableFile( new File( s ) );
633 public final static boolean isWindows() {
635 return OS_NAME.toLowerCase().indexOf( "win" ) > -1;
637 catch ( final Exception e ) {
638 ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
643 final public static String isWritableFile( final File f ) {
644 if ( f.isDirectory() ) {
645 return "[" + f + "] is a directory";
648 return "[" + f + "] already exists";
654 * Helper for method "stringToColor".
656 * (Last modified: 12/20/03)
658 final public static int limitRangeForColor( int i ) {
668 final public static SortedMap<Object, Integer> listToSortedCountsMap( final List<?> list ) {
669 final SortedMap<Object, Integer> map = new TreeMap<Object, Integer>();
670 for( final Object key : list ) {
671 if ( !map.containsKey( key ) ) {
675 map.put( key, map.get( key ) + 1 );
681 final public static void map2file( final File file,
682 final Map<?, ?> data,
683 final String entry_separator,
684 final String data_separator ) throws IOException {
685 final Writer writer = new BufferedWriter( new FileWriter( file ) );
686 map2writer( writer, data, entry_separator, data_separator );
690 final public static void map2writer( final Writer writer,
691 final Map<?, ?> data,
692 final String entry_separator,
693 final String data_separator ) throws IOException {
694 boolean first = true;
695 for( final Entry<?, ?> entry : data.entrySet() ) {
697 writer.write( data_separator );
702 writer.write( entry.getKey().toString() );
703 writer.write( entry_separator );
704 writer.write( entry.getValue().toString() );
708 final public static StringBuffer mapToStringBuffer( final Map<Object, Object> map, final String key_value_separator ) {
709 final StringBuffer sb = new StringBuffer();
710 for( final Object key : map.keySet() ) {
711 sb.append( key.toString() );
712 sb.append( key_value_separator );
713 sb.append( map.get( key ).toString() );
714 sb.append( ForesterUtil.getLineSeparator() );
719 final public static String normalizeString( final String s,
721 final boolean left_pad,
722 final char pad_char ) {
723 if ( s.length() > length ) {
724 return s.substring( 0, length );
727 final StringBuffer pad = new StringBuffer( length - s.length() );
728 for( int i = 0; i < ( length - s.length() ); ++i ) {
729 pad.append( pad_char );
740 public final static Color obtainColorDependingOnTaxonomyGroup( final String tax_group ) {
741 if ( !ForesterUtil.isEmpty( tax_group ) ) {
742 if ( tax_group.equals( TaxonomyGroups.DEUTEROSTOMIA ) ) {
743 return TaxonomyColors.DEUTEROSTOMIA_COLOR;
745 else if ( tax_group.equals( TaxonomyGroups.PROTOSTOMIA ) ) {
746 return TaxonomyColors.PROTOSTOMIA_COLOR;
748 else if ( tax_group.equals( TaxonomyGroups.CNIDARIA ) ) {
749 return TaxonomyColors.CNIDARIA_COLOR;
751 else if ( tax_group.equals( TaxonomyGroups.PLACOZOA ) ) {
752 return TaxonomyColors.PLACOZOA_COLOR;
754 else if ( tax_group.equals( TaxonomyGroups.CTENOPHORA ) ) {
755 return TaxonomyColors.CTENOPHORA_COLOR;
757 else if ( tax_group.equals( TaxonomyGroups.PORIFERA ) ) {
758 return TaxonomyColors.PORIFERA_COLOR;
760 else if ( tax_group.equals( TaxonomyGroups.CHOANOFLAGELLIDA ) ) {
761 return TaxonomyColors.CHOANOFLAGELLIDA;
763 else if ( tax_group.equals( TaxonomyGroups.ICHTHYOPHONIDA_FILASTEREA ) ) {
764 return TaxonomyColors.ICHTHYOSPOREA_AND_FILASTEREA;
766 else if ( tax_group.equals( TaxonomyGroups.DIKARYA ) ) {
767 return TaxonomyColors.DIKARYA_COLOR;
769 else if ( tax_group.equalsIgnoreCase( TaxonomyGroups.FUNGI )
770 || tax_group.equalsIgnoreCase( TaxonomyGroups.OTHER_FUNGI ) ) {
771 return TaxonomyColors.OTHER_FUNGI_COLOR;
773 else if ( tax_group.equals( TaxonomyGroups.NUCLEARIIDAE_AND_FONTICULA_GROUP ) ) {
774 return TaxonomyColors.NUCLEARIIDAE_AND_FONTICULA_GROUP_COLOR;
776 else if ( tax_group.equals( TaxonomyGroups.AMOEBOZOA ) ) {
777 return TaxonomyColors.AMOEBOZOA_COLOR;
779 else if ( tax_group.equals( TaxonomyGroups.EMBRYOPHYTA ) ) {
780 return TaxonomyColors.EMBRYOPHYTA_COLOR;
782 else if ( tax_group.equals( TaxonomyGroups.CHLOROPHYTA ) ) {
783 return TaxonomyColors.CHLOROPHYTA_COLOR;
785 else if ( tax_group.equals( TaxonomyGroups.RHODOPHYTA ) ) {
786 return TaxonomyColors.RHODOPHYTA_COLOR;
788 else if ( tax_group.equals( TaxonomyGroups.HACROBIA ) ) {
789 return TaxonomyColors.HACROBIA_COLOR;
791 else if ( tax_group.equals( TaxonomyGroups.GLAUCOCYSTOPHYCEAE ) ) {
792 return TaxonomyColors.GLAUCOPHYTA_COLOR;
794 else if ( tax_group.equals( TaxonomyGroups.STRAMENOPILES ) ) {
795 return TaxonomyColors.STRAMENOPILES_COLOR;
797 else if ( tax_group.equals( TaxonomyGroups.ALVEOLATA ) ) {
798 return TaxonomyColors.ALVEOLATA_COLOR;
800 else if ( tax_group.equals( TaxonomyGroups.RHIZARIA ) ) {
801 return TaxonomyColors.RHIZARIA_COLOR;
803 else if ( tax_group.equals( TaxonomyGroups.EXCAVATA ) ) {
804 return TaxonomyColors.EXCAVATA_COLOR;
806 else if ( tax_group.equals( TaxonomyGroups.APUSOZOA ) ) {
807 return TaxonomyColors.APUSOZOA_COLOR;
809 else if ( tax_group.equals( TaxonomyGroups.ARCHAEA ) ) {
810 return TaxonomyColors.ARCHAEA_COLOR;
812 else if ( tax_group.equals( TaxonomyGroups.BACTERIA ) ) {
813 return TaxonomyColors.BACTERIA_COLOR;
819 public final static String obtainNormalizedTaxonomyGroup( final String tax ) {
820 if ( tax.equalsIgnoreCase( TaxonomyGroups.DEUTEROSTOMIA ) ) {
821 return TaxonomyGroups.DEUTEROSTOMIA;
823 else if ( tax.equalsIgnoreCase( TaxonomyGroups.PROTOSTOMIA ) ) {
824 return TaxonomyGroups.PROTOSTOMIA;
826 else if ( tax.equalsIgnoreCase( TaxonomyGroups.CNIDARIA ) ) {
827 return TaxonomyGroups.CNIDARIA;
829 else if ( tax.toLowerCase().startsWith( "trichoplax" ) || tax.equalsIgnoreCase( TaxonomyGroups.PLACOZOA ) ) {
830 return TaxonomyGroups.PLACOZOA;
832 else if ( tax.toLowerCase().startsWith( "mnemiopsis" ) || tax.equalsIgnoreCase( TaxonomyGroups.CTENOPHORA ) ) {
833 return TaxonomyGroups.CTENOPHORA;
835 else if ( tax.toLowerCase().startsWith( "amphimedon" ) || tax.equalsIgnoreCase( TaxonomyGroups.PORIFERA ) ) {
836 return TaxonomyGroups.PORIFERA;
838 else if ( tax.equalsIgnoreCase( "codonosigidae" ) || tax.equalsIgnoreCase( TaxonomyGroups.CHOANOFLAGELLIDA ) ) {
839 return TaxonomyGroups.CHOANOFLAGELLIDA;
841 else if ( tax.toLowerCase().startsWith( TaxonomyGroups.ICHTHYOPHONIDA_FILASTEREA )
842 || tax.toLowerCase().startsWith( "ichthyophonida and filasterea" )
843 || tax.toLowerCase().startsWith( "ichthyosporea & filasterea" )
844 || tax.toLowerCase().startsWith( "ichthyosporea and filasterea" ) ) {
845 return TaxonomyGroups.ICHTHYOPHONIDA_FILASTEREA;
847 else if ( tax.equalsIgnoreCase( TaxonomyGroups.DIKARYA ) ) {
848 return TaxonomyGroups.DIKARYA;
850 else if ( tax.equalsIgnoreCase( TaxonomyGroups.FUNGI ) || tax.equalsIgnoreCase( TaxonomyGroups.OTHER_FUNGI ) ) {
851 return TaxonomyGroups.OTHER_FUNGI;
853 else if ( tax.toLowerCase().startsWith( "nucleariidae and fonticula" ) ) {
854 return TaxonomyGroups.NUCLEARIIDAE_AND_FONTICULA_GROUP;
856 else if ( tax.equalsIgnoreCase( TaxonomyGroups.AMOEBOZOA ) ) {
857 return TaxonomyGroups.AMOEBOZOA;
859 else if ( tax.equalsIgnoreCase( TaxonomyGroups.EMBRYOPHYTA ) ) {
860 return TaxonomyGroups.EMBRYOPHYTA;
862 else if ( tax.equalsIgnoreCase( TaxonomyGroups.CHLOROPHYTA ) ) {
863 return TaxonomyGroups.CHLOROPHYTA;
865 else if ( tax.equalsIgnoreCase( TaxonomyGroups.RHODOPHYTA ) ) {
866 return TaxonomyGroups.RHODOPHYTA;
868 else if ( tax.toLowerCase().startsWith( TaxonomyGroups.HACROBIA ) ) {
869 return TaxonomyGroups.HACROBIA;
871 else if ( tax.equalsIgnoreCase( TaxonomyGroups.GLAUCOCYSTOPHYCEAE ) || tax.equalsIgnoreCase( "glaucophyta" ) ) {
872 return TaxonomyGroups.GLAUCOCYSTOPHYCEAE;
874 else if ( tax.equalsIgnoreCase( TaxonomyGroups.STRAMENOPILES ) ) {
875 return TaxonomyGroups.STRAMENOPILES;
877 else if ( tax.equalsIgnoreCase( TaxonomyGroups.ALVEOLATA ) ) {
878 return TaxonomyGroups.ALVEOLATA;
880 else if ( tax.equalsIgnoreCase( TaxonomyGroups.RHIZARIA ) ) {
881 return TaxonomyGroups.RHIZARIA;
883 else if ( tax.equalsIgnoreCase( TaxonomyGroups.EXCAVATA ) ) {
884 return TaxonomyGroups.EXCAVATA;
886 else if ( tax.equalsIgnoreCase( TaxonomyGroups.APUSOZOA ) ) {
887 return TaxonomyGroups.APUSOZOA;
889 else if ( tax.equalsIgnoreCase( TaxonomyGroups.ARCHAEA ) ) {
890 return TaxonomyGroups.ARCHAEA;
892 else if ( tax.equalsIgnoreCase( TaxonomyGroups.BACTERIA ) ) {
893 return TaxonomyGroups.BACTERIA;
898 final public static BufferedReader obtainReader( final Object source ) throws IOException, FileNotFoundException {
899 BufferedReader reader = null;
900 if ( source instanceof File ) {
901 final File f = ( File ) source;
903 throw new IOException( "\"" + f.getAbsolutePath() + "\" does not exist" );
905 else if ( !f.isFile() ) {
906 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a file" );
908 else if ( !f.canRead() ) {
909 throw new IOException( "\"" + f.getAbsolutePath() + "\" is not a readable" );
911 reader = new BufferedReader( new FileReader( f ) );
913 else if ( source instanceof InputStream ) {
914 reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
916 else if ( source instanceof String ) {
917 reader = new BufferedReader( new StringReader( ( String ) source ) );
919 else if ( source instanceof StringBuffer ) {
920 reader = new BufferedReader( new StringReader( source.toString() ) );
923 throw new IllegalArgumentException( "attempt to parse object of type [" + source.getClass()
924 + "] (can only parse objects of type File, InputStream, String, or StringBuffer)" );
929 public final static void outOfMemoryError( final OutOfMemoryError e ) {
930 System.err.println();
931 System.err.println( "Java memory allocation might be too small, try \"-Xmx2048m\" java command line option" );
932 System.err.println();
933 e.printStackTrace( System.err );
934 System.err.println();
938 final public static StringBuffer pad( final double number, final int size, final char pad, final boolean left_pad ) {
939 return pad( new StringBuffer( number + "" ), size, pad, left_pad );
942 final public static StringBuffer pad( final String string, final int size, final char pad, final boolean left_pad ) {
943 return pad( new StringBuffer( string ), size, pad, left_pad );
946 final public static StringBuffer pad( final StringBuffer string,
949 final boolean left_pad ) {
950 final StringBuffer padding = new StringBuffer();
951 final int s = size - string.length();
953 return new StringBuffer( string.substring( 0, size ) );
955 for( int i = 0; i < s; ++i ) {
956 padding.append( pad );
959 return padding.append( string );
962 return string.append( padding );
966 final public static double parseDouble( final String str ) throws ParseException {
967 if ( ForesterUtil.isEmpty( str ) ) {
970 return Double.parseDouble( str );
973 final public static int parseInt( final String str ) throws ParseException {
974 if ( ForesterUtil.isEmpty( str ) ) {
977 return Integer.parseInt( str );
980 final public static void printArray( final Object[] a ) {
981 for( int i = 0; i < a.length; ++i ) {
982 System.out.println( "[" + i + "]=" + a[ i ] );
986 final public static void printCountingMap( final Map<String, Integer> counting_map ) {
987 for( final String key : counting_map.keySet() ) {
988 System.out.println( key + ": " + counting_map.get( key ) );
992 final public static void printErrorMessage( final String prg_name, final String message ) {
993 System.err.println( "[" + prg_name + "] > error: " + message );
996 final public static void printProgramInformation( final String prg_name, final String prg_version, final String date ) {
997 final int l = prg_name.length() + prg_version.length() + date.length() + 4;
998 System.out.println();
999 System.out.println( prg_name + " " + prg_version + " (" + date + ")" );
1000 for( int i = 0; i < l; ++i ) {
1001 System.out.print( "_" );
1003 System.out.println();
1006 final public static void printProgramInformation( final String prg_name,
1007 final String prg_version,
1010 final String www ) {
1011 printProgramInformation( prg_name, null, prg_version, date, email, www, null );
1014 final public static void printProgramInformation( final String prg_name,
1016 final String prg_version,
1020 final String based_on ) {
1021 String my_prg_name = new String( prg_name );
1022 if ( !ForesterUtil.isEmpty( desc ) ) {
1023 my_prg_name += ( " - " + desc );
1025 final int l = my_prg_name.length() + prg_version.length() + date.length() + 4;
1026 System.out.println();
1027 System.out.println( my_prg_name + " " + prg_version + " (" + date + ")" );
1028 for( int i = 0; i < l; ++i ) {
1029 System.out.print( "_" );
1031 System.out.println();
1032 System.out.println();
1033 System.out.println( "WWW : " + www );
1034 System.out.println( "Contact : " + email );
1035 if ( !ForesterUtil.isEmpty( based_on ) ) {
1036 System.out.println( "Based on: " + based_on );
1038 if ( !ForesterUtil.isEmpty( ForesterUtil.JAVA_VERSION ) && !ForesterUtil.isEmpty( ForesterUtil.JAVA_VENDOR ) ) {
1039 System.out.println();
1040 System.out.println( "[running on Java " + ForesterUtil.JAVA_VERSION + " " + ForesterUtil.JAVA_VENDOR + "]" );
1042 System.out.println();
1045 final public static void printWarningMessage( final String prg_name, final String message ) {
1046 System.out.println( "[" + prg_name + "] > warning: " + message );
1049 final public static void programMessage( final String prg_name, final String message ) {
1050 System.out.println( "[" + prg_name + "] > " + message );
1055 * Example regarding engulfment: ------------0.1 ----------0.2 --0.3 =>
1056 * domain with 0.3 is ignored
1058 * -----------0.1 ----------0.2 --0.3 => domain with 0.3 is ignored
1061 * ------------0.1 ----------0.3 --0.2 => domains with 0.3 and 0.2 are _not_
1064 * @param max_allowed_overlap
1065 * maximal allowed overlap (inclusive) to be still considered not
1066 * overlapping (zero or negative value to allow any overlap)
1067 * @param remove_engulfed_domains
1068 * to remove domains which are completely engulfed by coverage of
1069 * domains with better support
1073 public static Protein removeOverlappingDomains( final int max_allowed_overlap,
1074 final boolean remove_engulfed_domains,
1075 final Protein protein ) {
1076 final Protein pruned_protein = new BasicProtein( protein.getProteinId().getId(), protein.getSpecies()
1077 .getSpeciesId(), protein.getLength() );
1078 final List<Domain> sorted = SurfacingUtil.sortDomainsWithAscendingConfidenceValues( protein );
1079 final List<Boolean> covered_positions = new ArrayList<Boolean>();
1080 for( final Domain domain : sorted ) {
1081 if ( ( ( max_allowed_overlap < 0 ) || ( ForesterUtil.calculateOverlap( domain, covered_positions ) <= max_allowed_overlap ) )
1082 && ( !remove_engulfed_domains || !isEngulfed( domain, covered_positions ) ) ) {
1083 final int covered_positions_size = covered_positions.size();
1084 for( int i = covered_positions_size; i < domain.getFrom(); ++i ) {
1085 covered_positions.add( false );
1087 final int new_covered_positions_size = covered_positions.size();
1088 for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
1089 if ( i < new_covered_positions_size ) {
1090 covered_positions.set( i, true );
1093 covered_positions.add( true );
1096 pruned_protein.addProteinDomain( domain );
1099 return pruned_protein;
1102 final public static String removeSuffix( final String file_name ) {
1103 final int i = file_name.lastIndexOf( '.' );
1105 return file_name.substring( 0, i );
1111 * Removes all white space from String s.
1113 * @return String s with white space removed
1115 final public static String removeWhiteSpace( String s ) {
1117 for( i = 0; i <= ( s.length() - 1 ); i++ ) {
1118 if ( ( s.charAt( i ) == ' ' ) || ( s.charAt( i ) == '\t' ) || ( s.charAt( i ) == '\n' )
1119 || ( s.charAt( i ) == '\r' ) ) {
1120 s = s.substring( 0, i ) + s.substring( i + 1 );
1127 final public static String replaceIllegalNhxCharacters( final String nhx ) {
1128 if ( nhx == null ) {
1131 return nhx.trim().replaceAll( "[\\[\\]']+", "_" );
1134 final public static double round( final double value, final int decimal_place ) {
1135 BigDecimal bd = new BigDecimal( value );
1136 bd = bd.setScale( decimal_place, BigDecimal.ROUND_HALF_UP );
1137 return bd.doubleValue();
1141 * Rounds d to an int.
1143 final public static int roundToInt( final double d ) {
1144 return ( int ) ( d + 0.5 );
1147 final public static int roundToInt( final float f ) {
1148 return ( int ) ( f + 0.5f );
1151 final public static short roundToShort( final double d ) {
1152 return ( short ) ( d + 0.5 );
1155 final public static String sanitizeString( final String s ) {
1164 public final static StringBuilder santitizeStringForNH( String data ) {
1165 data = data.replaceAll( "\\s+", " " ).trim();
1166 final StringBuilder sb = new StringBuilder();
1167 if ( data.length() > 0 ) {
1168 final boolean single_pars = data.indexOf( '\'' ) > -1;
1169 final boolean double_pars = data.indexOf( '"' ) > -1;
1170 if ( single_pars && double_pars ) {
1171 data = data.replace( '\'', '`' );
1176 else if ( single_pars ) {
1181 else if ( PARANTHESESABLE_NH_CHARS_PATTERN.matcher( data ).find() ) {
1193 public static boolean seqIsLikelyToBeAa( final String s ) {
1194 final String seq = s.toLowerCase();
1195 if ( ( seq.indexOf( 'r' ) > -1 ) || ( seq.indexOf( 'd' ) > -1 ) || ( seq.indexOf( 'e' ) > -1 )
1196 || ( seq.indexOf( 'q' ) > -1 ) || ( seq.indexOf( 'h' ) > -1 ) || ( seq.indexOf( 'k' ) > -1 )
1197 || ( seq.indexOf( 'w' ) > -1 ) || ( seq.indexOf( 's' ) > -1 ) || ( seq.indexOf( 'm' ) > -1 )
1198 || ( seq.indexOf( 'p' ) > -1 ) || ( seq.indexOf( 'v' ) > -1 ) ) {
1204 final public static String stringArrayToString( final String[] a ) {
1205 return stringArrayToString( a, ", " );
1208 final public static String stringArrayToString( final String[] a, final String separator ) {
1209 final StringBuilder sb = new StringBuilder();
1210 if ( ( a != null ) && ( a.length > 0 ) ) {
1211 for( int i = 0; i < ( a.length - 1 ); ++i ) {
1212 sb.append( a[ i ] + separator );
1214 sb.append( a[ a.length - 1 ] );
1216 return sb.toString();
1219 final public static String[] stringListToArray( final List<String> list ) {
1220 if ( list != null ) {
1221 final String[] str = new String[ list.size() ];
1223 for( final String l : list ) {
1231 final public static String stringListToString( final List<String> l, final String separator ) {
1232 final StringBuilder sb = new StringBuilder();
1233 if ( ( l != null ) && ( l.size() > 0 ) ) {
1234 for( int i = 0; i < ( l.size() - 1 ); ++i ) {
1235 sb.append( l.get( i ) + separator );
1237 sb.append( l.get( l.size() - 1 ) );
1239 return sb.toString();
1242 final public static String[] stringSetToArray( final Set<String> strings ) {
1243 final String[] str_array = new String[ strings.size() ];
1245 for( final String e : strings ) {
1246 str_array[ i++ ] = e;
1251 final public static void unexpectedFatalError( final Error e ) {
1252 System.err.println();
1253 System.err.println( "unexpected error: should not have occured! Please contact program author(s)." );
1254 e.printStackTrace( System.err );
1255 System.err.println();
1259 final public static void unexpectedFatalError( final Exception e ) {
1260 System.err.println();
1261 System.err.println( "unexpected exception: should not have occured! Please contact program author(s)." );
1262 e.printStackTrace( System.err );
1263 System.err.println();
1267 final public static void unexpectedFatalError( final String message ) {
1268 System.err.println();
1269 System.err.println( "unexpected error: should not have occured! Please contact program author(s)." );
1270 System.err.println( message );
1271 System.err.println();
1275 final public static void unexpectedFatalError( final String prg_name, final Exception e ) {
1276 System.err.println();
1277 System.err.println( "[" + prg_name
1278 + "] > unexpected error; should not have occured! Please contact program author(s)." );
1279 e.printStackTrace( System.err );
1280 System.err.println();
1284 final public static void unexpectedFatalError( final String prg_name, final String message ) {
1285 System.err.println();
1286 System.err.println( "[" + prg_name
1287 + "] > unexpected error: should not have occured! Please contact program author(s)." );
1288 System.err.println( message );
1289 System.err.println();
1293 final public static void unexpectedFatalError( final String prg_name, final String message, final Exception e ) {
1294 System.err.println();
1295 System.err.println( "[" + prg_name
1296 + "] > unexpected error: should not have occured! Please contact program author(s)." );
1297 System.err.println( message );
1298 e.printStackTrace( System.err );
1299 System.err.println();
1303 public final static void updateProgress( final double progress_percentage ) {
1304 final int width = 50;
1305 System.out.print( "\r[" );
1307 for( ; i <= ForesterUtil.roundToInt( progress_percentage * width ); i++ ) {
1308 System.out.print( "." );
1310 for( ; i < width; i++ ) {
1311 System.out.print( " " );
1313 System.out.print( "]" );
1316 public final static void updateProgress( final int i, final DecimalFormat f ) {
1317 System.out.print( "\r[" + f.format( i ) + "]" );
1320 public final static String wordWrap( final String str, final int width ) {
1321 final StringBuilder sb = new StringBuilder( str );
1325 while ( i < sb.length() ) {
1326 if ( sb.charAt( i ) == ' ' ) {
1329 if ( sb.charAt( i ) == '\n' ) {
1333 if ( i > ( ( start + width ) - 1 ) ) {
1335 sb.setCharAt( ls, '\n' );
1340 sb.insert( i, '\n' );
1346 return sb.toString();
1350 * Helper method for calcColor methods.
1352 * @param smallercolor_component_x
1353 * color component the smaller color
1354 * @param largercolor_component_x
1355 * color component the larger color
1358 * @return an int representing a color component
1360 final private static int calculateColorComponent( final double smallercolor_component_x,
1361 final double largercolor_component_x,
1363 return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
1367 * Helper method for calcColor methods.
1375 * the smallest value
1376 * @return a normalized value between larger and smaller
1378 final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
1379 return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
1382 final private static String[] splitString( final String str ) {
1383 final String regex = "[\\s;,]+";
1384 return str.split( regex );