Absolute Percent Bias
        input:
        s: simulated
        o: observed
        output:
        apb_bias: absolute percent bias
177309
def apb(s, o):
    
    # s,o = filter_nan(s,o)
    return 100.0*np.sum(np.abs(s-o))/np.sum(o)
517916
def _fix_bias(self, op, attrs, num_inputs):
        """"""
        if op not in [mx.sym.Convolution, mx.sym.Deconvolution, mx.sym.FullyConnected]:
            return attrs
        if num_inputs == 3:
            attrs['no_bias'] = False
        elif num_inputs == 2:
            attrs['no_bias'] = True
        else:
            raise ValueError("Unexpected number of inputs for: {}".format(op))
        return attrs
424301
def bsseval(inargs=None):
    
    parser = argparse.ArgumentParser()

    parser.add_argument(
        'reference_dir',
        type=str
    )

    parser.add_argument(
        'estimates_dir',
        type=str
    )

    parser.add_argument('-o', help='output_dir')

    parser.add_argument(
        '--win', type=float, help='Window size in seconds', default=1.0
    )

    parser.add_argument(
        '--hop', type=float, help='Hop size in seconds', default=1.0
    )

    parser.add_argument(
        '-m', type=str, help='bss_eval version [`v3`, `v4`]', default='v4'
    )

    parser.add_argument(
        '--version', '-v',
        action='version',
        version='%%(prog)s %s' % util.__version__
    )

    args = parser.parse_args(inargs)

    if not args.o:
        output_dir = args.estimates_dir
    else:
        output_dir = args.o

    # evaluate an existing estimate folder with wav files
    data = eval_dir(
        args.reference_dir,
        args.estimates_dir,
        output_dir=output_dir,
        mode=args.m,
        win=args.win,
        hop=args.hop
    )

    print(data)
173595
def bias_ratio(self, positive_or_negative=False):
        
        return self.data.check_moving_average_bias_ratio(
                               self.data.moving_average_bias_ratio(3, 6)[0],
                               positive_or_negative=positive_or_negative)[0]
242822
def _pval_from_bootci(boot, estimate):
    
    if estimate == 0:
        out = 1
    else:
        out = 2 * min(sum(boot > 0), sum(boot < 0)) / len(boot)
    return min(out, 1)
406028
def matches_sample(output, target, threshold, is_correct, actual_output):
        
        return (bool(output > threshold) == bool(target)) == is_correct and actual_output == bool(output > threshold)
886794
def validate_regular_sampling(values, rtol=10e-6):
    
    diffs = np.diff(values)
    return (len(diffs) < 1) or abs(diffs.min()-diffs.max()) < abs(diffs.min()*rtol)
599010
def abs(cls, x: 'TensorFluent') -> 'TensorFluent':
        '''
        '''
        return cls._unary_op(x, tf.abs, tf.float32)
586036
def _fix_bias_shape(self, op_name, inputs, attrs):
        """"""
        if (op_name == 'Add' or op_name == 'Mul') and (int(len(self._params)) > 0) and \
                ('broadcast' in attrs and attrs['broadcast'] == 1):
            assert len(list(inputs)) == 2
            bias_name = self._renames.get(inputs[1], inputs[1])
            bias = self._params[bias_name]
            assert len(bias.shape) == 1
            # reshape to (1, n)
            bias = mx.nd.array(bias.asnumpy().reshape((1, -1, 1, 1)))
            # broadcast_add expects shape with sym.variable
            self._nodes[bias_name] = mx.sym.Variable(name=bias_name, shape=bias.shape)
            self._params[bias_name] = bias
1085589
private double computeConfidence(int support, int samples) {
    final double z = NormalDistribution.standardNormalQuantile(alpha);
    final double eprob = support / (double) samples;
    return Math.max(0., eprob - z * FastMath.sqrt((eprob * (1 - eprob)) / samples));
  }
601280
def __cal_ma_bias_ratio_point(cls, data, sample=5,
                                  positive_or_negative=False):
        
        sample_data = data[-sample:]
        if positive_or_negative:  # 正
            ckvalue = max(sample_data)  # 尋找最大值
            preckvalue = max(sample_data) > 0  # 區間最大值必須為正
        else:
            ckvalue = min(sample_data)  # 尋找最小值
            preckvalue = max(sample_data) < 0  # 區間最大值必須為負
        return (sample - sample_data.index(ckvalue) < 4 and \
                sample_data.index(ckvalue) != sample - 1 and preckvalue,
                sample - sample_data.index(ckvalue) - 1,
                ckvalue)
197653
def cat_acc(y_true, y_pred):
    
    return np.mean(y_true.argmax(axis=1) == y_pred.argmax(axis=1))
599046
def ma_bias_ratio_pivot(self, data, sample_size=5, position=False):
        """"""
        sample = data[-sample_size:]

        if position is True:
            check_value = max(sample)
            pre_check_value = max(sample) > 0
        elif position is False:
            check_value = min(sample)
            pre_check_value = max(sample) < 0

        return ((sample_size - sample.index(check_value) < 4 and
                 sample.index(check_value) != sample_size - 1 and pre_check_value),
                sample_size - sample.index(check_value) - 1,
                check_value)
251118
def p_minus_assignment(self, t):
    ''''''
    self.accu.add(Term('obs_vlabel', [self.name,"gen(\""+t[1]+"\")","-1"]))
