Get a subsequence as a new SeqProp object given a list of residue numbers
173979
def get_subsequence(self, resnums, new_id=None, copy_letter_annotations=True):
        """"""
        # XTODO: documentation
        biop_compound_list = []
        for resnum in resnums:
            # XTODO can be sped up by separating into ranges based on continuous resnums
            feat = FeatureLocation(resnum - 1, resnum)
            biop_compound_list.append(feat)

        if len(biop_compound_list) == 0:
            log.debug('Zero length subsequence')
            return
        elif len(biop_compound_list) == 1:
            log.debug('Subsequence only one residue long')
            sub_feature_location = biop_compound_list[0]
        else:
            sub_feature_location = CompoundLocation(biop_compound_list)

        try:
            sub_feature = sub_feature_location.extract(self)
        except TypeError:
            log.critical('SeqProp {}: unknown error when trying to get subsequence - please investigate! '
                          'Try using a feature to extract a subsequence from the SeqProp'.format(self.id))
            return

        if not new_id:
            new_id = '{}_subseq'.format(self.id)

        new_sp = SeqProp(id=new_id, seq=sub_feature.seq)
        if copy_letter_annotations:
            new_sp.letter_annotations = sub_feature.letter_annotations
        return new_sp
970732
function longestPositiveIncreasingSubsequence(ns, newStart) {
  let seq = [],
    is = [],
    l = -1,
    pre = new Array(ns.length);

  for (let i = newStart, len = ns.length; i < len; i++) {
    let n = ns[i];
    if (n < 0) continue;
    let j = findGreatestIndexLEQ(seq, n);
    if (j !== -1) pre[i] = is[j];
    if (j === l) {
      l++;
      seq[l] = n;
      is[l]  = i;
    } else if (n < seq[j + 1]) {
      seq[j + 1] = n;
      is[j + 1] = i;
    }
  }

  for (let i = is[l]; l >= 0; i = pre[i], l--) {
    seq[l] = i;
  }

  return seq;
}
691409
function seq(to, from = 0, step = 1) {
  var result = [];
  var count = 0;
  if (to > from) for (let i = from; i < to; i += step) result[count++] = i;
  else           for (let i = from; i > to; i -= step) result[count++] = i;

  return result;
}
767466
def create_pymol_selection_from_PDB_residue_ids(residue_list):
    ''''''
    residues_by_chain = {}
    for residue_id in residue_list:
        chain_id = residue_id[0]
        pruned_residue_id = residue_id[1:]
        residues_by_chain[chain_id] = residues_by_chain.get(chain_id, [])
        residues_by_chain[chain_id].append(pruned_residue_id)

    str = []
    for chain_id, residue_list in sorted(residues_by_chain.iteritems()):
        str.append('(chain %s and resi %s)' % (chain_id, '+'.join(map(string.strip, sorted(residue_list)))))
    return ' or '.join(str)
293284
def build_sequence(self, xs, masks, init, is_left_to_right):
        '''
        
        '''
        states = []
        last = init
        if is_left_to_right:
            for i, xs_i in enumerate(xs):
                h = self.build(xs_i, last, masks[i])
                states.append(h)
                last = h
        else:
            for i in range(len(xs) - 1, -1, -1):
                h = self.build(xs[i], last, masks[i])
                states.insert(0, h)
                last = h
        return states
329380
def filter_sequences(self, seq_type):
        
        return DictList(x for x in self.sequences if isinstance(x, seq_type))
725817
def chop_sequence(sequence, limit_length):
        
        return [sequence[i:i + limit_length] for i in range(0, len(sequence), limit_length)]
175037
def make_sequence(seq, name="S"):
    
    return ["{}_{}_{}".format(name, i, x) for i, x in enumerate(seq)]
961002
def split_seq(iterable, size):
    """"""
    elm = iter(iterable)
    item = list(itertools.islice(elm, size))
    while item:
        yield item
        item = list(itertools.islice(elm, size))
1006917
def is_sequential(self):
        
        seq_ids = tuple(int(residue["Seq_ID"]) for residue in self)
        return seq_ids == tuple(range(int(seq_ids[0]), int(seq_ids[-1])+1))
1087548
def p(self, sequence, subsequence=True):
        """"""
        if sequence[0] != self.startstate:
            if isinstance(sequence, tuple):
                sequence = (self.startstate,) + sequence
            else:
                sequence = (self.startstate,) + tuple(sequence)
        if self.endstate:
            if sequence[-1] != self.endstate:
                if isinstance(sequence, tuple):
                    sequence = sequence + (self.endstate,)
                else:
                    sequence = tuple(sequence) + (self.endstate,)

        prevnode = None
        prob = 1
        for node in sequence:
            if prevnode:
                try:
                    prob *= self.edges_out[prevnode][node]
                except:
                    return 0
        return prob
