Skip to content

Commit

Permalink
renamed fit_from_file -> fit_from_yaml; multiple fits in same plot
Browse files Browse the repository at this point in the history
  • Loading branch information
GuenterQuast committed Jun 28, 2022
1 parent 1fc0c80 commit 9554c60
Show file tree
Hide file tree
Showing 2 changed files with 68 additions and 63 deletions.
21 changes: 12 additions & 9 deletions PhyPraKit/phyFit.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@
It is also possible to run a fit without the need to provide own
Python code. In this case, the data, uncertainties and the model
are read from a file in yaml format and passed to the function
xyFit_from_file() as a dictionary.
xyFit_from_yaml() as a dictionary.
The implementation of the fitting procedure in this package is
- intentionally - rather minimalistic, and it is meant to
Expand Down Expand Up @@ -241,7 +241,7 @@ def xyFit(fitf, x, y, sx = None, sy = None,
# parameter names
return Fit.getResult()

def xyFit_from_file(fd, # dictionary definig fit input
def xyFit_from_yaml(fd, # dictionary definig fit input
plot=True, # plot data and model
plot_band=True, # plot model confidence-band
plot_cor=False, # plot profiles likelihood and contours
Expand Down Expand Up @@ -443,7 +443,7 @@ def decode_rel(e):

# - data
data_x = list(map(float, fd['x_data']))
data_y = list(mape(float, fd['y_data']))
data_y = list(map(float, fd['y_data']))
if 'x_label' in fd:
x_label = fd['x_label']
else:
Expand Down Expand Up @@ -491,7 +491,7 @@ def decode_rel(e):

# print input and model
if not quiet:
print('\n*==* xyFit_from_file:')
print('\n*==* xyFit_from_yaml:')
print('-- input data:')
print('x-data:', data_x)
print('+/- abs', sx)
Expand Down Expand Up @@ -774,7 +774,7 @@ def hFit(fitf, bin_contents, bin_edges, DeltaMu=None,
# parameter names
return Fit.getResult()

def hFit_from_file(fd, # dictionary defining fit input
def hFit_from_yaml(fd, # dictionary defining fit input
plot=True, # plot data and model
plot_band=True, # plot model confidence-band
plot_cor=False, # plot profiles likelihood and contours
Expand Down Expand Up @@ -3459,8 +3459,8 @@ def plotModel(self,
alpha=0.7, elinewidth=2.5, color='darkorange')
else:
plt.plot(xplt, yplt*sfac, label=model_legend,
linestyle='dashed', linewidth=2.5,
alpha=0.7, color='darkorange')
linestyle='dashed', linewidth=2.5, alpha = 0.7)
## color='darkorange')
plt.xlabel(axis_labels[0], size='x-large')
plt.ylabel(axis_labels[1], size='x-large')
plt.grid()
Expand Down Expand Up @@ -3489,8 +3489,11 @@ def plotModel(self,
xmax=(xplt[i]+0.4)/len(xplt),
alpha=0.3, color='darkkhaki', label=lbl)

# display legend with some fit info
fit_info = []
# display legend with fit info
global fit_info
try: fit_info
except NameError: fit_info = []

# 1. parameter values and uncertainties
pe = 2 # number of significant digits of uncertainty
if self.minosResult is not None and self.minos_ok:
Expand Down
110 changes: 56 additions & 54 deletions tools/run_phyFit.py
Original file line number Diff line number Diff line change
Expand Up @@ -26,12 +26,12 @@
"""

from PhyPraKit.phyFit import xyFit_from_file, hFit_from_file
from PhyPraKit.phyFit import xyFit_from_yaml, hFit_from_yaml
from pprint import pprint

if __name__ == "__main__": # --------------------------------------
#
# xyFit.py: Example of an application of PhyPraKit.phyFit.xyFit_from_file()
# xyFit.py: Example of an application of PhyPraKit.phyFit.xyFit_from_yaml()
#

# package imports
Expand Down Expand Up @@ -80,76 +80,80 @@
cont_flg=args.contour
band_flg=not args.noband
pltfmt=args.format
if sav_flg:
show = False
else:
show = True

# - - - End: Parse command-line arguments

# open and read input yaml file
# open and read input yaml file
f = open(fname, 'r')
try:
with open(fname) as f:
fd = yaml.load(f, Loader=yaml.Loader)
ymldata = yaml.load_all(f, Loader=yaml.Loader)
except (OSError, yaml.YAMLError) as exception:
print('!!! failed to read configuration file ' + fname)
print(str(exception))
sys.exit(1)

# another check
if len(fd.keys()) == 0:
print("!!! data file is empty!")
sys.exit(1)

fitType = 'xy'
if 'type' in fd.keys():
fitType = fd['type']
print("*==*", sys.argv[0], "received valid yaml data for fit:")
if 'parametric_model' in fd: # for complex kafe2go format
pprint(fd, compact=True)
else: # "nice" printout for simple xyFit format
print(' ** Type of Fit:', fitType)
for key in fd:
if type(fd[key]) is not type([]): # got a scalar or string
print(key + ': ', fd[key])
elif type(fd[key][0]) is not type({}): # got list of scalars
print(key + ': ', fd[key])
else: # got list of uncertainty dictionaries
print(key+':')
for d in fd[key]:
for k in d:
print(' '+ k +': ', d[k], end=' ')
print()

# select appropriate wrapper
ddata = []
for d in ymldata:
if 'type' in d:
fit_type = d['type']
ddata.append(d)
f.close()

# select appropriate wrapper
if fitType == 'xy':
fit = xyFit_from_file
fit = xyFit_from_yaml
elif fitType == 'histogram':
fit = hFit_from_file
fit = hFit_from_yaml
else:
print('!!! unsupported type of fit:', fitType)
sys.exit(1)

# run fit
rdict = fit(fd, # the input dictionary defining the fit
for fd in ddata:
if 'type' in fd.keys():
fitType = fd['type']
print("*==*", sys.argv[0], "received valid yaml data for fit:")
if 'parametric_model' in fd: # for complex kafe2go format
pprint(fd, compact=True)
else: # "nice" printout for simple xyFit format
print(' ** Type of Fit:', fitType)
for key in fd:
if type(fd[key]) is not type([]): # got a scalar or string
print(key + ': ', fd[key])
elif type(fd[key][0]) is not type({}): # got list of scalars
print(key + ': ', fd[key])
else: # got list of uncertainty dictionaries
print(key+':')
for d in fd[key]:
for k in d:
print(' '+ k +': ', d[k], end=' ')
print()
# run fit
rdict = fit(fd, # the input dictionary defining the fit
plot=plt_flg, # show plot of data and model
plot_band=band_flg, # plot model confidence-band
plot_cor=cont_flg, # plot profiles likelihood and contours
showplots= show, # show plots on screen
showplots= False, # show plots on screen
quiet=quiet_flg, # suppress informative printout
return_fitObject=False
)

# print results to illustrate how to use output
print('\n*==* Fit Result:')
pvals, perrs, cor, chi2, pnams= rdict.values()
print(" chi2: {:.3g}".format(chi2))
print(" parameter names: ", pnams)
print(" parameter values: ", pvals)
np.set_printoptions(precision=3)
print(" neg. parameter errors: ", perrs[:,0])
print(" pos. parameter errors: ", perrs[:,1])
print(" correlation matrix : \n", cor)
# print results to illustrate how to use output
print('\n*==* Fit Result:')
pvals, perrs, cor, chi2, pnams= rdict.values()
print(" chi2: {:.3g}".format(chi2))
print(" parameter names: ", pnams)
print(" parameter values: ", pvals)
np.set_printoptions(precision=3)
print(" neg. parameter errors: ", perrs[:,0])
print(" pos. parameter errors: ", perrs[:,1])
print(" correlation matrix : \n", cor)

if store_result:
outfile = fname.split('.')[0]+'.result'
with open(outfile, 'a') as outf:
for key in rdict:
print("{}\n".format(key), rdict[key], file=outf)

if (sav_flg):
# save all figures to file(s)
Expand All @@ -160,9 +164,7 @@
plt.savefig( (fname.split('.')[0] + '%s.' + pltfmt) %(tag))
n_fig += 1
tag = '_'+str(n_fig)
else:
# show on screen
plt.show()

if store_result:
outfile = fname.split('.')[0]+'.result'
with open(outfile, 'w') as outf:
for key in rdict:
print("{}\n".format(key), rdict[key], file=outf)

0 comments on commit 9554c60

Please sign in to comment.