3 import java.util.ArrayList;
4 import java.util.Collections;
5 import java.util.HashMap;
6 import java.util.Iterator;
11 import jalview.analysis.AlignmentSorter;
12 import jalview.api.AlignViewportI;
13 import jalview.commands.CommandI;
14 import jalview.commands.EditCommand;
15 import jalview.commands.EditCommand.Action;
16 import jalview.commands.EditCommand.Edit;
17 import jalview.commands.OrderCommand;
18 import jalview.datamodel.AlignedCodonFrame;
19 import jalview.datamodel.AlignmentI;
20 import jalview.datamodel.AlignmentOrder;
21 import jalview.datamodel.ColumnSelection;
22 import jalview.datamodel.SearchResults;
23 import jalview.datamodel.SearchResults.Match;
24 import jalview.datamodel.Sequence;
25 import jalview.datamodel.SequenceGroup;
26 import jalview.datamodel.SequenceI;
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(seq);
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(final SequenceGroup sg,
275 final AlignViewportI mapFrom, final 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()
286 * Copy group name, colours etc, but not sequences or sequence colour scheme
288 SequenceGroup mappedGroup = new SequenceGroup(sg);
289 mappedGroup.cs = mapTo.getGlobalColourScheme();
292 int minStartCol = -1;
294 final int selectionStartRes = sg.getStartRes();
295 final int selectionEndRes = sg.getEndRes();
296 for (SequenceI selected : sg.getSequences())
299 * Find the widest range of non-gapped positions in the selection range
301 int firstUngappedPos = selectionStartRes;
302 while (firstUngappedPos <= selectionEndRes
303 && Comparison.isGap(selected.getCharAt(firstUngappedPos)))
309 * If this sequence is only gaps in the selected range, skip it
311 if (firstUngappedPos > selectionEndRes)
316 int lastUngappedPos = selectionEndRes;
317 while (lastUngappedPos >= selectionStartRes
318 && Comparison.isGap(selected.getCharAt(lastUngappedPos)))
324 * Find the selected start/end residue positions in sequence
326 int startResiduePos = selected.findPosition(firstUngappedPos);
327 int endResiduePos = selected.findPosition(lastUngappedPos);
329 for (AlignedCodonFrame acf : codonFrames)
331 SequenceI mappedSequence = targetIsNucleotide ? acf
332 .getDnaForAaSeq(selected) : acf.getAaForDnaSeq(selected);
333 if (mappedSequence != null)
335 for (SequenceI seq : mapTo.getAlignment().getSequences())
337 int mappedStartResidue = 0;
338 int mappedEndResidue = 0;
339 if (seq.getDatasetSequence() == mappedSequence)
342 * Found a sequence mapping. Locate the start/end mapped residues.
344 SearchResults sr = buildSearchResults(selected,
345 startResiduePos, Collections.singleton(acf));
346 for (Match m : sr.getResults())
348 mappedStartResidue = m.getStart();
349 mappedEndResidue = m.getEnd();
351 sr = buildSearchResults(selected, endResiduePos,
352 Collections.singleton(acf));
353 for (Match m : sr.getResults())
355 mappedStartResidue = Math.min(mappedStartResidue,
357 mappedEndResidue = Math.max(mappedEndResidue, m.getEnd());
361 * Find the mapped aligned columns, save the range. Note findIndex
362 * returns a base 1 position, SequenceGroup uses base 0
364 int mappedStartCol = seq.findIndex(mappedStartResidue) - 1;
365 minStartCol = minStartCol == -1 ? mappedStartCol : Math.min(
366 minStartCol, mappedStartCol);
367 int mappedEndCol = seq.findIndex(mappedEndResidue) - 1;
368 maxEndCol = maxEndCol == -1 ? mappedEndCol : Math.max(
369 maxEndCol, mappedEndCol);
370 mappedGroup.addSequence(seq, false);
377 mappedGroup.setStartRes(minStartCol < 0 ? 0 : minStartCol);
378 mappedGroup.setEndRes(maxEndCol < 0 ? 0 : maxEndCol);
383 * Returns an OrderCommand equivalent to the given one, but acting on mapped
384 * sequences as described by the mappings, or null if no mapping can be made.
387 * the original order command
389 * if true, the action is to undo the sort
391 * the alignment we are mapping to
393 * the mappings available
396 public static CommandI mapOrderCommand(OrderCommand command,
397 boolean undo, AlignmentI mapTo, Set<AlignedCodonFrame> mappings)
399 SequenceI[] sortOrder = command.getSequenceOrder(undo);
400 List<SequenceI> mappedOrder = new ArrayList<SequenceI>();
402 for (SequenceI seq : sortOrder)
404 for (AlignedCodonFrame acf : mappings)
407 * Try protein-to-Dna, failing that try dna-to-protein
409 SequenceI mappedSeq = acf.getDnaForAaSeq(seq);
410 if (mappedSeq == null)
412 mappedSeq = acf.getAaForDnaSeq(seq);
414 if (mappedSeq != null)
416 for (SequenceI seq2 : mapTo.getSequences())
418 if (seq2.getDatasetSequence() == mappedSeq)
420 mappedOrder.add(seq2);
430 * Return null if no mappings made.
438 * Add any unmapped sequences on the end of the sort in their original
441 if (j < mapTo.getHeight())
443 for (SequenceI seq : mapTo.getSequences())
445 if (!mappedOrder.contains(seq))
447 mappedOrder.add(seq);
453 * Have to sort the sequences before constructing the OrderCommand - which
454 * then resorts them?!?
456 final SequenceI[] mappedOrderArray = mappedOrder
457 .toArray(new SequenceI[mappedOrder.size()]);
458 SequenceI[] oldOrder = mapTo.getSequencesArray();
459 AlignmentSorter.sortBy(mapTo, new AlignmentOrder(mappedOrderArray));
460 final OrderCommand result = new OrderCommand(command.getDescription(),
466 * Returns a ColumnSelection in the 'mapTo' view which corresponds to the
467 * given selection in the 'mapFrom' view. We assume one is nucleotide, the
468 * other is protein (and holds the mappings from codons to protein residues).
475 public static ColumnSelection mapColumnSelection(ColumnSelection colsel,
476 AlignViewportI mapFrom, AlignViewportI mapTo)
478 boolean targetIsNucleotide = mapTo.isNucleotide();
479 AlignViewportI protein = targetIsNucleotide ? mapFrom : mapTo;
480 Set<AlignedCodonFrame> codonFrames = protein.getAlignment()
482 ColumnSelection mappedColumns = new ColumnSelection();
483 char fromGapChar = mapFrom.getAlignment().getGapCharacter();
485 // FIXME allow for hidden columns
488 * For each mapped column, find the range of columns that residues in that
491 for (Object obj : colsel.getSelected())
493 int col = ((Integer) obj).intValue();
494 int mappedToMin = Integer.MAX_VALUE;
495 int mappedToMax = Integer.MIN_VALUE;
498 * For each sequence in the 'from' alignment
500 for (SequenceI fromSeq : mapFrom.getAlignment().getSequences())
503 * Ignore gaps (unmapped anyway)
505 if (fromSeq.getCharAt(col) == fromGapChar)
511 * Get the residue position and find the mapped position.
513 int residuePos = fromSeq.findPosition(col);
514 SearchResults sr = buildSearchResults(fromSeq, residuePos,
516 for (Match m : sr.getResults())
518 int mappedStartResidue = m.getStart();
519 int mappedEndResidue = m.getEnd();
520 SequenceI mappedSeq = m.getSequence();
523 * Locate the aligned sequence whose dataset is mappedSeq. TODO a
524 * datamodel that can do this efficiently.
526 for (SequenceI toSeq : mapTo.getAlignment().getSequences())
528 if (toSeq.getDatasetSequence() == mappedSeq)
530 int mappedStartCol = toSeq.findIndex(mappedStartResidue);
531 int mappedEndCol = toSeq.findIndex(mappedEndResidue);
532 mappedToMin = Math.min(mappedToMin, mappedStartCol);
533 mappedToMax = Math.max(mappedToMax, mappedEndCol);
534 // System.out.println(fromSeq.getName() + " mapped to cols "
535 // + mappedStartCol + ":" + mappedEndCol);
537 // note: remove break if we ever want to map one to many sequences
543 * Add the range of mapped columns to the mapped selection (converting
544 * base 1 to base 0). Note that this may include intron-only regions which
545 * lie between the start and end ranges of the selection.
547 for (int i = mappedToMin; i <= mappedToMax; i++)
549 mappedColumns.addElement(i - 1);
552 return mappedColumns;
556 * Returns the mapped codon for a given aligned sequence column position (base
560 * an aligned peptide sequence
562 * an aligned column position (base 0)
564 * a set of codon mappings
565 * @return the bases of the mapped codon in the cDNA dataset sequence, or null
568 public static char[] findCodonFor(SequenceI seq, int col,
569 Set<AlignedCodonFrame> mappings)
571 int dsPos = seq.findPosition(col);
572 for (AlignedCodonFrame mapping : mappings)
574 if (mapping.involvesSequence(seq))
576 return mapping.getMappedCodon(seq.getDatasetSequence(), dsPos);
583 * Converts a series of [start, end] ranges into an array of individual
589 public static int[] flattenRanges(int[] ranges)
592 * Count how many positions altogether
595 for (int i = 0; i < ranges.length - 1; i += 2)
597 count += ranges[i + 1] - ranges[i] + 1;
600 int[] result = new int[count];
602 for (int i = 0; i < ranges.length - 1; i += 2)
604 for (int j = ranges[i]; j <= ranges[i + 1]; j++)
613 * Returns a list of any mappings that are from or to the given (aligned or
620 public static List<AlignedCodonFrame> findMappingsForSequence(
621 SequenceI sequence, Set<AlignedCodonFrame> mappings)
623 List<AlignedCodonFrame> result = new ArrayList<AlignedCodonFrame>();
624 if (sequence == null || mappings == null)
628 for (AlignedCodonFrame mapping : mappings) {
629 if (mapping.involvesSequence(sequence)) {