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