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