pickmanager on sequence and alignment position, vamsas pick broadcast and refactor...
[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 import javax.swing.*;
27
28 import MCview.*;
29 import jalview.datamodel.*;
30 import jalview.datamodel.xdb.embl.*;
31 import java.io.File;
32 import jalview.io.*;
33 import jalview.ws.DBRefFetcher;
34 import jalview.ws.EBIFetchClient;
35
36 import java.awt.Rectangle;
37 import java.awt.BorderLayout;
38 import java.awt.Dimension;
39
40 public class SequenceFetcher
41 extends JPanel implements Runnable
42 {
43   jalview.ws.SequenceFetcher sfetch; 
44   JInternalFrame frame;
45   AlignFrame alignFrame;
46   StringBuffer result;
47   final String noDbSelected = "-- Select Database --";
48   public SequenceFetcher(AlignFrame af)
49   {
50     alignFrame = af;
51     sfetch = new jalview.ws.SequenceFetcher();
52     database.addItem(noDbSelected);
53     /*
54      * Dynamically generated database list
55      * will need a translation function from
56      * internal source to externally distinct names.
57      * UNIPROT and UP_NAME are identical DB sources,
58      * and should be collapsed. 
59      *
60      
61      String dbs[] = sfetch.getSupportedDb();
62     for (int i=0; i<dbs.length;i++)
63     {
64       if (DBRefSource.isPrimaryDb(dbs[i]))
65       {  
66         database.addItem(dbs[i]);
67         // should have some kind of human readable description of each database displayed when
68          * that combo is selected.
69       }
70     }*/
71     database.addItem("Uniprot");
72     database.addItem("EMBL");
73     database.addItem("EMBLCDS");
74     database.addItem("PDB");
75     database.addItem("PFAM");
76
77     try
78     {
79       jbInit();
80     }
81     catch (Exception ex)
82     {
83       ex.printStackTrace();
84     }
85
86     frame = new JInternalFrame();
87     frame.setContentPane(this);
88     if (System.getProperty("os.name").startsWith("Mac"))
89     {
90       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 140);
91     }
92     else
93     {
94       Desktop.addInternalFrame(frame, getFrameTitle(), 400, 125);
95     }
96   }
97
98   private String getFrameTitle()
99   {
100     return ( (alignFrame == null) ? "New " : "Additional ") +
101     "Sequence Fetcher";
102   }
103
104   private void jbInit()
105   throws Exception
106   {
107     this.setLayout(borderLayout2);
108
109     database.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
110     jLabel1.setFont(new java.awt.Font("Verdana", Font.ITALIC, 11));
111     jLabel1.setHorizontalAlignment(SwingConstants.CENTER);
112     jLabel1.setText(
113     "Separate multiple accession ids with semi colon \";\"");
114     ok.setText("OK");
115     ok.addActionListener(new ActionListener()
116     {
117       public void actionPerformed(ActionEvent e)
118       {
119         ok_actionPerformed();
120       }
121     });
122     close.setText("Close");
123     close.addActionListener(new ActionListener()
124     {
125       public void actionPerformed(ActionEvent e)
126       {
127         close_actionPerformed(e);
128       }
129     });
130     textArea.setFont(new java.awt.Font("Verdana", Font.PLAIN, 11));
131     textArea.setLineWrap(true);
132     textArea.addKeyListener(new KeyAdapter()
133     {
134       public void keyPressed(KeyEvent e)
135       {
136         if(e.getKeyCode()==KeyEvent.VK_ENTER)
137           ok_actionPerformed();
138       }
139     });
140     jPanel3.setLayout(borderLayout1);
141     borderLayout1.setVgap(5);
142     jPanel1.add(ok);
143     jPanel1.add(close);
144     jPanel3.add(jPanel2, java.awt.BorderLayout.WEST);
145     jPanel2.add(database);
146     jPanel3.add(jScrollPane1, java.awt.BorderLayout.CENTER);
147     jPanel3.add(jLabel1, java.awt.BorderLayout.NORTH);
148     this.add(jPanel1, java.awt.BorderLayout.SOUTH);
149     this.add(jPanel3, java.awt.BorderLayout.CENTER);
150     jScrollPane1.getViewport().add(textArea);
151
152   }
153
154   JComboBox database = new JComboBox();
155   JLabel jLabel1 = new JLabel();
156   JButton ok = new JButton();
157   JButton close = new JButton();
158   JPanel jPanel1 = new JPanel();
159   JTextArea textArea = new JTextArea();
160   JScrollPane jScrollPane1 = new JScrollPane();
161   JPanel jPanel2 = new JPanel();
162   JPanel jPanel3 = new JPanel();
163   BorderLayout borderLayout1 = new BorderLayout();
164   BorderLayout borderLayout2 = new BorderLayout();
165   public void close_actionPerformed(ActionEvent e)
166   {
167     try
168     {
169       frame.setClosed(true);
170     }
171     catch (Exception ex)
172     {}
173   }
174
175   public void ok_actionPerformed()
176   {
177     database.setEnabled(false);
178     textArea.setEnabled(false);
179     ok.setEnabled(false);
180     close.setEnabled(false);
181
182     Thread worker = new Thread(this);
183     worker.start();
184   }
185
186   private void resetDialog()
187   {
188     database.setEnabled(true);
189     textArea.setEnabled(true);
190     ok.setEnabled(true);
191     close.setEnabled(true);
192   }
193
194   public void run()
195   {
196     String error = "";
197     if (database.getSelectedItem().equals(noDbSelected))
198     {
199       error += "Please select the source database\n";
200     }
201     com.stevesoft.pat.Regex empty = new com.stevesoft.pat.Regex("\\s+", "");
202     textArea.setText(empty.replaceAll(textArea.getText()));
203     if (textArea.getText().length() == 0)
204     {
205       error += "Please enter a (semi-colon separated list of) database id(s)";
206     }
207     if (error.length() > 0)
208     {
209       showErrorMessage(error);
210       resetDialog();
211       return;
212     }
213
214     result = new StringBuffer();
215     if (database.getSelectedItem().equals("Uniprot"))
216     {
217       getUniprotFile(textArea.getText());
218     }
219     else if (database.getSelectedItem().equals("EMBL")
220         || database.getSelectedItem().equals("EMBLCDS"))
221     {
222       String DBRefSource = database.getSelectedItem().equals("EMBLCDS")
223       ? jalview.datamodel.DBRefSource.EMBLCDS
224           : jalview.datamodel.DBRefSource.EMBL;
225
226       StringTokenizer st = new StringTokenizer(textArea.getText(), ";");
227       SequenceI[] seqs = null;
228       while(st.hasMoreTokens())
229       {
230         EBIFetchClient dbFetch = new EBIFetchClient();
231
232         File reply = dbFetch.fetchDataAsFile(
233             database.getSelectedItem().toString().toLowerCase(
234             ) + ":" + st.nextToken(),
235             "emblxml",null);
236
237         jalview.datamodel.xdb.embl.EmblFile efile=null;
238         if (reply != null && reply.exists())
239         {
240           efile = jalview.datamodel.xdb.embl.EmblFile.getEmblFile(reply);
241         }
242         if (efile!=null) {
243           for (Iterator i=efile.getEntries().iterator(); i.hasNext(); ) {
244             EmblEntry entry = (EmblEntry) i.next();
245             SequenceI[] seqparts = entry.getSequences(false,true, DBRefSource);
246             if (seqparts!=null) {
247               SequenceI[] newseqs = null;
248               int si=0;
249               if (seqs==null) {
250                 newseqs = new SequenceI[seqparts.length];
251               } else {
252                 newseqs  = new SequenceI[seqs.length+seqparts.length];
253
254                 for (;si<seqs.length; si++) {
255                   newseqs[si] = seqs[si];
256                   seqs[si] = null;
257                 }
258               }
259               for (int j=0;j<seqparts.length; si++, j++) {
260                 newseqs[si] = seqparts[j].deriveSequence(); // place DBReferences on dataset and refer
261               }
262               seqs=newseqs;
263
264             }
265           }
266         } else {
267           result=null;
268         }
269       }
270       if (seqs!=null && seqs.length>0) {
271         if (parseResult(new Alignment(seqs), null, null)!=null)
272           result.append("# Successfully parsed the "+database.getSelectedItem()+" Queries into an Alignment");
273       }
274     }
275     else if (database.getSelectedItem().equals("PDB"))
276     {
277       StringTokenizer qset = new StringTokenizer(textArea.getText(), ";");
278       String query;
279       SequenceI[] seqs = null;
280       while (qset.hasMoreTokens() && ((query = qset.nextToken())!=null))
281       {
282         SequenceI[] seqparts = getPDBFile(query.toUpperCase());
283         if (seqparts != null)
284         {
285           if (seqs == null)
286           {
287             seqs = seqparts;
288           }
289           else
290           {
291             SequenceI[] newseqs = new SequenceI[seqs.length+seqparts.length];
292             int i=0;
293             for (; i < seqs.length; i++)
294             {
295               newseqs[i] = seqs[i];
296               seqs[i] = null;
297             }
298             for (int j=0;j<seqparts.length; i++, j++)
299             {
300               newseqs[i] = seqparts[j];
301             }
302             seqs=newseqs;
303           }
304           result.append("# Success for "+query.toUpperCase()+"\n");
305         }
306       }
307       if (seqs != null && seqs.length > 0)
308       {
309         if (parseResult(new Alignment(seqs), null, null)!=null)
310         {
311           result.append(
312           "# Successfully parsed the PDB File Queries into an Alignment");
313         }
314       }
315     }
316     else if( database.getSelectedItem().equals("PFAM"))
317     {
318       try
319       {
320         result.append(new FastaFile(
321             "http://www.sanger.ac.uk/cgi-bin/Pfam/getalignment.pl?format=fal&acc="
322             +  textArea.getText().toUpperCase(), "URL").print()
323         );
324
325         if(result.length()>0)
326         {
327           parseResult( result.toString(), textArea.getText().toUpperCase() );
328         }
329
330       }
331       catch (java.io.IOException ex)
332       {
333         result = null;
334       }
335     }
336
337     if (result == null || result.length() == 0)
338     {
339       showErrorMessage("Error retrieving " + textArea.getText()
340           + " from " + database.getSelectedItem());
341     }
342
343     resetDialog();
344     return;
345   }
346
347   void getUniprotFile(String id)
348   {
349     EBIFetchClient ebi = new EBIFetchClient();
350     File file = ebi.fetchDataAsFile("uniprot:" + id, "xml", null);
351
352     DBRefFetcher dbref = new DBRefFetcher();
353     Vector entries = dbref.getUniprotEntries(file);
354
355     if (entries != null)
356     {
357       //First, make the new sequences
358       Enumeration en = entries.elements();
359       while (en.hasMoreElements())
360       {
361         UniprotEntry entry = (UniprotEntry) en.nextElement();
362
363         StringBuffer name = new StringBuffer(">UniProt/Swiss-Prot");
364         Enumeration en2 = entry.getAccession().elements();
365         while (en2.hasMoreElements())
366         {
367           name.append("|");
368           name.append(en2.nextElement());
369         }
370         en2 = entry.getName().elements();
371         while (en2.hasMoreElements())
372         {
373           name.append("|");
374           name.append(en2.nextElement());
375         }
376
377         if (entry.getProtein() != null)
378         {
379           name.append(" " + entry.getProtein().getName().elementAt(0));
380         }
381
382         result.append(name + "\n" + entry.getUniprotSequence().getContent() +
383         "\n");
384
385       }
386
387       //Then read in the features and apply them to the dataset
388       Alignment al = parseResult(result.toString(), null);
389       for (int i = 0; i < entries.size(); i++)
390       {
391         UniprotEntry entry = (UniprotEntry) entries.elementAt(i);
392         Enumeration e = entry.getDbReference().elements();
393         Vector onlyPdbEntries = new Vector();
394         while (e.hasMoreElements())
395         {
396           PDBEntry pdb = (PDBEntry) e.nextElement();
397           if (!pdb.getType().equals("PDB"))
398           {
399             continue;
400           }
401
402           onlyPdbEntries.addElement(pdb);
403         }
404
405         Enumeration en2 = entry.getAccession().elements();
406         while (en2.hasMoreElements())
407         {
408           al.getSequenceAt(i).getDatasetSequence().addDBRef(new DBRefEntry(
409               DBRefSource.UNIPROT,
410               "0",
411               en2.nextElement().toString()));
412         }
413
414
415
416
417         al.getSequenceAt(i).getDatasetSequence().setPDBId(onlyPdbEntries);
418         if (entry.getFeature() != null)
419         {
420           e = entry.getFeature().elements();
421           while (e.hasMoreElements())
422           {
423             SequenceFeature sf = (SequenceFeature) e.nextElement();
424             sf.setFeatureGroup("Uniprot");
425             al.getSequenceAt(i).getDatasetSequence().addSequenceFeature( sf );
426           }
427         }
428       }
429     }
430   }
431
432   SequenceI[] getPDBFile(String id)
433   {
434     Vector result = new Vector();
435     String chain = null;
436     if (id.indexOf(":") > -1)
437     {
438       chain = id.substring(id.indexOf(":") + 1);
439       id = id.substring(0, id.indexOf(":"));
440     }
441
442     EBIFetchClient ebi = new EBIFetchClient();
443     String file = ebi.fetchDataAsFile("pdb:" + id, "pdb", "raw").
444     getAbsolutePath();
445     if (file == null)
446     {
447       return null;
448     }
449     try
450     {
451       PDBfile pdbfile = new PDBfile(file, jalview.io.AppletFormatAdapter.FILE);
452       for (int i = 0; i < pdbfile.chains.size(); i++)
453       {
454         if (chain == null ||
455             ( (PDBChain) pdbfile.chains.elementAt(i)).id.
456             toUpperCase().equals(chain))
457         {
458           PDBChain pdbchain = (PDBChain) pdbfile.chains.elementAt(i);
459           // Get the Chain's Sequence - who's dataset includes any special features added from the PDB file
460           SequenceI sq = pdbchain.sequence;
461           // Specially formatted name for the PDB chain sequences retrieved from the PDB
462           sq.setName("PDB|"+id+"|"+sq.getName());
463           // Might need to add more metadata to the PDBEntry object
464           // like below
465           /*
466            * PDBEntry entry = new PDBEntry();
467             // Construct the PDBEntry
468             entry.setId(id);
469             if (entry.getProperty() == null)
470                 entry.setProperty(new Hashtable());
471             entry.getProperty().put("chains",
472                         pdbchain.id
473                         + "=" + sq.getStart()
474                         + "-" + sq.getEnd());
475             sq.getDatasetSequence().addPDBId(entry);
476            */
477           // Add PDB DB Refs
478           // We make a DBRefEtntry because we have obtained the PDB file from a verifiable source
479           // JBPNote - PDB DBRefEntry should also carry the chain and mapping information
480           DBRefEntry dbentry = new DBRefEntry(jalview.datamodel.DBRefSource.PDB,
481               "0", id + pdbchain.id);
482           sq.addDBRef(dbentry);
483           // and add seuqence to the retrieved set
484           result.addElement(sq.deriveSequence());
485         }
486       }
487
488       if (result.size() < 1)
489       {
490         throw new Exception("WsDBFetch for PDB id resulted in zero result size");
491       }
492     }
493     catch (Exception ex) // Problem parsing PDB file
494     {
495       jalview.bin.Cache.log.warn("Exception when retrieving " +
496           textArea.getText() + " from " +
497           database.getSelectedItem(), ex);
498       return null;
499     }
500
501
502     SequenceI[] results = new SequenceI[result.size()];
503     for (int i = 0, j = result.size(); i < j; i++)
504     {
505       results[i] = (SequenceI) result.elementAt(i);
506       result.setElementAt(null,i);
507     }
508     return results;
509   }
510   Alignment parseResult(String result, String title)
511   {
512     String format = new IdentifyFile().Identify(result, "Paste");
513     Alignment sequences = null;
514     if (FormatAdapter.isValidFormat(format))
515     {
516       sequences = null;
517       try
518       {
519         sequences = new FormatAdapter().readFile(result.toString(), "Paste",
520             format);
521       }
522       catch (Exception ex)
523       {}
524
525       if (sequences!=null)
526       {
527         return parseResult(sequences, title, format);
528       }
529     }
530     else
531     {
532       showErrorMessage("Error retrieving " + textArea.getText()
533           + " from " + database.getSelectedItem());
534     }
535
536     return null;
537   }
538
539   Alignment parseResult(Alignment al, String title, String currentFileFormat)
540   {
541
542     if (al != null && al.getHeight() > 0)
543     {
544       if (alignFrame == null)
545       {
546         AlignFrame af = new AlignFrame(al,
547             AlignFrame.DEFAULT_WIDTH,
548             AlignFrame.DEFAULT_HEIGHT);
549         if (currentFileFormat!=null)
550         {
551           af.currentFileFormat = currentFileFormat; // WHAT IS THE DEFAULT FORMAT FOR NON-FormatAdapter Sourced Alignments?
552         }
553
554         if(title==null)
555         {
556           title = "Retrieved from " + database.getSelectedItem();
557         }
558
559         Desktop.addInternalFrame(af,
560             title,
561             AlignFrame.DEFAULT_WIDTH,
562             AlignFrame.DEFAULT_HEIGHT);
563
564         af.statusBar.setText("Successfully pasted alignment file");
565
566         try
567         {
568           af.setMaximum(jalview.bin.Cache.getDefault("SHOW_FULLSCREEN", false));
569         }
570         catch (Exception ex)
571         {}
572       }
573       else
574       {
575         for (int i = 0; i < al.getHeight(); i++)
576         {
577           alignFrame.viewport.alignment.addSequence(al.getSequenceAt(i)); // this also creates dataset sequence entries
578         }
579         alignFrame.viewport.setEndSeq(alignFrame.viewport.alignment.
580             getHeight());
581         alignFrame.viewport.alignment.getWidth();
582         alignFrame.viewport.firePropertyChange("alignment", null,
583             alignFrame.viewport.
584             getAlignment().getSequences());
585       }
586     }
587     return al;
588   }
589
590   void showErrorMessage(final String error)
591   {
592     resetDialog();
593     javax.swing.SwingUtilities.invokeLater(new Runnable()
594     {
595       public void run()
596       {
597         JOptionPane.showInternalMessageDialog(Desktop.desktop,
598             error, "Error Retrieving Data",
599             JOptionPane.WARNING_MESSAGE);
600       }
601     });
602   }
603 }
604