Sort a list of chromosomes in the order 1..22, X, Y, M/MT

    :param list in_chroms: Input chromosomes
    :return: Sorted chromosomes
    :rtype: list[str]
197088
def canonical_chrom_sorted(in_chroms):
    
    if len(in_chroms) == 0:
        return []
    chr_prefix = False
    mt = False
    if in_chroms[0].startswith('chr'):
        in_chroms = [x.lstrip('chr') for x in in_chroms]
        chr_prefix = True
    if 'MT' in in_chroms:
        in_chroms[in_chroms.index('MT')] = 'M'
        mt = True
    in_chroms = sorted(in_chroms, key=lambda c: int(c) if c not in ('X', 'Y', 'M') else c)
    try:
        m_index = in_chroms.index('M')
    except ValueError:
        pass
    else:
        in_chroms.pop(m_index)
        in_chroms.append('M')
    # At this point it should be nicely sorted
    if mt:
        in_chroms[in_chroms.index('M')] = 'MT'
    if chr_prefix:
        in_chroms = [''.join(['chr', x]) for x in in_chroms]
    return in_chroms
125788
def _freqs_by_chromosome(in_file, params, somatic_info):
    
    freqs = []
    coords = []
    cur_chrom = None
    with pysam.VariantFile(in_file) as bcf_in:
        for rec in bcf_in:
            if _is_biallelic_snp(rec) and _passes_plus_germline(rec) and chromhacks.is_autosomal(rec.chrom):
                if cur_chrom is None or rec.chrom != cur_chrom:
                    if cur_chrom and len(freqs) > 0:
                        yield cur_chrom, freqs, coords
                    cur_chrom = rec.chrom
                    freqs = []
                    coords = []
                stats = _tumor_normal_stats(rec, somatic_info)
                if tz.get_in(["tumor", "depth"], stats, 0) > params["min_depth"]:
                    # not a ref only call
                    if len(rec.samples) == 0 or sum(rec.samples[somatic_info.tumor_name].allele_indices) > 0:
                        freqs.append(tz.get_in(["tumor", "freq"], stats))
                        coords.append(rec.start)
        if cur_chrom and len(freqs) > 0:
            yield cur_chrom, freqs, coords
212699
def sort_idx(m, reverse=False):
    """"""
    return sorted(range(len(m)), key=lambda k: m[k], reverse=reverse)
545640
def _get_larger_chroms(ref_file):
    
    from scipy.cluster.vq import kmeans, vq
    all_sizes = []
    for c in ref.file_contigs(ref_file):
        all_sizes.append(float(c.size))
    all_sizes.sort()
    if len(all_sizes) > 5:
        # separate out smaller chromosomes and haplotypes with kmeans
        centroids, _ = kmeans(np.array(all_sizes), 2)
        idx, _ = vq(np.array(all_sizes), centroids)
        little_sizes = tz.first(tz.partitionby(lambda xs: xs[0], zip(idx, all_sizes)))
        little_sizes = [x[1] for x in little_sizes]
        # create one more cluster with the smaller, removing the haplotypes
        centroids2, _ = kmeans(np.array(little_sizes), 2)
        idx2, _ = vq(np.array(little_sizes), centroids2)
        little_sizes2 = tz.first(tz.partitionby(lambda xs: xs[0], zip(idx2, little_sizes)))
        little_sizes2 = [x[1] for x in little_sizes2]
        # get any chromosomes not in haplotype/random bin
        thresh = max(little_sizes2)
    else:
        thresh = 0
    larger_chroms = []
    for c in ref.file_contigs(ref_file):
        if c.size > thresh:
            larger_chroms.append(c.name)
    return larger_chroms
1286280
def sorted(cls, items, orders):
    ''''''
    return sorted(items, cmp=cls.multipleOrderComparison(orders))
1269679
def sort_list_of_dicts(lst_of_dct, keys, reverse=False, **sort_args):
    

    if type(keys) != list:
        keys = [keys]
    # dcmdir = lst_of_dct[:]
    # lst_of_dct.sort(key=lambda x: [x[key] for key in keys], reverse=reverse, **sort_args)
    lst_of_dct.sort(key=lambda x: [((False, x[key]) if key in x else (True, 0)) for key in keys], reverse=reverse, **sort_args)
    return lst_of_dct
638839
def natsorted(seq, cmp=natcmp):
    ""
    import copy
    temp = copy.copy(seq)
    natsort(temp, cmp)
    return temp
662764
def sort_return_tuples(response, **options):
    
    if not response or not options['groups']:
        return response
    n = options['groups']
    return list(zip(*[response[i::n] for i in range(n)]))
