From c94d646b024679d007ef3da6da0fb57b338d3359 Mon Sep 17 00:00:00 2001 From: Thibault Barnouin Date: Wed, 19 Mar 2025 16:38:03 +0100 Subject: [PATCH] change histogram binning to numpy function --- package/lib/background.py | 32 +++++++++----------------------- 1 file changed, 9 insertions(+), 23 deletions(-) diff --git a/package/lib/background.py b/package/lib/background.py index 99a09f2..96509d2 100755 --- a/package/lib/background.py +++ b/package/lib/background.py @@ -278,7 +278,7 @@ def bkg_fit(data, error, mask, headers, subtract_error=True, display=False, save return n_data_array, n_error_array, headers, background -def bkg_hist(data, error, mask, headers, sub_type=None, subtract_error=True, display=False, savename=None, plots_folder=""): +def bkg_hist(data, error, mask, headers, n_bins=None, subtract_error=True, display=False, savename=None, plots_folder=""): """ ---------- Inputs: @@ -333,29 +333,15 @@ def bkg_hist(data, error, mask, headers, sub_type=None, subtract_error=True, dis for i, image in enumerate(data): # Compute the Count-rate histogram for the image n_mask = np.logical_and(mask, image > 0.0) - if sub_type is not None: - if isinstance(sub_type, int): - n_bins = sub_type - elif sub_type.lower() in ["square-root", "squareroot", "sqrt"]: - n_bins = np.fix(np.sqrt(image[n_mask].size)).astype(int) # Square-root - elif sub_type.lower() in ["sturges"]: - n_bins = np.ceil(np.log2(image[n_mask].size)).astype(int) + 1 # Sturges - elif sub_type.lower() in ["rice"]: - n_bins = 2 * np.fix(np.power(image[n_mask].size, 1 / 3)).astype(int) # Rice - elif sub_type.lower() in ["freedman-diaconis", "freedmandiaconis", "freedman", "diaconis"]: - n_bins = np.fix( - (image[n_mask].max() - image[n_mask].min()) - / (2 * np.subtract(*np.percentile(image[n_mask], [75, 25])) / np.power(image[n_mask].size, 1 / 3)) - ).astype(int) # Freedman-Diaconis - else: # Fallback - n_bins = np.fix((image[n_mask].max() - image[n_mask].min()) / (3.5 * image[n_mask].std() / np.power(image[n_mask].size, 1 / 3))).astype( - int - ) # Scott - else: # Default statistic - n_bins = np.fix((image[n_mask].max() - image[n_mask].min()) / (3.5 * image[n_mask].std() / np.power(image[n_mask].size, 1 / 3))).astype( - int - ) # Scott + if not isinstance(n_bins, int) and n_bins not in ["auto", "fd", "doane", "scott", "stone", "rice", "sturges", "sqrt"]: + match n_bins.lower(): + case "square-root" | "squareroot": + n_bins = "sqrt" + case "freedman-diaconis" | "freedmandiaconis": + n_bins = "fd" + case _: + n_bins = "scott" hist, bin_edges = np.histogram(np.log(image[n_mask]), bins=n_bins) histograms.append(hist) binning.append(np.exp(bin_centers(bin_edges)))