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