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                         node.setName( "" );
246                     }
247                     updateTaxonomy( qt, node, tax, uniprot_tax );
248                 }
249                 else {
250                     if ( tax != null ) {
251                         not_found.add( tax.toString() );
252                     }
253                     else {
254                         not_found.add(node.getName() );
255                     }
256                     if ( delete && node.isExternal() ) {
257                         not_found_external_nodes.add( node );
258                     }
259                 }
260             }
261         }
262         if ( delete ) {
263             for( final PhylogenyNode node : not_found_external_nodes ) {
264                 phy.deleteSubtree( node, true );
265             }
266             phy.externalNodesHaveChanged();
267             phy.hashIDs();
268             phy.recalculateNumberOfExternalDescendants( true );
269         }
270         return not_found;
271     }
272
273     public final static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, Object query, QUERY_TYPE qt )
274             throws IOException, AncestralTaxonomyInferenceException {
275         if ( tax == null ) {
276             throw new IllegalArgumentException( "illegal attempt to use empty taxonomy object" );
277         }
278         if ( TaxonomyDataManager.isHasAppropriateId( tax ) ) {
279             query = tax.getIdentifier().getValue();
280             qt = QUERY_TYPE.ID;
281             return obtainTaxonomy( TaxonomyDataManager.getIdTaxCacheMap(), query, qt );
282         }
283         else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
284             if ( !ForesterUtil.isEmpty( tax.getLineage() ) ) {
285                 query = tax.getLineage();
286                 qt = QUERY_TYPE.LIN;
287                 return obtainTaxonomy( TaxonomyDataManager.getLineageTaxCacheMap(), query, qt );
288             }
289             else {
290                 query = tax.getScientificName();
291                 qt = QUERY_TYPE.SN;
292                 return obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), query, qt );
293             }
294         }
295         else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
296             query = tax.getTaxonomyCode();
297             qt = QUERY_TYPE.CODE;
298             return obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), query, qt );
299         }
300         else {
301             query = tax.getCommonName();
302             qt = QUERY_TYPE.CN;
303             return obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), query, qt );
304         }
305     }
306
307     public final static UniProtTaxonomy obtainUniProtTaxonomy( final String simple_name, QUERY_TYPE qt )
308             throws IOException, AncestralTaxonomyInferenceException {
309         if ( ForesterUtil.isEmpty( simple_name ) ) {
310             throw new IllegalArgumentException( "illegal attempt to use empty simple name" );
311         }
312         qt = QUERY_TYPE.SN;
313         UniProtTaxonomy ut = obtainTaxonomy( TaxonomyDataManager.getSnTaxCacheMap(), simple_name, qt );
314         if ( ut == null ) {
315             qt = QUERY_TYPE.CODE;
316             ut = obtainTaxonomy( TaxonomyDataManager.getCodeTaxCacheMap(), simple_name, qt );
317         }
318         if ( ut == null ) {
319             qt = QUERY_TYPE.CN;
320             ut = obtainTaxonomy( TaxonomyDataManager.getCnTaxCacheMap(), simple_name, qt );
321         }
322         return ut;
323     }
324
325     static final UniProtTaxonomy obtainUniProtTaxonomyFromLineage( final List<String> lineage )
326             throws AncestralTaxonomyInferenceException, IOException {
327         final String lineage_str = ForesterUtil.stringListToString( lineage, ">" );
328         UniProtTaxonomy up_tax = null;
329         if ( TaxonomyDataManager.getLineageTaxCacheMap().containsKey( lineage_str ) ) {
330             up_tax = TaxonomyDataManager.getLineageTaxCacheMap().get( lineage_str ).copy();
331         }
332         else {
333             final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( lineage
334                     .get( lineage.size() - 1 ) );
335             if ( ( up_taxonomies != null ) && ( up_taxonomies.size() > 0 ) ) {
336                 for( final UniProtTaxonomy up_taxonomy : up_taxonomies ) {
337                     boolean match = true;
338                     I: for( int i = 0; i < lineage.size(); ++i ) {
339                         if ( !lineage.get( i ).equalsIgnoreCase( up_taxonomy.getLineage().get( i ) ) ) {
340                             match = false;
341                             break I;
342                         }
343                     }
344                     if ( match ) {
345                         if ( up_tax != null ) {
346                             throw new AncestralTaxonomyInferenceException( "lineage \""
347                                     + ForesterUtil.stringListToString( lineage, " > " ) + "\" is not unique" );
348                         }
349                         up_tax = up_taxonomy;
350                     }
351                 }
352                 if ( up_tax == null ) {
353                     throw new AncestralTaxonomyInferenceException( "lineage \""
354                             + ForesterUtil.stringListToString( lineage, " > " ) + "\" not found" );
355                 }
356                 TaxonomyDataManager.getLineageTaxCacheMap().put( lineage_str, up_tax );
357                 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
358                     TaxonomyDataManager.getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
359                 }
360                 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
361                     TaxonomyDataManager.getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
362                 }
363                 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
364                     TaxonomyDataManager.getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
365                 }
366                 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
367                     TaxonomyDataManager.getIdTaxCacheMap().put( up_tax.getId(), up_tax );
368                 }
369             }
370         }
371         return up_tax;
372     }
373
374     synchronized final private static void updateTaxonomy( final QUERY_TYPE qt,
375                                                            final PhylogenyNode node,
376                                                            final Taxonomy tax,
377                                                            final UniProtTaxonomy up_tax ) {
378         if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
379                 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
380             tax.setScientificName( up_tax.getScientificName() );
381         }
382         if ( node.isExternal() && ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
383                 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
384             tax.setTaxonomyCode( up_tax.getCode() );
385         }
386         if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
387                 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
388             tax.setCommonName( up_tax.getCommonName() );
389         }
390         if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
391             tax.getSynonyms().add( up_tax.getSynonym() );
392         }
393         if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
394             try {
395                 tax.setRank( up_tax.getRank().toLowerCase() );
396             }
397             catch ( final PhyloXmlDataFormatException ex ) {
398                 tax.setRank( "" );
399             }
400         }
401         if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() )
402                 && ( ( tax.getIdentifier() == null ) || ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) ) ) {
403             tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
404         }
405         if ( up_tax.getLineage() != null ) {
406             tax.setLineage( new ArrayList<String>() );
407             for( final String lin : up_tax.getLineage() ) {
408                 if ( !ForesterUtil.isEmpty( lin ) ) {
409                     tax.getLineage().add( lin );
410                 }
411             }
412         }
413     }
414
415     private final void execute() {
416         start( _mf, "taxonomy data" );
417         SortedSet<String> not_found = null;
418         try {
419             not_found = obtainDetailedTaxonomicInformation( _phy, _delete, _allow_simple_names );
420         }
421         catch ( final UnknownHostException e ) {
422             JOptionPane.showMessageDialog( _mf,
423                                            "Could not connect to \"" + getBaseUrl() + "\"",
424                                            "Network error during taxonomic information gathering",
425                                            JOptionPane.ERROR_MESSAGE );
426             return;
427         }
428         catch ( final IOException e ) {
429             e.printStackTrace();
430             JOptionPane.showMessageDialog( _mf,
431                                            e.toString(),
432                                            "Failed to obtain taxonomic information",
433                                            JOptionPane.ERROR_MESSAGE );
434             return;
435         }
436         catch ( final AncestralTaxonomyInferenceException e ) {
437             e.printStackTrace();
438             JOptionPane.showMessageDialog( _mf,
439                                            e.toString(),
440                                            "Failed to obtain taxonomic information",
441                                            JOptionPane.ERROR_MESSAGE );
442             return;
443         }
444         finally {
445             end( _mf );
446         }
447         if ( ( _phy == null ) || _phy.isEmpty() ) {
448             try {
449                 JOptionPane.showMessageDialog( _mf,
450                                                "None of the external node taxonomies could be resolved",
451                                                "Taxonomy Tool Failed",
452                                                JOptionPane.WARNING_MESSAGE );
453             }
454             catch ( final Exception e ) {
455                 // Not important if this fails, do nothing. 
456             }
457             return;
458         }
459         _treepanel.setTree( _phy );
460         _mf.showWhole();
461         _treepanel.setEdited( true );
462         if ( ( not_found != null ) && ( not_found.size() > 0 ) ) {
463             int max = not_found.size();
464             boolean more = false;
465             if ( max > 20 ) {
466                 more = true;
467                 max = 20;
468             }
469             final StringBuffer sb = new StringBuffer();
470             sb.append( "Not all taxonomies could be resolved.\n" );
471             if ( not_found.size() == 1 ) {
472                 if ( _delete ) {
473                     sb.append( "The following taxonomy was not found and deleted (if external):\n" );
474                 }
475                 else {
476                     sb.append( "The following taxonomy was not found:\n" );
477                 }
478             }
479             else {
480                 if ( _delete ) {
481                     sb.append( "The following taxonomies were not found and deleted (if external) (total: "
482                             + not_found.size() + "):\n" );
483                 }
484                 else {
485                     sb.append( "The following taxonomies were not found (total: " + not_found.size() + "):\n" );
486                 }
487             }
488             int i = 0;
489             for( final String string : not_found ) {
490                 if ( i > 19 ) {
491                     break;
492                 }
493                 sb.append( string );
494                 sb.append( "\n" );
495                 ++i;
496             }
497             if ( more ) {
498                 sb.append( "..." );
499             }
500             try {
501                 JOptionPane.showMessageDialog( _mf,
502                                                sb.toString(),
503                                                "Taxonomy Tool Completed",
504                                                JOptionPane.WARNING_MESSAGE );
505             }
506             catch ( final Exception e ) {
507                 // Not important if this fails, do nothing. 
508             }
509         }
510         else {
511             try {
512                 JOptionPane.showMessageDialog( _mf,
513                                                "Taxonomy tool successfully completed",
514                                                "Taxonomy Tool Completed",
515                                                JOptionPane.INFORMATION_MESSAGE );
516             }
517             catch ( final Exception e ) {
518                 // Not important if this fails, do nothing.
519             }
520         }
521     }
522
523     private final String getBaseUrl() {
524         return UniProtWsTools.BASE_URL;
525     }
526
527     @Override
528     public void run() {
529         execute();
530     }
531 }