diff --git a/Franck_Hertz_Versuch/params/FrankcHertzKurve.csv~ b/Franck_Hertz_Versuch/params/FrankcHertzKurve.csv~ deleted file mode 100644 index f0ddb6ef6c28b16c9cc787e913b23cbf4f46350d..0000000000000000000000000000000000000000 --- a/Franck_Hertz_Versuch/params/FrankcHertzKurve.csv~ +++ /dev/null @@ -1,52 +0,0 @@ -UB,IA -0,02, 0,04 -1,00, 0,05 -1,99, 0,05 -2,98, 0,30 -4,01, 1,13 -4,61, 2,08 -5,01, 2,95 -5,47, 4,15 -5,89, 5,36 -6,21, 6,31 -6,62, 7,16 -7,07, 7,18 -7,49, 6,38 -7,86, 5,17 -8,22, 3,77 -8,50, 2,65 -8,70, 1,99 -9,03, 1,69 -9,47, 2,35 -9,80, 3,42 -10,05, 4,58 -10,30, 5,87 -10,48, 7,00 -10,67, 8,11 -10,85, 9,29 -11,07, 10,47 -11,30, 11,72 -11,60, 12,74 -11,88, 13,20 -12,23, 12,52 -12,45, 11,56 -12,64, 10,54 -12,80, 9,68 -13,00, 8,66 -13,19, 7,48 -13,46, 6,11 -13,78, 5,01 -14,23, 5,41 -14,52, 6,43 -14,86, 7,94 -15,17, 9,49 -15,46, 10,97 -15,75, 12,42 -16,08, 13,90 -16,38, 15,11 -16,71, 15,95 -17,07, 15,59 -17,34, 14,69 -17,56, 13,67 -17,76, 12,68 - diff --git a/Franck_Hertz_Versuch/tools/csv2yml.py b/Franck_Hertz_Versuch/tools/csv2yml.py deleted file mode 100755 index 8beca8301df8f711bbbbde4006aebef2e75efe3b..0000000000000000000000000000000000000000 --- a/Franck_Hertz_Versuch/tools/csv2yml.py +++ /dev/null @@ -1,95 +0,0 @@ -#!/usr/bin/env python3 -"""csv2yml.py - read floating-point column-data in very general .txt formats - and write an output block in yaml format - - keys taken from 1st header line - - Usage: - - ./cvs2yml [options] <input file name> - - Input: - - - file name - - Output: - - - yaml data block - - -.. moduleauthor:: Guenter Quast <g.quast@kit.edu> - -""" - -if __name__ == "__main__": # ------------------------------------------- - - import sys, os, yaml, argparse - from PhyPraKit import csv2yaml - if os.name == 'nt': # interactive mode on windows if error occurs - os.environ['PYTHONINSPECT']='x' - - # - - - Parse command-line arguments - # parser = argparse.ArgumentParser(usage=__doc__) - parser = argparse.ArgumentParser( - description="convert csv to yaml format") - - parser.add_argument('filename', type=str, - help="name of input file in csv format") - parser.add_argument('-s', '--save', - action='store_const', const=True, default=False, - help="save result in file") - parser.add_argument('-H', '--Header', - action='store_const', const=True, default=False, - help="print csv Header lines") - parser.add_argument('-q', '--quiet', - action='store_const', const=True, default=False, - help="quiet - no output to screen") - parser.add_argument('-d','--delimiter', - type=str, default=',', - help="delimiter, default=','") - parser.add_argument('-n','--header_lines', - type=int, default=1, - help="numer of header lines, default=1") - - if len(sys.argv)==1: # print help message if no input given - parser.print_help() - raise ValueError('!!! not input given -exit !') - - # collect input from ArgumentParser - args = parser.parse_args() - fnam = args.filename - - nlhead = args.header_lines - delim = args.delimiter - showHeader = args.Header - sav_flg = args.save - quiet = args.quiet - if quiet: sav_flg = True - - # ---- end argument parsing ------------------- - - f = open(fnam, 'r') - hlines, ylines = csv2yaml(f, nlhead, delim) - - if not quiet: - print('-->', fnam, 'to yaml', end='') - - if showHeader: - print(' csv header:') - for l in hlines: - print(l) - - # print results to screen - if not quiet: - print(' yaml block:') - for l in ylines: - print(l) - - # write to file - if sav_flg: - ymlfn = fnam.split('.')[0] + '.yaml' - with open(ymlfn, 'w') as f: - for l in ylines: - print(l, file=f) - print(' -> yaml saved in file',ymlfn) diff --git a/Franck_Hertz_Versuch/tools/plotCSV.py b/Franck_Hertz_Versuch/tools/plotCSV.py deleted file mode 100755 index 7739f8212d7bb91d0bd3b296aea0f7b1c99f0c78..0000000000000000000000000000000000000000 --- a/Franck_Hertz_Versuch/tools/plotCSV.py +++ /dev/null @@ -1,100 +0,0 @@ -#!/usr/bin/python3 - -"""plotCSV.py - uses PhyPraKkt.readtxt() to read floating-point column-data in csv format - - - usage: - - ./plotCSV.py [options] <input file name> - - Input: - - - input file in csv format - - Options: - - - s : character used as field separator, default ',' - - H : number of header lines, default 1 - - Output: - - - figure - - - -""" - -from PhyPraKit import readtxt - -# --- helper function -def wexit(code): - # keep Python window open on MS Windows - import os, sys - if os.name == 'nt': - _ = input('\n ==> type <ret> to end > ') - sys.exit(code) - -if __name__ == "__main__": - import sys, argparse, numpy as np, matplotlib.pyplot as plt - - # - - - Parse command-line arguments - parser = argparse.ArgumentParser(description = \ - "plot contents of CSV file") - - parser.add_argument('filename', type=str, nargs='+', - help="name of csv file") - parser.add_argument('-v', '--verbose', - action='store_const', const=True, default=False, - help="full printout to screen") - parser.add_argument('-s', '--separator', - type=str, default=',', - help="character used as field separator ") - parser.add_argument('-H', '--Headerlines', - type=int, default = 1, - help="number of header lines") - - if len(sys.argv)==1: # print help message if no input given - parser.print_help() - print(" \n !!! no input file given - exiting \n") - wexit(1) - - # collect input from ArgumentParser - args = parser.parse_args() - fname = args.filename[0] - quiet_flg = not args.verbose - separator = args.separator # field separator: , or \t, or \_ or ; etc. - nHlines = args.Headerlines # number of header lines - # print(args) - - # end parsing input ------------------------------------------ - - # read data from file in .txt format - hlines, data = readtxt(fname, delim=separator, nlhead=nHlines) - nColumns = data.shape[0] - nRows = data.shape[1] - keys = hlines[0].split(separator)[:] - # output to terminal - print(hlines) - print(" --> number of columns", nColumns) - print(" --> number of data points", nRows) - -# make plots - columns 1, 2, 3, ... vs. column 0 - fig=plt.figure(1, figsize=(10, 2.25*nColumns)) - fig.tight_layout() - fig.suptitle('contents of file '+fname, size='x-large', color='b') - fig.subplots_adjust(left=0.14, bottom=0.1, right=0.97, top=0.93, - wspace=None, hspace=.33)# - x = data[0] - axes = [] - ncol = nColumns - 1 - for i in range(1, ncol+1): - axes.append(fig.add_subplot(ncol, 1, i)) - ax = axes[i-1] - ax.plot(x, data[i], alpha=0.3, label='Column' + str(i)) - ax.set_ylabel(keys[i], size='large') - ax.set_xlabel(keys[0], size='large') - ax.legend(loc='best', numpoints=1, prop={'size':10}) - ax.grid() - - plt.show() diff --git a/Franck_Hertz_Versuch/tools/plotData.py b/Franck_Hertz_Versuch/tools/plotData.py deleted file mode 100755 index 009b9ddf09743389e68b0e77a88460219b02cce4..0000000000000000000000000000000000000000 --- a/Franck_Hertz_Versuch/tools/plotData.py +++ /dev/null @@ -1,171 +0,0 @@ -#!/usr/bin/env python3 -"""**plotData.py** [options] <input file name> - - Plot (several) data set(s) with error bars in x- and y- directions - or histograms from file in yaml format - - usage: - - ./plotData.py [options] <input file name> - - Input: - - - input file in yaml format - - Output: - - - figure - - yaml-format for (x-y) data: - - .. code-block:: yaml - - title: <title of plot> - x_label: <label for x-axis> - y_label: <label for y-axis> - - label: <name of data set> - x_data: [ x values ] - y_data: [ y values ] - x_errors: x-uncertainty or [x-uncertainties] - y_errors: y-uncertainty or [y-uncertainties] - - *Remark*: more than one input data sets are also possible. - Data sets and models can be overlayed in one plot if option - `showplots = False` ist specified. Either provide more than - one input file, or use yaml syntax, as shown here: - - .. code-block:: yaml - - # several input sets to be separated by - ... - --- - - yaml-format for histogram: - - .. code-block:: yaml - - title: <title of plot> - x_label: <label for x-axis> - y_label: <label for y-axis> - - label: <name of data set> - raw_data: [x1, ... , xn] - # define binning - n_bins: n - bin_range: [x_min, x_max] - # alternatively: - # bin edges: [e0, ..., en] - - several input sets to be separated by - ... - --- - - In case a model function is supplied, it is overlayed in the - output graph. The corresponding *yaml* block looks as follows: - - .. code-block:: yaml - - # optional model specification - model_label: <model name> - model_function: | - <Python code of model function> - - If no `y_data` or `raw_data` keys are provided, only the model function - is shown. Note that minimalistic `x_data` and `bin_range` or `bin_edges` - information must be given to define the x-range of the graph. - -""" - -from PhyPraKit import plot_xy_from_yaml,plot_hist_from_yaml - -# --- helper function -def wexit(code): - # keep Python window open on MS Windows - import os, sys - if os.name == 'nt': - _ = input('\n ==> type <ret> to end > ') - sys.exit(code) - -if __name__ == "__main__": # -------------------------------------- - - import os, sys, yaml, argparse, matplotlib.pyplot as plt - if os.name == 'nt': # interactive mode on windows if error occurs - os.environ['PYTHONINSPECT']='x' - - # - - - Parse command-line arguments - parser = argparse.ArgumentParser(description = \ - "Plot data with error bars or a histrogram from file in yaml format") - # parser = argparse.ArgumentParser(usage=__doc__) - - parser.add_argument('filename', type=str, nargs='+', - help="name(s) of input file(s) in yaml format") - parser.add_argument('-s', '--saveplot', - action='store_const', const=True, default=False, - help="save plot(s) in file(s)") - parser.add_argument('-f','--format', - type=str, default='pdf', - help="graphics output format, default=pdf") - parser.add_argument('-n', '--noplot', - action='store_const', const=True, default=False, - help="suppress ouput of plots on screen") - - if len(sys.argv)==1: # print help message if no input given - parser.print_help() - print(" \n !!! no input file given - exiting \n") - wexit(1) - - # collect input from ArgumentParser - args = parser.parse_args() - fnames = args.filename - sav_flg = args.saveplot - pltfmt = args.format - plt_flg = not args.noplot - - ddata = [] - for fnam in fnames: - f = open(fnam,'r') - try: - ymldata = yaml.load_all(f, Loader=yaml.Loader) - except (OSError, yaml.YAMLError) as exception: - print('!!! failed to read configuration file ' + fnam) - print(str(exception)) - wexit(1) - - data_type = 'xy' - for d in ymldata: - if 'type' in d: - data_type = d['type'] - ddata.append(d) - - # create a figure - if data_type == 'xy': - fignam = 'plotxyData' - elif data_type == 'histogram': - fignam = 'plothistData' - else: - print('!!! invalid data type', data_type) - wexit(1) - - # create figure - figsize = (7.5, 6.5) - figure = plt.figure(num=fignam, figsize=figsize) - - # decode yaml input and plot data for each yaml file - for d in ddata: - if data_type == 'xy': - plot_xy_from_yaml(d) - elif data_type == 'histogram': - plot_hist_from_yaml(d) - f.close() - - # output to file or screen - if (sav_flg): - oname = fnames[0].split('.')[0] + '.'+pltfmt - plt.savefig( oname ) - print(' -> graph saved to file ', oname) - # show plot on screen - if plt_flg: - plt.show() - - wexit(0) diff --git a/Franck_Hertz_Versuch/tools/run_phyFit.py b/Franck_Hertz_Versuch/tools/run_phyFit.py deleted file mode 100755 index b3898cd957743e65b42736985da84e0deb1b68ce..0000000000000000000000000000000000000000 --- a/Franck_Hertz_Versuch/tools/run_phyFit.py +++ /dev/null @@ -1,277 +0,0 @@ -#!/usr/bin/env python3 -"""**run_phyFit.py** [options] <input file name> - - Perform fit with data and model from yaml file - - Uses functions xyFit and hFit from PhyPraKit.phyFit - - This code performs fits - - - to x-y data with independent and correlated, absolute - and relative uncertainties in the x and y directions - - - and to histogram data with a binned likelihood fit. - - usage: - - ./run_phyFit.py [options] <input file name> - - ./run_phyFit.py --help for help - - - Input: - - - input file in yaml format - - output: - - - text and/or file, graph depending on options - - - **yaml format for x-y fit:** - - .. code-block:: yaml - - label: <str data-set name> - - x_label: <str name x-data> - x_data: [ list of float ] - - y_label: <str name y-data> - y_data: [ list of float ] - - x_errors: <float>, [list of floats], or {dictionary/ies} - y_errors: <float>, [list of floats], or {dictionary/ies} - - # optionally, add Gaussian constraints on parameters - parameter_constraints: - <parameter name>: - value: <value> - uncertaintiy: <value> - - model_label: <str model name> - model_function: | - <Python code> - - format of uncertainty dictionary: - - error_value: <float> or [list of floats] - - correlation_coefficient: 0. or 1. - - relative: true or false - relative errors may be spcified as <float>% - - - Simple example of *yaml* input: - - .. code-block:: yaml - - label: 'Test Data' - - x_data: [.05,0.36,0.68,0.80,1.09,1.46,1.71,1.83,2.44,2.09,3.72,4.36,4.60] - x_errors: 3% - x_label: 'x values' - - y_data: [0.35,0.26,0.52,0.44,0.48,0.55,0.66,0.48,0.75,0.70,0.75,0.80,0.90] - y_errors: [.06,.07,.05,.05,.07,.07,.09,.1,.11,.1,.11,.12,.1] - y_label: 'y values' - - model_label: 'Parabolic Fit' - model_function: | - def quadratic_model(x, a=0., b=1., c=0. ): - return a * x*x + b*x + c - - - **Example of yaml input for histogram fit:** - - .. code-block:: yaml - - # Example of a fit to histogram data - type: histogram - - label: example data - x_label: 'h' - y_label: 'pdf(h)' - - # data: - raw_data: [ 79.83,79.63,79.68,79.82,80.81,79.97,79.68,80.32,79.69,79.18, - 80.04,79.80,79.98,80.15,79.77,80.30,80.18,80.25,79.88,80.02 ] - - n_bins: 15 - bin_range: [79., 81.] - # alternatively an array for the bin edges can be specified - #bin_edges: [79., 79.5, 80, 80.5, 81.] - - model_density_function: | - def normal_distribution(x, mu=80., sigma=1.): - return np.exp(-0.5*((x - mu)/sigma)** 2)/np.sqrt(2.*np.pi*sigma** 2) - - - *Remark*: more than one input data sets are also possible. - Data sets and models can be overlayed in one plot if option - `showplots = False` ist specified. Either provide more than - one input file, or use yaml syntax, as shown here: - - .. code-block:: yaml - - # several input sets to be separated by - ... - --- -""" - -from PhyPraKit.phyFit import xyFit_from_yaml, hFit_from_yaml -from pprint import pprint - -# --- helper function -def wexit(code): - # keep Python window open on MS Windows - import os, sys - if os.name == 'nt': - _ = input('\n ==> type <ret> to end > ') - sys.exit(code) - -if __name__ == "__main__": # -------------------------------------- - # - # xyFit.py: Example of an application of PhyPraKit.phyFit.xyFit_from_yaml() - # - - # package imports - import os, sys, argparse, yaml, numpy as np, matplotlib.pyplot as plt - if os.name == 'nt': # interactive mode on windows if error occurs - os.environ['PYTHONINSPECT']='x' - - # - - - Parse command-line arguments - parser = argparse.ArgumentParser(description = \ - "Perform a fit with PhyPraKit.phyFit package driven by input file") - # parser = argparse.ArgumentParser(usage=__doc__) - - parser.add_argument('filename', type=str, nargs='+', - help="name(s) of fit input file(s) in yaml format") - parser.add_argument('-v', '--verbose', - action='store_const', const=True, default=False, - help="full printout to screen") - parser.add_argument('-r', '--result_to_file', - action='store_const', const=True, default=False, - help="store results to file") - parser.add_argument('-n', '--noplot', - action='store_const', const=True, default=False, - help="suppress ouput of plots on screen") - parser.add_argument('-s', '--saveplot', - action='store_const', const=True, default=False, - help="save plot(s) in file(s)") - parser.add_argument('-c', '--contour', - action='store_const', const=True, default=False, - help="plot contours and profiles") - parser.add_argument('--noband', - action='store_const', const=True, default=False, - help="suppress 1-sigma band around function") - parser.add_argument('-f','--format', - type=str, default='pdf', - help="graphics output format, default=pdf") - - if len(sys.argv)==1: # print help message if no input given - parser.print_help() - print(" \n !!! no input file given - exiting \n") - wexit(1) - - # collect input from ArgumentParser - args = parser.parse_args() - fnames=args.filename - quiet_flg = not args.verbose - store_result = args.result_to_file - plt_flg= not args.noplot - sav_flg=args.saveplot - cont_flg=args.contour - band_flg=not args.noband - pltfmt=args.format - - # - - - End: Parse command-line arguments - - ddata = [] - # open and read input yaml file - for fnam in fnames: - f = open(fnam, 'r') - try: - ymldata = yaml.load_all(f, Loader=yaml.Loader) - except (OSError, yaml.YAMLError) as exception: - print('!!! failed to read configuration file ' + fnam) - print(str(exception)) - wexit(1) - - fitType = 'xy' - for d in ymldata: - if 'type' in d: - fitType = d['type'] - ddata.append(d) - f.close() - - # select appropriate wrapper - if fitType == 'xy': - fit = xyFit_from_yaml - elif fitType == 'histogram': - fit = hFit_from_yaml - else: - print('!!! unsupported type of fit:', fitType) - wexit(1) - - 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= 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) - - if store_result: - outfile = (fnames[0].split('.')[0]+ '.result') - with open(outfile, 'a') as outf: - for key in rdict: - print("{}\n".format(key), rdict[key], file=outf) - print(' -> result saved to file ', outfile) - - if (sav_flg): - # save all figures to file(s) - n_fig = 0 - tag = '' - for n in plt.get_fignums(): - plt.figure(n) - oname = (fnames[0].split('.')[0] + '%s.' + pltfmt) %(tag) - plt.savefig( oname) - print(' -> figure saved to file ', oname) - n_fig += 1 - tag = '_'+str(n_fig) - else: - # show on screen - plt.show() - - wexit(0)