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