develop merge
[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         if (pdbpos >= residues.size())
152         {
153           continue;
154         }
155         Residue res = residues.elementAt(pdbpos);
156         for (Atom atom : res.atoms)
157         {
158           atom.alignmentMapping = alignpos;
159         }
160       }
161     }
162   }
163
164   /**
165    * copy over the RESNUM seqfeatures from the internal chain sequence to the
166    * mapped sequence
167    * 
168    * @param seq
169    * @param status
170    *          The Status of the transferred annotation
171    * @return the features added to sq (or its dataset)
172    */
173   public SequenceFeature[] transferRESNUMFeatures(SequenceI seq,
174           String status)
175   {
176     SequenceI sq = seq;
177     while (sq != null && sq.getDatasetSequence() != null)
178     {
179       sq = sq.getDatasetSequence();
180       if (sq == sequence)
181       {
182         return null;
183       }
184     }
185     /**
186      * Remove any existing features for this chain if they exist ?
187      * SequenceFeature[] seqsfeatures=seq.getSequenceFeatures(); int
188      * totfeat=seqsfeatures.length; // Remove any features for this exact chain
189      * ? for (int i=0; i<seqsfeatures.length; i++) { }
190      */
191     if (status == null)
192     {
193       status = PDBChain.IEASTATUS;
194     }
195     SequenceFeature[] features = sequence.getSequenceFeatures();
196     for (int i = 0; i < features.length; i++)
197     {
198       if (features[i].getFeatureGroup().equals(pdbid))
199       {
200         SequenceFeature tx = new SequenceFeature(features[i]);
201         tx.setBegin(1 + residues.elementAt(tx.getBegin() - offset).atoms
202                 .elementAt(0).alignmentMapping);
203         tx.setEnd(1 + residues.elementAt(tx.getEnd() - offset).atoms
204                 .elementAt(0).alignmentMapping);
205         tx.setStatus(status
206                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
207                         : ":" + tx.getStatus()));
208         if (tx.begin != 0 && tx.end != 0)
209         {
210           sq.addSequenceFeature(tx);
211         }
212       }
213     }
214     return features;
215   }
216
217   /**
218    * Traverses the list of residues and constructs bonds where CA-to-CA atoms or
219    * P-to-P atoms are found. Also sets the 'isNa' flag if more than 99% of
220    * residues contain a P not a CA.
221    */
222   public void makeCaBondList()
223   {
224     boolean na = false;
225     int numNa = 0;
226     for (int i = 0; i < (residues.size() - 1); i++)
227     {
228       Residue tmpres = residues.elementAt(i);
229       Residue tmpres2 = residues.elementAt(i + 1);
230       Atom at1 = tmpres.findAtom("CA");
231       Atom at2 = tmpres2.findAtom("CA");
232       na = false;
233       if ((at1 == null) && (at2 == null))
234       {
235         na = true;
236         at1 = tmpres.findAtom("P");
237         at2 = tmpres2.findAtom("P");
238       }
239       if ((at1 != null) && (at2 != null))
240       {
241         if (at1.chain.equals(at2.chain))
242         {
243           if (na)
244           {
245             numNa++;
246           }
247           makeBond(at1, at2);
248         }
249       }
250       else
251       {
252         System.out.println("not found " + i);
253       }
254     }
255
256     /*
257      * If > 99% 'P', flag as nucleotide; note the count doesn't include the last
258      * residue
259      */
260     if (residues.size() > 1 && (numNa / (residues.size() - 1) > 0.99))
261     {
262       isNa = true;
263     }
264   }
265
266   /**
267    * Construct a bond from atom1 to atom2 and add it to the list of bonds for
268    * this chain
269    * 
270    * @param at1
271    * @param at2
272    */
273   public void makeBond(Atom at1, Atom at2)
274   {
275     bonds.addElement(new Bond(at1, at2));
276   }
277
278   /**
279    * Traverses the list of atoms and
280    * <ul>
281    * <li>constructs a list of Residues, each containing all the atoms that share
282    * the same residue number</li>
283    * <li>adds a RESNUM sequence feature for each position</li>
284    * <li>creates the sequence string</li>
285    * <li>determines if nucleotide</li>
286    * <li>saves the residue number of the first atom as 'offset'</li>
287    * <li>adds temp factor annotation if the flag is set to do so</li>
288    * </ul>
289    * 
290    * @param visibleChainAnnotation
291    */
292   public void makeResidueList(boolean visibleChainAnnotation)
293   {
294     int count = 0;
295     Object symbol;
296     boolean deoxyn = false;
297     boolean nucleotide = false;
298     StringBuilder seq = new StringBuilder(256);
299     Vector<SequenceFeature> resFeatures = new Vector<SequenceFeature>();
300     Vector<Annotation> resAnnotation = new Vector<Annotation>();
301     int i, iSize = atoms.size() - 1;
302     int resNumber = -1;
303     char insCode = ' ';
304     for (i = 0; i <= iSize; i++)
305     {
306       Atom tmp = atoms.elementAt(i);
307       resNumber = tmp.resNumber;
308       insCode = tmp.insCode;
309
310       int res = resNumber;
311       char ins = insCode;
312
313       if (i == 0)
314       {
315         offset = resNumber;
316       }
317
318       Vector<Atom> resAtoms = new Vector<Atom>();
319       // Add atoms to a vector while the residue number
320       // remains the same as the first atom's resNumber (res)
321       while ((resNumber == res) && (ins == insCode) && (i < atoms.size()))
322       {
323         resAtoms.add(atoms.elementAt(i));
324         i++;
325
326         if (i < atoms.size())
327         {
328           resNumber = atoms.elementAt(i).resNumber;
329           insCode = atoms.elementAt(i).insCode;
330         }
331         else
332         {
333           resNumber++;
334         }
335       }
336
337       // We need this to keep in step with the outer for i = loop
338       i--;
339
340       // Add inserted residues as features to the base residue
341       Atom currAtom = resAtoms.get(0);
342       if (currAtom.insCode != ' '
343               && !residues.isEmpty()
344               && residues.lastElement().atoms.get(0).resNumber == currAtom.resNumber)
345       {
346         SequenceFeature sf = new SequenceFeature("INSERTION",
347                 currAtom.resName + ":" + currAtom.resNumIns + " " + pdbid
348                         + id, "", offset + count - 1, offset + count - 1,
349                 "PDB_INS");
350         resFeatures.addElement(sf);
351         residues.lastElement().atoms.addAll(resAtoms);
352       }
353       else
354       {
355
356         // boolean baseDetected = false;
357         // for (Atom resAtom : resAtoms)
358         // {
359         // if (resAtom.insCode == ' ')
360         // {
361         // baseDetected = true;
362         // }
363         // }
364         // if (!baseDetected)
365         // {
366         // continue;
367         // }
368       // Make a new Residue object with the new atoms vector
369       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
370
371       Residue tmpres = residues.lastElement();
372       Atom tmpat = tmpres.atoms.get(0);
373       // Make A new SequenceFeature for the current residue numbering
374         SequenceFeature sf = new SequenceFeature("RESNUM", tmpat.resName
375               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
376               + count, offset + count, pdbid);
377       // MCview.PDBChain.PDBFILEFEATURE);
378       resFeatures.addElement(sf);
379       resAnnotation.addElement(new Annotation(tmpat.tfactor));
380       // Keep totting up the sequence
381
382       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
383       {
384         String nucname = tmpat.resName.trim();
385         // use the aaIndex rather than call 'toLower' - which would take a bit
386         // more time.
387         deoxyn = nucname.length() == 2
388                 && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
389         if (tmpat.name.equalsIgnoreCase("CA")
390                 || ResidueProperties.nucleotideIndex[nucname
391                         .charAt((deoxyn ? 1 : 0))] == -1)
392         {
393           seq.append("X");
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 (StructureViewSettings.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
523         index = ResidueProperties.aa3Hash.get(b.at2.resName).intValue();
524         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
525
526       } catch (Exception e)
527       {
528         b.startCol = Color.gray;
529         b.endCol = Color.gray;
530       }
531     }
532   }
533
534   public void setChainColours(Color col)
535   {
536     for (Bond b : bonds)
537     {
538       b.startCol = col;
539       b.endCol = col;
540     }
541   }
542
543   /**
544    * copy any sequence annotation onto the sequence mapped using the provided
545    * StructureMapping
546    * 
547    * @param mapping
548    *          - positional mapping between destination sequence and pdb resnum
549    * @param sqmpping
550    *          - mapping between destination sequence and local chain
551    */
552   public void transferResidueAnnotation(StructureMapping mapping,
553           jalview.datamodel.Mapping sqmpping)
554   {
555     SequenceI sq = mapping.getSequence();
556     SequenceI dsq = sq;
557     if (sq != null)
558     {
559       while (dsq.getDatasetSequence() != null)
560       {
561         dsq = dsq.getDatasetSequence();
562       }
563       // any annotation will be transferred onto the dataset sequence
564
565       if (shadow != null && shadow.getAnnotation() != null)
566       {
567
568         for (AlignmentAnnotation ana : shadow.getAnnotation())
569         {
570           List<AlignmentAnnotation> transfer = sq.getAlignmentAnnotations(
571                   ana.getCalcId(), ana.label);
572           if (transfer == null || transfer.size() == 0)
573           {
574             ana = new AlignmentAnnotation(ana);
575             ana.liftOver(sequence, shadowMap);
576             ana.liftOver(dsq, sqmpping);
577             dsq.addAlignmentAnnotation(ana);
578           }
579           else
580           {
581             continue;
582           }
583         }
584       }
585       else
586       {
587         if (sequence != null && sequence.getAnnotation() != null)
588         {
589           for (AlignmentAnnotation ana : sequence.getAnnotation())
590           {
591             List<AlignmentAnnotation> transfer = sq
592                     .getAlignmentAnnotations(ana.getCalcId(), ana.label);
593             if (transfer == null || transfer.size() == 0)
594             {
595               ana = new AlignmentAnnotation(ana);
596               ana.liftOver(dsq, sqmpping);
597               // mapping.transfer(ana);
598             }
599             else
600             {
601               continue;
602             }
603           }
604         }
605       }
606       if (false)
607       {
608         // Useful for debugging mappings - adds annotation for mapped position
609         float min = -1, max = 0;
610         Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
611         for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
612         {
613           int prn = mapping.getPDBResNum(k + 1);
614
615           an[k] = new Annotation(prn);
616           if (min == -1)
617           {
618             min = k;
619             max = k;
620           }
621           else
622           {
623             if (min > k)
624             {
625               min = k;
626             }
627             else if (max < k)
628             {
629               max = k;
630             }
631           }
632         }
633         sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
634                 "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
635                 an, min, max, AlignmentAnnotation.LINE_GRAPH));
636       }
637     }
638   }
639 }