'Gaussian1D': models.Gaussian1D(1.0, 1.0, 1.0), 'GaussianAbsorption1D': models.GaussianAbsorption1D(1.0, 1.0, 1.0), 'Lorentz1D': models.Lorentz1D(1.0, 1.0, 1.0), 'MexicanHat1D': models.MexicanHat1D(1.0, 1.0, 1.0), 'Trapezoid1D': models.Trapezoid1D(1.0, 1.0, 1.0, 1.0), 'Moffat1D': models.Moffat1D(1.0, 1.0, 1.0, 1.0), 'ExponentialCutoffPowerLaw1D': models.ExponentialCutoffPowerLaw1D(1.0, 1.0, 1.0, 1.0), 'BrokenPowerLaw1D': models.BrokenPowerLaw1D(1.0, 1.0, 1.0, 1.0), 'LogParabola1D': models.LogParabola1D(1.0, 1.0, 1.0, 1.0), 'PowerLaw1D': models.PowerLaw1D(1.0, 1.0, 1.0), 'Linear1D': models.Linear1D(1.0, 0.0), 'Const1D': models.Const1D(0.0), 'Redshift': models.Redshift(0.0), 'Scale': models.Scale(1.0), 'Shift': models.Shift(0.0), 'Sine1D':
astmodels.Tangent1D(amplitude=10., frequency=0.5, phase=1.), astmodels.ArcSine1D(amplitude=10., frequency=0.5, phase=1.), astmodels.ArcCosine1D(amplitude=10., frequency=0.5, phase=1.), astmodels.ArcTangent1D(amplitude=10., frequency=0.5, phase=1.), astmodels.Trapezoid1D(amplitude=10., x_0=0.5, width=5., slope=1.), astmodels.TrapezoidDisk2D(amplitude=10., x_0=0.5, y_0=1.5, R_0=5., slope=1.), astmodels.Voigt1D(x_0=0.55, amplitude_L=10., fwhm_L=0.5, fwhm_G=0.9), astmodels.BlackBody(scale=10.0, temperature=6000. * u.K), astmodels.Drude1D(amplitude=10.0, x_0=0.5, fwhm=2.5), astmodels.Plummer1D(mass=10.0, r_plum=5.0), astmodels.BrokenPowerLaw1D(amplitude=10, x_break=0.5, alpha_1=2.0, alpha_2=3.5), astmodels.ExponentialCutoffPowerLaw1D(10, 0.5, 2.0, 7.), astmodels.LogParabola1D( amplitude=10, x_0=0.5, alpha=2., beta=3., ), astmodels.PowerLaw1D(amplitude=10., x_0=0.5, alpha=2.0), astmodels.SmoothlyBrokenPowerLaw1D(amplitude=10., x_break=5.0, alpha_1=2.0, alpha_2=3.0, delta=0.5), custom_and_analytical_inverse(),
# fit_sample = f(x) # p3 = plt.loglog(x, fit_sample, label="Smoothly Broken Power-Law for WikiText2") ################################################################################################################### # Wiki2 (C) ################################################################################################################### break_point = 4 dataset = 6 data = all_mi[dataset] alpha_1 = 0.38215 alpha_2 = 0.003 p1 = plt.loglog(np.arange(1, len(data) + 1), data, label="WikiText2 (C)") amplitude = all_mi[dataset][break_point + 12] x = np.linspace(1, len(data), len(data)) f = models.BrokenPowerLaw1D(amplitude=amplitude, x_break=break_point, alpha_1=alpha_1, alpha_2=alpha_2) fit_sample = f(x) p2 = plt.loglog(x, fit_sample, label="Broken Power-Law for WikiText2 (C)") amplitude = all_mi[dataset][break_point - 1] f = models.SmoothlyBrokenPowerLaw1D(amplitude=amplitude, x_break=break_point, alpha_1=alpha_1, alpha_2=alpha_2) f.delta = 0.25 fit_sample = f(x) p3 = plt.loglog(x, fit_sample, label="Smoothly Broken Power-Law for WikiText2 (C)") ###################################################################################################################
def _selective_fit(self): """Selection depending on Plot Units and Function Model Predefine Input Data in x and y We equate three components to y1, y2, y3. The value of x is the same for all cases x - independent variable, nominally energy in keV y - Plot Unit""" # load chosen file in Select Input section fname = Fitting.fname if fname is None: # if file not choosen, print print('Please, choose input file') else: hdulist = fits.open(fname) header1 = hdulist[1].header header3 = hdulist[3].header data1 = hdulist[1].data data2 = hdulist[2].data Rate = data1.RATE Time = data1.TIME - 2 Livetime = data1.LIVETIME Time_del = data1.TIMEDEL Channel = data1.CHANNEL Fitting.E_min = data2.E_MIN E_max = data2.E_MAX Area = header3[24] E_mean = np.mean(Fitting.E_min) """Define Spectrum Units: Rate, Counts, Flux""" # Define the range for Low and High energies n = len(Fitting.E_min) deltaE = np.zeros(shape=(n)) for i in range(n): deltaE[i] = E_max[i] - Fitting.E_min[i] # Next, we determine the PLot Units components # Rate CountRate = np.zeros(shape=(n)) for i in range(n): CountRate[i] = np.mean(Rate[:, i]) # Counts Counts = np.zeros(shape=(n)) for i in range(n): Counts[i] = np.mean(Rate[:, i] * Time_del[:]) # Flux Flux = np.zeros(shape=(n)) for i in range(n): Flux[i] = np.mean(Rate[:, i] / (Area * deltaE[i] - 2)) # Set the conditions to Set Y axis if Fitting.setEVal is None: x = Fitting.E_min y1 = CountRate y2 = Counts y3 = Flux else: # Energy boundaries energy_min = int(Fitting.setEVal.split(' - ')[0]) energy_max = int(Fitting.setEVal.split(' - ')[1]) assert energy_max > energy_min # Energy value mask energy_mask = (Fitting.E_min >= energy_min) & (Fitting.E_min <= energy_max) x = Fitting.E_min[energy_mask] y1 = CountRate[energy_mask] y2 = Counts[energy_mask] y3 = Flux[energy_mask] # def find_all_indexes(input_str, search_str): # l1 = [] # length = len(input_str) # index = 0 # while index < length: # i = input_str.find(search_str, index) # if i == -1: # return l1 # l1.append(i) # index = i + 1 # return l1 # print(find_all_indexes(str(E_min), str(E_min[0:-1]))) # indexesX = np.where((x <= x[-1]) & (x >= x[0])) # print(indexesX) # indexesY1 = np.where((y3 < y3[-1]) & (y3 > y3[0])) # print(indexesY1) # nX = int(input(self.e1.get())) # nY = int(input(self.e1.get())) # keyword_arrayX = [] # keyword_arrayY = [] # first_E_min = indexes[0] # last_E_min = indexes[-1] # # if first_E_min < arrayX[0] and last_E_min<arrayX[-1]: #################################################### Define Fitters ###################################################### # Fitter creates a new model for x and у, with finding the best fit values fitg1 = fitting.LevMarLSQFitter() #print(fitg1) """ Levenberg - Marquandt algorithm for non - linear least - squares optimization The algorithm works by minimizing the squared residuals, defined as: Residual^2 = (y - f(t))^2 , where y is the measured dependent variable; f(t) is the calculated value The LM algorithm is an iterative process, guessing at the solution of the best minimum """ #################################################### Fitting the data using astropy.modeling ############################### # Define a One dimensional power law model with initial guess PowerLaw1D = models.PowerLaw1D( ) #(amplitude=1, x_0=3, alpha=50, fixed = {'alpha': True}) """ PowerLaw1D(amplitude=1, x_0=1, alpha=1, **kwargs) One dimensional power law model. Parameters: amplitude : float. Model amplitude at the reference point. x_0 : float. Reference point. alpha : float. Power law index. """ # Define a One dimensional broken power law model BrokenPowerLaw1D = models.BrokenPowerLaw1D(amplitude=1, x_break=3, alpha_1=400, alpha_2=1.93, fixed={ 'alpha_1': True, 'alpha_2': True }) """ BrokenPowerLaw1D(amplitude=1, x_break=1, alpha_1=1, alpha_2=1, **kwargs) One dimensional power law model with a break. Parameters: amplitude : float. Model amplitude at the break point. x_break : float. Break point. alpha_1 : float. Power law index for x < x_break. alpha_2 : float. Power law index for x > x_break. """ # Define a Gaussian model ginit = models.Gaussian1D(1000, 6.7, 0.1, fixed={ 'mean': True, 'stddev': True }) #(1000, 6.7, 0.1) """ One dimensional Gaussian model Parameters: amplitude: Amplitude of the Gaussian. mean: Mean of the Gaussian. stddev: Standard deviation of the Gaussian. Other Parameters: fixed : optional. A dictionary {parameter_name: boolean} of parameters to not be varied during fitting. True means the parameter is held fixed. Alternatively the fixed property of a parameter may be used. tied: optional. A dictionary {parameter_name: callable} of parameters which are linked to some other parameter. The dictionary values are callables providing the linking relationship. Alternatively the tied property of a parameter may be used. bounds: optional. A dictionary {parameter_name: value} of lower and upper bounds of parameters. Keys are parameter names. Values are a list or a tuple of length 2 giving the desired range for the parameter. Alternatively, the min and max properties of a parameter may be used. eqcons: optional. A list of functions of length n such that eqcons[j](x0,*args) == 0.0 in a successfully optimized problem. ineqcons: optional. A list of functions of length n such that ieqcons[j](x0,*args) >= 0.0 is a successfully optimized problem. """ p_init = models.Polynomial1D( 2) # Define 2nd order Polynomial function #p_init.parameters = [1,1,1] """ 1D Polynomial model. Parameters: degree: Degree of the series. domain: Optional. window: Optional. If None, it is set to [-1,1] Fitters will remap the domain to this window. **params: Keyword. Value pairs, representing parameter_name: value. Other Parameters: fixed: optional. A dictionary {parameter_name: boolean} of parameters to not be varied during fitting. True means the parameter is held fixed. Alternatively the fixed property of a parameter may be used. tied: optional. A dictionary {parameter_name: callable} of parameters which are linked to some other parameter. The dictionary values are callables providing the linking relationship. Alternatively the tied property of a parameter may be used. bounds: optional. A dictionary {parameter_name: value} of lower and upper bounds of parameters. Keys are parameter names. Values are a list or a tuple of length 2 giving the desired range for the parameter. Alternatively, the min and max properties of a parameter may be used. eqcons: optional. A list of functions of length n such that eqcons[j](x0,*args) == 0.0 in a successfully optimized problem. ineqcons: optional. A list of functions of length n such that ieqcons[j](x0,*args) >= 0.0 is a successfully optimized problem. """ Model = ginit + p_init """ The Model(function) returns the sum of a Gaussian and 2nd order Polynomial """ # Define 6th order Polynomial function Poly = models.Polynomial1D(5, window=[-10, 10], fixed={ 'c3': True, 'c4': True }) Poly.parameters = [1, 1, 1, 1, 1, 50] # Define Exponential function @custom_model def func_exponential(x, t1=1., t2=1.): return (np.exp(t1 - x / t2)) exp = func_exponential(t1=1., t2=1.) """ Purpose: Exponential function Category: spectral fitting Inputs: t0 - Normalization t1 - Pseudo temperature Outputs: result of function, exponential """ # Define Single Power Law Times an Exponential @custom_model def func_exponential_powerlaw(x, p0=1., p1=1., p2=1., e3=1., e4=1.): return ((p0 * (x / p2)**p1) * (np.exp(e3 - x / e4))) exp_powerlaw = func_exponential_powerlaw(p0=1., p1=3., p2=50., e3=1., e4=1., fixed={'p2': True}) """ Purpose: single power - law times an exponential Category: spectral fitting Inputs: p - first 3 parameters describe the single power - law, e - describes the exponential p0 = noramlization at epivot for power - law p1 = negative power - law index p2 = epivot (keV) for power - law e3 = normalization for exponential e4 = pseudo temperature for exponential Outputs: result of function, a power - law times an exponential """ ######################### Define the functions for Rate ############################### # If user select the Rate in Plot Units and PowerLaw1D in Choose Fit Function Model, plot: if (self.var.get() == 'Rate') & (self.lbox.curselection()[0] == 0): gPLRate = fitg1(PowerLaw1D, x, y1, weights=1.0 / y1) print(gPLRate) plt.figure() plt.plot(x, y1, drawstyle='steps-post', label="Rate") plt.plot(x, gPLRate(x), drawstyle='steps-post', color='red', label="PowerLaw1D") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=100, ymin=0.1) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Rate(Counts/s)') plt.legend(loc=2) plt.title('Rate Fitting using 1D Power Law Model') plt.show() # print('RATE & PowerLaw1D') # If user select Rate in Plot Units and BrokenPowerLaw1D in Choose Fit Function Model, plot: elif (self.var.get() == 'Rate') & (self.lbox.curselection()[0] == 1): gBPLRate = fitg1(BrokenPowerLaw1D, x, y1, weights=1.0 / y1) print(gBPLRate) plt.figure() plt.plot(x, y1, drawstyle='steps-post', label="Rate") plt.plot(x, gBPLRate(x), drawstyle='steps-post', color='red', label="BrokenPowerLaw1D") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=100, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Rate(Counts/s)') plt.legend(loc=2) plt.title('Rate Fitting using 1D Broken Power Law Model') plt.show() # print('RATE & BrokenPowerLaw1D') # If user select Rate in Plot Units and Gaussian in Choose Fit Function Model: elif (self.var.get() == 'Rate') & (self.lbox.curselection()[0] == 2): gaussianRate = fitg1(Model, x, y1, weights=1.0 / y1) print(gaussianRate) plt.figure() plt.plot(x, y1, drawstyle='steps-post', label="Rate") plt.plot(x, gaussianRate(x), drawstyle='steps-pre', label='Gaussian') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=100, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Rate(Counts/s)') plt.title('Rate Fitting using Gaussian Model') plt.legend(loc=2) plt.show() # If user select Rate in Plot Units and Polynomial in Choose Fit Function Model: elif (self.var.get() == 'Rate') & (self.lbox.curselection()[0] == 3): PolyRate = fitg1(Poly, x, y1, weights=1.0 / y1) print(PolyRate) plt.figure() plt.plot(x, y1, drawstyle='steps-post', label="Rate") plt.plot(x, PolyRate(x), drawstyle='steps-pre', label='Polynomial') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=100, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Rate(Counts/s)') plt.title('Rate Fitting using Polynomial Model') plt.legend(loc=2) plt.show() # If user select Rate in Plot Units and Exponential in Choose Fit Function Model: elif (self.var.get() == 'Rate') & (self.lbox.curselection()[0] == 4): expRate = fitg1(exp, x, y1) print(expRate) plt.figure() plt.plot(x, y1, drawstyle='steps-post', label="Rate") plt.plot(x, expRate(x), drawstyle='steps-pre', label='Exponential') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=100, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Rate(Counts/s)') plt.title('Rate Fitting using Exponential Model') plt.legend(loc=2) plt.show() # If user select Rate in Plot Units and Exponential Power Law in Choose Fit Function Model: elif (self.var.get() == 'Rate') & (self.lbox.curselection()[0] == 5): ExpPLRate = fitg1(exp_powerlaw, x, y1, weights=1.0 / y1) print(ExpPLRate) plt.figure() plt.plot(x, y1, drawstyle='steps-post', label="Rate") plt.plot(x, ExpPLRate(x), drawstyle='steps-post', color='red', label="ExpPowerLaw") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=100, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Rate(Counts/s)') plt.legend(loc=2) plt.title('Rate Fitting using Exponential Power Law Model') plt.show() ######################### Define the functions for Counts ############################### # If user select Counts in Plot Units and PowerLaw1D in Choose Fit Function Model: elif (self.var.get() == 'Counts') & (self.lbox.curselection()[0] == 0): gPLCounts = fitg1(PowerLaw1D, x, y2, weights=1.0 / y2) print(gPLCounts) plt.figure() plt.plot(x, y2, drawstyle='steps-post', label="Counts") plt.plot(x, gPLCounts(x), drawstyle='steps-post', color='red', label="PowerLaw1D") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1000, ymin=0.1) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Counts(Counts)') plt.legend(loc=2) plt.title('Counts Fitting using 1D Power Law Model') plt.show() # print('COUNTS & PowerLaw1D') # If user select Counts in Plot Units and BrokenPowerLaw1D in Choose Fit Function Model: elif (self.var.get() == 'Counts') & (self.lbox.curselection()[0] == 1): gBPLCounts = fitg1(BrokenPowerLaw1D, x, y2, weights=1.0 / y2) print(gBPLCounts) plt.figure() plt.plot(x, y2, drawstyle='steps-post', label="Counts") plt.plot(x, gBPLCounts(x), drawstyle='steps-post', color='red', label="BrokenPowerLaw1D") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1000, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Counts(Counts)') plt.legend(loc=2) plt.title('Counts Fitting using 1D Broken Power Law Model') plt.show() # print('COUNTS & BrokenPowerLaw1D') # If user select Counts in Plot Units and Gaussian in Choose Fit Function Model: elif (self.var.get() == 'Counts') & (self.lbox.curselection()[0] == 2): gaussianCounts = fitg1(Model, x, y2, weights=1.0 / y2) print(gaussianCounts) plt.figure() plt.plot(x, y2, drawstyle='steps-post', label="Counts") plt.plot(x, gaussianCounts(x), drawstyle='steps-pre', label='Gaussian') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1000, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Counts(Counts)') plt.title('Counts Fitting using Gaussian Model') plt.legend(loc=2) plt.show() # If user select Counts in Plot Units and Polynomial in Choose Fit Function Model: elif (self.var.get() == 'Counts') & (self.lbox.curselection()[0] == 3): PolyCounts = fitg1(Poly, x, y2, weights=1.0 / y2) print(PolyCounts) plt.figure() plt.plot(x, y2, drawstyle='steps-post', label="Counts") plt.plot(x, PolyCounts(x), drawstyle='steps-pre', label='Polynomial') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1000, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Counts(Counts)') plt.title('Counts Fitting using Polynomial Model') plt.legend(loc=2) plt.show() # If user select Counts in Plot Units and Exponential in Choose Fit Function Model: elif (self.var.get() == 'Counts') & (self.lbox.curselection()[0] == 4): expCounts = fitg1(exp, x, y2, weights=1.0 / y2) print(expCounts) plt.figure() plt.plot(x, y2, drawstyle='steps-post', label="Counts") plt.plot(x, expCounts(x), drawstyle='steps-pre', label='Exponential') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1000, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Counts(Counts)') plt.title('Counts Fitting using Exponential Model') plt.legend(loc=2) plt.show() # If user select Counts in Plot Units and Exponential Power Law in Choose Fit Function Model: elif (self.var.get() == 'Counts') & (self.lbox.curselection()[0] == 5): ExpPLCounts = fitg1(exp_powerlaw, x, y2, weights=1.0 / y2) print(ExpPLCounts) plt.figure() plt.plot(x, y2, drawstyle='steps-post', label="Counts") plt.plot(x, ExpPLCounts(x), drawstyle='steps-post', color='red', label="ExpPowerLaw") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1000, ymin=0.1) plt.xlabel('Energy(keV)') plt.ylabel('Counts(Counts)') plt.legend(loc=2) plt.title('Counts Fitting using Exponential Power Law Model') plt.show() ######################### Define the functions for Flux ############################### # If user select Flux in Plot Units and PowerLaw1D in Choose Fit Function Model: elif (self.var.get() == 'Flux') & (self.lbox.curselection()[0] == 0): gPLFlux = fitg1(PowerLaw1D, x, y3, weights=1.0 / y3) plt.figure() plt.plot(x, y3, drawstyle='steps-post', label="Flux") plt.plot(x, gPLFlux(x), drawstyle='steps-post', color='red', label="PowerLaw1D") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1, ymin=0.0001) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Flux(Counts/s cm(-2) keV(-1))') plt.legend(loc=2) plt.title('Flux Fitting using 1D Power Law Model') plt.show() # print('FLUX & PowerLaw1D') # If user select Flux in Plot Units and BrokenPowerLaw1D in Choose Fit Function Model: elif (self.var.get() == 'Flux') & (self.lbox.curselection()[0] == 1): # Apply Levenberg - Marquandt algorithm gBPLFlux = fitg1(BrokenPowerLaw1D, x, y3, weights=1.0 / y3) print(gBPLFlux) plt.figure() plt.plot(x, y3, drawstyle='steps-post', label="Flux") plt.plot(x, gBPLFlux(x), drawstyle='steps-post', color='red', label="BrokenPowerLaw1D") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1, ymin=0.0001) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Flux(Counts/s cm(-2) keV(-1))') plt.legend(loc=2) plt.title('Flux Fitting using 1D Broken Power Law Model') plt.show() # print('FLUX & BrokenPowerLaw1D') # If user select Flux in Plot Units and Gaussian in Choose Fit Function Model: elif (self.var.get() == 'Flux') & (self.lbox.curselection()[0] == 2): gaussianFlux = fitg1(Model, x, y3, weights=1.0 / y3) print(gaussianFlux) plt.figure() plt.plot(x, y3, drawstyle='steps-post', label="Flux") plt.plot(x, gaussianFlux(x), drawstyle='steps-pre', label='Gaussian') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1, ymin=0.0001) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Flux(Counts/s cm(-2) keV(-1))') plt.title('Flux Fitting using Gaussian Model') plt.legend(loc=2) plt.show() # If user select Flux in Plot Units and Polynomial in Choose Fit Function Model: elif (self.var.get() == 'Flux') & (self.lbox.curselection()[0] == 3): PolyFlux = fitg1(Poly, x, y3, weights=1.0 / y3) print(PolyFlux) plt.figure() plt.plot(x, y3, drawstyle='steps-post', label="Flux") plt.plot(x, PolyFlux(x), drawstyle='steps-pre', label='Polynomial') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1, ymin=0.0001) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Flux(Counts/s cm(-2) keV(-1))') plt.title('Flux Fitting using Polynomial Model') plt.legend(loc=2) plt.show() # If user select Flux in Plot Units and Exponential in Choose Fit Function Model: elif (self.var.get() == 'Flux') & (self.lbox.curselection()[0] == 4): expFlux = fitg1(exp, x, y3) print(expFlux) plt.figure() plt.plot(x, y3, drawstyle='steps-post', label="Flux") plt.plot(x, expFlux(x), drawstyle='steps-pre', label='Exponential') plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1, ymin=0.0001) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Flux(Counts/s cm(-2) keV(-1))') plt.title('Flux Fitting using Exponential Model') plt.legend(loc=2) plt.show() # If user select Flux in Plot Units and Exponential Power Law in Choose Fit Function Model: elif (self.var.get() == 'Flux') & (self.lbox.curselection()[0] == 5): ExpPLFlux = fitg1(exp_powerlaw, x, y3, weights=1.0 / y3) print(ExpPLFlux) plt.figure() plt.plot(x, y3, drawstyle='steps-post', label="Flux") plt.plot(x, ExpPLFlux(x), drawstyle='steps-post', color='red', label="ExpPowerLaw") plt.yscale('log') plt.xscale('log') plt.ylim(ymax=1, ymin=0.0001) #FIXME: find a solution for general case plt.xlabel('Energy(keV)') plt.ylabel('Flux(Counts/s cm(-2) keV(-1))') plt.legend(loc=2) plt.title('Flux Fitting using Exponential Power Law Model') plt.show()
import numpy as np from astropy.modeling import models, fitting import matplotlib.pyplot as plt ##################################Read light curve data######################## GRB = "190114" lc_file_name = "flux_" + "GRB " + GRB + ".txt" lc_file = np.loadtxt(lc_file_name) t_data = lc_file[:, 0] lc_data = lc_file[:, 3] lc_err = 2 * lc_file[:, 4] nu = 2.4e17 * np.logspace(-0.5, 1., 100) #########################Fitting############################################### # BrokenPL=models.BrokenPowerLaw1D(amplitude=1, x_break=1,alpha_1=1,alpha_2=1,bounds={"x_break": (t_data[0], t_data[-1])}) BrokenPL = models.BrokenPowerLaw1D(amplitude=1, x_break=1, alpha_1=1, alpha_2=1) # BrokenPL=models.BrokenPowerLaw1D() fit = fitting.LevMarLSQFitter() # fit= fitting.LinearLSQFitter() PL = fit(BrokenPL, t_data, lc_data) # PL.x_break.min=t_data[0] print(PL) t_plot = np.logspace(np.log10(t_data[0]), np.log10(t_data[-1]), 100) plt.figure(figsize=(8, 5)) plt.plot(t_data, lc_data, 'ko') plt.plot(t_plot, PL(t_plot), label='Fit') plt.xscale("log") plt.yscale("log") plt.legend()
#for i in range(6,26): #bins = np.linspace(-31.08, -27, i) #dens_bin, frac, el, eh = qFrac_w(np.log10(dens[m1]), ssfr[m1], vmax[m1], bins, 0.68) #pl_init = models.PowerLaw1D(10**0.45, 10**-29, -0.2) #pl_fit = fitting.LevMarLSQFitter() #pl = pl_fit(pl_init, 10**dens_bin, 10**frac) #pl2_init = models.BrokenPowerLaw1D(10**0.45, 10**-29, 0., -0.2) #pl2_fit = fitting.LevMarLSQFitter() #pl2 = pl2_fit(pl2_init, 10**dens_bin, 10**frac) #crit_dens[i-6] = pl2.x_break.value #ax1.plot(np.log10(xband), np.log10(pl2(xband)), color=purple, ls='-', lw=0.75, alpha=0.25) pl2_init = models.BrokenPowerLaw1D(10**0.45, 10**-29, 0., -0.2) pl2_fit = fitting.LevMarLSQFitter() pl2 = pl2_fit(pl2_init, 10**dens_q, 10**frac_q) my_cmap = LinearSegmentedColormap.from_list('my_cmap', ['#ffffff', '#5d478b'], N=250) RedBlue = LinearSegmentedColormap.from_list('RedBlue', [red, blue], N=250) def gauss_smear(x0, y0, err, dx, dy): x, y = np.meshgrid(np.linspace(x0 - dx / 2., x0 + dx / 2., 50), np.linspace(y0 - dy / 2., y0 + dy / 2., 100)) return x, y, np.exp(-(y0 - y)**2 / err**2)
def run_CARMA(time, y, ysig, maxp, nsamples, aic_file, carma_sample_file, psd_file, psd_plot, fit_quality_plot, pl_plot, do_mags=True): #to calculate the order p and q of the CARMA(p,q) process, then run CARMA for values of p and q already calculated #function to calculate the order p and q of the CARMA(p,q) process # maxp: Maximum value allowed for p, maximun value for q is by default p-1 time = time - time[0] model = cm.CarmaModel(time, y, ysig) MAP, pqlist, AIC_list = model.choose_order(maxp, njobs=1) # convert lists to a numpy arrays, easier to manipulate #the results of the AIC test are stored for future references. pqarray = np.array(pqlist) pmodels = pqarray[:, 0] qmodels = pqarray[:, 1] AICc = np.array(AIC_list) np.savetxt(aic_file, np.transpose([pmodels, qmodels, AICc]), header='p q AICc') p = model.p q = model.q #running the sampler carma_model = cm.CarmaModel(time, y, ysig, p=p, q=q) carma_sample = carma_model.run_mcmc(nsamples) carma_sample.add_mle(MAP) #getting the PSD ax = plt.subplot(111) print 'Getting bounds on PSD...' psd_low, psd_hi, psd_mid, frequencies = carma_sample.plot_power_spectrum( percentile=95.0, sp=ax, doShow=False, color='SkyBlue', nsamples=5000) psd_mle = cm.power_spectrum(frequencies, carma_sample.mle['sigma'], carma_sample.mle['ar_coefs'], ma_coefs=np.atleast_1d( carma_sample.mle['ma_coefs'])) #saving the psd np.savetxt(psd_file, np.transpose([frequencies, psd_low, psd_hi, psd_mid, psd_mle]), header='frequencies psd_low psd_hi psd_mid psd_mle') ax.loglog(frequencies, psd_mle, '--b', lw=2) dt = time[1:] - time[0:-1] noise_level = 2.0 * np.median(dt) * np.mean(ysig**2) mean_noise_level = noise_level median_noise_level = 2.0 * np.median(dt) * np.median(ysig**2) ax.loglog(frequencies, np.ones(frequencies.size) * noise_level, color='grey', lw=2) ax.loglog(frequencies, np.ones(frequencies.size) * median_noise_level, color='green', lw=2) ax.set_ylim(bottom=noise_level / 100.0) ax.annotate("Measurement Noise Level", (3.0 * ax.get_xlim()[0], noise_level / 2.5)) ax.set_xlabel('Frequency [1 / day]') if do_mags: ax.set_ylabel('Power Spectral Density [mag$^2$ day]') else: ax.set_ylabel('Power Spectral Density [flux$^2$ day]') #plt.title(title) plt.savefig(psd_plot) plt.close('all') print 'Assessing the fit quality...' fig = carma_sample.assess_fit(doShow=False) ax_again = fig.add_subplot(2, 2, 1) #ax_again.set_title(title) if do_mags: ylims = ax_again.get_ylim() ax_again.set_ylim(ylims[1], ylims[0]) ax_again.set_ylabel('magnitude') else: ax_again.set_ylabel('ln Flux') plt.savefig(fit_quality_plot) pfile = open(carma_sample_file, 'wb') cPickle.dump(carma_sample, pfile) pfile.close() params = { param: carma_sample.get_samples(param) for param in carma_sample.parameters } params['p'] = model.p params['q'] = model.q print "fitting bending power-law" nf = np.where(psd_mid >= median_noise_level) psdfreq = frequencies[nf] psd_low = psd_low[nf] psd_hi = psd_hi[nf] psd_mid = psd_mid[nf] A, v_bend, a_low, a_high, blpfit = fit_BendingPL(psdfreq, psd_mid) pl_init = models.BrokenPowerLaw1D(amplitude=2, x_break=0.002, alpha_1=1, alpha_2=2) fit = LevMarLSQFitter() pl = fit(pl_init, psdfreq, psd_mid) amplitude = pl.amplitude.value x_break = pl.x_break.value alpha_1 = pl.alpha_1.value alpha_2 = pl.alpha_2.value print amplitude, x_break, alpha_1, alpha_2 print "BendingPL fit parameters = ", A, v_bend, a_low, a_high print "BrokenPL fit parameters = ", amplitude, x_break, alpha_1, alpha_2 plt.clf() plt.subplot(111) plt.loglog(psdfreq, psd_mid, color='green') plt.fill_between(psdfreq, psd_low, psd_hi, facecolor='green', alpha=0.3) plt.plot(psdfreq, blpfit, 'r--', lw=2) plt.plot(psdfreq, pl(psdfreq), 'k--', lw=2) plt.savefig(pl_plot) plt.close('all') return (params, mean_noise_level, median_noise_level, A, v_bend, a_low, a_high, amplitude, x_break, alpha_1, alpha_2)