[8a5f021] | 1 | #!/usr/bin/env python |
---|
| 2 | """ |
---|
[93d0ea7] | 3 | Script to run a batch fit in a series of files and plot the fitted parameters. |
---|
| 4 | |
---|
[8a5f021] | 5 | Usage syntax:: |
---|
[93d0ea7] | 6 | |
---|
[8a5f021] | 7 | python batch_fit.py model.py sample1.dat sample2.dat ... other_sample.dat |
---|
[93d0ea7] | 8 | (files named sample1.dat, sample2.dat, ..., other_sample.dat) |
---|
| 9 | |
---|
[8a5f021] | 10 | or if the file names are numbers (and the extension is .dat):: |
---|
| 11 | |
---|
| 12 | python batch_fit.py model.py 93190 93210 |
---|
| 13 | (files named 093190.dat, 093191.dat, ..., 093210.dat) |
---|
| 14 | |
---|
| 15 | or for Grasp-like naming:: |
---|
| 16 | |
---|
| 17 | python batch_fit.py model.py 93190 93210 200 |
---|
| 18 | (files named 093190_200.dat, 093191_201.dat, ..., 093210_220.dat) |
---|
| 19 | |
---|
| 20 | The script reads a series of files and fits the model defined by model.py. |
---|
| 21 | For example model_ellipsoid_hayter_msa.py fits a model consisting in an |
---|
| 22 | ellipsoid form factor multiplied by a Hayter MSA structure factor. |
---|
| 23 | |
---|
| 24 | The file *model.py* must load the data using:: |
---|
| 25 | |
---|
| 26 | data = load_data(sys.argv[1]) |
---|
| 27 | |
---|
| 28 | Include options to bumps (minimizer, steps, etc.) as desired. For example:: |
---|
| 29 | |
---|
| 30 | python batch_fit.py model.py 93190 93210 200 --fit=lm --steps=200 --ftol=1.5e-8 --xtol=1.5e-8 |
---|
| 31 | |
---|
| 32 | Fit options can come before or after the model and files. |
---|
[93d0ea7] | 33 | |
---|
[8a5f021] | 34 | For each file a directory named Fit_filename is created. There the file |
---|
| 35 | model.par contains the fitted parameters. These are gathered together into |
---|
| 36 | batch_fit.csv in the current directory. |
---|
[93d0ea7] | 37 | |
---|
[8a5f021] | 38 | Finally the fitted parameters are plotted for the full series. |
---|
[93d0ea7] | 39 | |
---|
[8a5f021] | 40 | Example:: |
---|
| 41 | |
---|
| 42 | python batch_fit.py model_ellipsoid_hayter_msa.py 93191 93195 201 |
---|
| 43 | |
---|
| 44 | Note: |
---|
| 45 | |
---|
| 46 | If sasmodels, sasview or bumps are not in the path, use the PYTHONPATH |
---|
| 47 | environment variable to set them. |
---|
| 48 | """ |
---|
[93d0ea7] | 49 | from __future__ import print_function |
---|
[8a5f021] | 50 | |
---|
[93d0ea7] | 51 | import sys |
---|
| 52 | import os |
---|
[8a5f021] | 53 | |
---|
[93d0ea7] | 54 | import numpy as np |
---|
| 55 | import matplotlib.pyplot as plt |
---|
[8a5f021] | 56 | from bumps.dream.views import tile_axes # make a grid of plots |
---|
| 57 | |
---|
| 58 | # GET INPUT AND ENSURE MODEL AND DATA FILES ARE DEFINED |
---|
[93d0ea7] | 59 | |
---|
[8a5f021] | 60 | fit_opts = [v for v in sys.argv[1:] if v.startswith('--')] |
---|
| 61 | args = [v for v in sys.argv[1:] if not v.startswith('--')] |
---|
[93d0ea7] | 62 | |
---|
[8a5f021] | 63 | nargs = len(args) |
---|
| 64 | if nargs < 2: |
---|
[93d0ea7] | 65 | print ("Error in the list of arguments! \n") |
---|
| 66 | sys.exit() |
---|
| 67 | |
---|
[8a5f021] | 68 | model_file = args[0] |
---|
| 69 | if not model_file.endswith('.py'): |
---|
| 70 | print("Expected model.py as the first argument") |
---|
| 71 | sys.exit(1) |
---|
| 72 | |
---|
| 73 | if '.' in args[1]: |
---|
| 74 | data_files = args[1:] |
---|
| 75 | else: |
---|
| 76 | first = int(args[1]) |
---|
| 77 | last = int(args[2]) |
---|
| 78 | count = last-first+1 |
---|
| 79 | data_files = [] |
---|
[93d0ea7] | 80 | if nargs == 3: |
---|
[8a5f021] | 81 | data_files = ['%06d.dat'%(first+i) for i in range(count)] |
---|
| 82 | elif nargs == 4: |
---|
| 83 | ext = int(args[3]) |
---|
| 84 | data_files = ['%06d_%d.dat'%(first+i, ext+i) for i in range(count)] |
---|
[93d0ea7] | 85 | else: |
---|
[8a5f021] | 86 | print("Unexpected arguments: " + " ".join(args[4:])) |
---|
| 87 | sys.exit(1) |
---|
| 88 | |
---|
| 89 | # CHECK THAT DATA FILES EXIST |
---|
| 90 | missing = [filename for filename in data_files if not os.path.isfile(filename)] |
---|
| 91 | if missing: |
---|
| 92 | print("Missing data files: %s" % ", ".join(missing)) |
---|
| 93 | sys.exit(1) |
---|
| 94 | |
---|
| 95 | # STORE DIRECTORY FOR BUMPS FITS |
---|
| 96 | def fit_dir(filename): |
---|
| 97 | "Return the store directory name for the given file" |
---|
| 98 | return "Fit_" + os.path.splitext(filename)[0] |
---|
| 99 | |
---|
| 100 | # LOOP OVER FILES AND CALL TO BUMPS FOR EACH OF THEM |
---|
| 101 | bumps_cmd = "python -m bumps.cli --batch" |
---|
| 102 | fit_opts = " ".join(fit_opts) |
---|
| 103 | for data_file in data_files: |
---|
| 104 | store_opts = "--store=" + fit_dir(data_file) |
---|
| 105 | cmd = " ".join((bumps_cmd, fit_opts, store_opts, model_file, data_file)) |
---|
| 106 | os.system(cmd) |
---|
| 107 | |
---|
| 108 | # GATHER RESULTS |
---|
| 109 | results = {} |
---|
| 110 | par_file = os.path.splitext(model_file)[0] + '.par' |
---|
| 111 | for data_file in data_files: |
---|
| 112 | with open(os.path.join(fit_dir(data_file), par_file), 'r') as fid: |
---|
| 113 | for line in fid: |
---|
| 114 | parameter, value = line.split() |
---|
| 115 | results.setdefault(parameter, []).append(float(value)) |
---|
| 116 | |
---|
| 117 | # SAVE RESULTS INTO FILE |
---|
| 118 | with open('batch_fit.csv', 'w') as fid: |
---|
| 119 | parameters = list(sorted(results.keys())) |
---|
| 120 | values_by_file = zip(*(v for k, v in sorted(results.items()))) |
---|
| 121 | fid.write(','.join(['filename'] + parameters) + '\n') |
---|
| 122 | for filename, values in zip(data_files, values_by_file): |
---|
| 123 | fid.write(','.join([filename] + [str(v) for v in values]) + '\n') |
---|
| 124 | |
---|
| 125 | # SHOW FITTED PARAMETERS |
---|
| 126 | nh, nw = tile_axes(len(results)) |
---|
| 127 | ticks = np.arange(1, len(data_files)+1) |
---|
| 128 | labels = [os.path.splitext(filename)[0] for filename in data_files] |
---|
| 129 | for k, (parameter, values) in enumerate(sorted(results.items())): |
---|
| 130 | plt.subplot(nh, nw, k+1) |
---|
| 131 | plt.plot(ticks, values) |
---|
| 132 | plt.xlim(ticks[0]-0.5, ticks[-1]+0.5) |
---|
| 133 | if k%nh == nh-1: |
---|
| 134 | #plt.xlabel('Dataset #') |
---|
| 135 | plt.xticks(ticks, labels, rotation=30) |
---|
| 136 | else: |
---|
| 137 | plt.xticks(ticks, [' ']*len(labels)) |
---|
| 138 | plt.ylabel(parameter) |
---|
| 139 | plt.suptitle("Fit " + args[0]) |
---|
| 140 | plt.show() |
---|