JAL-2349 store/restore mappable contact matrix in project and fix up interactive...
[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         if (mcolumn < 0 || mcolumn >= elements[column].length)
249         {
250           return -1;
251         }
252         return elements[column][mcolumn];
253       }
254     });
255   }
256
257   @Override
258   protected double getElementAt(int _column, int i)
259   {
260     return elements[_column][i];
261   }
262   @Override
263   public float getMin()
264   {
265     return 0;
266   }
267
268   @Override
269   public float getMax()
270   {
271     return maxscore;
272   }
273
274   @Override
275   public String getAnnotDescr()
276   {
277     return "Predicted Alignment Error"+((refSeq==null) ? "" : (" for " + refSeq.getName()));
278   }
279
280   @Override
281   public String getAnnotLabel()
282   {
283     StringBuilder label = new StringBuilder("PAE Matrix");
284     //if (this.getReferenceSeq() != null)
285     //{
286     //  label.append(":").append(this.getReferenceSeq().getDisplayId(false));
287     //}
288     return label.toString();
289   }
290
291   public static final String PAEMATRIX = "PAE_MATRIX";
292
293   @Override
294   public String getType()
295   {
296     return PAEMATRIX;
297   }
298
299   @Override
300   public int getWidth()
301   {
302     return length;
303   }
304
305   @Override
306   public int getHeight()
307   {
308     return length;
309   }
310   List<BitSet> groups=null;
311   @Override
312   public boolean hasGroups()
313   {
314     return groups!=null;
315   }
316   String newick=null;
317   @Override
318   public String getNewick()
319   {
320     return newick;
321   }
322   @Override
323   public boolean hasTree()
324   {
325     return newick!=null && newick.length()>0;
326   }
327   boolean abs;
328   double thresh;
329   String treeType=null;
330   public void makeGroups(float thresh,boolean abs)
331   {
332     AverageDistanceEngine clusterer = new AverageDistanceEngine(null, null, this);
333     double height = clusterer.findHeight(clusterer.getTopNode());
334     newick = new jalview.io.NewickFile(clusterer.getTopNode(),false,true).print();
335     treeType = "UPGMA";
336     Console.trace("Newick string\n"+newick);
337
338     List<BinaryNode> nodegroups;
339     if (abs ? height > thresh : 0 < thresh && thresh < 1)
340     {
341       float cut = abs ? (float) (thresh / height) : thresh;
342       Console.debug("Threshold "+cut+" for height="+height);
343
344       nodegroups = clusterer.groupNodes(cut);
345     }
346     else
347     {
348       nodegroups = new ArrayList<BinaryNode>();
349       nodegroups.add(clusterer.getTopNode());
350     }
351     this.abs=abs;
352     this.thresh=thresh;
353     groups = new ArrayList<>();
354     for (BinaryNode root:nodegroups)
355     {
356       BitSet gpset=new BitSet();
357       for (BinaryNode leaf:clusterer.findLeaves(root))
358       {
359         gpset.set((Integer)leaf.element());
360       }
361       groups.add(gpset);
362     }
363   }
364   @Override
365   public void updateGroups(List<BitSet> colGroups)
366   {
367     if (colGroups!=null)
368     {
369       groups=colGroups;
370     }    
371   }
372   @Override
373   public BitSet getGroupsFor(int column)
374   {
375     if (groups != null)
376     {
377       for (BitSet gp : groups)
378       {
379         if (gp.get(column))
380         {
381           return gp;
382         }
383       }
384     }
385     return ContactMatrixI.super.getGroupsFor(column);
386   }
387
388   HashMap<BitSet,Color> colorMap = new HashMap<>();
389   @Override 
390   public Color getColourForGroup(BitSet bs)
391   {
392     if (bs==null) {
393       return Color.white;
394     }
395     Color groupCol=colorMap.get(bs);
396     if (groupCol==null)
397     {
398       return Color.white;
399     }
400     return groupCol;
401   }
402   @Override 
403   public void setColorForGroup(BitSet bs,Color color)
404   {
405     colorMap.put(bs,color);
406   }
407   public void restoreGroups(List<BitSet> newgroups, String treeMethod,
408           String tree, double thresh2)
409   {
410     treeType=treeMethod;
411     groups = newgroups;
412     thresh=thresh2;
413     newick =tree;
414     
415   }
416   @Override
417   public boolean hasCutHeight() {
418     return groups!=null && thresh!=0;
419   }
420   @Override
421   public double getCutHeight()
422   {
423     return thresh;
424   }
425   @Override
426   public String getTreeMethod()
427   {
428     return treeType;
429   }
430
431   public static void validateContactMatrixFile(String fileName) throws FileFormatException,IOException
432   {
433     FileInputStream infile=null;
434     try {
435       infile = new FileInputStream(new File(fileName));
436     } catch (Throwable t)
437     {
438       new IOException("Couldn't open "+fileName,t);      
439     }
440     
441     
442     JSONObject paeDict=null;
443     try {
444       paeDict = EBIAlfaFold.parseJSONtoPAEContactMatrix(infile);
445     } catch (Throwable t)
446     {
447       new FileFormatException("Couldn't parse "+fileName+" as a JSON dict or array containing a dict");
448     }
449     
450     PAEContactMatrix matrix = new PAEContactMatrix(new SequenceDummy("Predicted"), (Map<String,Object>)paeDict);
451     if (matrix.getWidth()<=0)
452     {
453       throw new FileFormatException("No data in PAE matrix read from '"+fileName+"'");
454     }
455   }
456
457   @Override
458   protected PAEContactMatrix newMappableContactMatrix(
459           SequenceI newRefSeq, MapList newFromMapList)
460   {
461       return new PAEContactMatrix(newRefSeq, newFromMapList,
462               elements);
463   } 
464 }