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;
20 import java.util.ArrayList;
21 import java.util.HashMap;
22 import java.util.Iterator;
23 import java.util.List;
28 * Helper methods for manipulations involving sequence mappings.
33 public final class MappingUtils
37 * Helper method to map a CUT or PASTE command.
40 * the original command
42 * if true, the command is to be undone
44 * the mapped sequences to apply the mapped command to
46 * the mapped EditCommand to add to
49 protected static void mapCutOrPaste(Edit edit, boolean undo,
50 List<SequenceI> targetSeqs, EditCommand result,
51 Set<AlignedCodonFrame> mappings)
53 Action action = edit.getAction();
56 action = action.getUndoAction();
59 System.err.println("MappingUtils.mapCutOrPaste not yet implemented");
63 * Returns a new EditCommand representing the given command as mapped to the
64 * given sequences. If there is no mapping, returns null.
73 public static EditCommand mapEditCommand(EditCommand command,
74 boolean undo, final AlignmentI mapTo, char gapChar,
75 Set<AlignedCodonFrame> mappings)
78 * For now, only support mapping from protein edits to cDna
80 if (!mapTo.isNucleotide())
86 * Cache a copy of the target sequences so we can mimic successive edits on
87 * them. This lets us compute mappings for all edits in the set.
89 Map<SequenceI, SequenceI> targetCopies = new HashMap<SequenceI, SequenceI>();
90 for (SequenceI seq : mapTo.getSequences())
92 SequenceI ds = seq.getDatasetSequence();
95 final SequenceI copy = new Sequence("", new String(
97 copy.setDatasetSequence(ds);
98 targetCopies.put(ds, copy);
103 * Compute 'source' sequences as they were before applying edits:
105 Map<SequenceI, SequenceI> originalSequences = command.priorState(undo);
107 EditCommand result = new EditCommand();
108 Iterator<Edit> edits = command.getEditIterator(!undo);
109 while (edits.hasNext())
111 Edit edit = edits.next();
112 if (edit.getAction() == Action.CUT
113 || edit.getAction() == Action.PASTE)
115 mapCutOrPaste(edit, undo, mapTo.getSequences(), result, mappings);
117 else if (edit.getAction() == Action.INSERT_GAP
118 || edit.getAction() == Action.DELETE_GAP)
120 mapInsertOrDelete(edit, undo, originalSequences,
121 mapTo.getSequences(), targetCopies, gapChar, result,
125 return result.getSize() > 0 ? result : null;
129 * Helper method to map an edit command to insert or delete gaps.
132 * the original command
134 * if true, the action is to undo the command
135 * @param originalSequences
136 * the sequences the command acted on
138 * @param targetCopies
141 * the new EditCommand to add mapped commands to
144 protected static void mapInsertOrDelete(Edit edit, boolean undo,
145 Map<SequenceI, SequenceI> originalSequences,
146 final List<SequenceI> targetSeqs,
147 Map<SequenceI, SequenceI> targetCopies, char gapChar,
148 EditCommand result, Set<AlignedCodonFrame> mappings)
150 Action action = edit.getAction();
153 * Invert sense of action if an Undo.
157 action = action.getUndoAction();
159 final int count = edit.getNumber();
160 final int editPos = edit.getPosition();
161 for (SequenceI seq : edit.getSequences())
164 * Get residue position at (or to right of) edit location. Note we use our
165 * 'copy' of the sequence before editing for this.
167 SequenceI ds = seq.getDatasetSequence();
172 final SequenceI actedOn = originalSequences.get(ds);
173 final int seqpos = actedOn.findPosition(editPos);
176 * Determine all mappings from this position to mapped sequences.
178 SearchResults sr = buildSearchResults(seq, seqpos, mappings);
182 for (SequenceI targetSeq : targetSeqs)
184 ds = targetSeq.getDatasetSequence();
189 SequenceI copyTarget = targetCopies.get(ds);
190 final int[] match = sr.getResults(copyTarget, 0,
191 copyTarget.getLength());
194 final int ratio = 3; // TODO: compute this - how?
195 final int mappedCount = count * ratio;
198 * Shift Delete start position left, as it acts on positions to its
201 int mappedEditPos = action == Action.DELETE_GAP ? match[0]
202 - mappedCount : match[0];
203 Edit e = result.new Edit(action, new SequenceI[]
204 { targetSeq }, mappedEditPos, mappedCount, gapChar);
208 * and 'apply' the edit to our copy of its target sequence
210 if (action == Action.INSERT_GAP)
212 copyTarget.setSequence(new String(StringUtils.insertCharAt(
213 copyTarget.getSequence(), mappedEditPos, mappedCount,
216 else if (action == Action.DELETE_GAP)
218 copyTarget.setSequence(new String(StringUtils.deleteChars(
219 copyTarget.getSequence(), mappedEditPos,
220 mappedEditPos + mappedCount)));
226 * and 'apply' the edit to our copy of its source sequence
228 if (action == Action.INSERT_GAP)
230 actedOn.setSequence(new String(StringUtils.insertCharAt(
231 actedOn.getSequence(), editPos, count, gapChar)));
233 else if (action == Action.DELETE_GAP)
235 actedOn.setSequence(new String(StringUtils.deleteChars(
236 actedOn.getSequence(), editPos, editPos + count)));
242 * Returns a SearchResults object describing the mapped region corresponding
243 * to the specified sequence position.
250 public static SearchResults buildSearchResults(SequenceI seq, int index,
251 Set<AlignedCodonFrame> seqmappings)
253 SearchResults results;
254 results = new SearchResults();
255 if (index >= seq.getStart() && index <= seq.getEnd())
257 for (AlignedCodonFrame acf : seqmappings)
259 acf.markMappedRegion(seq, index, results);
266 * Returns a (possibly empty) SequenceGroup containing any sequences in the
267 * mapped viewport corresponding to the given group in the source viewport.
274 public static SequenceGroup mapSequenceGroup(SequenceGroup sg,
275 AlignViewportI mapFrom, AlignViewportI mapTo)
278 * Note the SequenceGroup holds aligned sequences, the mappings hold dataset
281 boolean targetIsNucleotide = mapTo.isNucleotide();
282 AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
283 Set<AlignedCodonFrame> codonFrames = protein.getAlignment()
287 * Copy group name, colours, but not sequences
289 SequenceGroup mappedGroup = new SequenceGroup(sg);
291 // TODO set width of mapped group
293 for (SequenceI selected : sg.getSequences())
295 for (AlignedCodonFrame acf : codonFrames)
297 SequenceI mappedSequence = targetIsNucleotide ? acf
298 .getDnaForAaSeq(selected) : acf.getAaForDnaSeq(selected);
299 if (mappedSequence != null)
301 for (SequenceI seq : mapTo.getAlignment().getSequences())
303 if (seq.getDatasetSequence() == mappedSequence)
305 mappedGroup.addSequence(seq, false);
316 * Returns an OrderCommand equivalent to the given one, but acting on mapped
317 * sequences as described by the mappings, or null if no mapping can be made.
320 * the original order command
322 * if true, the action is to undo the sort
324 * the alignment we are mapping to
326 * the mappings available
329 public static CommandI mapOrderCommand(OrderCommand command,
330 boolean undo, AlignmentI mapTo, Set<AlignedCodonFrame> mappings)
332 SequenceI[] sortOrder = command.getSequenceOrder(undo);
333 List<SequenceI> mappedOrder = new ArrayList<SequenceI>();
335 for (SequenceI seq : sortOrder)
337 for (AlignedCodonFrame acf : mappings)
340 * Try protein-to-Dna, failing that try dna-to-protein
342 SequenceI mappedSeq = acf.getDnaForAaSeq(seq);
343 if (mappedSeq == null)
345 mappedSeq = acf.getAaForDnaSeq(seq);
347 if (mappedSeq != null)
349 for (SequenceI seq2 : mapTo.getSequences())
351 if (seq2.getDatasetSequence() == mappedSeq)
353 mappedOrder.add(seq2);
363 * Return null if no mappings made.
371 * Add any unmapped sequences on the end of the sort in their original
374 if (j < mapTo.getHeight())
376 for (SequenceI seq : mapTo.getSequences())
378 if (!mappedOrder.contains(seq))
380 mappedOrder.add(seq);
386 * Have to sort the sequences before constructing the OrderCommand - which
387 * then resorts them?!?
389 final SequenceI[] mappedOrderArray = mappedOrder
390 .toArray(new SequenceI[mappedOrder.size()]);
391 SequenceI[] oldOrder = mapTo.getSequencesArray();
392 AlignmentSorter.sortBy(mapTo, new AlignmentOrder(mappedOrderArray));
393 final OrderCommand result = new OrderCommand(command.getDescription(),
399 * Returns a ColumnSelection in the 'mapTo' view which corresponds to the
400 * given selection in the 'mapFrom' view. We assume one is nucleotide, the
401 * other is protein (and holds the mappings from codons to protein residues).
408 public static ColumnSelection mapColumnSelection(ColumnSelection colsel,
409 AlignViewportI mapFrom, AlignViewportI mapTo)
411 boolean targetIsNucleotide = mapTo.isNucleotide();
412 AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
413 Set<AlignedCodonFrame> codonFrames = protein.getAlignment()
415 ColumnSelection mappedColumns = new ColumnSelection();
416 char fromGapChar = mapFrom.getAlignment().getGapCharacter();
418 // FIXME allow for hidden columns
421 * For each mapped column, find the range of columns that residues in that
424 for (Object obj : colsel.getSelected())
426 int col = ((Integer) obj).intValue();
427 int mappedToMin = Integer.MAX_VALUE;
428 int mappedToMax = Integer.MIN_VALUE;
431 * For each sequence in the 'from' alignment
433 for (SequenceI fromSeq : mapFrom.getAlignment().getSequences())
436 * Ignore gaps (unmapped anyway)
438 if (fromSeq.getCharAt(col) == fromGapChar)
444 * Get the residue position and find the mapped position.
446 int residuePos = fromSeq.findPosition(col);
447 SearchResults sr = buildSearchResults(fromSeq, residuePos,
449 for (Match m : sr.getResults())
451 int mappedStartResidue = m.getStart();
452 int mappedEndResidue = m.getEnd();
453 SequenceI mappedSeq = m.getSequence();
456 * Locate the aligned sequence whose dataset is mappedSeq. TODO a
457 * datamodel that can do this efficiently.
459 for (SequenceI toSeq : mapTo.getAlignment().getSequences())
461 if (toSeq.getDatasetSequence() == mappedSeq)
463 int mappedStartCol = toSeq.findIndex(mappedStartResidue);
464 int mappedEndCol = toSeq.findIndex(mappedEndResidue);
465 mappedToMin = Math.min(mappedToMin, mappedStartCol);
466 mappedToMax = Math.max(mappedToMax, mappedEndCol);
467 // System.out.println(fromSeq.getName() + " mapped to cols "
468 // + mappedStartCol + ":" + mappedEndCol);
470 // note: remove break if we ever want to map one to many sequences
476 * Add the range of mapped columns to the mapped selection (converting
477 * base 1 to base 0). Note that this may include intron-only regions which
478 * lie between the start and end ranges of the selection.
480 for (int i = mappedToMin; i <= mappedToMax; i++)
482 mappedColumns.addElement(i - 1);
485 return mappedColumns;