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.ws.seqdb.SequenceDbWsTools;
51 import org.forester.ws.seqdb.UniProtTaxonomy;
53 public final class TaxonomyDataManager extends RunnableProcess {
56 CODE, SN, CN, ID, LIN;
58 private static final int MAX_CACHE_SIZE = 100000;
59 private static final int MAX_TAXONOMIES_TO_RETURN = 10;
60 private static final HashMap<String, UniProtTaxonomy> _sn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
61 private static final HashMap<String, UniProtTaxonomy> _lineage_up_cache_map = new HashMap<String, UniProtTaxonomy>();
62 private static final HashMap<String, UniProtTaxonomy> _code_up_cache_map = new HashMap<String, UniProtTaxonomy>();
63 private static final HashMap<String, UniProtTaxonomy> _cn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
64 private static final HashMap<String, UniProtTaxonomy> _id_up_cache_map = new HashMap<String, UniProtTaxonomy>();
65 private final Phylogeny _phy;
66 private final MainFrameApplication _mf;
67 private final TreePanel _treepanel;
68 private final boolean _delete;
69 private final boolean _allow_simple_names;
71 public TaxonomyDataManager( final MainFrameApplication mf, final TreePanel treepanel, final Phylogeny phy ) {
74 _treepanel = treepanel;
76 _allow_simple_names = false;
79 public TaxonomyDataManager( final MainFrameApplication mf,
80 final TreePanel treepanel,
83 final boolean allow_simple_name ) {
86 _treepanel = treepanel;
88 _allow_simple_names = allow_simple_name;
91 synchronized static void clearCachesIfTooLarge() {
92 if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
93 getSnTaxCacheMap().clear();
95 if ( getLineageTaxCacheMap().size() > MAX_CACHE_SIZE ) {
96 getLineageTaxCacheMap().clear();
98 if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
99 getCnTaxCacheMap().clear();
101 if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
102 getCodeTaxCacheMap().clear();
104 if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
105 getIdTaxCacheMap().clear();
109 synchronized final static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
110 return _cn_up_cache_map;
113 synchronized final static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
114 return _code_up_cache_map;
117 synchronized final static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
118 return _id_up_cache_map;
121 synchronized final static HashMap<String, UniProtTaxonomy> getLineageTaxCacheMap() {
122 return _lineage_up_cache_map;
125 synchronized final static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
126 return _sn_up_cache_map;
129 private final static UniProtTaxonomy obtainTaxonomy( final HashMap<String, UniProtTaxonomy> cache,
131 final QUERY_TYPE qt ) throws IOException,
132 AncestralTaxonomyInferenceException {
133 if ( cache.containsKey( query ) ) {
134 return cache.get( query ).copy();
137 List<UniProtTaxonomy> up_taxonomies = null;
140 up_taxonomies = getTaxonomiesFromId( ( String ) query );
143 up_taxonomies = getTaxonomiesFromTaxonomyCode( ( String ) query );
146 up_taxonomies = getTaxonomiesFromScientificName( ( String ) query );
149 up_taxonomies = getTaxonomiesFromCommonName( ( String ) query );
152 return obtainUniProtTaxonomyFromLineage( ( List<String> ) query );
154 throw new RuntimeException();
156 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
157 final UniProtTaxonomy up_tax = up_taxonomies.get( 0 );
158 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
159 TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
161 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
162 TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
164 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
165 TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
167 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
168 TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
178 private final static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query ) throws IOException {
179 return SequenceDbWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
182 private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
183 return SequenceDbWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
186 private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
187 if ( query.equalsIgnoreCase( UniProtTaxonomy.BACTERIA ) ||
188 query.equalsIgnoreCase( UniProtTaxonomy.ARCHAEA ) ||
189 query.equalsIgnoreCase( UniProtTaxonomy.VIRUSES ) ||
190 query.equalsIgnoreCase( UniProtTaxonomy.EUKARYOTA )
192 final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
193 l.add( UniProtTaxonomy.createSpecialFromScientificName( query ) );
197 return SequenceDbWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
200 private final static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query ) throws IOException {
201 return SequenceDbWsTools.getTaxonomiesFromTaxonomyCode( query, MAX_TAXONOMIES_TO_RETURN );
204 static final boolean isHasAppropriateId( final Taxonomy tax ) {
205 return ( ( tax.getIdentifier() != null ) && ( !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) && ( tax
206 .getIdentifier().getProvider().equalsIgnoreCase( "ncbi" )
207 || tax.getIdentifier().getProvider().equalsIgnoreCase( "uniprot" ) || tax.getIdentifier().getProvider()
208 .equalsIgnoreCase( "uniprotkb" ) ) ) );
211 synchronized final private static SortedSet<String> obtainDetailedTaxonomicInformation( final Phylogeny phy,
212 final boolean delete,
213 final boolean allow_to_use_basic_node_names )
214 throws IOException, AncestralTaxonomyInferenceException {
215 clearCachesIfTooLarge();
216 final SortedSet<String> not_found = new TreeSet<String>();
217 List<PhylogenyNode> not_found_external_nodes = null;
219 not_found_external_nodes = new ArrayList<PhylogenyNode>();
221 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
222 final PhylogenyNode node = iter.next();
223 final QUERY_TYPE qt = null;
225 if ( node.getNodeData().isHasTaxonomy() ) {
226 tax = node.getNodeData().getTaxonomy();
228 else if ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) {
229 // Nothing to be done.
231 else if ( node.isExternal() ) {
232 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
233 not_found.add( node.getName() );
236 not_found.add( node.toString() );
239 not_found_external_nodes.add( node );
242 UniProtTaxonomy uniprot_tax = null;
243 if ( ( ( tax != null ) && ( isHasAppropriateId( tax ) || !ForesterUtil.isEmpty( tax.getScientificName() )
244 || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil.isEmpty( tax.getCommonName() ) ) )
245 || ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) ) {
247 uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
250 uniprot_tax = obtainUniProtTaxonomy( node.getName(), qt );
252 if ( uniprot_tax != null ) {
254 tax = new Taxonomy();
255 node.getNodeData().addTaxonomy( tax );
258 updateTaxonomy( qt, node, tax, uniprot_tax );
262 not_found.add( tax.toString() );
265 not_found.add( node.getName() );
267 if ( delete && node.isExternal() ) {
268 not_found_external_nodes.add( node );
274 for( final PhylogenyNode node : not_found_external_nodes ) {
275 phy.deleteSubtree( node, true );
277 phy.externalNodesHaveChanged();
278 phy.clearHashIdToNodeMap();
279 phy.recalculateNumberOfExternalDescendants( true );
284 public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
285 throws IOException, AncestralTaxonomyInferenceException {
287 throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
289 if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
290 query = tax.getIdentifier().getValue();
292 return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
294 else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
295 if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
296 query = tax.getLineage();
298 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
301 query = tax.getScientificName();
303 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
306 else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
307 query = tax.getTaxonomyCode();
308 qt = QUERY_TYPE.CODE;
309 return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
312 query = tax.getCommonName();
314 return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
318 public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
319 throws IOException, AncestralTaxonomyInferenceException {
320 if ( ForesterUtil.isEmpty( simple_name ) ) {
321 throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
324 UniProtTaxonomy ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), simple_name, qt );
326 qt = QUERY_TYPE.CODE;
327 ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), simple_name, qt );
331 ut = obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), simple_name, qt );
336 static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
337 throws AncestralTaxonomyInferenceException, IOException {
338 final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
339 if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
340 return TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
343 final List<UniProtTaxonomy> matching_taxonomies = new ArrayList<UniProtTaxonomy>();
344 final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
345 .get( lineage.size() - 1 ) );
346 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
347 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
348 boolean match = true;
349 I: for( int i = 0; i < lineage.size(); ++i ) {
350 if ( ( i == up_taxonomy.getLineage().size() )
351 || !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
357 matching_taxonomies.add( up_taxonomy );
360 if ( matching_taxonomies.isEmpty() ) {
361 throw new AncestralTaxonomyInferenceException( "lineage \""
362 + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
364 //in case of more than one (e.g. "Xenopus" Genus and Subgenus), keep shorter, less specific one:
365 int shortest = Integer.MAX_VALUE;
366 UniProtTaxonomy least_specific_up_tax = null;
367 for( final UniProtTaxonomy m : matching_taxonomies ) {
368 final int s = m.getLineage().size();
369 if ( s < shortest ) {
371 least_specific_up_tax = m;
374 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, least_specific_up_tax );
375 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getScientificName() ) ) {
376 TaxonomyDataManager.getSnTaxCacheMap().put( least_specific_up_tax.getScientificName(),
377 least_specific_up_tax );
379 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCode() ) ) {
380 TaxonomyDataManager.getCodeTaxCacheMap().put( least_specific_up_tax.getCode(),
381 least_specific_up_tax );
383 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCommonName() ) ) {
384 TaxonomyDataManager.getCnTaxCacheMap().put( least_specific_up_tax.getCommonName(),
385 least_specific_up_tax );
387 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getId() ) ) {
388 TaxonomyDataManager.getIdTaxCacheMap().put( least_specific_up_tax.getId(), least_specific_up_tax );
390 return least_specific_up_tax;
393 throw new AncestralTaxonomyInferenceException( "taxonomy \"" + ( lineage.get( lineage.size() - 1 ) )
399 synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
400 final PhylogenyNode node,
402 final UniProtTaxonomy up_tax )
403 throws PhyloXmlDataFormatException {
404 if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
405 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
406 tax.setScientificName( up_tax.getScientificName() );
408 if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
409 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
410 tax.setTaxonomyCode( up_tax.getCode() );
412 if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
413 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
414 tax.setCommonName( up_tax.getCommonName() );
416 if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
417 tax.getSynonyms().add( up_tax.getSynonym() );
419 if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
421 tax.setRank( up_tax.getRank().toLowerCase() );
423 catch ( final PhyloXmlDataFormatException ex ) {
427 if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
428 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
429 tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
431 if ( up_tax.getLineage() != null ) {
432 tax.setLineage( new ArrayList<String>() );
433 for( final String lin : up_tax.getLineage() ) {
434 if ( !ForesterUtil.isEmpty( lin ) ) {
435 tax.getLineage().add( lin );
441 private final void execute() {
442 start( _mf, "taxonomy data" );
443 SortedSet<String> not_found = null;
445 not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
447 catch ( final UnknownHostException e ) {
448 JOptionPane.showMessageDialog( _mf,
449 "Could not connect to \"" + getBaseUrl() + "\"",
450 "Network error during taxonomic information gathering",
451 JOptionPane.ERROR_MESSAGE );
454 catch ( final IOException e ) {
456 JOptionPane.showMessageDialog( _mf,
458 "Failed to obtain taxonomic information",
459 JOptionPane.ERROR_MESSAGE );
462 catch ( final AncestralTaxonomyInferenceException e ) {
464 JOptionPane.showMessageDialog( _mf,
466 "Failed to obtain taxonomic information",
467 JOptionPane.ERROR_MESSAGE );
473 if ( ( _phy == null ) || _phy.isEmpty() ) {
475 JOptionPane.showMessageDialog( _mf,
476 "None of the external node taxonomies could be resolved",
477 "Taxonomy Tool Failed",
478 JOptionPane.WARNING_MESSAGE );
480 catch ( final Exception e ) {
481 // Not important if this fails, do nothing.
485 _treepanel.setTree( _phy );
487 _treepanel.setEdited( true );
488 if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
489 int max = not_found.size();
490 boolean more = false;
495 final StringBuffer sb = new StringBuffer();
496 sb.append( "Not all taxonomies could be resolved.\n" );
497 if ( not_found.size() == 1 ) {
499 sb.append( "The following taxonomy was not found and deleted (if external):\n" );
502 sb.append( "The following taxonomy was not found:\n" );
507 sb.append( "The following taxonomies were not found and deleted (if external) (total: "
508 + not_found.size() + "):\n" );
511 sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
515 for( final String string : not_found ) {
527 JOptionPane.showMessageDialog( _mf,
529 "Taxonomy Tool Completed",
530 JOptionPane.WARNING_MESSAGE );
532 catch ( final Exception e ) {
533 // Not important if this fails, do nothing.
538 JOptionPane.showMessageDialog( _mf,
539 "Taxonomy tool successfully completed",
540 "Taxonomy Tool Completed",
541 JOptionPane.INFORMATION_MESSAGE );
543 catch ( final Exception e ) {
544 // Not important if this fails, do nothing.
549 private final String getBaseUrl() {
550 return AncestralTaxonomyInferrer.getBaseUrl();