Пример #1
0
    def start(self):
        """Starts the progress bar by taking the start time and setting the
        progress value to the start value.
        If this progress bar has a parent, it adds itself to the parent's list
        of running sub progress bars. Otherwise it will render and print this
        progress bar for the first time.

        Returns
        -------
        self : instance of ProgressBar
            The instance of this ProgressBar.
        """
        self._start_time = time.time()
        self._val = self._startval

        parent = self._parent
        if (parent is not None):
            # Add this progress bar to the parent progress bar.
            parent.add_sub_progress_bar(self)
            return self

        if (not session.is_interactive_session()):
            return self

        self._last_rendered_pbar_str = self._render_pbar_str()

        sys.stdout.write(self._last_rendered_pbar_str)
        sys.stdout.flush()

        return self
Пример #2
0
    def trigger_rerendering(self):
        """Triggers a rerendering of the most top progress bar.
        """
        parent = self._parent
        if (parent is not None):
            parent.trigger_rerendering()
            return

        if (not session.is_interactive_session()):
            return

        # We are the most top parent progress bar. So we need to get rerendered.
        self.rerender()
Пример #3
0
    def finish(self):
        """Finishes this progress bar by setting the current progress value to
        its max value.
        If this progress bar has a parent, it triggers a rerendering of the
        parent and then removes itself from the parent's list of running sub
        progress bars. Otherwise it will render and print this progress bar for
        the last time.
        """
        self._val = self._maxval

        parent = self._parent
        if (parent is not None):
            parent.trigger_rerendering()
            # Remove this progress bar from the parent progress bar.
            parent.remove_sub_progress_bar(self)
            return

        if (not session.is_interactive_session()):
            return

        self._last_rendered_pbar_str = self._render_pbar_str()

        sys.stdout.write('\r' + self._last_rendered_pbar_str + "\n")
        sys.stdout.flush()
Пример #4
0
 def gets_shown(self):
     """(read-only) Flag if the progress bar gets shown. This is ``True``
     if the program is run in an interactive session, ``False`` otherwise.
     """
     return session.is_interactive_session()
Пример #5
0
def generate_mu_of_p_spline_interpolation(
        ana, rss, h0_ts_vals, h0_ts_quantile, eps_p, mu_range, mu_step,
        kind='cubic', bkg_kwargs=None, sig_kwargs=None, ppbar=None, tl=None):
    """Generates a spline interpolation for mu(p) function for a pre-defined
    range of mu, where mu is the mean number of injected signal events and p the
    probability for the ts value larger than the ts value corresponding to the
    given quantile, h0_ts_quantile, of the null hypothesis test-statistic
    distribution.

    Parameters
    ----------
    ana : instance of Analysis
        The Analysis instance to use for the calculation.
    rss : instance of RandomStateService
        The RandomStateService instance to use for generating random numbers.
    h0_ts_vals : (n_h0_ts_vals,)-shaped 1D ndarray | None
        The 1D ndarray holding the test-statistic values for the
        null-hypothesis. If set to `None`, 100/(1-h0_ts_quantile)
        null-hypothesis trials will be generated.
    h0_ts_quantile : float
        Null-hypothesis test statistic quantile, which should be exceeded by
        the alternative hypothesis ts value.
    eps_p : float
        The one sigma precision in `p` as stopping condition for the
        calculation for a single mu value.
    mu_range : 2-element sequence
        The range (lower,upper) of mean number of injected signal events to
        create the interpolation spline for.
    mu_step : float
        The step size of the mean number of signal events.
    kind : str
        The kind of spline to generate. Possble values are 'linear' and 'cubic'
        (default).
    bkg_kwargs : dict | None
        Additional keyword arguments for the `generate_events` method of the
        background generation method class. An usual keyword argument is
        `poisson`.
    sig_kwargs : dict | None
        Additional keyword arguments for the `generate_signal_events` method
        of the `SignalGenerator` class. An usual keyword argument is
        `poisson`. If `poisson` is set to True, the actual number of
        generated signal events will be drawn from a Poisson distribution
        with the mean number of signal events, mu.
    ppbar : instance of ProgressBar | None
        The possible parent ProgressBar instance.
    tl: instance of TimeLord | None
        The optional TimeLord instance that should be used to collect timing
        information about this function.

    Returns
    -------
    spline : callable
        The spline function mu(p).
    """
    logger = logging.getLogger(__name__)

    n_total_generated_trials = 0

    if(h0_ts_vals is None):
        n_bkg = int(100/(1 - h0_ts_quantile))
        logger.debug('Generate %d null-hypothesis trials', n_bkg)
        h0_ts_vals = ana.do_trials(
            rss, n_bkg, mean_n_sig=0, bkg_kwargs=bkg_kwargs,
            sig_kwargs=sig_kwargs, ppbar=ppbar, tl=tl)['ts']
        n_total_generated_trials += n_bkg

    n_h0_ts_vals = len(h0_ts_vals)
    h0_ts_vals = h0_ts_vals[np.isfinite(h0_ts_vals)]
    logger.debug(
        'Number of trials after finite cut: %d (%g%% of total)',
        len(h0_ts_vals), (len(h0_ts_vals)/n_h0_ts_vals)*100)

    c = np.percentile(h0_ts_vals, (1 - h0_ts_quantile) * 100)
    logger.debug(
        'Critical ts value for bkg ts quantile %g: %g',
        h0_ts_quantile, c)

    n_mu = int((mu_range[1]-mu_range[0])/mu_step) + 1
    mu_vals = np.linspace(mu_range[0], mu_range[1], n_mu)
    p_vals = np.empty_like(mu_vals)

    logger.debug(
        'Generate trials for %d mu values',
        n_mu)

    # Create the progress bar if we are in an interactive session.
    pbar = None
    if(is_interactive_session()):
        pbar = ProgressBar(len(mu_vals), parent=ppbar).start()

    for (idx,mu) in enumerate(mu_vals):
        p = None
        (ts_vals, p_sigma) = ([], 2*eps_p)
        while (p_sigma > eps_p):
            ts_vals = np.concatenate(
                (ts_vals,
                 ana.do_trials(
                     rss, 100, mean_n_sig=mu, bkg_kwargs=bkg_kwargs,
                     sig_kwargs=sig_kwargs, ppbar=pbar, tl=tl)['ts']))
            (p, p_sigma) = calculate_pval_from_trials(ts_vals, c)
            n_total_generated_trials += 100
        logger.debug(
            'mu: %g, n_trials: %d, p: %g, p_sigma: %g',
            mu, ts_vals.size, p, p_sigma)
        p_vals[idx] = p

        if(pbar is not None):
            pbar.increment()

    # Make a mu(p) spline via interp1d.
    # The interp1d function requires unique x values. So we need to sort the
    # p_vals in increasing order and mask out repeating p values.
    p_mu_vals = np.array(sorted(zip(p_vals, mu_vals)), dtype=np.float)
    p_vals = p_mu_vals[:,0]
    unique_pval_mask = np.concatenate(([True], np.invert(
        p_vals[1:] <= p_vals[:-1])))
    p_vals = p_vals[unique_pval_mask]
    mu_vals = p_mu_vals[:,1][unique_pval_mask]

    spline = interp1d(p_vals, mu_vals, kind=kind, copy=False,
        assume_sorted=True)

    if(pbar is not None):
        pbar.finish()

    return spline