Merge branch 'test_paolo_JAL-1065' into Tcoffee_JAL-1065
authorjprocter <jprocter@compbio.dundee.ac.uk>
Fri, 4 May 2012 16:08:21 +0000 (17:08 +0100)
committerjprocter <jprocter@compbio.dundee.ac.uk>
Fri, 4 May 2012 16:08:21 +0000 (17:08 +0100)
Conflicts:
src/jalview/appletgui/AlignFrame.java
src/jalview/gui/AlignFrame.java
updated handler methods for creating colourscheme for new 'jalviewish' approach to storing tcoffee scores.

1  2 
src/jalview/appletgui/AlignFrame.java
src/jalview/gui/AlignFrame.java
src/jalview/io/TCoffeeScoreFile.java

@@@ -100,7 -100,6 +100,6 @@@ public class AlignFrame extends Embmenu
  \r
    String jalviewServletURL;\r
    \r
-   TCoffeeScoreFile tcoffeeScoreFile;\r
  \r
    public AlignFrame(AlignmentI al, jalview.bin.JalviewLite applet, String title, boolean embedded)\r
    {\r
        changeColour(new Blosum62ColourScheme());\r
      }\r
      else if (source == tcoffeeColour) {\r
-         changeColour(new TCoffeeColourScheme(tcoffeeScoreFile));\r
+         changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));\r
      }\r
      else if (source == annotationColour)\r
      {\r
          {\r
            try\r
            {\r
 -            sg.cs = (ColourSchemeI) cs.getClass().newInstance();\r
 +            sg.cs = cs.getClass().newInstance();\r
            } catch (Exception ex)\r
            {\r
              ex.printStackTrace();\r
          \r
          TCoffeeScoreFile file = TCoffeeScoreFile.load( new InputStreamReader( url.openStream() ) );\r
          if( file == null ) {\r
++       // TODO: raise a dialog box here rather than bomb out.\r
++            \r
                  throw new RuntimeException("The file provided does not match the T-Coffee scores file format");\r
          }\r
 -        // TODO add parameter to indicate if matching should be done\r
 +        \r
 +        /*\r
 +         * check that the score matrix matches the alignment dimensions\r
 +         */\r
 +        AlignmentI aln; \r
 +        if( (aln=viewport.alignment) != null && (aln.getHeight() != file.getHeight() || aln.getWidth() != file.getWidth()) ) {\r
-                 throw new RuntimeException("The scores matrix does not match the alignment dimensions");\r
++          // TODO: raise a dialog box here rather than bomb out.\r
++          throw new RuntimeException("The scores matrix does not match the alignment dimensions");\r
++                \r
 +        }\r
 +        \r
-         tcoffeeColour.setEnabled(true);\r
-         tcoffeeScoreFile = file;\r
-         \r
-         // switch to this color\r
-         changeColour(new TCoffeeColourScheme(tcoffeeScoreFile));\r
++         // TODO add parameter to indicate if matching should be done\r
+         if (file.annotateAlignment(alignPanel.getAlignment(), false))\r
+         {\r
+                 tcoffeeColour.setEnabled(true);\r
+                 // switch to this color\r
+                 changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));\r
+           }\r
 -\r
    }\r
    \r
    \r
@@@ -143,8 -143,6 +143,6 @@@ public class AlignFrame extends GAlignF
  
    Vector alignPanels = new Vector();
    
