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