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, name colours, but not sequences or sequence colour
290 SequenceGroup mappedGroup = new SequenceGroup(sg);
291 mappedGroup.cs = mapTo.getGlobalColourScheme();
293 // TODO set width of mapped group
295 for (SequenceI selected : sg.getSequences())
297 for (AlignedCodonFrame acf : codonFrames)
299 SequenceI mappedSequence = targetIsNucleotide ? acf
300 .getDnaForAaSeq(selected) : acf.getAaForDnaSeq(selected);
301 if (mappedSequence != null)
303 for (SequenceI seq : mapTo.getAlignment().getSequences())
305 if (seq.getDatasetSequence() == mappedSequence)
307 mappedGroup.addSequence(seq, false);
318 * Returns an OrderCommand equivalent to the given one, but acting on mapped
319 * sequences as described by the mappings, or null if no mapping can be made.
322 * the original order command
324 * if true, the action is to undo the sort
326 * the alignment we are mapping to
328 * the mappings available
331 public static CommandI mapOrderCommand(OrderCommand command,
332 boolean undo, AlignmentI mapTo, Set<AlignedCodonFrame> mappings)
334 SequenceI[] sortOrder = command.getSequenceOrder(undo);
335 List<SequenceI> mappedOrder = new ArrayList<SequenceI>();
337 for (SequenceI seq : sortOrder)
339 for (AlignedCodonFrame acf : mappings)
342 * Try protein-to-Dna, failing that try dna-to-protein
344 SequenceI mappedSeq = acf.getDnaForAaSeq(seq);
345 if (mappedSeq == null)
347 mappedSeq = acf.getAaForDnaSeq(seq);
349 if (mappedSeq != null)
351 for (SequenceI seq2 : mapTo.getSequences())
353 if (seq2.getDatasetSequence() == mappedSeq)
355 mappedOrder.add(seq2);
365 * Return null if no mappings made.
373 * Add any unmapped sequences on the end of the sort in their original
376 if (j < mapTo.getHeight())
378 for (SequenceI seq : mapTo.getSequences())
380 if (!mappedOrder.contains(seq))
382 mappedOrder.add(seq);
388 * Have to sort the sequences before constructing the OrderCommand - which
389 * then resorts them?!?
391 final SequenceI[] mappedOrderArray = mappedOrder
392 .toArray(new SequenceI[mappedOrder.size()]);
393 SequenceI[] oldOrder = mapTo.getSequencesArray();
394 AlignmentSorter.sortBy(mapTo, new AlignmentOrder(mappedOrderArray));
395 final OrderCommand result = new OrderCommand(command.getDescription(),
401 * Returns a ColumnSelection in the 'mapTo' view which corresponds to the
402 * given selection in the 'mapFrom' view. We assume one is nucleotide, the
403 * other is protein (and holds the mappings from codons to protein residues).
410 public static ColumnSelection mapColumnSelection(ColumnSelection colsel,
411 AlignViewportI mapFrom, AlignViewportI mapTo)
413 boolean targetIsNucleotide = mapTo.isNucleotide();
414 AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
415 Set<AlignedCodonFrame> codonFrames = protein.getAlignment()
417 ColumnSelection mappedColumns = new ColumnSelection();
418 char fromGapChar = mapFrom.getAlignment().getGapCharacter();
420 // FIXME allow for hidden columns
423 * For each mapped column, find the range of columns that residues in that
426 for (Object obj : colsel.getSelected())
428 int col = ((Integer) obj).intValue();
429 int mappedToMin = Integer.MAX_VALUE;
430 int mappedToMax = Integer.MIN_VALUE;
433 * For each sequence in the 'from' alignment
435 for (SequenceI fromSeq : mapFrom.getAlignment().getSequences())
438 * Ignore gaps (unmapped anyway)
440 if (fromSeq.getCharAt(col) == fromGapChar)
446 * Get the residue position and find the mapped position.
448 int residuePos = fromSeq.findPosition(col);
449 SearchResults sr = buildSearchResults(fromSeq, residuePos,
451 for (Match m : sr.getResults())
453 int mappedStartResidue = m.getStart();
454 int mappedEndResidue = m.getEnd();
455 SequenceI mappedSeq = m.getSequence();
458 * Locate the aligned sequence whose dataset is mappedSeq. TODO a
459 * datamodel that can do this efficiently.
461 for (SequenceI toSeq : mapTo.getAlignment().getSequences())
463 if (toSeq.getDatasetSequence() == mappedSeq)
465 int mappedStartCol = toSeq.findIndex(mappedStartResidue);
466 int mappedEndCol = toSeq.findIndex(mappedEndResidue);
467 mappedToMin = Math.min(mappedToMin, mappedStartCol);
468 mappedToMax = Math.max(mappedToMax, mappedEndCol);
469 // System.out.println(fromSeq.getName() + " mapped to cols "
470 // + mappedStartCol + ":" + mappedEndCol);
472 // note: remove break if we ever want to map one to many sequences
478 * Add the range of mapped columns to the mapped selection (converting
479 * base 1 to base 0). Note that this may include intron-only regions which
480 * lie between the start and end ranges of the selection.
482 for (int i = mappedToMin; i <= mappedToMax; i++)
484 mappedColumns.addElement(i - 1);
487 return mappedColumns;