JAL-674 switch from .transfer to .liftOver for transfer of annotation
[jalview.git] / src / MCview / PDBChain.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.2)
3  * Copyright (C) 2014 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.ResidueProperties;
31 import jalview.structure.StructureMapping;
32
33 import java.awt.Color;
34 import java.util.Enumeration;
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 bonds = new Vector();
50
51   public Vector atoms = new Vector();
52
53   public Vector 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   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     String tmp = "";
108
109     for (int i = 0; i < bonds.size(); i++)
110     {
111       tmp = tmp + ((Bond) bonds.elementAt(i)).at1.resName + " "
112               + ((Bond) bonds.elementAt(i)).at1.resNumber + " " + offset
113               + newline;
114     }
115
116     return tmp;
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 : (Vector<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         Residue res = (Residue) residues.elementAt(pdbpos);
152         Enumeration en = res.atoms.elements();
153         while (en.hasMoreElements())
154         {
155           Atom atom = (Atom) en.nextElement();
156           atom.alignmentMapping = alignpos;
157         }
158       }
159     }
160   }
161
162   /**
163    * copy over the RESNUM seqfeatures from the internal chain sequence to the
164    * mapped sequence
165    * 
166    * @param seq
167    * @param status
168    *          The Status of the transferred annotation
169    * @return the features added to sq (or its dataset)
170    */
171   public SequenceFeature[] transferRESNUMFeatures(SequenceI seq,
172           String status)
173   {
174     SequenceI sq = seq;
175     while (sq != null && sq.getDatasetSequence() != null)
176     {
177       sq = sq.getDatasetSequence();
178       if (sq == sequence)
179       {
180         return null;
181       }
182     }
183     /**
184      * Remove any existing features for this chain if they exist ?
185      * SequenceFeature[] seqsfeatures=seq.getSequenceFeatures(); int
186      * totfeat=seqsfeatures.length; // Remove any features for this exact chain
187      * ? for (int i=0; i<seqsfeatures.length; i++) { }
188      */
189     if (status == null)
190     {
191       status = PDBChain.IEASTATUS;
192     }
193     SequenceFeature[] features = sequence.getSequenceFeatures();
194     for (int i = 0; i < features.length; i++)
195     {
196       if (features[i].getFeatureGroup().equals(pdbid))
197       {
198         SequenceFeature tx = new SequenceFeature(features[i]);
199         tx.setBegin(1 + ((Atom) ((Residue) residues.elementAt(tx.getBegin()
200                 - offset)).atoms.elementAt(0)).alignmentMapping);
201         tx.setEnd(1 + ((Atom) ((Residue) residues.elementAt(tx.getEnd()
202                 - offset)).atoms.elementAt(0)).alignmentMapping);
203         tx.setStatus(status
204                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
205                         : ":" + tx.getStatus()));
206         if (tx.begin != 0 && tx.end != 0)
207         {
208           sq.addSequenceFeature(tx);
209         }
210       }
211     }
212     return features;
213   }
214
215   public void makeCaBondList()
216   {
217     boolean na = false;
218     int numNa = 0;
219     for (int i = 0; i < (residues.size() - 1); i++)
220     {
221       Residue tmpres = (Residue) residues.elementAt(i);
222       Residue tmpres2 = (Residue) residues.elementAt(i + 1);
223       Atom at1 = tmpres.findAtom("CA");
224       Atom at2 = tmpres2.findAtom("CA");
225       na = false;
226       if ((at1 == null) && (at2 == null))
227       {
228         na = true;
229         at1 = tmpres.findAtom("P");
230         at2 = tmpres2.findAtom("P");
231       }
232       if ((at1 != null) && (at2 != null))
233       {
234         if (at1.chain.equals(at2.chain))
235         {
236           if (na)
237           {
238             numNa++;
239           }
240           makeBond(at1, at2);
241         }
242       }
243       else
244       {
245         System.out.println("not found " + i);
246       }
247     }
248     if (numNa > 0 && ((numNa / residues.size()) > 0.99))
249     {
250       isNa = true;
251     }
252   }
253
254   public void makeBond(Atom at1, Atom at2)
255   {
256     float[] start = new float[3];
257     float[] end = new float[3];
258
259     start[0] = at1.x;
260     start[1] = at1.y;
261     start[2] = at1.z;
262
263     end[0] = at2.x;
264     end[1] = at2.y;
265     end[2] = at2.z;
266
267     bonds.addElement(new Bond(start, end, at1, at2));
268   }
269
270   public void makeResidueList()
271   {
272     int count = 0;
273     Object symbol;
274     boolean deoxyn = false;
275     boolean nucleotide = false;
276     StringBuffer seq = new StringBuffer();
277     Vector resFeatures = new Vector();
278     Vector resAnnotation = new Vector();
279     int i, iSize = atoms.size() - 1;
280     int resNumber = -1;
281     for (i = 0; i <= iSize; i++)
282     {
283       Atom tmp = (Atom) atoms.elementAt(i);
284       resNumber = tmp.resNumber;
285       int res = resNumber;
286
287       if (i == 0)
288       {
289         offset = resNumber;
290       }
291
292       Vector resAtoms = new Vector();
293       // Add atoms to a vector while the residue number
294       // remains the same as the first atom's resNumber (res)
295       while ((resNumber == res) && (i < atoms.size()))
296       {
297         resAtoms.addElement(atoms.elementAt(i));
298         i++;
299
300         if (i < atoms.size())
301         {
302           resNumber = ((Atom) atoms.elementAt(i)).resNumber;
303         }
304         else
305         {
306           resNumber++;
307         }
308       }
309
310       // We need this to keep in step with the outer for i = loop
311       i--;
312
313       // Make a new Residue object with the new atoms vector
314       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
315
316       Residue tmpres = (Residue) residues.lastElement();
317       Atom tmpat = (Atom) tmpres.atoms.elementAt(0);
318       // Make A new SequenceFeature for the current residue numbering
319       SequenceFeature sf = new SequenceFeature("RESNUM", tmpat.resName
320               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
321               + count, offset + count, pdbid);
322       // MCview.PDBChain.PDBFILEFEATURE);
323       resFeatures.addElement(sf);
324       resAnnotation.addElement(new Annotation(tmpat.tfactor));
325       // Keep totting up the sequence
326       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
327       {
328         String nucname = tmpat.resName.trim();
329         // use the aaIndex rather than call 'toLower' - which would take a bit
330         // more time.
331         deoxyn = nucname.length() == 2
332                 && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
333         if (tmpat.name.equalsIgnoreCase("CA")
334                 || ResidueProperties.nucleotideIndex[nucname
335                         .charAt((deoxyn ? 1 : 0))] == -1)
336         {
337           seq.append("X");
338           // System.err.println("PDBReader:Null aa3Hash for " +
339           // tmpat.resName);
340         }
341         else
342         {
343           // nucleotide flag
344           nucleotide = true;
345           seq.append(nucname.charAt((deoxyn ? 1 : 0)));
346         }
347       }
348       else
349       {
350         if (nucleotide)
351         {
352           System.err
353                   .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
354         }
355         seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
356       }
357       count++;
358     }
359
360     if (id.length() < 1)
361     {
362       id = " ";
363     }
364     isNa = nucleotide;
365     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
366     // resNumber-offset
367     // ~=
368     // seq.size()
369     // Add normalised feature scores to RESNUM indicating start/end of sequence
370     // sf.setScore(offset+count);
371
372     // System.out.println("PDB Sequence is :\nSequence = " + seq);
373     // System.out.println("No of residues = " + residues.size());
374     for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
375     {
376       sequence.addSequenceFeature((SequenceFeature) resFeatures
377               .elementAt(i));
378       resFeatures.setElementAt(null, i);
379     }
380     Annotation[] annots = new Annotation[resAnnotation.size()];
381     float max = 0;
382     for (i = 0, iSize = annots.length; i < iSize; i++)
383     {
384       annots[i] = (Annotation) resAnnotation.elementAt(i);
385       if (annots[i].value > max)
386       {
387         max = annots[i].value;
388       }
389       resAnnotation.setElementAt(null, i);
390     }
391     AlignmentAnnotation tfactorann = new AlignmentAnnotation(
392             "PDB.TempFactor", "Temperature Factor for "
393                     + sequence.getName(), annots, 0, max,
394             AlignmentAnnotation.LINE_GRAPH);
395     tfactorann.setSequenceRef(sequence);
396     sequence.addAlignmentAnnotation(tfactorann);
397   }
398
399   public void setChargeColours()
400   {
401     for (int i = 0; i < bonds.size(); i++)
402     {
403       try
404       {
405         Bond b = (Bond) bonds.elementAt(i);
406
407         if (b.at1.resName.equalsIgnoreCase("ASP")
408                 || b.at1.resName.equalsIgnoreCase("GLU"))
409         {
410           b.startCol = Color.red;
411         }
412         else if (b.at1.resName.equalsIgnoreCase("LYS")
413                 || b.at1.resName.equalsIgnoreCase("ARG"))
414         {
415           b.startCol = Color.blue;
416         }
417         else if (b.at1.resName.equalsIgnoreCase("CYS"))
418         {
419           b.startCol = Color.yellow;
420         }
421         else
422         {
423           b.startCol = Color.lightGray;
424         }
425
426         if (b.at2.resName.equalsIgnoreCase("ASP")
427                 || b.at2.resName.equalsIgnoreCase("GLU"))
428         {
429           b.endCol = Color.red;
430         }
431         else if (b.at2.resName.equalsIgnoreCase("LYS")
432                 || b.at2.resName.equalsIgnoreCase("ARG"))
433         {
434           b.endCol = Color.blue;
435         }
436         else if (b.at2.resName.equalsIgnoreCase("CYS"))
437         {
438           b.endCol = Color.yellow;
439         }
440         else
441         {
442           b.endCol = Color.lightGray;
443         }
444       } catch (Exception e)
445       {
446         Bond b = (Bond) bonds.elementAt(i);
447         b.startCol = Color.gray;
448         b.endCol = Color.gray;
449       }
450     }
451   }
452
453   public void setChainColours(jalview.schemes.ColourSchemeI cs)
454   {
455     Bond b;
456     int index;
457     for (int i = 0; i < bonds.size(); i++)
458     {
459       try
460       {
461         b = (Bond) bonds.elementAt(i);
462
463         index = ((Integer) ResidueProperties.aa3Hash.get(b.at1.resName))
464                 .intValue();
465         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
466
467         index = ((Integer) ResidueProperties.aa3Hash.get(b.at2.resName))
468                 .intValue();
469         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
470
471       } catch (Exception e)
472       {
473         b = (Bond) bonds.elementAt(i);
474         b.startCol = Color.gray;
475         b.endCol = Color.gray;
476       }
477     }
478   }
479
480   public void setChainColours(Color col)
481   {
482     for (int i = 0; i < bonds.size(); i++)
483     {
484       Bond tmp = (Bond) bonds.elementAt(i);
485       tmp.startCol = col;
486       tmp.endCol = col;
487     }
488   }
489
490   /**
491    * copy any sequence annotation onto the sequence mapped using the provided
492    * StructureMapping
493    * 
494    * @param mapping
495    *          - positional mapping between destination sequence and pdb resnum
496    * @param sqmpping
497    *          - mapping between destination sequence and local chain
498    */
499   public void transferResidueAnnotation(
500           StructureMapping mapping, jalview.datamodel.Mapping sqmpping)
501   {
502     SequenceI sq = mapping.getSequence();
503     SequenceI dsq = sq;
504     if (sq != null)
505     {
506       while (dsq.getDatasetSequence() != null)
507       {
508         dsq = dsq.getDatasetSequence();
509       }
510       // any annotation will be transferred onto the dataset sequence
511
512       if (shadow != null && shadow.getAnnotation() != null)
513       {
514
515         for (AlignmentAnnotation ana : shadow.getAnnotation())
516         {
517           List<AlignmentAnnotation> transfer = sq.getAlignmentAnnotations(
518                   ana.getCalcId(), ana.label);
519           if (transfer == null || transfer.size() == 0)
520           {
521             ana.liftOver(sequence, shadowMap);
522             ana.liftOver(dsq, sqmpping);
523             dsq.addAlignmentAnnotation(ana);
524           }
525           else
526           {
527             continue;
528           }
529         }
530       }
531       else
532       {
533       if (sequence != null && sequence.getAnnotation() != null)
534       {
535         for (AlignmentAnnotation ana : sequence.getAnnotation())
536         {
537           List<AlignmentAnnotation> transfer = sq.getAlignmentAnnotations(
538                   ana.getCalcId(), ana.label);
539           if (transfer == null || transfer.size() == 0)
540           {
541             ana.liftOver(dsq, sqmpping);
542             // mapping.transfer(ana);
543           }
544           else
545           {
546             continue;
547           }
548         }
549       }
550       }
551       float min = -1, max = 0;
552       Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
553       for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
554       {
555         int prn = mapping.getPDBResNum(k + 1);
556
557         an[k] = new Annotation(prn);
558         if (min == -1)
559         {
560           min = k;
561           max = k;
562         }
563         else
564         {
565           if (min > k)
566           {
567             min = k;
568           }
569           else if (max < k)
570           {
571             max = k;
572           }
573         }
574       }
575       sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
576               "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
577               an, min, max, AlignmentAnnotation.LINE_GRAPH));
578
579     }
580   }
581 }