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