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