e4e619c577052c6a7a0803760c994c33af058f92
[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() > 1 && (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     char insCode = ' ';
299     for (i = 0; i <= iSize; i++)
300     {
301       Atom tmp = atoms.elementAt(i);
302       resNumber = tmp.resNumber;
303       insCode = tmp.insCode;
304
305       int res = resNumber;
306       char ins = insCode;
307
308       if (i == 0)
309       {
310         offset = resNumber;
311       }
312
313       Vector<Atom> resAtoms = new Vector<Atom>();
314       // Add atoms to a vector while the residue number
315       // remains the same as the first atom's resNumber (res)
316       while ((resNumber == res) && (ins == insCode) && (i < atoms.size()))
317       {
318         resAtoms.add(atoms.elementAt(i));
319         i++;
320
321         if (i < atoms.size())
322         {
323           resNumber = atoms.elementAt(i).resNumber;
324           insCode = atoms.elementAt(i).insCode;
325         }
326         else
327         {
328           resNumber++;
329         }
330       }
331
332       // We need this to keep in step with the outer for i = loop
333       i--;
334
335       // Add inserted residues as features to the base residue
336       Atom currAtom = resAtoms.get(0);
337       if (currAtom.insCode != ' '
338               && residues.lastElement().atoms.get(0).resNumber == currAtom.resNumber)
339       {
340         SequenceFeature sf = new SequenceFeature("INSERTION",
341                 currAtom.resName + ":" + currAtom.resNumIns + " " + pdbid
342                         + id, "", offset + count - 1, offset + count - 1,
343                 "PDB_INS");
344         resFeatures.addElement(sf);
345         residues.lastElement().atoms.addAll(resAtoms);
346       }
347       else
348       {
349
350       // Make a new Residue object with the new atoms vector
351       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
352
353       Residue tmpres = residues.lastElement();
354       Atom tmpat = tmpres.atoms.get(0);
355       // Make A new SequenceFeature for the current residue numbering
356         SequenceFeature sf = new SequenceFeature("RES NUM", tmpat.resName
357               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
358               + count, offset + count, pdbid);
359       // MCview.PDBChain.PDBFILEFEATURE);
360       resFeatures.addElement(sf);
361       resAnnotation.addElement(new Annotation(tmpat.tfactor));
362       // Keep totting up the sequence
363       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
364       {
365         String nucname = tmpat.resName.trim();
366         // use the aaIndex rather than call 'toLower' - which would take a bit
367         // more time.
368         deoxyn = nucname.length() == 2
369                 && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
370         if (tmpat.name.equalsIgnoreCase("CA")
371                 || ResidueProperties.nucleotideIndex[nucname
372                         .charAt((deoxyn ? 1 : 0))] == -1)
373         {
374           seq.append("X");
375           // System.err.println("PDBReader:Null aa3Hash for " +
376           // tmpat.resName);
377         }
378         else
379         {
380           // nucleotide flag
381           nucleotide = true;
382           seq.append(nucname.charAt((deoxyn ? 1 : 0)));
383         }
384       }
385       else
386       {
387         if (nucleotide)
388         {
389           System.err
390                   .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
391         }
392         seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
393       }
394         count++;
395       }
396     }
397
398     if (id.length() < 1)
399     {
400       id = " ";
401     }
402     isNa = nucleotide;
403     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
404     // resNumber-offset
405     // ~=
406     // seq.size()
407     // Add normalised feature scores to RESNUM indicating start/end of sequence
408     // sf.setScore(offset+count);
409
410     // System.out.println("PDB Sequence is :\nSequence = " + seq);
411     // System.out.println("No of residues = " + residues.size());
412     for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
413     {
414       sequence.addSequenceFeature(resFeatures.elementAt(i));
415       resFeatures.setElementAt(null, i);
416     }
417     if (visibleChainAnnotation)
418     {
419       Annotation[] annots = new Annotation[resAnnotation.size()];
420       float max = 0;
421       for (i = 0, iSize = annots.length; i < iSize; i++)
422       {
423         annots[i] = resAnnotation.elementAt(i);
424         if (annots[i].value > max)
425         {
426           max = annots[i].value;
427         }
428         resAnnotation.setElementAt(null, i);
429       }
430
431       AlignmentAnnotation tfactorann = new AlignmentAnnotation(
432               "Temperature Factor", "Temperature Factor for " + pdbid + id,
433               annots, 0, max, AlignmentAnnotation.LINE_GRAPH);
434       tfactorann.setSequenceRef(sequence);
435       sequence.addAlignmentAnnotation(tfactorann);
436     }
437   }
438
439   /**
440    * Colour start/end of bonds by charge
441    * <ul>
442    * <li>ASP and GLU red</li>
443    * <li>LYS and ARG blue</li>
444    * <li>CYS yellow</li>
445    * <li>others light gray</li>
446    * </ul>
447    */
448   public void setChargeColours()
449   {
450     for (Bond b : bonds)
451     {
452       if (b.at1 != null && b.at2 != null)
453       {
454         b.startCol = getChargeColour(b.at1.resName);
455         b.endCol = getChargeColour(b.at2.resName);
456       }
457       else
458       {
459         b.startCol = Color.gray;
460         b.endCol = Color.gray;
461       }
462     }
463   }
464
465   public static Color getChargeColour(String resName)
466   {
467     Color result = Color.lightGray;
468     if ("ASP".equals(resName) || "GLU".equals(resName))
469     {
470       result = Color.red;
471     }
472     else if ("LYS".equals(resName) || "ARG".equals(resName))
473     {
474       result = Color.blue;
475     }
476     else if ("CYS".equals(resName))
477     {
478       result = Color.yellow;
479     }
480     return result;
481   }
482
483   /**
484    * Sets the start/end colours of bonds to those of the start/end atoms
485    * according to the specified colour scheme. Note: currently only works for
486    * peptide residues.
487    * 
488    * @param cs
489    */
490   public void setChainColours(ColourSchemeI cs)
491   {
492     int index;
493     for (Bond b : bonds)
494     {
495       try
496       {
497         index = ResidueProperties.aa3Hash.get(b.at1.resName).intValue();
498         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
499
500         index = ResidueProperties.aa3Hash.get(b.at2.resName).intValue();
501         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
502
503       } catch (Exception e)
504       {
505         b.startCol = Color.gray;
506         b.endCol = Color.gray;
507       }
508     }
509   }
510
511   public void setChainColours(Color col)
512   {
513     for (Bond b : bonds)
514     {
515       b.startCol = col;
516       b.endCol = col;
517     }
518   }
519
520   /**
521    * copy any sequence annotation onto the sequence mapped using the provided
522    * StructureMapping
523    * 
524    * @param mapping
525    *          - positional mapping between destination sequence and pdb resnum
526    * @param sqmpping
527    *          - mapping between destination sequence and local chain
528    */
529   public void transferResidueAnnotation(StructureMapping mapping,
530           jalview.datamodel.Mapping sqmpping)
531   {
532     SequenceI sq = mapping.getSequence();
533     SequenceI dsq = sq;
534     if (sq != null)
535     {
536       while (dsq.getDatasetSequence() != null)
537       {
538         dsq = dsq.getDatasetSequence();
539       }
540       // any annotation will be transferred onto the dataset sequence
541
542       if (shadow != null && shadow.getAnnotation() != null)
543       {
544
545         for (AlignmentAnnotation ana : shadow.getAnnotation())
546         {
547           List<AlignmentAnnotation> transfer = sq.getAlignmentAnnotations(
548                   ana.getCalcId(), ana.label);
549           if (transfer == null || transfer.size() == 0)
550           {
551             ana = new AlignmentAnnotation(ana);
552             ana.liftOver(sequence, shadowMap);
553             ana.liftOver(dsq, sqmpping);
554             dsq.addAlignmentAnnotation(ana);
555           }
556           else
557           {
558             continue;
559           }
560         }
561       }
562       else
563       {
564         if (sequence != null && sequence.getAnnotation() != null)
565         {
566           for (AlignmentAnnotation ana : sequence.getAnnotation())
567           {
568             List<AlignmentAnnotation> transfer = sq
569                     .getAlignmentAnnotations(ana.getCalcId(), ana.label);
570             if (transfer == null || transfer.size() == 0)
571             {
572               ana = new AlignmentAnnotation(ana);
573               ana.liftOver(dsq, sqmpping);
574               // mapping.transfer(ana);
575             }
576             else
577             {
578               continue;
579             }
580           }
581         }
582       }
583       if (false)
584       {
585         // Useful for debugging mappings - adds annotation for mapped position
586         float min = -1, max = 0;
587         Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
588         for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
589         {
590           int prn = mapping.getPDBResNum(k + 1);
591
592           an[k] = new Annotation(prn);
593           if (min == -1)
594           {
595             min = k;
596             max = k;
597           }
598           else
599           {
600             if (min > k)
601             {
602               min = k;
603             }
604             else if (max < k)
605             {
606               max = k;
607             }
608           }
609         }
610         sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
611                 "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
612                 an, min, max, AlignmentAnnotation.LINE_GRAPH));
613       }
614     }
615   }
616 }