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