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;
54 public final class TaxonomyDataManager extends RunnableProcess {
57 CODE, SN, CN, ID, LIN;
59 private static final int MAX_CACHE_SIZE = 100000;
60 private static final int MAX_TAXONOMIES_TO_RETURN = 2000;
61 private static final HashMap<String, UniProtTaxonomy> _sn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
62 private static final HashMap<String, UniProtTaxonomy> _lineage_up_cache_map = new HashMap<String, UniProtTaxonomy>();
63 private static final HashMap<String, UniProtTaxonomy> _code_up_cache_map = new HashMap<String, UniProtTaxonomy>();
64 private static final HashMap<String, UniProtTaxonomy> _cn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
65 private static final HashMap<String, UniProtTaxonomy> _id_up_cache_map = new HashMap<String, UniProtTaxonomy>();
66 private final Phylogeny _phy;
67 private final MainFrameApplication _mf;
68 private final TreePanel _treepanel;
69 private final boolean _delete;
70 private final boolean _allow_simple_names;
72 public TaxonomyDataManager( final MainFrameApplication mf, final TreePanel treepanel, final Phylogeny phy ) {
75 _treepanel = treepanel;
77 _allow_simple_names = false;
80 public TaxonomyDataManager( final MainFrameApplication mf,
81 final TreePanel treepanel,
84 final boolean allow_simple_name ) {
87 _treepanel = treepanel;
89 _allow_simple_names = allow_simple_name;
92 synchronized static void clearCachesIfTooLarge() {
93 if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
94 getSnTaxCacheMap().clear();
96 if ( getLineageTaxCacheMap().size() > MAX_CACHE_SIZE ) {
97 getLineageTaxCacheMap().clear();
99 if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
100 getCnTaxCacheMap().clear();
102 if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
103 getCodeTaxCacheMap().clear();
105 if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
106 getIdTaxCacheMap().clear();
110 synchronized final static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
111 return _cn_up_cache_map;
114 synchronized final static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
115 return _code_up_cache_map;
118 synchronized final static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
119 return _id_up_cache_map;
122 synchronized final static HashMap<String, UniProtTaxonomy> getLineageTaxCacheMap() {
123 return _lineage_up_cache_map;
126 synchronized final static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
127 return _sn_up_cache_map;
130 private final static UniProtTaxonomy obtainTaxonomy( final HashMap<String, UniProtTaxonomy> cache,
132 final QUERY_TYPE qt ) throws IOException,
133 AncestralTaxonomyInferenceException {
134 if ( cache.containsKey( query ) ) {
135 return cache.get( query ).copy();
138 List<UniProtTaxonomy> up_taxonomies = null;
141 up_taxonomies = getTaxonomiesFromId( ( String ) query );
144 up_taxonomies = getTaxonomiesFromTaxonomyCode( ( String ) query );
147 up_taxonomies = getTaxonomiesFromScientificName( ( String ) query );
150 up_taxonomies = getTaxonomiesFromCommonName( ( String ) query );
153 return obtainUniProtTaxonomyFromLineage( ( List<String> ) query );
155 throw new RuntimeException();
157 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
158 final UniProtTaxonomy up_tax = up_taxonomies.get( 0 );
159 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
160 TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
162 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
163 TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
165 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
166 TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
168 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
169 TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
179 private final static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query ) throws IOException {
180 return SequenceDbWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
183 private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
184 return SequenceDbWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
187 private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
188 if ( query.equalsIgnoreCase( UniProtTaxonomy.BACTERIA ) || query.equalsIgnoreCase( UniProtTaxonomy.ARCHAEA )
189 || query.equalsIgnoreCase( UniProtTaxonomy.VIRUSES )
190 || query.equalsIgnoreCase( UniProtTaxonomy.EUKARYOTA ) || query.equalsIgnoreCase( UniProtTaxonomy.X ) ) {
191 final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
192 l.add( UniProtTaxonomy.createSpecialFromScientificName( query ) );
195 return SequenceDbWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
198 private final static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query ) throws IOException {
199 if ( ( query.indexOf( "XX" ) == 3 ) && TaxonomyUtil.isHasTaxIdFromFakeTaxCode( query ) ) {
200 final int id = TaxonomyUtil.getTaxIdFromFakeTaxCode( query );
201 return SequenceDbWsTools.getTaxonomiesFromId( String.valueOf( id ), MAX_TAXONOMIES_TO_RETURN );
203 return SequenceDbWsTools.getTaxonomiesFromTaxonomyCode( query, MAX_TAXONOMIES_TO_RETURN );
206 static final boolean isHasAppropriateId( final Taxonomy tax ) {
207 return ( ( tax.getIdentifier() != null ) && ( !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) && ( tax
208 .getIdentifier().getProvider().equalsIgnoreCase( "ncbi" )
209 || tax.getIdentifier().getProvider().equalsIgnoreCase( "uniprot" ) || tax.getIdentifier().getProvider()
210 .equalsIgnoreCase( "uniprotkb" ) ) ) );
213 synchronized final private static SortedSet<String> obtainDetailedTaxonomicInformation( final Phylogeny phy,
214 final boolean delete,
215 final boolean allow_to_use_basic_node_names )
216 throws IOException, AncestralTaxonomyInferenceException {
217 clearCachesIfTooLarge();
218 final SortedSet<String> not_found = new TreeSet<String>();
219 List<PhylogenyNode> not_found_external_nodes = null;
221 not_found_external_nodes = new ArrayList<PhylogenyNode>();
223 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
224 final PhylogenyNode node = iter.next();
225 final QUERY_TYPE qt = null;
227 if ( node.getNodeData().isHasTaxonomy() ) {
228 tax = node.getNodeData().getTaxonomy();
230 else if ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) {
231 // Nothing to be done.
233 else if ( node.isExternal() ) {
234 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
235 not_found.add( node.getName() );
238 not_found.add( node.toString() );
241 not_found_external_nodes.add( node );
244 UniProtTaxonomy uniprot_tax = null;
245 if ( ( ( tax != null ) && ( isHasAppropriateId( tax ) || !ForesterUtil.isEmpty( tax.getScientificName() )
246 || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil.isEmpty( tax.getCommonName() ) ) )
247 || ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) ) {
249 uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
252 uniprot_tax = obtainUniProtTaxonomy( node.getName(), qt );
254 if ( uniprot_tax != null ) {
256 tax = new Taxonomy();
257 node.getNodeData().addTaxonomy( tax );
260 updateTaxonomy( qt, node, tax, uniprot_tax );
264 not_found.add( tax.toString() );
267 not_found.add( node.getName() );
269 if ( delete && node.isExternal() ) {
270 not_found_external_nodes.add( node );
276 for( final PhylogenyNode node : not_found_external_nodes ) {
277 phy.deleteSubtree( node, true );
279 phy.externalNodesHaveChanged();
280 phy.clearHashIdToNodeMap();
281 phy.recalculateNumberOfExternalDescendants( true );
286 public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
287 throws IOException, AncestralTaxonomyInferenceException {
289 throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
291 if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
292 query = tax.getIdentifier().getValue();
294 return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
296 else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
297 if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
298 query = tax.getLineage();
300 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
303 query = tax.getScientificName();
305 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
308 else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
309 query = tax.getTaxonomyCode();
310 qt = QUERY_TYPE.CODE;
311 return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
314 query = tax.getCommonName();
316 return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
320 public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
321 throws IOException, AncestralTaxonomyInferenceException {
322 if ( ForesterUtil.isEmpty( simple_name ) ) {
323 throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
326 UniProtTaxonomy ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), simple_name, qt );
328 qt = QUERY_TYPE.CODE;
329 ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), simple_name, qt );
333 ut = obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), simple_name, qt );
338 static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
339 throws AncestralTaxonomyInferenceException, IOException {
340 final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
341 if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
342 return TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
345 final List<UniProtTaxonomy> matching_taxonomies = new ArrayList<UniProtTaxonomy>();
346 final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
347 .get( lineage.size() - 1 ) );
348 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
349 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
350 boolean match = true;
351 I: for( int i = 0; i < lineage.size(); ++i ) {
352 if ( ( i == up_taxonomy.getLineage().size() )
353 || !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
359 matching_taxonomies.add( up_taxonomy );
362 if ( matching_taxonomies.isEmpty() ) {
363 throw new AncestralTaxonomyInferenceException( "lineage \""
364 + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
366 //in case of more than one (e.g. "Xenopus" Genus and Subgenus), keep shorter, less specific one:
367 int shortest = Integer.MAX_VALUE;
368 UniProtTaxonomy least_specific_up_tax = null;
369 for( final UniProtTaxonomy m : matching_taxonomies ) {
370 final int s = m.getLineage().size();
371 if ( s < shortest ) {
373 least_specific_up_tax = m;
376 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, least_specific_up_tax );
377 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getScientificName() ) ) {
378 TaxonomyDataManager.getSnTaxCacheMap().put( least_specific_up_tax.getScientificName(),
379 least_specific_up_tax );
381 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCode() ) ) {
382 TaxonomyDataManager.getCodeTaxCacheMap().put( least_specific_up_tax.getCode(),
383 least_specific_up_tax );
385 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCommonName() ) ) {
386 TaxonomyDataManager.getCnTaxCacheMap().put( least_specific_up_tax.getCommonName(),
387 least_specific_up_tax );
389 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getId() ) ) {
390 TaxonomyDataManager.getIdTaxCacheMap().put( least_specific_up_tax.getId(), least_specific_up_tax );
392 return least_specific_up_tax;
395 throw new AncestralTaxonomyInferenceException( "taxonomy \"" + ( lineage.get( lineage.size() - 1 ) )
401 synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
402 final PhylogenyNode node,
404 final UniProtTaxonomy up_tax )
405 throws PhyloXmlDataFormatException {
406 if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
407 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
408 tax.setScientificName( up_tax.getScientificName() );
410 if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
411 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
412 tax.setTaxonomyCode( up_tax.getCode() );
414 if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
415 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
416 tax.setCommonName( up_tax.getCommonName() );
418 if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
419 tax.getSynonyms().add( up_tax.getSynonym() );
421 if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
423 tax.setRank( up_tax.getRank().toLowerCase() );
425 catch ( final PhyloXmlDataFormatException ex ) {
429 if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
430 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
431 tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
433 if ( up_tax.getLineage() != null ) {
434 tax.setLineage( new ArrayList<String>() );
435 for( final String lin : up_tax.getLineage() ) {
436 if ( !ForesterUtil.isEmpty( lin ) ) {
437 tax.getLineage().add( lin );
443 private final void execute() {
444 start( _mf, "taxonomy data" );
445 SortedSet<String> not_found = null;
447 not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
449 catch ( final UnknownHostException e ) {
450 JOptionPane.showMessageDialog( _mf,
451 "Could not connect to \"" + getBaseUrl() + "\"",
452 "Network error during taxonomic information gathering",
453 JOptionPane.ERROR_MESSAGE );
456 catch ( final IOException e ) {
458 JOptionPane.showMessageDialog( _mf,
460 "Failed to obtain taxonomic information",
461 JOptionPane.ERROR_MESSAGE );
464 catch ( final AncestralTaxonomyInferenceException e ) {
466 JOptionPane.showMessageDialog( _mf,
468 "Failed to obtain taxonomic information",
469 JOptionPane.ERROR_MESSAGE );
475 if ( ( _phy == null ) || _phy.isEmpty() ) {
477 JOptionPane.showMessageDialog( _mf,
478 "None of the external node taxonomies could be resolved",
479 "Taxonomy Tool Failed",
480 JOptionPane.WARNING_MESSAGE );
482 catch ( final Exception e ) {
483 // Not important if this fails, do nothing.
487 _treepanel.setTree( _phy );
489 _treepanel.setEdited( true );
490 if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
491 int max = not_found.size();
492 boolean more = false;
497 final StringBuffer sb = new StringBuffer();
498 sb.append( "Not all taxonomies could be resolved.\n" );
499 if ( not_found.size() == 1 ) {
501 sb.append( "The following taxonomy was not found and deleted (if external):\n" );
504 sb.append( "The following taxonomy was not found:\n" );
509 sb.append( "The following taxonomies were not found and deleted (if external) (total: "
510 + not_found.size() + "):\n" );
513 sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
517 for( final String string : not_found ) {
529 JOptionPane.showMessageDialog( _mf,
531 "Taxonomy Tool Completed",
532 JOptionPane.WARNING_MESSAGE );
534 catch ( final Exception e ) {
535 // Not important if this fails, do nothing.
540 JOptionPane.showMessageDialog( _mf,
541 "Taxonomy tool successfully completed",
542 "Taxonomy Tool Completed",
543 JOptionPane.INFORMATION_MESSAGE );
545 catch ( final Exception e ) {
546 // Not important if this fails, do nothing.
551 private final String getBaseUrl() {
552 return AncestralTaxonomyInferrer.getBaseUrl();