dcd20225e83e38efd36f06dfda61b4d88412cd5f
[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.FloatContactMatrix;
17 import jalview.datamodel.GroupSet;
18 import jalview.datamodel.SequenceDummy;
19 import jalview.datamodel.SequenceI;
20 import jalview.io.FileFormatException;
21 import jalview.util.MapList;
22 import jalview.util.MapUtils;
23 import jalview.ws.dbsources.EBIAlfaFold;
24
25 /**
26  * routines and class for holding predicted alignment error matrices as produced
27  * by alphafold et al.
28  * 
29  * getContactList(column) returns the vector of predicted alignment errors for
30  * reference position given by column getElementAt(column, i) returns the
31  * predicted superposition error for the ith position when column is used as
32  * reference
33  * 
34  * Many thanks to Ora Schueler Furman for noticing that earlier development
35  * versions did not show the PAE oriented correctly
36  *
37  * @author jprocter
38  *
39  */
40 public class PAEContactMatrix extends
41         MappableContactMatrix<PAEContactMatrix> implements ContactMatrixI
42 {
43
44
45   @SuppressWarnings("unchecked")
46   public PAEContactMatrix(SequenceI _refSeq, Map<String, Object> pae_obj)
47           throws FileFormatException
48   {
49     setRefSeq(_refSeq);
50     // convert the lists to primitive arrays and store
51
52     if (!MapUtils.containsAKey(pae_obj, "predicted_aligned_error", "pae"))
53     {
54       parse_version_1_pAE(pae_obj);
55       return;
56     }
57     else
58     {
59       parse_version_2_pAE(pae_obj);
60     }
61   }
62
63   /**
64    * construct a sequence associated PAE matrix directly from a float array
65    * 
66    * @param _refSeq
67    * @param matrix
68    */
69   public PAEContactMatrix(SequenceI _refSeq, float[][] matrix)
70   {
71     mappedMatrix=new FloatContactMatrix(matrix);
72     setRefSeq(_refSeq);
73   }
74
75   /**
76    * new matrix with specific mapping to a reference sequence
77    * 
78    * @param newRefSeq
79    * @param newFromMapList
80    * @param elements2
81    * @param grps2
82    */
83   public PAEContactMatrix(SequenceI newRefSeq, MapList newFromMapList,
84           float[][] elements2, GroupSet grps2)
85   {
86     this(newRefSeq, new FloatContactMatrix(elements2,grps2));
87     toSeq = newFromMapList;
88   }
89
90   public PAEContactMatrix(SequenceI _refSeq,
91           ContactMatrixI floatContactMatrix)
92   {
93     mappedMatrix = floatContactMatrix;
94     setRefSeq(_refSeq);
95   }
96   public PAEContactMatrix(SequenceI _refSeq, MapList newFromMapList,
97           ContactMatrixI floatContactMatrix)
98   {
99     mappedMatrix = floatContactMatrix;
100     setRefSeq(_refSeq);
101     toSeq = newFromMapList;
102   }
103   
104   @Override
105   protected PAEContactMatrix newMappableContactMatrix(SequenceI newRefSeq,
106           MapList newFromMapList)
107   {
108     return new PAEContactMatrix(newRefSeq, newFromMapList, mappedMatrix);
109   }
110
111   /**
112    * parse a sane JSON representation of the pAE and update the mappedMatrix
113    * 
114    * @param pae_obj
115    */
116   @SuppressWarnings("unchecked")
117   private void parse_version_2_pAE(Map<String, Object> pae_obj)
118   {
119     float maxscore = -1;
120     // look for a maxscore element - if there is one...
121     try
122     {
123       // this is never going to be reached by the integer rounding.. or is it ?
124       maxscore = ((Double) MapUtils.getFirst(pae_obj,
125               "max_predicted_aligned_error", "max_pae")).floatValue();
126     } catch (Throwable t)
127     {
128       // ignore if a key is not found.
129     }
130     List<List<Long>> scoreRows = ((List<List<Long>>) MapUtils
131             .getFirst(pae_obj, "predicted_aligned_error", "pae"));
132     float[][] elements = new float[scoreRows.size()][scoreRows.size()];
133     int row = 0, col = 0;
134     for (List<Long> scoreRow : scoreRows)
135     {
136       Iterator<Long> scores = scoreRow.iterator();
137       while (scores.hasNext())
138       {
139         Object d = scores.next();
140         if (d instanceof Double)
141         {
142           elements[col][row] = ((Double) d).longValue();
143         }
144         else
145         {
146           elements[col][row] = (float) ((Long) d).longValue();
147         }
148
149         if (maxscore < elements[col][row])
150         {
151           maxscore = elements[col][row];
152         }
153         col++;
154       }
155       row++;
156       col = 0;
157     }
158     mappedMatrix=new FloatContactMatrix(elements);
159   }
160
161   /**
162    * v1 format got ditched 28th July 2022 see
163    * https://alphafold.ebi.ac.uk/faq#:~:text=We%20updated%20the%20PAE%20JSON%20file%20format%20on%2028th%20July%202022
164    * 
165    * @param pae_obj
166    */
167   @SuppressWarnings("unchecked")
168   private void parse_version_1_pAE(Map<String, Object> pae_obj)
169   {
170     // assume indices are with respect to range defined by _refSeq on the
171     // dataset refSeq
172     Iterator<Long> rows = ((List<Long>) pae_obj.get("residue1")).iterator();
173     Iterator<Long> cols = ((List<Long>) pae_obj.get("residue2")).iterator();
174     // two pass - to allocate the elements array
175     
176     int maxrow=-1,maxcol=-1;
177     while (rows.hasNext())
178     {
179       int row = rows.next().intValue();
180       int col = cols.next().intValue();
181       if (maxrow < row)
182       {
183         maxrow = row;
184       }
185       if (maxcol < col)
186       {
187         maxcol = col;
188       }
189
190     }
191     rows = ((List<Long>) pae_obj.get("residue1")).iterator();
192     cols = ((List<Long>) pae_obj.get("residue2")).iterator();
193     Iterator<Double> scores = ((List<Double>) pae_obj.get("distance"))
194             .iterator();
195     float[][] elements = new float[maxcol][maxrow];
196     while (scores.hasNext())
197     {
198       float escore = scores.next().floatValue();
199       int row = rows.next().intValue();
200       int col = cols.next().intValue();
201       if (maxrow < row)
202       {
203         maxrow = row;
204       }
205       if (maxcol < col)
206       {
207         maxcol = col;
208       }
209       elements[col - 1][row-1] = escore;
210     }
211
212     mappedMatrix=new FloatContactMatrix(elements);
213   }
214
215   @Override
216   public String getAnnotDescr()
217   {
218     return "Predicted Alignment Error"
219             + ((refSeq == null) ? "" : (" for " + refSeq.getName()));
220   }
221
222   @Override
223   public String getAnnotLabel()
224   {
225     StringBuilder label = new StringBuilder("PAE Matrix");
226     // if (this.getReferenceSeq() != null)
227     // {
228     // label.append(":").append(this.getReferenceSeq().getDisplayId(false));
229     // }
230     return label.toString();
231   }
232
233   public static final String PAEMATRIX = "PAE_MATRIX";
234
235   @Override
236   public String getType()
237   {
238     return PAEMATRIX;
239   }
240
241
242   public static void validateContactMatrixFile(String fileName)
243           throws FileFormatException, IOException
244   {
245     FileInputStream infile = null;
246     try
247     {
248       infile = new FileInputStream(new File(fileName));
249     } catch (Throwable t)
250     {
251       new IOException("Couldn't open " + fileName, t);
252     }
253     JSONObject paeDict = null;
254     try
255     {
256       paeDict = EBIAlfaFold.parseJSONtoPAEContactMatrix(infile);
257     } catch (Throwable t)
258     {
259       new FileFormatException("Couldn't parse " + fileName
260               + " as a JSON dict or array containing a dict");
261     }
262
263     PAEContactMatrix matrix = new PAEContactMatrix(
264             new SequenceDummy("Predicted"), (Map<String, Object>) paeDict);
265     if (matrix.getWidth() <= 0)
266     {
267       throw new FileFormatException(
268               "No data in PAE matrix read from '" + fileName + "'");
269     }
270   }
271   @Override
272   public boolean equals(Object obj)
273   {
274     return super.equals(obj);
275   }
276   @Override
277   public int hashCode()
278   {
279     return super.hashCode();
280   }
281 }