return basic descriptive stats of some numerical sample
5653
function descStats(sample) {
    var S = [].concat(sample);
    S.sort(function sortOrder(a, b) {
        return a - b;
    });
    var N = S.length;
    var q1 = S[Math.floor(0.25 * N)];
    var q2 = S[Math.floor(0.50 * N)];
    var q3 = S[Math.floor(0.70 * N)];
    var iqr = q3 - q1;
    var tol = 3 * iqr / 2;
    var hi = q3 + tol;
    var whiIndex = N;
    while (--whiIndex > 0) {
        if (S[whiIndex] <= hi) {
            break;
        }
    }
    var whiPct = (whiIndex + 1) / N;
    var whi = S[whiIndex];
    return {
        min: S[0],
        max: S[N - 1],
        q1: q1,
        q2: q2,
        q3: q3,
        hi: hi,
        whi: whi,
        whiPct: whiPct
    };
}
606300
def _repr_tty_(self) -> str:
        """"""
        header_description = ['Sample_ID', 'Description']
        header_samples = [
            'Sample_ID',
            'Sample_Name',
            'Library_ID',
            'index',
            'index2',
        ]

        header = SingleTable([], 'Header')
        setting = SingleTable([], 'Settings')
        sample_main = SingleTable([header_samples], 'Identifiers')
        sample_desc = SingleTable([header_description], 'Descriptions')

        # All key:value pairs found in the [Header] section.
        max_header_width = max(MIN_WIDTH, sample_desc.column_max_width(-1))
        for key in self.Header.keys():
            if 'Description' in key:
                value = '\n'.join(
                    wrap(getattr(self.Header, key), max_header_width)
                )
            else:
                value = getattr(self.Header, key)
            header.table_data.append([key, value])

        # All key:value pairs found in the [Settings] and [Reads] sections.
        for key in self.Settings.keys():
            setting.table_data.append((key, getattr(self.Settings, key) or ''))
        setting.table_data.append(('Reads', ', '.join(map(str, self.Reads))))

        # Descriptions are wrapped to the allowable space remaining.
        description_width = max(MIN_WIDTH, sample_desc.column_max_width(-1))
        for sample in self.samples:
            # Add all key:value pairs for this sample
            sample_main.table_data.append(
                [getattr(sample, title) or '' for title in header_samples]
            )
            # Wrap and add the sample descrption
            sample_desc.table_data.append(
                (
                    sample.Sample_ID,
                    '\n'.join(
                        wrap(sample.Description or '', description_width)
                    ),
                )
            )

        # These tables do not have horizontal headers so remove the frame.
        header.inner_heading_row_border = False
        setting.inner_heading_row_border = False

        table = '\n'.join(
            [header.table, setting.table, sample_main.table, sample_desc.table]
        )

        return table
1272817
def get_peak_number(self, sample):
        
        proc = subprocess.Popen(["wc", "-l", sample.peaks], stdout=subprocess.PIPE)
        out, err = proc.communicate()
        sample["peakNumber"] = re.sub("\D.*", "", out)
        return sample
622115
def stats(self):
        
        ret = '{name}:\n' \
            '  sample_num={sample_num}, batch_num={batch_num}\n' \
            '  key={bucket_keys}\n' \
            '  cnt={bucket_counts}\n' \
            '  batch_size={bucket_batch_sizes}'\
            .format(name=self.__class__.__name__,
                    sample_num=len(self._lengths),
                    batch_num=len(self._batch_infos),
                    bucket_keys=self._bucket_keys,
                    bucket_counts=[len(sample_ids) for sample_ids in self._bucket_sample_ids],
                    bucket_batch_sizes=self._bucket_batch_sizes)
        return ret
240844
def get_data(n_samples=100):
    """"""
    X, y = make_classification(
        n_samples=n_samples,
        n_features=N_FEATURES,
        n_classes=N_CLASSES,
        random_state=0,
    )
    X = X.astype(np.float32)
    return X, y
266125
def samples(self):
        """"""
        names = self.series.dimensions
        for values in zip(*(getattr(self.series, name) for name in names)):
            yield dict(zip(names, values))
873711
def write_stats(stats, fname, header=None):
    """"""
    # Write stats output to file

    for bg in list(stats.values())[0].keys():
        f = open(fname.format(bg), "w")
        if header:
            f.write(header)
        
        stat_keys = sorted(list(list(stats.values())[0].values())[0].keys())
        f.write("{}\t{}\n".format("Motif", "\t".join(stat_keys)))

        for motif in stats:
            m_stats = stats.get(str(motif), {}).get(bg)
            if m_stats:
                f.write("{}\t{}\n".format(
                    "_".join(motif.split("_")[:-1]),
                    "\t".join([str(m_stats[k]) for k in stat_keys])
                    ))
            else:
                logger.warn("No stats for motif {0}, skipping this motif!".format(motif.id))
            #motifs.remove(motif)
        f.close()

    return
