Returns a dict mapping from an index in the ungapped sequence to an index
    in the gapped sequence.

    >>> ungap_index_map('AC-TG-')
    {0: 0, 1: 1, 2: 3, 3: 4}
188980
def ungap_index_map(sequence, gap_chars='-'):
    
    counter = itertools.count(0).__next__
    ungap_indexes = [
        counter() if c not in gap_chars else None for c in iter(sequence)
    ]
    return dict(
        (ungapped, gapped)
        for ungapped, gapped in zip(ungap_indexes, range(len(sequence)))
        if ungapped is not None)
1110515
def _advanced_indexer_subspaces(key):
    
    if not isinstance(key, tuple):
        key = (key,)
    advanced_index_positions = [i for i, k in enumerate(key)
                                if not isinstance(k, slice)]

    if (not advanced_index_positions or
            not _is_contiguous(advanced_index_positions)):
        # Nothing to reorder: dimensions on the indexing result are already
        # ordered like vindex. See NumPy's rule for "Combining advanced and
        # basic indexing":
        # https://docs.scipy.org/doc/numpy/reference/arrays.indexing.html#combining-advanced-and-basic-indexing
        return (), ()

    non_slices = [k for k in key if not isinstance(k, slice)]
    ndim = len(np.broadcast(*non_slices).shape)
    mixed_positions = advanced_index_positions[0] + np.arange(ndim)
    vindex_positions = np.arange(ndim)
    return mixed_positions, vindex_positions
1366462
def group_by_key_impl(sequence):
    
    result = {}
    for element in sequence:
        if result.get(element[0]):
            result.get(element[0]).append(element[1])
        else:
            result[element[0]] = [element[1]]
    return six.viewitems(result)
