Return the alignment mismatches in the specified alignment pair as 0-based [closed, open) ranges.

@param alignmentPair alignment pair, must not be null
@return the alignment mismatches in the alignment pair as 0-based [closed, open) ranges
514367
public static List<Range<Long>> mismatches(final AlignmentPair alignmentPair) {
        checkNotNull(alignmentPair);
        List<Range<Long>> mismatches = new ArrayList<Range<Long>>();
        int mismatchStart = -1;
        for (int i = 1, length = alignmentPair.length() + 1; i < length; i++) {
            if (isMismatchSymbol(alignmentPair.symbolAt(i))) {
                if (mismatchStart < 0) {
                    mismatchStart = i;
                }
            }
            else {
                if (mismatchStart > 0) {
                    // biojava coordinates are 1-based
                    mismatches.add(Range.closedOpen(Long.valueOf(mismatchStart - 1L), Long.valueOf(i - 1L)));
                    mismatchStart = -1;
                }
            }
        }
        if (mismatchStart > 0) {
            mismatches.add(Range.closedOpen(Long.valueOf(mismatchStart - 1L), Long.valueOf(alignmentPair.length())));
        }
        return mismatches;
    }
167009
def get_abi_alignment(self, target_data, context=None):
        
        llty = self._get_ll_pointer_type(target_data, context)
        return target_data.get_pointee_abi_alignment(llty)
748521
static Matcher flattenNestedSequences(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
      List<Matcher> ms = new ArrayList<>();
      for (Matcher m : matchers) {
        if (m instanceof SeqMatcher) {
          ms.addAll(m.<SeqMatcher>as().matchers());
        } else {
          ms.add(m);
        }
      }
      return SeqMatcher.create(ms);
    }
    return matcher;
  }
557831
static Matcher extractPrefixFromOr(Matcher matcher) {
    if (matcher instanceof OrMatcher) {
      // Get the prefix for the first condition
      List<Matcher> matchers = matcher.<OrMatcher>as().matchers();
      if (matchers.isEmpty()) {
        return matcher;
      }
      Matcher prefix = PatternUtils.getPrefix(matchers.get(0));
      if (prefix.alwaysMatches()) {
        return matcher;
      }
      List<Matcher> ms = new ArrayList<>();
      ms.add(PatternUtils.getSuffix(matchers.get(0)));

      // Verify all OR conditions have the same prefix
      for (Matcher m : matchers.subList(1, matchers.size())) {
        Matcher p = PatternUtils.getPrefix(m);
        if (!prefix.equals(p)) {
          return matcher;
        }
        ms.add(PatternUtils.getSuffix(m));
      }

      return SeqMatcher.create(prefix, OrMatcher.create(ms));
    }
    return matcher;
  }
455055
static Matcher inlineMatchAnyPrecedingOr(Matcher matcher) {
    if (matcher instanceof ZeroOrMoreMatcher) {
      ZeroOrMoreMatcher zm = matcher.as();
      if (zm.repeated() instanceof AnyMatcher && zm.next() instanceof OrMatcher) {
        List<Matcher> matchers = zm.next().<OrMatcher>as().matchers();
        List<Matcher> ms = new ArrayList<>();
        for (Matcher m : matchers) {
          ms.add(new ZeroOrMoreMatcher(AnyMatcher.INSTANCE, m));
        }
        return OrMatcher.create(ms);
      }
    }
    return matcher;
  }
43512
List<ExpandedPair> decodeRow2pairs(int rowNumber, BitArray row) throws NotFoundException {
    boolean done = false;
    while (!done) {
      try {
        this.pairs.add(retrieveNextPair(row, this.pairs, rowNumber));
      } catch (NotFoundException nfe) {
        if (this.pairs.isEmpty()) {
          throw nfe;
        }
        // exit this loop when retrieveNextPair() fails and throws
        done = true;
      }
    }

    // TODO: verify sequence of finder patterns as in checkPairSequence()
    if (checkChecksum()) {
      return this.pairs;
    }

    boolean tryStackedDecode = !this.rows.isEmpty();
    storeRow(rowNumber, false); // TODO: deal with reversed rows
    if (tryStackedDecode) {
      // When the image is 180-rotated, then rows are sorted in wrong direction.
      // Try twice with both the directions.
      List<ExpandedPair> ps = checkRows(false);
      if (ps != null) {
        return ps;
      }
      ps = checkRows(true);
      if (ps != null) {
        return ps;
      }
    }

    throw NotFoundException.getNotFoundInstance();
  }
