Sort order for Features, by genomic coordinate,
        disambiguated by feature type (alphabetically).
436228
def _recSortKey(r):
        
        return r.seqname, r.start, -r.end, r.type
27976
def normalize_geojson_featurecollection(obj):
    
    if not isinstance(obj, Sequence):
        obj = [obj]

    features = []
    for x in obj:
        if not isinstance(x, Mapping) or 'type' not in x:
            raise ValueError(
                "Expecting a geojson-like mapping or sequence of them")

        if 'features' in x:
            features.extend(x['features'])
        elif 'geometry' in x:
            features.append(x)
        elif 'coordinates' in x:
            feat = {'type': 'Feature',
                    'properties': {},
                    'geometry': x}
            features.append(feat)
        else:
            raise ValueError(
                "Expecting a geojson-like mapping or sequence of them")

    return {'type': 'FeatureCollection', 'features': features}
1168686
def _parse_dict(features, new_names):
        """"""
        feature_collection = OrderedDict()
        for feature_type, feature_names in features.items():
            try:
                feature_type = FeatureType(feature_type)
            except ValueError:
                ValueError('Failed to parse {}, keys of the dictionary have to be instances '
                           'of {}'.format(features, FeatureType.__name__))

            feature_collection[feature_type] = feature_collection.get(feature_type, OrderedDict())

            if feature_names is ...:
                feature_collection[feature_type] = ...

            if feature_type.has_dict() and feature_collection[feature_type] is not ...:
                feature_collection[feature_type].update(FeatureParser._parse_feature_names(feature_names, new_names))

        return feature_collection
1222527
def sort_coords(coord):
    
    import iris
    order = {'T': -2, 'Z': -1, 'X': 1, 'Y': 2}
    axis = iris.util.guess_coord_axis(coord)
    return (order.get(axis, 0), coord and coord.name())
1152135
def genes_with_a_representative_sequence(self):
        """"""
        return DictList(x for x in self.genes if x.protein.representative_sequence)
1016668
def _compute_sorted_indices(self):
        
        sorted_indices = []
        for to_sort in [self.y] + self.x:
            data_w_indices = [(val, i) for (i, val) in enumerate(to_sort)]
            data_w_indices.sort()
            sorted_indices.append([i for val, i in data_w_indices])
        # save in meaningful variable names
        self._yi_sorted = sorted_indices[0]  # list (like self.y)
        self._xi_sorted = sorted_indices[1:]
866934
def filterOverlappingAlignments(alignments):
    
    l = []
    alignments = alignments[:]
    sortAlignments(alignments)
    alignments.reverse()
    for pA1 in alignments:
        for pA2 in l:
            if pA1.contig1 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start1+1, pA2.end1) is not None: #One offset, inclusive coordinates
                break
            if pA1.contig2 == pA2.contig2 and getPositiveCoordinateRangeOverlap(pA1.start2+1, pA1.end2, pA2.start2+1, pA2.end2) is not None: #One offset, inclusive coordinates
                break
            if pA1.contig2 == pA2.contig1 and getPositiveCoordinateRangeOverlap(pA1.start2+1, pA1.end2, pA2.start1+1, pA2.end1) is not None: #One offset, inclusive coordinates
                break
            if pA1.contig1 == pA2.contig2 and getPositiveCoordinateRangeOverlap(pA1.start1+1, pA1.end1, pA2.start2+1, pA2.end2) is not None: #One offset, inclusive coordinates
                break
        else:
            l.append(pA1)
    l.reverse()
    return l
131527
def _parse_tuple(features, new_names):
        """"""
        name_idx = 1
        try:
            feature_type = FeatureType(features[0])
        except ValueError:
            feature_type = None
            name_idx = 0

        if feature_type and not feature_type.has_dict():
            return OrderedDict([(feature_type, ...)])
        return OrderedDict([(feature_type, FeatureParser._parse_names_tuple(features[name_idx:], new_names))])
