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