Exemplo n.º 1
0
    def test_find_bin_warning(self, mock_logger):
        exp_warn = 'When trying to find the bin indices at least one value '\
                   'could not be attributed to a bin in the passed binning'
        bins = hu.get_binning(hist = r.TH1D(create_random_str(), '', 10, 0, 1))
        values = np.array([-0.1, 0.2, 0.3, 0.4])
        bin_idcs = hu.find_bin(bins, values)
        mock_logger.warn.assert_called_with(exp_warn)

        values = np.array([0.1, 0.2, 1.3, 0.4, 0.5])
        bin_idcs = hu.find_bin(bins, values)
        mock_logger.warn.assert_called_with(exp_warn)
Exemplo n.º 2
0
    def eval(self, *args):
        """
        Evaluate the correction map at all the passed values

        Args:
            np.arrays: As many arrays as there are dimensions in the correction
                map. All arrays must be one dimensional and have the same length

        Returns:
            np.array: Array of the values in the correction map at the given
                input coordinates. For coordinates where the acceptance map
                contained 0 (i.e. infinite correction) or where any masking
                condition was true -1 is returned
        """
        if len(args) != self.ndim:
            logging.error('Correction map has dimension {} but trying to '
                          'evaluate it with {}'.format(self.ndim, len(args)))
            return None

        shape = args[0].shape
        for arg in args:
            if arg.shape != shape:
                logging.error('All input values need to have the same shape')
                return None

        var_bins = []
        for i in xrange(self.ndim):
            var_bins.append(find_bin(self.var_binnings[i], args[i]))

        return self.corr_map[var_bins]
Exemplo n.º 3
0
def make_plot_min_chi2(data, var_x, var_y, tf_x, tf_y, gf_only=False):
    """Make a plot showing the min chi2 from the scan for each scan point, where
    the fit was OK"""
    data.loc[:, 'delta_chi2'] = 2 * (data.llh - data.llh.min())

    bin_data = apply_selections(data, lambda d: d.delta_chi2 != 0)
    # Cleanup the data frame by dropping duplicates which can stem from
    # overlapping scanning when done in parallel
    bin_data = bin_data.drop_duplicates()

    if gf_only:
        bin_data = apply_selections(bin_data, lambda d: d.goodFit > 0)

    # Get the binning
    trans_f_x = globals()[tf_x]
    trans_f_y = globals()[tf_y]
    x_vals = trans_f_x(bin_data.loc[:, var_x])
    y_vals = trans_f_y(bin_data.loc[:, var_y])

    x_binning = get_variable_binning(x_vals)
    y_binning = get_variable_binning(y_vals)

    arr = np.zeros((len(x_binning) - 1, len(y_binning) - 1))
    x_bin = find_bin(x_binning, x_vals)
    y_bin = find_bin(y_binning, y_vals)

    dchi2 = bin_data.delta_chi2.values
    arr[x_bin, y_bin] = dchi2[:]

    hist = from_array(arr, np.array([x_binning, y_binning]))

    can = _setup_canvas(None)
    can.SetRightMargin(0.12)

    mkplot(hist,
           can=can,
           drawOpt='colz',
           xRange=[x_binning[0], x_binning[-1]],
           yRange=[y_binning[0], y_binning[-1]],
           xLabel=get_var_name(var_x, tf_x),
           yLabel=get_var_name(var_y, tf_y))

    hist.GetZaxis().SetRangeUser(0, 25)

    can.Update()

    return can
def get_pt_bin(amap, pt_val):
    """
    Get the pt bin costh-phi map from the passed (3d) acceptance map
    """
    pt_bin = find_bin(get_binning(amap, 2), np.array([pt_val]))[0]
    val, err = get_array(amap), get_array(amap, errors=True)
    ctp_binning = np.array([get_binning(amap, i) for i in [0, 1]])

    return from_array(val[:, :, pt_bin], ctp_binning, errors=err[:, :, pt_bin])
Exemplo n.º 5
0
    def test_find_bin_nonreg_binning(self):
        hist = r.TH1D(create_random_str(8), '', 10, np.linspace(0, 1, 11)**2)
        binning = hu.get_binning(hist)

        values = np.random.uniform(0, 1, 1000)
        exp_idcs = np.array([hist.FindBin(v) for v in values])
        exp_idcs -= 1

        bin_idcs = hu.find_bin(binning, values)
        npt.assert_equal(bin_idcs, exp_idcs)
Exemplo n.º 6
0
    def test_find_bin_reg_binning(self):
        hist = r.TH1D(create_random_str(8), '', 10, 0, 1)
        binning = hu.get_binning(hist)

        values = np.random.uniform(0, 1, 1000)
        exp_idcs = np.array([hist.FindBin(v) for v in values])
        exp_idcs -= 1 # correct for TH1 indexing starting at 1

        bin_idcs = hu.find_bin(binning, values)
        npt.assert_equal(bin_idcs, exp_idcs)
Exemplo n.º 7
0
def get_coverage_contour(hist, coverage=0.683):
    """
    Get the contour from the passed histogram that surpasses the specified coerage
    """
    vals = get_array(hist)
    sum_vals = np.sum(vals)

    def _coverage(level):
        """Calculate the coverage corresponding to the passed level"""
        return np.sum(vals * (vals >= level)) / sum_vals

    # do some pre-processing to start from a slightly better bracket for the
    # secant method
    dec_cov = np.array(
        [_coverage(0.05 * i * np.max(vals)) for i in xrange(21)])
    q_bin = find_bin(dec_cov, np.array([coverage]))
    search_brack = [
        q_bin * 0.05 * np.max(vals), (q_bin + 1) * 0.05 * np.max(vals)
    ]

    cov_level = root_scalar(lambda x: _coverage(x) - coverage,
                            bracket=search_brack)

    filled = vals >= cov_level.root

    x_vals, y_vals = get_binning(hist, 'X'), get_binning(hist, 'Y')
    # get the bin centers
    x_vals = 0.5 * (x_vals[1:] + x_vals[:-1])
    y_vals = 0.5 * (y_vals[1:] + y_vals[:-1])

    filled_coords = []
    for ix, xv in enumerate(x_vals):
        for iy, yv in enumerate(y_vals):
            if filled[ix, iy]:
                filled_coords.append([xv, yv])

    return contour_as_tgraph(np.array(filled_coords))