Esempio n. 1
0
def main():
    with open('../Data/calibration.txt') as f:  #calibration readings file
        x0 = [
            0, 0, 0, 1, 1, 1, 0, 0, 0
        ]  #% Structure of vector: x0 = [ALFAxy, ALFAzx, ALFAzy, Sx, Sy, Sz, bx, by, bz]
        accelData = []
        for row in f:
            vector = row.split(',')
            vector[0] = float(vector[0])
            vector[1] = float(vector[1])
            vector[2] = float(vector[2])
            accelData.append(vector)
        x = opt((lambda x: minimize(x, accelData)), x0, method='BFGS').x

        N = [[1, 0, 0], [x[0], 1, 0], [x[1], x[2], 1]]

        S = [[x[3], 0, 0], [0, x[4], 0], [0, 0, x[5]]]

        b = [x[6], x[7], x[8]]

        print("\nN =\n" + str(np.array(N)))
        print("\nS =\n" + str(np.array(S)))
        print("\nb = " + str(np.array(b)))

        print("\nRMSE before calibration: " +
              '{:5f}'.format(rmse(accelData) * gval) + " m/s^2")
        print("RMSE after calibration: " +
              '{:5f}'.format(rmse(correction(accelData, N, S, b)) * gval) +
              " m/s^2")
Esempio n. 2
0
    def _optimization(self,
                      max_scf=100,
                      log=True,
                      scf=True,
                      readguess=None,
                      argnum=[0],
                      taskname='Output',
                      method='BFGS',
                      penalize=None,
                      **otherargs):
        print readguess
        print max_scf
        if self.verbose:
            t0 = time.clock()
            self._print_head_optimization(taskname, max_scf, readguess,
                                          **otherargs)

        name = taskname
        rguess = None

        ### If initial guess
        if readguess:
            pguess = name + '.npy'
            out = False
            ene = self._singlepoint(max_scf,
                                    max_d,
                                    printcoef=pguess,
                                    name=name,
                                    output=False)
            if ene == 99999:
                raise NameError('SCF did not converved')
            rguess = pguess

        pguess = None
        record = False

        args = self._energy_args(max_scf=max_scf,
                                 max_d=max_scf,
                                 log=log,
                                 printguess=pguess,
                                 readguess=rguess,
                                 name=name,
                                 write=record)
        ene_function = rhfenergy
        grad_fun = function_grads_algopy(
            ene_function,
            argnum)  ## This defines de gradient function of autograd
        opt = self.select_method.get(
            method, lambda: self._BFGS)  ## This selects the opt method

        res = opt(ene_function, grad_fun, args, argnum, log, name, **otherargs)

        if self.verbose:
            timer = time.clock() - t0
            self._print_tail_optimization(res, timer)

        self.status = bool(res.status == 0 or res.status == 1)
        self._optupdateparam(argnum, res.x)
        return res, timer
Esempio n. 3
0
def data_fit(spectre):

    mu1 = np.argmax(spectre[0:int(np.argmax(spectre) * 0.9)])
    mu2 = int(np.argmax(spectre) * 1.2) + np.argmax(
        spectre[int(np.argmax(spectre) * 1.1):len(spectre) - 1])

    if spectre[mu1] > spectre[mu2]:

        pars = [
            np.max(spectre) * 5., 1., 1.,
            np.argmax(spectre) * 1., 0.1, spectre[mu1] * 5., 1., 1., mu1 * 1.
        ]

    else:

        pars = [
            np.max(spectre) * 5., 1., 1.,
            np.argmax(spectre) * 1., 0.1, spectre[mu2] * 5., 1., 1., mu2 * 1.
        ]

    print('')
    print('Parameters acquisition...')
    print('')

    out = opt(errfunc_voigt, pars, args=(np.arange(len(spectre)), spectre))[0]

    out1 = out[0:4].tolist()
    out2 = out[5:].tolist()

    dist = int((abs(out2[3] - out1[3]) / 2.) * 0.8)

    print('')
    print('Plotting spectre...')
    print('')

    plt.figure(100)

    plt.plot(spectre)
    plt.plot(V(np.arange(len(spectre)), *out1) + out[4])
    plt.plot(V(np.arange(len(spectre)), *out2) + out[4])
    plt.plot(Vbis(np.arange(len(spectre)), *out))

    integral1 = sum(spectre[int(out1[3] - dist) + 1:int(out1[3] + dist)]) + (
        spectre[int(out1[3]) - dist] + spectre[int(out1[3]) + dist]) * 0.5

    integral2 = sum(spectre[int(out2[3] - dist) + 1:int(out2[3] + dist)]) + (
        spectre[int(out2[3]) - dist] + spectre[int(out2[3]) + dist]) * 0.5

    return (integral1, out[3], integral2, out2[3])
