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