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