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