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