1039467
private static <T> Comparator<List<Optional<LocalProperty<T>>>> matchedLayoutPreference()
    {
        return (matchLayout1, matchLayout2) -> {
            Iterator<Optional<LocalProperty<T>>> match1Iterator = matchLayout1.iterator();
            Iterator<Optional<LocalProperty<T>>> match2Iterator = matchLayout2.iterator();
            while (match1Iterator.hasNext() && match2Iterator.hasNext()) {
                Optional<LocalProperty<T>> match1 = match1Iterator.next();
                Optional<LocalProperty<T>> match2 = match2Iterator.next();
                if (match1.isPresent() && match2.isPresent()) {
                    return Integer.compare(match1.get().getColumns().size(), match2.get().getColumns().size());
                }
                else if (match1.isPresent()) {
                    return 1;
                }
                else if (match2.isPresent()) {
                    return -1;
                }
            }
            checkState(!match1Iterator.hasNext() && !match2Iterator.hasNext()); // Should be the same size
            return 0;
        };
    }
646553
static Matcher tail(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> ms = matcher.<SeqMatcher>as().matchers();
      return SeqMatcher.create(ms.subList(1, ms.size()));
    } else {
      return TrueMatcher.INSTANCE;
    }
  }
297588
def _get_alignment_lines(self):
        ''' '''

        # Strip the boilerplate lines
        lines = self.alignment_output.split("\n")
        assert(lines[0].startswith('CLUSTAL'))
        lines = '\n'.join(lines[1:]).lstrip().split('\n')

        # The sequence IDs should be unique. Reassert this here
        assert(len(self.sequence_ids.values()) == len(set(self.sequence_ids.values())))

        # Create the list of sequence IDs
        id_list = [v for k, v in sorted(self.sequence_ids.iteritems())]

        # Determine the indentation level
        first_id = id_list[0]
        header_regex = re.compile("(.*?\s+)(.*)")
        alignment_regex = re.compile("^([A-Z\-]+)\s*$")
        mtchs = header_regex.match(lines[0])
        assert(mtchs.group(1).strip() == first_id)
        indentation = len(mtchs.group(1))
        sequence = mtchs.group(2)
        assert(sequence)
        assert(alignment_regex.match(sequence))

        # Create empty lists for the sequences
        sequences = {}
        for id in id_list:
            sequences[id] = []
        sequences[-1] = []

        # Get the lists of sequences
        num_ids = len(id_list)
        for x in range(0, len(lines), num_ids + 2):
            for y in range(num_ids):
                id = id_list[y]
                assert(lines[x + y][:indentation].strip() == id)
                assert(lines[x + y][indentation - 1] == ' ')
                sequence = lines[x + y][indentation:].strip()
                assert(alignment_regex.match(sequence))
                sequences[id].append(sequence)

            # Get the length of the sequence lines
            length_of_sequences = list(set(map(len, [v[-1] for k, v in sequences.iteritems() if k != -1])))
            assert(len(length_of_sequences) == 1)
            length_of_sequences = length_of_sequences[0]

            # Parse the Clustal match line
            assert(lines[x + num_ids][:indentation].strip() == '')
            match_sequence = lines[x + num_ids][indentation:indentation + length_of_sequences]
            assert(match_sequence.strip() == lines[x + num_ids].strip())
            assert(lines[x + y][indentation - 1] == ' ')
            sequences[-1].append(match_sequence)

            # Check for the empty line
            assert(lines[x + num_ids + 1].strip() == '')

        # Create the sequences, making sure that all sequences are the same length
        lengths = set()
        for k, v in sequences.iteritems():
            sequences[k] = "".join(v)
            lengths.add(len(sequences[k]))
        assert(len(lengths) == 1)

        return sequences