def get_m_exponent(m, Tc, start_temp, end_temp, num_temp):
    """
    Takes in Cv array and underlying temps params and returns critical exponent and error
    """
    # temps
    temps = linspace(start_temp, end_temp, num=num_temp)

    # trim the function to only T < Tc
    crit_temp_idx = argmin(abs(temps - Tc))
    m_trimmed = m[:crit_temp_idx]
    temps_trimmed = temps[:crit_temp_idx]

    # fit the function
    m_best_params, m_cov = opt(lambda t, b, c, d: tc_fit(t, Tc, b, c, d),
                               xdata=temps_trimmed,
                               ydata=m_trimmed,
                               p0=[1 / 8, 0, 0])

    # get best params and errors
    (best_beta, best_c, best_d) = m_best_params
    err_params = sqrt(diag(m_cov))
    best_beta_err = err_params[0]

    # print out best params estimated with this method
    print("Estimated critical exponent = {:.3} +/- {:.1}".format(
        best_beta, best_beta_err))

    # make best fit array with
    best_fit = tc_fit(temps_trimmed, Tc, best_beta, best_c, best_d)

    # plot results
    fig = plt.figure(figsize=(16, 8))
    plt.title("Magnetization fit with " +
              "$(T_c - T)^{beta}$" + " and $beta =$ {:.3} $+/-$ {:.1}".format(
                  abs(best_beta), best_beta_err))
    plt.scatter(temps_trimmed, m_trimmed, c='k')
    plt.plot(temps_trimmed, best_fit, c='darkcyan', label="Best fit")
    plt.ylabel("Magnetization")
    plt.xlabel("Temperature in units of $J/k_b$")
    plt.legend()
    plt.show()

    return best_beta, best_beta_err, best_fit
Esempio n. 5
0
    def refine(self, idx, fun=None, yvec=None):
        """use quadratic interpolation to locate a fine maximum of
        the peak position and value

        Arguments:
            idx: index of the peak to interpolate
        """

        pos = self._idx[idx]
        if yvec is not None:
            y = yvec
        else:
            y = self.y

        if fun:
            from scipy.optimize import broyden1 as opt
            # val = fun(self.val[idx])
            sur = fun(y[pos-1:pos+2])
        else:
            # val = self.val[idx]
            sur = y[pos-1:pos+2]

        if sur[1] > sur[0] and sur[1] >= sur[2]:
            c = sur[1]
            b = (sur[2] - sur[0])/2
            a = (sur[2] + sur[0])/2 - c

            lpos = - b/2/a
            fpos = float(pos) + lpos
            if fun:
                ival = a*lpos*lpos + b*lpos + c
                # print "rpos = %d; rf(val) = %f; f(val) = %f; dpos = %f;"%(pos, sur[1], ival, lpos)
                fval = opt(lambda x: fun(x)-ival, self.val[idx]/2)
            else:
                fval = a*lpos*lpos + b*lpos + c
                # print "rpos = %d; rval = %f; val = %f; dpos = %f; pos = %f"%(pos, sur[1], fval, lpos, fpos)

        else:
            fpos = pos
            fval = sur[1]

        return np.interp(fpos, np.arange(len(self.x)), self.x), fval.tolist()
