inprogress
[jalview.git] / forester / java / src / org / forester / archaeopteryx / TreePanelUtil.java
1
2 package org.forester.archaeopteryx;
3
4 import java.awt.Color;
5 import java.awt.Component;
6 import java.io.UnsupportedEncodingException;
7 import java.net.URLEncoder;
8 import java.util.ArrayList;
9 import java.util.HashMap;
10 import java.util.HashSet;
11 import java.util.List;
12 import java.util.Map;
13 import java.util.Map.Entry;
14 import java.util.Set;
15 import java.util.SortedMap;
16 import java.util.SortedSet;
17 import java.util.TreeMap;
18
19 import javax.swing.JOptionPane;
20
21 import org.forester.analysis.TaxonomyDataManager;
22 import org.forester.phylogeny.Phylogeny;
23 import org.forester.phylogeny.PhylogenyMethods;
24 import org.forester.phylogeny.PhylogenyNode;
25 import org.forester.phylogeny.data.Annotation;
26 import org.forester.phylogeny.data.BranchColor;
27 import org.forester.phylogeny.data.NodeData.NODE_DATA;
28 import org.forester.phylogeny.data.Sequence;
29 import org.forester.phylogeny.data.Taxonomy;
30 import org.forester.phylogeny.iterators.PhylogenyNodeIterator;
31 import org.forester.phylogeny.iterators.PreorderTreeIterator;
32 import org.forester.util.ForesterConstants;
33 import org.forester.util.ForesterUtil;
34 import org.forester.util.SequenceIdParser;
35 import org.forester.ws.seqdb.UniProtTaxonomy;
36
37 public class TreePanelUtil {
38
39     static int makeSB( final List<String> data, final Options optz, final StringBuilder sb ) {
40         final SortedMap<String, Integer> map = new TreeMap<String, Integer>();
41         if ( ( optz.getExtDescNodeDataToReturn() != NODE_DATA.SEQUENCE_MOL_SEQ )
42                 && ( optz.getExtDescNodeDataToReturn() != NODE_DATA.SEQUENCE_MOL_SEQ_FASTA ) ) {
43             for( final String d : data ) {
44                 if ( !ForesterUtil.isEmpty( d ) ) {
45                     if ( map.containsKey( d ) ) {
46                         map.put( d, map.get( d ) + 1 );
47                     }
48                     else {
49                         map.put( d, 1 );
50                     }
51                 }
52             }
53         }
54         int size = 0;
55         if ( ( optz.getExtDescNodeDataToReturn() != NODE_DATA.SEQUENCE_MOL_SEQ )
56                 && ( optz.getExtDescNodeDataToReturn() != NODE_DATA.SEQUENCE_MOL_SEQ_FASTA ) ) {
57             for( final Entry<String, Integer> e : map.entrySet() ) {
58                 final String v = e.getKey();
59                 final Object c = e.getValue();
60                 sb.append( v );
61                 sb.append( "\t" );
62                 sb.append( c );
63                 sb.append( ForesterUtil.LINE_SEPARATOR );
64             }
65             size = map.size();
66         }
67         else {
68             for( final String d : data ) {
69                 if ( !ForesterUtil.isEmpty( d ) ) {
70                     sb.append( d );
71                     sb.append( ForesterUtil.LINE_SEPARATOR );
72                 }
73             }
74             size = data.size();
75         }
76         return size;
77     }
78
79     public final static String createUriForSeqWeb( final PhylogenyNode node,
80                                                    final Configuration conf,
81                                                    final TreePanel tp ) {
82         String uri_str = null;
83         final String upkb = ForesterUtil.extractUniProtKbProteinSeqIdentifier( node );
84         if ( !ForesterUtil.isEmpty( upkb ) ) {
85             try {
86                 uri_str = ForesterUtil.UNIPROT_KB + URLEncoder.encode( upkb, ForesterConstants.UTF8 );
87             }
88             catch ( final UnsupportedEncodingException e ) {
89                 AptxUtil.showErrorMessage( tp, e.toString() );
90                 e.printStackTrace();
91             }
92         }
93         if ( ForesterUtil.isEmpty( uri_str ) ) {
94             final String v = ForesterUtil.extractGenbankAccessor( node );
95             if ( !ForesterUtil.isEmpty( v ) ) {
96                 try {
97                     if ( SequenceIdParser.isProtein( v ) ) {
98                         uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
99                     }
100                     else {
101                         uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
102                     }
103                 }
104                 catch ( final UnsupportedEncodingException e ) {
105                     AptxUtil.showErrorMessage( tp, e.toString() );
106                     e.printStackTrace();
107                 }
108             }
109         }
110         if ( ForesterUtil.isEmpty( uri_str ) ) {
111             final String v = ForesterUtil.extractRefSeqAccessorAccessor( node );
112             if ( !ForesterUtil.isEmpty( v ) ) {
113                 try {
114                     if ( SequenceIdParser.isProtein( v ) ) {
115                         uri_str = ForesterUtil.NCBI_PROTEIN + URLEncoder.encode( v, ForesterConstants.UTF8 );
116                     }
117                     else {
118                         uri_str = ForesterUtil.NCBI_NUCCORE + URLEncoder.encode( v, ForesterConstants.UTF8 );
119                     }
120                 }
121                 catch ( final UnsupportedEncodingException e ) {
122                     AptxUtil.showErrorMessage( tp, e.toString() );
123                     e.printStackTrace();
124                 }
125             }
126         }
127         if ( ForesterUtil.isEmpty( uri_str ) ) {
128             final String v = ForesterUtil.extractGInumber( node );
129             if ( !ForesterUtil.isEmpty( v ) ) {
130                 try {
131                     uri_str = ForesterUtil.NCBI_GI + URLEncoder.encode( v, ForesterConstants.UTF8 );
132                 }
133                 catch ( final UnsupportedEncodingException e ) {
134                     AptxUtil.showErrorMessage( tp, e.toString() );
135                     e.printStackTrace();
136                 }
137             }
138         }
139         return uri_str;
140     }
141
142     /**
143      * Returns the set of distinct taxonomies of
144      * all external nodes of node.
145      * If at least one the external nodes has no taxonomy,
146      * null is returned.
147      * 
148      */
149     public static Set<Taxonomy> obtainDistinctTaxonomies( final PhylogenyNode node ) {
150         final List<PhylogenyNode> descs = node.getAllExternalDescendants();
151         final Set<Taxonomy> tax_set = new HashSet<Taxonomy>();
152         for( final PhylogenyNode n : descs ) {
153             if ( !n.getNodeData().isHasTaxonomy() || n.getNodeData().getTaxonomy().isEmpty() ) {
154                 return null;
155             }
156             tax_set.add( n.getNodeData().getTaxonomy() );
157         }
158         return tax_set;
159     }
160
161     public final static void showExtDescNodeDataUserSelectedHelper( final ControlPanel cp,
162                                                                     final PhylogenyNode node,
163                                                                     final List<String> data ) {
164         final StringBuilder sb = new StringBuilder();
165         if ( cp.isShowNodeNames() && !ForesterUtil.isEmpty( node.getName() ) ) {
166             TreePanelUtil.showExtDescNodeDataUserSelectedHelperHelper( node.getName(), sb );
167         }
168         if ( cp.isShowGeneNames() && node.getNodeData().isHasSequence()
169                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getName() ) ) {
170             TreePanelUtil.showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getName(), sb );
171         }
172         if ( cp.isShowGeneSymbols() && node.getNodeData().isHasSequence()
173                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getSymbol() ) ) {
174             TreePanelUtil
175                     .showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getSymbol(), sb );
176         }
177         if ( cp.isShowSequenceAcc() && node.getNodeData().isHasSequence()
178                 && ( node.getNodeData().getSequence().getAccession() != null )
179                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getAccession().toString() ) ) {
180             TreePanelUtil.showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence().getAccession()
181                     .toString(), sb );
182         }
183         if ( cp.isShowTaxonomyCode() && node.getNodeData().isHasTaxonomy()
184                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getTaxonomyCode() ) ) {
185             TreePanelUtil.showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy()
186                     .getTaxonomyCode(), sb );
187         }
188         if ( cp.isShowTaxonomyScientificNames() && node.getNodeData().isHasTaxonomy()
189                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getScientificName() ) ) {
190             TreePanelUtil.showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy()
191                     .getScientificName(), sb );
192         }
193         if ( cp.isShowTaxonomyCommonNames() && node.getNodeData().isHasTaxonomy()
194                 && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getCommonName() ) ) {
195             TreePanelUtil
196                     .showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getTaxonomy().getCommonName(), sb );
197         }
198         if ( ( cp.isShowGeneNames() || cp.isShowGeneSymbols() || cp.isShowSequenceAcc() )
199                 && node.getNodeData().isHasSequence()
200                 && !ForesterUtil.isEmpty( node.getNodeData().getSequence().getMolecularSequence() ) ) {
201             TreePanelUtil.showExtDescNodeDataUserSelectedHelperHelper( node.getNodeData().getSequence()
202                     .getMolecularSequence(), sb );
203         }
204         final String s = sb.toString().trim();
205         if ( !ForesterUtil.isEmpty( s ) ) {
206             data.add( s );
207         }
208     }
209
210     public final static void showExtDescNodeDataUserSelectedHelperHelper( final String s, final StringBuilder sb ) {
211         if ( sb.length() > 0 ) {
212             sb.append( "\t" );
213         }
214         sb.append( s );
215     }
216
217     final public static void showInformationMessage( final Component parent, final String title, final String msg ) {
218         JOptionPane.showMessageDialog( parent, msg, title, JOptionPane.INFORMATION_MESSAGE );
219     }
220
221     final static Color calculateColorFromString( final String str, final boolean is_taxonomy ) {
222         final String my_str = str.toUpperCase();
223         char first = my_str.charAt( 0 );
224         char second = ' ';
225         char third = ' ';
226         if ( my_str.length() > 1 ) {
227             if ( is_taxonomy ) {
228                 second = my_str.charAt( 1 );
229             }
230             else {
231                 second = my_str.charAt( my_str.length() - 1 );
232             }
233             if ( is_taxonomy ) {
234                 if ( my_str.length() > 2 ) {
235                     if ( my_str.indexOf( " " ) > 0 ) {
236                         third = my_str.charAt( my_str.indexOf( " " ) + 1 );
237                     }
238                     else {
239                         third = my_str.charAt( 2 );
240                     }
241                 }
242             }
243             else if ( my_str.length() > 2 ) {
244                 third = my_str.charAt( ( my_str.length() - 1 ) / 2 );
245             }
246         }
247         first = TreePanelUtil.normalizeCharForRGB( first );
248         second = TreePanelUtil.normalizeCharForRGB( second );
249         third = TreePanelUtil.normalizeCharForRGB( third );
250         if ( ( first > 235 ) && ( second > 235 ) && ( third > 235 ) ) {
251             first = 0;
252         }
253         else if ( ( first < 60 ) && ( second < 60 ) && ( third < 60 ) ) {
254             second = 255;
255         }
256         return new Color( first, second, third );
257     }
258
259     final static void collapseSpeciesSpecificSubtrees( final Phylogeny phy ) {
260         boolean inferred = false;
261         for( final PhylogenyNodeIterator it = phy.iteratorPreorder(); it.hasNext(); ) {
262             final PhylogenyNode n = it.next();
263             if ( !n.isExternal() && !n.isCollapse() && ( n.getNumberOfDescendants() > 1 ) ) {
264                 final Set<Taxonomy> taxs = TreePanelUtil.obtainDistinctTaxonomies( n );
265                 if ( ( taxs != null ) && ( taxs.size() == 1 ) ) {
266                     TreePanelUtil.collapseSubtree( n, true );
267                     if ( !n.getNodeData().isHasTaxonomy() ) {
268                         n.getNodeData().setTaxonomy( ( Taxonomy ) n.getAllExternalDescendants().get( 0 ).getNodeData()
269                                 .getTaxonomy().copy() );
270                     }
271                     inferred = true;
272                 }
273                 else {
274                     n.setCollapse( false );
275                 }
276             }
277         }
278         if ( inferred ) {
279             phy.setRerootable( false );
280         }
281     }
282
283     final static void collapseSubtree( final PhylogenyNode node, final boolean collapse ) {
284         node.setCollapse( collapse );
285         if ( node.isExternal() ) {
286             return;
287         }
288         final PhylogenyNodeIterator it = new PreorderTreeIterator( node );
289         while ( it.hasNext() ) {
290             it.next().setCollapse( collapse );
291         }
292     }
293
294     static void colorizeSubtree( final PhylogenyNode node, final BranchColor c ) {
295         node.getBranchData().setBranchColor( c );
296         final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( node );
297         for( final PhylogenyNode desc : descs ) {
298             desc.getBranchData().setBranchColor( c );
299         }
300     }
301
302     final static void colorPhylogenyAccordingToConfidenceValues( final Phylogeny tree, final TreePanel tree_panel ) {
303         double max_conf = 0.0;
304         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
305             final PhylogenyNode n = it.next();
306             n.getBranchData().setBranchColor( null );
307             if ( n.getBranchData().isHasConfidences() ) {
308                 final double conf = PhylogenyMethods.getConfidenceValue( n );
309                 if ( conf > max_conf ) {
310                     max_conf = conf;
311                 }
312             }
313         }
314         if ( max_conf > 0.0 ) {
315             final Color bg = tree_panel.getTreeColorSet().getBackgroundColor();
316             final Color br = tree_panel.getTreeColorSet().getBranchColor();
317             for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
318                 final PhylogenyNode n = it.next();
319                 if ( n.getBranchData().isHasConfidences() ) {
320                     final double conf = PhylogenyMethods.getConfidenceValue( n );
321                     final BranchColor c = new BranchColor( ForesterUtil.calcColor( conf, 0.0, max_conf, bg, br ) );
322                     TreePanelUtil.colorizeSubtree( n, c );
323                 }
324             }
325         }
326     }
327
328     final static void colorPhylogenyAccordingToExternalTaxonomy( final Phylogeny tree, final TreePanel tree_panel ) {
329         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
330             it.next().getBranchData().setBranchColor( null );
331         }
332         for( final PhylogenyNodeIterator it = tree.iteratorPreorder(); it.hasNext(); ) {
333             final PhylogenyNode n = it.next();
334             if ( !n.getBranchData().isHasBranchColor() ) {
335                 final Taxonomy tax = PhylogenyMethods.getExternalDescendantsTaxonomy( n );
336                 if ( tax != null ) {
337                     n.getBranchData().setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
338                     final List<PhylogenyNode> descs = PhylogenyMethods.getAllDescendants( n );
339                     for( final PhylogenyNode desc : descs ) {
340                         desc.getBranchData()
341                                 .setBranchColor( new BranchColor( tree_panel.calculateTaxonomyBasedColor( tax ) ) );
342                     }
343                 }
344             }
345         }
346     }
347
348     final static int colorPhylogenyAccordingToRanks( final Phylogeny tree, final String rank, final TreePanel tree_panel ) {
349         final Map<String, Color> true_lineage_to_color_map = new HashMap<String, Color>();
350         int colorizations = 0;
351         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
352             final PhylogenyNode n = it.next();
353             if ( n.getNodeData().isHasTaxonomy()
354                     && ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() )
355                             || !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getCommonName() ) || !ForesterUtil
356                             .isEmpty( n.getNodeData().getTaxonomy().getTaxonomyCode() ) ) ) {
357                 if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getRank() )
358                         && n.getNodeData().getTaxonomy().getRank().equalsIgnoreCase( rank ) ) {
359                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( n.getNodeData()
360                             .getTaxonomy() ) );
361                     TreePanelUtil.colorizeSubtree( n, c );
362                     ++colorizations;
363                     if ( !ForesterUtil.isEmpty( n.getNodeData().getTaxonomy().getScientificName() ) ) {
364                         true_lineage_to_color_map.put( n.getNodeData().getTaxonomy().getScientificName(), c.getValue() );
365                     }
366                 }
367             }
368         }
369         for( final PhylogenyNodeIterator it = tree.iteratorPostorder(); it.hasNext(); ) {
370             final PhylogenyNode node = it.next();
371             if ( ( node.getBranchData().getBranchColor() == null ) && node.getNodeData().isHasTaxonomy()
372                     && !ForesterUtil.isEmpty( node.getNodeData().getTaxonomy().getLineage() ) ) {
373                 boolean success = false;
374                 if ( !true_lineage_to_color_map.isEmpty() ) {
375                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
376                         if ( true_lineage_to_color_map.containsKey( lin ) ) {
377                             TreePanelUtil
378                                     .colorizeSubtree( node, new BranchColor( true_lineage_to_color_map.get( lin ) ) );
379                             ++colorizations;
380                             success = true;
381                             break;
382                         }
383                     }
384                 }
385                 if ( !success ) {
386                     final Map<String, String> lineage_to_rank_map = MainPanel.getLineageToRankMap();
387                     for( final String lin : node.getNodeData().getTaxonomy().getLineage() ) {
388                         final Taxonomy temp_tax = new Taxonomy();
389                         temp_tax.setScientificName( lin );
390                         if ( lineage_to_rank_map.containsKey( lin )
391                                 && !ForesterUtil.isEmpty( lineage_to_rank_map.get( lin ) )
392                                 && lineage_to_rank_map.get( lin ).equalsIgnoreCase( rank ) ) {
393                             final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
394                             TreePanelUtil.colorizeSubtree( node, c );
395                             ++colorizations;
396                             true_lineage_to_color_map.put( lin, c.getValue() );
397                             break;
398                         }
399                         else {
400                             UniProtTaxonomy up = null;
401                             try {
402                                 up = TaxonomyDataManager.obtainUniProtTaxonomy( temp_tax, null, null );
403                             }
404                             catch ( final Exception e ) {
405                                 e.printStackTrace();
406                             }
407                             if ( ( up != null ) && !ForesterUtil.isEmpty( up.getRank() ) ) {
408                                 lineage_to_rank_map.put( lin, up.getRank() );
409                                 if ( up.getRank().equalsIgnoreCase( rank ) ) {
410                                     final BranchColor c = new BranchColor( tree_panel.calculateTaxonomyBasedColor( temp_tax ) );
411                                     TreePanelUtil.colorizeSubtree( node, c );
412                                     ++colorizations;
413                                     true_lineage_to_color_map.put( lin, c.getValue() );
414                                     break;
415                                 }
416                             }
417                         }
418                     }
419                 }
420             }
421         }
422         return colorizations;
423     }
424
425     final static String createAnnotationString( final SortedSet<Annotation> annotations, final boolean show_ref_sources ) {
426         final SortedMap<String, List<Annotation>> m = new TreeMap<String, List<Annotation>>();
427         for( final Annotation an : annotations ) {
428             final String ref_source = ForesterUtil.isEmpty( an.getRefSource() ) ? "?" : an.getRefSource();
429             if ( !m.containsKey( ref_source ) ) {
430                 m.put( ref_source, new ArrayList<Annotation>() );
431             }
432             m.get( ref_source ).add( an );
433         }
434         final StringBuilder sb = new StringBuilder();
435         for( final Entry<String, List<Annotation>> e : m.entrySet() ) {
436             final String ref_source = e.getKey();
437             final List<Annotation> ans = e.getValue();
438             if ( m.size() > 1 ) {
439                 sb.append( "[" );
440             }
441             if ( show_ref_sources && !ref_source.equals( "?" ) ) {
442                 sb.append( ref_source );
443                 sb.append( ": " );
444             }
445             for( int i = 0; i < ans.size(); ++i ) {
446                 final Annotation an = ans.get( i );
447                 if ( !ForesterUtil.isEmpty( an.getRefValue() ) ) {
448                     sb.append( an.getRefValue() );
449                     sb.append( " " );
450                 }
451                 if ( !ForesterUtil.isEmpty( an.getDesc() ) ) {
452                     sb.append( an.getDesc() );
453                 }
454                 if ( sb.charAt( sb.length() - 1 ) == ' ' ) {
455                     sb.deleteCharAt( sb.length() - 1 );
456                 }
457                 if ( i < ans.size() - 1 ) {
458                     sb.append( ", " );
459                 }
460             }
461             if ( m.size() > 1 ) {
462                 sb.append( "] " );
463             }
464         }
465         return sb.toString();
466     }
467
468     final static String getPartAfterColon( final String s ) {
469         final int i = s.indexOf( ':' );
470         if ( ( i < 1 ) || ( i == ( s.length() - 1 ) ) ) {
471             return s;
472         }
473         return s.substring( i + 1, s.length() );
474     }
475
476     final static boolean isHasAssignedEvent( final PhylogenyNode node ) {
477         if ( !node.getNodeData().isHasEvent() ) {
478             return false;
479         }
480         if ( ( node.getNodeData().getEvent() ).isUnassigned() ) {
481             return false;
482         }
483         return true;
484     }
485
486     final static boolean isSequenceEmpty( final Sequence seq ) {
487         return ( seq.getAccession() == null ) && ForesterUtil.isEmpty( seq.getName() )
488                 && ForesterUtil.isEmpty( seq.getSymbol() );
489     }
490
491     final static boolean isTaxonomyEmpty( final Taxonomy tax ) {
492         return ( ( tax.getIdentifier() == null ) && ForesterUtil.isEmpty( tax.getTaxonomyCode() )
493                 && ForesterUtil.isEmpty( tax.getCommonName() ) && ForesterUtil.isEmpty( tax.getScientificName() ) && tax
494                 .getSynonyms().isEmpty() );
495     }
496
497     final static char normalizeCharForRGB( char c ) {
498         c -= 65;
499         c *= 10.2;
500         c = c > 255 ? 255 : c;
501         c = c < 0 ? 0 : c;
502         return c;
503     }
504
505     final static Phylogeny subTree( final PhylogenyNode new_root, final Phylogeny source_phy ) {
506         final Phylogeny new_phy = new Phylogeny();
507         new_phy.setRooted( true );
508         new_phy.setName( source_phy.getName() );
509         new_phy.setDescription( source_phy.getDescription() );
510         new_phy.setType( source_phy.getType() );
511         new_phy.setDistanceUnit( source_phy.getDistanceUnit() );
512         new_phy.setConfidence( source_phy.getConfidence() );
513         new_phy.setIdentifier( source_phy.getIdentifier() );
514         new_phy.setRoot( new_root.copyNodeDataShallow() );
515         int i = 0;
516         for( final PhylogenyNode n : new_root.getDescendants() ) {
517             new_phy.getRoot().setChildNode( i++, n );
518         }
519         return new_phy;
520     }
521 }