-   TCoffeeScoreFile tcoffeeScoreFile;
    /**
     * Last format used to load or save alignments in this window
     */
        }
        FormatAdapter f = new FormatAdapter();
        String output = f.formatSequences(format,
 -              (Alignment) viewport.alignment, // class cast exceptions will
 +              viewport.alignment, // class cast exceptions will
                // occur in the distant future
                omitHidden, f.getCacheSuffixDefault(format), viewport.colSel);
  
          {
            try
            {
 -            sg.cs = (ColourSchemeI) cs.getClass().newInstance();
 +            sg.cs = cs.getClass().newInstance();
            } catch (Exception ex)
            {
            }
              try 
              {
                  TCoffeeScoreFile result = TCoffeeScoreFile.load(new File(sFilePath));
 -                if( result == null ) { throw new RuntimeException("The file provided does not match the T-Coffee scores file format"); }
 -
 -                // TODO check that the loaded scores matches the current MSA 'dimension'
 +                if( result == null ) { 
++                     // TODO: raise a dialog box here rather than bomb out.
++                
 +                        throw new RuntimeException("The file provided does not match the T-Coffee scores file format"); 
 +                }
 +
 +                /*
 +                 * check that the score matrix matches the alignment dimensions
 +                 */
 +                AlignmentI aln; 
 +                if( (aln=viewport.alignment) != null && (aln.getHeight() != result.getHeight() || aln.getWidth() != result.getWidth()) ) {
-                         throw new RuntimeException("The scores matrix does not match the alignment dimensions");
++                    // TODO: raise a dialog box here rather than bomb out.
++                  throw new RuntimeException("The scores matrix does not match the alignment dimensions");
 +                }
-                 changeColour( new TCoffeeColourScheme(result) );
-                 tcoffeeScoreFile = result;
-                 tcoffeeColour.setEnabled(true);
-                 tcoffeeColour.setSelected(true);
-                 
+                 if (result.annotateAlignment(alignPanel.getAlignment(), true))
+                 {
+                         tcoffeeColour.setEnabled(true);
+                         tcoffeeColour.setSelected(true);
+                         // switch to this color
+                         changeColour(new TCoffeeColourScheme(alignPanel.getAlignment()));
+                 } else {
+                   tcoffeeColour.setEnabled(false);
+                   tcoffeeColour.setSelected(false);
+                 }
              } 
              catch (Exception ex) {
                JOptionPane.showMessageDialog(
    
    @Override
    protected void tcoffeeColorScheme_actionPerformed(ActionEvent e) {
-         if( tcoffeeScoreFile != null ) {
-         changeColour( new TCoffeeColourScheme(tcoffeeScoreFile) );
-         }
+         changeColour( new TCoffeeColourScheme(alignPanel.getAlignment()) );
    }
    
  //  /**
@@@ -1,5 -1,12 +1,12 @@@
  package jalview.io;
  
+ import jalview.analysis.SequenceIdMatcher;
+ import jalview.datamodel.AlignmentAnnotation;
+ import jalview.datamodel.AlignmentI;
+ import jalview.datamodel.Annotation;
+ import jalview.datamodel.SequenceI;
+ import java.awt.Color;
  import java.io.BufferedReader;
  import java.io.File;
  import java.io.FileNotFoundException;
@@@ -75,8 -82,7 +82,8 @@@ public class TCoffeeScoreFile 
         * insertion order. 
         */
        LinkedHashMap<String,StringBuilder> scores = new LinkedHashMap<String,StringBuilder>();
 -      
 +
 +      Integer fWidth;
  
        /**
         * Parse the specified file.
        }
                
        /**
 +       * @return The 'height' of the score matrix i.e. the numbers of score rows that should matches 
 +       * the number of sequences in the alignment
 +       */
 +      public int getHeight() {
 +              // the last entry will always be the 'global' alingment consensus scores, so it is removed 
 +              // from the 'height' count to make this value compatible with the number of sequences in the MSA
 +              return scores != null && scores.size() > 0 ? scores.size()-1 : 0;
 +      }
 +      
 +      /**
 +       * @return The 'width' of the score matrix i.e. the number of columns. 
 +       * Since teh score value are supposd to be calculated for an 'aligned' MSA, all the entries 
 +       * have to have the same width.  
 +       */
 +      public int getWidth() {
 +              return fWidth != null ? fWidth : 0;
 +      }
 +      
 +      /**
         * The default constructor is marked as {@code protected} since this class is meant to created 
         * through the {@link #load(File)} or {@link #load(Reader)} factory methods
         */
                        for( Map.Entry<String,String> entry : block.items.entrySet() ) {
                                StringBuilder scoreStringBuilder = scores.get(entry.getKey());
                                if( scoreStringBuilder == null ) {
 -                                      throw new RuntimeException(String.format("Invalid T-Coffee score file. Sequence ID '%s' is not declared in header section", entry.getKey()));
 +                                      throw new RuntimeException(String.format("Invalid T-Coffee score file: Sequence ID '%s' is not declared in header section", entry.getKey()));
                                }
                                
                                scoreStringBuilder.append( entry.getValue() );
                        }
 -                      
                }
                
 +              /*
 +               * verify that all rows have the same width
 +               */
 +              for( StringBuilder str : scores.values() ) {
 +                      if( fWidth == null ) {
 +                              fWidth = str.length();
 +                      }
 +                      else if( fWidth != str.length() ) {
 +                              throw new RuntimeException("Invalid T-Coffee score file: All the score sequences must have the same length");
 +                      }
 +              }
 +              
 +              
 +              
        }
  
  
                        return items.get("cons");
                }
        }
