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