Wrap alignment added to preferences
[jalview.git] / src / jalview / io / SequenceFeatureFetcher.java
1 /*\r
2 * Jalview - A Sequence Alignment Editor and Viewer\r
3 * Copyright (C) 2005 AM Waterhouse, J Procter, G Barton, M Clamp, S Searle\r
4 *\r
5 * This program is free software; you can redistribute it and/or\r
6 * modify it under the terms of the GNU General Public License\r
7 * as published by the Free Software Foundation; either version 2\r
8 * of the License, or (at your option) any later version.\r
9 *\r
10 * This program is distributed in the hope that it will be useful,\r
11 * but WITHOUT ANY WARRANTY; without even the implied warranty of\r
12 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the\r
13 * GNU General Public License for more details.\r
14 *\r
15 * You should have received a copy of the GNU General Public License\r
16 * along with this program; if not, write to the Free Software\r
17 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA\r
18 */\r
19 package jalview.io;\r
20 \r
21 import jalview.datamodel.*;\r
22 \r
23 import jalview.gui.*;\r
24 \r
25 import java.io.*;\r
26 \r
27 import java.util.*;\r
28 \r
29 import org.exolab.castor.mapping.Mapping;\r
30 \r
31 import org.exolab.castor.xml.*;\r
32 import jalview.analysis.AlignSeq;\r
33 \r
34 \r
35 \r
36 /**\r
37  * DOCUMENT ME!\r
38  *\r
39  * @author $author$\r
40  * @version $Revision$\r
41  */\r
42 public class SequenceFeatureFetcher implements Runnable\r
43 {\r
44 \r
45   AlignmentI align;\r
46   AlignmentI dataset;\r
47   AlignmentPanel ap;\r
48   ArrayList unknownSequences;\r
49   CutAndPasteTransfer output = new CutAndPasteTransfer();\r
50   StringBuffer sbuffer = new StringBuffer();\r
51   boolean uniprotFlag = false;\r
52 \r
53   public SequenceFeatureFetcher()\r
54   {}\r
55 \r
56   public Vector getUniprotEntries(File file)\r
57   {\r
58 \r
59     UniprotFile uni = new UniprotFile();\r
60     try\r
61     {\r
62       // 1. Load the mapping information from the file\r
63       Mapping map = new Mapping(uni.getClass().getClassLoader());\r
64       java.net.URL url = getClass().getResource("/uniprot_mapping.xml");\r
65       map.loadMapping(url);\r
66 \r
67       // 2. Unmarshal the data\r
68       Unmarshaller unmar = new Unmarshaller(uni);\r
69       unmar.setIgnoreExtraElements(true);\r
70       unmar.setMapping(map);\r
71    //   unmar.setDebug(true);\r
72 \r
73       uni = (UniprotFile) unmar.unmarshal(new FileReader(file));\r
74     }\r
75     catch (Exception e)\r
76     {\r
77       System.out.println("Error getUniprotEntries() "+e);\r
78     }\r
79 \r
80 \r
81     return uni.getUniprotEntries();\r
82   }\r
83 \r
84   /**\r
85    * Creates a new SequenceFeatureFetcher object.\r
86    *\r
87    * @param align DOCUMENT ME!\r
88    * @param ap DOCUMENT ME!\r
89    */\r
90   public SequenceFeatureFetcher(AlignmentI align, AlignmentPanel ap)\r
91   {\r
92     unknownSequences = new ArrayList();\r
93     this.align = align;\r
94     this.dataset = align.getDataset();\r
95     this.ap = ap;\r
96 \r
97     Thread thread = new Thread(this);\r
98     thread.start();\r
99   }\r
100 \r
101   /**\r
102    * DOCUMENT ME!\r
103    */\r
104   public void run()\r
105   {\r
106     try\r
107     {\r
108       int seqIndex = 0;\r
109       Vector sequences = dataset.getSequences();\r
110 \r
111       while (seqIndex < sequences.size())\r
112       {\r
113         Vector ids = new Vector();\r
114 \r
115         for (int i = 0; (seqIndex < sequences.size()) && (i < 50);\r
116              seqIndex++, i++)\r
117         {\r
118           Sequence sequence = (Sequence) sequences.get(seqIndex);\r
119           Vector uprefs = jalview.util.DBRefUtils.selectRefs(sequence.getDBRef(), new String[] { "Uniprot"});\r
120           if (uprefs!=null)\r
121           {\r
122             // we know the id for this entry, so don't note its ID in the unknownSequences list\r
123             for (int j=0,k=uprefs.size(); j<k; j++)\r
124               ids.add(((DBRefEntry) uprefs.get(j)).getAccessionId());\r
125             unknownSequences.add(sequence);\r
126           } else {\r
127             if (!ids.contains(sequence.getName()))\r
128             {\r
129               ids.add(sequence.getName());\r
130               unknownSequences.add(sequence);\r
131             }\r
132           }\r
133         }\r
134 \r
135         ///////////////////////////////////\r
136         ///READ FROM EBI\r
137         if (ids.size() > 0)\r
138         {\r
139           StringBuffer remainingIds = new StringBuffer("uniprot:");\r
140           for (int i = 0; i < ids.size(); i++)\r
141            {\r
142              if(ids.get(i).toString().indexOf("|")>-1)\r
143              {\r
144                remainingIds.append(ids.get(i).toString().substring(\r
145                    ids.get(i).toString().lastIndexOf("|") + 1));\r
146                uniprotFlag = true;\r
147              }\r
148              remainingIds.append(ids.get(i) + ";");\r
149            }\r
150           EBIFetchClient ebi = new EBIFetchClient();\r
151           File file = ebi.fetchDataAsFile(remainingIds.toString(),\r
152                                           "xml", "raw");\r
153 \r
154 \r
155 \r
156           if (file != null)\r
157           {\r
158             ReadUniprotFile(file, ids);\r
159           }\r
160         }\r
161       }\r
162     }\r
163     catch (Exception ex)\r
164     {\r
165       ex.printStackTrace();\r
166     }\r
167 \r
168     if (sbuffer.length() > 0)\r
169     {\r
170       output.setText(\r
171           "Your sequences have been matched to Uniprot. Some of the ids have been\n" +\r
172           "altered, most likely the start/end residue will have been updated.\n" +\r
173           "Save your alignment to maintain the updated id.\n\n" +\r
174           sbuffer.toString());\r
175       Desktop.addInternalFrame(output, "Sequence names updated ", 600, 300);\r
176       // The above is the dataset, we must now find out the index\r
177       // of the viewed sequence\r
178 \r
179     }\r
180 \r
181     promptBeforeBlast();\r
182 \r
183   }\r
184 \r
185 \r
186   void promptBeforeBlast()\r
187    {\r
188      // This must be outside the run() body as java 1.5\r
189      // will not return any value from the OptionPane to the expired thread.\r
190       if (unknownSequences.size() > 0)\r
191       {\r
192        // int reply = javax.swing.JOptionPane.showConfirmDialog(\r
193        //     Desktop.desktop, "Couldn't find a match for "+unknownSequences.size()+" sequences."\r
194         //        +"\nPerform blast for unknown sequences?",\r
195         //            "Blast for Unidentified Sequences",\r
196         //             javax.swing.JOptionPane.YES_NO_OPTION, javax.swing.JOptionPane.QUESTION_MESSAGE);\r
197      javax.swing.JOptionPane.showMessageDialog(\r
198     Desktop.desktop, "Couldn't find a match for "+unknownSequences.size()+" sequences.",\r
199             "Unidentified Sequences",\r
200              javax.swing.JOptionPane.WARNING_MESSAGE);\r
201 \r
202 \r
203       //  if(reply == javax.swing.JOptionPane.YES_OPTION)\r
204      //    new WSWUBlastClient(ap, align, unknownSequences);\r
205       }\r
206 \r
207 \r
208     ap.repaint();\r
209   }\r
210 \r
211   /**\r
212    * DOCUMENT ME!\r
213    *\r
214    * @param result DOCUMENT ME!\r
215    * @param out DOCUMENT ME!\r
216    * @param align DOCUMENT ME!\r
217    */\r
218   void ReadUniprotFile(File file, Vector ids)\r
219   {\r
220     if(!file.exists())\r
221       return;\r
222 \r
223     SequenceI sequence = null;\r
224 \r
225     Vector entries = getUniprotEntries(file);\r
226 \r
227     int i, iSize = entries==null?0:entries.size();\r
228     UniprotEntry entry;\r
229     for (i = 0; i < iSize; i++)\r
230     {\r
231       entry = (UniprotEntry) entries.elementAt(i);\r
232       String idmatch = entry.getAccession().elementAt(0).toString();\r
233       sequence = dataset.findName(idmatch);\r
234 \r
235       if (sequence == null)\r
236       {\r
237         //Sequence maybe Name, not Accession\r
238         idmatch = entry.getName().elementAt(0).toString();\r
239         sequence = dataset.findName(idmatch);\r
240       }\r
241 \r
242       if(sequence!=null)\r
243         ids.remove(sequence.getName());\r
244 \r
245       else  if (sequence == null && uniprotFlag)\r
246       {\r
247           sequence = dataset.findName("UniProt/Swiss-Prot|"+entry.getAccession().elementAt(0)+"|"+idmatch);\r
248           ids.remove(idmatch);\r
249       }\r
250 \r
251       if(sequence ==null)\r
252       {\r
253         System.out.println(idmatch+" not found");\r
254         continue;\r
255       }\r
256 \r
257 \r
258       String nonGapped = AlignSeq.extractGaps("-. ", sequence.getSequence());\r
259 \r
260       int absStart = entry.getUniprotSequence().getContent().indexOf(\r
261           nonGapped.toString());\r
262 \r
263       if (absStart == -1)\r
264       {\r
265         // Is UniprotSequence contained in dataset sequence?\r
266         absStart = nonGapped.toString().indexOf(entry.getUniprotSequence().getContent());\r
267         if(absStart == -1)\r
268         {\r
269           sbuffer.append(sequence.getName() +\r
270                          " SEQUENCE NOT %100 MATCH \n");\r
271 \r
272           continue;\r
273         }\r
274         else\r
275         {\r
276 \r
277           if(entry.getFeature()!=null)\r
278           {\r
279             Enumeration e = entry.getFeature().elements();\r
280             while (e.hasMoreElements())\r
281             {\r
282               SequenceFeature sf = (SequenceFeature) e.nextElement();\r
283               sf.setBegin(sf.getBegin() + absStart + 1);\r
284               sf.setEnd(sf.getEnd() + absStart + 1);\r
285             }\r
286           }\r
287 \r
288           sbuffer.append(sequence.getName() +\r
289                          " HAS "+absStart+" PREFIXED RESIDUES COMPARED TO UNIPROT - ANY SEQUENCE FEATURES"\r
290                         +" HAVE BEEN ADJUSTED ACCORDINGLY \n");\r
291           absStart = 0;\r
292         }\r
293 \r
294       }\r
295 \r
296       unknownSequences.remove(sequence);\r
297 \r
298       int absEnd = absStart + nonGapped.toString().length();\r
299       absStart += 1;\r
300 \r
301       Enumeration e = entry.getDbReference().elements();\r
302       Vector onlyPdbEntries = new Vector();\r
303       while(e.hasMoreElements())\r
304       {\r
305         PDBEntry pdb = (PDBEntry)e.nextElement();\r
306         if(!pdb.getType().equals("PDB"))\r
307           continue;\r
308 \r
309         onlyPdbEntries.addElement(pdb);\r
310       }\r
311 \r
312       sequence.setPDBId(onlyPdbEntries);\r
313       if (entry.getFeature()!=null) {\r
314         e = entry.getFeature().elements();\r
315         while (e.hasMoreElements())\r
316         {\r
317           SequenceFeature sf = (SequenceFeature) e.nextElement();\r
318           sf.setFeatureGroup("Uniprot");\r
319           sequence.addSequenceFeature( sf );\r
320         }\r
321       }\r
322       sequence.setStart(absStart);\r
323       sequence.setEnd(absEnd);\r
324 \r
325 \r
326       int n = 0;\r
327       SequenceI seq2;\r
328       while (n < align.getHeight())\r
329       {\r
330         //This loop enables multiple sequences with the same\r
331         //id to have features added and seq limits updated\r
332         seq2 = align.getSequenceAt(n);\r
333         if (seq2.getName().equals(idmatch))\r
334         {\r
335 \r
336           nonGapped = AlignSeq.extractGaps("-. ", seq2.getSequence());\r
337 \r
338           absStart = sequence.getSequence().indexOf(nonGapped);\r
339           absEnd = absStart + nonGapped.toString().length() - 1;\r
340 \r
341           // This is the Viewd alignment sequences\r
342           // No need to tell the user of the dataset updates\r
343           if ( (seq2.getStart() != absStart+sequence.getStart())\r
344              || (seq2.getEnd() != absEnd+sequence.getStart()))\r
345           {\r
346             sbuffer.append("Updated: " + seq2.getName() + " " +\r
347                            seq2.getStart() + "/" + seq2.getEnd() +\r
348                            "  to  " + (absStart + sequence.getStart()) + "/" +\r
349                            (absEnd + sequence.getStart()) + "\n");\r
350 \r
351             seq2.setStart(absStart + sequence.getStart());\r
352             seq2.setEnd(absEnd + sequence.getStart());\r
353           }\r
354         }\r
355 \r
356         n++;\r
357       }\r
358     }\r
359   }\r
360 }\r
361 \r
362 \r