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 < 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