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