Esempio n. 6
0
    def refine(self, idx, fun=None, xvec=None):
        """use quadratic interpolation to locate a fine maximum of
        the peak position and value
        
        Arguments:
            idx: index of the peak to interpolate
        """

        pos = self.pos[idx]
        if xvec is not None:
            x = xvec
        else:
            x = self.x

        if fun:
            from scipy.optimize import broyden1 as opt
            #val = fun(self.val[idx])
            sur = fun(x[pos - 1:pos + 2])
        else:
            #val = self.val[idx]
            sur = x[pos - 1:pos + 2]

        if sur[1] > sur[0] and sur[1] > sur[2]:
            c = sur[1]
            b = (sur[2] - sur[0]) / 2
            a = (sur[2] + sur[0]) / 2 - c

            lpos = -b / 2 / a
            fpos = float(pos) + lpos
            if fun:
                ival = a * lpos * lpos + b * lpos + c
                #print "rpos = %d; rf(val) = %f; f(val) = %f; dpos = %f;"%(pos,sur[1],ival, lpos)
                fval = opt(lambda x: fun(x) - ival, self.val[idx] / 2)
            else:
                fval = a * lpos * lpos + b * lpos + c
                #print "rpos = %d; rval = %f; val = %f; dpos = %f; pos = %f"%(pos,sur[1],fval, lpos, fpos)

        else:
            fpos = pos
            fval = sur[1]

        return fpos, fval.tolist()
Esempio n. 7
0
def fitLeastSq(fn, p0, xs, ys, yerrs=None, log_fit=0):
    """ Example fitting a parabola:
        fn = lambda p,xs: p[0]+p[1]*xs**2
        xs,ys=np.arange(-10,10),fn((1,2),xs)
        plt.plot(xs,ys,lw=3)
        pars = fitLeastSq(fn,[15,2],xs,ys)
        plt.plot(xs,fn(pars,xs),'r--',lw=3)"""
    if yerrs is not None:
        if log_fit:
            fit_func = lambda p: np.log10(ys) - np.log10(fn(p, xs))
        else:
            fit_func = lambda p: (ys - fn(p, xs)) / yerrs
    else:
        if log_fit:
            fit_func = lambda p: np.log10(ys) - np.log10(fn(p, xs))
        else:
            fit_func = lambda p: (ys - fn(p, xs))
    pars, res = opt(fit_func, p0)

    return pars
def get_cv_exponent(Cv, Tc, start_temp, end_temp, num_temp):
    """
    Takes in Cv array and underlying temps params and returns critical exponent and error
    """
    # temps
    temps = linspace(start_temp, end_temp, num=num_temp)

    # fit the function

    # split it in two
    cv_best_params, cv_cov = opt(lambda t, a, c: tc_fit_abs(t, Tc, a, c),
                                 xdata=temps,
                                 ydata=Cv,
                                 p0=[0.1, 0])

    # get best params and errors
    (best_alpha, best_c) = cv_best_params
    err_params = sqrt(diag(cv_cov))
    best_alpha_err = err_params[0]

    # print out best params estimated with this method
    print("Estimated critical exponent = {:.3} +/- {:.1}".format(
        best_alpha, best_alpha_err))

    # make best fit array with
    best_fit = tc_fit_abs(temps, Tc, best_alpha, best_c)

    # plot results
    fig = plt.figure(figsize=(16, 8))
    plt.title(
        "Heat capacity fit with " + "$|T_c - T|^{-alpha}$" +
        " and $alpha =$ {:.3} $+/-$ {:.1}".format(best_alpha, best_alpha_err))
    plt.scatter(temps, Cv, c='k')
    plt.plot(temps, best_fit, c='darkcyan', label="Best fit")
    plt.ylabel("Heat capacity")
    plt.xlabel("Temperature in units of $J/k_b$")
    plt.legend()
    plt.show()

    return best_alpha, best_alpha_err, best_fit
