2 * Jalview - A Sequence Alignment Editor and Viewer ($$Version-Rel$$)
3 * Copyright (C) $$Year-Rel$$ 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
10 * of the License, or (at your option) any later version.
12 * Jalview is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty
14 * of MERCHANTABILITY or FITNESS FOR A PARTICULAR
15 * PURPOSE. See the GNU General Public License for more details.
17 * You should have received a copy of the GNU General Public License
18 * along with Jalview. If not, see <http://www.gnu.org/licenses/>.
19 * The Jalview Authors are detailed in the 'AUTHORS' file.
21 package jalview.datamodel;
23 import jalview.util.MessageManager;
27 public abstract class CigarBase
30 * Base class for compact idiosyncratic representation of gaps and aligned
31 * residues Regards to Tom Oldfield for his DynamicArray class. 17th July 2006
36 // nothing to be done (probably)
39 protected int length = 0;
41 protected int _inc_length = 10; // extension range for addition of new
45 protected char[] operation = null;
47 protected int[] range = null;
50 * Range of Hidden residues in seq (translated as deleted in seq)
52 public static final char D = 'D';
55 * Range of insertions to seq
57 public static final char I = 'I';
60 * Range of aligned residues
62 public static final char M = 'M';
64 static protected final char _case_shift = 'a' - 'A';
67 * Ugly function to get edited sequence string, start and end symbol positions
68 * and the deletion regions as an array of int pairs May return null for an
69 * empty cigar string. May return null for deletion ranges if there are none.
72 * - the symbol sequence to apply the cigar operations to (or null if
75 * - the symbol to use for Insert operations
76 * @return Object[] { String, int[] {start, startcol, end, endcol}, int[][3]
77 * {start, end, col} or null} the gapped sequence, first and last
78 * residue index, and the deletion ranges on the reference sequence
80 public Object[] getSequenceAndDeletions(String reference, char GapChar)
83 int[][] deletions = new int[length][];
84 int[][] trunc_deletions = null;
85 StringBuffer sq = new StringBuffer();
86 int cursor = 0, alcursor = 0, start = 0, startpos = 0, end = 0, endpos = 0, delcount = -1;
87 boolean consecutive_del = false;
92 if (reference != null)
94 rlength = reference.length();
96 boolean modstart = true;
97 for (int i = 0; i < length; i++)
102 if (!consecutive_del)
104 deletions[++delcount] = new int[]
105 { cursor, 0, alcursor };
108 deletions[delcount][1] = cursor - 1;
109 consecutive_del = true;
112 consecutive_del = false;
113 for (int r = 0; r < range[i]; r++)
120 consecutive_del = false;
127 if (reference != null)
129 int sbend = cursor + range[i];
132 sq.append(reference.substring(cursor, rlength));
133 while (sbend-- >= rlength)
140 sq.append(reference.substring(cursor, sbend));
143 alcursor += range[i];
149 throw new Error(MessageManager.formatMessage("error.unknown_seq_cigar_operation", new String[]{new StringBuffer(operation[i]).toString()}));
154 trunc_deletions = new int[delcount][];
155 System.arraycopy(deletions, 0, trunc_deletions, 0, delcount);
159 { ((reference != null) ? sq.toString() : null), new int[]
160 { start, startpos, end, endpos }, trunc_deletions };
163 protected void compact_operations()
166 if (operation == null)
170 char last = operation[0];
173 if (last == operation[i])
175 range[i - 1] += range[i];
179 System.arraycopy(range, i + 1, range, i, r);
180 System.arraycopy(operation, i + 1, operation, i, r);
186 last = operation[i++];
192 * turn a cigar string into a series of operation range pairs
196 * @return object[] {char[] operation, int[] range}
197 * @throws java.lang.Exception
198 * for improperly formated cigar strings or ones with unknown
201 public static Object[] parseCigarString(String cigarString)
205 for (int i = 0, l = cigarString.length(); i < l; i++)
207 char c = cigarString.charAt(i);
208 if (c == M || c == (M - _case_shift) || c == I
209 || c == (I - _case_shift) || c == D || c == (D - _case_shift))
214 char[] operation = new char[ops];
215 int[] range = new int[ops];
217 int i = 0, l = cigarString.length();
224 c = cigarString.charAt(j++);
225 } while (c >= '0' && c <= '9' && j < l);
226 if (j >= l && c >= '0' && c <= '9')
228 throw new Exception(MessageManager.getString("exception.unterminated_cigar_string"));
232 String rangeint = cigarString.substring(i, j - 1);
233 range[op] = Integer.parseInt(rangeint);
235 } catch (Exception e)
237 throw new Error(MessageManager.getString("error.implementation_bug_parse_cigar_string"));
239 if (c >= 'a' && c <= 'z')
243 if ((c == M || c == I || c == D))
249 throw new Exception(MessageManager.formatMessage("exception.unexpected_operation_cigar_string_pos", new String[]{
250 new StringBuffer(c).toString(),
251 Integer.valueOf(i).toString(),
257 { operation, range };
261 * add an operation to cigar string
268 public void addOperation(char op, int range)
270 if (op >= 'a' && op <= 'z')
274 if (op != M && op != D && op != I)
276 throw new Error(MessageManager.getString("error.implementation_error_invalid_operation_string"));
280 return; // No Operation to add.
284 throw new Error(MessageManager.getString("error.invalid_range_string"));
287 if (operation == null)
289 this.operation = new char[_inc_length];
290 this.range = new int[_inc_length];
292 if (length + 1 == operation.length)
294 char[] ops = this.operation;
295 this.operation = new char[length + 1 + _inc_length];
296 System.arraycopy(ops, 0, this.operation, 0, length);
298 int[] rng = this.range;
299 this.range = new int[length + 1 + _inc_length];
300 System.arraycopy(rng, 0, this.range, 0, length);
303 if ((length > 0) && (operation[length - 1] == op))
305 length--; // modify existing operation.
309 this.range[length] = 0; // reset range
311 this.operation[length] = op;
312 this.range[length++] += range;
316 * semi-efficient insert an operation on the current cigar string set at
317 * column pos (from 1) NOTE: Insertion operations simply extend width of cigar
318 * result - affecting registration of alignment Deletion ops will shorten
319 * length of result - and affect registration of alignment Match ops will also
320 * affect length of result - affecting registration of alignment (ie
321 * "10M".insert(4,I,3)->"4M3I3M") - (replace?) (ie
322 * "10M".insert(4,D,3)->"4M3D3M") - (shortens alignment) (ie
323 * "5I5M".insert(4,I,3)->"8I5M") - real insertion (ie
324 * "5I5M".insert(4,D,3)->"4I2D3M") - shortens aligment - I's are removed, Ms
325 * changed to Ds (ie "10M".insert(4,M,3)->"13M") - lengthens - Is changed to
326 * M, Ds changed to M. (ie "5I5M".insert(4,M,3)->"4I8M") - effectively shifts
327 * sequence left by 1 residue and extends it by 3 (
328 * "10D5M".insert(-1,M,3)->"3M7D5M") ( "10D5M".insert(0,M,3)->"7D8M") (
329 * "10D5M".insert(1,M,3)->"10D8M") ( "1M10D5M".insert(0,M,3)->"1M10D8M") (
330 * "1M10D5M".insert(1,M,3)->"
332 * if pos is beyond width - I operations are added before the operation
335 * int -1, 0-length of visible region, or greater to append new ops
336 * (with insertions in between)
340 * int public void addOperationAt(int pos, char op, int range) { int
341 * cursor = -1; // mark the position for the current operation being
342 * edited. int o = 0; boolean last_d = false; // previous op was a
343 * deletion. if (pos < -1) throw new
344 * Error("pos<-1 is not supported."); while (o<length) { if
345 * (operation[o] != D) { if ( (cursor + this.range[o]) < pos) {
346 * cursor += this.range[o]; o++; last_d=false; } else { break; } }
347 * else { last_d=true; o++; } } if (o==length) { // must insert more
348 * operations before pos if (pos-cursor>0) addInsertion(pos-cursor);
349 * // then just add the new operation. Regardless of what it is.
350 * addOperation(op, range); } else { int diff = pos - cursor;
352 * int e_length = length-o; // new edit operation array length. //
353 * diff<0 - can only happen before first insertion or match. -
354 * affects op and all following // dif==0 - only when at first
355 * position of existing op - // diff>0 - must preserve some existing
356 * operations int[] e_range = new int[e_length];
357 * System.arraycopy(this.range, o, e_range, 0, e_length); char[] e_op
358 * = new char[e_length]; System.arraycopy(this.operation, o, e_op, 0,
359 * e_length); length = o; // can now use add_operation to extend
360 * list. int e_o=0; // current operation being edited. switch (op) {
361 * case M: switch (e_op[e_o]) { case M: if (last_d && diff <= 0) { //
362 * reduce D's, if possible if (range<=this.range[o-1]) { this.range[o
363 * - 1] -= range; } else { this.range[o-1]=0; } if
364 * (this.range[o-1]==0) o--; // lose this op. } e_range[e_o] +=
365 * range; // just add more matched residues break; case I: // change
366 * from insertion to match if (last_d && diff<=0) { // reduce D's, if
367 * possible if (range<=this.range[o-1]) { this.range[o - 1] -= range;
368 * } else { this.range[o-1]=0; } if (this.range[o-1]==0) o--; // lose
369 * this op. } e_range[e_o] break; default: throw new Inp }
371 * break; case I: break; case D: } break; default: throw new
372 * Error("Implementation Error: Unknown operation in addOperation!");
373 * } // finally, add remaining ops. while (e_o<e_length) {
374 * addOperation(e_op[e_o], e_range[e_o]); e_o++; } } }
377 * Mark residues from start to end (inclusive) as deleted from the alignment,
378 * and removes any insertions.
384 * @return deleted int - number of symbols marked as deleted
386 public int deleteRange(int start, int end)
391 // nothing to do here
394 if (start < 0 || start > end)
396 throw new Error(MessageManager.getString("error.implementation_error_delete_range_out_of_bounds"));
399 int cursor = 0; // mark the position for the current operation being edited.
400 int rlength = 1 + end - start; // number of positions to delete
403 boolean editing = false;
404 char[] oldops = operation;
405 int[] oldrange = range;
409 compact_operations();
410 while (o < oldlen && cursor <= end && rlength > 0)
414 // absorbed into new deleted region.
415 addDeleted(oldrange[o++]);
419 int remain = oldrange[o]; // number of op characters left to edit
422 if ((cursor + remain) <= start)
424 addOperation(oldops[o], oldrange[o]);
425 cursor += oldrange[o++];
426 continue; // next operation
429 // add operations before hidden region
430 if (start - cursor > 0)
432 addOperation(oldops[o], start - cursor);
433 remain -= start - cursor;
436 // start inserting new ops
437 if (o < oldlen && editing && rlength > 0 && remain > 0)
442 if (rlength > remain)
451 if (remain - rlength > 0)
453 this.addOperation(M, remain - rlength); // add remaining back.
460 if (remain - rlength > 0)
462 // only remove some gaps
463 addInsertion(remain - rlength);
468 throw new Error(MessageManager.getString("error.implementation_error")); // do nothing;
470 throw new Error(MessageManager.formatMessage("error.implementation_error_unknown_operation", new String[]{new StringBuffer(oldops[o]).toString()}));
473 remain = oldrange[++o]; // number of op characters left to edit
479 addOperation(oldops[o], oldrange[o++]);
481 // if (cursor<(start+1)) {
482 // ran out of ops - nothing to do here ?
483 // addInsertion(start-cursor);
489 * Deleted regions mean that there will be discontinuous sequence numbering in
490 * the sequence returned by getSeq(char).
492 * @return true if there deletions
494 public boolean hasDeletedRegions()
496 for (int i = 0; i < length; i++)
498 if (operation[i] == D)
507 * enumerate the ranges on seq that are marked as deleted in this cigar
509 * @return int[] { vis_start, sym_start, length }
511 public int[] getDeletedRegions()
517 Vector dr = new Vector();
518 int cursor = 0, vcursor = 0;
519 for (int i = 0; i < length; i++)
521 switch (operation[i])
529 dr.addElement(new int[]
530 { vcursor, cursor, range[i] });
538 int[] delregions = new int[dr.size() * 3];
539 for (int i = 0, l = dr.size(); i < l; i++)
541 int[] reg = (int[]) dr.elementAt(i);
542 delregions[i * 3] = reg[0];
543 delregions[i * 3 + 1] = reg[1];
544 delregions[i * 3 + 2] = reg[2];
550 * sum of ranges in cigar string
552 * @return int number of residues hidden, matched, or gaps inserted into
555 public int getFullWidth()
560 for (int i = 0; i < length; i++)
569 * Visible length of aligned sequence
571 * @return int length of including gaps and less hidden regions
573 public int getWidth()
578 for (int i = 0; i < length; i++)
580 if (operation[i] == M || operation[i] == I)
590 * mark a range of inserted residues
595 public void addInsertion(int range)
597 this.addOperation(I, range);
601 * mark the next range residues as hidden (not aligned) or deleted
606 public void addDeleted(int range)
608 this.addOperation(D, range);
612 * Modifies operation list to delete columns from start to end (inclusive)
613 * editing will remove insertion operations, and convert matches to deletions
619 * @return boolean true if residues were marked as deleted. public boolean
620 * deleteRange(int start, int end) { boolean deleted = false; int op =
621 * 0, prevop = -1, firstm = -1, lastm = -1, postop = -1; int width =
622 * 0; // zero'th column if (length > 0) { // find operation bracketing
623 * start of the range do { if (operation[op] != D) { width +=
624 * range[prevop = op]; } op++; } while (op < length && width < start);
625 * } if (width < start) { // run off end - add more operations up to
626 * deletion. addInsertion(start - width); } else { // edit existing
627 * operations. op = prevop; width -= range[prevop]; int[] oldrange =
628 * range; char[] oldops = operation; range = new int[oldrange.length];
629 * operation = new char[oldops.length]; if (op < length) { do { if
630 * (operation[op] != D) { width += range[postop = op]; } op++; } while
631 * (op < length && width <= end); } } if (deleted == true) {
632 * addDeleted(end - start + 1); } return deleted; }
635 * Return an ENSEMBL style cigar string where D may indicates excluded parts
638 * @return String of form ([0-9]+[IMD])+
640 public String getCigarstring()
642 StringBuffer cigarString = new StringBuffer();
643 for (int i = 0; i < length; i++)
645 cigarString.append("" + range[i]);
646 cigarString.append(operation[i]);
648 return cigarString.toString();