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