726235
def sort(self, cmp=None, key=None, reverse=False):
        
        self._col_list.sort(cmp, key, reverse)
646958
def human_sorting(the_list):
    
    def try_int(s):
        try:
            return int(s)
        except ValueError:
            return s

    def alphanum_key(s):
        """Turn a string into a list of string and number chunks.

        For instance : "z23a" -> ["z", 23, "a"]
        """
        return [try_int(c) for c in re.split('([0-9]+)', s)]

    the_list.sort(key=alphanum_key)
    return the_list
730905
def range(self):
    
    chrs = set([x.range.chr for x in self.get_transcripts()])
    if len(chrs) != 1: return None
    start = min([x.range.start for x in self.get_transcripts()])
    end = max([x.range.end for x in self.get_transcripts()])
    return GenomicRange(list(chrs)[0],start,end)
1203474
def get_chromosomes(snps):
    

    if isinstance(snps, pd.DataFrame):
        return list(pd.unique(snps["chrom"]))
    else:
        return []
608658
def sort_variants(vcf_handle):
    
    logger.debug("Creating temp file")
    temp_file = NamedTemporaryFile(delete=False)
    temp_file.close()
    logger.debug("Opening temp file with codecs")
    temp_file_handle = codecs.open(
                        temp_file.name,
                        mode='w',
                        encoding='utf-8',
                        errors='replace'
                        )

    try:
        with codecs.open(temp_file.name,mode='w',encoding='utf-8',errors='replace') as f:
            for line in vcf_handle:
                if not line.startswith('#'):
                    line = line.rstrip().split('\t')
                    chrom = line[0]
                    priority = get_chromosome_priority(chrom)
                
                    print_line = "{0}\t{1}\n".format(priority, '\t'.join(line))
                    f.write(print_line)
        #Sort the variants
        sort_variant_file(temp_file.name)
        
        with codecs.open(temp_file.name,mode='r',encoding='utf-8',errors='replace') as f:
            for line in f:
                line = line.rstrip().split('\t')
                yield '\t'.join(line[1:])

    except Exception as err:
        logger.error("Something went wrong")
        logger.error(err)
    finally:
        logger.debug("Deleting temp file")
        os.remove(temp_file.name)
        logger.debug("Temp file deleted")
179177
def sort_index(self):
        
        sort = sorted_list_indexes(self._index)
        # sort index
        self._index = blist([self._index[x] for x in sort]) if self._blist else [self._index[x] for x in sort]
        # sort data
        self._data = blist([self._data[x] for x in sort]) if self._blist else [self._data[x] for x in sort]
1172982
private List<Coordinate> sortY(List<Coordinate> coordinates) {
		List<Coordinate> sorted = new ArrayList<Coordinate>(coordinates);
		Collections.sort(sorted, new YComparator());
		return sorted;
	}
305931
def batchlobstr(args):
    
    p = OptionParser(batchlobstr.__doc__)
    p.add_option("--haploid", default="chrY,chrM",
                 help="Use haploid model for these chromosomes")
    p.set_cpus()
    opts, args = p.parse_args(args)

    if len(args) != 1:
        sys.exit(not p.print_help())

    bamlist, = args
    cmd = "python -m jcvi.variation.str lobstr TREDs"
    cmd += " --input_bam_path {}"
    cmd += " --haploid {}".format(opts.haploid)
    cmd += " --simulation"
    cmds = [cmd.format(x.strip()) for x in open(bamlist).readlines()]
    p = Parallel(cmds, cpus=opts.cpus)
    p.run()
