JAL-4134 column grouping model and methods moved to their own object held by by Conta...
[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.GroupSet;
27 import jalview.datamodel.GroupSetI;
28 import jalview.datamodel.Mapping;
29 import jalview.datamodel.SequenceDummy;
30 import jalview.datamodel.SequenceI;
31 import jalview.io.DataSourceType;
32 import jalview.io.FileFormatException;
33 import jalview.io.FileParse;
34 import jalview.util.MapList;
35 import jalview.util.MapUtils;
36 import jalview.ws.dbsources.EBIAlfaFold;
37
38 public class PAEContactMatrix extends MappableContactMatrix<PAEContactMatrix> implements ContactMatrixI
39 {
40   int maxrow = 0, maxcol = 0;
41
42   float[][] elements;
43
44   float maxscore;
45
46
47   @SuppressWarnings("unchecked")
48   public PAEContactMatrix(SequenceI _refSeq, Map<String, Object> pae_obj) throws FileFormatException
49   {
50     setRefSeq(_refSeq);
51     // convert the lists to primitive arrays and store
52
53     if (!MapUtils.containsAKey(pae_obj, "predicted_aligned_error", "pae"))
54     {
55       parse_version_1_pAE(pae_obj);
56       return;
57     }
58     else
59     {
60       parse_version_2_pAE(pae_obj);
61     }
62   }
63
64   /**
65    * construct a sequence associated PAE matrix directly from a float array
66    * 
67    * @param _refSeq
68    * @param matrix
69    */
70   public PAEContactMatrix(SequenceI _refSeq, float[][] matrix)
71   {
72     setRefSeq(_refSeq);
73     maxcol = 0;
74     for (float[] row : matrix)
75     {
76       if (row.length > maxcol)
77       {
78         maxcol = row.length;
79       }
80       maxscore = row[0];
81       for (float f : row)
82       {
83         if (maxscore < f)
84         {
85           maxscore = f;
86         }
87       }
88     }
89     maxrow = matrix.length;
90     elements = matrix;
91
92   }
93
94   /**
95    * new matrix with specific mapping to a reference sequence
96    * @param newRefSeq
97    * @param newFromMapList
98    * @param elements2
99    * @param grps2 
100    */
101   public PAEContactMatrix(SequenceI newRefSeq,
102           MapList newFromMapList, float[][] elements2, GroupSet grps2)
103   {
104     this(newRefSeq,elements2);
105     toSeq = newFromMapList;
106     grps= grps2;
107   }
108
109   /**
110    * parse a sane JSON representation of the pAE
111    * 
112    * @param pae_obj
113    */
114   @SuppressWarnings("unchecked")
115   private void parse_version_2_pAE(Map<String, Object> pae_obj)
116   {
117     maxscore = -1;
118     // look for a maxscore element - if there is one...
119     try
120     {
121       // this is never going to be reached by the integer rounding.. or is it ?
122       maxscore = ((Double) MapUtils.getFirst(pae_obj,
123               "max_predicted_aligned_error", "max_pae")).floatValue();
124     } catch (Throwable t)
125     {
126       // ignore if a key is not found.
127     }
128     List<List<Long>> scoreRows = ((List<List<Long>>) MapUtils
129             .getFirst(pae_obj, "predicted_aligned_error", "pae"));
130     elements = new float[scoreRows.size()][scoreRows.size()];
131     int row = 0, col = 0;
132     for (List<Long> scoreRow : scoreRows)
133     {
134       Iterator<Long> scores = scoreRow.iterator();
135       while (scores.hasNext())
136       {
137         Object d = scores.next();
138
139         if (d instanceof Double)
140         {
141           elements[row][col++] = ((Double) d).longValue();
142         }
143         else
144         {
145           elements[row][col++] = (float) ((Long) d).longValue();
146         }
147         
148         if (maxscore < elements[row][col - 1])
149         {
150           maxscore = elements[row][col - 1];
151         }
152       }
153       row++;
154       col = 0;
155     }
156     maxcol = length;
157     maxrow = length;
158   }
159
160   /**
161    * v1 format got ditched 28th July 2022 see
162    * https://alphafold.ebi.ac.uk/faq#:~:text=We%20updated%20the%20PAE%20JSON%20file%20format%20on%2028th%20July%202022
163    * 
164    * @param pae_obj
165    */
166   @SuppressWarnings("unchecked")
167   private void parse_version_1_pAE(Map<String, Object> pae_obj)
168   {
169     // assume indices are with respect to range defined by _refSeq on the
170     // dataset refSeq
171     Iterator<Long> rows = ((List<Long>) pae_obj.get("residue1")).iterator();
172     Iterator<Long> cols = ((List<Long>) pae_obj.get("residue2")).iterator();
173     // two pass - to allocate the elements array
174     while (rows.hasNext())
175     {
176       int row = rows.next().intValue();
177       int col = cols.next().intValue();
178       if (maxrow < row)
179       {
180         maxrow = row;
181       }
182       if (maxcol < col)
183       {
184         maxcol = col;
185       }
186
187     }
188     rows = ((List<Long>) pae_obj.get("residue1")).iterator();
189     cols = ((List<Long>) pae_obj.get("residue2")).iterator();
190     Iterator<Double> scores = ((List<Double>) pae_obj.get("distance"))
191             .iterator();
192     elements = new float[maxrow][maxcol];
193     while (scores.hasNext())
194     {
195       float escore = scores.next().floatValue();
196       int row = rows.next().intValue();
197       int col = cols.next().intValue();
198       if (maxrow < row)
199       {
200         maxrow = row;
201       }
202       if (maxcol < col)
203       {
204         maxcol = col;
205       }
206       elements[row - 1][col - 1] = escore;
207     }
208
209     maxscore = ((Double) MapUtils.getFirst(pae_obj,
210             "max_predicted_aligned_error", "max_pae")).floatValue();
211   }
212
213   @Override
214   public ContactListI getContactList(final int column)
215   {
216 //    final int _column;
217 //    if (toSeq != null)
218 //    {
219 //      int[] word = toSeq.locateInTo(column, column);
220 //      if (word == null)
221 //      {
222 //        return null;
223 //      }
224 //      _column = word[0];
225 //    }
226 //    else
227 //    {
228 //      _column = column;
229 //    }
230     if (column < 0 || column >= elements.length)
231     {
232       return null;
233     }
234
235     return new ContactListImpl(new ContactListProviderI()
236     {
237       @Override
238       public int getPosition()
239       {
240         return column;
241       }
242
243       @Override
244       public int getContactHeight()
245       {
246         return maxcol - 1;
247       }
248
249       @Override
250       public double getContactAt(int mcolumn)
251       {
252         if (mcolumn < 0 || mcolumn >= elements[column].length)
253         {
254           return -1;
255         }
256         return elements[column][mcolumn];
257       }
258     });
259   }
260
261   @Override
262   protected double getElementAt(int _column, int i)
263   {
264     return elements[_column][i];
265   }
266   @Override
267   public float getMin()
268   {
269     return 0;
270   }
271
272   @Override
273   public float getMax()
274   {
275     return maxscore;
276   }
277
278   @Override
279   public String getAnnotDescr()
280   {
281     return "Predicted Alignment Error"+((refSeq==null) ? "" : (" for " + refSeq.getName()));
282   }
283
284   @Override
285   public String getAnnotLabel()
286   {
287     StringBuilder label = new StringBuilder("PAE Matrix");
288     //if (this.getReferenceSeq() != null)
289     //{
290     //  label.append(":").append(this.getReferenceSeq().getDisplayId(false));
291     //}
292     return label.toString();
293   }
294
295   public static final String PAEMATRIX = "PAE_MATRIX";
296
297   @Override
298   public String getType()
299   {
300     return PAEMATRIX;
301   }
302
303   @Override
304   public int getWidth()
305   {
306     return length;
307   }
308
309   @Override
310   public int getHeight()
311   {
312     return length;
313   }
314   
315   public static void validateContactMatrixFile(String fileName) throws FileFormatException,IOException
316   {
317     FileInputStream infile=null;
318     try {
319       infile = new FileInputStream(new File(fileName));
320     } catch (Throwable t)
321     {
322       new IOException("Couldn't open "+fileName,t);      
323     }
324     
325     
326     JSONObject paeDict=null;
327     try {
328       paeDict = EBIAlfaFold.parseJSONtoPAEContactMatrix(infile);
329     } catch (Throwable t)
330     {
331       new FileFormatException("Couldn't parse "+fileName+" as a JSON dict or array containing a dict");
332     }
333     
334     PAEContactMatrix matrix = new PAEContactMatrix(new SequenceDummy("Predicted"), (Map<String,Object>)paeDict);
335     if (matrix.getWidth()<=0)
336     {
337       throw new FileFormatException("No data in PAE matrix read from '"+fileName+"'");
338     }
339   }
340
341   @Override
342   protected PAEContactMatrix newMappableContactMatrix(
343           SequenceI newRefSeq, MapList newFromMapList)
344   {
345     PAEContactMatrix pae=new PAEContactMatrix(newRefSeq, newFromMapList,
346               elements, new GroupSet(grps));
347     return pae;
348   } 
349 }