3 import jalview.analysis.AlignmentSorter;
4 import jalview.api.AlignViewportI;
5 import jalview.commands.CommandI;
6 import jalview.commands.EditCommand;
7 import jalview.commands.EditCommand.Action;
8 import jalview.commands.EditCommand.Edit;
9 import jalview.commands.OrderCommand;
10 import jalview.datamodel.AlignedCodonFrame;
11 import jalview.datamodel.AlignmentI;
12 import jalview.datamodel.AlignmentOrder;
13 import jalview.datamodel.ColumnSelection;
14 import jalview.datamodel.SearchResults;
15 import jalview.datamodel.SearchResults.Match;
16 import jalview.datamodel.Sequence;
17 import jalview.datamodel.SequenceGroup;
18 import jalview.datamodel.SequenceI;
19 import jalview.gui.AlignViewport;
21 import java.util.ArrayList;
22 import java.util.HashMap;
23 import java.util.Iterator;
24 import java.util.List;
29 * Helper methods for manipulations involving sequence mappings.
34 public final class MappingUtils
38 * Helper method to map a CUT or PASTE command.
41 * the original command
43 * if true, the command is to be undone
45 * the mapped sequences to apply the mapped command to
47 * the mapped EditCommand to add to
50 protected static void mapCutOrPaste(Edit edit, boolean undo,
51 List<SequenceI> targetSeqs, EditCommand result,
52 Set<AlignedCodonFrame> mappings)
54 Action action = edit.getAction();
57 action = action.getUndoAction();
60 System.err.println("MappingUtils.mapCutOrPaste not yet implemented");
64 * Returns a new EditCommand representing the given command as mapped to the
65 * given sequences. If there is no mapping, returns null.
74 public static EditCommand mapEditCommand(EditCommand command,
75 boolean undo, final AlignmentI mapTo, char gapChar,
76 Set<AlignedCodonFrame> mappings)
79 * For now, only support mapping from protein edits to cDna
81 if (!mapTo.isNucleotide())
87 * Cache a copy of the target sequences so we can mimic successive edits on
88 * them. This lets us compute mappings for all edits in the set.
90 Map<SequenceI, SequenceI> targetCopies = new HashMap<SequenceI, SequenceI>();
91 for (SequenceI seq : mapTo.getSequences())
93 SequenceI ds = seq.getDatasetSequence();
96 final SequenceI copy = new Sequence("", new String(
98 copy.setDatasetSequence(ds);
99 targetCopies.put(ds, copy);
104 * Compute 'source' sequences as they were before applying edits:
106 Map<SequenceI, SequenceI> originalSequences = command.priorState(undo);
108 EditCommand result = new EditCommand();
109 Iterator<Edit> edits = command.getEditIterator(!undo);
110 while (edits.hasNext())
112 Edit edit = edits.next();
113 if (edit.getAction() == Action.CUT
114 || edit.getAction() == Action.PASTE)
116 mapCutOrPaste(edit, undo, mapTo.getSequences(), result, mappings);
118 else if (edit.getAction() == Action.INSERT_GAP
119 || edit.getAction() == Action.DELETE_GAP)
121 mapInsertOrDelete(edit, undo, originalSequences,
122 mapTo.getSequences(), targetCopies, gapChar, result,
126 return result.getSize() > 0 ? result : null;
130 * Helper method to map an edit command to insert or delete gaps.
133 * the original command
135 * if true, the action is to undo the command
136 * @param originalSequences
137 * the sequences the command acted on
139 * @param targetCopies
142 * the new EditCommand to add mapped commands to
145 protected static void mapInsertOrDelete(Edit edit, boolean undo,
146 Map<SequenceI, SequenceI> originalSequences,
147 final List<SequenceI> targetSeqs,
148 Map<SequenceI, SequenceI> targetCopies, char gapChar,
149 EditCommand result, Set<AlignedCodonFrame> mappings)
151 Action action = edit.getAction();
154 * Invert sense of action if an Undo.
158 action = action.getUndoAction();
160 final int count = edit.getNumber();
161 final int editPos = edit.getPosition();
162 for (SequenceI seq : edit.getSequences())
165 * Get residue position at (or to right of) edit location. Note we use our
166 * 'copy' of the sequence before editing for this.
168 SequenceI ds = seq.getDatasetSequence();
173 final SequenceI actedOn = originalSequences.get(ds);
174 final int seqpos = actedOn.findPosition(editPos);
177 * Determine all mappings from this position to mapped sequences.
179 SearchResults sr = buildSearchResults(seq, seqpos, mappings);
183 for (SequenceI targetSeq : targetSeqs)
185 ds = targetSeq.getDatasetSequence();
190 SequenceI copyTarget = targetCopies.get(ds);
191 final int[] match = sr.getResults(copyTarget, 0,
192 copyTarget.getLength());
195 final int ratio = 3; // TODO: compute this - how?
196 final int mappedCount = count * ratio;
199 * Shift Delete start position left, as it acts on positions to its
202 int mappedEditPos = action == Action.DELETE_GAP ? match[0]
203 - mappedCount : match[0];
204 Edit e = result.new Edit(action, new SequenceI[]
205 { targetSeq }, mappedEditPos, mappedCount, gapChar);
209 * and 'apply' the edit to our copy of its target sequence
211 if (action == Action.INSERT_GAP)
213 copyTarget.setSequence(new String(StringUtils.insertCharAt(
214 copyTarget.getSequence(), mappedEditPos, mappedCount,
217 else if (action == Action.DELETE_GAP)
219 copyTarget.setSequence(new String(StringUtils.deleteChars(
220 copyTarget.getSequence(), mappedEditPos,
221 mappedEditPos + mappedCount)));
227 * and 'apply' the edit to our copy of its source sequence
229 if (action == Action.INSERT_GAP)
231 actedOn.setSequence(new String(StringUtils.insertCharAt(
232 actedOn.getSequence(), editPos, count, gapChar)));
234 else if (action == Action.DELETE_GAP)
236 actedOn.setSequence(new String(StringUtils.deleteChars(
237 actedOn.getSequence(), editPos, editPos + count)));
243 * Returns a SearchResults object describing the mapped region corresponding
244 * to the specified sequence position.
251 public static SearchResults buildSearchResults(SequenceI seq, int index,
252 Set<AlignedCodonFrame> seqmappings)
254 SearchResults results;
255 results = new SearchResults();
256 if (index >= seq.getStart() && index <= seq.getEnd())
258 for (AlignedCodonFrame acf : seqmappings)
260 acf.markMappedRegion(seq, index, results);
267 * Returns a (possibly empty) SequenceGroup containing any sequences in the
268 * mapped viewport corresponding to the given group in the source viewport.
275 public static SequenceGroup mapSequenceGroup(SequenceGroup sg,
276 AlignViewportI mapFrom, AlignViewportI mapTo)
279 * Note the SequenceGroup holds aligned sequences, the mappings hold dataset
282 boolean targetIsNucleotide = mapTo.isNucleotide();
283 AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
284 Set<AlignedCodonFrame> codonFrames = protein.getAlignment()
288 * Copy group name, colours, but not sequences
290 SequenceGroup mappedGroup = new SequenceGroup(sg);
292 // TODO set width of mapped group
294 for (SequenceI selected : sg.getSequences())
296 for (AlignedCodonFrame acf : codonFrames)
298 SequenceI mappedSequence = targetIsNucleotide ? acf
299 .getDnaForAaSeq(selected) : acf.getAaForDnaSeq(selected);
300 if (mappedSequence != null)
302 for (SequenceI seq : mapTo.getAlignment().getSequences())
304 if (seq.getDatasetSequence() == mappedSequence)
306 mappedGroup.addSequence(seq, false);
317 * Returns an OrderCommand equivalent to the given one, but acting on mapped
318 * sequences as described by the mappings, or null if no mapping can be made.
321 * the original order command
323 * if true, the action is to undo the sort
325 * the alignment we are mapping to
327 * the mappings available
330 public static CommandI mapOrderCommand(OrderCommand command,
331 boolean undo, AlignmentI mapTo, Set<AlignedCodonFrame> mappings)
333 SequenceI[] sortOrder = command.getSequenceOrder(undo);
334 List<SequenceI> mappedOrder = new ArrayList<SequenceI>();
336 for (SequenceI seq : sortOrder)
338 for (AlignedCodonFrame acf : mappings)
341 * Try protein-to-Dna, failing that try dna-to-protein
343 SequenceI mappedSeq = acf.getDnaForAaSeq(seq);
344 if (mappedSeq == null)
346 mappedSeq = acf.getAaForDnaSeq(seq);
348 if (mappedSeq != null)
350 for (SequenceI seq2 : mapTo.getSequences())
352 if (seq2.getDatasetSequence() == mappedSeq)
354 mappedOrder.add(seq2);
364 * Return null if no mappings made.
372 * Add any unmapped sequences on the end of the sort in their original
375 if (j < mapTo.getHeight())
377 for (SequenceI seq : mapTo.getSequences())
379 if (!mappedOrder.contains(seq))
381 mappedOrder.add(seq);
387 * Have to align the sequences before constructing the OrderCommand - which
388 * then realigns them?!?
390 final SequenceI[] mappedOrderArray = mappedOrder
391 .toArray(new SequenceI[mappedOrder.size()]);
392 SequenceI[] oldOrder = mapTo.getSequencesArray();
393 AlignmentSorter.sortBy(mapTo, new AlignmentOrder(mappedOrderArray));
394 final OrderCommand result = new OrderCommand(command.getDescription(),
400 * Returns a ColumnSelection in the 'mapTo' view which corresponds to the
401 * given selection in the 'mapFrom' view. We assume one is nucleotide, the
402 * other is protein (and holds the mappings from codons to protein residues).
409 public static ColumnSelection mapColumnSelection(ColumnSelection colsel,
410 AlignViewportI mapFrom, AlignViewport mapTo)
412 boolean targetIsNucleotide = mapTo.isNucleotide();
413 AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
414 Set<AlignedCodonFrame> codonFrames = protein.getAlignment()
416 ColumnSelection mappedColumns = new ColumnSelection();
417 char fromGapChar = mapFrom.getAlignment().getGapCharacter();
419 for (Object obj : colsel.getSelected())
421 int col = ((Integer) obj).intValue();
422 int mappedToMin = Integer.MAX_VALUE;
423 int mappedToMax = Integer.MIN_VALUE;
426 * For each sequence in the 'from' alignment
428 for (SequenceI fromSeq : mapFrom.getAlignment().getSequences())
431 * Ignore gaps (unmapped anyway)
433 if (fromSeq.getCharAt(col) == fromGapChar)
439 * Get the residue position and find the mapped position.
441 int residuePos = fromSeq.findPosition(col);
442 SearchResults sr = buildSearchResults(fromSeq, residuePos,
444 for (Match m : sr.getResults())
446 int mappedStartResidue = m.getStart();
447 int mappedEndResidue = m.getEnd();
448 SequenceI mappedSeq = m.getSequence();
451 * Locate the aligned sequence whose dataset is mappedSeq. TODO a
452 * datamodel that can do this efficiently.
454 for (SequenceI toSeq : mapTo.getAlignment().getSequences())
456 if (toSeq.getDatasetSequence() == mappedSeq)
458 int mappedStartCol = toSeq.findIndex(mappedStartResidue);
459 int mappedEndCol = toSeq.findIndex(mappedEndResidue);
460 mappedToMin = Math.min(mappedToMin, mappedStartCol);
461 mappedToMax = Math.max(mappedToMax, mappedEndCol);
462 // System.out.println(fromSeq.getName() + " mapped to cols "
463 // + mappedStartCol + ":" + mappedEndCol);
465 // TODO remove break if we ever want to map one to many sequences
471 * Add mapped columns to mapped selection (converting base 1 to base 0)
473 for (int i = mappedToMin; i <= mappedToMax; i++)
475 mappedColumns.addElement(i - 1);
478 return mappedColumns;