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;
37 import javax.swing.JOptionPane;
39 import org.forester.archaeopteryx.MainFrameApplication;
40 import org.forester.archaeopteryx.TreePanel;
41 import org.forester.archaeopteryx.tools.AncestralTaxonomyInferrer;
42 import org.forester.archaeopteryx.tools.RunnableProcess;
43 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
44 import org.forester.phylogeny.Phylogeny;
45 import org.forester.phylogeny.PhylogenyNode;
46 import org.forester.phylogeny.data.Identifier;
47 import org.forester.phylogeny.data.Taxonomy;
48 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
49 import org.forester.util.ForesterUtil;
50 import org.forester.util.TaxonomyUtil;
51 import org.forester.ws.seqdb.SequenceDbWsTools;
52 import org.forester.ws.seqdb.UniProtTaxonomy;
53 import org.forester.archaeopteryx.*;
55 public final class TaxonomyDataManager extends RunnableProcess {
58 CODE, SN, CN, ID, LIN;
60 private static final int MAX_CACHE_SIZE = 100000;
61 private static final int MAX_TAXONOMIES_TO_RETURN = 10;
62 private static final HashMap<String, UniProtTaxonomy> _sn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
63 private static final HashMap<String, UniProtTaxonomy> _lineage_up_cache_map = new HashMap<String, UniProtTaxonomy>();
64 private static final HashMap<String, UniProtTaxonomy> _code_up_cache_map = new HashMap<String, UniProtTaxonomy>();
65 private static final HashMap<String, UniProtTaxonomy> _cn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
66 private static final HashMap<String, UniProtTaxonomy> _id_up_cache_map = new HashMap<String, UniProtTaxonomy>();
67 private final Phylogeny _phy;
68 private final MainFrameApplication _mf;
69 private final TreePanel _treepanel;
70 private final boolean _delete;
71 private final boolean _allow_simple_names;
73 public TaxonomyDataManager( final MainFrameApplication mf, final TreePanel treepanel, final Phylogeny phy ) {
76 _treepanel = treepanel;
78 _allow_simple_names = false;
81 public TaxonomyDataManager( final MainFrameApplication mf,
82 final TreePanel treepanel,
85 final boolean allow_simple_name ) {
88 _treepanel = treepanel;
90 _allow_simple_names = allow_simple_name;
93 synchronized static void clearCachesIfTooLarge() {
94 if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
95 getSnTaxCacheMap().clear();
97 if ( getLineageTaxCacheMap().size() > MAX_CACHE_SIZE ) {
98 getLineageTaxCacheMap().clear();
100 if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
101 getCnTaxCacheMap().clear();
103 if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
104 getCodeTaxCacheMap().clear();
106 if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
107 getIdTaxCacheMap().clear();
111 synchronized final static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
112 return _cn_up_cache_map;
115 synchronized final static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
116 return _code_up_cache_map;
119 synchronized final static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
120 return _id_up_cache_map;
123 synchronized final static HashMap<String, UniProtTaxonomy> getLineageTaxCacheMap() {
124 return _lineage_up_cache_map;
127 synchronized final static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
128 return _sn_up_cache_map;
131 private final static UniProtTaxonomy obtainTaxonomy( final HashMap<String, UniProtTaxonomy> cache,
133 final QUERY_TYPE qt ) throws IOException,
134 AncestralTaxonomyInferenceException {
135 if ( cache.containsKey( query ) ) {
136 return cache.get( query ).copy();
139 List<UniProtTaxonomy> up_taxonomies = null;
142 up_taxonomies = getTaxonomiesFromId( ( String ) query );
145 up_taxonomies = getTaxonomiesFromTaxonomyCode( ( String ) query );
148 up_taxonomies = getTaxonomiesFromScientificName( ( String ) query );
151 up_taxonomies = getTaxonomiesFromCommonName( ( String ) query );
154 return obtainUniProtTaxonomyFromLineage( ( List<String> ) query );
156 throw new RuntimeException();
158 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
159 final UniProtTaxonomy up_tax = up_taxonomies.get( 0 );
160 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
161 TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
163 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
164 TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
166 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
167 TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
169 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
170 TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
180 private final static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query ) throws IOException {
181 return SequenceDbWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
184 private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
185 return SequenceDbWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
188 private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
189 if ( query.equalsIgnoreCase( UniProtTaxonomy.BACTERIA ) || query.equalsIgnoreCase( UniProtTaxonomy.ARCHAEA )
190 || query.equalsIgnoreCase( UniProtTaxonomy.VIRUSES )
191 || query.equalsIgnoreCase( UniProtTaxonomy.EUKARYOTA ) || query.equalsIgnoreCase( UniProtTaxonomy.X ) ) {
192 final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
193 l.add( UniProtTaxonomy.createSpecialFromScientificName( query ) );
196 return SequenceDbWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
199 private final static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query ) throws IOException {
200 if ( query.indexOf( "XX" ) == 3 && TaxonomyUtil.isHasTaxIdFromFakeTaxCode( query ) ) {
201 final int id = TaxonomyUtil.getTaxIdFromFakeTaxCode( query );
202 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() ) ) ) {
252 uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
255 uniprot_tax = obtainUniProtTaxonomy( node.getName(), qt );
257 if ( uniprot_tax != null ) {
259 tax = new Taxonomy();
260 node.getNodeData().addTaxonomy( tax );
263 updateTaxonomy( qt, node, tax, uniprot_tax );
267 not_found.add( tax.toString() );
270 not_found.add( node.getName() );
272 if ( delete && node.isExternal() ) {
273 not_found_external_nodes.add( node );
279 for( final PhylogenyNode node : not_found_external_nodes ) {
280 phy.deleteSubtree( node, true );
282 phy.externalNodesHaveChanged();
283 phy.clearHashIdToNodeMap();
284 phy.recalculateNumberOfExternalDescendants( true );
289 public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
290 throws IOException, AncestralTaxonomyInferenceException {
292 throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
294 if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
295 query = tax.getIdentifier().getValue();
297 return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
299 else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
300 if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
301 query = tax.getLineage();
303 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
306 query = tax.getScientificName();
308 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
311 else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
312 query = tax.getTaxonomyCode();
313 qt = QUERY_TYPE.CODE;
314 return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
317 query = tax.getCommonName();
319 return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
323 public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
324 throws IOException, AncestralTaxonomyInferenceException {
325 if ( ForesterUtil.isEmpty( simple_name ) ) {
326 throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
329 UniProtTaxonomy ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), simple_name, qt );
331 qt = QUERY_TYPE.CODE;
332 ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), simple_name, qt );
336 ut = obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), simple_name, qt );
341 static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
342 throws AncestralTaxonomyInferenceException, IOException {
343 final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
344 if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
345 return TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
348 final List<UniProtTaxonomy> matching_taxonomies = new ArrayList<UniProtTaxonomy>();
349 final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
350 .get( lineage.size() - 1 ) );
351 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
352 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
353 boolean match = true;
354 I: for( int i = 0; i < lineage.size(); ++i ) {
355 if ( ( i == up_taxonomy.getLineage().size() )
356 || !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
362 matching_taxonomies.add( up_taxonomy );
365 if ( matching_taxonomies.isEmpty() ) {
366 throw new AncestralTaxonomyInferenceException( "lineage \""
367 + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
369 //in case of more than one (e.g. "Xenopus" Genus and Subgenus), keep shorter, less specific one:
370 int shortest = Integer.MAX_VALUE;
371 UniProtTaxonomy least_specific_up_tax = null;
372 for( final UniProtTaxonomy m : matching_taxonomies ) {
373 final int s = m.getLineage().size();
374 if ( s < shortest ) {
376 least_specific_up_tax = m;
379 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, least_specific_up_tax );
380 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getScientificName() ) ) {
381 TaxonomyDataManager.getSnTaxCacheMap().put( least_specific_up_tax.getScientificName(),
382 least_specific_up_tax );
384 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCode() ) ) {
385 TaxonomyDataManager.getCodeTaxCacheMap().put( least_specific_up_tax.getCode(),
386 least_specific_up_tax );
388 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCommonName() ) ) {
389 TaxonomyDataManager.getCnTaxCacheMap().put( least_specific_up_tax.getCommonName(),
390 least_specific_up_tax );
392 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getId() ) ) {
393 TaxonomyDataManager.getIdTaxCacheMap().put( least_specific_up_tax.getId(), least_specific_up_tax );
395 return least_specific_up_tax;
398 throw new AncestralTaxonomyInferenceException( "taxonomy \"" + ( lineage.get( lineage.size() - 1 ) )
404 synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
405 final PhylogenyNode node,
407 final UniProtTaxonomy up_tax )
408 throws PhyloXmlDataFormatException {
409 if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
410 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
411 tax.setScientificName( up_tax.getScientificName() );
413 if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
414 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
415 tax.setTaxonomyCode( up_tax.getCode() );
417 if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
418 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
419 tax.setCommonName( up_tax.getCommonName() );
421 if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
422 tax.getSynonyms().add( up_tax.getSynonym() );
424 if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
426 tax.setRank( up_tax.getRank().toLowerCase() );
428 catch ( final PhyloXmlDataFormatException ex ) {
432 if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
433 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
434 tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
436 if ( up_tax.getLineage() != null ) {
437 tax.setLineage( new ArrayList<String>() );
438 for( final String lin : up_tax.getLineage() ) {
439 if ( !ForesterUtil.isEmpty( lin ) ) {
440 tax.getLineage().add( lin );
446 private final void execute() {
447 start( _mf, "taxonomy data" );
448 SortedSet<String> not_found = null;
450 not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
452 catch ( final UnknownHostException e ) {
453 JOptionPane.showMessageDialog( _mf,
454 "Could not connect to \"" + getBaseUrl() + "\"",
455 "Network error during taxonomic information gathering",
456 JOptionPane.ERROR_MESSAGE );
459 catch ( final IOException e ) {
461 JOptionPane.showMessageDialog( _mf,
463 "Failed to obtain taxonomic information",
464 JOptionPane.ERROR_MESSAGE );
467 catch ( final AncestralTaxonomyInferenceException e ) {
469 JOptionPane.showMessageDialog( _mf,
471 "Failed to obtain taxonomic information",
472 JOptionPane.ERROR_MESSAGE );
478 if ( ( _phy == null ) || _phy.isEmpty() ) {
480 JOptionPane.showMessageDialog( _mf,
481 "None of the external node taxonomies could be resolved",
482 "Taxonomy Tool Failed",
483 JOptionPane.WARNING_MESSAGE );
485 catch ( final Exception e ) {
486 // Not important if this fails, do nothing.
490 _treepanel.setTree( _phy );
492 _treepanel.setEdited( true );
493 if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
494 int max = not_found.size();
495 boolean more = false;
500 final StringBuffer sb = new StringBuffer();
501 sb.append( "Not all taxonomies could be resolved.\n" );
502 if ( not_found.size() == 1 ) {
504 sb.append( "The following taxonomy was not found and deleted (if external):\n" );
507 sb.append( "The following taxonomy was not found:\n" );
512 sb.append( "The following taxonomies were not found and deleted (if external) (total: "
513 + not_found.size() + "):\n" );
516 sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
520 for( final String string : not_found ) {
532 JOptionPane.showMessageDialog( _mf,
534 "Taxonomy Tool Completed",
535 JOptionPane.WARNING_MESSAGE );
537 catch ( final Exception e ) {
538 // Not important if this fails, do nothing.
543 JOptionPane.showMessageDialog( _mf,
544 "Taxonomy tool successfully completed",
545 "Taxonomy Tool Completed",
546 JOptionPane.INFORMATION_MESSAGE );
548 catch ( final Exception e ) {
549 // Not important if this fails, do nothing.
554 private final String getBaseUrl() {
555 return AncestralTaxonomyInferrer.getBaseUrl();