JAL-2349 allow PAE or other contact matrices to hold a coordinate mapping allowing...
[jalview.git] / src / jalview / ws / datamodel / alphafold / PAEContactMatrix.java
1 package jalview.ws.datamodel.alphafold;
2
3 import java.awt.Color;
4 import java.io.BufferedInputStream;
5 import java.io.File;
6 import java.io.FileInputStream;
7 import java.io.IOException;
8 import java.util.ArrayList;
9 import java.util.BitSet;
10 import java.util.HashMap;
11 import java.util.Iterator;
12 import java.util.List;
13 import java.util.Map;
14 import java.util.Map.Entry;
15
16 import org.json.simple.JSONObject;
17
18 import jalview.analysis.AverageDistanceEngine;
19 import jalview.bin.Console;
20 import jalview.datamodel.Annotation;
21 import jalview.datamodel.BinaryNode;
22 import jalview.datamodel.ContactListI;
23 import jalview.datamodel.ContactListImpl;
24 import jalview.datamodel.ContactListProviderI;
25 import jalview.datamodel.ContactMatrixI;
26 import jalview.datamodel.Mapping;
27 import jalview.datamodel.SequenceDummy;
28 import jalview.datamodel.SequenceI;
29 import jalview.io.DataSourceType;
30 import jalview.io.FileFormatException;
31 import jalview.io.FileParse;
32 import jalview.util.MapList;
33 import jalview.util.MapUtils;
34 import jalview.ws.dbsources.EBIAlfaFold;
35
36 public class PAEContactMatrix extends MappableContactMatrix<PAEContactMatrix> implements ContactMatrixI
37 {
38   int maxrow = 0, maxcol = 0;
39
40   float[][] elements;
41
42   float maxscore;
43
44
45   @SuppressWarnings("unchecked")
46   public PAEContactMatrix(SequenceI _refSeq, Map<String, Object> pae_obj) throws FileFormatException
47   {
48     setRefSeq(_refSeq);
49     // convert the lists to primitive arrays and store
50
51     if (!MapUtils.containsAKey(pae_obj, "predicted_aligned_error", "pae"))
52     {
53       parse_version_1_pAE(pae_obj);
54       return;
55     }
56     else
57     {
58       parse_version_2_pAE(pae_obj);
59     }
60   }
61
62   /**
63    * construct a sequence associated PAE matrix directly from a float array
64    * 
65    * @param _refSeq
66    * @param matrix
67    */
68   public PAEContactMatrix(SequenceI _refSeq, float[][] matrix)
69   {
70     setRefSeq(_refSeq);
71     maxcol = 0;
72     for (float[] row : matrix)
73     {
74       if (row.length > maxcol)
75       {
76         maxcol = row.length;
77       }
78       maxscore = row[0];
79       for (float f : row)
80       {
81         if (maxscore < f)
82         {
83           maxscore = f;
84         }
85       }
86     }
87     maxrow = matrix.length;
88     elements = matrix;
89
90   }
91
92   /**
93    * new matrix with specific mapping to a reference sequence
94    * @param newRefSeq
95    * @param newFromMapList
96    * @param elements2
97    */
98   public PAEContactMatrix(SequenceI newRefSeq,
99           MapList newFromMapList, float[][] elements2)
100   {
101     this(newRefSeq,elements2);
102     toSeq = newFromMapList;
103   }
104
105   /**
106    * parse a sane JSON representation of the pAE
107    * 
108    * @param pae_obj
109    */
110   @SuppressWarnings("unchecked")
111   private void parse_version_2_pAE(Map<String, Object> pae_obj)
112   {
113     maxscore = -1;
114     // look for a maxscore element - if there is one...
115     try
116     {
117       // this is never going to be reached by the integer rounding.. or is it ?
118       maxscore = ((Double) MapUtils.getFirst(pae_obj,
119               "max_predicted_aligned_error", "max_pae")).floatValue();
120     } catch (Throwable t)
121     {
122       // ignore if a key is not found.
123     }
124     List<List<Long>> scoreRows = ((List<List<Long>>) MapUtils
125             .getFirst(pae_obj, "predicted_aligned_error", "pae"));
126     elements = new float[scoreRows.size()][scoreRows.size()];
127     int row = 0, col = 0;
128     for (List<Long> scoreRow : scoreRows)
129     {
130       Iterator<Long> scores = scoreRow.iterator();
131       while (scores.hasNext())
132       {
133         Object d = scores.next();
134
135         if (d instanceof Double)
136         {
137           elements[row][col++] = ((Double) d).longValue();
138         }
139         else
140         {
141           elements[row][col++] = (float) ((Long) d).longValue();
142         }
143         
144         if (maxscore < elements[row][col - 1])
145         {
146           maxscore = elements[row][col - 1];
147         }
148       }
149       row++;
150       col = 0;
151     }
152     maxcol = length;
153     maxrow = length;
154   }
155
156   /**
157    * v1 format got ditched 28th July 2022 see
158    * https://alphafold.ebi.ac.uk/faq#:~:text=We%20updated%20the%20PAE%20JSON%20file%20format%20on%2028th%20July%202022
159    * 
160    * @param pae_obj
161    */
162   @SuppressWarnings("unchecked")
163   private void parse_version_1_pAE(Map<String, Object> pae_obj)
164   {
165     // assume indices are with respect to range defined by _refSeq on the
166     // dataset refSeq
167     Iterator<Long> rows = ((List<Long>) pae_obj.get("residue1")).iterator();
168     Iterator<Long> cols = ((List<Long>) pae_obj.get("residue2")).iterator();
169     // two pass - to allocate the elements array
170     while (rows.hasNext())
171     {
172       int row = rows.next().intValue();
173       int col = cols.next().intValue();
174       if (maxrow < row)
175       {
176         maxrow = row;
177       }
178       if (maxcol < col)
179       {
180         maxcol = col;
181       }
182
183     }
184     rows = ((List<Long>) pae_obj.get("residue1")).iterator();
185     cols = ((List<Long>) pae_obj.get("residue2")).iterator();
186     Iterator<Double> scores = ((List<Double>) pae_obj.get("distance"))
187             .iterator();
188     elements = new float[maxrow][maxcol];
189     while (scores.hasNext())
190     {
191       float escore = scores.next().floatValue();
192       int row = rows.next().intValue();
193       int col = cols.next().intValue();
194       if (maxrow < row)
195       {
196         maxrow = row;
197       }
198       if (maxcol < col)
199       {
200         maxcol = col;
201       }
202       elements[row - 1][col - 1] = escore;
203     }
204
205     maxscore = ((Double) MapUtils.getFirst(pae_obj,
206             "max_predicted_aligned_error", "max_pae")).floatValue();
207   }
208
209   @Override
210   public ContactListI getContactList(final int column)
211   {
212     final int _column;
213     if (toSeq != null)
214     {
215       int[] word = toSeq.locateInTo(column, column);
216       if (word == null)
217       {
218         return null;
219       }
220       _column = word[0];
221     }
222     else
223     {
224       _column = column;
225     }
226     if (_column < 0 || _column >= elements.length)
227     {
228       return null;
229     }
230
231     return new ContactListImpl(new ContactListProviderI()
232     {
233       @Override
234       public int getPosition()
235       {
236         return _column;
237       }
238
239       @Override
240       public int getContactHeight()
241       {
242         return maxcol - 1;
243       }
244
245       @Override
246       public double getContactAt(int mcolumn)
247       {
248         int[] column=(toSeq==null) ? new int[] {mcolumn} : toSeq.locateInTo(mcolumn,mcolumn);
249         if (column==null || column[0] < 0 || column[0] >= elements[_column].length)
250         {
251           return -1;
252         }
253         return elements[_column][column[0]];
254       }
255     });
256   }
257
258   @Override
259   protected double getElementAt(int _column, int i)
260   {
261     return elements[_column][i];
262   }
263   @Override
264   public float getMin()
265   {
266     return 0;
267   }
268
269   @Override
270   public float getMax()
271   {
272     return maxscore;
273   }
274
275   @Override
276   public String getAnnotDescr()
277   {
278     return "Predicted Alignment Error"+((refSeq==null) ? "" : (" for " + refSeq.getName()));
279   }
280
281   @Override
282   public String getAnnotLabel()
283   {
284     StringBuilder label = new StringBuilder("PAE Matrix");
285     //if (this.getReferenceSeq() != null)
286     //{
287     //  label.append(":").append(this.getReferenceSeq().getDisplayId(false));
288     //}
289     return label.toString();
290   }
291
292   public static final String PAEMATRIX = "PAE_MATRIX";
293
294   @Override
295   public String getType()
296   {
297     return PAEMATRIX;
298   }
299
300   @Override
301   public int getWidth()
302   {
303     return length;
304   }
305
306   @Override
307   public int getHeight()
308   {
309     return length;
310   }
311   List<BitSet> groups=null;
312   @Override
313   public boolean hasGroups()
314   {
315     return groups!=null;
316   }
317   String newick=null;
318   @Override
319   public String getNewick()
320   {
321     return newick;
322   }
323   @Override
324   public boolean hasTree()
325   {
326     return newick!=null && newick.length()>0;
327   }
328   boolean abs;
329   double thresh;
330   String treeType=null;
331   public void makeGroups(float thresh,boolean abs)
332   {
333     AverageDistanceEngine clusterer = new AverageDistanceEngine(null, null, this);
334     double height = clusterer.findHeight(clusterer.getTopNode());
335     newick = new jalview.io.NewickFile(clusterer.getTopNode(),false,true).print();
336     treeType = "UPGMA";
337     Console.trace("Newick string\n"+newick);
338
339     List<BinaryNode> nodegroups;
340     if (abs ? height > thresh : 0 < thresh && thresh < 1)
341     {
342       float cut = abs ? (float) (thresh / height) : thresh;
343       Console.debug("Threshold "+cut+" for height="+height);
344
345       nodegroups = clusterer.groupNodes(cut);
346     }
347     else
348     {
349       nodegroups = new ArrayList<BinaryNode>();
350       nodegroups.add(clusterer.getTopNode());
351     }
352     this.abs=abs;
353     this.thresh=thresh;
354     groups = new ArrayList<>();
355     for (BinaryNode root:nodegroups)
356     {
357       BitSet gpset=new BitSet();
358       for (BinaryNode leaf:clusterer.findLeaves(root))
359       {
360         gpset.set((Integer)leaf.element());
361       }
362       groups.add(gpset);
363     }
364   }
365   @Override
366   public void updateGroups(List<BitSet> colGroups)
367   {
368     if (colGroups!=null)
369     {
370       groups=colGroups;
371     }    
372   }
373   @Override
374   public BitSet getGroupsFor(int column)
375   {
376     if (groups != null)
377     {
378       for (BitSet gp : groups)
379       {
380         if (gp.get(column))
381         {
382           return gp;
383         }
384       }
385     }
386     return ContactMatrixI.super.getGroupsFor(column);
387   }
388
389   HashMap<BitSet,Color> colorMap = new HashMap<>();
390   @Override 
391   public Color getColourForGroup(BitSet bs)
392   {
393     if (bs==null) {
394       return Color.white;
395     }
396     Color groupCol=colorMap.get(bs);
397     if (groupCol==null)
398     {
399       return Color.white;
400     }
401     return groupCol;
402   }
403   @Override 
404   public void setColorForGroup(BitSet bs,Color color)
405   {
406     colorMap.put(bs,color);
407   }
408   public void restoreGroups(List<BitSet> newgroups, String treeMethod,
409           String tree, double thresh2)
410   {
411     treeType=treeMethod;
412     groups = newgroups;
413     thresh=thresh2;
414     newick =tree;
415     
416   }
417   @Override
418   public boolean hasCutHeight() {
419     return groups!=null && thresh!=0;
420   }
421   @Override
422   public double getCutHeight()
423   {
424     return thresh;
425   }
426   @Override
427   public String getTreeMethod()
428   {
429     return treeType;
430   }
431
432   public static void validateContactMatrixFile(String fileName) throws FileFormatException,IOException
433   {
434     FileInputStream infile=null;
435     try {
436       infile = new FileInputStream(new File(fileName));
437     } catch (Throwable t)
438     {
439       new IOException("Couldn't open "+fileName,t);      
440     }
441     
442     
443     JSONObject paeDict=null;
444     try {
445       paeDict = EBIAlfaFold.parseJSONtoPAEContactMatrix(infile);
446     } catch (Throwable t)
447     {
448       new FileFormatException("Couldn't parse "+fileName+" as a JSON dict or array containing a dict");
449     }
450     
451     PAEContactMatrix matrix = new PAEContactMatrix(new SequenceDummy("Predicted"), (Map<String,Object>)paeDict);
452     if (matrix.getWidth()<=0)
453     {
454       throw new FileFormatException("No data in PAE matrix read from '"+fileName+"'");
455     }
456   }
457
458   @Override
459   protected PAEContactMatrix newMappableContactMatrix(
460           SequenceI newRefSeq, MapList newFromMapList)
461   {
462       return new PAEContactMatrix(newRefSeq, newFromMapList,
463               elements);
464   } 
465 }