Esempio n. 9
0
     def _optimization(self,max_scf=100,log=True,scf=True,readguess=None,argnum=[0],taskname='Output', method='BFGS',penalize=None,**otherargs):
          name=taskname
          record = False
          maxsteps = 100
          rhf_old = 1000
          grad_fun = []
          lbda = 1.0
          rguess = None
          if readguess:
             pguess = name +'.npy'
             out = False
             ene = self._singlepoint(maxsteps,maxsteps,pguess,name,False)
	     if ene == 99999:
                raise NameError('SCF did not converved')
             rguess= pguess

	  if self.verbose:
             self.tape.write(' \n Optimization ...\n')
             self.tape.write(' ---Start--- \n')
             self._optprintparam(max_scf,rguess)

          ene_function = rhfenergy
          pguess = None

          record = False
       	  args=[np.log(self.sys.alpha),self.sys.coef,self.sys.xyz,self.sys.l,self.sys.charges,self.sys.atom,self.sys.natoms,self.sys.nbasis,
               self.sys.list_contr,self.sys.ne,
               max_scf,max_scf,log,True,pguess,rguess,
               name,record,self.sys.alpha] # Last term is only used for Algopy
          grad_fun = self._algo_gradfun(ene_function,args,argnum)  ## This defines de gradient function of autograd
          opt = self.select_method.get(method,lambda: self._BFGS)  ## This selects the opt method
          t0 = time.clock()
          res = opt(ene_function,grad_fun,args,argnum,log,name,**otherargs)
          timer = time.clock()-t0
          self._optupdateparam(argnum,res.x)
          self.status = bool(res.status == 0 or res.status==1)
          return res,timer
Esempio n. 10
0
for i in range(len(rho)):
	rho[i] = l/Ts[i] + (betas/(1 + lambdas*Ts[i])).sum()
rho_norm = rho/beta
rho_norm_error = np.ones_like(rho_norm)

for i in range(len(rho_norm_error)):
	x = ((betas*lambdas)/((1+lambdas*Ts[i])**2)).sum()
	x = x*Ts_error[i]/beta
	x = x + (l*Ts_error[i])/(beta*Ts[i]**2)
	rho_norm_error[i] = x

Text1 = "Fitansatz:  "
Text1 = Text1 + r"$y = a\cdot\sin^2\left(\frac{\pi\cdot x}{b}\right)$"


p_opt,kov = opt(differentieller_Fit,z1/np.amax(z1),rho_norm/np.amax(rho_norm))#,sigma=rho_norm_error)
z1_fit = np.linspace(np.amin(z1/np.amax(z1)),np.amax(z1/np.amax(z1)),1000)
rho1_fit = differentieller_Fit(z1_fit,*p_opt)
x = np.linspace(0,4000)
diff1 = differentieller_Fit(x,0.120,5440)
int1 = integrate.cumtrapz(diff1, x, initial=0) # kumulierte Intergralwerte
#int1 = integrale_Kennlinie(x,0.120,5440)

Text2 = r"$a = ($"
Text2 = Text2 + "{0:.2f}".format(p_opt[0])
Text2 = Text2 + r"$\pm$"
Text2 = Text2 + "{0:.2f}".format(np.sqrt(kov[0][0]))
Text2 = Text2 + r"$)$"


Text3 = r"$b = ($"
Esempio n. 11
0
random.shuffle(mm)
m = mm[0]  # m is the index of largest projection axis

####### U construction #######
def unitary(x0):
    for i in range(m):
        M[m][i] = x0[i]
        M[i][m] = -x0[i]
    for i in range(m + 1, n):
        M[m][i] = x0[i - 1]
        M[i][m] = -x0[i - 1]
    U = LA.expm(M)
    return U


def Energy(x0):
    U = unitary(x0)
    dQ = (U - I).dot(P)
    E = E0 + g0.T.dot(dQ) + 0.5 * dQ.T.dot(H0).dot(dQ)
    return E


####### optimization #######
res = opt(Energy, x0, approx_grad=1)
x = res[0]  # optimized parameters
Q = unitary(x).dot(P) + C

