JAL-1503 update version in GPL header
[jalview.git] / src / MCview / PDBChain.java
1 /*
2  * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.1)
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 of the License, or (at your option) any later version.
10  *  
11  * Jalview is distributed in the hope that it will be useful, but 
12  * WITHOUT ANY WARRANTY; without even the implied warranty 
13  * of MERCHANTABILITY or FITNESS FOR A PARTICULAR 
14  * PURPOSE.  See the GNU General Public License for more details.
15  * 
16  * You should have received a copy of the GNU General Public License along with Jalview.  If not, see <http://www.gnu.org/licenses/>.
17  * The Jalview Authors are detailed in the 'AUTHORS' file.
18  */
19 package MCview;
20
21 import java.util.*;
22
23 import java.awt.*;
24
25 import jalview.analysis.*;
26 import jalview.datamodel.*;
27 import jalview.schemes.*;
28 import jalview.structure.StructureMapping;
29
30 public class PDBChain
31 {
32   /**
33    * SequenceFeature group for PDB File features added to sequences
34    */
35   private static final String PDBFILEFEATURE = "PDBFile";
36
37   private static final String IEASTATUS = "IEA:jalview";
38
39   public String id;
40
41   public Vector bonds = new Vector();
42
43   public Vector atoms = new Vector();
44
45   public Vector residues = new Vector();
46
47   public int offset;
48
49   public Sequence sequence;
50
51   public boolean isNa = false;
52
53   public boolean isVisible = true;
54
55   public int pdbstart = 0;
56
57   public int pdbend = 0;
58
59   public int seqstart = 0;
60
61   public int seqend = 0;
62
63   public String pdbid = "";
64
65   public PDBChain(String pdbid, String id)
66   {
67     this.pdbid = pdbid.toLowerCase();
68     this.id = id;
69   }
70
71   /**
72    * character used to write newlines
73    */
74   protected String newline = System.getProperty("line.separator");
75
76   public void setNewlineString(String nl)
77   {
78     newline = nl;
79   }
80
81   public String getNewlineString()
82   {
83     return newline;
84   }
85
86   public String print()
87   {
88     String tmp = "";
89
90     for (int i = 0; i < bonds.size(); i++)
91     {
92       tmp = tmp + ((Bond) bonds.elementAt(i)).at1.resName + " "
93               + ((Bond) bonds.elementAt(i)).at1.resNumber + " " + offset
94               + newline;
95     }
96
97     return tmp;
98   }
99
100   /**
101    * Annotate the residues with their corresponding positions in s1 using the
102    * alignment in as NOTE: This clears all atom.alignmentMapping values on the
103    * structure.
104    * 
105    * @param as
106    * @param s1
107    */
108   public void makeExactMapping(AlignSeq as, SequenceI s1)
109   {
110     int pdbpos = as.getSeq2Start() - 2;
111     int alignpos = s1.getStart() + as.getSeq1Start() - 3;
112     // first clear out any old alignmentMapping values:
113     for (Atom atom : (Vector<Atom>) atoms)
114     {
115       atom.alignmentMapping = -1;
116     }
117     // and now trace the alignment onto the atom set.
118     for (int i = 0; i < as.astr1.length(); i++)
119     {
120       if (as.astr1.charAt(i) != '-')
121       {
122         alignpos++;
123       }
124
125       if (as.astr2.charAt(i) != '-')
126       {
127         pdbpos++;
128       }
129
130       if (as.astr1.charAt(i) == as.astr2.charAt(i))
131       {
132         Residue res = (Residue) residues.elementAt(pdbpos);
133         Enumeration en = res.atoms.elements();
134         while (en.hasMoreElements())
135         {
136           Atom atom = (Atom) en.nextElement();
137           atom.alignmentMapping = alignpos;
138         }
139       }
140     }
141   }
142
143   /**
144    * copy over the RESNUM seqfeatures from the internal chain sequence to the
145    * mapped sequence
146    * 
147    * @param seq
148    * @param status
149    *          The Status of the transferred annotation
150    * @return the features added to sq (or its dataset)
151    */
152   public SequenceFeature[] transferRESNUMFeatures(SequenceI seq,
153           String status)
154   {
155     SequenceI sq = seq;
156     while (sq != null && sq.getDatasetSequence() != null)
157     {
158       sq = sq.getDatasetSequence();
159       if (sq == sequence)
160       {
161         return null;
162       }
163     }
164     /**
165      * Remove any existing features for this chain if they exist ?
166      * SequenceFeature[] seqsfeatures=seq.getSequenceFeatures(); int
167      * totfeat=seqsfeatures.length; // Remove any features for this exact chain
168      * ? for (int i=0; i<seqsfeatures.length; i++) { }
169      */
170     if (status == null)
171     {
172       status = PDBChain.IEASTATUS;
173     }
174     SequenceFeature[] features = sequence.getSequenceFeatures();
175     for (int i = 0; i < features.length; i++)
176     {
177       if (features[i].getFeatureGroup().equals(pdbid))
178       {
179         SequenceFeature tx = new SequenceFeature(features[i]);
180         tx.setBegin(1 + ((Atom) ((Residue) residues.elementAt(tx.getBegin()
181                 - offset)).atoms.elementAt(0)).alignmentMapping);
182         tx.setEnd(1 + ((Atom) ((Residue) residues.elementAt(tx.getEnd()
183                 - offset)).atoms.elementAt(0)).alignmentMapping);
184         tx.setStatus(status
185                 + ((tx.getStatus() == null || tx.getStatus().length() == 0) ? ""
186                         : ":" + tx.getStatus()));
187         if (tx.begin != 0 && tx.end != 0)
188           sq.addSequenceFeature(tx);
189       }
190     }
191     return features;
192   }
193
194   public void makeCaBondList()
195   {
196     boolean na = false;
197     int numNa = 0;
198     for (int i = 0; i < (residues.size() - 1); i++)
199     {
200       Residue tmpres = (Residue) residues.elementAt(i);
201       Residue tmpres2 = (Residue) residues.elementAt(i + 1);
202       Atom at1 = tmpres.findAtom("CA");
203       Atom at2 = tmpres2.findAtom("CA");
204       na = false;
205       if ((at1 == null) && (at2 == null))
206       {
207         na = true;
208         at1 = tmpres.findAtom("P");
209         at2 = tmpres2.findAtom("P");
210       }
211       if ((at1 != null) && (at2 != null))
212       {
213         if (at1.chain.equals(at2.chain))
214         {
215           if (na)
216           {
217             numNa++;
218           }
219           makeBond(at1, at2);
220         }
221       }
222       else
223       {
224         System.out.println("not found " + i);
225       }
226     }
227     if (numNa > 0 && ((numNa / residues.size()) > 0.99))
228     {
229       isNa = true;
230     }
231   }
232
233   public void makeBond(Atom at1, Atom at2)
234   {
235     float[] start = new float[3];
236     float[] end = new float[3];
237
238     start[0] = at1.x;
239     start[1] = at1.y;
240     start[2] = at1.z;
241
242     end[0] = at2.x;
243     end[1] = at2.y;
244     end[2] = at2.z;
245
246     bonds.addElement(new Bond(start, end, at1, at2));
247   }
248
249   public void makeResidueList()
250   {
251     int count = 0;
252     Object symbol;
253     boolean deoxyn = false;
254     boolean nucleotide = false;
255     StringBuffer seq = new StringBuffer();
256     Vector resFeatures = new Vector();
257     Vector resAnnotation = new Vector();
258     int i, iSize = atoms.size() - 1;
259     int resNumber = -1;
260     for (i = 0; i <= iSize; i++)
261     {
262       Atom tmp = (Atom) atoms.elementAt(i);
263       resNumber = tmp.resNumber;
264       int res = resNumber;
265
266       if (i == 0)
267       {
268         offset = resNumber;
269       }
270
271       Vector resAtoms = new Vector();
272       // Add atoms to a vector while the residue number
273       // remains the same as the first atom's resNumber (res)
274       while ((resNumber == res) && (i < atoms.size()))
275       {
276         resAtoms.addElement((Atom) atoms.elementAt(i));
277         i++;
278
279         if (i < atoms.size())
280         {
281           resNumber = ((Atom) atoms.elementAt(i)).resNumber;
282         }
283         else
284         {
285           resNumber++;
286         }
287       }
288
289       // We need this to keep in step with the outer for i = loop
290       i--;
291
292       // Make a new Residue object with the new atoms vector
293       residues.addElement(new Residue(resAtoms, resNumber - 1, count));
294
295       Residue tmpres = (Residue) residues.lastElement();
296       Atom tmpat = (Atom) tmpres.atoms.elementAt(0);
297       // Make A new SequenceFeature for the current residue numbering
298       SequenceFeature sf = new SequenceFeature("RESNUM", tmpat.resName
299               + ":" + tmpat.resNumIns + " " + pdbid + id, "", offset
300               + count, offset + count, pdbid);
301       // MCview.PDBChain.PDBFILEFEATURE);
302       resFeatures.addElement(sf);
303       resAnnotation.addElement(new Annotation(tmpat.tfactor));
304       // Keep totting up the sequence
305       if ((symbol = ResidueProperties.getAA3Hash().get(tmpat.resName)) == null)
306       {
307         String nucname = tmpat.resName.trim();
308         // use the aaIndex rather than call 'toLower' - which would take a bit
309         // more time.
310         deoxyn = nucname.length() == 2
311                 && ResidueProperties.aaIndex[nucname.charAt(0)] == ResidueProperties.aaIndex['D'];
312         if (tmpat.name.equalsIgnoreCase("CA")
313                 || ResidueProperties.nucleotideIndex[nucname
314                         .charAt((deoxyn ? 1 : 0))] == -1)
315         {
316           seq.append("X");
317           // System.err.println("PDBReader:Null aa3Hash for " +
318           // tmpat.resName);
319         }
320         else
321         {
322           // nucleotide flag
323           nucleotide = true;
324           seq.append(nucname.charAt((deoxyn ? 1 : 0)));
325         }
326       }
327       else
328       {
329         if (nucleotide)
330         {
331           System.err
332                   .println("Warning: mixed nucleotide and amino acid chain.. its gonna do bad things to you!");
333         }
334         seq.append(ResidueProperties.aa[((Integer) symbol).intValue()]);
335       }
336       count++;
337     }
338
339     if (id.length() < 1)
340     {
341       id = " ";
342     }
343     isNa = nucleotide;
344     sequence = new Sequence(id, seq.toString(), offset, resNumber - 1); // Note:
345     // resNumber-offset
346     // ~=
347     // seq.size()
348     // Add normalised feature scores to RESNUM indicating start/end of sequence
349     // sf.setScore(offset+count);
350
351     // System.out.println("PDB Sequence is :\nSequence = " + seq);
352     // System.out.println("No of residues = " + residues.size());
353     for (i = 0, iSize = resFeatures.size(); i < iSize; i++)
354     {
355       sequence.addSequenceFeature((SequenceFeature) resFeatures
356               .elementAt(i));
357       resFeatures.setElementAt(null, i);
358     }
359     Annotation[] annots = new Annotation[resAnnotation.size()];
360     float max = 0;
361     for (i = 0, iSize = annots.length; i < iSize; i++)
362     {
363       annots[i] = (Annotation) resAnnotation.elementAt(i);
364       if (annots[i].value > max)
365         max = annots[i].value;
366       resAnnotation.setElementAt(null, i);
367     }
368     AlignmentAnnotation tfactorann = new AlignmentAnnotation(
369             "PDB.TempFactor", "Temperature Factor for "
370                     + sequence.getName(), annots, 0, max,
371             AlignmentAnnotation.LINE_GRAPH);
372     tfactorann.setSequenceRef(sequence);
373     sequence.addAlignmentAnnotation(tfactorann);
374   }
375
376   public void setChargeColours()
377   {
378     for (int i = 0; i < bonds.size(); i++)
379     {
380       try
381       {
382         Bond b = (Bond) bonds.elementAt(i);
383
384         if (b.at1.resName.equalsIgnoreCase("ASP")
385                 || b.at1.resName.equalsIgnoreCase("GLU"))
386         {
387           b.startCol = Color.red;
388         }
389         else if (b.at1.resName.equalsIgnoreCase("LYS")
390                 || b.at1.resName.equalsIgnoreCase("ARG"))
391         {
392           b.startCol = Color.blue;
393         }
394         else if (b.at1.resName.equalsIgnoreCase("CYS"))
395         {
396           b.startCol = Color.yellow;
397         }
398         else
399         {
400           b.startCol = Color.lightGray;
401         }
402
403         if (b.at2.resName.equalsIgnoreCase("ASP")
404                 || b.at2.resName.equalsIgnoreCase("GLU"))
405         {
406           b.endCol = Color.red;
407         }
408         else if (b.at2.resName.equalsIgnoreCase("LYS")
409                 || b.at2.resName.equalsIgnoreCase("ARG"))
410         {
411           b.endCol = Color.blue;
412         }
413         else if (b.at2.resName.equalsIgnoreCase("CYS"))
414         {
415           b.endCol = Color.yellow;
416         }
417         else
418         {
419           b.endCol = Color.lightGray;
420         }
421       } catch (Exception e)
422       {
423         Bond b = (Bond) bonds.elementAt(i);
424         b.startCol = Color.gray;
425         b.endCol = Color.gray;
426       }
427     }
428   }
429
430   public void setChainColours(jalview.schemes.ColourSchemeI cs)
431   {
432     Bond b;
433     int index;
434     for (int i = 0; i < bonds.size(); i++)
435     {
436       try
437       {
438         b = (Bond) bonds.elementAt(i);
439
440         index = ((Integer) ResidueProperties.aa3Hash.get(b.at1.resName))
441                 .intValue();
442         b.startCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
443
444         index = ((Integer) ResidueProperties.aa3Hash.get(b.at2.resName))
445                 .intValue();
446         b.endCol = cs.findColour(ResidueProperties.aa[index].charAt(0));
447
448       } catch (Exception e)
449       {
450         b = (Bond) bonds.elementAt(i);
451         b.startCol = Color.gray;
452         b.endCol = Color.gray;
453       }
454     }
455   }
456
457   public void setChainColours(Color col)
458   {
459     for (int i = 0; i < bonds.size(); i++)
460     {
461       Bond tmp = (Bond) bonds.elementAt(i);
462       tmp.startCol = col;
463       tmp.endCol = col;
464     }
465   }
466
467   public AlignmentAnnotation[] transferResidueAnnotation(SequenceI seq,
468           String status)
469   {
470     AlignmentAnnotation[] transferred = null;
471
472     return transferred;
473
474   }
475
476   /**
477    * copy any sequence annotation onto the sequence mapped using the provided
478    * StructureMapping
479    * 
480    * @param mapping
481    */
482   public void transferResidueAnnotation(StructureMapping mapping)
483   {
484     SequenceI sq = mapping.getSequence();
485     if (sq != null)
486     {
487       if (sequence != null && sequence.getAnnotation() != null)
488       {
489
490       }
491       float min = -1, max = 0;
492       Annotation[] an = new Annotation[sq.getEnd() - sq.getStart() + 1];
493       for (int i = sq.getStart(), j = sq.getEnd(), k = 0; i <= j; i++, k++)
494       {
495         int prn = mapping.getPDBResNum(k + 1);
496
497         an[k] = new Annotation((float) prn);
498         if (min == -1)
499         {
500           min = k;
501           max = k;
502         }
503         else
504         {
505           if (min > k)
506           {
507             min = k;
508           }
509           else if (max < k)
510           {
511             max = k;
512           }
513         }
514       }
515       sq.addAlignmentAnnotation(new AlignmentAnnotation("PDB.RESNUM",
516               "PDB Residue Numbering for " + this.pdbid + ":" + this.id,
517               an, (float) min, (float) max, AlignmentAnnotation.LINE_GRAPH));
518     }
519   }
520 }