1208950
def get_PSL(self,min_intron_size=68):
    
    from seqtools.format.psl import PSL
    matches = sum([x[0].length for x in self.alignment_ranges]) # 1. Matches - Number of matching bases that aren't repeats
    stats = AlignmentStats(matches,0,0,0,0,0,0,0)
    sub = self.query_sequence
    ref = self._options.reference
    if ref and sub:
      stats = self._analyze_alignment(min_intron_size=min_intron_size)
    strand = self.strand # 9. strand 
    qName = self.alignment_ranges[0][1].chr # 10. qName - Query sequence name
    qSize = self.query_sequence_length
    qStart = self.alignment_ranges[0][1].start-1
    qEnd = self.alignment_ranges[-1][1].end
    tName = self.alignment_ranges[0][0].chr
    tSize = self.target_sequence_length
    tStart = self.alignment_ranges[0][0].start-1
    tEnd = self.alignment_ranges[-1][0].end
    blockCount = len(self.alignment_ranges)
    blockSizes = ','.join([str(x[0].length) for x in self.alignment_ranges])+','
    qStarts = ','.join([str(x[1].start-1) for x in self.alignment_ranges])+','
    tStarts = ','.join([str(x[0].start-1) for x in self.alignment_ranges])+','

    psl_string = str(stats.matches)+"\t"+\
    str(stats.misMatches)+"\t"+\
    str(stats.repMatches)+"\t"+\
    str(stats.nCount)+"\t"+\
    str(stats.qNumInsert)+"\t"+\
    str(stats.qBaseInsert)+"\t"+\
    str(stats.tNumInsert)+"\t"+\
    str(stats.tBaseInsert)+"\t"+\
    strand+"\t"+\
    qName+"\t"+\
    str(qSize)+"\t"+\
    str(qStart)+"\t"+\
    str(qEnd)+"\t"+\
    tName+"\t"+\
    str(tSize)+"\t"+\
    str(tStart)+"\t"+\
    str(tEnd)+"\t"+\
    str(blockCount)+"\t"+\
    blockSizes+"\t"+\
    qStarts+"\t"+\
    tStarts
    return PSL(psl_string,PSL.Options(query_sequence=self.query_sequence,reference=self._options.reference,query_quality=self.query_quality))
1331323
public boolean sequenceAndQualityLengthsMatch()
	{
		if (sequence == null && quality == null)
		{
			return true;
		}
		if ((sequence != null && quality == null) || (sequence == null && quality != null))
		{
			return false;
		}
		return sequence.length() == quality.length();
	}
383119
public int calculateScore(AlignmentScoring<S> scoring) {
        return AlignmentUtils.calculateScore(sequence1, sequence1Range, mutations, scoring);
    }
