This repository has been archived by the owner on Jan 13, 2020. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathprocedures.py
368 lines (280 loc) · 11.7 KB
/
procedures.py
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
from __future__ import print_function
import numpy as np
from lmfit import Parameters, minimize
import matplotlib.pyplot as plt
from optimization import *
from export import *
import time
import sys
# TODO: make up a custom print-function that duplicates string into standart output and file
def onegauss_fit(prm_name):
orig_stdout = sys.stdout
fout_name = 'tests/'+'pyXSW_' + str(int(time.time()))
fout = open(fout_name + '.log', mode='a') # log-file, unique for each trial
sys.stdout = fout
print('Output will be written to:\n', file=orig_stdout)
print(fout_name, file=orig_stdout)
initials = prm_name # reads all fitting parameters from .prm-file
num_params, str_params = get_initials(initials)
# multilayer structure parameters
table = str_params['table']
zmin = float(num_params['zmin'])
num_params.add('zmin', zmin, vary=False)
zmax = float(num_params['zmax'])
num_params.add('zmax', zmax, vary=False)
ml_period = num_params['ml_period']
# experimental data parameters
data = str_params['data']
template = str_params['template']
bragg = float(num_params['bragg'])
# print (params['normalize'])
# fitting parameters
normalize = str_params['normalize']
if normalize == 'true':
normalize = True
else:
normalize = False
scan_zmin_zmax = str_params['scan_zmin_zmax']
if scan_zmin_zmax.lower() == 'true':
scan_zmin_zmax = True
else:
scan_zmin_zmax = False
try:
window = num_params['window']
except KeyError:
window = 1
# fitting initial conditions
angle_slope = float(num_params['angle_slope'])
amplitude = float(num_params['amplitude'])
sigma = float(num_params['sigma'])
x0 = float(num_params['x0'])
print('pyXSW is running. '
'Initial numerical parameters are:\n')
print('pyXSW is running. '
'Initial numerical parameters are:\n', file=orig_stdout)
num_params.pretty_print()
sys.stdout = orig_stdout
num_params.pretty_print()
sys.stdout = fout
print('\nString parameters are:\n')
print('\nString parameters are:\n', file=orig_stdout)
for key in str_params:
print(key, str_params[key], sep='=\t')
print(key, str_params[key], sep='=\t', file=orig_stdout)
# TODO: organise this part depending on 'template' keyword
# theta, real_data = get_dat(data, normalize=normalize, bragg=bragg, template=template)
# errors = np.ones(len(theta))
theta, real_data, errors = get_dat(data, normalize=normalize, bragg=bragg, template=template)
real_data = smooth(real_data, window)
table_opt = get_grd(table)
# plt.errorbar(theta, real_data, yerr=errors, fmt='ok')
# plt.show()
# exit()
start = time.time()
print('\n\nOptimization is running...\n\n')
print('\n\nOptimization is running...\n\n', file=orig_stdout)
# The most important string -- fitting itself, all the rest is just fun
if scan_zmin_zmax:
x0s = initial_conditions_list(x0, zmin, zmax, ml_period)
for value in x0s:
i = int(value)
print("""
****************
Model # %d *****
****************
""" % i)
print("""
****************
Model # %d *****
****************
""" % i, file=orig_stdout)
num_params.add('x0', value)
out = minimize(residual_onegaussian, num_params, args=(table_opt, theta, real_data, errors))
Model = intensity_onegaussian(table_opt, theta,
out.params['amplitude'],
out.params['sigma'],
out.params['x0'],
out.params['zmax'],
out.params['angle_slope'],
out.params['bragg'],
out.params['zmin'],
)
rfactor = sum(abs(Model-real_data))/sum(real_data)
print('\n\n')
print('\n\n',file=orig_stdout)
print('\nFitted parameters are:\n')
print('\nFitted parameters are:\n', file=orig_stdout)
out.params.pretty_print()
sys.stdout = orig_stdout
out.params.pretty_print()
sys.stdout = fout
print('\n')
print('\n', file=orig_stdout)
chisquared = residual_onegaussian(out, table_opt, theta, real_data, errors)
print("\nChi-squared=%f" % chisquared)
print("\nChi-squared=%f" % chisquared, file=orig_stdout)
print("\nR-factor=%f" % rfactor)
print("\nR-factor=%f" % rfactor, file=orig_stdout)
image_filename = fout_name + '__' + str(i) + '.png'
plt.plot(theta, real_data, 'ok')
plt.plot(theta, Model, label='x0=%.2f, sg=%.2f'%(out.params['x0'].value, out.params['sigma'].value))
plt.legend()
plt.savefig(image_filename)
plt.clf()
print('\nImage is saved into: %s' % image_filename)
print('\nImage is saved into: %s' % image_filename, file=orig_stdout)
else:
out = minimize(residual_onegaussian, num_params, args=(table_opt, theta, real_data, errors))
Model = intensity_onegaussian(table_opt, theta,
out.params['amplitude'],
out.params['sigma'],
out.params['x0'],
out.params['zmax'],
out.params['angle_slope'],
out.params['zmin'],
)
rfactor = sum(abs(Model-real_data))/sum(real_data)
print('\n\n')
print('\n\n', file=orig_stdout)
print('\nFitted parameters are:\n')
print('\nFitted parameters are:\n', file=orig_stdout)
out.params.pretty_print()
sys.stdout = orig_stdout
out.params.pretty_print()
sys.stdout = fout
print('\n')
print('\n',file=orig_stdout)
chisquared = 1.0 / (len(theta) - 4) * sum((Model - real_data)**2 / errors**2)
print("\nChi-squared=%f" % chisquared)
print("\nChi-squared=%f" % chisquared, file=orig_stdout)
print("\nR-factor=%f"%rfactor)
print("\nR-factor=%f"%rfactor, file=orig_stdout)
image_filename = fout_name + '.png'
print('\nImage is saved into: %s' % image_filename)
print('\nImage is saved into: %s' % image_filename, file=orig_stdout)
plt.plot(theta, real_data, 'ok')
plt.plot(theta, Model, label='x0=%.2f, sg=%.2f'%(out.params['x0'].value, out.params['sigma'].value))
plt.legend()
plt.savefig(image_filename)
# plt.show()
print("Sigma_al \t sigma_ni")
print("Sigma_al \t sigma_ni", file=orig_stdout)
stop = time.time()
print('Total time consumed is %.1f sec\n\n' % (stop - start))
print('Total time consumed is %.1f sec\n\n' % (stop - start), file=orig_stdout)
sys.stdout = orig_stdout
fout.close()
return 0
def twogauss_fit(prm_name):
orig_stdout = sys.stdout
fout_name = 'tests/'+'pyXSW_' + str(int(time.time()))
fout = open(fout_name + '.log', mode='a') # log-file, unique for each trial
sys.stdout = fout
print('Output will be written to:\n', file=orig_stdout)
print(fout_name, file=orig_stdout)
initials = prm_name # reads all fitting parameters from .prm-file
num_params, str_params = get_initials(initials)
# multilayer structure parameters
table = str_params['table']
zmin = float(num_params['zmin'])
num_params.add('zmin', zmin, vary=False)
zmax = float(num_params['zmax'])
num_params.add('zmax', zmax, vary=False)
ml_period = num_params['ml_period']
# experimental data parameters
data = str_params['data']
template = str_params['template']
bragg = float(num_params['bragg'])
# print (params['normalize'])
# fitting parameters
normalize = str_params['normalize']
if normalize == 'true':
normalize = True
else:
normalize = False
scan_zmin_zmax = str_params['scan_zmin_zmax']
if scan_zmin_zmax.lower() == 'true':
scan_zmin_zmax = True
else:
scan_zmin_zmax = False
try:
window = num_params['window']
except KeyError:
window = 1
# fitting initial conditions
angle_slope = float(num_params['angle_slope'])
amplitude1 = float(num_params['amplitude1'])
sigma1 = float(num_params['sigma1'])
x01 = float(num_params['x01'])
amplitude2 = float(num_params['amplitude2'])
sigma2 = float(num_params['sigma2'])
x02 = float(num_params['x02'])
print('pyXSW is running. '
'Initial numerical parameters are:\n')
print('pyXSW is running. '
'Initial numerical parameters are:\n', file=orig_stdout)
num_params.pretty_print()
sys.stdout = orig_stdout
num_params.pretty_print()
sys.stdout = fout
print('\nString parameters are:\n')
print('\nString parameters are:\n', file=orig_stdout)
for key in str_params:
print(key, str_params[key], sep='=\t')
print(key, str_params[key], sep='=\t', file=orig_stdout)
# TODO: organise errors export
# theta, real_data = get_dat(data, normalize=normalize, bragg=bragg, template=template)
# errors = np.ones(len(theta))
theta, real_data, errors = get_dat(data, normalize=normalize, bragg=bragg, template=template)
real_data = smooth(real_data, window)
table_opt = get_grd(table)
# plt.errorbar(theta, real_data, yerr=errors, fmt='ok')
# plt.show()
# exit()
start = time.time()
print('\n\nOptimization is running...\n\n')
print('\n\nOptimization is running...\n\n', file=orig_stdout)
# The most important string -- fitting itself, all the rest is just fun
out = minimize(gaussian_residual_two, num_params, args=(table_opt, theta, real_data, errors))
Model = intensity_two(table_opt, theta,
out.params['amplitude1'],
out.params['amplitude2'],
out.params['sigma1'],
out.params['sigma2'],
out.params['x01'],
out.params['x02'],
out.params['angle_slope'],
out.params['zmin'],
out.params['zmax'])
rfactor = sum(abs(Model-real_data))/sum(real_data)
print('\n\n')
print('\n\n', file=orig_stdout)
print('\nFitted parameters are:\n')
print('\nFitted parameters are:\n', file=orig_stdout)
out.params.pretty_print()
sys.stdout = orig_stdout
out.params.pretty_print()
sys.stdout = fout
print('\n')
print('\n',file=orig_stdout)
chisquared = 1.0 / (len(theta) - 6) * sum((Model - real_data)**2 / errors**2)
print("\nChi-squared=%f" % chisquared)
print("\nChi-squared=%f" % chisquared, file=orig_stdout)
print("\nR-factor=%f"%rfactor)
print("\nR-factor=%f"%rfactor, file=orig_stdout)
image_filename = fout_name + '.png'
print('\nImage is saved into: %s' % image_filename)
print('\nImage is saved into: %s' % image_filename, file=orig_stdout)
plt.plot(theta, real_data, 'ok')
plt.plot(theta, Model, label='x01=%.2f, sg1=%.2f, x02=%.2f, sg2=%.2f' %
(out.params['x01'].value, out.params['sigma1'].value,
out.params['x02'].value, out.params['sigma2'].value))
plt.legend()
plt.savefig(image_filename)
# plt.show()
stop = time.time()
print('Total time consumed is %.1f sec\n\n' % (stop - start))
print('Total time consumed is %.1f sec\n\n' % (stop - start), file=orig_stdout)
sys.stdout = orig_stdout
fout.close()
return 0