17822
def insertions_from_masked(seq):
    
    insertions = []
    prev = True
    for i, base in enumerate(seq):
        if base.isupper() and prev is True:
            insertions.append([])
            prev = False
        elif base.islower():
            insertions[-1].append(i)
            prev = True
    return [[min(i), max(i)] for i in insertions if i != []]
979960
def _get_seqprop_to_seqprop_alignment(self, seqprop1, seqprop2):
        """"""
        if isinstance(seqprop1, str):
            seqprop1_id = seqprop1
        else:
            seqprop1_id = seqprop1.id
        if isinstance(seqprop2, str):
            seqprop2_id = seqprop2
        else:
            seqprop2_id = seqprop2.id

        aln_id = '{}_{}'.format(seqprop1_id, seqprop2_id)

        if self.sequence_alignments.has_id(aln_id):
            alignment = self.sequence_alignments.get_by_id(aln_id)
            return alignment
        else:
            raise ValueError('{}: sequence alignment not found, please run the alignment first'.format(aln_id))
278270
def pairwise(seq):
    
    for i in range(0, len(seq) - 1):
        yield (seq[i], seq[i + 1])
278669
function map(seq, pred, ctx) {
        return sequencep(seq)?  __map.call(seq, pred, ctx)
             : /* non-seq */    []
    }
755628
def _py_expand_short(subsequence, sequence, max_l_dist):
    """"""
    # The following diagram shows the score calculation step.
    #
    # Each new score is the minimum of:
    #  * a OR a + 1 (substitution, if needed)
    #  * b + 1 (deletion, i.e. skipping a sequence character)
    #  * c + 1 (insertion, i.e. skipping a sub-sequence character)
    #
    # a -- +1 -> c
    #
    # |  \       |
    # |   \      |
    # +1  +1?    +1
    # |      \   |
    # v       ⌟  v
    #
    # b -- +1 -> scores[subseq_index]

    subseq_len = len(subsequence)
    if subseq_len == 0:
        return (0, 0)

    # Initialize the scores array with values for just skipping sub-sequence
    # chars.
    scores = list(range(1, subseq_len + 1))

    min_score = subseq_len
    min_score_idx = -1

    for seq_index, char in enumerate(sequence):
        # calculate scores, one for each character in the sub-sequence
        a = seq_index
        c = a + 1
        for subseq_index in range(subseq_len):
            b = scores[subseq_index]
            c = scores[subseq_index] = min(
                a + (char != subsequence[subseq_index]),
                b + 1,
                c + 1,
            )
            a = b

        # keep the minimum score found for matches of the entire sub-sequence
        if c <= min_score:
            min_score = c
            min_score_idx = seq_index

        # bail early when it is impossible to find a better expansion
        elif min(scores) >= min_score:
            break

    return (min_score, min_score_idx + 1) if min_score <= max_l_dist else (None, None)
633712
def getSequence(self, level=0):
        ''''''

        seq = []
        op = ''
        left_operand = None
        right_operand = None
        sequence_closed = False
        while True:
            c = self.next()
            if not c:
                break
            if c and c not in self.meta_chars:
                seq.append(self.getLiteral())
            elif c and c == u'$' and self.lookahead() == u'{':
                seq.append(self.getSource())
            elif c == u'[' and not self.last() == u'\\':
                seq.append(self.getCharacterSet())
            elif c == u'(' and not self.last() == u'\\':
                seq.append(self.getSequence(level + 1))
            elif c == u')' and not self.last() == u'\\':
                # end of this sequence
                if level == 0:
                    # there should be no parens here
                    raise StringGenerator.SyntaxError(u"Extra closing parenthesis")
                sequence_closed = True
                break
            elif c == u'|' and not self.last() == u'\\':
                op = c
            elif c == u'&' and not self.last() == u'\\':
                op = c
            else:
                if c in self.meta_chars and not self.last() == u"\\":
                    raise StringGenerator.SyntaxError(u"Un-escaped special character: %s" % c)
            
            #print( op,len(seq) )
            if op and not left_operand:
                if not seq or len(seq) < 1:
                    raise StringGenerator.SyntaxError(u"Operator: %s with no left operand" % op)
                left_operand = seq.pop()
            elif op and len(seq) >= 1 and left_operand:
                right_operand = seq.pop()

                #print( "popped: [%s] %s:%s"%( op, left_operand, right_operand) )
                if op == u'|':
                    seq.append(StringGenerator.SequenceOR([left_operand, right_operand]))
                elif op == u'&':
                    seq.append(StringGenerator.SequenceAND([left_operand, right_operand]))

                op = u''
                left_operand = None
                right_operand = None

        # check for syntax errors
        if op:
            raise StringGenerator.SyntaxError(u"Operator: %s with no right operand" % op)
        if level > 0 and not sequence_closed:
            # it means we are finishing a non-first-level sequence without closing parens
            raise StringGenerator.SyntaxError(u"Missing closing parenthesis")

        return StringGenerator.Sequence(seq)