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