996462
public static WildcardPatternMatcher compile(String patterns) {
		if(patterns == null || patterns.isEmpty()) {
			return matchNone;
		} else {
			List<String> list = StringUtility.splitStringCommaSpace(patterns);
			// Match none shortcut
			if(list.isEmpty()) return matchNone;

			// Parse into a series of individual matchers
			final List<WildcardPatternMatcher> matchers = new ArrayList<>(list.size());
			for(String pattern : list) {
				int end = pattern.length();
				if(end > 0) {
					// Beginning wildcards
					int pos = 0;
					final boolean startsWildcard;
					if(pattern.charAt(0) == '*') {
						startsWildcard = true;
						pos++;
						// Skip consecutive beginning
						while(pos < end && pattern.charAt(pos) == '*') pos++;
						if(pos >= end) {
							// Is any number of '*' only, matchAll shortcut
							return matchAll;
						}
					} else {
						startsWildcard = false;
					}
					// Ending wildcards
					final boolean endsWildcard;
					if(pattern.charAt(end - 1) == '*') {
						endsWildcard = true;
						end--;
						// Skip consecutive ending
						while(end > pos && pattern.charAt(end - 1) == '*') end--;
						assert end > pos;
					} else {
						endsWildcard = false;
					}
					// Split the remaining pattern on any internal '*'
					final List<String> sequences = new ArrayList<>();
					while(pos < end) {
						assert pattern.charAt(pos) != '*';
						int starPos = pattern.indexOf('*', pos + 1);
						if(starPos == -1 || starPos >= end) {
							// Not more '*' found
							sequences.add(pattern.substring(pos, end));
							pos = end;
						} else {
							// Found
							sequences.add(pattern.substring(pos, starPos));
							pos = starPos + 1;
							// Skip consecutive
							while(pos < end && pattern.charAt(pos) == '*') pos++;
						}
					}
					int seqCount = sequences.size();
					assert seqCount >= 1;
					if(seqCount == 1) {
						final String sequence = sequences.get(0);
						if(startsWildcard) {
							if(endsWildcard) {
								// *infix*
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.contains(sequence);
										}
									}
								);
							} else {
								// *suffix
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.endsWith(sequence);
										}
									}
								);
							}
						} else {
							if(endsWildcard) {
								// prefix*
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.startsWith(sequence);
										}
									}
								);
							} else {
								// exact
								matchers.add(
									new WildcardPatternMatcher() {
										@Override
										public boolean isMatch(String paramName) {
											return paramName.equals(sequence);
										}
									}
								);
							}
						}
					} else {
						matchers.add(
							new WildcardPatternMatcher() {
								@Override
								public boolean isMatch(String paramName) {
									int index = 0;
									int indexEnd = sequences.size();
									int pos = 0;
									int end = paramName.length();
									// Handle non-wildcard start
									if(!startsWildcard) {
										String prefix = sequences.get(0);
										if(!paramName.startsWith(prefix)) {
											return false;
										}
										index++;
										pos += prefix.length();
									}
									// Handle non-wildcard end
									if(!endsWildcard) {
										indexEnd--;
										String suffix = sequences.get(indexEnd);
										if(!paramName.endsWith(suffix)) {
											return false;
										}
										end -= suffix.length();
									}
									// Check if overlapping prefix and suffix matches
									if(end < pos) return false;
									// Handle any remaining infixes
									while(index < indexEnd) {
										String sequence = sequences.get(index++);
										int sequenceLen = sequence.length();
										assert sequenceLen > 0;
										int foundAt = paramName.indexOf(sequence, pos);
										if(foundAt == -1 || foundAt > (end - sequenceLen)) {
											return false;
										}
										pos += sequenceLen;
									}
									return true;
								}
							}
						);
					}
				}
			}
			if(matchers.isEmpty()) {
				return matchNone;
			}
			if(matchers.size() == 1) return matchers.get(0);
			return new WildcardPatternMatcher() {
				@Override
				public boolean isMatch(String paramName) {
					for(WildcardPatternMatcher matcher : matchers) {
						if(matcher.isMatch(paramName)) return true;
					}
					return false;
				}
			};
		}
	}
1253282
protected String findOffsetMatch(TestInfo info, int startOffset, MutableOffset mutableOffset, final byte[] bytes,
			final char[] chars, final int maxPos) {

		// verify the starting offset
		if (startOffset < 0) {
			return null;
		}

		int targetPos = startOffset;
		boolean lastMagicCompactWhitespace = false;
		for (int magicPos = 0; magicPos < info.pattern.length(); magicPos++) {
			char magicCh = info.pattern.charAt(magicPos);
			boolean lastChar = (magicPos == info.pattern.length() - 1);
			// did we reach the end?
			if (targetPos >= maxPos) {
				return null;
			}
			char targetCh;
			if (bytes == null) {
				targetCh = chars[targetPos];
			} else {
				targetCh = charFromByte(bytes, targetPos);
			}
			targetPos++;

			// if it matches, we can continue
			if (info.operator.doTest(targetCh, magicCh, lastChar)) {
				if (info.compactWhiteSpace) {
					lastMagicCompactWhitespace = Character.isWhitespace(magicCh);
				}
				continue;
			}

			// if it doesn't match, maybe the target is a whitespace
			if ((lastMagicCompactWhitespace || info.optionalWhiteSpace) && Character.isWhitespace(targetCh)) {
				do {
					if (targetPos >= maxPos) {
						break;
					}
					if (bytes == null) {
						targetCh = chars[targetPos];
					} else {
						targetCh = charFromByte(bytes, targetPos);
					}
					targetPos++;
				} while (Character.isWhitespace(targetCh));
				// now that we get to the first non-whitespace, it must match
				if (info.operator.doTest(targetCh, magicCh, lastChar)) {
					if (info.compactWhiteSpace) {
						lastMagicCompactWhitespace = Character.isWhitespace(magicCh);
					}
					continue;
				}
				// if it doesn't match, check the case insensitive
			}

			// maybe it doesn't match because of case insensitive handling and magic-char is lowercase
			if (info.caseInsensitive && Character.isLowerCase(magicCh)) {
				if (info.operator.doTest(Character.toLowerCase(targetCh), magicCh, lastChar)) {
					// matches
					continue;
				}
				// upper-case characters must match
			}

			return null;
		}

		char[] resultChars;
		if (bytes == null) {
			resultChars = Arrays.copyOfRange(chars, startOffset, targetPos);
		} else {
			resultChars = new char[targetPos - startOffset];
			for (int i = 0; i < resultChars.length; i++) {
				resultChars[i] = charFromByte(bytes, startOffset + i);
			}
		}
		mutableOffset.offset = targetPos;
		return new String(resultChars);
	}