1068752
def compute_absolute_error(self, predicted_data, record, dataframe_record):
        ''''''

        new_idxs = []
        for analysis_set in self.get_analysis_sets(record):
            ddg_details = record['DDG'][analysis_set]
            exp_ddg_fieldname = BenchmarkRun.get_analysis_set_fieldname('Experimental', analysis_set)
            absolute_error_fieldname = BenchmarkRun.get_analysis_set_fieldname('AbsoluteError', analysis_set)
            new_idxs.append(absolute_error_fieldname)
            dataframe_record[absolute_error_fieldname] = None

            if ddg_details and predicted_data[self.ddg_analysis_type] != None:
                absolute_error = abs(dataframe_record[exp_ddg_fieldname] - predicted_data[self.ddg_analysis_type])
                dataframe_record[absolute_error_fieldname] = absolute_error

        # Update the CSV headers
        try:
            idx = self.csv_headers.index('AbsoluteError')
            self.csv_headers = self.csv_headers[:idx] + new_idxs + self.csv_headers[idx + 1:]
        except ValueError, e: pass
478140
def simulation(n_obs=300, n_vars=None, alpha=None, beta=None, gamma=None, alpha_=None, t_max=None,
               noise_model='normal', noise_level=1, switches=None):
    
    from .tools.dynamical_model_utils import unspliced, spliced, vectorize

    def draw_poisson(n):
        from random import uniform  # draw from poisson
        t = np.cumsum([- .1 * np.log(uniform(0, 1)) for _ in range(n - 1)])
        return np.insert(t, 0, 0)  # prepend t0=0

    def simulate_dynamics(tau, alpha, beta, gamma, u0, s0, noise_model, noise_level):
        ut = unspliced(tau, u0, alpha, beta)
        st = spliced(tau, s0, u0, alpha, beta, gamma)

        if noise_model is 'normal':  # add noise
            ut += np.random.normal(scale=noise_level * np.percentile(ut, 99) / 10, size=len(ut))
            st += np.random.normal(scale=noise_level * np.percentile(st, 99) / 10, size=len(st))
        ut, st = np.clip(ut, 0, None), np.clip(st, 0, None)
        return ut, st

    def simulate_gillespie(alpha, beta, gamma):
        # update rules: transcription (u+1,s), splicing (u-1,s+1), degradation (u,s-1), nothing (u,s)
        update_rule = np.array([[1, 0], [-1, 1], [0, -1], [0, 0]])

        def update(props):
            if np.sum(props) > 0:
                props /= np.sum(props)
            p_cumsum = props.cumsum()
            p = np.random.rand()
            i = 0
            while p > p_cumsum[i]:
                i += 1
            return update_rule[i]

        u, s = np.zeros(len(alpha)), np.zeros(len(alpha))
        for i, alpha_i in enumerate(alpha):
            u_, s_ = (u[i - 1], s[i - 1]) if i > 0 else (0, 0)
            du, ds = update(props=np.array([alpha_i, beta * u_, gamma * s_]))
            u[i], s[i] = (u_ + du, s_ + ds)
        return u, s

    alpha = 5 if alpha is None else alpha
    beta = .5 if beta is None else beta
    gamma = .3 if gamma is None else gamma
    alpha_ = 0 if alpha_ is None else alpha_

    t = draw_poisson(n_obs)
    if t_max is not None:
        t *= t_max / np.max(t)
    t_max = np.max(t)

    def cycle(array, n_vars=None):
        if isinstance(array, (list, tuple)):
            return array if n_vars is None else array * int(np.ceil(n_vars / len(array)))
        else:
            return [array] if n_vars is None else [array] * n_vars

    # switching time point obtained as fraction of t_max rounded down
    switches = cycle([.4, .7, 1, .1], n_vars) if switches is None else cycle(switches, n_vars)
    t_ = np.array([np.max(t[t < t_i * t_max]) for t_i in switches])

    noise_level = cycle(noise_level, len(switches) if n_vars is None else n_vars)

    n_vars = max(len(switches), len(noise_level))
    U = np.zeros(shape=(len(t), n_vars))
    S = np.zeros(shape=(len(t), n_vars))
    for i in range(n_vars):
        alpha_i = alpha[i] if isinstance(alpha, (tuple, list, np.ndarray)) else alpha
        beta_i = beta[i] if isinstance(beta, (tuple, list, np.ndarray)) else beta
        gamma_i = gamma[i] if isinstance(gamma, (tuple, list, np.ndarray)) else gamma
        tau, alpha_vec, u0_vec, s0_vec = vectorize(t, t_[i], alpha_i, beta_i, gamma_i, alpha_=alpha_, u0=0, s0=0)
        beta_i
        if noise_model is 'gillespie':
            U[:, i], S[:, i] = simulate_gillespie(alpha_vec, beta, gamma)
        else:
            U[:, i], S[:, i] = simulate_dynamics(tau, alpha_vec, beta_i, gamma_i,
                                                 u0_vec, s0_vec, noise_model, noise_level[i])

    obs = {'true_t': t.round(2)}
    var = {'true_t_': t_[:n_vars],
           'true_alpha': np.ones(n_vars) * alpha,
           'true_beta': np.ones(n_vars) * beta,
           'true_gamma': np.ones(n_vars) * gamma,
           'true_scaling': np.ones(n_vars)}
    layers = {'unspliced': U, 'spliced': S}

    return AnnData(S, obs, var, layers=layers)
774584
def check_moving_average_bias_ratio(cls, data, sample=5,
                                        positive_or_negative=False):
        
        return cls.__cal_ma_bias_ratio_point(data, sample,
                                              positive_or_negative)