678437
def nargsort(items, kind='quicksort', ascending=True, na_position='last'):
    

    # specially handle Categorical
    if is_categorical_dtype(items):
        if na_position not in {'first', 'last'}:
            raise ValueError('invalid na_position: {!r}'.format(na_position))

        mask = isna(items)
        cnt_null = mask.sum()
        sorted_idx = items.argsort(ascending=ascending, kind=kind)
        if ascending and na_position == 'last':
            # NaN is coded as -1 and is listed in front after sorting
            sorted_idx = np.roll(sorted_idx, -cnt_null)
        elif not ascending and na_position == 'first':
            # NaN is coded as -1 and is listed in the end after sorting
            sorted_idx = np.roll(sorted_idx, cnt_null)
        return sorted_idx

    with warnings.catch_warnings():
        # https://github.com/pandas-dev/pandas/issues/25439
        # can be removed once ExtensionArrays are properly handled by nargsort
        warnings.filterwarnings(
            "ignore", category=FutureWarning,
            message="Converting timezone-aware DatetimeArray to")
        items = np.asanyarray(items)
    idx = np.arange(len(items))
    mask = isna(items)
    non_nans = items[~mask]
    non_nan_idx = idx[~mask]
    nan_idx = np.nonzero(mask)[0]
    if not ascending:
        non_nans = non_nans[::-1]
        non_nan_idx = non_nan_idx[::-1]
    indexer = non_nan_idx[non_nans.argsort(kind=kind)]
    if not ascending:
        indexer = indexer[::-1]
    # Finally, place the NaNs at the end or the beginning according to
    # na_position
    if na_position == 'last':
        indexer = np.concatenate([indexer, nan_idx])
    elif na_position == 'first':
        indexer = np.concatenate([nan_idx, indexer])
    else:
        raise ValueError('invalid na_position: {!r}'.format(na_position))
    return indexer
291272
function sortByFirst(valueArrays) {
  const firstValues = valueArrays[0];
  const indices = sortedIndices(firstValues);
  return valueArrays.map(function(values) {
    return indices.map(function(sortedIndex) {
      return values[sortedIndex];
    });
  });
}
817464
public List<Feature> getSortedFeatures() {
        ArrayList<Feature> result = new ArrayList<>(pcm.getConcreteFeatures());
        Collections.sort(result, new Comparator<Feature>() {
            @Override
            public int compare(Feature f1, Feature f2) {
                Integer fp1 = getFeaturePosition(f1);
                Integer fp2 = getFeaturePosition(f2);
                return fp1.compareTo(fp2);
            }
        });
        return result;
    }
1095666
def sort_genomic_ranges(rngs):
  """"""
  return sorted(rngs, key=lambda x: (x.chr, x.start, x.end))
1323748
def sort_precursor(c, loci):
    
    # Original Py 2.7 code
    #data_loci = map(lambda (x): [x, loci[x].chr, int(loci[x].start), int(loci[x].end), loci[x].strand, len(c.loci2seq[x])], c.loci2seq.keys())
    # 2to3 suggested Py 3 rewrite
    data_loci = [[x, loci[x].chr, int(loci[x].start), int(loci[x].end), loci[x].strand, len(c.loci2seq[x])] for x in list(c.loci2seq.keys())]
    data_loci = sorted(data_loci, key=itemgetter(5), reverse=True)
    return data_loci
56823
def topological_sort(dependency_pairs):
    ""
    num_heads = defaultdict(int)  # num arrows pointing in
    tails = defaultdict(list)  # list of arrows going out
    heads = []  # unique list of heads in order first seen
    for h, t in dependency_pairs:
        num_heads[t] += 1
        if h in tails:
            tails[h].append(t)
        else:
            tails[h] = [t]
            heads.append(h)

    ordered = [h for h in heads if h not in num_heads]
    for h in ordered:
        for t in tails[h]:
            num_heads[t] -= 1
            if not num_heads[t]:
                ordered.append(t)
    cyclic = [n for n, heads in num_heads.items() if heads]
    return Results(ordered, cyclic)
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)
876452
def find_features(seqs, locus_tag="all", utr_len=200):
    """"""
    found_features = []

    for seq_i in seqs:
        for feature in seq_i.features:
            if feature.type == "CDS" and (locus_tag == "all" or \
                    ('locus_tag' in feature.qualifiers and \
                    feature.qualifiers['locus_tag'][0] == locus_tag)):
                start = max(0, feature.location.nofuzzy_start - utr_len)
                stop  = max(0, feature.location.nofuzzy_end + utr_len)
                feature_seq = seq_i.seq[start:stop]
                f_match = FeatureMatch(feature, feature_seq, feature.strand,
                                       utr_len)
                found_features.append(f_match)

    return found_features
12446
def rank_features(self, inputs: pd.DataFrame, targets: pd.DataFrame, problem_type='classification') -> pd.DataFrame:
        
        try:

            X = normalize( \
                                inputs.apply(pd.to_numeric, errors='coerce') \
                                .applymap(lambda x: 0.0 if np.isnan(x) else x) \
                                .values, axis=0)
            y = targets.iloc[:,0].values
            original_columns = list(inputs)
            print(original_columns)

            if problem_type == 'classification':
                predictor = RandomForestClassifier()
            else:
                predictor = RandomForestRegressor()

            rfe = RFE(predictor, n_features_to_select=1)
            rfe = rfe.fit(X, y)
            
            best_features = [original_columns[i-1] for i in rfe.ranking_]

        except:
            logging.exception("Failed")
            # If any error occurs, just return indices in original order
            # In the future we should consider a better error handling strategy
            best_features = [i for i in range(inputs.shape[1])]

        return best_features