if ( !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
[jalview.git] / forester / java / src / org / forester / analysis / TaxonomyDataManager.java
1 // $Id:
2 //
3 // forester -- software libraries and applications
4 // for genomics and evolutionary biology research.
5 //
6 // Copyright (C) 2010 Christian M Zmasek
7 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
8 // All rights reserved
9 //
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.
14 //
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.
19 //
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
23 //
24 // Contact: phylosoft @ gmail . com
25 // WWW: https://sites.google.com/site/cmzmasek/home/software/forester
26
27 package org.forester.analysis;
28
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
37 import javax.swing.JOptionPane;
38
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;
52
53 public final class TaxonomyDataManager extends RunnableProcess {
54
55     enum QUERY_TYPE {
56         CODE, SN, CN, ID, LIN;
57     }
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;
70
71     public TaxonomyDataManager( final MainFrameApplication mf, final TreePanel treepanel, final Phylogeny phy ) {
72         _phy = phy;
73         _mf = mf;
74         _treepanel = treepanel;
75         _delete = false;
76         _allow_simple_names = false;
77     }
78
79     public TaxonomyDataManager( final MainFrameApplication mf,
80                                 final TreePanel treepanel,
81                                 final Phylogeny phy,
82                                 final boolean delete,
83                                 final boolean allow_simple_name ) {
84         _phy = phy;
85         _mf = mf;
86         _treepanel = treepanel;
87         _delete = delete;
88         _allow_simple_names = allow_simple_name;
89     }
90
91     synchronized static void clearCachesIfTooLarge() {
92         if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
93             getSnTaxCacheMap().clear();
94         }
95         if ( getLineageTaxCacheMap().size() > MAX_CACHE_SIZE ) {
96             getLineageTaxCacheMap().clear();
97         }
98         if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
99             getCnTaxCacheMap().clear();
100         }
101         if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
102             getCodeTaxCacheMap().clear();
103         }
104         if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
105             getIdTaxCacheMap().clear();
106         }
107     }
108
109     synchronized final static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
110         return _cn_up_cache_map;
111     }
112
113     synchronized final static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
114         return _code_up_cache_map;
115     }
116
117     synchronized final static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
118         return _id_up_cache_map;
119     }
120
121     synchronized final static HashMap<String, UniProtTaxonomy> getLineageTaxCacheMap() {
122         return _lineage_up_cache_map;
123     }
124
125     synchronized final static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
126         return _sn_up_cache_map;
127     }
128
129     private final static UniProtTaxonomy obtainTaxonomy( final HashMap<String, UniProtTaxonomy> cache,
130                                                          final Object query,
131                                                          final QUERY_TYPE qt ) throws IOException,
132             AncestralTaxonomyInferenceException {
133         if ( cache.containsKey( query ) ) {
134             return cache.get( query ).copy();
135         }
136         else {
137             List<UniProtTaxonomy> up_taxonomies = null;
138             switch ( qt ) {
139                 case ID:
140                     up_taxonomies = getTaxonomiesFromId( ( String ) query );
141                     break;
142                 case CODE:
143                     up_taxonomies = getTaxonomiesFromTaxonomyCode( ( String ) query );
144                     break;
145                 case SN:
146                     up_taxonomies = getTaxonomiesFromScientificName( ( String ) query );
147                     break;
148                 case CN:
149                     up_taxonomies = getTaxonomiesFromCommonName( ( String ) query );
150                     break;
151                 case LIN:
152                     return obtainUniProtTaxonomyFromLineage( ( List<String> ) query );
153                 default:
154                     throw new RuntimeException();
155             }
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 );
160                 }
161                 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
162                     TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
163                 }
164                 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
165                     TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
166                 }
167                 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
168                     TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
169                 }
170                 return up_tax;
171             }
172             else {
173                 return null;
174             }
175         }
176     }
177
178     private final static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query ) throws IOException {
179         return SequenceDbWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
180     }
181
182     private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
183         return SequenceDbWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
184     }
185
186     private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
187         return SequenceDbWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
188     }
189
190     private final static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query ) throws IOException {
191         return SequenceDbWsTools.getTaxonomiesFromTaxonomyCode( query, MAX_TAXONOMIES_TO_RETURN );
192     }
193
194     static final boolean isHasAppropriateId( final Taxonomy tax ) {
195         return ( ( tax.getIdentifier() != null ) && ( !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) && ( tax
196                 .getIdentifier().getProvider().equalsIgnoreCase( "ncbi" )
197                 || tax.getIdentifier().getProvider().equalsIgnoreCase( "uniprot" ) || tax.getIdentifier().getProvider()
198                 .equalsIgnoreCase( "uniprotkb" ) ) ) );
199     }
200
201     synchronized final private static SortedSet<String> obtainDetailedTaxonomicInformation( final Phylogeny phy,
202                                                                                             final boolean delete,
203                                                                                             final boolean allow_to_use_basic_node_names )
204             throws IOException, AncestralTaxonomyInferenceException {
205         clearCachesIfTooLarge();
206         final SortedSet<String> not_found = new TreeSet<String>();
207         List<PhylogenyNode> not_found_external_nodes = null;
208         if ( delete ) {
209             not_found_external_nodes = new ArrayList<PhylogenyNode>();
210         }
211         for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
212             final PhylogenyNode node = iter.next();
213             final QUERY_TYPE qt = null;
214             Taxonomy tax = null;
215             if ( node.getNodeData().isHasTaxonomy() ) {
216                 tax = node.getNodeData().getTaxonomy();
217             }
218             else if ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) {
219                 // Nothing to be done.
220             }
221             else if ( node.isExternal() ) {
222                 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
223                     not_found.add( node.getName() );
224                 }
225                 else {
226                     not_found.add( node.toString() );
227                 }
228                 if ( delete ) {
229                     not_found_external_nodes.add( node );
230                 }
231             }
232             UniProtTaxonomy uniprot_tax = null;
233             if ( ( ( tax != null ) && ( isHasAppropriateId( tax ) || !ForesterUtil.isEmpty( tax.getScientificName() )
234                     || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil.isEmpty( tax.getCommonName() ) ) )
235                     || ( allow_to_use_basic_node_names && !ForesterUtil.isEmpty( node.getName() ) ) ) {
236                 if ( tax != null ) {
237                     uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
238                 }
239                 else {
240                     uniprot_tax = obtainUniProtTaxonomy( node.getName(), qt );
241                 }
242                 if ( uniprot_tax != null ) {
243                     if ( tax == null ) {
244                         tax = new Taxonomy();
245                         node.getNodeData().addTaxonomy( tax );
246                         node.setName( "" );
247                     }
248                     updateTaxonomy( qt, node, tax, uniprot_tax );
249                 }
250                 else {
251                     if ( tax != null ) {
252                         not_found.add( tax.toString() );
253                     }
254                     else {
255                         not_found.add( node.getName() );
256                     }
257                     if ( delete && node.isExternal() ) {
258                         not_found_external_nodes.add( node );
259                     }
260                 }
261             }
262         }
263         if ( delete ) {
264             for( final PhylogenyNode node : not_found_external_nodes ) {
265                 phy.deleteSubtree( node, true );
266             }
267             phy.externalNodesHaveChanged();
268             phy.clearHashIdToNodeMap();
269             phy.recalculateNumberOfExternalDescendants( true );
270         }
271         return not_found;
272     }
273
274     public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
275             throws IOException, AncestralTaxonomyInferenceException {
276         if ( tax == null ) {
277             throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
278         }
279         if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
280             query = tax.getIdentifier().getValue();
281             qt = QUERY_TYPE.ID;
282             return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
283         }
284         else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
285             if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
286                 query = tax.getLineage();
287                 qt = QUERY_TYPE.LIN;
288                 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
289             }
290             else {
291                 query = tax.getScientificName();
292                 qt = QUERY_TYPE.SN;
293                 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
294             }
295         }
296         else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
297             query = tax.getTaxonomyCode();
298             qt = QUERY_TYPE.CODE;
299             return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
300         }
301         else {
302             query = tax.getCommonName();
303             qt = QUERY_TYPE.CN;
304             return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
305         }
306     }
307
308     public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
309             throws IOException, AncestralTaxonomyInferenceException {
310         if ( ForesterUtil.isEmpty( simple_name ) ) {
311             throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
312         }
313         qt = QUERY_TYPE.SN;
314         UniProtTaxonomy ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), simple_name, qt );
315         if ( ut == null ) {
316             qt = QUERY_TYPE.CODE;
317             ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), simple_name, qt );
318         }
319         if ( ut == null ) {
320             qt = QUERY_TYPE.CN;
321             ut = obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), simple_name, qt );
322         }
323         return ut;
324     }
325
326     static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
327             throws AncestralTaxonomyInferenceException, IOException {
328         final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
329         UniProtTaxonomy up_tax = null;
330         if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
331             up_tax = TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
332         }
333         else {
334             final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
335                     .get( lineage.size() - 1 ) );
336             if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
337                 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
338                     boolean match = true;
339                     I: for( int i = 0; i < lineage.size(); ++i ) {
340                         if ( i == up_taxonomy.getLineage().size() || !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
341                             match = false;
342                             break I;
343                         }
344                     }
345                     if ( match ) {
346                         if ( up_tax != null ) {
347                             //TODO this is dead code?!
348                             throw new AncestralTaxonomyInferenceException( "lineage \""
349                                     + ForesterUtil.stringListToString( lineage, " > " ) + "\" is not unique" );
350                         }
351                         up_tax = up_taxonomy;
352                     }
353                 }
354                 if ( up_tax == null ) {
355                     throw new AncestralTaxonomyInferenceException( "lineage \""
356                             + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
357                 }
358                 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, up_tax );
359                 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
360                     TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
361                 }
362                 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
363                     TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
364                 }
365                 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
366                     TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
367                 }
368                 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
369                     TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
370                 }
371             }
372         }
373         return up_tax;
374     }
375
376     synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
377                                                            final PhylogenyNode node,
378                                                            final Taxonomy tax,
379                                                            final UniProtTaxonomy up_tax )
380             throws PhyloXmlDataFormatException {
381         if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
382                 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
383             tax.setScientificName( up_tax.getScientificName() );
384         }
385         if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
386                 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
387             tax.setTaxonomyCode( up_tax.getCode() );
388         }
389         if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
390                 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
391             tax.setCommonName( up_tax.getCommonName() );
392         }
393         if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
394             tax.getSynonyms().add( up_tax.getSynonym() );
395         }
396         if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
397             try {
398                 tax.setRank( up_tax.getRank().toLowerCase() );
399             }
400             catch ( final PhyloXmlDataFormatException ex ) {
401                 tax.setRank( "" );
402             }
403         }
404         if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
405                 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
406             tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
407         }
408         if ( up_tax.getLineage() != null ) {
409             tax.setLineage( new ArrayList<String>() );
410             for( final String lin : up_tax.getLineage() ) {
411                 if ( !ForesterUtil.isEmpty( lin ) ) {
412                     tax.getLineage().add( lin );
413                 }
414             }
415         }
416     }
417
418     private final void execute() {
419         start( _mf, "taxonomy data" );
420         SortedSet<String> not_found = null;
421         try {
422             not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
423         }
424         catch ( final UnknownHostException e ) {
425             JOptionPane.showMessageDialog( _mf,
426                                            "Could not connect to \"" + getBaseUrl() + "\"",
427                                            "Network error during taxonomic information gathering",
428                                            JOptionPane.ERROR_MESSAGE );
429             return;
430         }
431         catch ( final IOException e ) {
432             e.printStackTrace();
433             JOptionPane.showMessageDialog( _mf,
434                                            e.toString(),
435                                            "Failed to obtain taxonomic information",
436                                            JOptionPane.ERROR_MESSAGE );
437             return;
438         }
439         catch ( final AncestralTaxonomyInferenceException e ) {
440             e.printStackTrace();
441             JOptionPane.showMessageDialog( _mf,
442                                            e.toString(),
443                                            "Failed to obtain taxonomic information",
444                                            JOptionPane.ERROR_MESSAGE );
445             return;
446         }
447         finally {
448             end( _mf );
449         }
450         if ( ( _phy == null ) || _phy.isEmpty() ) {
451             try {
452                 JOptionPane.showMessageDialog( _mf,
453                                                "None of the external node taxonomies could be resolved",
454                                                "Taxonomy Tool Failed",
455                                                JOptionPane.WARNING_MESSAGE );
456             }
457             catch ( final Exception e ) {
458                 // Not important if this fails, do nothing. 
459             }
460             return;
461         }
462         _treepanel.setTree( _phy );
463         _mf.showWhole();
464         _treepanel.setEdited( true );
465         if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
466             int max = not_found.size();
467             boolean more = false;
468             if ( max > 20 ) {
469                 more = true;
470                 max = 20;
471             }
472             final StringBuffer sb = new StringBuffer();
473             sb.append( "Not all taxonomies could be resolved.\n" );
474             if ( not_found.size() == 1 ) {
475                 if ( _delete ) {
476                     sb.append( "The following taxonomy was not found and deleted (if external):\n" );
477                 }
478                 else {
479                     sb.append( "The following taxonomy was not found:\n" );
480                 }
481             }
482             else {
483                 if ( _delete ) {
484                     sb.append( "The following taxonomies were not found and deleted (if external) (total: "
485                             + not_found.size() + "):\n" );
486                 }
487                 else {
488                     sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
489                 }
490             }
491             int i = 0;
492             for( final String string : not_found ) {
493                 if ( i > 19 ) {
494                     break;
495                 }
496                 sb.append( string );
497                 sb.append( "\n" );
498                 ++i;
499             }
500             if ( more ) {
501                 sb.append( "..." );
502             }
503             try {
504                 JOptionPane.showMessageDialog( _mf,
505                                                sb.toString(),
506                                                "Taxonomy Tool Completed",
507                                                JOptionPane.WARNING_MESSAGE );
508             }
509             catch ( final Exception e ) {
510                 // Not important if this fails, do nothing. 
511             }
512         }
513         else {
514             try {
515                 JOptionPane.showMessageDialog( _mf,
516                                                "Taxonomy tool successfully completed",
517                                                "Taxonomy Tool Completed",
518                                                JOptionPane.INFORMATION_MESSAGE );
519             }
520             catch ( final Exception e ) {
521                 // Not important if this fails, do nothing.
522             }
523         }
524     }
525
526     private final String getBaseUrl() {
527         return AncestralTaxonomyInferrer.getBaseUrl();
528     }
529
530     @Override
531     public void run() {
532         execute();
533     }
534 }