3 // forester -- software libraries and applications
4 // for genomics and evolutionary biology research.
6 // Copyright (C) 2010 Christian M Zmasek
7 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
10 // This library is free software; you can redistribute it and/or
11 // modify it under the terms of the GNU Lesser General Public
12 // License as published by the Free Software Foundation; either
13 // version 2.1 of the License, or (at your option) any later version.
15 // This library is distributed in the hope that it will be useful,
16 // but WITHOUT ANY WARRANTY; without even the implied warranty of
17 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
18 // Lesser General Public License for more details.
20 // You should have received a copy of the GNU Lesser General Public
21 // License along with this library; if not, write to the Free Software
22 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
24 // Contact: phylosoft @ gmail . com
25 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
27 package org.forester.analysis;
29 import java.io.IOException;
30 import java.net.UnknownHostException;
31 import java.util.ArrayList;
32 import java.util.HashMap;
33 import java.util.List;
34 import java.util.SortedSet;
35 import java.util.TreeSet;
36 import java.util.regex.Matcher;
38 import javax.swing.JOptionPane;
40 import org.forester.archaeopteryx.MainFrameApplication;
41 import org.forester.archaeopteryx.TreePanel;
42 import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer;
43 import org.forester.archaeopteryx.tools.RunnableProcess;
44 import org.forester.io.parsers.nhx.NHXParser;
45 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
46 import org.forester.io.parsers.util.ParserUtils;
47 import org.forester.phylogeny.Phylogeny;
48 import org.forester.phylogeny.PhylogenyNode;
49 import org.forester.phylogeny.data.Identifier;
50 import org.forester.phylogeny.data.Taxonomy;
51 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
52 import org.forester.util.ForesterUtil;
53 import org.forester.util.TaxonomyUtil;
54 import org.forester.ws.seqdb.SequenceDbWsTools;
55 import org.forester.ws.seqdb.UniProtTaxonomy;
57 public final class TaxonomyDataManager extends RunnableProcess {
60 CODE, SN, CN, ID, LIN;
62 private static final int MAX_CACHE_SIZE = 100000;
63 private static final int MAX_TAXONOMIES_TO_RETURN = 2000;
64 private static final HashMap<String, UniProtTaxonomy> _sn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
65 private static final HashMap<String, UniProtTaxonomy> _lineage_up_cache_map = new HashMap<String, UniProtTaxonomy>();
66 private static final HashMap<String, UniProtTaxonomy> _code_up_cache_map = new HashMap<String, UniProtTaxonomy>();
67 private static final HashMap<String, UniProtTaxonomy> _cn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
68 private static final HashMap<String, UniProtTaxonomy> _id_up_cache_map = new HashMap<String, UniProtTaxonomy>();
69 private final Phylogeny _phy;
70 private final MainFrameApplication _mf;
71 private final TreePanel _treepanel;
72 private final boolean _delete;
73 private final boolean _allow_simple_names;
75 public TaxonomyDataManager( final MainFrameApplication mf, final TreePanel treepanel, final Phylogeny phy ) {
78 _treepanel = treepanel;
80 _allow_simple_names = false;
83 public TaxonomyDataManager( final MainFrameApplication mf,
84 final TreePanel treepanel,
87 final boolean allow_simple_name ) {
90 _treepanel = treepanel;
92 _allow_simple_names = allow_simple_name;
95 synchronized static void clearCachesIfTooLarge() {
96 if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
97 getSnTaxCacheMap().clear();
99 if ( getLineageTaxCacheMap().size() > MAX_CACHE_SIZE ) {
100 getLineageTaxCacheMap().clear();
102 if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
103 getCnTaxCacheMap().clear();
105 if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
106 getCodeTaxCacheMap().clear();
108 if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
109 getIdTaxCacheMap().clear();
113 synchronized final static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
114 return _cn_up_cache_map;
117 synchronized final static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
118 return _code_up_cache_map;
121 synchronized final static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
122 return _id_up_cache_map;
125 synchronized final static HashMap<String, UniProtTaxonomy> getLineageTaxCacheMap() {
126 return _lineage_up_cache_map;
129 synchronized final static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
130 return _sn_up_cache_map;
133 private final static UniProtTaxonomy obtainTaxonomy( final HashMap<String, UniProtTaxonomy> cache,
135 final QUERY_TYPE qt ) throws IOException,
136 AncestralTaxonomyInferenceException {
137 if ( cache.containsKey( query ) ) {
138 return cache.get( query ).copy();
141 List<UniProtTaxonomy> up_taxonomies = null;
144 up_taxonomies = getTaxonomiesFromId( ( String ) query );
147 up_taxonomies = getTaxonomiesFromTaxonomyCode( ( String ) query );
150 up_taxonomies = getTaxonomiesFromScientificName( ( String ) query );
153 up_taxonomies = getTaxonomiesFromCommonName( ( String ) query );
156 return obtainUniProtTaxonomyFromLineage( ( List<String> ) query );
158 throw new RuntimeException();
160 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
161 final UniProtTaxonomy up_tax = up_taxonomies.get( 0 );
162 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
163 TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
165 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
166 TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
168 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
169 TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
171 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
172 TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
182 private final static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query ) throws IOException {
183 return SequenceDbWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
186 private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
187 return SequenceDbWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
190 private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
191 if ( query.equalsIgnoreCase( UniProtTaxonomy.BACTERIA ) || query.equalsIgnoreCase( UniProtTaxonomy.ARCHAEA )
192 || query.equalsIgnoreCase( UniProtTaxonomy.VIRUSES )
193 || query.equalsIgnoreCase( UniProtTaxonomy.EUKARYOTA ) || query.equalsIgnoreCase( UniProtTaxonomy.X ) ) {
194 final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
195 l.add( UniProtTaxonomy.createSpecialFromScientificName( query ) );
198 return SequenceDbWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
201 private final static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query ) throws IOException {
202 if ( ( query.indexOf( "XX" ) == 3 ) && TaxonomyUtil.isHasTaxIdFromFakeTaxCode( query ) ) {
203 final int id = TaxonomyUtil.getTaxIdFromFakeTaxCode( query );
204 return SequenceDbWsTools.getTaxonomiesFromId( String.valueOf( id ), MAX_TAXONOMIES_TO_RETURN );
206 return SequenceDbWsTools.getTaxonomiesFromTaxonomyCode( query, MAX_TAXONOMIES_TO_RETURN );
209 static final boolean isHasAppropriateId( final Taxonomy tax ) {
210 return ( ( tax.getIdentifier() != null ) && ( !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) && ( tax
211 .getIdentifier().getProvider().equalsIgnoreCase( "ncbi" )
212 || tax.getIdentifier().getProvider().equalsIgnoreCase( "uniprot" ) || tax.getIdentifier().getProvider()
213 .equalsIgnoreCase( "uniprotkb" ) ) ) );
216 synchronized final private static SortedSet<String> obtainDetailedTaxonomicInformation( final Phylogeny phy,
217 final boolean delete,
218 final boolean allow_to_use_basic_node_names )
219 throws IOException, AncestralTaxonomyInferenceException {
220 clearCachesIfTooLarge();
221 final SortedSet<String> not_found = new TreeSet<String>();
222 List<PhylogenyNode> not_found_external_nodes = null;
224 not_found_external_nodes = new ArrayList<PhylogenyNode>();
226 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
227 final PhylogenyNode node = iter.next();
228 final QUERY_TYPE qt = null;
230 if ( node.getNodeData().isHasTaxonomy() ) {
231 tax = node.getNodeData().getTaxonomy();
233 else if ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) {
234 // Nothing to be done.
236 else if ( node.isExternal() ) {
237 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
238 not_found.add( node.getName() );
241 not_found.add( node.toString() );
244 not_found_external_nodes.add( node );
247 UniProtTaxonomy uniprot_tax = null;
248 if ( ( ( tax != null ) && ( isHasAppropriateId( tax ) || !ForesterUtil.isEmpty( tax.getScientificName() )
249 || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil.isEmpty( tax.getCommonName() ) ) )
250 || ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) ) {
251 if ( ( ( tax != null ) && ( isHasAppropriateId( tax )
252 || !ForesterUtil.isEmpty( tax.getScientificName() )
253 || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil
254 .isEmpty( tax.getCommonName() ) ) ) ) {
255 uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
258 uniprot_tax = obtainUniProtTaxonomy( node.getName(), qt );
260 if ( uniprot_tax != null ) {
262 tax = new Taxonomy();
263 node.getNodeData().addTaxonomy( tax );
265 updateTaxonomy( qt, node, tax, uniprot_tax );
269 not_found.add( tax.toString() );
272 not_found.add( node.getName() );
274 if ( delete && node.isExternal() ) {
275 not_found_external_nodes.add( node );
281 for( final PhylogenyNode node : not_found_external_nodes ) {
282 phy.deleteSubtree( node, true );
284 phy.externalNodesHaveChanged();
285 phy.clearHashIdToNodeMap();
286 phy.recalculateNumberOfExternalDescendants( true );
291 public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
292 throws IOException, AncestralTaxonomyInferenceException {
294 throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
296 if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
297 query = tax.getIdentifier().getValue();
299 return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
301 else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
302 if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
303 query = tax.getLineage();
305 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
308 query = tax.getScientificName();
310 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
313 else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
314 query = tax.getTaxonomyCode();
315 qt = QUERY_TYPE.CODE;
316 return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
319 query = tax.getCommonName();
321 return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
325 public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
326 throws IOException, AncestralTaxonomyInferenceException {
327 if ( ForesterUtil.isEmpty( simple_name ) ) {
328 throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
330 UniProtTaxonomy ut = null;
331 final String code = ParserUtils.extractTaxonomyCodeFromNodeName( simple_name,
332 NHXParser.TAXONOMY_EXTRACTION.AGGRESSIVE );
333 if ( !ForesterUtil.isEmpty( code ) ) {
334 qt = QUERY_TYPE.CODE;
335 ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), code, qt );
338 final String sn = ParserUtils.extractScientificNameFromNodeName( simple_name );
339 if ( !ForesterUtil.isEmpty( sn ) ) {
341 ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), sn, qt );
345 final String id = ParserUtils
346 .extractUniprotTaxonomyIdFromNodeName( simple_name,
347 NHXParser.TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
348 if ( !ForesterUtil.isEmpty( id ) ) {
350 ut = obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), id, qt );
355 final Matcher m = ParserUtils.TAXOMONY_SN_PATTERN_GENUS.matcher( simple_name );
359 if ( !ForesterUtil.isEmpty( sn ) ) {
361 ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), sn, qt );
367 static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
368 throws AncestralTaxonomyInferenceException, IOException {
369 final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
370 if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
371 return TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
374 final List<UniProtTaxonomy> matching_taxonomies = new ArrayList<UniProtTaxonomy>();
375 final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
376 .get( lineage.size() - 1 ) );
377 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
378 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
379 boolean match = true;
380 I: for( int i = 0; i < lineage.size(); ++i ) {
381 if ( ( i == up_taxonomy.getLineage().size() )
382 || !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
388 matching_taxonomies.add( up_taxonomy );
391 if ( matching_taxonomies.isEmpty() ) {
392 throw new AncestralTaxonomyInferenceException( "lineage \""
393 + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
395 //in case of more than one (e.g. "Xenopus" Genus and Subgenus), keep shorter, less specific one:
396 int shortest = Integer.MAX_VALUE;
397 UniProtTaxonomy least_specific_up_tax = null;
398 for( final UniProtTaxonomy m : matching_taxonomies ) {
399 final int s = m.getLineage().size();
400 if ( s < shortest ) {
402 least_specific_up_tax = m;
405 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, least_specific_up_tax );
406 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getScientificName() ) ) {
407 TaxonomyDataManager.getSnTaxCacheMap().put( least_specific_up_tax.getScientificName(),
408 least_specific_up_tax );
410 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCode() ) ) {
411 TaxonomyDataManager.getCodeTaxCacheMap().put( least_specific_up_tax.getCode(),
412 least_specific_up_tax );
414 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCommonName() ) ) {
415 TaxonomyDataManager.getCnTaxCacheMap().put( least_specific_up_tax.getCommonName(),
416 least_specific_up_tax );
418 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getId() ) ) {
419 TaxonomyDataManager.getIdTaxCacheMap().put( least_specific_up_tax.getId(), least_specific_up_tax );
421 return least_specific_up_tax;
424 throw new AncestralTaxonomyInferenceException( "taxonomy \"" + ( lineage.get( lineage.size() - 1 ) )
430 synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
431 final PhylogenyNode node,
433 final UniProtTaxonomy up_tax )
434 throws PhyloXmlDataFormatException {
435 if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
436 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
437 tax.setScientificName( up_tax.getScientificName() );
439 if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
440 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
441 tax.setTaxonomyCode( up_tax.getCode() );
443 if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
444 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
445 tax.setCommonName( up_tax.getCommonName() );
447 if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
448 tax.getSynonyms().add( up_tax.getSynonym() );
450 if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
452 tax.setRank( up_tax.getRank().toLowerCase() );
454 catch ( final PhyloXmlDataFormatException ex ) {
458 if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
459 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
460 tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
462 if ( up_tax.getLineage() != null ) {
463 tax.setLineage( new ArrayList<String>() );
464 for( final String lin : up_tax.getLineage() ) {
465 if ( !ForesterUtil.isEmpty( lin ) ) {
466 tax.getLineage().add( lin );
472 private final void execute() {
473 start( _mf, "taxonomy data" );
474 SortedSet<String> not_found = null;
476 not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
478 catch ( final UnknownHostException e ) {
479 JOptionPane.showMessageDialog( _mf,
480 "Could not connect to \"" + getBaseUrl() + "\"",
481 "Network error during taxonomic information gathering",
482 JOptionPane.ERROR_MESSAGE );
485 catch ( final IOException e ) {
487 JOptionPane.showMessageDialog( _mf,
489 "Failed to obtain taxonomic information",
490 JOptionPane.ERROR_MESSAGE );
493 catch ( final AncestralTaxonomyInferenceException e ) {
495 JOptionPane.showMessageDialog( _mf,
497 "Failed to obtain taxonomic information",
498 JOptionPane.ERROR_MESSAGE );
504 if ( ( _phy == null ) || _phy.isEmpty() ) {
506 JOptionPane.showMessageDialog( _mf,
507 "None of the external node taxonomies could be resolved",
508 "Taxonomy Tool Failed",
509 JOptionPane.WARNING_MESSAGE );
511 catch ( final Exception e ) {
512 // Not important if this fails, do nothing.
516 _treepanel.setTree( _phy );
518 _treepanel.setEdited( true );
519 if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
520 int max = not_found.size();
521 boolean more = false;
526 final StringBuffer sb = new StringBuffer();
527 sb.append( "Not all taxonomies could be resolved.\n" );
528 if ( not_found.size() == 1 ) {
530 sb.append( "The following taxonomy was not found and deleted (if external):\n" );
533 sb.append( "The following taxonomy was not found:\n" );
538 sb.append( "The following taxonomies were not found and deleted (if external) (total: "
539 + not_found.size() + "):\n" );
542 sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
546 for( final String string : not_found ) {
558 JOptionPane.showMessageDialog( _mf,
560 "Taxonomy Tool Completed",
561 JOptionPane.WARNING_MESSAGE );
563 catch ( final Exception e ) {
564 // Not important if this fails, do nothing.
569 JOptionPane.showMessageDialog( _mf,
570 "Taxonomy tool successfully completed",
571 "Taxonomy Tool Completed",
572 JOptionPane.INFORMATION_MESSAGE );
574 catch ( final Exception e ) {
575 // Not important if this fails, do nothing.
580 private final String getBaseUrl() {
581 return AncestralTaxonomyInferrer.getBaseUrl();