1303063
def calculate_statistics(self):
        ""
        rev_ids = range(0, 100, 1)
        feature_values = zip(rev_ids, [0] * 100)
        scores = [self.score(f) for f in feature_values]
        labels = [s['prediction'] for s in scores]
        statistics = Classification(labels, threshold_ndigits=1, decision_key='probability')
        score_labels = list(zip(scores, labels))
        statistics.fit(score_labels)
        return statistics
877269
def stats
      result = cmd("stats")
      Hash[*result.split("\n").map { |line|
          stat = line.strip!.split(/\s+/, 2)
          [stat[1], stat[0].to_i]
        }.flatten
      ]
    end
41561
def bootstrap_statistics(series, statistic, n_samples=1000,
                         confidence_interval=0.95, random_state=None):
    
    if random_state is None:
        random_state = np.random

    alpha = 1 - confidence_interval
    size = (n_samples, len(series))
    inds = random_state.randint(0, len(series), size=size)
    samples = series.values[inds]
    means = np.sort(statistic(samples, axis=1))
    return pd.DataFrame({'ymin': means[int((alpha/2)*n_samples)],
                         'ymax': means[int((1-alpha/2)*n_samples)],
                         'y': [statistic(series)]})
1296557
def _iostats_dict(header, stats):
    '''
    
    '''
    stats = [float((sum(stat) / len(stat)).quantize(decimal.Decimal('.01'))) for stat in zip(*stats)]
    stats = dict(zip(header, stats))
    return stats
744806
def peaks(samples):
    
    max_index = numpy.argmax(samples)
    max_value = samples[max_index]

    min_index = numpy.argmin(samples)
    min_value = samples[min_index]

    if min_index < max_index:
        return (min_value, max_value)
    else:
        return (max_value, min_value)
1205722
def _t1_summary(self,x):
        
        # set decimal places
        if isinstance(self._decimals,int):
            n = self._decimals
        elif isinstance(self._decimals,dict):
            try:
                n = self._decimals[x.name]
            except:
                n = 1
        else:
            n = 1
            warnings.warn('The decimals arg must be an int or dict. Defaulting to {} d.p.'.format(n))

        if x.name in self._nonnormal:
            f = '{{:.{}f}} [{{:.{}f}},{{:.{}f}}]'.format(n,n,n)
            return f.format(np.nanmedian(x.values),
                np.nanpercentile(x.values,25), np.nanpercentile(x.values,75))
        else:
            f = '{{:.{}f}} ({{:.{}f}})'.format(n,n)
            return f.format(np.nanmean(x.values),
                np.nanstd(x.values,ddof=self._ddof))
569206
def _mirbase_stats(data, out_dir):
    """"""
    utils.safe_makedir(out_dir)
    out_file = os.path.join(out_dir, "%s_bcbio_mirbase.txt" % dd.get_sample_name(data))
    out_file_novel = os.path.join(out_dir, "%s_bcbio_mirdeeep2.txt" % dd.get_sample_name(data))
    mirbase_fn = data.get("seqbuster", None)
    if mirbase_fn:
        _get_stats_from_miraligner(mirbase_fn, out_file, "seqbuster")
    mirdeep_fn = data.get("seqbuster_novel", None)
    if mirdeep_fn:
        _get_stats_from_miraligner(mirdeep_fn, out_file_novel, "mirdeep2")
    return {"base": out_file, "secondary": [out_file_novel]}
215923
def mean(self):
    """"""
    if len(self) == 0:
      return float('NaN')
    arr = self.samples()
    return sum(arr) / float(len(arr))
182389
def mp_calc_stats(motifs, fg_fa, bg_fa, bg_name=None):
    """"""
    try:
        stats = calc_stats(motifs, fg_fa, bg_fa, ncpus=1)
    except Exception as e:
        raise
        sys.stderr.write("ERROR: {}\n".format(str(e)))
        stats = {}

    if not bg_name:
        bg_name = "default"

    return bg_name, stats
93147
def parse_summary(self, contents):
        """"""

        lines = contents.strip().split('\n')

        data = {}
        for row in lines[1:]:
            split = row.strip().split('\t')

            sample = split[0]

            data[sample] = {
                'species_a': int(split[1]),
                'species_b': int(split[2]),
                'ambiguous': int(split[3])
            }

        return data