ef86cfd647d2191b71f606410aea9e34cb2fa337
[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       SequenceFeature feature = features[i];
208       if (feature.getFeatureGroup() != null
209               && feature.getFeatureGroup().equals(pdbid))
210       {
211         int newBegin = 1 + residues.elementAt(feature.getBegin() - offset).atoms
212                 .elementAt(0).alignmentMapping;
213         int newEnd = 1 + residues.elementAt(feature.getEnd() - offset).atoms
214                 .elementAt(0).alignmentMapping;
215         SequenceFeature tx = new SequenceFeature(feature, newBegin, newEnd,
216                 feature.getFeatureGroup(), feature.getScore());
217         tx.setStatus(status
218                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
219                         : ":" + tx.getStatus()));
220         if (tx.begin != 0 && tx.end != 0)
221         {
222           sq.addSequenceFeature(tx);
223         }
224       }
225     }
226     return features;
227   }
228
229   /**
230    * Traverses the list of residues and constructs bonds where CA-to-CA atoms or
231    * P-to-P atoms are found. Also sets the 'isNa' flag if more than 99% of
232    * residues contain a P not a CA.
233    */
234   public void makeCaBondList()
235   {
236     boolean na = false;
237     int numNa = 0;
238     for (int i = 0; i < (residues.size() - 1); i++)
239     {
240       Residue tmpres = residues.elementAt(i);
241       Residue tmpres2 = residues.elementAt(i + 1);
242       Atom at1 = tmpres.findAtom("CA");
243       Atom at2 = tmpres2.findAtom("CA");
244       na = false;
245       if ((at1 == null) && (at2 == null))
246       {
247         na = true;
248         at1 = tmpres.findAtom("P");
249         at2 = tmpres2.findAtom("P");
250       }
251       if ((at1 != null) && (at2 != null))
252       {
253         if (at1.chain.equals(at2.chain))
254         {
255           if (na)
256           {
257             numNa++;
258           }
259           makeBond(at1, at2);
260         }
261       }
262       else
263       {
264         System.out.println("not found " + i);
265       }
266     }
267
268     /*
269      * If > 99% 'P', flag as nucleotide; note the count doesn't include the last
270      * residue
271      */
272     if (residues.size() > 1 && (numNa / (residues.size() - 1) > 0.99))
273     {
274       isNa = true;
275     }
276   }
277
278   /**
279    * Construct a bond from atom1 to atom2 and add it to the list of bonds for
280    * this chain
281    * 
282    * @param at1
283    * @param at2
284    */
285   public void makeBond(Atom at1, Atom at2)
286   {
287     bonds.addElement(new Bond(at1, at2));
288   }
289
290   /**
291    * Traverses the list of atoms and
292    * <ul>
293    * <li>constructs a list of Residues, each containing all the atoms that share
294    * the same residue number</li>
295    * <li>adds a RESNUM sequence feature for each position</li>
296    * <li>creates the sequence string</li>
297    * <li>determines if nucleotide</li>
298    * <li>saves the residue number of the first atom as 'offset'</li>
299    * <li>adds temp factor annotation if the flag is set to do so</li>
300    * </ul>
301    * 
302    * @param visibleChainAnnotation
303    */
304   public void makeResidueList(boolean visibleChainAnnotation)
305   {
306     int count = 0;
307     Object symbol;
308     boolean deoxyn = false;
309     boolean nucleotide = false;
310     StringBuilder seq = new StringBuilder(256);
311     Vector<SequenceFeature> resFeatures = new Vector<SequenceFeature>();
312     Vector<Annotation> resAnnotation = new Vector<Annotation>();
313     int i, iSize = atoms.size() - 1;
314     int resNumber = -1;
315     char insCode = ' ';
316     for (i = 0; i <= iSize; i++)
317     {
318       Atom tmp = atoms.elementAt(i);
319       resNumber = tmp.resNumber;
320       insCode = tmp.insCode;
321
322       int res = resNumber;
323       char ins = insCode;
324
325       if (i == 0)
326       {
327         offset = resNumber;
328       }
329
330       Vector<Atom> resAtoms = new Vector<Atom>();
331       // Add atoms to a vector while the residue number
332       // remains the same as the first atom's resNumber (res)
333       while ((resNumber == res) && (ins == insCode) && (i < atoms.size()))
334       {
335         resAtoms.add(atoms.elementAt(i));
336         i++;
337
338         if (i < atoms.size())
339         {
340           resNumber = atoms.elementAt(i).resNumber;
341           insCode = atoms.elementAt(i).insCode;
342         }
343         else
344         {
345           resNumber++;
346         }
347       }
348
349       // We need this to keep in step with the outer for i = loop
350       i--;
351
352       // Add inserted residues as features to the base residue
353       Atom currAtom = resAtoms.get(0);
354       if (currAtom.insCode != ' '
355               && !residues.isEmpty()
356               && residues.lastElement().atoms.get(0).resNumber == currAtom.resNumber)
357       {
358         String desc = currAtom.resName + ":" + currAtom.resNumIns + " "
359                 + pdbid + id;
360         SequenceFeature sf = new SequenceFeature("INSERTION", desc, offset
361                 + count - 1, offset + count - 1, "PDB_INS");
362         resFeatures.addElement(sf);
363         residues.lastElement().atoms.addAll(resAtoms);
364       }
365       else
366       {
367         // Make a new Residue object with the new atoms vector
368         residues.addElement(new Residue(resAtoms, resNumber - 1, count));
369
370         Residue tmpres = residues.lastElement();
371         Atom tmpat = tmpres.atoms.get(0);
372         // Make A new SequenceFeature for the current residue numbering
373         String desc = tmpat.resName
374                 + ":" + tmpat.resNumIns + " " + pdbid + id;
375         SequenceFeature sf = new SequenceFeature(RESNUM_FEATURE, desc,
376                 offset + count, offset + count, pdbid);
377         resFeatures.addElement(sf);
378         resAnnotation.addElement(new Annotation(tmpat.tfactor));
379         // Keep totting up the sequence
380
381         if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
382         {
383           String nucname = tmpat.resName.trim();
384           // use the aaIndex rather than call 'toLower' - which would take a bit
385           // more time.
386           deoxyn = nucname.length() == 2
387                   && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
388           if (tmpat.name.equalsIgnoreCase("CA")
389                   || ResidueProperties.nucleotideIndex[nucname
390                           .charAt((deoxyn ? 1 : 0))] == -1)
391           {
392             char r = ResidueProperties
393                     .getSingleCharacterCode(ResidueProperties
394                             .getCanonicalAminoAcid(tmpat.resName));
395             seq.append(r == '0' ? 'X' : r);
396             // System.err.println("PDBReader:Null aa3Hash for " +
397             // tmpat.resName);
398           }
399           else
400           {
401             // nucleotide flag
402             nucleotide = true;
403             seq.append(nucname.charAt((deoxyn ? 1 : 0)));
404           }
405         }
406         else
407         {
408           if (nucleotide)
409           {
410             System.err
411                     .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
412           }
413           seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
414         }
415         count++;
416       }
417     }
418
419     if (id.length() < 1)
420     {
421       id = " ";
422     }
423     isNa = nucleotide;
424     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
425     // resNumber-offset
426     // ~=
427     // seq.size()
428     // Add normalised feature scores to RESNUM indicating start/end of sequence
429     // sf.setScore(offset+count);
430
431     // System.out.println("PDB Sequence is :\nSequence = " + seq);
432     // System.out.println("No of residues = " + residues.size());
433
434     if (StructureImportSettings.isShowSeqFeatures())
435     {
436       for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
437       {
438         sequence.addSequenceFeature(resFeatures.elementAt(i));
439         resFeatures.setElementAt(null, i);
440       }
441     }
442     if (visibleChainAnnotation)
443     {
444       Annotation[] annots = new Annotation[resAnnotation.size()];
445       float max = 0;
446       for (i = 0, iSize = annots.length; i < iSize; i++)
447       {
448         annots[i] = resAnnotation.elementAt(i);
449         if (annots[i].value > max)
450         {
451           max = annots[i].value;
452         }
453         resAnnotation.setElementAt(null, i);
454       }
455
456       AlignmentAnnotation tfactorann = new AlignmentAnnotation(
457               "Temperature Factor", "Temperature Factor for " + pdbid + id,
458               annots, 0, max, AlignmentAnnotation.LINE_GRAPH);
459       tfactorann.setSequenceRef(sequence);
460       sequence.addAlignmentAnnotation(tfactorann);
461     }
462   }
463
464   /**
465    * Colour start/end of bonds by charge
466    * <ul>
467    * <li>ASP and GLU red</li>
468    * <li>LYS and ARG blue</li>
469    * <li>CYS yellow</li>
470    * <li>others light gray</li>
471    * </ul>
472    */
473   public void setChargeColours()
474   {
475     for (Bond b : bonds)
476     {
477       if (b.at1 != null && b.at2 != null)
478       {
479         b.startCol = getChargeColour(b.at1.resName);
480         b.endCol = getChargeColour(b.at2.resName);
481       }
482       else
483       {
484         b.startCol = Color.gray;
485         b.endCol = Color.gray;
486       }
487     }
488   }
489
490   public static Color getChargeColour(String resName)
491   {
492     Color result = Color.lightGray;
493     if ("ASP".equals(resName) || "GLU".equals(resName))
494     {
495       result = Color.red;
496     }
497     else if ("LYS".equals(resName) || "ARG".equals(resName))
498     {
499       result = Color.blue;
500     }
501     else if ("CYS".equals(resName))
502     {
503       result = Color.yellow;
504     }
505     return result;
506   }
507
508   /**
509    * Sets the start/end colours of bonds to those of the start/end atoms
510    * according to the specified colour scheme. Note: currently only works for
511    * peptide residues.
512    * 
513    * @param cs
514    */
515   public void setChainColours(ColourSchemeI cs)
516   {
517     int index;
518     for (Bond b : bonds)
519     {
520       try
521       {
522         index = ResidueProperties.aa3Hash.get(b.at1.resName).intValue();
523         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0),
524                 0, null, null, 0f);
525
526         index = ResidueProperties.aa3Hash.get(b.at2.resName).intValue();
527         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0), 0,
528                 null, null, 0f);
529
530       } catch (Exception e)
531       {
532         b.startCol = Color.gray;
533         b.endCol = Color.gray;
534       }
535     }
536   }
537
538   public void setChainColours(Color col)
539   {
540     for (Bond b : bonds)
541     {
542       b.startCol = col;
543       b.endCol = col;
544     }
545   }
546
547   /**
548    * copy any sequence annotation onto the sequence mapped using the provided
549    * StructureMapping
550    * 
551    * @param mapping
552    *          - positional mapping between destination sequence and pdb resnum
553    * @param sqmpping
554    *          - mapping between destination sequence and local chain
555    */
556   public void transferResidueAnnotation(StructureMapping mapping,
557           jalview.datamodel.Mapping sqmpping)
558   {
559     SequenceI sq = mapping.getSequence();
560     SequenceI dsq = sq;
561     if (sq != null)
562     {
563       while (dsq.getDatasetSequence() != null)
564       {
565         dsq = dsq.getDatasetSequence();
566       }
567       // any annotation will be transferred onto the dataset sequence
568
569       if (shadow != null && shadow.getAnnotation() != null)
570       {
571
572         for (AlignmentAnnotation ana : shadow.getAnnotation())
573         {
574           List<AlignmentAnnotation> transfer = sq.getAlignmentAnnotations(
575                   ana.getCalcId(), ana.label);
576           if (transfer == null || transfer.size() == 0)
577           {
578             ana = new AlignmentAnnotation(ana);
579             ana.liftOver(sequence, shadowMap);
580             ana.liftOver(dsq, sqmpping);
581             dsq.addAlignmentAnnotation(ana);
582           }
583           else
584           {
585             continue;
586           }
587         }
588       }
589       else
590       {
591         if (sequence != null && sequence.getAnnotation() != null)
592         {
593           for (AlignmentAnnotation ana : sequence.getAnnotation())
594           {
595             List<AlignmentAnnotation> transfer = dsq
596                     .getAlignmentAnnotations(ana.getCalcId(), ana.label);
597             if (transfer == null || transfer.size() == 0)
598             {
599               ana = new AlignmentAnnotation(ana);
600               ana.liftOver(dsq, sqmpping);
601               dsq.addAlignmentAnnotation(ana);
602               // mapping.transfer(ana);
603             }
604             else
605             {
606               continue;
607             }
608           }
609         }
610       }
611       if (false)
612       {
613         // Useful for debugging mappings - adds annotation for mapped position
614         float min = -1, max = 0;
615         Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
616         for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
617         {
618           int prn = mapping.getPDBResNum(k + 1);
619
620           an[k] = new Annotation(prn);
621           if (min == -1)
622           {
623             min = k;
624             max = k;
625           }
626           else
627           {
628             if (min > k)
629             {
630               min = k;
631             }
632             else if (max < k)
633             {
634               max = k;
635             }
636           }
637         }
638         sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
639                 "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
640                 an, min, max, AlignmentAnnotation.LINE_GRAPH));
641       }
642     }
643   }
644 }