cc71355f85e9ee1d57130db16d395b40e220a80b
[jalview.git] / src / MCview / PDBChain.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3  * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, 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 NOTE: This clears all atom.alignmentMapping values on the
102    * structure.
103    * 
104    * @param as
105    * @param s1
106    */
107   public void makeExactMapping(AlignSeq as, SequenceI s1)
108   {
109     int pdbpos = as.getSeq2Start() - 2;
110     int alignpos = s1.getStart() + as.getSeq1Start() - 3;
111     // first clear out any old alignmentMapping values:
112     for (Atom atom : (Vector<Atom>) atoms)
113     {
114       atom.alignmentMapping = -1;
115     }
116     // and now trace the alignment onto the atom set.
117     for (int i = 0; i < as.astr1.length(); i++)
118     {
119       if (as.astr1.charAt(i) != '-')
120       {
121         alignpos++;
122       }
123
124       if (as.astr2.charAt(i) != '-')
125       {
126         pdbpos++;
127       }
128
129       if (as.astr1.charAt(i) == as.astr2.charAt(i))
130       {
131         Residue res = (Residue) residues.elementAt(pdbpos);
132         Enumeration en = res.atoms.elements();
133         while (en.hasMoreElements())
134         {
135           Atom atom = (Atom) en.nextElement();
136           atom.alignmentMapping = alignpos;
137         }
138       }
139     }
140   }
141
142   /**
143    * copy over the RESNUM seqfeatures from the internal chain sequence to the
144    * mapped sequence
145    * 
146    * @param seq
147    * @param status
148    *          The Status of the transferred annotation
149    * @return the features added to sq (or its dataset)
150    */
151   public SequenceFeature[] transferRESNUMFeatures(SequenceI seq,
152           String status)
153   {
154     SequenceI sq = seq;
155     while (sq != null && sq.getDatasetSequence() != null)
156     {
157       sq = sq.getDatasetSequence();
158       if (sq == sequence)
159       {
160         return null;
161       }
162     }
163     /**
164      * Remove any existing features for this chain if they exist ?
165      * SequenceFeature[] seqsfeatures=seq.getSequenceFeatures(); int
166      * totfeat=seqsfeatures.length; // Remove any features for this exact chain
167      * ? for (int i=0; i<seqsfeatures.length; i++) { }
168      */
169     if (status == null)
170     {
171       status = PDBChain.IEASTATUS;
172     }
173     SequenceFeature[] features = sequence.getSequenceFeatures();
174     for (int i = 0; i < features.length; i++)
175     {
176       if (features[i].getFeatureGroup().equals(pdbid))
177       {
178         SequenceFeature tx = new SequenceFeature(features[i]);
179         tx.setBegin(1 + ((Atom) ((Residue) residues.elementAt(tx.getBegin()
180                 - offset)).atoms.elementAt(0)).alignmentMapping);
181         tx.setEnd(1 + ((Atom) ((Residue) residues.elementAt(tx.getEnd()
182                 - offset)).atoms.elementAt(0)).alignmentMapping);
183         tx.setStatus(status
184                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
185                         : ":" + tx.getStatus()));
186         if (tx.begin != 0 && tx.end != 0)
187           sq.addSequenceFeature(tx);
188       }
189     }
190     return features;
191   }
192
193   public void makeCaBondList()
194   {
195     boolean na = false;
196     int numNa = 0;
197     for (int i = 0; i < (residues.size() - 1); i++)
198     {
199       Residue tmpres = (Residue) residues.elementAt(i);
200       Residue tmpres2 = (Residue) residues.elementAt(i + 1);
201       Atom at1 = tmpres.findAtom("CA");
202       Atom at2 = tmpres2.findAtom("CA");
203       na = false;
204       if ((at1 == null) && (at2 == null))
205       {
206         na = true;
207         at1 = tmpres.findAtom("P");
208         at2 = tmpres2.findAtom("P");
209       }
210       if ((at1 != null) && (at2 != null))
211       {
212         if (at1.chain.equals(at2.chain))
213         {
214           if (na)
215           {
216             numNa++;
217           }
218           makeBond(at1, at2);
219         }
220       }
221       else
222       {
223         System.out.println("not found " + i);
224       }
225     }
226     if (numNa > 0 && ((numNa / residues.size()) > 0.99))
227     {
228       isNa = true;
229     }
230   }
231
232   public void makeBond(Atom at1, Atom at2)
233   {
234     float[] start = new float[3];
235     float[] end = new float[3];
236
237     start[0] = at1.x;
238     start[1] = at1.y;
239     start[2] = at1.z;
240
241     end[0] = at2.x;
242     end[1] = at2.y;
243     end[2] = at2.z;
244
245     bonds.addElement(new Bond(start, end, at1, at2));
246   }
247
248   public void makeResidueList()
249   {
250     int count = 0;
251     Object symbol;
252     boolean deoxyn = false;
253     boolean nucleotide = false;
254     StringBuffer seq = new StringBuffer();
255     Vector resFeatures = new Vector();
256     Vector resAnnotation = new Vector();
257     int i, iSize = atoms.size() - 1;
258     int resNumber = -1;
259     for (i = 0; i <= iSize; i++)
260     {
261       Atom tmp = (Atom) atoms.elementAt(i);
262       resNumber = tmp.resNumber;
263       int res = resNumber;
264
265       if (i == 0)
266       {
267         offset = resNumber;
268       }
269
270       Vector resAtoms = new Vector();
271       // Add atoms to a vector while the residue number
272       // remains the same as the first atom's resNumber (res)
273       while ((resNumber == res) && (i < atoms.size()))
274       {
275         resAtoms.addElement((Atom) atoms.elementAt(i));
276         i++;
277
278         if (i < atoms.size())
279         {
280           resNumber = ((Atom) atoms.elementAt(i)).resNumber;
281         }
282         else
283         {
284           resNumber++;
285         }
286       }
287
288       // We need this to keep in step with the outer for i = loop
289       i--;
290
291       // Make a new Residue object with the new atoms vector
292       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
293
294       Residue tmpres = (Residue) residues.lastElement();
295       Atom tmpat = (Atom) tmpres.atoms.elementAt(0);
296       // Make A new SequenceFeature for the current residue numbering
297       SequenceFeature sf = new SequenceFeature("RESNUM", tmpat.resName
298               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
299               + count, offset + count, pdbid);
300       // MCview.PDBChain.PDBFILEFEATURE);
301       resFeatures.addElement(sf);
302       resAnnotation.addElement(new Annotation(tmpat.tfactor));
303       // Keep totting up the sequence
304       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
305       {
306         String nucname = tmpat.resName.trim();
307         // use the aaIndex rather than call 'toLower' - which would take a bit
308         // more time.
309         deoxyn = nucname.length() == 2
310                 && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
311         if (tmpat.name.equalsIgnoreCase("CA")
312                 || ResidueProperties.nucleotideIndex[nucname
313                         .charAt((deoxyn ? 1 : 0))] == -1)
314         {
315           seq.append("X");
316           // System.err.println("PDBReader:Null aa3Hash for " +
317           // tmpat.resName);
318         }
319         else
320         {
321           // nucleotide flag
322           nucleotide = true;
323           seq.append(nucname.charAt((deoxyn ? 1 : 0)));
324         }
325       }
326       else
327       {
328         if (nucleotide)
329         {
330           System.err
331                   .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
332         }
333         seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
334       }
335       count++;
336     }
337
338     if (id.length() < 1)
339     {
340       id = " ";
341     }
342     isNa = nucleotide;
343     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
344     // resNumber-offset
345     // ~=
346     // seq.size()
347     // Add normalised feature scores to RESNUM indicating start/end of sequence
348     // sf.setScore(offset+count);
349
350     // System.out.println("PDB Sequence is :\nSequence = " + seq);
351     // System.out.println("No of residues = " + residues.size());
352     for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
353     {
354       sequence.addSequenceFeature((SequenceFeature) resFeatures
355               .elementAt(i));
356       resFeatures.setElementAt(null, i);
357     }
358     Annotation[] annots = new Annotation[resAnnotation.size()];
359     float max = 0;
360     for (i = 0, iSize = annots.length; i < iSize; i++)
361     {
362       annots[i] = (Annotation) resAnnotation.elementAt(i);
363       if (annots[i].value > max)
364         max = annots[i].value;
365       resAnnotation.setElementAt(null, i);
366     }
367     AlignmentAnnotation tfactorann = new AlignmentAnnotation(
368             "PDB.TempFactor", "Temperature Factor for "
369                     + sequence.getName(), annots, 0, max,
370             AlignmentAnnotation.LINE_GRAPH);
371     tfactorann.setSequenceRef(sequence);
372     sequence.addAlignmentAnnotation(tfactorann);
373   }
374
375   public void setChargeColours()
376   {
377     for (int i = 0; i < bonds.size(); i++)
378     {
379       try
380       {
381         Bond b = (Bond) bonds.elementAt(i);
382
383         if (b.at1.resName.equalsIgnoreCase("ASP")
384                 || b.at1.resName.equalsIgnoreCase("GLU"))
385         {
386           b.startCol = Color.red;
387         }
388         else if (b.at1.resName.equalsIgnoreCase("LYS")
389                 || b.at1.resName.equalsIgnoreCase("ARG"))
390         {
391           b.startCol = Color.blue;
392         }
393         else if (b.at1.resName.equalsIgnoreCase("CYS"))
394         {
395           b.startCol = Color.yellow;
396         }
397         else
398         {
399           b.startCol = Color.lightGray;
400         }
401
402         if (b.at2.resName.equalsIgnoreCase("ASP")
403                 || b.at2.resName.equalsIgnoreCase("GLU"))
404         {
405           b.endCol = Color.red;
406         }
407         else if (b.at2.resName.equalsIgnoreCase("LYS")
408                 || b.at2.resName.equalsIgnoreCase("ARG"))
409         {
410           b.endCol = Color.blue;
411         }
412         else if (b.at2.resName.equalsIgnoreCase("CYS"))
413         {
414           b.endCol = Color.yellow;
415         }
416         else
417         {
418           b.endCol = Color.lightGray;
419         }
420       } catch (Exception e)
421       {
422         Bond b = (Bond) bonds.elementAt(i);
423         b.startCol = Color.gray;
424         b.endCol = Color.gray;
425       }
426     }
427   }
428
429   public void setChainColours(jalview.schemes.ColourSchemeI cs)
430   {
431     Bond b;
432     int index;
433     for (int i = 0; i < bonds.size(); i++)
434     {
435       try
436       {
437         b = (Bond) bonds.elementAt(i);
438
439         index = ((Integer) ResidueProperties.aa3Hash.get(b.at1.resName))
440                 .intValue();
441         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
442
443         index = ((Integer) ResidueProperties.aa3Hash.get(b.at2.resName))
444                 .intValue();
445         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
446
447       } catch (Exception e)
448       {
449         b = (Bond) bonds.elementAt(i);
450         b.startCol = Color.gray;
451         b.endCol = Color.gray;
452       }
453     }
454   }
455
456   public void setChainColours(Color col)
457   {
458     for (int i = 0; i < bonds.size(); i++)
459     {
460       Bond tmp = (Bond) bonds.elementAt(i);
461       tmp.startCol = col;
462       tmp.endCol = col;
463     }
464   }
465
466   public AlignmentAnnotation[] transferResidueAnnotation(SequenceI seq,
467           String status)
468   {
469     AlignmentAnnotation[] transferred = null;
470
471     return transferred;
472
473   }
474
475   /**
476    * copy any sequence annotation onto the sequence mapped using the provided
477    * StructureMapping
478    * 
479    * @param mapping
480    */
481   public void transferResidueAnnotation(StructureMapping mapping)
482   {
483     SequenceI sq = mapping.getSequence();
484     if (sq != null)
485     {
486       if (sequence != null && sequence.getAnnotation() != null)
487       {
488
489       }
490       float min = -1, max = 0;
491       Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
492       for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
493       {
494         int prn = mapping.getPDBResNum(k + 1);
495
496         an[k] = new Annotation((float) prn);
497         if (min == -1)
498         {
499           min = k;
500           max = k;
501         }
502         else
503         {
504           if (min > k)
505           {
506             min = k;
507           }
508           else if (max < k)
509           {
510             max = k;
511           }
512         }
513       }
514       sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
515               "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
516               an, (float) min, (float) max, AlignmentAnnotation.LINE_GRAPH));
517     }
518   }
519 }