org.forester.util.ForesterUtil Maven / Gradle / Ivy
Go to download
Show more of this group Show more artifacts with this name
Show all versions of forester Show documentation
Show all versions of forester Show documentation
Applications and software libraries for evolutionary biology and comparative genomics research
The newest version!
// $Id:
// FORESTER -- software libraries and applications
// for evolutionary biology research and applications.
//
// Copyright (C) 2008-2009 Christian M. Zmasek
// Copyright (C) 2008-2009 Burnham Institute for Medical Research
// All rights reserved
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation; either
// version 2.1 of the License, or (at your option) any later version.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
//
// Contact: phylosoft @ gmail . com
// WWW: https://sites.google.com/site/cmzmasek/home/software/forester
package org.forester.util;
import java.awt.Color;
import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileNotFoundException;
import java.io.FileOutputStream;
import java.io.FileReader;
import java.io.FileWriter;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.StringReader;
import java.io.Writer;
import java.math.BigDecimal;
import java.net.URL;
import java.net.URLConnection;
import java.text.DateFormat;
import java.text.DecimalFormat;
import java.text.DecimalFormatSymbols;
import java.text.NumberFormat;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;
import java.util.SortedMap;
import java.util.SortedSet;
import java.util.TreeMap;
import java.util.TreeSet;
import java.util.regex.Matcher;
import java.util.regex.Pattern;
import org.forester.archaeopteryx.Constants;
import org.forester.phylogeny.PhylogenyNode;
import org.forester.phylogeny.data.Distribution;
import org.forester.phylogeny.data.Sequence;
import org.forester.phylogeny.data.Taxonomy;
import org.forester.protein.BasicProtein;
import org.forester.protein.Domain;
import org.forester.protein.Protein;
import org.forester.sequence.MolecularSequence;
import org.forester.sequence.MolecularSequence.TYPE;
import org.forester.surfacing.SurfacingUtil;
public final class ForesterUtil {
public final static String FILE_SEPARATOR = System.getProperty( "file.separator" );
public static final NumberFormat FORMATTER_06;
public static final NumberFormat FORMATTER_3;
public static final NumberFormat FORMATTER_6;
public static final NumberFormat FORMATTER_9;
public final static String JAVA_VENDOR = System.getProperty( "java.vendor" );
public final static String JAVA_VERSION = System.getProperty( "java.version" );
public final static String LINE_SEPARATOR = System.getProperty( "line.separator" );
public static final String NCBI_GI = "http://www.ncbi.nlm.nih.gov/protein/gi:";
public static final String NCBI_NUCCORE = "http://www.ncbi.nlm.nih.gov/nuccore/";
public static final String NCBI_PROTEIN = "http://www.ncbi.nlm.nih.gov/protein/";
public static final BigDecimal NULL_BD = new BigDecimal( 0 );
public final static String OS_ARCH = System.getProperty( "os.arch" );
public final static String OS_NAME = System.getProperty( "os.name" );
public final static String OS_VERSION = System.getProperty( "os.version" );
public static final String PDB = "http://www.pdb.org/pdb/explore/explore.do?pdbId=";
public final static String UNIPROT_KB = "http://www.uniprot.org/uniprot/";
public final static double ZERO_DIFF = 1.0E-9;
private static final Pattern PARANTHESESABLE_NH_CHARS_PATTERN = Pattern.compile( "[(),;\\s:\\[\\]]" );
static {
final DecimalFormatSymbols dfs = new DecimalFormatSymbols();
dfs.setDecimalSeparator( '.' );
// dfs.setGroupingSeparator( ( char ) 0 );
FORMATTER_9 = new DecimalFormat( "#.#########", dfs );
FORMATTER_6 = new DecimalFormat( "#.######", dfs );
FORMATTER_06 = new DecimalFormat( "0.######", dfs );
FORMATTER_3 = new DecimalFormat( "#.###", dfs );
}
final public static void appendSeparatorIfNotEmpty( final StringBuffer sb, final char separator ) {
if ( sb.length() > 0 ) {
sb.append( separator );
}
}
/**
* This calculates a color. If value is equal to min the returned color is
* minColor, if value is equal to max the returned color is maxColor,
* otherwise a color 'proportional' to value is returned.
*
* @param value
* the value
* @param min
* the smallest value
* @param max
* the largest value
* @param minColor
* the color for min
* @param maxColor
* the color for max
* @return a Color
*/
final public static Color calcColor( double value,
final double min,
final double max,
final Color minColor,
final Color maxColor ) {
if ( value < min ) {
value = min;
}
if ( value > max ) {
value = max;
}
final double x = ForesterUtil.calculateColorFactor( value, max, min );
final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), maxColor.getRed(), x );
final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), maxColor.getGreen(), x );
final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), maxColor.getBlue(), x );
return new Color( red, green, blue );
}
/**
* This calculates a color. If value is equal to min the returned color is
* minColor, if value is equal to max the returned color is maxColor, if
* value is equal to mean the returned color is meanColor, otherwise a color
* 'proportional' to value is returned -- either between min-mean or
* mean-max
*
* @param value
* the value
* @param min
* the smallest value
* @param max
* the largest value
* @param mean
* the mean/median value
* @param minColor
* the color for min
* @param maxColor
* the color for max
* @param meanColor
* the color for mean
* @return a Color
*/
final public static Color calcColor( double value,
final double min,
final double max,
final double mean,
final Color minColor,
final Color maxColor,
final Color meanColor ) {
if ( value < min ) {
value = min;
}
if ( value > max ) {
value = max;
}
if ( value < mean ) {
final double x = ForesterUtil.calculateColorFactor( value, mean, min );
final int red = ForesterUtil.calculateColorComponent( minColor.getRed(), meanColor.getRed(), x );
final int green = ForesterUtil.calculateColorComponent( minColor.getGreen(), meanColor.getGreen(), x );
final int blue = ForesterUtil.calculateColorComponent( minColor.getBlue(), meanColor.getBlue(), x );
return new Color( red, green, blue );
}
else if ( value > mean ) {
final double x = ForesterUtil.calculateColorFactor( value, max, mean );
final int red = ForesterUtil.calculateColorComponent( meanColor.getRed(), maxColor.getRed(), x );
final int green = ForesterUtil.calculateColorComponent( meanColor.getGreen(), maxColor.getGreen(), x );
final int blue = ForesterUtil.calculateColorComponent( meanColor.getBlue(), maxColor.getBlue(), x );
return new Color( red, green, blue );
}
else {
return meanColor;
}
}
/**
* Helper method for calcColor methods.
*
* @param smallercolor_component_x
* color component the smaller color
* @param largercolor_component_x
* color component the larger color
* @param x
* factor
* @return an int representing a color component
*/
final private static int calculateColorComponent( final double smallercolor_component_x,
final double largercolor_component_x,
final double x ) {
return ( int ) ( smallercolor_component_x + ( ( x * ( largercolor_component_x - smallercolor_component_x ) ) / 255.0 ) );
}
/**
* Helper method for calcColor methods.
*
*
* @param value
* the value
* @param larger
* the largest value
* @param smaller
* the smallest value
* @return a normalized value between larger and smaller
*/
final private static double calculateColorFactor( final double value, final double larger, final double smaller ) {
return ( 255.0 * ( value - smaller ) ) / ( larger - smaller );
}
public static int calculateOverlap( final Domain domain, final List covered_positions ) {
int overlap_count = 0;
for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
if ( ( i < covered_positions.size() ) && ( covered_positions.get( i ) == true ) ) {
++overlap_count;
}
}
return overlap_count;
}
final public static String collapseWhiteSpace( final String s ) {
return s.replaceAll( "[\\s]+", " " );
}
final public static void collection2file( final File file, final Collection> data, final String separator )
throws IOException {
final Writer writer = new BufferedWriter( new FileWriter( file ) );
collection2writer( writer, data, separator );
writer.close();
}
final public static void collection2writer( final Writer writer, final Collection> data, final String separator )
throws IOException {
boolean first = true;
for( final Object object : data ) {
if ( !first ) {
writer.write( separator );
}
else {
first = false;
}
writer.write( object.toString() );
}
}
final public static String colorToHex( final Color color ) {
final String rgb = Integer.toHexString( color.getRGB() );
return rgb.substring( 2, rgb.length() );
}
synchronized public static void copyFile( final File in, final File out ) throws IOException {
final FileInputStream in_s = new FileInputStream( in );
final FileOutputStream out_s = new FileOutputStream( out );
try {
final byte[] buf = new byte[ 1024 ];
int i = 0;
while ( ( i = in_s.read( buf ) ) != -1 ) {
out_s.write( buf, 0, i );
}
}
catch ( final IOException e ) {
throw e;
}
finally {
if ( in_s != null ) {
in_s.close();
}
if ( out_s != null ) {
out_s.close();
}
}
}
final public static int countChars( final String str, final char c ) {
int count = 0;
for( int i = 0; i < str.length(); ++i ) {
if ( str.charAt( i ) == c ) {
++count;
}
}
return count;
}
final public static BufferedWriter createBufferedWriter( final File file ) throws IOException {
if ( file.exists() ) {
throw new IOException( "[" + file + "] already exists" );
}
return new BufferedWriter( new FileWriter( file ) );
}
final public static BufferedWriter createBufferedWriter( final String name ) throws IOException {
return new BufferedWriter( new FileWriter( createFileForWriting( name ) ) );
}
final public static EasyWriter createEasyWriter( final File file ) throws IOException {
return new EasyWriter( createBufferedWriter( file ) );
}
final public static BufferedWriter createEasyWriter( final String name ) throws IOException {
return createEasyWriter( createFileForWriting( name ) );
}
final public static File createFileForWriting( final String name ) throws IOException {
final File file = new File( name );
if ( file.exists() ) {
throw new IOException( "[" + name + "] already exists" );
}
return file;
}
final public static void ensurePresenceOfDate( final PhylogenyNode node ) {
if ( !node.getNodeData().isHasDate() ) {
node.getNodeData().setDate( new org.forester.phylogeny.data.Date() );
}
}
final public static void ensurePresenceOfDistribution( final PhylogenyNode node ) {
if ( !node.getNodeData().isHasDistribution() ) {
node.getNodeData().setDistribution( new Distribution( "" ) );
}
}
public static void ensurePresenceOfSequence( final PhylogenyNode node ) {
if ( !node.getNodeData().isHasSequence() ) {
node.getNodeData().setSequence( new Sequence() );
}
}
public static void ensurePresenceOfTaxonomy( final PhylogenyNode node ) {
if ( !node.getNodeData().isHasTaxonomy() ) {
node.getNodeData().setTaxonomy( new Taxonomy() );
}
}
public static void fatalError( final String message ) {
System.err.println();
System.err.println( "error: " + message );
System.err.println();
System.exit( -1 );
}
public static void fatalError( final String prg_name, final String message ) {
System.err.println();
System.err.println( "[" + prg_name + "] > " + message );
System.err.println();
System.exit( -1 );
}
public static void fatalErrorIfFileNotReadable( final File file ) {
final String error = isReadableFile( file );
if ( !isEmpty( error ) ) {
System.err.println();
System.err.println( "error: " + error );
System.err.println();
System.exit( -1 );
}
}
public static void fatalErrorIfFileNotReadable( final String prg_name, final File file ) {
final String error = isReadableFile( file );
if ( !isEmpty( error ) ) {
System.err.println();
System.err.println( "[" + prg_name + "] > " + error );
System.err.println();
System.exit( -1 );
}
}
public static String[][] file22dArray( final File file ) throws IOException {
final List list = new ArrayList();
final BufferedReader in = new BufferedReader( new FileReader( file ) );
String str;
while ( ( str = in.readLine() ) != null ) {
str = str.trim();
if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
list.add( str );
}
}
in.close();
final String[][] ary = new String[ list.size() ][ 2 ];
final Pattern pa = Pattern.compile( "(\\S+)\\s+(\\S+)" );
int i = 0;
for( final String s : list ) {
final Matcher m = pa.matcher( s );
if ( m.matches() ) {
ary[ i ][ 0 ] = m.group( 1 );
ary[ i ][ 1 ] = m.group( 2 );
++i;
}
else {
throw new IOException( "unexpcted format: " + s );
}
}
return ary;
}
public static String[] file2array( final File file ) throws IOException {
final List list = file2list( file );
final String[] ary = new String[ list.size() ];
int i = 0;
for( final String s : list ) {
ary[ i++ ] = s;
}
return ary;
}
final public static List file2list( final File file ) throws IOException {
final List list = new ArrayList();
final BufferedReader in = new BufferedReader( new FileReader( file ) );
String str;
while ( ( str = in.readLine() ) != null ) {
str = str.trim();
if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
for( final String s : splitString( str ) ) {
list.add( s );
}
}
}
in.close();
return list;
}
final public static SortedSet file2set( final File file ) throws IOException {
final SortedSet set = new TreeSet();
final BufferedReader in = new BufferedReader( new FileReader( file ) );
String str;
while ( ( str = in.readLine() ) != null ) {
str = str.trim();
if ( ( str.length() > 0 ) && !str.startsWith( "#" ) ) {
for( final String s : splitString( str ) ) {
set.add( s );
}
}
}
in.close();
return set;
}
final public static String getCurrentDateTime() {
final DateFormat format = new SimpleDateFormat( "yyyy/MM/dd HH:mm:ss" );
return format.format( new Date() );
}
final public static String getFileSeparator() {
return ForesterUtil.FILE_SEPARATOR;
}
final public static String getFirstLine( final Object source ) throws FileNotFoundException, IOException {
BufferedReader reader = null;
if ( source instanceof File ) {
final File f = ( File ) source;
if ( !f.exists() ) {
throw new IOException( "[" + f.getAbsolutePath() + "] does not exist" );
}
else if ( !f.isFile() ) {
throw new IOException( "[" + f.getAbsolutePath() + "] is not a file" );
}
else if ( !f.canRead() ) {
throw new IOException( "[" + f.getAbsolutePath() + "] is not a readable" );
}
reader = new BufferedReader( new FileReader( f ) );
}
else if ( source instanceof InputStream ) {
reader = new BufferedReader( new InputStreamReader( ( InputStream ) source ) );
}
else if ( source instanceof String ) {
reader = new BufferedReader( new StringReader( ( String ) source ) );
}
else if ( source instanceof StringBuffer ) {
reader = new BufferedReader( new StringReader( source.toString() ) );
}
else if ( source instanceof URL ) {
final URLConnection url_connection = ( ( URL ) source ).openConnection();
url_connection.setDefaultUseCaches( false );
reader = new BufferedReader( new InputStreamReader( url_connection.getInputStream() ) );
}
else {
throw new IllegalArgumentException( "dont know how to read [" + source.getClass() + "]" );
}
String line;
while ( ( line = reader.readLine() ) != null ) {
line = line.trim();
if ( !ForesterUtil.isEmpty( line ) ) {
if ( reader != null ) {
reader.close();
}
return line;
}
}
if ( reader != null ) {
reader.close();
}
return line;
}
final public static String getForesterLibraryInformation() {
return "forester " + ForesterConstants.FORESTER_VERSION + " (" + ForesterConstants.FORESTER_DATE + ")";
}
final public static String getLineSeparator() {
return ForesterUtil.LINE_SEPARATOR;
}
final public static MolecularSequence.TYPE guessMolecularSequenceType( final String mol_seq ) {
if ( mol_seq.contains( "L" ) || mol_seq.contains( "I" ) || mol_seq.contains( "E" ) || mol_seq.contains( "H" )
|| mol_seq.contains( "D" ) || mol_seq.contains( "Q" ) ) {
return TYPE.AA;
}
else {
if ( mol_seq.contains( "T" ) ) {
return TYPE.DNA;
}
else if ( mol_seq.contains( "U" ) ) {
return TYPE.RNA;
}
}
return null;
}
final public static void increaseCountingMap( final Map counting_map, final String item_name ) {
if ( !counting_map.containsKey( item_name ) ) {
counting_map.put( item_name, 1 );
}
else {
counting_map.put( item_name, counting_map.get( item_name ) + 1 );
}
}
final public static boolean isEmpty( final List> l ) {
if ( ( l == null ) || l.isEmpty() ) {
return true;
}
for( final Object o : l ) {
if ( o != null ) {
return false;
}
}
return true;
}
final public static boolean isEmpty( final Set> s ) {
if ( ( s == null ) || s.isEmpty() ) {
return true;
}
for( final Object o : s ) {
if ( o != null ) {
return false;
}
}
return true;
}
final public static boolean isEmpty( final String s ) {
return ( ( s == null ) || ( s.length() < 1 ) );
}
/**
* Returns true is Domain domain falls in an uninterrupted stretch of
* covered positions.
*
* @param domain
* @param covered_positions
* @return
*/
public static boolean isEngulfed( final Domain domain, final List covered_positions ) {
for( int i = domain.getFrom(); i <= domain.getTo(); ++i ) {
if ( ( i >= covered_positions.size() ) || ( covered_positions.get( i ) != true ) ) {
return false;
}
}
return true;
}
final public static boolean isEqual( final double a, final double b ) {
return ( ( Math.abs( a - b ) ) < ZERO_DIFF );
}
final public static boolean isEven( final int n ) {
return ( n % 2 ) == 0;
}
/**
* This determines whether String[] a and String[] b have at least one
* String in common (intersect). Returns false if at least one String[] is
* null or empty.
*
* @param a
* a String[] b a String[]
* @return true if both a and b or not empty or null and contain at least
* one element in common false otherwise
*/
final public static boolean isIntersecting( final String[] a, final String[] b ) {
if ( ( a == null ) || ( b == null ) ) {
return false;
}
if ( ( a.length < 1 ) || ( b.length < 1 ) ) {
return false;
}
for( final String ai : a ) {
for( final String element : b ) {
if ( ( ai != null ) && ( element != null ) && ai.equals( element ) ) {
return true;
}
}
}
return false;
}
final public static double isLargerOrEqualToZero( final double d ) {
if ( d > 0.0 ) {
return d;
}
else {
return 0.0;
}
}
public final static boolean isMac() {
try {
return OS_NAME.toLowerCase().startsWith( "mac" );
}
catch ( final Exception e ) {
ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
return false;
}
}
final public static boolean isNull( final BigDecimal s ) {
return ( ( s == null ) || ( s.compareTo( NULL_BD ) == 0 ) );
}
final public static String isReadableFile( final File f ) {
if ( !f.exists() ) {
return "file [" + f + "] does not exist";
}
if ( f.isDirectory() ) {
return "[" + f + "] is a directory";
}
if ( !f.isFile() ) {
return "[" + f + "] is not a file";
}
if ( !f.canRead() ) {
return "file [" + f + "] is not readable";
}
if ( f.length() < 1 ) {
return "file [" + f + "] is empty";
}
return null;
}
final public static String isReadableFile( final String s ) {
return isReadableFile( new File( s ) );
}
public final static boolean isWindows() {
try {
return OS_NAME.toLowerCase().indexOf( "win" ) > -1;
}
catch ( final Exception e ) {
ForesterUtil.printWarningMessage( Constants.PRG_NAME, "minor error: " + e );
return false;
}
}
final public static String isWritableFile( final File f ) {
if ( f.isDirectory() ) {
return "[" + f + "] is a directory";
}
if ( f.exists() ) {
return "[" + f + "] already exists";
}
return null;
}
/**
* Helper for method "stringToColor".
*
* (Last modified: 12/20/03)
*/
final public static int limitRangeForColor( int i ) {
if ( i > 255 ) {
i = 255;
}
else if ( i < 0 ) {
i = 0;
}
return i;
}
final public static SortedMap