pfam seed and full alignment retrieval and nicer ordering of sequence db sources...
[jalview.git] / src / jalview / gui / SequenceFetcher.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer
3  * Copyright (C) 2007 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle
4  *
5  * This program is free software; you can redistribute it and/or
6  * modify it under the terms of the GNU General Public License
7  * as published by the Free Software Foundation; either version 2
8  * of the License, or (at your option) any later version.
9  *
10  * This program is distributed in the hope that it will be useful,
11  * but WITHOUT ANY WARRANTY; without even the implied warranty of
12  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
13  * GNU General Public License for more details.
14  *
15  * You should have received a copy of the GNU General Public License
16  * along with this program; if not, write to the Free Software
17  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA
18  */
19 package jalview.gui;
20
21 import java.io.*;
22 import java.util.*;
23
24 import java.awt.*;
25 import java.awt.event.*;
26
27 import javax.swing.*;
28
29 import MCview.*;
30 import jalview.datamodel.*;
31 import jalview.datamodel.xdb.embl.*;
32 import java.io.File;
33 import jalview.io.*;
34 import jalview.ws.DBRefFetcher;
35 import jalview.ws.ebi.EBIFetchClient;
36 import jalview.ws.seqfetcher.ASequenceFetcher;
37 import jalview.ws.seqfetcher.DbSourceProxy;
38
39 import java.awt.Rectangle;
40 import java.awt.BorderLayout;
41 import java.awt.Dimension;
42
43 public class SequenceFetcher
44 extends JPanel implements Runnable
45 {
46   // ASequenceFetcher sfetch; 
47   JInternalFrame frame;
48   IProgressIndicator guiWindow;
49   AlignFrame alignFrame;
50   StringBuffer result;
51   final String noDbSelected = "-- Select Database --";
52   Hashtable sources = new Hashtable();
53   private static jalview.ws.SequenceFetcher sfetch=null;
54   public SequenceFetcher(IProgressIndicator guiIndic)
55   {
56       final IProgressIndicator guiWindow = guiIndic;
57       final SequenceFetcher us = this;
58       // launch initialiser thread
59       Thread sf = new Thread(new Runnable() {
60
61         public void run()
62         {
63           if (sfetch==null)
64           {
65             /**
66            * give a visual indication that sequence fetcher construction is occuring
67            */
68           if ( guiWindow!=null )
69             {
70               guiWindow.setProgressBar("Initialising Sequence Database Fetchers", this.hashCode());
71             }
72             jalview.ws.SequenceFetcher sf = new jalview.ws.SequenceFetcher();
73             if ( guiWindow!=null )
74             {
75               guiWindow.setProgressBar("Initialising Sequence Database Fetchers", this.hashCode());
76             }
77             sfetch = sf;
78             
79           }
80           us.initGui(guiWindow);
81         }
82       });
83       sf.start();
84   }
85   /**
86    * called by thread spawned by constructor
87    * @param guiWindow
88    */
89   private void initGui(IProgressIndicator guiWindow) {
90     this.guiWindow = guiWindow;
91     if (guiWindow instanceof AlignFrame)
92     {
93       alignFrame = (AlignFrame) guiWindow;
94     }
95       
96     database.addItem(noDbSelected);
97     /*
98      * Dynamically generated database list
99      * will need a translation function from
100      * internal source to externally distinct names.
101      * UNIPROT and UP_NAME are identical DB sources,
102      * and should be collapsed. 
103      */
104      
105     String dbs[] = sfetch.getOrderedSupportedSources();
106     for (int i=0; i<dbs.length;i++)
107     {
108       if (!sources.containsValue(dbs[i]))
109       {  
110         String name = sfetch.getSourceProxy(dbs[i]).getDbName();
111         // duplicate source names are thrown away, here.
112         if (!sources.containsKey(name))
113         {
114           database.addItem(name);
115         }
116         // overwrite with latest version of the retriever for this source
117         sources.put(name, dbs[i]);        
118       }
119     }
120     try
121     {
122       jbInit();
123     }
124     catch (Exception ex)
125     {
126       ex.printStackTrace();
127     }
128
129     frame = new JInternalFrame();
130     frame.setContentPane(this);
131     if (new jalview.util.Platform().isAMac())
132     {
133       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 140);
134     }
135     else
136     {
137       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 125);
138     }
139   }
140
141   private String getFrameTitle()
142   {
143     return ( (alignFrame == null) ? "New " : "Additional ") +
144     "Sequence Fetcher";
145   }
146
147   private void jbInit()
148   throws Exception
149   {
150     this.setLayout(borderLayout2);
151
152     database.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
153     dbeg.setFont(new java.awt.Font("Verdana", Font.BOLD, 11));
154     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
155     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
156     jLabel1.setText(
157     "Separate multiple accession ids with semi colon \";\"");
158     ok.setText("OK");
159     ok.addActionListener(new ActionListener()
160     {
161       public void actionPerformed(ActionEvent e)
162       {
163         ok_actionPerformed();
164       }
165     });
166     clear.setText("Clear");
167     clear.addActionListener(new ActionListener()
168     {
169       public void actionPerformed(ActionEvent e)
170       {
171         clear_actionPerformed();
172       }
173     });
174
175     example.setText("Example");
176     example.addActionListener(new ActionListener()
177     {
178       public void actionPerformed(ActionEvent e)
179       {
180         example_actionPerformed();
181       }
182     });
183     close.setText("Close");
184     close.addActionListener(new ActionListener()
185     {
186       public void actionPerformed(ActionEvent e)
187       {
188         close_actionPerformed(e);
189       }
190     });
191     textArea.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
192     textArea.setLineWrap(true);
193     textArea.addKeyListener(new KeyAdapter()
194     {
195       public void keyPressed(KeyEvent e)
196       {
197         if(e.getKeyCode()==KeyEvent.VK_ENTER)
198           ok_actionPerformed();
199       }
200     });
201     jPanel3.setLayout(borderLayout1);
202     borderLayout1.setVgap(5);
203     jPanel1.add(ok);
204     jPanel1.add(example);
205     jPanel1.add(clear);
206     jPanel1.add(close);
207     jPanel3.add(jPanel2, java.awt.BorderLayout.CENTER);
208     jPanel2.setLayout(borderLayout3);
209     
210     database.addActionListener(new ActionListener() {
211
212       public void actionPerformed(ActionEvent e)
213       {
214         DbSourceProxy db=null;
215         try {
216           db = sfetch.getSourceProxy((String)sources.get(database.getSelectedItem()));
217           dbeg.setText("Example query: "+db.getTestQuery());
218         } catch (Exception ex)
219         {
220           dbeg.setText("");
221         }
222         jPanel2.repaint();
223       }
224     });
225     dbeg.setText("");
226     jPanel2.add(database, java.awt.BorderLayout.NORTH);
227     jPanel2.add(dbeg, java.awt.BorderLayout.CENTER);
228     jPanel2.add(jLabel1, java.awt.BorderLayout.SOUTH);
229     // jPanel2.setPreferredSize(new Dimension())
230     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
231     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
232     this.add(jPanel3, java.awt.BorderLayout.CENTER);
233     this.add(jPanel2,java.awt.BorderLayout.NORTH);
234     jScrollPane1.getViewport().add(textArea);
235     
236
237   }
238   protected void example_actionPerformed()
239   {
240     DbSourceProxy db=null;
241     try {
242       db = sfetch.getSourceProxy((String)sources.get(database.getSelectedItem()));
243       textArea.setText(db.getTestQuery());
244     } catch (Exception ex)
245     {
246     }
247     jPanel3.repaint();
248   }
249
250   protected void clear_actionPerformed()
251   {
252     textArea.setText("");
253     jPanel3.repaint();
254   }
255   JLabel dbeg = new JLabel();
256   JComboBox database = new JComboBox();
257   JLabel jLabel1 = new JLabel();
258   JButton ok = new JButton();
259   JButton clear = new JButton();
260   JButton example = new JButton();
261   JButton close = new JButton();
262   JPanel jPanel1 = new JPanel();
263   JTextArea textArea = new JTextArea();
264   JScrollPane jScrollPane1 = new JScrollPane();
265   JPanel jPanel2 = new JPanel();
266   JPanel jPanel3 = new JPanel();
267   JPanel jPanel4 = new JPanel();
268   
269   BorderLayout borderLayout1 = new BorderLayout();
270   BorderLayout borderLayout2 = new BorderLayout();
271   BorderLayout borderLayout3 = new BorderLayout();
272   public void close_actionPerformed(ActionEvent e)
273   {
274     try
275     {
276       frame.setClosed(true);
277     }
278     catch (Exception ex)
279     {}
280   }
281
282   public void ok_actionPerformed()
283   {
284     database.setEnabled(false);
285     textArea.setEnabled(false);
286     ok.setEnabled(false);
287     close.setEnabled(false);
288
289     Thread worker = new Thread(this);
290     worker.start();
291   }
292
293   private void resetDialog()
294   {
295     database.setEnabled(true);
296     textArea.setEnabled(true);
297     ok.setEnabled(true);
298     close.setEnabled(true);
299   }
300
301   public void run()
302   {
303     String error = "";
304     if (database.getSelectedItem().equals(noDbSelected))
305     {
306       error += "Please select the source database\n";
307     }
308     com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex("\\s+", "");
309     textArea.setText(empty.replaceAll(textArea.getText()));
310     if (textArea.getText().length() == 0)
311     {
312       error += "Please enter a (semi-colon separated list of) database id(s)";
313     }
314     if (error.length() > 0)
315     {
316       showErrorMessage(error);
317       resetDialog();
318       return;
319     }
320     AlignmentI aresult=null;
321     try {
322       guiWindow.setProgressBar("Fetching Sequences from "+database.getSelectedItem(), Thread.currentThread().hashCode());
323       aresult = sfetch.getSourceProxy((String)sources.get(database.getSelectedItem()))
324       .getSequenceRecords(textArea.getText());
325       
326     }
327     catch (Exception e)
328     {
329       showErrorMessage("Error retrieving " + textArea.getText()
330               + " from " + database.getSelectedItem());
331       //error +="Couldn't retrieve sequences from "+database.getSelectedItem();
332       System.err.println("Retrieval failed for source ='"+database.getSelectedItem()+"' and query\n'"+textArea.getText()+"'\n");
333       e.printStackTrace();
334     }
335     catch (OutOfMemoryError e)
336     {
337       showErrorMessage("Out of Memory when retrieving " + textArea.getText()
338               + " from " + database.getSelectedItem()+"\nPlease see the Jalview FAQ for instructions for increasing the memory available to Jalview.\n");
339       e.printStackTrace();
340     }
341     catch (Error e)
342     {
343       showErrorMessage("Serious Error retrieving " + textArea.getText()
344               + " from " + database.getSelectedItem());
345       e.printStackTrace();
346     }
347     guiWindow.setProgressBar(null, Thread.currentThread().hashCode());
348     if (aresult!=null)
349     {
350       parseResult(aresult, null, null);
351     }
352     resetDialog();
353   }
354     /*
355     result = new StringBuffer();
356     if (database.getSelectedItem().equals("Uniprot"))
357     {
358       getUniprotFile(textArea.getText());
359     }
360     else if (database.getSelectedItem().equals("EMBL")
361         || database.getSelectedItem().equals("EMBLCDS"))
362     {
363       String DBRefSource = database.getSelectedItem().equals("EMBLCDS")
364       ? jalview.datamodel.DBRefSource.EMBLCDS
365           : jalview.datamodel.DBRefSource.EMBL;
366
367       StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
368       SequenceI[] seqs = null;
369       while(st.hasMoreTokens())
370       {
371         EBIFetchClient dbFetch = new EBIFetchClient();
372         String qry = database.getSelectedItem().toString().toLowerCase(
373         ) + ":" + st.nextToken();
374         File reply = dbFetch.fetchDataAsFile(
375             qry,
376             "emblxml",null);
377
378         jalview.datamodel.xdb.embl.EmblFile efile=null;
379         if (reply != null && reply.exists())
380         {
381           efile = jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply);
382         }
383         if (efile!=null) {
384           for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) {
385             EmblEntry entry = (EmblEntry) i.next();
386             SequenceI[] seqparts = entry.getSequences(false,true, DBRefSource);
387             if (seqparts!=null) {
388               SequenceI[] newseqs = null;
389               int si=0;
390               if (seqs==null) {
391                 newseqs = new SequenceI[seqparts.length];
392               } else {
393                 newseqs  = new SequenceI[seqs.length+seqparts.length];
394
395                 for (;si<seqs.length; si++) {
396                   newseqs[si] = seqs[si];
397                   seqs[si] = null;
398                 }
399               }
400               for (int j=0;j<seqparts.length; si++, j++) {
401                 newseqs[si] = seqparts[j].deriveSequence(); // place DBReferences on dataset and refer
402               }
403               seqs=newseqs;
404
405             }
406           }
407         } else {
408           result.append("# no response for "+qry);
409         }
410       }
411       if (seqs!=null && seqs.length>0) {
412         if (parseResult(new Alignment(seqs), null, null)!=null)
413         {
414             result.append("# Successfully parsed the "+database.getSelectedItem()+" Queries into an Alignment");
415         }
416       }
417     }
418     else if (database.getSelectedItem().equals("PDB"))
419     {
420       StringTokenizer qset = new StringTokenizer(textArea.getText(), ";");
421       String query;
422       SequenceI[] seqs = null;
423       while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null))
424       {
425         SequenceI[] seqparts = getPDBFile(query.toUpperCase());
426         if (seqparts != null)
427         {
428           if (seqs == null)
429           {
430             seqs = seqparts;
431           }
432           else
433           {
434             SequenceI[] newseqs = new SequenceI[seqs.length+seqparts.length];
435             int i=0;
436             for (; i < seqs.length; i++)
437             {
438               newseqs[i] = seqs[i];
439               seqs[i] = null;
440             }
441             for (int j=0;j<seqparts.length; i++, j++)
442             {
443               newseqs[i] = seqparts[j];
444             }
445             seqs=newseqs;
446           }
447           result.append("# Success for "+query.toUpperCase()+"\n");
448         }
449       }
450       if (seqs != null && seqs.length > 0)
451       {
452         if (parseResult(new Alignment(seqs), null, null)!=null)
453         {
454           result.append(
455           "# Successfully parsed the PDB File Queries into an Alignment");
456         }
457       }
458     }
459     else if( database.getSelectedItem().equals("PFAM"))
460     {
461       try
462       {
463         result.append(new FastaFile(
464             "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc="
465             +  textArea.getText().toUpperCase(), "URL").print()
466         );
467
468         if(result.length()>0)
469         {
470           parseResult( result.toString(), textArea.getText().toUpperCase() );
471         }
472
473       }
474       catch (java.io.IOException ex)
475       {
476         result = null;
477       }
478     }
479
480     if (result == null || result.length() == 0)
481     {
482       showErrorMessage("Error retrieving " + textArea.getText()
483           + " from " + database.getSelectedItem());
484     }
485
486     resetDialog();
487     return;
488   }
489
490   void getUniprotFile(String id)
491   {
492     EBIFetchClient ebi = new EBIFetchClient();
493     File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
494
495     DBRefFetcher dbref = new DBRefFetcher();
496     Vector entries = dbref.getUniprotEntries(file);
497
498     if (entries != null)
499     {
500       //First, make the new sequences
501       Enumeration en = entries.elements();
502       while (en.hasMoreElements())
503       {
504         UniprotEntry entry = (UniprotEntry) en.nextElement();
505
506         StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot");
507         Enumeration en2 = entry.getAccession().elements();
508         while (en2.hasMoreElements())
509         {
510           name.append("|");
511           name.append(en2.nextElement());
512         }
513         en2 = entry.getName().elements();
514         while (en2.hasMoreElements())
515         {
516           name.append("|");
517           name.append(en2.nextElement());
518         }
519
520         if (entry.getProtein() != null)
521         {
522           name.append(" " + entry.getProtein().getName().elementAt(0));
523         }
524
525         result.append(name + "\n" + entry.getUniprotSequence().getContent() +
526         "\n");
527
528       }
529
530       //Then read in the features and apply them to the dataset
531       Alignment al = parseResult(result.toString(), null);
532       for (int i = 0; i < entries.size(); i++)
533       {
534         UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
535         Enumeration e = entry.getDbReference().elements();
536         Vector onlyPdbEntries = new Vector();
537         while (e.hasMoreElements())
538         {
539           PDBEntry pdb = (PDBEntry) e.nextElement();
540           if (!pdb.getType().equals("PDB"))
541           {
542             continue;
543           }
544
545           onlyPdbEntries.addElement(pdb);
546         }
547
548         Enumeration en2 = entry.getAccession().elements();
549         while (en2.hasMoreElements())
550         {
551           al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
552               DBRefSource.UNIPROT,
553               "0",
554               en2.nextElement().toString()));
555         }
556
557
558
559
560         al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries);
561         if (entry.getFeature() != null)
562         {
563           e = entry.getFeature().elements();
564           while (e.hasMoreElements())
565           {
566             SequenceFeature sf = (SequenceFeature) e.nextElement();
567             sf.setFeatureGroup("Uniprot");
568             al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf );
569           }
570         }
571       }
572     }
573   }
574
575   SequenceI[] getPDBFile(String id)
576   {
577     Vector result = new Vector();
578     String chain = null;
579     if (id.indexOf(":") > -1)
580     {
581       chain = id.substring(id.indexOf(":") + 1);
582       id = id.substring(0, id.indexOf(":"));
583     }
584
585     EBIFetchClient ebi = new EBIFetchClient();
586     String file = ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw").
587     getAbsolutePath();
588     if (file == null)
589     {
590       return null;
591     }
592     try
593     {
594       PDBfile pdbfile = new PDBfile(file, jalview.io.AppletFormatAdapter.FILE);
595       for (int i = 0; i < pdbfile.chains.size(); i++)
596       {
597         if (chain == null ||
598             ( (PDBChain) pdbfile.chains.elementAt(i)).id.
599             toUpperCase().equals(chain))
600         {
601           PDBChain pdbchain = (PDBChain) pdbfile.chains.elementAt(i);
602           // Get the Chain's Sequence - who's dataset includes any special features added from the PDB file
603           SequenceI sq = pdbchain.sequence;
604           // Specially formatted name for the PDB chain sequences retrieved from the PDB
605           sq.setName("PDB|"+id+"|"+sq.getName());
606           // Might need to add more metadata to the PDBEntry object
607           // like below
608           /*
609            * PDBEntry entry = new PDBEntry();
610             // Construct the PDBEntry
611             entry.setId(id);
612             if (entry.getProperty() == null)
613                 entry.setProperty(new Hashtable());
614             entry.getProperty().put("chains",
615                         pdbchain.id
616                         + "=" + sq.getStart()
617                         + "-" + sq.getEnd());
618             sq.getDatasetSequence().addPDBId(entry);
619            *
620           // Add PDB DB Refs
621           // We make a DBRefEtntry because we have obtained the PDB file from a verifiable source
622           // JBPNote - PDB DBRefEntry should also carry the chain and mapping information
623           DBRefEntry dbentry = new DBRefEntry(jalview.datamodel.DBRefSource.PDB,
624               "0", id + pdbchain.id);
625           sq.addDBRef(dbentry);
626           // and add seuqence to the retrieved set
627           result.addElement(sq.deriveSequence());
628         }
629       }
630
631       if (result.size() < 1)
632       {
633         throw new Exception("WsDBFetch for PDB id resulted in zero result size");
634       }
635     }
636     catch (Exception ex) // Problem parsing PDB file
637     {
638       jalview.bin.Cache.log.warn("Exception when retrieving " +
639           textArea.getText() + " from " +
640           database.getSelectedItem(), ex);
641       return null;
642     }
643
644
645     SequenceI[] results = new SequenceI[result.size()];
646     for (int i = 0, j = result.size(); i < j; i++)
647     {
648       results[i] = (SequenceI) result.elementAt(i);
649       result.setElementAt(null,i);
650     }
651     return results; 
652   }*/
653   AlignmentI parseResult(String result, String title)
654   {
655     String format = new IdentifyFile().Identify(result, "Paste");
656     Alignment sequences = null;
657     if (FormatAdapter.isValidFormat(format))
658     {
659       sequences = null;
660       try
661       {
662         sequences = new FormatAdapter().readFile(result.toString(), "Paste",
663             format);
664       }
665       catch (Exception ex)
666       {}
667
668       if (sequences!=null)
669       {
670         return parseResult(sequences, title, format);
671       }
672     }
673     else
674     {
675       showErrorMessage("Error retrieving " + textArea.getText()
676           + " from " + database.getSelectedItem());
677     }
678
679     return null;
680   }
681
682   AlignmentI parseResult(AlignmentI al, String title, String currentFileFormat)
683   {
684
685     if (al != null && al.getHeight() > 0)
686     {
687       if (alignFrame == null)
688       {
689         AlignFrame af = new AlignFrame(al,
690             AlignFrame.DEFAULT_WIDTH,
691             AlignFrame.DEFAULT_HEIGHT);
692         if (currentFileFormat!=null)
693         {
694           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT FORMAT FOR NON-FormatAdapter Sourced Alignments?
695         }
696
697         if(title==null)
698         {
699           title = "Retrieved from " + database.getSelectedItem();
700         }
701
702         Desktop.addInternalFrame(af,
703             title,
704             AlignFrame.DEFAULT_WIDTH,
705             AlignFrame.DEFAULT_HEIGHT);
706
707         af.statusBar.setText("Successfully pasted alignment file");
708
709         try
710         {
711           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false));
712         }
713         catch (Exception ex)
714         {}
715       }
716       else
717       {
718         for (int i = 0; i < al.getHeight(); i++)
719         {
720           alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this also creates dataset sequence entries
721         }
722         alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment.
723             getHeight());
724         alignFrame.viewport.alignment.getWidth();
725         alignFrame.viewport.firePropertyChange("alignment", null,
726             alignFrame.viewport.
727             getAlignment().getSequences());
728       }
729     }
730     return al;
731   }
732
733   void showErrorMessage(final String error)
734   {
735     resetDialog();
736     javax.swing.SwingUtilities.invokeLater(new Runnable()
737     {
738       public void run()
739       {
740         JOptionPane.showInternalMessageDialog(Desktop.desktop,
741             error, "Error Retrieving Data",
742             JOptionPane.WARNING_MESSAGE);
743       }
744     });
745   }
746 }
747