285481
static Matcher startsWithCharSeq(Matcher matcher) {
    if (matcher instanceof SeqMatcher) {
      List<Matcher> matchers = matcher.<SeqMatcher>as().matchers();
      if (matchers.size() >= 2
          && matchers.get(0) instanceof StartMatcher
          && matchers.get(1) instanceof CharSeqMatcher) {
        List<Matcher> ms = new ArrayList<>();
        ms.add(new StartsWithMatcher(matchers.get(1).<CharSeqMatcher>as().pattern()));
        ms.addAll(matchers.subList(2, matchers.size()));
        return SeqMatcher.create(ms);
      }
    }
    return matcher;
  }
752830
public String[] getLabels(Matcher matcher) {
        if ((matcher instanceof AnyOfMatcher) && ((AnyOfMatcher)matcher).characters.toString().equals(matcher.getLabel())) {
            AnyOfMatcher cMatcher = (AnyOfMatcher) matcher;
            if (!cMatcher.characters.isSubtractive()) {
                String[] labels = new String[cMatcher.characters.getChars().length];
                for (int i = 0; i < labels.length; i++) {
                    labels[i] = '\'' + String.valueOf(cMatcher.characters.getChars()[i]) + '\'';
                }
                return labels;
            }
        }
        return new String[] {matcher.getLabel()};
    }
1100333
def process_uclust_pw_alignment_results(fasta_pairs_lines, uc_lines):
    
    alignments = get_next_two_fasta_records(fasta_pairs_lines)
    for hit in get_next_record_type(uc_lines, 'H'):
        matching_strand = hit[4]
        if matching_strand == '-':
            strand_id = '-'
            target_rev_match = True
        elif matching_strand == '+':
            strand_id = '+'
            target_rev_match = False
        elif matching_strand == '.':
            # protein sequence, so no strand information
            strand_id = ''
            target_rev_match = False
        else:
            raise UclustParseError("Unknown strand type: %s" % matching_strand)
        uc_query_id = hit[8]
        uc_target_id = hit[9]
        percent_id = float(hit[3])

        fasta_pair = alignments.next()

        fasta_query_id = fasta_pair[0][0]
        aligned_query = fasta_pair[0][1]

        if fasta_query_id != uc_query_id:
            raise UclustParseError("Order of fasta and uc files do not match." +
                                   " Got query %s but expected %s." %
                                   (fasta_query_id, uc_query_id))

        fasta_target_id = fasta_pair[1][0]
        aligned_target = fasta_pair[1][1]

        if fasta_target_id != uc_target_id + strand_id:
            raise UclustParseError("Order of fasta and uc files do not match." +
                                   " Got target %s but expected %s." %
                                   (fasta_target_id, uc_target_id + strand_id))

        if target_rev_match:
            query_id = uc_query_id + ' RC'
            aligned_query = DNA.rc(aligned_query)
            target_id = uc_target_id
            aligned_target = DNA.rc(aligned_target)
        else:
            query_id = uc_query_id
            aligned_query = aligned_query
            target_id = uc_target_id
            aligned_target = aligned_target

        yield (query_id, target_id, aligned_query, aligned_target, percent_id)