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.nhx.NHXParser;
44 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
45 import org.forester.io.parsers.util.ParserUtils;
46 import org.forester.phylogeny.Phylogeny;
47 import org.forester.phylogeny.PhylogenyNode;
48 import org.forester.phylogeny.data.Identifier;
49 import org.forester.phylogeny.data.Taxonomy;
50 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
51 import org.forester.util.ForesterUtil;
52 import org.forester.util.TaxonomyUtil;
53 import org.forester.ws.seqdb.SequenceDbWsTools;
54 import org.forester.ws.seqdb.UniProtTaxonomy;
56 public final class TaxonomyDataManager extends RunnableProcess {
59 CODE, SN, CN, ID, LIN;
61 private static final int MAX_CACHE_SIZE = 100000;
62 private static final int MAX_TAXONOMIES_TO_RETURN = 2000;
63 private static final HashMap<String, UniProtTaxonomy> _sn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
64 private static final HashMap<String, UniProtTaxonomy> _lineage_up_cache_map = new HashMap<String, UniProtTaxonomy>();
65 private static final HashMap<String, UniProtTaxonomy> _code_up_cache_map = new HashMap<String, UniProtTaxonomy>();
66 private static final HashMap<String, UniProtTaxonomy> _cn_up_cache_map = new HashMap<String, UniProtTaxonomy>();
67 private static final HashMap<String, UniProtTaxonomy> _id_up_cache_map = new HashMap<String, UniProtTaxonomy>();
68 private final Phylogeny _phy;
69 private final MainFrameApplication _mf;
70 private final TreePanel _treepanel;
71 private final boolean _delete;
72 private final boolean _allow_simple_names;
74 public TaxonomyDataManager( final MainFrameApplication mf, final TreePanel treepanel, final Phylogeny phy ) {
77 _treepanel = treepanel;
79 _allow_simple_names = false;
82 public TaxonomyDataManager( final MainFrameApplication mf,
83 final TreePanel treepanel,
86 final boolean allow_simple_name ) {
89 _treepanel = treepanel;
91 _allow_simple_names = allow_simple_name;
94 synchronized static void clearCachesIfTooLarge() {
95 if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
96 getSnTaxCacheMap().clear();
98 if ( getLineageTaxCacheMap().size() > MAX_CACHE_SIZE ) {
99 getLineageTaxCacheMap().clear();
101 if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
102 getCnTaxCacheMap().clear();
104 if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
105 getCodeTaxCacheMap().clear();
107 if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
108 getIdTaxCacheMap().clear();
112 synchronized final static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
113 return _cn_up_cache_map;
116 synchronized final static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
117 return _code_up_cache_map;
120 synchronized final static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
121 return _id_up_cache_map;
124 synchronized final static HashMap<String, UniProtTaxonomy> getLineageTaxCacheMap() {
125 return _lineage_up_cache_map;
128 synchronized final static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
129 return _sn_up_cache_map;
132 private final static UniProtTaxonomy obtainTaxonomy( final HashMap<String, UniProtTaxonomy> cache,
134 final QUERY_TYPE qt ) throws IOException,
135 AncestralTaxonomyInferenceException {
136 if ( cache.containsKey( query ) ) {
137 return cache.get( query ).copy();
140 List<UniProtTaxonomy> up_taxonomies = null;
143 up_taxonomies = getTaxonomiesFromId( ( String ) query );
146 up_taxonomies = getTaxonomiesFromTaxonomyCode( ( String ) query );
149 up_taxonomies = getTaxonomiesFromScientificName( ( String ) query );
152 up_taxonomies = getTaxonomiesFromCommonName( ( String ) query );
155 return obtainUniProtTaxonomyFromLineage( ( List<String> ) query );
157 throw new RuntimeException();
159 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
160 final UniProtTaxonomy up_tax = up_taxonomies.get( 0 );
161 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
162 TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
164 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
165 TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
167 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
168 TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
170 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
171 TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
181 private final static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query ) throws IOException {
182 return SequenceDbWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
185 private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
186 return SequenceDbWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
189 private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
190 if ( query.equalsIgnoreCase( UniProtTaxonomy.BACTERIA ) || query.equalsIgnoreCase( UniProtTaxonomy.ARCHAEA )
191 || query.equalsIgnoreCase( UniProtTaxonomy.VIRUSES )
192 || query.equalsIgnoreCase( UniProtTaxonomy.EUKARYOTA ) || query.equalsIgnoreCase( UniProtTaxonomy.X ) ) {
193 final List<UniProtTaxonomy> l = new ArrayList<UniProtTaxonomy>();
194 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 if ( ( query.indexOf( "XX" ) == 3 ) && TaxonomyUtil.isHasTaxIdFromFakeTaxCode( query ) ) {
202 final int id = TaxonomyUtil.getTaxIdFromFakeTaxCode( query );
203 return SequenceDbWsTools.getTaxonomiesFromId( String.valueOf( id ), MAX_TAXONOMIES_TO_RETURN );
205 return SequenceDbWsTools.getTaxonomiesFromTaxonomyCode( query, MAX_TAXONOMIES_TO_RETURN );
208 static final boolean isHasAppropriateId( final Taxonomy tax ) {
209 return ( ( tax.getIdentifier() != null ) && ( !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) && ( tax
210 .getIdentifier().getProvider().equalsIgnoreCase( "ncbi" )
211 || tax.getIdentifier().getProvider().equalsIgnoreCase( "uniprot" ) || tax.getIdentifier().getProvider()
212 .equalsIgnoreCase( "uniprotkb" ) ) ) );
215 synchronized final private static SortedSet<String> obtainDetailedTaxonomicInformation( final Phylogeny phy,
216 final boolean delete,
217 final boolean allow_to_use_basic_node_names )
218 throws IOException, AncestralTaxonomyInferenceException {
219 clearCachesIfTooLarge();
220 final SortedSet<String> not_found = new TreeSet<String>();
221 List<PhylogenyNode> not_found_external_nodes = null;
223 not_found_external_nodes = new ArrayList<PhylogenyNode>();
225 for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
226 final PhylogenyNode node = iter.next();
227 final QUERY_TYPE qt = null;
229 if ( node.getNodeData().isHasTaxonomy() ) {
230 tax = node.getNodeData().getTaxonomy();
232 else if ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) {
233 // Nothing to be done.
235 else if ( node.isExternal() ) {
236 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
237 not_found.add( node.getName() );
240 not_found.add( node.toString() );
243 not_found_external_nodes.add( node );
246 UniProtTaxonomy uniprot_tax = null;
247 if ( ( ( tax != null ) && ( isHasAppropriateId( tax ) || !ForesterUtil.isEmpty( tax.getScientificName() )
248 || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil.isEmpty( tax.getCommonName() ) ) )
249 || ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) ) {
250 if ( ( ( tax != null ) && ( isHasAppropriateId( tax )
251 || !ForesterUtil.isEmpty( tax.getScientificName() )
252 || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil
253 .isEmpty( tax.getCommonName() ) ) ) ) {
254 uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
257 uniprot_tax = obtainUniProtTaxonomy( node.getName(), qt );
259 if ( uniprot_tax != null ) {
261 tax = new Taxonomy();
262 node.getNodeData().addTaxonomy( tax );
264 updateTaxonomy( qt, node, tax, uniprot_tax );
268 not_found.add( tax.toString() );
271 not_found.add( node.getName() );
273 if ( delete && node.isExternal() ) {
274 not_found_external_nodes.add( node );
280 for( final PhylogenyNode node : not_found_external_nodes ) {
281 phy.deleteSubtree( node, true );
283 phy.externalNodesHaveChanged();
284 phy.clearHashIdToNodeMap();
285 phy.recalculateNumberOfExternalDescendants( true );
290 public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
291 throws IOException, AncestralTaxonomyInferenceException {
293 throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
295 if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
296 query = tax.getIdentifier().getValue();
298 return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
300 else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
301 if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
302 query = tax.getLineage();
304 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
307 query = tax.getScientificName();
309 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
312 else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
313 query = tax.getTaxonomyCode();
314 qt = QUERY_TYPE.CODE;
315 return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
318 query = tax.getCommonName();
320 return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
324 public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
325 throws IOException, AncestralTaxonomyInferenceException {
326 if ( ForesterUtil.isEmpty( simple_name ) ) {
327 throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
329 UniProtTaxonomy ut = null;
330 final String code = ParserUtils.extractTaxonomyCodeFromNodeName( simple_name,
331 NHXParser.TAXONOMY_EXTRACTION.AGGRESSIVE );
332 if ( !ForesterUtil.isEmpty( code ) ) {
333 qt = QUERY_TYPE.CODE;
334 ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), code, qt );
337 final String sn = ParserUtils.extractScientificNameFromNodeName( simple_name );
338 if ( !ForesterUtil.isEmpty( sn ) ) {
340 ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), sn, qt );
344 final String id = ParserUtils
345 .extractUniprotTaxonomyIdFromNodeName( simple_name,
346 NHXParser.TAXONOMY_EXTRACTION.PFAM_STYLE_RELAXED );
347 if ( !ForesterUtil.isEmpty( id ) ) {
349 ut = obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), id, qt );
353 // qt = QUERY_TYPE.SN;
354 // UniProtTaxonomy ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), simple_name, qt );
355 // if ( ut == null ) {
356 // qt = QUERY_TYPE.CODE;
357 // ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), simple_name, qt );
359 // if ( ut == null ) {
360 // qt = QUERY_TYPE.CN;
361 // ut = obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), simple_name, qt );
366 static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
367 throws AncestralTaxonomyInferenceException, IOException {
368 final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
369 if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
370 return TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
373 final List<UniProtTaxonomy> matching_taxonomies = new ArrayList<UniProtTaxonomy>();
374 final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
375 .get( lineage.size() - 1 ) );
376 if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
377 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
378 boolean match = true;
379 I: for( int i = 0; i < lineage.size(); ++i ) {
380 if ( ( i == up_taxonomy.getLineage().size() )
381 || !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
387 matching_taxonomies.add( up_taxonomy );
390 if ( matching_taxonomies.isEmpty() ) {
391 throw new AncestralTaxonomyInferenceException( "lineage \""
392 + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
394 //in case of more than one (e.g. "Xenopus" Genus and Subgenus), keep shorter, less specific one:
395 int shortest = Integer.MAX_VALUE;
396 UniProtTaxonomy least_specific_up_tax = null;
397 for( final UniProtTaxonomy m : matching_taxonomies ) {
398 final int s = m.getLineage().size();
399 if ( s < shortest ) {
401 least_specific_up_tax = m;
404 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, least_specific_up_tax );
405 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getScientificName() ) ) {
406 TaxonomyDataManager.getSnTaxCacheMap().put( least_specific_up_tax.getScientificName(),
407 least_specific_up_tax );
409 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCode() ) ) {
410 TaxonomyDataManager.getCodeTaxCacheMap().put( least_specific_up_tax.getCode(),
411 least_specific_up_tax );
413 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getCommonName() ) ) {
414 TaxonomyDataManager.getCnTaxCacheMap().put( least_specific_up_tax.getCommonName(),
415 least_specific_up_tax );
417 if ( !ForesterUtil.isEmpty( least_specific_up_tax.getId() ) ) {
418 TaxonomyDataManager.getIdTaxCacheMap().put( least_specific_up_tax.getId(), least_specific_up_tax );
420 return least_specific_up_tax;
423 throw new AncestralTaxonomyInferenceException( "taxonomy \"" + ( lineage.get( lineage.size() - 1 ) )
429 synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
430 final PhylogenyNode node,
432 final UniProtTaxonomy up_tax )
433 throws PhyloXmlDataFormatException {
434 if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
435 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
436 tax.setScientificName( up_tax.getScientificName() );
438 if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
439 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
440 tax.setTaxonomyCode( up_tax.getCode() );
442 if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
443 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
444 tax.setCommonName( up_tax.getCommonName() );
446 if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
447 tax.getSynonyms().add( up_tax.getSynonym() );
449 if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
451 tax.setRank( up_tax.getRank().toLowerCase() );
453 catch ( final PhyloXmlDataFormatException ex ) {
457 if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
458 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
459 tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
461 if ( up_tax.getLineage() != null ) {
462 tax.setLineage( new ArrayList<String>() );
463 for( final String lin : up_tax.getLineage() ) {
464 if ( !ForesterUtil.isEmpty( lin ) ) {
465 tax.getLineage().add( lin );
471 private final void execute() {
472 start( _mf, "taxonomy data" );
473 SortedSet<String> not_found = null;
475 not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
477 catch ( final UnknownHostException e ) {
478 JOptionPane.showMessageDialog( _mf,
479 "Could not connect to \"" + getBaseUrl() + "\"",
480 "Network error during taxonomic information gathering",
481 JOptionPane.ERROR_MESSAGE );
484 catch ( final IOException e ) {
486 JOptionPane.showMessageDialog( _mf,
488 "Failed to obtain taxonomic information",
489 JOptionPane.ERROR_MESSAGE );
492 catch ( final AncestralTaxonomyInferenceException e ) {
494 JOptionPane.showMessageDialog( _mf,
496 "Failed to obtain taxonomic information",
497 JOptionPane.ERROR_MESSAGE );
503 if ( ( _phy == null ) || _phy.isEmpty() ) {
505 JOptionPane.showMessageDialog( _mf,
506 "None of the external node taxonomies could be resolved",
507 "Taxonomy Tool Failed",
508 JOptionPane.WARNING_MESSAGE );
510 catch ( final Exception e ) {
511 // Not important if this fails, do nothing.
515 _treepanel.setTree( _phy );
517 _treepanel.setEdited( true );
518 if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
519 int max = not_found.size();
520 boolean more = false;
525 final StringBuffer sb = new StringBuffer();
526 sb.append( "Not all taxonomies could be resolved.\n" );
527 if ( not_found.size() == 1 ) {
529 sb.append( "The following taxonomy was not found and deleted (if external):\n" );
532 sb.append( "The following taxonomy was not found:\n" );
537 sb.append( "The following taxonomies were not found and deleted (if external) (total: "
538 + not_found.size() + "):\n" );
541 sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
545 for( final String string : not_found ) {
557 JOptionPane.showMessageDialog( _mf,
559 "Taxonomy Tool Completed",
560 JOptionPane.WARNING_MESSAGE );
562 catch ( final Exception e ) {
563 // Not important if this fails, do nothing.
568 JOptionPane.showMessageDialog( _mf,
569 "Taxonomy tool successfully completed",
570 "Taxonomy Tool Completed",
571 JOptionPane.INFORMATION_MESSAGE );
573 catch ( final Exception e ) {
574 // Not important if this fails, do nothing.
579 private final String getBaseUrl() {
580 return AncestralTaxonomyInferrer.getBaseUrl();