6d5f9fe1d02bdc07d8b3ed50c809ad78babd08d0
[jalview.git] / src / MCview / PDBChain.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3  * Copyright (C) $$Year-Rel$$ 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.ColourSchemeI;
31 import jalview.schemes.ResidueProperties;
32 import jalview.structure.StructureMapping;
33
34 import java.awt.Color;
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<Bond> bonds = new Vector<Bond>();
50
51   public Vector<Atom> atoms = new Vector<Atom>();
52
53   public Vector<Residue> residues = new Vector<Residue>();
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     StringBuilder tmp = new StringBuilder(256);
108
109     for (Bond b : bonds)
110     {
111       tmp.append(b.at1.resName).append(" ").append(b.at1.resNumber)
112               .append(" ").append(offset).append(newline);
113     }
114
115     return tmp.toString();
116   }
117
118   /**
119    * Annotate the residues with their corresponding positions in s1 using the
120    * alignment in as NOTE: This clears all atom.alignmentMapping values on the
121    * structure.
122    * 
123    * @param as
124    * @param s1
125    */
126   public void makeExactMapping(AlignSeq as, SequenceI s1)
127   {
128     int pdbpos = as.getSeq2Start() - 2;
129     int alignpos = s1.getStart() + as.getSeq1Start() - 3;
130     // first clear out any old alignmentMapping values:
131     for (Atom atom : atoms)
132     {
133       atom.alignmentMapping = -1;
134     }
135     // and now trace the alignment onto the atom set.
136     for (int i = 0; i < as.astr1.length(); i++)
137     {
138       if (as.astr1.charAt(i) != '-')
139       {
140         alignpos++;
141       }
142
143       if (as.astr2.charAt(i) != '-')
144       {
145         pdbpos++;
146       }
147
148       if (as.astr1.charAt(i) == as.astr2.charAt(i))
149       {
150         Residue res = residues.elementAt(pdbpos);
151         for (Atom atom : res.atoms)
152         {
153           atom.alignmentMapping = alignpos;
154         }
155       }
156     }
157   }
158
159   /**
160    * copy over the RESNUM seqfeatures from the internal chain sequence to the
161    * mapped sequence
162    * 
163    * @param seq
164    * @param status
165    *          The Status of the transferred annotation
166    * @return the features added to sq (or its dataset)
167    */
168   public SequenceFeature[] transferRESNUMFeatures(SequenceI seq,
169           String status)
170   {
171     SequenceI sq = seq;
172     while (sq != null && sq.getDatasetSequence() != null)
173     {
174       sq = sq.getDatasetSequence();
175       if (sq == sequence)
176       {
177         return null;
178       }
179     }
180     /**
181      * Remove any existing features for this chain if they exist ?
182      * SequenceFeature[] seqsfeatures=seq.getSequenceFeatures(); int
183      * totfeat=seqsfeatures.length; // Remove any features for this exact chain
184      * ? for (int i=0; i<seqsfeatures.length; i++) { }
185      */
186     if (status == null)
187     {
188       status = PDBChain.IEASTATUS;
189     }
190     SequenceFeature[] features = sequence.getSequenceFeatures();
191     for (int i = 0; i < features.length; i++)
192     {
193       if (features[i].getFeatureGroup().equals(pdbid))
194       {
195         SequenceFeature tx = new SequenceFeature(features[i]);
196         tx.setBegin(1 + residues.elementAt(tx.getBegin() - offset).atoms
197                 .elementAt(0).alignmentMapping);
198         tx.setEnd(1 + residues.elementAt(tx.getEnd() - offset).atoms
199                 .elementAt(0).alignmentMapping);
200         tx.setStatus(status
201                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
202                         : ":" + tx.getStatus()));
203         if (tx.begin != 0 && tx.end != 0)
204         {
205           sq.addSequenceFeature(tx);
206         }
207       }
208     }
209     return features;
210   }
211
212   /**
213    * Traverses the list of residues and constructs bonds where CA-to-CA atoms or
214    * P-to-P atoms are found. Also sets the 'isNa' flag if more than 99% of
215    * residues contain a P not a CA.
216    */
217   public void makeCaBondList()
218   {
219     boolean na = false;
220     int numNa = 0;
221     for (int i = 0; i < (residues.size() - 1); i++)
222     {
223       Residue tmpres = residues.elementAt(i);
224       Residue tmpres2 = residues.elementAt(i + 1);
225       Atom at1 = tmpres.findAtom("CA");
226       Atom at2 = tmpres2.findAtom("CA");
227       na = false;
228       if ((at1 == null) && (at2 == null))
229       {
230         na = true;
231         at1 = tmpres.findAtom("P");
232         at2 = tmpres2.findAtom("P");
233       }
234       if ((at1 != null) && (at2 != null))
235       {
236         if (at1.chain.equals(at2.chain))
237         {
238           if (na)
239           {
240             numNa++;
241           }
242           makeBond(at1, at2);
243         }
244       }
245       else
246       {
247         System.out.println("not found " + i);
248       }
249     }
250
251     /*
252      * If > 99% 'P', flag as nucleotide; note the count doesn't include the last
253      * residue
254      */
255     if (residues.size() > 0 && (numNa / (residues.size() - 1) > 0.99))
256     {
257       isNa = true;
258     }
259   }
260
261   /**
262    * Construct a bond from atom1 to atom2 and add it to the list of bonds for
263    * this chain
264    * 
265    * @param at1
266    * @param at2
267    */
268   public void makeBond(Atom at1, Atom at2)
269   {
270     bonds.addElement(new Bond(at1, at2));
271   }
272
273   /**
274    * Traverses the list of atoms and
275    * <ul>
276    * <li>constructs a list of Residues, each containing all the atoms that share
277    * the same residue number</li>
278    * <li>adds a RESNUM sequence feature for each position</li>
279    * <li>creates the sequence string</li>
280    * <li>determines if nucleotide</li>
281    * <li>saves the residue number of the first atom as 'offset'</li>
282    * <li>adds temp factor annotation if the flag is set to do so</li>
283    * </ul>
284    * 
285    * @param visibleChainAnnotation
286    */
287   public void makeResidueList(boolean visibleChainAnnotation)
288   {
289     int count = 0;
290     Object symbol;
291     boolean deoxyn = false;
292     boolean nucleotide = false;
293     StringBuilder seq = new StringBuilder(256);
294     Vector<SequenceFeature> resFeatures = new Vector<SequenceFeature>();
295     Vector<Annotation> resAnnotation = new Vector<Annotation>();
296     int i, iSize = atoms.size() - 1;
297     int resNumber = -1;
298     for (i = 0; i <= iSize; i++)
299     {
300       Atom tmp = atoms.elementAt(i);
301       resNumber = tmp.resNumber;
302       int res = resNumber;
303
304       if (i == 0)
305       {
306         offset = resNumber;
307       }
308
309       Vector<Atom> resAtoms = new Vector<Atom>();
310       // Add atoms to a vector while the residue number
311       // remains the same as the first atom's resNumber (res)
312       while ((resNumber == res) && (i < atoms.size()))
313       {
314         resAtoms.add(atoms.elementAt(i));
315         i++;
316
317         if (i < atoms.size())
318         {
319           resNumber = atoms.elementAt(i).resNumber;
320         }
321         else
322         {
323           resNumber++;
324         }
325       }
326
327       // We need this to keep in step with the outer for i = loop
328       i--;
329
330       // Make a new Residue object with the new atoms vector
331       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
332
333       Residue tmpres = residues.lastElement();
334       Atom tmpat = tmpres.atoms.get(0);
335       // Make A new SequenceFeature for the current residue numbering
336       SequenceFeature sf = new SequenceFeature("RESNUM", tmpat.resName
337               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
338               + count, offset + count, pdbid);
339       // MCview.PDBChain.PDBFILEFEATURE);
340       resFeatures.addElement(sf);
341       resAnnotation.addElement(new Annotation(tmpat.tfactor));
342       // Keep totting up the sequence
343       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
344       {
345         String nucname = tmpat.resName.trim();
346         // use the aaIndex rather than call 'toLower' - which would take a bit
347         // more time.
348         deoxyn = nucname.length() == 2
349                 && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
350         if (tmpat.name.equalsIgnoreCase("CA")
351                 || ResidueProperties.nucleotideIndex[nucname
352                         .charAt((deoxyn ? 1 : 0))] == -1)
353         {
354           seq.append("X");
355           // System.err.println("PDBReader:Null aa3Hash for " +
356           // tmpat.resName);
357         }
358         else
359         {
360           // nucleotide flag
361           nucleotide = true;
362           seq.append(nucname.charAt((deoxyn ? 1 : 0)));
363         }
364       }
365       else
366       {
367         if (nucleotide)
368         {
369           System.err
370                   .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
371         }
372         seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
373       }
374       count++;
375     }
376
377     if (id.length() < 1)
378     {
379       id = " ";
380     }
381     isNa = nucleotide;
382     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
383     // resNumber-offset
384     // ~=
385     // seq.size()
386     // Add normalised feature scores to RESNUM indicating start/end of sequence
387     // sf.setScore(offset+count);
388
389     // System.out.println("PDB Sequence is :\nSequence = " + seq);
390     // System.out.println("No of residues = " + residues.size());
391     for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
392     {
393       sequence.addSequenceFeature(resFeatures.elementAt(i));
394       resFeatures.setElementAt(null, i);
395     }
396     if (visibleChainAnnotation)
397     {
398       Annotation[] annots = new Annotation[resAnnotation.size()];
399       float max = 0;
400       for (i = 0, iSize = annots.length; i < iSize; i++)
401       {
402         annots[i] = resAnnotation.elementAt(i);
403         if (annots[i].value > max)
404         {
405           max = annots[i].value;
406         }
407         resAnnotation.setElementAt(null, i);
408       }
409
410       AlignmentAnnotation tfactorann = new AlignmentAnnotation(
411               "Temperature Factor", "Temperature Factor for " + pdbid + id,
412               annots, 0, max, AlignmentAnnotation.LINE_GRAPH);
413       tfactorann.setSequenceRef(sequence);
414       sequence.addAlignmentAnnotation(tfactorann);
415     }
416   }
417
418   /**
419    * Colour start/end of bonds by charge
420    * <ul>
421    * <li>ASP and GLU red</li>
422    * <li>LYS and ARG blue</li>
423    * <li>CYS yellow</li>
424    * <li>others light gray</li>
425    * </ul>
426    */
427   public void setChargeColours()
428   {
429     for (Bond b : bonds)
430     {
431       if (b.at1 != null && b.at2 != null)
432       {
433         b.startCol = getChargeColour(b.at1.resName);
434         b.endCol = getChargeColour(b.at2.resName);
435       }
436       else
437       {
438         b.startCol = Color.gray;
439         b.endCol = Color.gray;
440       }
441     }
442   }
443
444   public static Color getChargeColour(String resName)
445   {
446     Color result = Color.lightGray;
447     if ("ASP".equals(resName) || "GLU".equals(resName))
448     {
449       result = Color.red;
450     }
451     else if ("LYS".equals(resName) || "ARG".equals(resName))
452     {
453       result = Color.blue;
454     }
455     else if ("CYS".equals(resName))
456     {
457       result = Color.yellow;
458     }
459     return result;
460   }
461
462   /**
463    * Sets the start/end colours of bonds to those of the start/end atoms
464    * according to the specified colour scheme. Note: currently only works for
465    * peptide residues.
466    * 
467    * @param cs
468    */
469   public void setChainColours(ColourSchemeI cs)
470   {
471     int index;
472     for (Bond b : bonds)
473     {
474       try
475       {
476         index = ResidueProperties.aa3Hash.get(b.at1.resName).intValue();
477         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
478
479         index = ResidueProperties.aa3Hash.get(b.at2.resName).intValue();
480         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
481
482       } catch (Exception e)
483       {
484         b.startCol = Color.gray;
485         b.endCol = Color.gray;
486       }
487     }
488   }
489
490   public void setChainColours(Color col)
491   {
492     for (Bond b : bonds)
493     {
494       b.startCol = col;
495       b.endCol = col;
496     }
497   }
498
499   /**
500    * copy any sequence annotation onto the sequence mapped using the provided
501    * StructureMapping
502    * 
503    * @param mapping
504    *          - positional mapping between destination sequence and pdb resnum
505    * @param sqmpping
506    *          - mapping between destination sequence and local chain
507    */
508   public void transferResidueAnnotation(StructureMapping mapping,
509           jalview.datamodel.Mapping sqmpping)
510   {
511     SequenceI sq = mapping.getSequence();
512     SequenceI dsq = sq;
513     if (sq != null)
514     {
515       while (dsq.getDatasetSequence() != null)
516       {
517         dsq = dsq.getDatasetSequence();
518       }
519       // any annotation will be transferred onto the dataset sequence
520
521       if (shadow != null && shadow.getAnnotation() != null)
522       {
523
524         for (AlignmentAnnotation ana : shadow.getAnnotation())
525         {
526           List<AlignmentAnnotation> transfer = sq.getAlignmentAnnotations(
527                   ana.getCalcId(), ana.label);
528           if (transfer == null || transfer.size() == 0)
529           {
530             ana = new AlignmentAnnotation(ana);
531             ana.liftOver(sequence, shadowMap);
532             ana.liftOver(dsq, sqmpping);
533             dsq.addAlignmentAnnotation(ana);
534           }
535           else
536           {
537             continue;
538           }
539         }
540       }
541       else
542       {
543         if (sequence != null && sequence.getAnnotation() != null)
544         {
545           for (AlignmentAnnotation ana : sequence.getAnnotation())
546           {
547             List<AlignmentAnnotation> transfer = sq
548                     .getAlignmentAnnotations(ana.getCalcId(), ana.label);
549             if (transfer == null || transfer.size() == 0)
550             {
551               ana = new AlignmentAnnotation(ana);
552               ana.liftOver(dsq, sqmpping);
553               // mapping.transfer(ana);
554             }
555             else
556             {
557               continue;
558             }
559           }
560         }
561       }
562       if (false)
563       {
564         // Useful for debugging mappings - adds annotation for mapped position
565         float min = -1, max = 0;
566         Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
567         for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
568         {
569           int prn = mapping.getPDBResNum(k + 1);
570
571           an[k] = new Annotation(prn);
572           if (min == -1)
573           {
574             min = k;
575             max = k;
576           }
577           else
578           {
579             if (min > k)
580             {
581               min = k;
582             }
583             else if (max < k)
584             {
585               max = k;
586             }
587           }
588         }
589         sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
590                 "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
591                 an, min, max, AlignmentAnnotation.LINE_GRAPH));
592       }
593     }
594   }
595 }