update author list in license for (JAL-826)
[jalview.git] / src / MCview / PDBChain.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.7)
3  * Copyright (C) 2011 J Procter, AM Waterhouse, J Engelhardt, LM Lui, G Barton, M Clamp, S Searle
4  * 
5  * This file is part of Jalview.
6  * 
7  * Jalview is free software: you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License 
9  * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
10  * 
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  */
18 package MCview;
19
20 import java.util.*;
21
22 import java.awt.*;
23
24 import jalview.analysis.*;
25 import jalview.datamodel.*;
26 import jalview.schemes.*;
27 import jalview.structure.StructureMapping;
28
29 public class PDBChain
30 {
31   /**
32    * SequenceFeature group for PDB File features added to sequences
33    */
34   private static final String PDBFILEFEATURE = "PDBFile";
35
36   private static final String IEASTATUS = "IEA:jalview";
37
38   public String id;
39
40   public Vector bonds = new Vector();
41
42   public Vector atoms = new Vector();
43
44   public Vector residues = new Vector();
45
46   public int offset;
47
48   public Sequence sequence;
49
50   public boolean isNa = false;
51
52   public boolean isVisible = true;
53
54   public int pdbstart = 0;
55
56   public int pdbend = 0;
57
58   public int seqstart = 0;
59
60   public int seqend = 0;
61
62   public String pdbid = "";
63
64   public PDBChain(String pdbid, String id)
65   {
66     this.pdbid = pdbid.toLowerCase();
67     this.id = id;
68   }
69
70   /**
71    * character used to write newlines
72    */
73   protected String newline = System.getProperty("line.separator");
74
75   public void setNewlineString(String nl)
76   {
77     newline = nl;
78   }
79
80   public String getNewlineString()
81   {
82     return newline;
83   }
84
85   public String print()
86   {
87     String tmp = "";
88
89     for (int i = 0; i < bonds.size(); i++)
90     {
91       tmp = tmp + ((Bond) bonds.elementAt(i)).at1.resName + " "
92               + ((Bond) bonds.elementAt(i)).at1.resNumber + " " + offset
93               + newline;
94     }
95
96     return tmp;
97   }
98
99   /**
100    * Annotate the residues with their corresponding positions in s1 using the
101    * alignment in as
102    * NOTE: This clears all atom.alignmentMapping values on the structure.
103    * @param as
104    * @param s1
105    */
106   public void makeExactMapping(AlignSeq as, SequenceI s1)
107   {
108     int pdbpos = as.getSeq2Start() - 2;
109     int alignpos = s1.getStart() + as.getSeq1Start() - 3;
110     // first clear out any old alignmentMapping values:
111     for (Atom atom: (Vector<Atom>) atoms) { 
112       atom.alignmentMapping=-1;
113     }
114     // and now trace the alignment onto the atom set.
115     for (int i = 0; i < as.astr1.length(); i++)
116     {
117       if (as.astr1.charAt(i) != '-')
118       {
119         alignpos++;
120       }
121
122       if (as.astr2.charAt(i) != '-')
123       {
124         pdbpos++;
125       }
126
127       if (as.astr1.charAt(i) == as.astr2.charAt(i))
128       {
129         Residue res = (Residue) residues.elementAt(pdbpos);
130         Enumeration en = res.atoms.elements();
131         while (en.hasMoreElements())
132         {
133           Atom atom = (Atom) en.nextElement();
134           atom.alignmentMapping = alignpos;
135         }
136       }
137     }
138   }
139
140   /**
141    * copy over the RESNUM seqfeatures from the internal chain sequence to the
142    * mapped sequence
143    * 
144    * @param seq
145    * @param status
146    *          The Status of the transferred annotation
147    * @return the features added to sq (or its dataset)
148    */
149   public SequenceFeature[] transferRESNUMFeatures(SequenceI seq,
150           String status)
151   {
152     SequenceI sq = seq;
153     while (sq != null && sq.getDatasetSequence() != null)
154     {
155       sq = sq.getDatasetSequence();
156       if (sq == sequence)
157       {
158         return null;
159       }
160     }
161     /**
162      * Remove any existing features for this chain if they exist ?
163      * SequenceFeature[] seqsfeatures=seq.getSequenceFeatures(); int
164      * totfeat=seqsfeatures.length; // Remove any features for this exact chain
165      * ? for (int i=0; i<seqsfeatures.length; i++) { }
166      */
167     if (status == null)
168     {
169       status = PDBChain.IEASTATUS;
170     }
171     SequenceFeature[] features = sequence.getSequenceFeatures();
172     for (int i = 0; i < features.length; i++)
173     {
174       if (features[i].getFeatureGroup().equals(pdbid))
175       {
176         SequenceFeature tx = new SequenceFeature(features[i]);
177         tx.setBegin(1 + ((Atom) ((Residue) residues.elementAt(tx.getBegin()
178                 - offset)).atoms.elementAt(0)).alignmentMapping);
179         tx.setEnd(1 + ((Atom) ((Residue) residues.elementAt(tx.getEnd()
180                 - offset)).atoms.elementAt(0)).alignmentMapping);
181         tx.setStatus(status
182                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
183                         : ":" + tx.getStatus()));
184         if (tx.begin != 0 && tx.end != 0)
185           sq.addSequenceFeature(tx);
186       }
187     }
188     return features;
189   }
190
191   public void makeCaBondList()
192   {
193     boolean na = false;
194     int numNa = 0;
195     for (int i = 0; i < (residues.size() - 1); i++)
196     {
197       Residue tmpres = (Residue) residues.elementAt(i);
198       Residue tmpres2 = (Residue) residues.elementAt(i + 1);
199       Atom at1 = tmpres.findAtom("CA");
200       Atom at2 = tmpres2.findAtom("CA");
201       na = false;
202       if ((at1 == null) && (at2 == null))
203       {
204         na = true;
205         at1 = tmpres.findAtom("P");
206         at2 = tmpres2.findAtom("P");
207       }
208       if ((at1 != null) && (at2 != null))
209       {
210         if (at1.chain.equals(at2.chain))
211         {
212           if (na)
213           {
214             numNa++;
215           }
216           makeBond(at1, at2);
217         }
218       }
219       else
220       {
221         System.out.println("not found " + i);
222       }
223     }
224     if (numNa > 0 && ((numNa / residues.size()) > 0.99))
225     {
226       isNa = true;
227     }
228   }
229
230   public void makeBond(Atom at1, Atom at2)
231   {
232     float[] start = new float[3];
233     float[] end = new float[3];
234
235     start[0] = at1.x;
236     start[1] = at1.y;
237     start[2] = at1.z;
238
239     end[0] = at2.x;
240     end[1] = at2.y;
241     end[2] = at2.z;
242
243     bonds.addElement(new Bond(start, end, at1, at2));
244   }
245
246   public void makeResidueList()
247   {
248     int count = 0;
249     Object symbol;
250     boolean deoxyn=false;
251     boolean nucleotide = false;
252     StringBuffer seq = new StringBuffer();
253     Vector resFeatures = new Vector();
254     Vector resAnnotation = new Vector();
255     int i, iSize = atoms.size() - 1;
256     int resNumber = -1;
257     for (i = 0; i <= iSize; i++)
258     {
259       Atom tmp = (Atom) atoms.elementAt(i);
260       resNumber = tmp.resNumber;
261       int res = resNumber;
262
263       if (i == 0)
264       {
265         offset = resNumber;
266       }
267
268       Vector resAtoms = new Vector();
269       // Add atoms to a vector while the residue number
270       // remains the same as the first atom's resNumber (res)
271       while ((resNumber == res) && (i < atoms.size()))
272       {
273         resAtoms.addElement((Atom) atoms.elementAt(i));
274         i++;
275
276         if (i < atoms.size())
277         {
278           resNumber = ((Atom) atoms.elementAt(i)).resNumber;
279         }
280         else
281         {
282           resNumber++;
283         }
284       }
285
286       // We need this to keep in step with the outer for i = loop
287       i--;
288
289       // Make a new Residue object with the new atoms vector
290       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
291
292       Residue tmpres = (Residue) residues.lastElement();
293       Atom tmpat = (Atom) tmpres.atoms.elementAt(0);
294       // Make A new SequenceFeature for the current residue numbering
295       SequenceFeature sf = new SequenceFeature("RESNUM", tmpat.resName
296               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
297               + count, offset + count, pdbid);
298       // MCview.PDBChain.PDBFILEFEATURE);
299       resFeatures.addElement(sf);
300       resAnnotation.addElement(new Annotation(tmpat.tfactor));
301       // Keep totting up the sequence
302       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
303       {
304         String nucname = tmpat.resName.trim();
305         // use the aaIndex rather than call 'toLower' - which would take a bit more time.
306         deoxyn=nucname.length()==2 && ResidueProperties.aaIndex[nucname.charAt(0)]==ResidueProperties.aaIndex['D'];
307         if (tmpat.name.equalsIgnoreCase("CA")
308                 || ResidueProperties.nucleotideIndex[nucname.charAt((deoxyn ? 1 : 0))] == -1)
309         {
310           seq.append("X");
311           // System.err.println("PDBReader:Null aa3Hash for " +
312           // tmpat.resName);
313         }
314         else
315         {
316           // nucleotide flag
317           nucleotide = true;
318           seq.append(nucname.charAt((deoxyn ? 1 : 0)));
319         }
320       }
321       else
322       {
323         if (nucleotide)
324         {
325           System.err
326                   .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
327         }
328         seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
329       }
330       count++;
331     }
332
333     if (id.length() < 1)
334     {
335       id = " ";
336     }
337     isNa = nucleotide;
338     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
339     // resNumber-offset
340     // ~=
341     // seq.size()
342     // Add normalised feature scores to RESNUM indicating start/end of sequence
343     // sf.setScore(offset+count);
344
345     // System.out.println("PDB Sequence is :\nSequence = " + seq);
346     // System.out.println("No of residues = " + residues.size());
347     for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
348     {
349       sequence.addSequenceFeature((SequenceFeature) resFeatures
350               .elementAt(i));
351       resFeatures.setElementAt(null, i);
352     }
353     Annotation[] annots = new Annotation[resAnnotation.size()];
354     float max = 0;
355     for (i = 0, iSize = annots.length; i < iSize; i++)
356     {
357       annots[i] = (Annotation) resAnnotation.elementAt(i);
358       if (annots[i].value > max)
359         max = annots[i].value;
360       resAnnotation.setElementAt(null, i);
361     }
362     AlignmentAnnotation tfactorann = new AlignmentAnnotation(
363             "PDB.TempFactor", "Temperature Factor for "
364                     + sequence.getName(), annots, 0, max,
365             AlignmentAnnotation.LINE_GRAPH);
366     tfactorann.setSequenceRef(sequence);
367     sequence.addAlignmentAnnotation(tfactorann);
368   }
369
370   public void setChargeColours()
371   {
372     for (int i = 0; i < bonds.size(); i++)
373     {
374       try
375       {
376         Bond b = (Bond) bonds.elementAt(i);
377
378         if (b.at1.resName.equalsIgnoreCase("ASP")
379                 || b.at1.resName.equalsIgnoreCase("GLU"))
380         {
381           b.startCol = Color.red;
382         }
383         else if (b.at1.resName.equalsIgnoreCase("LYS")
384                 || b.at1.resName.equalsIgnoreCase("ARG"))
385         {
386           b.startCol = Color.blue;
387         }
388         else if (b.at1.resName.equalsIgnoreCase("CYS"))
389         {
390           b.startCol = Color.yellow;
391         }
392         else
393         {
394           b.startCol = Color.lightGray;
395         }
396
397         if (b.at2.resName.equalsIgnoreCase("ASP")
398                 || b.at2.resName.equalsIgnoreCase("GLU"))
399         {
400           b.endCol = Color.red;
401         }
402         else if (b.at2.resName.equalsIgnoreCase("LYS")
403                 || b.at2.resName.equalsIgnoreCase("ARG"))
404         {
405           b.endCol = Color.blue;
406         }
407         else if (b.at2.resName.equalsIgnoreCase("CYS"))
408         {
409           b.endCol = Color.yellow;
410         }
411         else
412         {
413           b.endCol = Color.lightGray;
414         }
415       } catch (Exception e)
416       {
417         Bond b = (Bond) bonds.elementAt(i);
418         b.startCol = Color.gray;
419         b.endCol = Color.gray;
420       }
421     }
422   }
423
424   public void setChainColours(jalview.schemes.ColourSchemeI cs)
425   {
426     Bond b;
427     int index;
428     for (int i = 0; i < bonds.size(); i++)
429     {
430       try
431       {
432         b = (Bond) bonds.elementAt(i);
433
434         index = ((Integer) ResidueProperties.aa3Hash.get(b.at1.resName))
435                 .intValue();
436         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
437
438         index = ((Integer) ResidueProperties.aa3Hash.get(b.at2.resName))
439                 .intValue();
440         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
441
442       } catch (Exception e)
443       {
444         b = (Bond) bonds.elementAt(i);
445         b.startCol = Color.gray;
446         b.endCol = Color.gray;
447       }
448     }
449   }
450
451   public void setChainColours(Color col)
452   {
453     for (int i = 0; i < bonds.size(); i++)
454     {
455       Bond tmp = (Bond) bonds.elementAt(i);
456       tmp.startCol = col;
457       tmp.endCol = col;
458     }
459   }
460
461   public AlignmentAnnotation[] transferResidueAnnotation(SequenceI seq,
462           String status)
463   {
464     AlignmentAnnotation[] transferred = null;
465
466     return transferred;
467
468   }
469
470   /**
471    * copy any sequence annotation onto the sequence mapped using the provided
472    * StructureMapping
473    * 
474    * @param mapping
475    */
476   public void transferResidueAnnotation(StructureMapping mapping)
477   {
478     SequenceI sq = mapping.getSequence();
479     if (sq != null)
480     {
481       if (sequence != null && sequence.getAnnotation() != null)
482       {
483
484       }
485       float min = -1, max = 0;
486       Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
487       for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
488       {
489         int prn = mapping.getPDBResNum(k + 1);
490
491         an[k] = new Annotation((float) prn);
492         if (min == -1)
493         {
494           min = k;
495           max = k;
496         }
497         else
498         {
499           if (min > k)
500           {
501             min = k;
502           }
503           else if (max < k)
504           {
505             max = k;
506           }
507         }
508       }
509       sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
510               "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
511               an, (float) min, (float) max, AlignmentAnnotation.LINE_GRAPH));
512     }
513   }
514 }