####### output result #######
print np.reshape(Q, (n / 3, 3))
Esempio n. 12
0
 row_alpha = []
 row_beta = []
 row_alpha_err = []
 row_beta_err = []
 for y in range(64):
     points = (tools.get_points(paths=paths,
                                coords=(x, y),
                                freqs=freqs,
                                directory=pathcore,
                                extension=extension))
     frequencies, svalues = zip(*points)
     svalues = np.array(svalues)
     try:
         popt, pcov = opt(tools.lit_fit,
                          frequencies,
                          svalues,
                          p0=[2800, 30e-6],
                          bounds=([1e-8, 1e-8], [np.inf, np.inf]),
                          method='trf')
         perr = np.sqrt(np.diag(pcov))
         row_alpha.append(popt[1])
         row_beta.append(popt[0])
         row_alpha_err.append(perr[1])
         row_beta_err.append(perr[0])
     except:
         row_alpha.append(0)
         row_beta.append(0)
         row_alpha_err.append(0)
         row_beta_err.append(0)
 z_alpha.append(row_alpha)
 z_beta.append(row_beta)
 z_alpha_err.append(row_alpha_err)
Esempio n. 13
0
Q=np.empty((n,3))
sample=open('GeomO','r')
for i in range(n):
        line=sample.readline()
        word=line.split()
        Q[i,0]=float(word[2])
        Q[i,1]=float(word[3])
        Q[i,2]=float(word[4])
sample.close() # reading geometry

def Energy(Q):
	f=open('Geom_tmp','w')
	f.write(str(np.reshape(Q,(n,3))))
	f.close()
        result=os.popen('Cal_Energy.sh','r')
	E=result.read()
	if (len(E)!=0):
		E=float(E)
		f=open('Geom_app','a')
		f.write('\n\n'+str(np.reshape(Q,(n,3))))
		f.write('\n\n'+str(E))
		f.close()
		return E
	else:
		return 0

res=opt(Energy,Q,approx_grad=1)
x=res[0] #optimized parameters
print np.reshape(x,(n,3))
print Energy(x)
Esempio n. 14
0
def data_analisys(file):

    f = h5py.File(file, 'r')

    max_y = 0
    max_x = 0

    events = f['Events']

    for label in np.arange(len(events)):

        mix = np.max(events[str(label + 1)]['spots_x'][...])

        if max_x < mix: max_x = mix

        miy = np.max(events[str(label + 1)]['spots_y'][...])

        if max_y < miy: max_y = miy

    [max_y, max_x] = [max_y + 1, max_x + 1]

    tot_img = np.zeros([max_y, max_x])

    print('')
    print('Creating total image...')
    print('')

    xcms = []
    ycms = []

    for label in np.arange(len(events)):

        xs = events[str(label + 1)]['spots_x'][...]
        ys = events[str(label + 1)]['spots_y'][...]
        zs = events[str(label + 1)]['spots_z'][...]

        max_val = np.max(zs)

        k = np.log(max_val) / max_val

        pounds = np.exp(zs * k)

        xcms.append(sum(pounds * xs) / sum(pounds))

        ycms.append(sum(pounds * ys) / sum(pounds))

        for ind in np.arange(len(xs)):

            tot_img[ys[ind], xs[ind]] += zs[ind]

    print('')
    print('Shifting data...')
    print('')

    [py, px] = np.unravel_index(tot_img.argmax(), [max_y, max_x])

    pars = [py, 0., 0.]

    maxs = []

    for col in np.arange(max_x):

        maxs.append(np.argmax(tot_img[:, col]))

    out = opt(errfunc, pars, args=(np.arange(len(maxs)), maxs))[0]

    truemaxs = []
    trueargs = []

    for col in np.arange(len(maxs)):

        if (maxs[col] - parabola(col, *out))**2 / parabola(col, *out) < 1.:

            truemaxs.append(maxs[col])
            trueargs.append(col)

    out = opt(errfunc,
              pars,
              args=(np.asarray(trueargs) * 1.0, np.asarray(truemaxs) * 1.0))[0]

    x_0_pol = parabola(np.arange(max_x), *out)

    shift_0 = max(x_0_pol)

    shape_row = max_y + int(max(x_0_pol)) - int(min(x_0_pol))

    print('')
    print('Creating spectrum...')
    print('')

    spectre = np.zeros(shape_row)

    for label in np.arange(len(xcms)):

        delta = shift_0 - parabola(xcms[label], *out)

        spectre[int(round(ycms[label] + delta))] += 1

    return (spectre)