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