JAL-1551 spotlessApply
[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   public int[] getMappedPositionsFor(final SequenceI localFrame, int from,
190           int to)
191   {
192     if (localFrame == null)
193     {
194       throw new Error("Unimplemented when no local sequence given.");
195     }
196     // return a ContactListI for column
197     // column is index into localFrame
198     // 1. map column to corresponding column in matrix
199
200     final int _lcolumn = localFrame.findPosition(from);
201     final int _rcolumn = (from == to) ? _lcolumn
202             : localFrame.findPosition(to);
203     if (toSeq == null)
204     {
205       // no mapping
206       return new int[] { _lcolumn, _rcolumn };
207     }
208
209     SequenceI lf = localFrame, uf = refSeq;
210
211     // just look for dataset sequences and check they are the same.
212     // in future we could use DBRefMappings/whatever.
213     while (lf.getDatasetSequence() != null
214             || uf.getDatasetSequence() != null)
215     {
216       if (lf.getDatasetSequence() != null)
217       {
218         lf = lf.getDatasetSequence();
219       }
220       if (uf.getDatasetSequence() != null)
221       {
222         uf = uf.getDatasetSequence();
223       }
224     }
225     if (lf != uf)
226     {
227       // could try harder to find a mapping
228       throw new Error("This Matrix associated with '" + refSeq.getName()
229               + "' is not mappable for the given localFrame sequence. ("
230               + localFrame.getName() + ")");
231     }
232
233     int[] mappedPositions = toSeq.locateInFrom(_lcolumn, _rcolumn);
234     // TODO - trim to localFrame ?
235     // if (mappedPositions!=null) {
236     // int s=-1,e=-1;
237     // for (int p=0;p<mappedPositions.length;p++)
238     // {
239     // if (s==-1 && mappedPositions[p]>=localFrame.getStart())
240     // {
241     // s=p; // remember first position within local frame
242     // }
243     // if (e==-1 || mappedPositions[p]<=localFrame.getEnd())
244     // {
245     // // update end pointer
246     // e=p;
247     // // compute local map
248     // mappedPositions[p] = localFrame.findIndex(mappedPositions[p]);
249     // }
250     // }
251     // }
252     return mappedPositions;
253   }
254
255   @Override
256   public ContactListI getMappableContactList(final SequenceI localFrame,
257           final int column)
258   {
259     final int _column;
260     final int _lcolumn;
261     if (localFrame == null)
262     {
263       throw new Error("Unimplemented when no local sequence given.");
264     }
265     // return a ContactListI for column
266     // column is index into localFrame
267     // 1. map column to corresponding column in matrix
268     final MappableContactMatrix us = this;
269     _lcolumn = localFrame.findPosition(column);
270
271     if (toSeq != null)
272     {
273       SequenceI lf = localFrame, uf = refSeq;
274
275       // just look for dataset sequences and check they are the same.
276       // in future we could use DBRefMappings/whatever.
277       while (lf.getDatasetSequence() != null
278               || uf.getDatasetSequence() != null)
279       {
280         if (lf.getDatasetSequence() != null)
281         {
282           lf = lf.getDatasetSequence();
283         }
284         if (uf.getDatasetSequence() != null)
285         {
286           uf = uf.getDatasetSequence();
287         }
288       }
289       if (lf != uf)
290       {
291         // could try harder to find a mapping
292         throw new Error("This Matrix associated with '" + refSeq.getName()
293                 + "' is not mappable for the given localFrame sequence. ("
294                 + localFrame.getName() + ")");
295       }
296       // check the mapping to see if localFrame _lcolumn exists
297       int[] word = toSeq.locateInTo(_lcolumn, _lcolumn);
298       if (word == null)
299       {
300         return null;
301       }
302       _column = word[0];
303     }
304     else
305     {
306       // no mapping
307       _column = _lcolumn;
308     }
309
310     // TODO - remove ? this may be a redundant check
311     if (_column < 0 || ((toSeq != null && _column > toSeq.getToHighest())
312             || (toSeq == null && getHeight() <= _column)))
313     {
314       return null;
315     }
316
317     // 2. resolve ranges in matrix corresponding to range in localFrame
318     final int[] matrixRange = toSeq == null
319             ? new int[]
320             { localFrame.getStart(), localFrame.getEnd() }
321             : toSeq.locateInTo(localFrame.getStart(), localFrame.getEnd());
322
323     int h = 0;
324     for (int p = 0; p < matrixRange.length; p += 2)
325     {
326       h += 1 + Math.abs(matrixRange[p + 1] - matrixRange[p]);
327     }
328     final int rangeHeight = h;
329     // 3. Construct ContactListImpl instance for just those segments.
330
331     return new ContactListImpl(new ContactListProviderI()
332     {
333
334       public int getColumn()
335       {
336         return column;
337       }
338
339       @Override
340       public int getPosition()
341       {
342         return _column;
343       }
344
345       @Override
346       public int getContactHeight()
347       {
348         return rangeHeight;
349       }
350
351       @Override
352       public double getContactAt(int mcolumn)
353       {
354         if (mcolumn < 0 || mcolumn >= rangeHeight)
355         {
356           return -1;
357         }
358         return getElementAt(_column, locateInRange(mcolumn));
359
360         // this code maps from mcolumn to localFrame - but that isn't what's
361         // needed
362         // int loccolumn = localFrame.findPosition(mcolumn);
363         // int[] lcolumn=(toSeq==null) ? new int[] {mcolumn} :
364         // toSeq.locateInTo(loccolumn,loccolumn);
365         // if (lcolumn==null || lcolumn[0] < 0 || lcolumn[0] >= rangeHeight)
366         // {
367         // return -1;
368         // }
369         // return getElementAt(_column,lcolumn[0]);
370       }
371
372       @Override
373       public int[] getMappedPositionsFor(int cStart, int cEnd)
374       {
375         if (!hasReferenceSeq())
376         {
377           return ContactListProviderI.super.getMappedPositionsFor(cStart,
378                   cEnd);
379         }
380         // map into segment of matrix being shown
381         int realCstart = locateInRange(cStart);
382         int realCend = locateInRange(cEnd);
383
384         // TODO account for discontinuities in the mapping
385
386         int[] mappedPositions = toSeq.locateInFrom(realCstart, realCend);
387         if (mappedPositions != null)
388         {
389           int s = -1, e = -1;
390           for (int p = 0; p < mappedPositions.length; p++)
391           {
392             if (s == -1 && mappedPositions[p] >= localFrame.getStart())
393             {
394               s = p; // remember first position within local frame
395             }
396             if (e == -1 || mappedPositions[p] <= localFrame.getEnd())
397             {
398               // update end pointer
399               e = p;
400               // compute local map
401               mappedPositions[p] = localFrame.findIndex(mappedPositions[p]);
402             }
403           }
404         }
405         return mappedPositions;
406       }
407
408       /**
409        * @return the mcolumn'th position in the matrixRange window on the matrix
410        */
411       private int locateInRange(int mcolumn)
412       {
413
414         int h = 0, p = 0;
415         while (h < mcolumn && p + 2 < matrixRange.length)
416         {
417           h += 1 + Math.abs(matrixRange[p + 1] - matrixRange[p]);
418           p += 2;
419         }
420         return matrixRange[p] + mcolumn - h;
421       }
422
423       @Override
424       public Color getColourForGroup()
425       {
426         BitSet gp = us.getGroupsFor(_column);
427         Color col = us.getColourForGroup(gp);
428         return col;
429       }
430     });
431   }
432
433   /**
434    * get a specific element of the contact matrix in its data-local coordinates
435    * rather than the mapped frame. Implementations are allowed to throw
436    * RunTimeExceptions if _column/i are out of bounds
437    * 
438    * @param _column
439    * @param i
440    * @return
441    */
442   protected abstract double getElementAt(int _column, int i);
443
444 }