2 * Jalview - A Sequence Alignment Editor and Viewer (Version 2.8)
3 * Copyright (C) 2012 J Procter, AM Waterhouse, LM Lui, J Engelhardt, G Barton, M Clamp, S Searle
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/>.
18 package jalview.datamodel;
20 import java.util.Enumeration;
21 import java.util.Hashtable;
23 import jalview.analysis.*;
24 import jalview.util.*;
26 public class SeqCigar extends CigarSimple
29 * start(inclusive) and end(exclusive) of subsequence on refseq
31 private int start, end;
33 private SequenceI refseq = null;
35 private Hashtable seqProps;
38 * Reference dataset sequence for the cigar string
42 public SequenceI getRefSeq()
49 * @return int start index of cigar ops on refSeq
58 * @return int end index (exclusive) of cigar ops on refSeq
66 * Returns sequence as a string with cigar operations applied to it
70 public String getSequenceString(char GapChar)
72 return (length == 0) ? "" : (String) getSequenceAndDeletions(
73 refseq.getSequenceAsString(start, end), GapChar)[0];
77 * recreates a gapped and edited version of RefSeq or null for an empty cigar
82 public SequenceI getSeq(char GapChar)
85 if (refseq == null || length == 0)
89 Object[] edit_result = getSequenceAndDeletions(
90 refseq.getSequenceAsString(start, end), GapChar);
91 if (edit_result == null)
94 "Implementation Error - unexpected null from getSequenceAndDeletions");
96 int bounds[] = (int[]) edit_result[1];
97 seq = new Sequence(refseq.getName(), (String) edit_result[0],
98 refseq.getStart() + start + bounds[0], refseq.getStart()
99 + start + ((bounds[2] == 0) ? -1 : bounds[2]));
100 seq.setDescription(refseq.getDescription());
101 int sstart = seq.getStart(), send = seq.getEnd();
102 // seq.checkValidRange(); probably not needed
103 // recover local properties if present
104 if (seqProps != null)
106 // this recovers dataset sequence reference as well as local features,
107 // names, start/end settings.
108 SeqsetUtils.SeqCharacterUnhash(seq, seqProps);
110 // ensure dataset sequence is up to date from local reference
111 seq.setDatasetSequence(refseq);
112 seq.setStart(sstart);
118 * We don't allow this - refseq is given at construction time only public void
119 * setSeq(SequenceI seq) { this.seq = seq; }
122 * internal constructor - sets seq to a gapless sequence derived from seq and
123 * prepends any 'D' operations needed to get to the first residue of seq.
127 * @param initialDeletion
128 * true to mark initial dataset sequence residues as deleted in
131 * index of first position in seq
133 * index after last position in (possibly gapped) seq
134 * @return true if gaps are present in seq
136 private boolean _setSeq(SequenceI seq, boolean initialDeletion, int _s,
139 boolean hasgaps = false;
142 throw new Error("Implementation Error - _setSeq(null,...)");
146 throw new Error("Implementation Error: _s=" + _s);
148 String seq_string = seq.getSequenceAsString();
149 if (_e == 0 || _e < _s || _e > seq_string.length())
151 _e = seq_string.length();
153 // resolve start and end positions relative to ungapped reference sequence
154 start = seq.findPosition(_s) - seq.getStart();
155 end = seq.findPosition(_e) - seq.getStart();
156 int l_ungapped = end - start;
157 // Find correct sequence to reference and correct start and end - if
159 SequenceI ds = seq.getDatasetSequence();
162 // make a new dataset sequence
163 String ungapped = AlignSeq.extractGaps(
164 jalview.util.Comparison.GapChars, new String(seq_string));
165 l_ungapped = ungapped.length();
166 // check that we haven't just duplicated an ungapped sequence.
167 if (l_ungapped == seq.getLength())
173 ds = new Sequence(seq.getName(), ungapped, seq.getStart(),
174 seq.getStart() + ungapped.length() - 1);
175 // JBPNote: this would be consistent but may not be useful
176 // seq.setDatasetSequence(ds);
179 // add in offset between seq and the dataset sequence
180 if (ds.getStart() < seq.getStart())
182 int offset = seq.getStart() - ds.getStart();
185 // absolute cigar string
186 addDeleted(_s + offset);
192 // normal behaviour - just mark start and end subsequence
200 // any gaps to process ?
201 if (l_ungapped != (_e - _s))
207 // copy over local properties for the sequence instance of the refseq
208 seqProps = SeqsetUtils.SeqCharacterHash(seq);
210 if (end > ds.getLength())
213 "SeqCigar: Possible implementation error: sequence is longer than dataset sequence");
214 // end = ds.getLength();
221 * directly initialise a cigar object with a sequence of range, operation
222 * pairs and a sequence to apply it to. operation and range should be relative
223 * to the seq.getStart()'th residue of the dataset seq resolved from seq.
232 public SeqCigar(SequenceI seq, char operation[], int range[])
237 throw new Error("Implementation Bug. Null seq !");
239 if (operation.length != range.length)
242 "Implementation Bug. Cigar Operation list!= range list");
245 if (operation != null)
247 this.operation = new char[operation.length + _inc_length];
248 this.range = new int[operation.length + _inc_length];
250 if (_setSeq(seq, false, 0, 0))
253 "NOT YET Implemented: Constructing a Cigar object from a cigar string and a gapped sequence.");
255 for (int i = this.length, j = 0; j < operation.length; i++, j++)
257 char op = operation[j];
258 if (op != M && op != I && op != D)
260 throw new Error("Implementation Bug. Cigar Operation '" + j
261 + "' '" + op + "' not one of '" + M + "', '" + I
262 + "', or '" + D + "'.");
264 this.operation[i] = op;
265 this.range[i] = range[j];
267 this.length += operation.length;
271 this.operation = null;
274 if (_setSeq(seq, false, 0, 0))
277 "NOT YET Implemented: Constructing a Cigar object from a cigar string and a gapped sequence.");
283 * add range matched residues to cigar string
288 public void addMatch(int range)
290 this.addOperation(M, range);
294 * Adds insertion and match operations based on seq to the cigar up to the
295 * endpos column of seq.
305 * @param initialDeletions
306 * if true then initial deletions will be added from start of seq to
309 protected static void addSequenceOps(CigarBase cigar, SequenceI seq,
310 int startpos, int endpos, boolean initialDeletions)
314 int p = 0, res = seq.getLength();
316 if (!initialDeletions)
323 boolean isGap = (p < res) ? jalview.util.Comparison.isGap(seq
324 .getCharAt(p)) : true;
325 if ((startpos <= p) && (p <= endpos))
329 if (range > 0 && op != I)
331 cigar.addOperation(op, range);
339 if (range > 0 && op != M)
341 cigar.addOperation(op, range);
352 if (range > 0 && op != D)
354 cigar.addOperation(op, range);
362 // do nothing - insertions are not made in flanking regions
369 cigar.addOperation(op, range);
374 * create a cigar string for given sequence
379 public SeqCigar(SequenceI seq)
384 throw new Error("Implementation error for new Cigar(SequenceI)");
386 _setSeq(seq, false, 0, 0);
387 // there is still work to do
388 addSequenceOps(this, seq, 0, seq.getLength() - 1, false);
392 * Create Cigar from a range of gaps and residues on a sequence object
397 * int - first column in range
399 * int - last column in range
401 public SeqCigar(SequenceI seq, int start, int end)
406 throw new Error("Implementation error for new Cigar(SequenceI)");
408 _setSeq(seq, false, start, end + 1);
409 // there is still work to do
410 addSequenceOps(this, seq, start, end, false);
414 * Create a cigar object from a cigar string like '[<I|D|M><range>]+' Will
415 * fail if the given seq already contains gaps (JBPNote: future implementation
419 * SequenceI object resolvable to a dataset sequence
424 public static SeqCigar parseCigar(SequenceI seq, String cigarString)
427 Object[] opsandrange = parseCigarString(cigarString);
428 return new SeqCigar(seq, (char[]) opsandrange[0],
429 (int[]) opsandrange[1]);
433 * create an alignment from the given array of cigar sequences and gap
434 * character, and marking the given segments as visible in the given
438 * @param gapCharacter
440 * - columnSelection where hidden regions are marked
442 * - visible regions of alignment
443 * @return SequenceI[]
445 public static SequenceI[] createAlignmentSequences(SeqCigar[] alseqs,
446 char gapCharacter, ColumnSelection colsel, int[] segments)
448 SequenceI[] seqs = new SequenceI[alseqs.length];
449 StringBuffer[] g_seqs = new StringBuffer[alseqs.length];
450 String[] alseqs_string = new String[alseqs.length];
451 Object[] gs_regions = new Object[alseqs.length];
452 for (int i = 0; i < alseqs.length; i++)
454 alseqs_string[i] = alseqs[i].getRefSeq().getSequenceAsString(
455 alseqs[i].start, alseqs[i].end);
456 gs_regions[i] = alseqs[i].getSequenceAndDeletions(alseqs_string[i],
457 gapCharacter); // gapped sequence, {start, start col, end.
458 // endcol}, hidden regions {{start, end, col}})
459 if (gs_regions[i] == null)
461 throw new Error("Implementation error: " + i
462 + "'th sequence Cigar has no operations.");
464 g_seqs[i] = new StringBuffer((String) ((Object[]) gs_regions[i])[0]); // the
469 // Now account for insertions. (well - deletions)
470 // this is complicated because we must keep track of shifted positions in
472 ShiftList shifts = new ShiftList();
473 for (int i = 0; i < alseqs.length; i++)
475 Object[] gs_region = ((Object[]) ((Object[]) gs_regions[i])[2]);
476 if (gs_region != null)
479 for (int hr = 0; hr < gs_region.length; hr++)
481 int[] region = (int[]) gs_region[hr];
482 char[] insert = new char[region[1] - region[0] + 1];
483 for (int s = 0; s < insert.length; s++)
485 insert[s] = gapCharacter;
487 int inspos = shifts.shift(region[2]); // resolve insertion position in
488 // current alignment frame of
490 for (int s = 0; s < alseqs.length; s++)
494 if (g_seqs[s].length() <= inspos)
496 // prefix insertion with more gaps.
497 for (int l = inspos - g_seqs[s].length(); l > 0; l--)
499 g_seqs[s].append(gapCharacter); // to debug - use a diffferent
500 // gap character here
503 g_seqs[s].insert(inspos, insert);
507 g_seqs[s].insert(inspos,
508 alseqs_string[i].substring(region[0], region[1] + 1));
511 shifts.addShift(region[2], insert.length); // update shift in
512 // alignment frame of
514 if (segments == null)
516 // add a hidden column for this deletion
517 colsel.hideColumns(inspos, inspos + insert.length - 1);
522 for (int i = 0; i < alseqs.length; i++)
524 int[] bounds = ((int[]) ((Object[]) gs_regions[i])[1]);
525 SequenceI ref = alseqs[i].getRefSeq();
526 seqs[i] = new Sequence(ref.getName(), g_seqs[i].toString(),
527 ref.getStart() + alseqs[i].start + bounds[0], ref.getStart()
528 + alseqs[i].start + (bounds[2] == 0 ? -1 : bounds[2]));
529 seqs[i].setDatasetSequence(ref);
530 seqs[i].setDescription(ref.getDescription());
532 if (segments != null)
534 for (int i = 0; i < segments.length; i += 3)
536 // int start=shifts.shift(segments[i]-1)+1;
537 // int end=shifts.shift(segments[i]+segments[i+1]-1)-1;
538 colsel.hideColumns(segments[i + 1], segments[i + 1]
539 + segments[i + 2] - 1);
546 * non rigorous testing
552 * @param ex_cs_gapped
556 public static String testCigar_string(Sequence seq, String ex_cs_gapped)
558 SeqCigar c_sgapped = new SeqCigar(seq);
559 String cs_gapped = c_sgapped.getCigarstring();
560 if (!cs_gapped.equals(ex_cs_gapped))
562 System.err.println("Failed getCigarstring: incorect string '"
563 + cs_gapped + "' != " + ex_cs_gapped);
568 public static boolean testSeqRecovery(SeqCigar gen_sgapped,
571 // this is non-rigorous - start and end recovery is not tested.
572 SequenceI gen_sgapped_s = gen_sgapped.getSeq('-');
573 if (!gen_sgapped_s.getSequence().equals(s_gapped.getSequence()))
575 System.err.println("Couldn't reconstruct sequence.\n"
576 + gen_sgapped_s.getSequenceAsString() + "\n"
577 + s_gapped.getSequenceAsString());
583 public static void main(String argv[]) throws Exception
586 Sequence s = new Sequence("MySeq",
587 o_seq = "asdfktryasdtqwrtsaslldddptyipqqwaslchvhttt", 39, 80);
589 Sequence s_gapped = new Sequence(
591 orig_gapped = "----asdf------ktryas---dtqwrtsasll----dddptyipqqwa----slchvhttt",
593 String ex_cs_gapped = "4I4M6I6M3I11M4I12M4I9M";
594 s_gapped.setDatasetSequence(s);
596 Sequence s_subsequence_gapped = new Sequence(
598 sub_gapped_s = "------ktryas---dtqwrtsasll----dddptyipqqwa----slchvh",
601 s_subsequence_gapped.setDatasetSequence(s);
602 SeqCigar c_null = new SeqCigar(s);
603 String cs_null = c_null.getCigarstring();
604 if (!cs_null.equals("42M"))
607 .println("Failed to recover ungapped sequence cigar operations:"
608 + ((cs_null == "") ? "empty string" : cs_null));
610 testCigar_string(s_gapped, ex_cs_gapped);
611 SeqCigar gen_sgapped = SeqCigar.parseCigar(s, ex_cs_gapped);
612 if (!gen_sgapped.getCigarstring().equals(ex_cs_gapped))
614 System.err.println("Failed parseCigar(" + ex_cs_gapped
615 + ")->getCigarString()->'" + gen_sgapped.getCigarstring()
618 testSeqRecovery(gen_sgapped, s_gapped);
619 // Test dataset resolution
620 SeqCigar sub_gapped = new SeqCigar(s_subsequence_gapped);
621 if (!testSeqRecovery(sub_gapped, s_subsequence_gapped))
624 .println("Failed recovery for subsequence of dataset sequence");
627 if (sub_gapped.getWidth() != sub_gapped_s.length())
629 System.err.println("Failed getWidth()");
632 sub_gapped.getFullWidth();
633 if (sub_gapped.hasDeletedRegions())
635 System.err.println("hasDeletedRegions is incorrect.");
637 // Test start-end region SeqCigar
638 SeqCigar sub_se_gp = new SeqCigar(s_subsequence_gapped, 8, 48);
639 if (sub_se_gp.getWidth() != 41)
642 .println("SeqCigar(seq, start, end) not properly clipped alignsequence.");
644 System.out.println("Original sequence align:\n" + sub_gapped_s
645 + "\nReconstructed window from 8 to 48\n" + "XXXXXXXX"
646 + sub_se_gp.getSequenceString('-') + "..." + "\nCigar String:"
647 + sub_se_gp.getCigarstring() + "\n");
648 SequenceI ssgp = sub_se_gp.getSeq('-');
649 System.out.println("\t " + ssgp.getSequenceAsString());
650 for (int r = 0; r < 10; r++)
652 sub_se_gp = new SeqCigar(s_subsequence_gapped, 8, 48);
653 int sl = sub_se_gp.getWidth();
655 for (int rs = 0; rs < 10; rs++)
658 sub_se_gp.deleteRange(st, e);
659 String ssgapedseq = sub_se_gp.getSeq('-').getSequenceAsString();
660 System.out.println(st + "," + e + "\t:" + ssgapedseq);
665 SeqCigar[] set = new SeqCigar[]
666 { new SeqCigar(s), new SeqCigar(s_subsequence_gapped, 8, 48),
667 new SeqCigar(s_gapped) };
668 Alignment al = new Alignment(set);
669 for (int i = 0; i < al.getHeight(); i++)
671 System.out.println("" + al.getSequenceAt(i).getName() + "\t"
672 + al.getSequenceAt(i).getStart() + "\t"
673 + al.getSequenceAt(i).getEnd() + "\t"
674 + al.getSequenceAt(i).getSequenceAsString());
678 System.out.println("Gapped.");
679 SeqCigar[] set = new SeqCigar[]
680 { new SeqCigar(s), new SeqCigar(s_subsequence_gapped, 8, 48),
681 new SeqCigar(s_gapped) };
682 set[0].deleteRange(20, 25);
683 Alignment al = new Alignment(set);
684 for (int i = 0; i < al.getHeight(); i++)
686 System.out.println("" + al.getSequenceAt(i).getName() + "\t"
687 + al.getSequenceAt(i).getStart() + "\t"
688 + al.getSequenceAt(i).getEnd() + "\t"
689 + al.getSequenceAt(i).getSequenceAsString());
692 // if (!ssgapedseq.equals("ryas---dtqqwa----slchvh"))
693 // System.err.println("Subseqgaped\n------ktryas---dtqwrtsasll----dddptyipqqwa----slchvhryas---dtqwrtsasll--qwa----slchvh\n"+ssgapedseq+"\n"+sub_se_gp.getCigarstring());
697 * references to entities that this sequence cigar is associated with.
699 private Hashtable selGroups = null;
701 public void setGroupMembership(Object group)
703 if (selGroups == null)
705 selGroups = new Hashtable();
707 selGroups.put(group, new int[0]);
711 * Test for and if present remove association to group.
714 * @return true if group was associated and it was removed
716 public boolean removeGroupMembership(Object group)
718 if (selGroups != null && selGroups.containsKey(group))
720 selGroups.remove(group);
727 * forget all associations for this sequence.
729 public void clearMemberships()
731 if (selGroups != null)
740 * @return null or array of all associated entities
742 public Object[] getAllMemberships()
744 if (selGroups == null)
748 Object[] mmbs = new Object[selGroups.size()];
749 Enumeration en = selGroups.keys();
750 for (int i = 0; en.hasMoreElements(); i++)
752 mmbs[i] = en.nextElement();
758 * Test for group membership
761 * - a selection group or some other object that may be associated
763 * @return true if sgr is associated with this seqCigar
765 public boolean isMemberOf(Object sgr)
767 return (selGroups != null) && selGroups.get(sgr) != null;