JAL-4134 properly resolve positions in associated aligned sequence for matrix group...
[jalview.git] / src / jalview / ws / datamodel / alphafold / MappableContactMatrix.java
1 package jalview.ws.datamodel.alphafold;
2
3 import java.awt.Color;
4 import java.util.ArrayList;
5 import java.util.BitSet;
6
7 import jalview.datamodel.ContactListI;
8 import jalview.datamodel.ContactListImpl;
9 import jalview.datamodel.ContactListProviderI;
10 import jalview.datamodel.GroupSet;
11 import jalview.datamodel.GroupSetI;
12 import jalview.datamodel.Mapping;
13 import jalview.datamodel.SequenceI;
14 import jalview.util.MapList;
15 import jalview.ws.datamodel.MappableContactMatrixI;
16
17 public abstract class MappableContactMatrix<T extends MappableContactMatrix<T>>
18         implements MappableContactMatrixI
19 {
20   SequenceI refSeq = null;
21
22   MapList toSeq = null;
23
24   /**
25    * the length that refSeq is expected to be (excluding gaps, of course)
26    */
27   int length;
28
29   @Override
30   public boolean hasReferenceSeq()
31   {
32     return (refSeq != null);
33   }
34
35   @Override
36   public SequenceI getReferenceSeq()
37   {
38     return refSeq;
39   }
40
41   /**
42    * container for groups - defined on matrix columns
43    */
44   GroupSet grps = new GroupSet();
45
46   @Override
47   public GroupSetI getGroupSet()
48   {
49     return grps;
50   };
51
52   @Override
53   public void setGroupSet(GroupSet makeGroups)
54   {
55     grps = makeGroups;
56   }
57
58   @Override
59   public MapList getMapFor(SequenceI mapSeq)
60   {
61     if (refSeq != null)
62     {
63       while (mapSeq != refSeq && mapSeq.getDatasetSequence() != null)
64       {
65         mapSeq = mapSeq.getDatasetSequence();
66       }
67       if (mapSeq != refSeq)
68       {
69         return null;
70       }
71     }
72     else
73     {
74       if (mapSeq != null)
75       {
76         // our MapList does not concern this seq
77         return null;
78       }
79     }
80
81     return toSeq;
82   }
83
84   /**
85    * set the reference sequence and construct the mapping between the start-end
86    * positions of given sequence and row/columns of contact matrix
87    * 
88    * @param _refSeq
89    */
90   public void setRefSeq(SequenceI _refSeq)
91   {
92     refSeq = _refSeq;
93     while (refSeq.getDatasetSequence() != null)
94     {
95       refSeq = refSeq.getDatasetSequence();
96     }
97     length = _refSeq.getEnd() - _refSeq.getStart() + 1;
98     // if (length!=refSeq.getLength() || _refSeq.getStart()!=1)
99     {
100       toSeq = new MapList(
101               new int[]
102               { _refSeq.getStart(), _refSeq.getEnd() },
103               new int[]
104               { 0, length - 1 }, 1, 1);
105     }
106   }
107
108   public T liftOver(SequenceI newRefSeq, Mapping sp2sq)
109   {
110     if (sp2sq.getMappedWidth() != sp2sq.getWidth())
111     {
112       // TODO: employ getWord/MappedWord to transfer annotation between cDNA and
113       // Protein reference frames
114       throw new Error(
115               "liftOver currently not implemented for transfer of annotation between different types of seqeunce");
116     }
117     boolean mapIsTo = (sp2sq != null) ? (sp2sq.getTo() == refSeq) : false;
118
119     /**
120      * map from matrix to toSeq's coordinate frame
121      */
122     int[] refMap = toSeq.locateInFrom(0, length - 1);
123     ArrayList<Integer> newFromMap = new ArrayList<Integer>();
124     int last = -1;
125     for (int i = 0; i < refMap.length; i += 2)
126     {
127       /*
128        * for each contiguous range in toSeq, locate corresponding range in sequence mapped to toSeq by sp2sq
129        */
130       int[] sp2map = mapIsTo
131               ? sp2sq.getMap().locateInFrom(refMap[i], refMap[i + 1])
132               : sp2sq.getMap().locateInTo(refMap[i], refMap[i + 1]);
133       if (sp2map == null)
134       {
135         continue;
136       }
137
138       for (int spm = 0; spm < sp2map.length; spm += 2)
139       {
140
141         if (last > -1)
142         {
143           if (sp2map[spm] != last + 1)
144           {
145             newFromMap.add(sp2map[spm]);
146           }
147           else
148           {
149             newFromMap.remove(newFromMap.size() - 1);
150           }
151         }
152         else
153         {
154           newFromMap.add(sp2map[spm]);
155         }
156         last = sp2map[spm + 1];
157         newFromMap.add(last);
158       }
159     }
160     if ((newFromMap.size() % 2) != 0)
161     {
162       // should have had an even number of int ranges!
163       throw new Error("PAEMatrix liftover failed.");
164     }
165     int fromIntMap[] = new int[newFromMap.size()];
166     int ipos = 0;
167     for (Integer i : newFromMap)
168     {
169       fromIntMap[ipos++] = i;
170     }
171     MapList newFromMapList = new MapList(fromIntMap,
172             new int[]
173             { 0, length - 1 }, 1, 1);
174
175     T newCM = newMappableContactMatrix(newRefSeq, newFromMapList);
176     return newCM;
177   }
178
179   protected abstract T newMappableContactMatrix(SequenceI newRefSeq,
180           MapList newFromMapList);
181
182   @Override
183   public int[] getMappedPositionsFor(final SequenceI localFrame,
184           final int column)
185   {
186     return getMappedPositionsFor(localFrame, column, column);
187   }
188
189   @Override
190   public int[] getMappedPositionsFor(final SequenceI localFrame, int from,
191           int to)
192   {
193     if (localFrame == null)
194     {
195       throw new Error("Unimplemented when no local sequence given.");
196     }
197     SequenceI lf = localFrame, uf = refSeq;
198
199     // check that localFrame is derived from refSeq
200     // just look for dataset sequences and check they are the same.
201     // in future we could use DBRefMappings/whatever.
202     while (lf.getDatasetSequence() != null
203             || uf.getDatasetSequence() != null)
204     {
205       if (lf.getDatasetSequence() != null)
206       {
207         lf = lf.getDatasetSequence();
208       }
209       if (uf.getDatasetSequence() != null)
210       {
211         uf = uf.getDatasetSequence();
212       }
213     }
214     if (lf != uf)
215     {
216       // could try harder to find a mapping
217       throw new Error("This Matrix associated with '" + refSeq.getName()
218               + "' is not mappable for the given localFrame sequence. ("
219               + localFrame.getName() + ")");
220     }
221     
222     // now look up from-to matrix columns in toSeq frame
223     
224     if (toSeq == null)
225     {
226       // no mapping - so we assume 1:1
227       return new int[] { from, to };
228     }
229     // from-to are matrix columns
230     // first locate on reference sequence
231
232     int[] mappedPositions = toSeq.locateInFrom(from, to);
233     if (mappedPositions==null)
234     {
235       return null;
236     }
237     
238     // and now map to localFrame
239     // from-to columns on the associated sequence should be
240     // i. restricted to positions in localFrame
241     // ii. 
242
243 //    int s = -1, e = -1;
244 //    for (int p = 0; p < mappedPositions.length; p++)
245 //    {
246 //      if (s == -1 && mappedPositions[p] >= localFrame.getStart())
247 //      {
248 //        s = p; // remember first position within local frame
249 //      }
250 //      if (e == -1 || mappedPositions[p] <= localFrame.getEnd())
251 //      {
252 //        // update end pointer
253 //        e = p;
254 //        // compute local map
255 //        mappedPositions[p] = localFrame.findIndex(mappedPositions[p]);
256 //      }
257 //    }
258 //    int[] _trimmed = new int[e - s + 1];
259 //    return _trimmed;
260     return mappedPositions;
261   }
262
263   @Override
264   public ContactListI getMappableContactList(final SequenceI localFrame,
265           final int column)
266   {
267     final int _column;
268     final int _lcolumn;
269     if (localFrame == null)
270     {
271       throw new Error("Unimplemented when no local sequence given.");
272     }
273     // return a ContactListI for column
274     // column is index into localFrame
275     // 1. map column to corresponding column in matrix
276     final MappableContactMatrix us = this;
277     _lcolumn = localFrame.findPosition(column);
278
279     if (toSeq != null)
280     {
281       SequenceI lf = localFrame, uf = refSeq;
282
283       // just look for dataset sequences and check they are the same.
284       // in future we could use DBRefMappings/whatever.
285       while (lf.getDatasetSequence() != null
286               || uf.getDatasetSequence() != null)
287       {
288         if (lf.getDatasetSequence() != null)
289         {
290           lf = lf.getDatasetSequence();
291         }
292         if (uf.getDatasetSequence() != null)
293         {
294           uf = uf.getDatasetSequence();
295         }
296       }
297       if (lf != uf)
298       {
299         // could try harder to find a mapping
300         throw new Error("This Matrix associated with '" + refSeq.getName()
301                 + "' is not mappable for the given localFrame sequence. ("
302                 + localFrame.getName() + ")");
303       }
304       // check the mapping to see if localFrame _lcolumn exists
305       int[] word = toSeq.locateInTo(_lcolumn, _lcolumn);
306       if (word == null)
307       {
308         return null;
309       }
310       _column = word[0];
311     }
312     else
313     {
314       // no mapping
315       _column = _lcolumn;
316     }
317
318     // TODO - remove ? this may be a redundant check
319     if (_column < 0 || ((toSeq != null && _column > toSeq.getToHighest())
320             || (toSeq == null && getHeight() <= _column)))
321     {
322       return null;
323     }
324
325     // 2. resolve ranges in matrix corresponding to range in localFrame
326     final int[] matrixRange = toSeq == null
327             ? new int[]
328             { localFrame.getStart(), localFrame.getEnd() }
329             : toSeq.locateInTo(localFrame.getStart(), localFrame.getEnd());
330
331     int h = 0;
332     for (int p = 0; p < matrixRange.length; p += 2)
333     {
334       h += 1 + Math.abs(matrixRange[p + 1] - matrixRange[p]);
335     }
336     final int rangeHeight = h;
337     // 3. Construct ContactListImpl instance for just those segments.
338
339     return new ContactListImpl(new ContactListProviderI()
340     {
341
342       public int getColumn()
343       {
344         return column;
345       }
346
347       @Override
348       public int getPosition()
349       {
350         return _column;
351       }
352
353       @Override
354       public int getContactHeight()
355       {
356         return rangeHeight;
357       }
358
359       @Override
360       public double getContactAt(int mcolumn)
361       {
362         if (mcolumn < 0 || mcolumn >= rangeHeight)
363         {
364           return -1;
365         }
366         return getElementAt(_column, locateInRange(mcolumn));
367
368         // this code maps from mcolumn to localFrame - but that isn't what's
369         // needed
370         // int loccolumn = localFrame.findPosition(mcolumn);
371         // int[] lcolumn=(toSeq==null) ? new int[] {mcolumn} :
372         // toSeq.locateInTo(loccolumn,loccolumn);
373         // if (lcolumn==null || lcolumn[0] < 0 || lcolumn[0] >= rangeHeight)
374         // {
375         // return -1;
376         // }
377         // return getElementAt(_column,lcolumn[0]);
378       }
379
380       @Override
381       public int[] getMappedPositionsFor(int cStart, int cEnd)
382       {
383         if (!hasReferenceSeq())
384         {
385           return ContactListProviderI.super.getMappedPositionsFor(cStart,
386                   cEnd);
387         }
388         // map into segment of matrix being shown
389         int realCstart = locateInRange(cStart);
390         int realCend = locateInRange(cEnd);
391
392         // TODO account for discontinuities in the mapping
393
394         int[] mappedPositions = toSeq.locateInFrom(realCstart, realCend);
395         if (mappedPositions != null)
396         {
397           int s = -1, e = -1;
398           for (int p = 0; p < mappedPositions.length; p++)
399           {
400             if (s == -1 && mappedPositions[p] >= localFrame.getStart())
401             {
402               s = p; // remember first position within local frame
403             }
404             if (e == -1 || mappedPositions[p] <= localFrame.getEnd())
405             {
406               // update end pointer
407               e = p;
408               // compute local map
409               mappedPositions[p] = localFrame.findIndex(mappedPositions[p]);
410             }
411           }
412         }
413         return mappedPositions;
414       }
415
416       /**
417        * @return the mcolumn'th position in the matrixRange window on the matrix
418        */
419       private int locateInRange(int mcolumn)
420       {
421
422         int h = 0, p = 0;
423         while (h < mcolumn && p + 2 < matrixRange.length)
424         {
425           h += 1 + Math.abs(matrixRange[p + 1] - matrixRange[p]);
426           p += 2;
427         }
428         return matrixRange[p] + mcolumn - h;
429       }
430
431       @Override
432       public Color getColourForGroup()
433       {
434         BitSet gp = us.getGroupsFor(_column);
435         Color col = us.getColourForGroup(gp);
436         return col;
437       }
438     });
439   }
440
441   /**
442    * get a specific element of the contact matrix in its data-local coordinates
443    * rather than the mapped frame. Implementations are allowed to throw
444    * RunTimeExceptions if _column/i are out of bounds
445    * 
446    * @param _column
447    * @param i
448    * @return
449    */
450   protected abstract double getElementAt(int _column, int i);
451
452 }