1152500
def cross_index(values, index):
    
    lengths = [len(v) for v in values]
    length = np.product(lengths)
    if index >= length:
        raise IndexError('Index %d out of bounds for cross-product of size %d'
                         % (index, length))
    indexes = []
    for i in range(1, len(values))[::-1]:
        p = np.product(lengths[-i:])
        indexes.append(index//p)
        index -= indexes[-1] * p
    indexes.append(index)
    return tuple(v[i] for v, i in zip(values, indexes))
766154
def _mapping_to_tuple_pairs(d):
    
    # order the keys, this will prevent different implementations of Python,
    # return different results from the same dictionary since the order of
    # iteration depends on it
    t = []
    ord_keys = sorted(d.keys())
    for k in ord_keys:
        t.append(_product(k, d[k]))
    return tuple(product(*t))
980104
def _to_dict(self):
        
        mapping = {}

        if self.start_open:
            mapping["start_open"] = self.start_open

        if self.start_closed:
            mapping["start_closed"] = self.start_closed

        if self.end_open:
            mapping["end_open"] = self.end_open

        if self.end_closed:
            mapping["end_closed"] = self.end_closed

        return mapping
443833
def interp(mapping, x):
    
    mapping = sorted(mapping)
    if len(mapping) == 1:
        xa, ya = mapping[0]
        if xa == x:
            return ya
        return x
    for (xa, ya), (xb, yb) in zip(mapping[:-1], mapping[1:]):
        if xa <= x <= xb:
            return ya + float(x - xa) / (xb - xa) * (yb - ya)
    return x
12299
def map_alignment(self, prot_seq, nucl_seq):
        
        if prot_seq.id != nucl_seq.id:
            logging.warning(
                'ID mismatch: %s != %s. Are the sequences in the same order?',
                prot_seq.id, nucl_seq.id)

        # Ungap nucleotides
        codons = batch(str(nucl_seq.seq.ungap('-')), 3)
        codons = [''.join(i) for i in codons]
        codon_iter = iter(codons)

        ungapped_prot = str(prot_seq.seq).replace('-', '')

        if len(ungapped_prot) != len(codons):
            table = self.translation_table.forward_table
            prot_str = ' '.join(' ' + p + ' ' for p in ungapped_prot)
            codon_str = ' '.join(codons)
            trans_str = ' '.join(' ' + table.get(codon, 'X') + ' '
                                 for codon in codons)
            raise ValueError("""Length of codon sequence ({0}) does not match \
length of protein sequence ({1}) for {2}
Protein:       {3}
Codons:        {4}
Trans. Codons: {5}""".format(len(codons), len(ungapped_prot), nucl_seq.id, prot_str,
                            codon_str, trans_str))

        try:
            nucl_align = ['---' if p == '-' else next(codon_iter)
                          for p in str(prot_seq.seq)]
        except StopIteration:
            assert False  # Should be checked above

        result = SeqRecord(Seq(''.join(nucl_align)), id=nucl_seq.id,
                           description=nucl_seq.description)

        # Validate
        self._validate_translation(prot_seq.seq.upper(), result.seq.upper())

        return result
168401
function indexMap(s) {
        if (typeof s == 'string') {
            return indexMapStr(s);
        } else {
            var ret = [],
                i = 0,
                l = s.length;
            for (; i < l; i++) {
                ret[i] = indexMapStr(s[i]);
            }
            return ret;
        }
    }
1284201
def get_substructure_mapping(self, other, limit=1):
        
        i = self._matcher(other).subgraph_isomorphisms_iter()
        if limit == 1:
            m = next(i, None)
            if m:
                return {v: k for k, v in m.items()}
            return
        elif limit == 0:
            return ({v: k for k, v in m.items()} for m in i)
        return [{v: k for k, v in m.items()} for m in islice(i, limit)]
293095
def get_residue_mapping(self):
        ''''''
        if len(self.sequence_ids) == 2:
            if not self.alignment_output:
                self.align()
            assert(self.alignment_output)
            return self._create_residue_map(self._get_alignment_lines(), self.sequence_ids[1], self.sequence_ids[2])
        else:
            return None
263837
def get_mapping(self, other):
        
        m = next(self._matcher(other).isomorphisms_iter(), None)
        if m:
            return {v: k for k, v in m.items()}
257492
def get_mapping(self, using=None, **kwargs):
        
        return self._get_connection(using).indices.get_mapping(index=self._name, **kwargs)
1225345
def extract_index(index_data, global_index=False):
    '''
    
    '''
    parsed_data = {}
    keys = []

    for key, value in six.iteritems(index_data):
        for item in value:
            for field, data in six.iteritems(item):
                if field == 'hash_key':
                    parsed_data['hash_key'] = data
                elif field == 'hash_key_data_type':
                    parsed_data['hash_key_data_type'] = data
                elif field == 'range_key':
                    parsed_data['range_key'] = data
                elif field == 'range_key_data_type':
                    parsed_data['range_key_data_type'] = data
                elif field == 'name':
                    parsed_data['name'] = data
                elif field == 'read_capacity_units':
                    parsed_data['read_capacity_units'] = data
                elif field == 'write_capacity_units':
                    parsed_data['write_capacity_units'] = data
                elif field == 'includes':
                    parsed_data['includes'] = data
                elif field == 'keys_only':
                    parsed_data['keys_only'] = True

    if parsed_data['hash_key']:
        keys.append(
            HashKey(
                parsed_data['hash_key'],
                data_type=parsed_data['hash_key_data_type']
            )
        )
    if parsed_data.get('range_key'):
        keys.append(
            RangeKey(
                parsed_data['range_key'],
                data_type=parsed_data['range_key_data_type']
            )
        )
    if (
            global_index and
            parsed_data['read_capacity_units'] and
            parsed_data['write_capacity_units']):
        parsed_data['throughput'] = {
            'read':     parsed_data['read_capacity_units'],
            'write':    parsed_data['write_capacity_units']
        }
    if parsed_data['name'] and keys:
        if global_index:
            if parsed_data.get('keys_only') and parsed_data.get('includes'):
                raise SaltInvocationError('Only one type of GSI projection can be used.')

            if parsed_data.get('includes'):
                return GlobalIncludeIndex(
                    parsed_data['name'],
                    parts=keys,
                    throughput=parsed_data['throughput'],
                    includes=parsed_data['includes']
                )
            elif parsed_data.get('keys_only'):
                return GlobalKeysOnlyIndex(
                    parsed_data['name'],
                    parts=keys,
                    throughput=parsed_data['throughput'],
                )
            else:
                return GlobalAllIndex(
                    parsed_data['name'],
                    parts=keys,
                    throughput=parsed_data['throughput']
                )
        else:
            return AllIndex(
                parsed_data['name'],
                parts=keys
            )
1214695
def get_chain_mapping(self, pdb_name1, pdb_name2):
        ''''''
        raise Exception('Implement. Map pdb_namex to its equivalence class, call get_representative_chain_mapping, and something something.')
        pprint.pprint(self.chain_mapping)

        d = {}
        for pdb1_chain_id, matched_chain_list in self.chain_mapping[(pdb_name1, pdb_name2)].iteritems():
            d[pdb1_chain_id] = matched_chain_list.get_related_chains_ids(pdb_name2)
        return d
1123054
def _dict_mapping_to_pb(mapping, proto_type):
    
    converted_pb = getattr(trace_pb2, proto_type)()
    ParseDict(mapping, converted_pb)
    return converted_pb
219997
def uniform_get(sequence, index, default=None):
    """"""

    if isinstance(sequence, abc.Mapping):
        return sequence.get(index, default)
    else:
        return sequence[index] if index < len(sequence) else default