tsa_saxs/Minimization/Fit_CBX.py

92 lines
2.6 KiB
Python

#!/usr/bin/python
import sys
import os.path
import time
import numpy as np
import os
from cbx.dynamics import CBXDynamic, CBO
localtime = time.asctime( time.localtime(time.time()) )
print(localtime)
sys.path.append("/home/semeraro/Programming/PythonStuff/python_tools")
from Tools import Reading
from Tools import ReadData
from Tools import PlotData
import FitTools
import TSA_algorithm
############################################################
############################################################
############################################################
def X2function(Q,IDATA,I,ERR,N):
'X^2 calculation'
X2 = np.sum( ( ( IDATA-I ) / ERR )**2 )
return X2/(Q.shape[0]-(N-1))
############################################################
t0=time.time()
############################################################ Read Options & Parameters
############### Read File & Options
print("\n-- Reading File:")
read_par = Reading(sys.argv)
iters = int(sys.argv[2])
print("\n-- Reading Options")
options = read_par.Options()
############### Read Function, from the MODEL parameter
"-- Reading Function"
(function, pltOptions) = FitTools.ChooseFunction( options['function'] )
############### Read Parameters
print("\n-- Reading Parameters\n")
(NAME, PAR, FIX, PRIOR, L_LIM, H_LIM) = read_par.Parameters()
############################################################ Read & Select Data
(Q, IDATA ,ERR) = ReadData( options['datafile'] ).SelectColumns( options['qmin'],
options['qmax'],
options['bing'],
options['err_mul'] )
lo_bounds = np.array(L_LIM)
hi_bounds = np.array(H_LIM)
free_idx = np.array(FIX) == '-'
params = np.array(PAR)
N_free = sum(free_idx)
x_init = np.array(params[free_idx])
print("# params: " + str(len(params)))
print("# fixed : " + str(sum(~free_idx)))
print("# free : " + str(sum(free_idx)))
print("# len(x): " + str(len(x_init)))
def set_params_vector(x):
params[free_idx] = x
def check_bounds(x):
return (lo_bounds <= x).all() and (x <= hi_bounds).all()
def objective(x):
print(x)
set_params_vector(x)
if not check_bounds(params): return 1e10
I_pre = function(Q, params)
I = np.array(I_pre.intensity())
print(I.max())
return X2function(Q,IDATA,I,ERR,N_free)
dyn = CBXDynamic(objective, d = N_free)
dyn.optimize()
# cbo = CBO(objective, x=x_init)
# cbo = CBO(objective, x=x_init, d=N_free, sigma=0.1, dt=0.01)
# cbo.optimize()