phylotastic hackathon at NESCENT 120606
[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.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.uniprot.UniProtTaxonomy;
51 import org.forester.ws.uniprot.UniProtWsTools;
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 UniProtWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
180     }
181
182     private final static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
183         return UniProtWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
184     }
185
186     private final static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query ) throws IOException {
187         return UniProtWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
188     }
189
190     private final static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query ) throws IOException {
191         return UniProtWsTools.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.hashIDs();
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 ( !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                             throw new AncestralTaxonomyInferenceException( "lineage \""
348                                     + ForesterUtil.stringListToString( lineage, " > " ) + "\" is not unique" );
349                         }
350                         up_tax = up_taxonomy;
351                     }
352                 }
353                 if ( up_tax == null ) {
354                     throw new AncestralTaxonomyInferenceException( "lineage \""
355                             + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
356                 }
357                 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, up_tax );
358                 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
359                     TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
360                 }
361                 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
362                     TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
363                 }
364                 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
365                     TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
366                 }
367                 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
368                     TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
369                 }
370             }
371         }
372         return up_tax;
373     }
374
375     synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
376                                                            final PhylogenyNode node,
377                                                            final Taxonomy tax,
378                                                            final UniProtTaxonomy up_tax ) {
379         if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
380                 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
381             tax.setScientificName( up_tax.getScientificName() );
382         }
383         if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
384                 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
385             tax.setTaxonomyCode( up_tax.getCode() );
386         }
387         if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
388                 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
389             tax.setCommonName( up_tax.getCommonName() );
390         }
391         if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
392             tax.getSynonyms().add( up_tax.getSynonym() );
393         }
394         if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
395             try {
396                 tax.setRank( up_tax.getRank().toLowerCase() );
397             }
398             catch ( final PhyloXmlDataFormatException ex ) {
399                 tax.setRank( "" );
400             }
401         }
402         if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
403                 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
404             tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
405         }
406         if ( up_tax.getLineage() != null ) {
407             tax.setLineage( new ArrayList<String>() );
408             for( final String lin : up_tax.getLineage() ) {
409                 if ( !ForesterUtil.isEmpty( lin ) ) {
410                     tax.getLineage().add( lin );
411                 }
412             }
413         }
414     }
415
416     private final void execute() {
417         start( _mf, "taxonomy data" );
418         SortedSet<String> not_found = null;
419         try {
420             not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
421         }
422         catch ( final UnknownHostException e ) {
423             JOptionPane.showMessageDialog( _mf,
424                                            "Could not connect to \"" + getBaseUrl() + "\"",
425                                            "Network error during taxonomic information gathering",
426                                            JOptionPane.ERROR_MESSAGE );
427             return;
428         }
429         catch ( final IOException e ) {
430             e.printStackTrace();
431             JOptionPane.showMessageDialog( _mf,
432                                            e.toString(),
433                                            "Failed to obtain taxonomic information",
434                                            JOptionPane.ERROR_MESSAGE );
435             return;
436         }
437         catch ( final AncestralTaxonomyInferenceException e ) {
438             e.printStackTrace();
439             JOptionPane.showMessageDialog( _mf,
440                                            e.toString(),
441                                            "Failed to obtain taxonomic information",
442                                            JOptionPane.ERROR_MESSAGE );
443             return;
444         }
445         finally {
446             end( _mf );
447         }
448         if ( ( _phy == null ) || _phy.isEmpty() ) {
449             try {
450                 JOptionPane.showMessageDialog( _mf,
451                                                "None of the external node taxonomies could be resolved",
452                                                "Taxonomy Tool Failed",
453                                                JOptionPane.WARNING_MESSAGE );
454             }
455             catch ( final Exception e ) {
456                 // Not important if this fails, do nothing. 
457             }
458             return;
459         }
460         _treepanel.setTree( _phy );
461         _mf.showWhole();
462         _treepanel.setEdited( true );
463         if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
464             int max = not_found.size();
465             boolean more = false;
466             if ( max > 20 ) {
467                 more = true;
468                 max = 20;
469             }
470             final StringBuffer sb = new StringBuffer();
471             sb.append( "Not all taxonomies could be resolved.\n" );
472             if ( not_found.size() == 1 ) {
473                 if ( _delete ) {
474                     sb.append( "The following taxonomy was not found and deleted (if external):\n" );
475                 }
476                 else {
477                     sb.append( "The following taxonomy was not found:\n" );
478                 }
479             }
480             else {
481                 if ( _delete ) {
482                     sb.append( "The following taxonomies were not found and deleted (if external) (total: "
483                             + not_found.size() + "):\n" );
484                 }
485                 else {
486                     sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
487                 }
488             }
489             int i = 0;
490             for( final String string : not_found ) {
491                 if ( i > 19 ) {
492                     break;
493                 }
494                 sb.append( string );
495                 sb.append( "\n" );
496                 ++i;
497             }
498             if ( more ) {
499                 sb.append( "..." );
500             }
501             try {
502                 JOptionPane.showMessageDialog( _mf,
503                                                sb.toString(),
504                                                "Taxonomy Tool Completed",
505                                                JOptionPane.WARNING_MESSAGE );
506             }
507             catch ( final Exception e ) {
508                 // Not important if this fails, do nothing. 
509             }
510         }
511         else {
512             try {
513                 JOptionPane.showMessageDialog( _mf,
514                                                "Taxonomy tool successfully completed",
515                                                "Taxonomy Tool Completed",
516                                                JOptionPane.INFORMATION_MESSAGE );
517             }
518             catch ( final Exception e ) {
519                 // Not important if this fails, do nothing.
520             }
521         }
522     }
523
524     private final String getBaseUrl() {
525         return AncestralTaxonomyInferrer.getBaseUrl();
526     }
527
528     @Override
529     public void run() {
530         execute();
531     }
532 }