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