source: sasmodels/example/batch_fit.py @ 93d0ea7

core_shell_microgelscostrafo411magnetic_modelticket-1257-vesicle-productticket_1156ticket_1265_superballticket_822_more_unit_tests
Last change on this file since 93d0ea7 was 93d0ea7, checked in by Gonzalez, Miguel <gonzalez@…>, 7 years ago

Example and data files to run a batch fit from command line

  • Property mode set to 100644
File size: 3.6 KB
Line 
1'''
2Script to run a batch fit in a series of files and plot the fitted parameters.
3
4Usage syntax:
5
6    python batch_fit.py model.py "sample1.dat, sample2.dat, ..., other_sample.dat"
7    (files named sample1.dat, sample2.dat, ..., other_sample.dat)
8   
9    or if the file names are numbers (and the extension is .dat):
10
11                python batch_fit.py model.py 93190 93210
12                (files named 093190.dat, 093191.dat, ..., 093210.dat)
13   
14    or for Grasp-like naming:
15   
16                python batch_fit.py model.py 93190 93210 200
17                (files named 093190_200.dat, 093191_201.dat, ..., 093210_202.dat)
18   
19    The script reads a series of files and fits the model defined by model.py.
20    E.g. python batch_fit.py  model_ellipsoid_hayter_msa.py fits a model
21    consisting in an ellipsoid form factor multiplied by a Hayter MSA structure factor. 
22   
23    The file model.py must load the data using data = load_data('data.txt'), as the script
24    replaces 'data.txt' by the files given here.
25   
26    Modify the call to bumps and the options (minimizer, steps, etc.) as desired.
27   
28    For each file a directory named Fit_filename is created. There the file fit.par contains
29    the fitted parameters.
30   
31    Finally the fitted parameters are shown for the full series.
32   
33Example:     
34
35    python batch_fit.py model_ellipsoid_hayter_msa.py 93191 93195 201
36   
37Note:
38
39    If sasmodels is not in the path, edit the line sys.path.append to provide the
40    right path to sasmodels.   
41
42'''
43
44from __future__ import print_function
45import sys
46import os
47import numpy as np
48import matplotlib.pyplot as plt
49
50''' GET INPUT AND ENSURE MODEL AND DATA FILES ARE DEFINED'''
51
52nargs = len(sys.argv) - 1
53if (nargs < 2) or (nargs > 4):
54    print ("Error in the list of arguments! \n")
55    sys.exit()
56
57modelName = sys.argv[1]
58f = open(modelName, 'r')
59fileModel = f.read()
60f.close()
61
62if nargs == 2:
63    dataFiles = sys.argv[2].split(',')
64else: 
65    numorFirst = int(sys.argv[2])
66    numorLast = int(sys.argv[3])
67    dataFiles = []
68    if nargs == 3:
69        for i in range(numorFirst, numorLast+1):
70            name = str(i).zfill(6) + '.dat'
71            dataFiles.append(name)
72    else:
73        numorExt = int(sys.argv[4])   
74        for i in range(numorFirst, numorLast+1):
75            name = str(i).zfill(6) + '_' + str(numorExt) + '.dat'
76            numorExt += 1
77            dataFiles.append(name)
78
79for file in dataFiles:
80    if not os.path.isfile(file.strip()):
81        print ("File %s does not exist! \n" % file.strip())
82        sys.exit()
83
84       
85''' CALL TO BUMPS AND DEFINITION OF FITTING OPTIONS '''
86
87msg0 = "python -m bumps.cli fit.py"
88options = " --fit=lm --steps=200 --ftol=1.5e-8 --xtol=1.5e-8 --batch"
89
90
91''' LOOP OVER FILES AND CALL TO BUMPS FOR EACH OF THEM'''   
92
93for file in dataFiles:
94    currentModel = fileModel.replace('data.txt', file.strip())
95    f = open('fit.py', 'w')
96    f.write(currentModel)
97    f.close()
98    store = " --store=Fit_" + file.strip()
99    msg = msg0 + options + store
100    os.system(msg)
101
102
103''' SHOW FITTED PARAMETERS '''   
104
105parDict = {}
106for file in dataFiles:
107    parFile = os.path.join('Fit_' + file.strip(), 'fit.par')
108    f = open(parFile, 'r')
109    lines = f.readlines()
110    for line in lines:
111        parName = line.split()[0]
112        if parName in parDict.keys():
113            parList = parDict[parName]
114            parList.append(line.split()[1])
115            parDict[parName] = parList
116        else:
117            parDict[parName] = [line.split()[1]]
118   
119for parName in parDict.keys():
120    values = np.array(map(float, parDict[parName]))   
121    plt.plot(values)
122    plt.title(parName)
123    plt.xlabel('Dataset #')
124    plt.ylabel('Value')
125    plt.show()
126
Note: See TracBrowser for help on using the repository browser.