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