1188030
def multiprocess_permutation(bed_dict, mut_df, opts, indel_df=None):
    
    chroms = sorted(bed_dict.keys(), key=lambda x: len(bed_dict[x]), reverse=True)
    multiprocess_flag = opts['processes']>0
    if multiprocess_flag:
        num_processes = opts['processes']
    else:
        num_processes = 1
    #file_handle = open(opts['output'], 'w')
    file_handle = opts['handle']
    mywriter = csv.writer(file_handle, delimiter='\t', lineterminator='\n')
    if opts['maf'] and opts['num_iterations']:
        header = ['Gene', 'strand', 'Chromosome', 'Start_Position',
                  'End_Position', 'Reference_Allele', 'Tumor_Allele',
                  'Context', 'DNA_Change', 'Protein_Change', 'Variant_Classification']
    elif opts['maf']:
        header = ['Gene', 'strand', 'Chromosome', 'Start_Position',
                  'End_Position', 'Reference_Allele', 'Tumor_Allele',
                  'DNA_Change', 'Protein_Change', 'Variant_Classification',
                  'Tumor_Sample', 'Tumor_Type']
    else:
        header = ['Gene', 'ID', 'gene length', 'non-silent snv', 'silent snv', 'nonsense', 'lost stop',
                  'splice site', 'lost start', 'missense', 'recurrent missense',
                  'normalized missense position entropy',]
        # add column header for scores, is user provided one
        if opts['score_dir']:
            header += ['Total Missense MGAEntropy', 'Total Missense VEST Score']
        # add indel columns
        header += ['frameshift indel', 'inframe indel', 'normalized mutation entropy']
    mywriter.writerow(header)
    num_iterations = opts['num_iterations']

    # simulate indel counts
    if opts['summary'] and num_iterations:
        fs_cts, inframe_cts, gene_names = indel.simulate_indel_counts(indel_df,
                                                                      bed_dict,
                                                                      num_iterations,
                                                                      opts['seed'])
        name2ix = {gene_names[z]: z for z in range(len(gene_names))}
    # just count observed indels
    elif opts['summary']:
        # get gene names
        gene_names = [mybed.gene_name
                      for chrom in bed_dict
                      for mybed in bed_dict[chrom]]
        name2ix = {gene_names[z]: z for z in range(len(gene_names))}

        # initiate count vectors
        inframe_cts = np.zeros((1, len(gene_names)))
        fs_cts = np.zeros((1, len(gene_names)))

        # populate observed counts
        indel_cts_dict = indel_df['Gene'].value_counts().to_dict()
        fs_cts_dict = indel_df[indel.is_frameshift_annotation(indel_df)]['Gene'].value_counts().to_dict()
        for mygene in indel_cts_dict:
            if mygene in name2ix:
                # gene should be found in BED file annotation
                ix = name2ix[mygene]
                fs_cts[0, ix] = 0 if mygene not in fs_cts_dict else fs_cts_dict[mygene]
                inframe_cts[0, ix] = indel_cts_dict[mygene] - fs_cts[0, ix]

    # simulate snvs
    obs_result = []
    for i in range(0, len(chroms), num_processes):
        if multiprocess_flag:
            pool = Pool(processes=num_processes)
            tmp_num_proc = len(chroms) - i if i + num_processes > len(chroms) else num_processes
            info_repeat = ((bed_dict[chroms[tmp_ix]], mut_df, opts)
                            for tmp_ix in range(i, i+tmp_num_proc))
            process_results = pool.imap(singleprocess_permutation, info_repeat)
            process_results.next = utils.keyboard_exit_wrapper(process_results.next)
            try:
                # iterate through each chromosome result
                for chrom_result in process_results:
                    # add columns for indels
                    if opts['summary']:
                        tmp_chrom_result = []
                        for gname, grp in it.groupby(chrom_result, lambda x: x[0]):
                            for l, row in enumerate(grp):
                                gene_ix = name2ix[gname]
                                fs_count = fs_cts[l, gene_ix]
                                inframe_count = inframe_cts[l, gene_ix]
                                missense_pos_ct = list(row.pop(-1).values())  # missense codon counts
                                silent_pos_ct = [1 for l in range(row[4])]
                                inactivating_ct = sum(row[5:9]) + fs_count
                                tmp_count_list = missense_pos_ct + silent_pos_ct + [inactivating_ct, inframe_count]
                                norm_ent = math.normalized_mutation_entropy(tmp_count_list)
                                tmp_chrom_result.append(row+[fs_count, inframe_count, norm_ent])
                        chrom_result = tmp_chrom_result

                    # write output to file
                    mywriter.writerows(chrom_result)
            except KeyboardInterrupt:
                pool.close()
                pool.join()
                logger.info('Exited by user. ctrl-c')
                sys.exit(0)
            pool.close()
            pool.join()
        else:
            # perform simulation
            info = (bed_dict[chroms[i]], mut_df, opts)
            chrom_results = singleprocess_permutation(info)

            # add indel columns
            if opts['summary']:
                tmp_chrom_result = []
                for gname, grp in it.groupby(chrom_results, lambda x: x[0]):
                    for l, row in enumerate(grp):
                        gene_ix = name2ix[gname]
                        fs_count = fs_cts[l, gene_ix]
                        inframe_count = inframe_cts[l, gene_ix]
                        missense_pos_ct = list(row.pop(-1).values())  # missense codon counts
                        silent_pos_ct = [1 for l in range(row[4])]
                        inactivating_ct = sum(row[5:9]) + fs_count
                        tmp_count_list = missense_pos_ct + silent_pos_ct + [inactivating_ct, inframe_count]
                        norm_ent = math.normalized_mutation_entropy(tmp_count_list)
                        tmp_chrom_result.append(row+[fs_count, inframe_count, norm_ent])
                chrom_results = tmp_chrom_result

            # write to file
            mywriter.writerows(chrom_results)