From bf4fc055a5ad1608f2615db9e686be760be901da Mon Sep 17 00:00:00 2001 From: Florez Ospina Juan Felipe Date: Thu, 9 Nov 2023 10:17:47 +0100 Subject: [PATCH] Implemented module for background estimation --- utils_bge.py | 58 ++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 58 insertions(+) create mode 100644 utils_bge.py diff --git a/utils_bge.py b/utils_bge.py new file mode 100644 index 0000000..a6fd20c --- /dev/null +++ b/utils_bge.py @@ -0,0 +1,58 @@ +import scipy.optimize as sp_opt +import pandas as pd + + + +def construct_mask(x, subinterval_list): + + """ constructs a mask of length len(x) that indicates whether the entries of x lie within the subintervals, + speficified in the subinterval_list. + + Parameters: + x (array_like): + subinterval_list (list of two-element tuples): + + Returns: + mask (Bool array_like): + + Usage: + + x = np.array([0.0 0.25 0.5 0.75 1.5 2.0 2.5 3.0 3.5 4.0]) + subinterval_list = [(0.25,0.75),(2.5,3.5)] + mask = contruct_mask(x,subinterval_list) + + """ + + mask = x < 0.9*x.min() + for subinterval in subinterval_list: + mask = mask | ((x >= subinterval[0]) & (x <= subinterval[1])) + + return mask + + +def estimate_background(x,y,mask,method: str): + + """fits a background model based on the values of x and y indicated by a mask using a method, among available options. + + Parameters: + x,y (array_like, e.g., np.array, pd.Series): + mask (Bool array_like): + method (str): + + Returns: + y_bg (array_like): values of the fitted model at x, or similarly the obtained background estimate + + """ + + if method == 'linear': + def linear_model(x,m,b): + return (m*x) + b + + popt, pcov = sp_opt.curve_fit(linear_model,x[mask],y[mask]) + + y_bg = linear_model(x,*popt) + + else: + raise ValueError("Parameter 'method' can only be set as 'linear'. Future code releases may include more options. ") + + return y_bg