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