-       
-       
+       /**
+        * TCOFFEE score colourscheme
+        */
+       static final Color[] colors = {
+                       new Color( 102, 102, 255 ),     // #6666FF
+                       new Color( 0, 255, 0),          // #00FF00
+                       new Color( 102, 255, 0),        // #66FF00
+                       new Color( 204, 255, 0),        // #CCFF00
+                       new Color( 255, 255, 0),        // #FFFF00
+                       new Color( 255, 204, 0),        // #FFCC00
+                       new Color( 255, 153, 0),        // #FF9900
+                       new Color( 255, 102, 0),        // #FF6600
+                       new Color( 255, 51, 0),         // #FF3300
+                       new Color( 255, 34, 0)          // #FF2000
+               };
+       public final static String TCOFFEE_SCORE="TCoffeeScore";
+       /**
+        * generate annotation for this TCoffee score set on the given alignment
+        * @param al alignment to annotate
+        * @param matchids if true, annotate sequences based on matching sequence names
+        * @return true if alignment annotation was modified, false otherwise.
+        */
+       public boolean annotateAlignment(AlignmentI al, boolean matchids)
+       {
+         boolean added=false;
+         int i=0;
+         SequenceIdMatcher sidmatcher = new SequenceIdMatcher(al.getSequencesArray());
+         byte[][] scoreMatrix=getScoresArray();
+         // for 2.8 - we locate any existing TCoffee annotation and remove it first before adding this.
+         for (Map.Entry<String,StringBuilder> id:scores.entrySet())
+         {
+           byte[] srow=scoreMatrix[i];
+           SequenceI s;
+           if (matchids)
+           {
+             s=sidmatcher.findIdMatch(id.getKey());
+           } else {
+             s=al.getSequenceAt(i);
+           }
+           i++;
+             if (s==null && i!=scores.size() && !id.getKey().equals("cons"))
+             {
+               System.err.println("No "+(matchids ? "match ":" sequences left ")+" for TCoffee score set : "+id.getKey());
+               continue;
+             }
+             int jSize=al.getWidth()< srow.length ? al.getWidth() : srow.length;
+           Annotation[] annotations=new Annotation[al.getWidth()];
+           for (int j=0;j<jSize;j++) {
+             byte val = srow[j];
+             annotations[j]=new Annotation(s==null ? ""+val:null,s==null ? ""+val:null,(char) val,val*1f,val >= 0 && val < colors.length ? colors[val] : Color.white);
+           }
+           AlignmentAnnotation aa=null;
+           if (s!=null)
+           {
+             // TODO - set per sequence score
+             aa=new AlignmentAnnotation(TCOFFEE_SCORE, "Score for "+id.getKey(), annotations);
+             
+             aa.setSequenceRef(s);
+             aa.visible=false;
+             aa.belowAlignment=false;
+           } else {
+             aa=new AlignmentAnnotation("T-COFFEE", "TCoffee column reliability score", annotations);
+               aa.belowAlignment=true;
+             aa.visible=true;
+             
+           }
+           al.addAnnotation(aa);
+           added=true;
+         }
+         return added;
+       }
+         
  
  }