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