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