dec0a635a22def5b0097f958aaca0c0fc2fe536e
[jalview.git] / forester / java / src / org / forester / analysis / AncestralTaxonomyInference.java
1 // forester -- software libraries and applications
2 // for genomics and evolutionary biology research.
3 //
4 // Copyright (C) 2010 Christian M Zmasek
5 // Copyright (C) 2010 Sanford-Burnham Medical Research Institute
6 // All rights reserved
7 //
8 // This library is free software; you can redistribute it and/or
9 // modify it under the terms of the GNU Lesser General Public
10 // License as published by the Free Software Foundation; either
11 // version 2.1 of the License, or (at your option) any later version.
12 //
13 // This library is distributed in the hope that it will be useful,
14 // but WITHOUT ANY WARRANTY; without even the implied warranty of
15 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 // Lesser General Public License for more details.
17 //
18 // You should have received a copy of the GNU Lesser General Public
19 // License along with this library; if not, write to the Free Software
20 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
21 //
22 // Contact: phylosoft @ gmail . com
23 // WWW: www.phylosoft.org/forester
24
25 package org.forester.analysis;
26
27 import java.io.IOException;
28 import java.util.ArrayList;
29 import java.util.HashMap;
30 import java.util.List;
31 import java.util.SortedSet;
32 import java.util.TreeSet;
33
34 import org.forester.io.parsers.phyloxml.PhyloXmlDataFormatException;
35 import org.forester.phylogeny.Phylogeny;
36 import org.forester.phylogeny.PhylogenyNode;
37 import org.forester.phylogeny.data.Identifier;
38 import org.forester.phylogeny.data.Taxonomy;
39 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
40 import org.forester.util.ForesterUtil;
41 import org.forester.ws.uniprot.UniProtTaxonomy;
42 import org.forester.ws.uniprot.UniProtWsTools;
43
44 public final class AncestralTaxonomyInference {
45
46     private static final int                              MAX_CACHE_SIZE           = 100000;
47     private static final int                              MAX_TAXONOMIES_TO_RETURN = 100;
48     private static final HashMap<String, UniProtTaxonomy> _sn_up_cache_map         = new HashMap<String, UniProtTaxonomy>();
49     private static final HashMap<String, UniProtTaxonomy> _code_up_cache_map       = new HashMap<String, UniProtTaxonomy>();
50     private static final HashMap<String, UniProtTaxonomy> _cn_up_cache_map         = new HashMap<String, UniProtTaxonomy>();
51     private static final HashMap<String, UniProtTaxonomy> _id_up_cache_map         = new HashMap<String, UniProtTaxonomy>();
52
53     synchronized private static void clearCachesIfTooLarge() {
54         if ( getSnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
55             getSnTaxCacheMap().clear();
56         }
57         if ( getCnTaxCacheMap().size() > MAX_CACHE_SIZE ) {
58             getCnTaxCacheMap().clear();
59         }
60         if ( getCodeTaxCacheMap().size() > MAX_CACHE_SIZE ) {
61             getCodeTaxCacheMap().clear();
62         }
63         if ( getIdTaxCacheMap().size() > MAX_CACHE_SIZE ) {
64             getIdTaxCacheMap().clear();
65         }
66     }
67
68     synchronized private static HashMap<String, UniProtTaxonomy> getCnTaxCacheMap() {
69         return _cn_up_cache_map;
70     }
71
72     synchronized private static HashMap<String, UniProtTaxonomy> getCodeTaxCacheMap() {
73         return _code_up_cache_map;
74     }
75
76     synchronized private static HashMap<String, UniProtTaxonomy> getIdTaxCacheMap() {
77         return _id_up_cache_map;
78     }
79
80     synchronized private static HashMap<String, UniProtTaxonomy> getSnTaxCacheMap() {
81         return _sn_up_cache_map;
82     }
83
84     synchronized private static UniProtTaxonomy getTaxonomies( final HashMap<String, UniProtTaxonomy> cache,
85                                                                final String query,
86                                                                final QUERY_TYPE qt ) throws IOException {
87         if ( cache.containsKey( query ) ) {
88             return cache.get( query ).copy();
89         }
90         else {
91             List<UniProtTaxonomy> up_taxonomies = null;
92             switch ( qt ) {
93                 case ID:
94                     up_taxonomies = getTaxonomiesFromId( query );
95                     break;
96                 case CODE:
97                     up_taxonomies = getTaxonomiesFromTaxonomyCode( query );
98                     break;
99                 case SN:
100                     up_taxonomies = getTaxonomiesFromScientificName( query );
101                     break;
102                 case CN:
103                     up_taxonomies = getTaxonomiesFromCommonName( query );
104                     break;
105                 default:
106                     throw new RuntimeException();
107             }
108             if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
109                 final UniProtTaxonomy up_tax = up_taxonomies.get( 0 );
110                 if ( !ForesterUtil.isEmpty( up_tax.getScientificName() ) ) {
111                     getSnTaxCacheMap().put( up_tax.getScientificName(), up_tax );
112                 }
113                 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
114                     getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
115                 }
116                 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
117                     getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
118                 }
119                 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
120                     getIdTaxCacheMap().put( up_tax.getId(), up_tax );
121                 }
122                 return up_tax;
123             }
124             else {
125                 return null;
126             }
127         }
128     }
129
130     synchronized private static List<UniProtTaxonomy> getTaxonomiesFromCommonName( final String query )
131             throws IOException {
132         return UniProtWsTools.getTaxonomiesFromCommonNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
133     }
134
135     synchronized private static List<UniProtTaxonomy> getTaxonomiesFromId( final String query ) throws IOException {
136         return UniProtWsTools.getTaxonomiesFromId( query, MAX_TAXONOMIES_TO_RETURN );
137     }
138
139     synchronized private static List<UniProtTaxonomy> getTaxonomiesFromScientificName( final String query )
140             throws IOException {
141         return UniProtWsTools.getTaxonomiesFromScientificNameStrict( query, MAX_TAXONOMIES_TO_RETURN );
142     }
143
144     synchronized private static List<UniProtTaxonomy> getTaxonomiesFromTaxonomyCode( final String query )
145             throws IOException {
146         return UniProtWsTools.getTaxonomiesFromTaxonomyCode( query, MAX_TAXONOMIES_TO_RETURN );
147     }
148
149     synchronized public static SortedSet<String> inferTaxonomyFromDescendents( final Phylogeny phy ) throws IOException {
150         clearCachesIfTooLarge();
151         final SortedSet<String> not_found = new TreeSet<String>();
152         for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
153             final PhylogenyNode node = iter.next();
154             if ( !node.isExternal() ) {
155                 inferTaxonomyFromDescendents( node, not_found );
156             }
157         }
158         return not_found;
159     }
160
161     synchronized private static void inferTaxonomyFromDescendents( final PhylogenyNode n,
162                                                                    final SortedSet<String> not_found )
163             throws IOException {
164         if ( n.isExternal() ) {
165             throw new IllegalArgumentException( "attempt to infer taxonomy from descendants of external node" );
166         }
167         n.getNodeData().setTaxonomy( null );
168         final List<PhylogenyNode> descs = n.getDescendants();
169         final List<String[]> lineages = new ArrayList<String[]>();
170         int shortest_lin_length = Integer.MAX_VALUE;
171         for( final PhylogenyNode desc : descs ) {
172             if ( desc.getNodeData().isHasTaxonomy()
173                     && ( isHasAppropriateId( desc.getNodeData().getTaxonomy() )
174                             || !ForesterUtil.isEmpty( desc.getNodeData().getTaxonomy().getScientificName() )
175                             || !ForesterUtil.isEmpty( desc.getNodeData().getTaxonomy().getTaxonomyCode() ) || !ForesterUtil
176                             .isEmpty( desc.getNodeData().getTaxonomy().getCommonName() ) ) ) {
177              
178                 final UniProtTaxonomy up_tax = obtainUniProtTaxonomy( desc.getNodeData().getTaxonomy(), null, null );
179                 String[] lineage = null;
180                 if ( up_tax != null ) {
181                     //lineage = obtainLineagePlusOwnScientificName( up_tax );
182                     lineage = up_tax.getLineageAsArray();
183                 }
184                 if ( ( lineage == null ) || ( lineage.length < 1 ) ) {
185                     //TODO remove me
186                     System.out.println( "node " + desc.getNodeData().getTaxonomy().toString() + " has no lineage!" );
187                     not_found.add( desc.getNodeData().getTaxonomy().asText().toString() );
188                     return;
189                 }
190                 if ( lineage.length < shortest_lin_length ) {
191                     shortest_lin_length = lineage.length;
192                 }
193                 lineages.add( lineage );
194             }
195             else {
196                 String msg = "Node(s) with no or inappropriate taxonomic information found";
197                 String node = "";
198                 if ( !ForesterUtil.isEmpty( desc.getName() ) ) {
199                     node = "\"" + desc.getName() + "\"";
200                 }
201                 else {
202                     node = "[" + desc.getId() + "]";
203                 }
204                 msg = "Node " + node + " has no or inappropriate taxonomic information";
205              //   final List<PhylogenyNode> e = desc.getAllExternalDescendants();
206                 //TODO remove me!
207 //                System.out.println();
208 //                int x = 0;
209 //                for( final PhylogenyNode object : e ) {
210 //                    System.out.println( x + ":" );
211 //                    System.out.println( object.getName() + "  " );
212 //                    x++;
213 //                }
214 //                System.out.println();
215                 //
216                 throw new IllegalArgumentException( msg );
217             }
218         }
219         String last_common_lineage = null;
220         if ( shortest_lin_length > 0 ) {
221             I: for( int i = 0; i < shortest_lin_length; ++i ) {
222                 final String lineage_0 = lineages.get( 0 )[ i ];
223                 for( int j = 1; j < lineages.size(); ++j ) {
224                     if ( !lineage_0.equals( lineages.get( j )[ i ] ) ) {
225                         break I;
226                     }
227                 }
228                 last_common_lineage = lineage_0;
229             }
230         }
231         if ( last_common_lineage == null ) {
232             System.out.println( "No common lineage for:" );
233             int counter = 0;
234             for( final String[] strings : lineages ) {
235                 System.out.print( counter + ": " );
236                 ++counter;
237                 for( final String string : strings ) {
238                     System.out.print( string + " " );
239                 }
240                 System.out.println();
241             }
242             return;
243         }
244         final Taxonomy tax = new Taxonomy();
245         n.getNodeData().setTaxonomy( tax );
246         tax.setScientificName( last_common_lineage );
247         final UniProtTaxonomy up_tax = obtainUniProtTaxonomyFromSn( last_common_lineage, lineage );
248         if ( up_tax != null ) {
249             if ( !ForesterUtil.isEmpty( up_tax.getRank() ) ) {
250                 try {
251                     tax.setRank( up_tax.getRank().toLowerCase() );
252                 }
253                 catch ( final PhyloXmlDataFormatException ex ) {
254                     tax.setRank( "" );
255                 }
256             }
257             if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
258                 tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
259             }
260             if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
261                 tax.setCommonName( up_tax.getCommonName() );
262             }
263             if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
264                 tax.getSynonyms().add( up_tax.getSynonym() );
265             }
266             if ( up_tax.getLineage() != null ) {
267                 tax.setLineage( new ArrayList<String>() );
268                 for( final String lin : up_tax.getLineage() ) {
269                     if ( !ForesterUtil.isEmpty( lin ) ) {
270                         tax.getLineage().add( lin );
271                     }
272                 }
273             }
274             
275         }
276         for( final PhylogenyNode desc : descs ) {
277             if ( !desc.isExternal() && desc.getNodeData().isHasTaxonomy()
278                     && desc.getNodeData().getTaxonomy().isEqual( tax ) ) {
279                 desc.getNodeData().setTaxonomy( null );
280             }
281         }
282     }
283
284     synchronized private static boolean isHasAppropriateId( final Taxonomy tax ) {
285         return ( ( tax.getIdentifier() != null ) && ( !ForesterUtil.isEmpty( tax.getIdentifier().getValue() ) && ( tax
286                 .getIdentifier().getProvider().equalsIgnoreCase( "ncbi" )
287                 || tax.getIdentifier().getProvider().equalsIgnoreCase( "uniprot" ) || tax.getIdentifier().getProvider()
288                 .equalsIgnoreCase( "uniprotkb" ) ) ) );
289     }
290
291     synchronized public static SortedSet<String> obtainDetailedTaxonomicInformation( final Phylogeny phy,
292                                                                                      final boolean delete )
293             throws IOException {
294         clearCachesIfTooLarge();
295         final SortedSet<String> not_found = new TreeSet<String>();
296         List<PhylogenyNode> not_found_external_nodes = null;
297         if ( delete ) {
298             not_found_external_nodes = new ArrayList<PhylogenyNode>();
299         }
300         for( final PhylogenyNodeIterator iter = phy.iteratorPostorder(); iter.hasNext(); ) {
301             final PhylogenyNode node = iter.next();
302             final QUERY_TYPE qt = null;
303             Taxonomy tax = null;
304             if ( node.getNodeData().isHasTaxonomy() ) {
305                 tax = node.getNodeData().getTaxonomy();
306             }
307             else if ( node.isExternal() ) {
308                 if ( !ForesterUtil.isEmpty( node.getName() ) ) {
309                     not_found.add( node.getName() );
310                 }
311                 else {
312                     not_found.add( node.toString() );
313                 }
314                 if ( delete ) {
315                     not_found_external_nodes.add( node );
316                 }
317             }
318             UniProtTaxonomy uniprot_tax = null;
319             if ( ( tax != null )
320                     && ( isHasAppropriateId( tax ) || !ForesterUtil.isEmpty( tax.getScientificName() )
321                             || !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) || !ForesterUtil.isEmpty( tax
322                             .getCommonName() ) ) ) {
323                 uniprot_tax = obtainUniProtTaxonomy( tax, null, qt );
324                 if ( uniprot_tax != null ) {
325                     updateTaxonomy( qt, node, tax, uniprot_tax );
326                 }
327                 else {
328                     not_found.add( tax.toString() );
329                     if ( delete && node.isExternal() ) {
330                         not_found_external_nodes.add( node );
331                     }
332                 }
333             }
334         }
335         if ( delete ) {
336             for( final PhylogenyNode node : not_found_external_nodes ) {
337                 phy.deleteSubtree( node, true );
338             }
339             phy.externalNodesHaveChanged();
340             phy.hashIDs();
341             phy.recalculateNumberOfExternalDescendants( true );
342         }
343         return not_found;
344     }
345
346     // TODO this might not be needed anymore
347     //  synchronized private static String[] obtainLineagePlusOwnScientificName( final UniProtTaxonomy up_tax ) {
348     //      final String[] lineage = up_tax.getLineageAsArray();
349     //      final String[] lin_plus_self = new String[ lineage.length + 1 ];
350     //      for( int i = 0; i < lineage.length; ++i ) {
351     //          lin_plus_self[ i ] = lineage[ i ];
352     //      }
353     //      lin_plus_self[ lineage.length ] = up_tax.getScientificName();
354     //      return lin_plus_self;
355     //  }
356     synchronized private static UniProtTaxonomy obtainUniProtTaxonomy( final Taxonomy tax, String query, QUERY_TYPE qt )
357             throws IOException {
358         if ( isHasAppropriateId( tax ) ) {
359             query = tax.getIdentifier().getValue();
360             qt = QUERY_TYPE.ID;
361             System.out.println( "query by id: " + query);
362             return getTaxonomies( getIdTaxCacheMap(), query, qt );
363         }
364         else if ( !ForesterUtil.isEmpty( tax.getScientificName() ) ) {
365             query = tax.getScientificName();
366             qt = QUERY_TYPE.SN;
367             System.out.println( "query by sn: " + query);
368             return getTaxonomies( getSnTaxCacheMap(), query, qt );
369         }
370         else if ( !ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
371             query = tax.getTaxonomyCode();
372             qt = QUERY_TYPE.CODE;
373             return getTaxonomies( getCodeTaxCacheMap(), query, qt );
374         }
375         else {
376             query = tax.getCommonName();
377             qt = QUERY_TYPE.CN;
378             return getTaxonomies( getCnTaxCacheMap(), query, qt );
379         }
380     }
381
382     synchronized private static UniProtTaxonomy obtainUniProtTaxonomyFromSn( final String sn, List<String> lineage ) throws IOException {
383         UniProtTaxonomy up_tax = null;
384         if ( getSnTaxCacheMap().containsKey( sn ) ) {
385             up_tax = getSnTaxCacheMap().get( sn ).copy();
386         }
387         else {
388             final List<UniProtTaxonomy> up_taxonomies = getTaxonomiesFromScientificName( sn );
389             if ( ( up_taxonomies != null ) && ( up_taxonomies.size() == 1 ) ) {
390                 up_tax = up_taxonomies.get( 0 );
391                 getSnTaxCacheMap().put( sn, up_tax );
392                 if ( !ForesterUtil.isEmpty( up_tax.getCode() ) ) {
393                     getCodeTaxCacheMap().put( up_tax.getCode(), up_tax );
394                 }
395                 if ( !ForesterUtil.isEmpty( up_tax.getCommonName() ) ) {
396                     getCnTaxCacheMap().put( up_tax.getCommonName(), up_tax );
397                 }
398                 if ( !ForesterUtil.isEmpty( up_tax.getId() ) ) {
399                     getIdTaxCacheMap().put( up_tax.getId(), up_tax );
400                 }
401                 
402             }
403         }
404         return up_tax;
405     }
406
407     synchronized private static void updateTaxonomy( final QUERY_TYPE qt,
408                                                      final PhylogenyNode node,
409                                                      final Taxonomy tax,
410                                                      final UniProtTaxonomy up_tax ) {
411         if ( ( qt != QUERY_TYPE.SN ) && !ForesterUtil.isEmpty( up_tax.getScientificName() )
412                 && ForesterUtil.isEmpty( tax.getScientificName() ) ) {
413             tax.setScientificName( up_tax.getScientificName() );
414         }
415         //  if ( node.isExternal()
416         if ( ( qt != QUERY_TYPE.CODE ) && !ForesterUtil.isEmpty( up_tax.getCode() )
417                 && ForesterUtil.isEmpty( tax.getTaxonomyCode() ) ) {
418             tax.setTaxonomyCode( up_tax.getCode() );
419         }
420         if ( ( qt != QUERY_TYPE.CN ) && !ForesterUtil.isEmpty( up_tax.getCommonName() )
421                 && ForesterUtil.isEmpty( tax.getCommonName() ) ) {
422             tax.setCommonName( up_tax.getCommonName() );
423         }
424         if ( !ForesterUtil.isEmpty( up_tax.getSynonym() ) && !tax.getSynonyms().contains( up_tax.getSynonym() ) ) {
425             tax.getSynonyms().add( up_tax.getSynonym() );
426         }
427         if ( !ForesterUtil.isEmpty( up_tax.getRank() ) && ForesterUtil.isEmpty( tax.getRank() ) ) {
428             try {
429                 tax.setRank( up_tax.getRank().toLowerCase() );
430             }
431             catch ( final PhyloXmlDataFormatException ex ) {
432                 tax.setRank( "" );
433             }
434         }
435         if ( ( qt != QUERY_TYPE.ID ) && !ForesterUtil.isEmpty( up_tax.getId() ) && ( tax.getIdentifier() == null ) ) {
436             tax.setIdentifier( new Identifier( up_tax.getId(), "uniprot" ) );
437         }
438         if ( up_tax.getLineage() != null ) {
439             tax.setLineage( new ArrayList<String>() );
440             for( final String lin : up_tax.getLineage() ) {
441                 if ( !ForesterUtil.isEmpty( lin ) ) {
442                     tax.getLineage().add( lin );
443                 }
444             }
445         }
446         
447     }
448
449     private enum QUERY_TYPE {
450         CODE, SN, CN, ID;
451     }
452 }