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