2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8.0b1)
3 * Copyright (C) 2014 The Jalview Authors
5 * This file is part of Jalview.
7 * Jalview is free software: you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation, either version 3 of the License, or (at your option) any later version.
11 * Jalview is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty
13 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
14 * PURPOSE. See the GNU General Public License for more details.
16 * You should have received a copy of the GNU General Public License along with Jalview. If not, see <http://www.gnu.org/licenses/>.
17 * The Jalview Authors are detailed in the 'AUTHORS' file.
19 package jalview.datamodel;
23 public abstract class CigarBase
26 * Base class for compact idiosyncratic representation of gaps and aligned
27 * residues Regards to Tom Oldfield for his DynamicArray class. 17th July 2006
32 // nothing to be done (probably)
35 protected int length = 0;
37 protected int _inc_length = 10; // extension range for addition of new
41 protected char[] operation = null;
43 protected int[] range = null;
46 * Range of Hidden residues in seq (translated as deleted in seq)
48 public static final char D = 'D';
51 * Range of insertions to seq
53 public static final char I = 'I';
56 * Range of aligned residues
58 public static final char M = 'M';
60 static protected final char _case_shift = 'a' - 'A';
63 * Ugly function to get edited sequence string, start and end symbol positions
64 * and the deletion regions as an array of int pairs May return null for an
65 * empty cigar string. May return null for deletion ranges if there are none.
68 * - the symbol sequence to apply the cigar operations to (or null if
71 * - the symbol to use for Insert operations
72 * @return Object[] { String, int[] {start, startcol, end, endcol}, int[][3]
73 * {start, end, col} or null} the gapped sequence, first and last
74 * residue index, and the deletion ranges on the reference sequence
76 public Object[] getSequenceAndDeletions(String reference, char GapChar)
79 int[][] deletions = new int[length][];
80 int[][] trunc_deletions = null;
81 StringBuffer sq = new StringBuffer();
82 int cursor = 0, alcursor = 0, start = 0, startpos = 0, end = 0, endpos = 0, delcount = -1;
83 boolean consecutive_del = false;
88 if (reference != null)
90 rlength = reference.length();
92 boolean modstart = true;
93 for (int i = 0; i < length; i++)
100 deletions[++delcount] = new int[]
101 { cursor, 0, alcursor };
104 deletions[delcount][1] = cursor - 1;
105 consecutive_del = true;
108 consecutive_del = false;
109 for (int r = 0; r < range[i]; r++)
116 consecutive_del = false;
123 if (reference != null)
125 int sbend = cursor + range[i];
128 sq.append(reference.substring(cursor, rlength));
129 while (sbend-- >= rlength)
136 sq.append(reference.substring(cursor, sbend));
139 alcursor += range[i];
145 throw new Error("Unknown SeqCigar operation '" + operation[i] + "'");
150 trunc_deletions = new int[delcount][];
151 System.arraycopy(deletions, 0, trunc_deletions, 0, delcount);
155 { ((reference != null) ? sq.toString() : null), new int[]
156 { start, startpos, end, endpos }, trunc_deletions };
159 protected void compact_operations()
162 if (operation == null)
166 char last = operation[0];
169 if (last == operation[i])
171 range[i - 1] += range[i];
175 System.arraycopy(range, i + 1, range, i, r);
176 System.arraycopy(operation, i + 1, operation, i, r);
182 last = operation[i++];
188 * turn a cigar string into a series of operation range pairs
192 * @return object[] {char[] operation, int[] range}
193 * @throws java.lang.Exception
194 * for improperly formated cigar strings or ones with unknown
197 public static Object[] parseCigarString(String cigarString)
201 for (int i = 0, l = cigarString.length(); i < l; i++)
203 char c = cigarString.charAt(i);
204 if (c == M || c == (M - _case_shift) || c == I
205 || c == (I - _case_shift) || c == D || c == (D - _case_shift))
210 char[] operation = new char[ops];
211 int[] range = new int[ops];
213 int i = 0, l = cigarString.length();
220 c = cigarString.charAt(j++);
221 } while (c >= '0' && c <= '9' && j < l);
222 if (j >= l && c >= '0' && c <= '9')
224 throw new Exception("Unterminated cigar string.");
228 String rangeint = cigarString.substring(i, j - 1);
229 range[op] = Integer.parseInt(rangeint);
231 } catch (Exception e)
233 throw new Error("Implementation bug in parseCigarString");
235 if (c >= 'a' && c <= 'z')
239 if ((c == M || c == I || c == D))
245 throw new Exception("Unexpected operation '" + c
246 + "' in cigar string (position " + i + " in '"
247 + cigarString + "'");
251 { operation, range };
255 * add an operation to cigar string
262 public void addOperation(char op, int range)
264 if (op >= 'a' && op <= 'z')
268 if (op != M && op != D && op != I)
270 throw new Error("Implementation error. Invalid operation string.");
274 return; // No Operation to add.
279 "Invalid range string (must be zero or positive number)");
282 if (operation == null)
284 this.operation = new char[_inc_length];
285 this.range = new int[_inc_length];
287 if (length + 1 == operation.length)
289 char[] ops = this.operation;
290 this.operation = new char[length + 1 + _inc_length];
291 System.arraycopy(ops, 0, this.operation, 0, length);
293 int[] rng = this.range;
294 this.range = new int[length + 1 + _inc_length];
295 System.arraycopy(rng, 0, this.range, 0, length);
298 if ((length > 0) && (operation[length - 1] == op))
300 length--; // modify existing operation.
304 this.range[length] = 0; // reset range
306 this.operation[length] = op;
307 this.range[length++] += range;
311 * semi-efficient insert an operation on the current cigar string set at
312 * column pos (from 1) NOTE: Insertion operations simply extend width of cigar
313 * result - affecting registration of alignment Deletion ops will shorten
314 * length of result - and affect registration of alignment Match ops will also
315 * affect length of result - affecting registration of alignment (ie
316 * "10M".insert(4,I,3)->"4M3I3M") - (replace?) (ie
317 * "10M".insert(4,D,3)->"4M3D3M") - (shortens alignment) (ie
318 * "5I5M".insert(4,I,3)->"8I5M") - real insertion (ie
319 * "5I5M".insert(4,D,3)->"4I2D3M") - shortens aligment - I's are removed, Ms
320 * changed to Ds (ie "10M".insert(4,M,3)->"13M") - lengthens - Is changed to
321 * M, Ds changed to M. (ie "5I5M".insert(4,M,3)->"4I8M") - effectively shifts
322 * sequence left by 1 residue and extends it by 3 (
323 * "10D5M".insert(-1,M,3)->"3M7D5M") ( "10D5M".insert(0,M,3)->"7D8M") (
324 * "10D5M".insert(1,M,3)->"10D8M") ( "1M10D5M".insert(0,M,3)->"1M10D8M") (
325 * "1M10D5M".insert(1,M,3)->"
327 * if pos is beyond width - I operations are added before the operation
330 * int -1, 0-length of visible region, or greater to append new ops
331 * (with insertions in between)
335 * int public void addOperationAt(int pos, char op, int range) { int
336 * cursor = -1; // mark the position for the current operation being
337 * edited. int o = 0; boolean last_d = false; // previous op was a
338 * deletion. if (pos < -1) throw new
339 * Error("pos<-1 is not supported."); while (o<length) { if
340 * (operation[o] != D) { if ( (cursor + this.range[o]) < pos) {
341 * cursor += this.range[o]; o++; last_d=false; } else { break; } }
342 * else { last_d=true; o++; } } if (o==length) { // must insert more
343 * operations before pos if (pos-cursor>0) addInsertion(pos-cursor);
344 * // then just add the new operation. Regardless of what it is.
345 * addOperation(op, range); } else { int diff = pos - cursor;
347 * int e_length = length-o; // new edit operation array length. //
348 * diff<0 - can only happen before first insertion or match. -
349 * affects op and all following // dif==0 - only when at first
350 * position of existing op - // diff>0 - must preserve some existing
351 * operations int[] e_range = new int[e_length];
352 * System.arraycopy(this.range, o, e_range, 0, e_length); char[] e_op
353 * = new char[e_length]; System.arraycopy(this.operation, o, e_op, 0,
354 * e_length); length = o; // can now use add_operation to extend
355 * list. int e_o=0; // current operation being edited. switch (op) {
356 * case M: switch (e_op[e_o]) { case M: if (last_d && diff <= 0) { //
357 * reduce D's, if possible if (range<=this.range[o-1]) { this.range[o
358 * - 1] -= range; } else { this.range[o-1]=0; } if
359 * (this.range[o-1]==0) o--; // lose this op. } e_range[e_o] +=
360 * range; // just add more matched residues break; case I: // change
361 * from insertion to match if (last_d && diff<=0) { // reduce D's, if
362 * possible if (range<=this.range[o-1]) { this.range[o - 1] -= range;
363 * } else { this.range[o-1]=0; } if (this.range[o-1]==0) o--; // lose
364 * this op. } e_range[e_o] break; default: throw new Inp }
366 * break; case I: break; case D: } break; default: throw new
367 * Error("Implementation Error: Unknown operation in addOperation!");
368 * } // finally, add remaining ops. while (e_o<e_length) {
369 * addOperation(e_op[e_o], e_range[e_o]); e_o++; } } }
372 * Mark residues from start to end (inclusive) as deleted from the alignment,
373 * and removes any insertions.
379 * @return deleted int - number of symbols marked as deleted
381 public int deleteRange(int start, int end)
386 // nothing to do here
389 if (start < 0 || start > end)
392 "Implementation Error: deleteRange out of bounds: start must be non-negative and less than end.");
395 int cursor = 0; // mark the position for the current operation being edited.
396 int rlength = 1 + end - start; // number of positions to delete
399 boolean editing = false;
400 char[] oldops = operation;
401 int[] oldrange = range;
405 compact_operations();
406 while (o < oldlen && cursor <= end && rlength > 0)
410 // absorbed into new deleted region.
411 addDeleted(oldrange[o++]);
415 int remain = oldrange[o]; // number of op characters left to edit
418 if ((cursor + remain) <= start)
420 addOperation(oldops[o], oldrange[o]);
421 cursor += oldrange[o++];
422 continue; // next operation
425 // add operations before hidden region
426 if (start - cursor > 0)
428 addOperation(oldops[o], start - cursor);
429 remain -= start - cursor;
432 // start inserting new ops
433 if (o < oldlen && editing && rlength > 0 && remain > 0)
438 if (rlength > remain)
447 if (remain - rlength > 0)
449 this.addOperation(M, remain - rlength); // add remaining back.
456 if (remain - rlength > 0)
458 // only remove some gaps
459 addInsertion(remain - rlength);
464 throw new Error("Implementation error."); // do nothing;
466 throw new Error("Implementation Error! Unknown operation '"
470 remain = oldrange[++o]; // number of op characters left to edit
476 addOperation(oldops[o], oldrange[o++]);
478 // if (cursor<(start+1)) {
479 // ran out of ops - nothing to do here ?
480 // addInsertion(start-cursor);
486 * Deleted regions mean that there will be discontinuous sequence numbering in
487 * the sequence returned by getSeq(char).
489 * @return true if there deletions
491 public boolean hasDeletedRegions()
493 for (int i = 0; i < length; i++)
495 if (operation[i] == D)
504 * enumerate the ranges on seq that are marked as deleted in this cigar
506 * @return int[] { vis_start, sym_start, length }
508 public int[] getDeletedRegions()
514 Vector dr = new Vector();
515 int cursor = 0, vcursor = 0;
516 for (int i = 0; i < length; i++)
518 switch (operation[i])
526 dr.addElement(new int[]
527 { vcursor, cursor, range[i] });
535 int[] delregions = new int[dr.size() * 3];
536 for (int i = 0, l = dr.size(); i < l; i++)
538 int[] reg = (int[]) dr.elementAt(i);
539 delregions[i * 3] = reg[0];
540 delregions[i * 3 + 1] = reg[1];
541 delregions[i * 3 + 2] = reg[2];
547 * sum of ranges in cigar string
549 * @return int number of residues hidden, matched, or gaps inserted into
552 public int getFullWidth()
557 for (int i = 0; i < length; i++)
566 * Visible length of aligned sequence
568 * @return int length of including gaps and less hidden regions
570 public int getWidth()
575 for (int i = 0; i < length; i++)
577 if (operation[i] == M || operation[i] == I)
587 * mark a range of inserted residues
592 public void addInsertion(int range)
594 this.addOperation(I, range);
598 * mark the next range residues as hidden (not aligned) or deleted
603 public void addDeleted(int range)
605 this.addOperation(D, range);
609 * Modifies operation list to delete columns from start to end (inclusive)
610 * editing will remove insertion operations, and convert matches to deletions
616 * @return boolean true if residues were marked as deleted. public boolean
617 * deleteRange(int start, int end) { boolean deleted = false; int op =
618 * 0, prevop = -1, firstm = -1, lastm = -1, postop = -1; int width =
619 * 0; // zero'th column if (length > 0) { // find operation bracketing
620 * start of the range do { if (operation[op] != D) { width +=
621 * range[prevop = op]; } op++; } while (op < length && width < start);
622 * } if (width < start) { // run off end - add more operations up to
623 * deletion. addInsertion(start - width); } else { // edit existing
624 * operations. op = prevop; width -= range[prevop]; int[] oldrange =
625 * range; char[] oldops = operation; range = new int[oldrange.length];
626 * operation = new char[oldops.length]; if (op < length) { do { if
627 * (operation[op] != D) { width += range[postop = op]; } op++; } while
628 * (op < length && width <= end); } } if (deleted == true) {
629 * addDeleted(end - start + 1); } return deleted; }
632 * Return an ENSEMBL style cigar string where D may indicates excluded parts
635 * @return String of form ([0-9]+[IMD])+
637 public String getCigarstring()
639 StringBuffer cigarString = new StringBuffer();
640 for (int i = 0; i < length; i++)
642 cigarString.append("" + range[i]);
643 cigarString.append(operation[i]);
645 return cigarString.toString();