def fitLorentz(self, x, y):
     if x[0] / 1e9 > 1:
         raise 'I hate the large number, please divided by 1e9, processing x in GHz'
     para = self.guessLorentz(x, y)
     res = ls(self.errLorentz, para, args=(x, y))
     a, b, c, d = res.x
     return a, b, c, d, np.sqrt(np.abs(1 / c)) * 2e3, res
 def fitCos(self, volt, s):
     x, y = volt, s
     if x[0] / 1e9 > 1:
         raise 'I hate the large number, please divided by 1e9, processing x in GHz'
     Ag, Cg, Wg, phig = self.guessCos(x, y)
     print(Ag, Cg, Wg, phig)
     res = ls(self.errCos, [Ag, Cg, Wg, phig], args=(x, y))
     A, C, W, phi = res.x
     return A, C, W, phi
    def estimate_pose(self, X_gcp, u_gcp, p):
        """
        This function adjusts the pose vector such that the difference between the observed pixel coordinates u_gcp
        and the projected pixels coordinates of X_gcp is minimized.
        """

        p_opt = ls(self.residual, p, method='lm', args=(X_gcp, u_gcp))['x']

        return p_opt
Exemple #4
0
def circleLeastFit(x, y):
    def circle_err(params, x, y):
        xc, yc, R = params
        return (x - xc)**2 + (y - yc)**2 - R**2

    p0 = [
        x.mean(),
        y.mean(),
        np.sqrt(((x - x.mean())**2 + (y - y.mean())**2).mean())
    ]
    res = ls(circle_err, p0, args=(x, y))
    return res.x
def find_accuracy(true_labels, pred_labels):

    # Implement.
    # Return a number corresponding to the accuracy of the two sets of labels.
    m = len(true_labels)
    matrix = build_matrix(true_labels, pred_labels)
    cluster_num, class_num = matrix.shape
    rows, cols = ls(-1 * matrix)
    correct = 0
    for row, col in zip(rows, cols):
        correct += matrix[row][col]
    return correct / m
Exemple #6
0
def optimize(vector, beta_ideal, n_steps, precision, opt_type):

    print('Start optimization')

    arg = read_twiss('twiss.txt', SP2)
    beat_initial = (np.array(arg[0]) -
                    np.array(beta_ideal)) / np.array(beta_ideal)
    arg += (beat_initial, )

    if opt_type == 0:
        metric0 = np.std(beat_initial)
        print('Start from metric {}'.format(metric0))
        print('Try to make zero deviation of beta from ideal')

        vec = ls(first_assumption,
                 vector,
                 args=arg,
                 max_nfev=n_steps,
                 ftol=precision,
                 xtol=precision)
    else:
        beat_periodic = np.transpose(np.reshape(beat_initial, (6, 14)))
        metric0 = np.mean([np.std(b) for b in beat_periodic])
        print('Start from metric {}'.format(metric0))
        print('Make beta-function periodic again!')

        vec = ls(metric_counter,
                 vector,
                 args=arg,
                 max_nfev=n_steps,
                 ftol=precision)

    metric = np.mean(vec.fun)
    print('Optimum {}found'.format('' if vec.success == True else 'not'))
    print('Final metric is {}'.format(metric))
    print('Optimization rate is {}'.format(metric0 / metric))
    set_quads(vec.x, 1, R)

    return vec.x
 def fitRabi(self, x, y):
     if self.envelopemethod == 'hilbert':
         out = self.envelope_Hilbert(y)
     else:
         out = self.envelope(y)
     A, B, T1, w, phi = self.guessRabi(x, out, y)
     amp = (np.max(y) - np.min(y)) / 2
     A = A if np.abs(A - amp) < 0.1 * amp else amp
     B = B if np.abs(B - np.mean(y)) < 0.1 * np.mean(y) else np.mean(y)
     p0 = A, B, T1, w, self.phi
     print(p0)
     res = ls(self.errRabi, p0, args=(np.array(x), np.array(y)))
     A, B, T1, w, phi = res.x
     return A, B, T1, w, phi
Exemple #8
0
def fit_eTofts(T10, cp, signal):
    '''
    Implementation of nonlinear-least-square
    :param T10:
    :param cp:
    :param signal:
    :return:
    '''
    k_trans0 = 0.01
    vb0 = 0.02
    vo0 = 0.2
    x0 = (k_trans0, vb0, vo0)
    bounds = [(1e-5, 0.0005, 0.04), (0.2, 0.1, 0.6)]
    result = ls(target_func, x0, bounds=bounds, args=(T10, cp, signal))
    return result.x
Exemple #9
0
def find_opt_h(x_list, eps):
    N = len(x_list)
    X = x_list
    shift = min(X)
    X_shifted = [x - shift for x in X]

    scale = 1 / max(X_shifted)
    X_shifted_scale = [x * scale for x in X_shifted]

    sigma = stdev(X_shifted_scale)

    phi6 = (-15 / (16 * math.sqrt(math.pi))) * math.pow(sigma, -7)
    phi8 = (105 / (32 * math.sqrt(math.pi))) * math.pow(sigma, -9)

    g1 = (-6 / (math.sqrt(2 * math.pi) * phi6 * N))**(1 / 7)
    g2 = (30 / (math.sqrt(2 * math.pi) * phi8 * N))**(1 / 9)

    D4 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g1, 4, eps)
    D4.evaluate()
    phi4 = sum(D4.pD) / (N - 1)

    D6 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g2, 6, eps)
    D6.evaluate()
    phi6 = sum(D6.pD) / (N - 1)

    constant1 = (1 / (2 * math.sqrt(math.pi) * N))**(1 / 5)
    constant2 = (-6 * math.sqrt(2) * phi4 / phi6)**(1 / 7)

    h_initial = constant1 * phi4**(-1 / 5)

    h = ls(
        fast_h_fun,
        h_initial,
        bounds=(0, np.inf),
        ftol=1e-14,
        xtol=1e-14,
        verbose=1,
        args=(N, X_shifted_scale, constant1, constant2, eps),
    )

    h = float(h.x) / scale
    print(h)

    sortX = sorted(X_shifted_scale)
    D0 = FUDD(N, N, sortX, sortX, h, 0, eps)
    D0.evaluate()
    return h, D0.pD
Exemple #10
0
def find_accuracy(true_labels, pred_labels):

    # Implement.
    # Return a number corresponding to the accuracy of the two sets of labels.
    m = len(true_labels)
    matrix = build_matrix(true_labels, pred_labels)
    cluster_num, class_num = matrix.shape
    # cluster_sum = matrix.sum(axis=1, dtype=float).reshape((cluster_num,1))
    # class_sum = matrix.sum(axis=0, dtype=float).reshape((1,class_num))
    # p_matrix = matrix/cluster_sum   # probability pij
    # recall_matrix = matrix/ class_sum
    # f_matrix = (2 * p_matrix * recall_matrix) /(p_matrix + recall_matrix)
    rows, cols = ls(-1 * matrix)
    correct = 0
    for row, col in zip(rows, cols):
        correct += matrix[row][col]

    return correct / m
def _fair_t1_fit(s0, ti, t1_guess):
    """
    Fit the perfusion FAIR equation:
        
        signal = bias + abs(M0 * (1 - 2 * (exp(-TI/T1))))
        
    using scipy.optimize.least_squares (default Trust Region Reflective
    algorithm). Bias, M0 and T1 are all estimated with a zero lower bound.
    Starting values for bias (zero) and M0 (mean of input signals) are
    calculated automatically; T1 has to be supplied, with the mean of TIs
    being a good guess.
    
    Parameters
    ----------
    s0 : numpy array of int or float
        The aquired signals.
        
    ti : list of int or float
        The inversion times. Must have the same length as s0.
        
    t1_guess : int or float
        An initial starting value for T1. The mean of TIs is a good guess.

    Returns
    -------
    class scipy.optimize.OptimizeResult    
    
    Notes
    ----- 
    Levenberg-Marquardt (method='lm'), the usual literature algorithm, cannot
    be used here as the implementation in scipy does not accept bounds. From
    experience with the R MINPACK implementation (minpack.lm function nlsLM),
    these bounds are necessary to assure good fitting. The lmfit python package
    does implement bounds for MINPACK Levenberg-Marquardt (method=leastsq;
    default), though the results appear to be worse than for TRR
    (method=least_squares), whose results bizarrely look closer to those of R
    minpack.lm nlsLM (to confirm), and are of course identical to
    scipy.optimize.least_squares with method='trf' (default).
    """

    return ls(_fair_t1_func,
              np.array([0, np.mean(s0), t1_guess]),
              bounds=([0, 0, 0], np.inf),
              args=(s0, np.array(ti)))
 def fitT2(self, x, y):
     '''
     几个参数的限制范围还需要考究,A,T1,T2
     '''
     d = self.space(y)
     if self.envelopemethod == 'hilbert':
         out = self.envelope_Hilbert(y)
     else:
         out = self.envelope(y)
     A, B, T1, T2, w, phi = self.guessT2(x, out, y)
     if T2 > 0.8 * x[d - 1] and d < 0.8 * len(y):
         T2 = 0.37 * x[d - 1]
     amp = (np.max(y) - np.min(y)) / 2
     A = A if np.abs(A - amp) < 0.1 * amp else amp
     p0 = A, B, T1, T2, w, self.phi
     print(p0)
     res = ls(self.errT2, p0, args=(x, y))
     A, B, T1, T2, w, phi = res.x
     return A, B, T1, T2, w, phi
Exemple #13
0
def simple_fit(objective_func, guess_params, xdata, ydata, verbose=True, bounds=(-np.inf, np.inf)):
    """
    Wrapper for SciPy's scipy.optimize.least_squares

    Parameters
    ----------
    objective_func : function
        function to fit to with syntax of f(x, p1, p2, ...,) or f(x, params)
    guess_params : array_like with shape (n,)
        Initial guess on independent variables. 
    xdata : array_like with shape (m,)
        Independent data.
    ydata : array_like with shape (m,)
        Dependent data.
    verbose : bool, optional
        Toggle printing of fitting time, cost, and parameters. The default is True.
    bounds : 2-tuple of array_like, optional
        Lower and upper bounds on independent variables. 
        Defaults to no bounds. 
        Each array must match the size of guess_params or be a scalar, in the latter case a bound will be the same for all variables. 
        Use np.inf with an appropriate sign to disable bounds on all or some variables.
        The default is (-np.inf, np.inf).

    Returns
    -------
    params : array_like with shape (n,)

    """
    def cost_func(params):
        # simple, linear cost function. 
        # One can make more nuanced cost functions if needed.
        cost = ydata - objective_func(xdata, params)
        return cost
    t0 = time.time()
    out = ls(cost_func, guess_params, bounds=bounds)
    t1 = time.time()
    if verbose:
        print('Fit done in {0} s with cost of {1}.'.format(str(round(t1-t0,2)), str(out.cost)))
        print(out.x)
    return out.x
def gaussNewton(f, df, jac, r, x, niter=10):
    """Solve a nonlinear least squares problem with Gauss-Newton method.

    Parameters:
        f (function): The objective function.
        df (function): The gradient of f.
        jac (function): The jacobian of the residual vector.
        r (function): The residual vector.
        x (ndarray of shape (n,)): The initial point.
        niter (int): The number of iterations.
    
    Returns:
        (ndarray of shape (n,)) The minimizer.
    """
    for i in xrange(niter):
        try:
            p = la.solve(np.dot(jac(x).T, jac(x)), np.dot(-jac(x).T, r(x)))
            a = ls(f, df, x, p)[0]
            x = x + a * p
        except:
            true
    return x
Exemple #15
0
def fit(x, s, params=None, with_delay=False, with_high_order=False):
    def err(params,
            f,
            s21,
            with_delay=with_delay,
            with_high_order=with_high_order):
        f0, Qi, Qe, phi, A, Aphi, delay, a, b = params
        background = A * (with_high_order *
                          (a * (f - f0)**2 + b *
                           (f - f0)) + 1) * np.exp(1j * (with_delay * delay *
                                                         (f - f0) + Aphi))
        y = 1 / s21 - invS21(f, f0, Qi, Qe, phi) / background
        return np.abs(y)

    if params is None:
        f0, Qi, Qe, QL, phi, A, Aphi, delay, a, b = guessParams(x, s)
    else:
        f0, Qi, Qe, QL, phi, A, Aphi, delay, a, b = params

    res = ls(err, [f0, Qi, Qe, phi, A, Aphi, delay, a, b], args=(x, s))
    f0, Qi, Qe, phi, A, Aphi, delay, a, b = res.x
    QL = 1 / (1 / Qi + 1 / Qe)
    return f0, Qi, Qe, QL, phi, A, Aphi, delay, a, b
Exemple #16
0
    def fitSpec2d(self,v,f,s=None,classify=False):
        if s is not None:
            v,f = self.profile(v,f,s,classify)
        paras, func = self.fitCos(v,f)
        A, C, W, phi = paras.x
        voffset, vperiod, ec, d = self.firstMax(v,f,num=0), 1/W, 0.2, 0
        ejs = (np.max(f)+ec)**2/8/ec
        p0 = [voffset, vperiod,ejs,ec,d]

        while 1:
            # print(p0)
            mybounds = MyBounds(xmin=[0.5*voffset,0,0,0,0],xmax=[1.5*voffset,1.5*vperiod,2*ejs,2*ec,10])
            res = bh(self.err,p0,niter = 200,minimizer_kwargs={"method":"Nelder-Mead","args":(v, f)},accept_test=mybounds) 
            res = ls(self.err,res.x,args=(v, f)) 
            voffset, vperiod, ejs, ec, d = res.x
            space = self.errspace(self.f01,res.x,{'x':v,'y':f})
            if np.max(space) > 0.001:
                v = v[space<0.001]
                f = f[space<0.001]
                p0 = res.x
                # print(len(v),(space<0.001))
            else:
                return f, v, voffset, vperiod, ejs, ec, d
def _get_opt_h(x_list, eps):
    N = len(x_list)
    X_shifted_scale, scale = _get_scale_list(x_list)

    sigma = std(X_shifted_scale)

    phi6 = (-15 / (16 * sqrt(pi))) * power(sigma, -7)
    phi8 = (105 / (32 * sqrt(pi))) * power(sigma, -9)

    g1 = (-6 / (sqrt(2 * pi) * phi6 * N))**(1 / 7)
    g2 = (30 / (sqrt(2 * pi) * phi8 * N))**(1 / 9)

    D4 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g1, 4, eps)
    D6 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g2, 6, eps)

    D4.evaluate()
    D6.evaluate()

    phi4 = sum(D4.pD) / (N - 1)
    phi6 = sum(D6.pD) / (N - 1)

    constant1 = (1 / (2 * sqrt(pi) * N))**(1 / 5)
    constant2 = (-6 * sqrt(2) * phi4 / phi6)**(1 / 7)

    h_initial = constant1 * phi4**(-1 / 5)
    h = ls(
        _fast_h_fun,
        h_initial,
        bounds=(0, inf),
        ftol=1e-14,
        xtol=1e-14,
        verbose=0,
        args=(N, X_shifted_scale, constant1, constant2, eps),
    )
    h = float(h.x) / scale
    return h
 def fitExp(self, x, s):
     y = np.abs(s)
     p0 = self.guessExp(x, y)
     res = ls(self.errExp, p0, args=(x, y))
     return res.x
Exemple #19
0
    betaxbpm, betaybpm = read_twiss('twiss.txt', SP2)

    metric_x = (np.array(measured_x / np.mean(measured_x)) -
                np.array(betaxbpm / np.mean(betaxbpm)))
    metric_y = (np.array(measured_y / np.mean(measured_y)) -
                np.array(betaybpm / np.mean(betaybpm)))
    #    metric_orb = [np.std(orbit_x),np.std(orbit_y)]

    print("metric is {}".format(np.mean(metric_x) + np.mean(metric_y)))

    return list(metric_x) + list(metric_y)


#    return list(metric_x)+list(metric_y)+metric_orb

ls(metric_counter, theta0)

#metric_counter(theta0)

SP2 = 48  # header of twiss file
betaxbpm, betaybpm = read_twiss('twiss.txt', SP2)

plt.figure()
plt.plot(betaxbpm / np.mean(betaxbpm), color="red", ls="--")
plt.plot(measured_x / np.mean(measured_x), marker="^", color="red")

plt.plot(betaybpm / np.mean(betaybpm), color="blue", ls="--")
plt.plot(measured_y / np.mean(measured_y), marker="^", color="blue")

plt.grid(True)
def _get_array_bounds(kernel, low_bound, high_bound):
    low = ls(_ls_get_value, 0, args=(kernel, low_bound))
    high = ls(_ls_get_value, 0, args=(kernel, high_bound))
    return float(low.x), float(high.x)
Exemple #21
0
phi4 = sum(D4.pD) / (N - 1)

D6 = FUDD(N, N, X_shifted_scale, X_shifted_scale, g2, 6, eps)
D6.evaluate()
phi6 = sum(D6.pD) / (N - 1)

constant1 = (1 / (2 * math.sqrt(math.pi) * N))**(1 / 5)
constant2 = (-6 * math.sqrt(2) * phi4 / phi6)**(1 / 7)

h_initial = constant1 * phi4**(-1 / 5)

h = ls(
    fast_h_fun,
    h_initial,
    bounds=(0, np.inf),
    ftol=1e-14,
    xtol=1e-14,
    verbose=2,
    args=(N, X_shifted_scale, constant1, constant2, eps),
)

h = float(h.x) / scale
print(f"BANDWIDTH (h): {h:.5f}")
inf = float("inf")

fim = []
for i in range(0, len(X_shifted_scale) - 36, 1):
    fim.append(ker(X[i + 36], X[i:i + 36], h) / 36)

plt.plot(fim)
plt.show()
# misfit equation
def pers(var_m, x_inp, y):
    return forward(var_m, x_inp) - y


# initial model
x0 = 20  # m
alpha = 300 * (np.pi / 180)
h = 40  # m
K = 94500
m0 = np.array([x0, alpha, h, K])

# Levenberg Marquardt (LM) algorithm
# Ref: https://docs.scipy.org/doc/scipy/reference/generated/scipy.optimize.least_squares.html
result = ls(pers, m0, method='lm', args=(position, SPData_syntethic))
x0 = result.x[0]
alpha = result.x[1]
h = result.x[2]
K = result.x[3]
m = np.array([x0, alpha, h, K])
SPData_calculation = forward(m, position)

# real data without noise
x0_real = 77.07  # m
alpha_real = 309.37 * (np.pi / 180)
h_real = 41.81  # m
K_real = 94686
m_real = np.array([x0_real, alpha_real, h_real, K_real])
SPData_real = forward(m_real, position)
Exemple #23
0
def plot_gradients(source_param, jet_param):

    d43 = get_data(43, source_param)
    d15 = get_data(15, source_param)
    fitfunc = lambda p, x: p[0] + p[1] * x
    errfunc = lambda p, x, y, err: (y - fitfunc(p, x)) / err

    if jet_param == 'l':
        x43 = d43[0]
        y43 = d43[1]
        x15 = d15[0]
        y15 = d15[1]
        pinit = [1.0, 1.0]
        mask15 = np.where(x15 <= np.max(x43))[0]
        mask43 = np.where(x43 >= np.min(x15))[0]
        err43 = d43[5]
        err15 = d15[5]
        jp = 'l'
        ylab = r'$d_j/\mathrm{mas}$'
        xlab = r'$d_c/\mathrm{mas}$'

    if jet_param == 's':
        x43 = d43[0]
        y43 = d43[2]
        x15 = d15[0]
        y15 = d15[2]
        pinit = [1.0, -1.0]
        mask15 = np.where(x15 <= np.max(x43))[0]
        mask43 = np.where(x43 >= np.min(x15))[0]
        err43 = d43[4]
        err15 = d15[4]
        jp = 's'
        ylab = r'$t_b/\mathrm{K}$'
        xlab = r'$d_c/\mathrm{mas}$'

    if jet_param == 'sd':
        x43 = d43[1]
        y43 = d43[2]
        x15 = d15[1]
        y15 = d15[2]
        pinit = [1.0, -1.0]
        mask15 = np.where(x15 <= np.max(x43))[0]
        mask43 = np.where(x43 >= np.min(x15))[0]
        err43 = d43[4]
        err15 = d15[4]
        jp = r'$s_d$'
        ylab = r'$t_b/\mathrm{K}$'
        xlab = r'$d_j/\mathrm{mas}$'

    epoch15 = d15[3]
    epoch43 = d43[3]

    #fit 15
    logx15 = np.log10(x15)
    logy15 = np.log10(y15)
    logyerr15 = err15 / y15
    out15 = ls(errfunc,
               pinit,
               args=(logx15, logy15, logyerr15),
               loss='cauchy',
               verbose=0)
    pfinal15 = out15.x
    index15 = pfinal15[1]
    amp15 = 10.0**pfinal15[0]
    x0_15 = np.linspace(np.min(x15), np.max(x15), x15.shape[0])
    residual15 = np.log10(y15) - np.log10(amp15 * x15**index15)
    #rel_residual15 = (np.log10(y15)-np.log10(amp15*x15**index15))/(np.log10(y15)+np.log10(amp15*x15**index15))
    residual_stderror15 = np.sqrt(np.sum(residual15**2) / x15.shape[0])
    chi_temp15 = np.sum(
        Dchisquared(logy15, np.log10(amp15 * x15**index15), logyerr15))
    chisq_red15 = chi_temp15 / (x15.shape[0] - 2)  #(out15.nfev-3)
    error15 = np.sqrt(np.sum(residual15**2) / x15.shape[0])  # * chisq_red15)
    error15_slope = error15
    fit15 = amp15 * x0_15**index15
    amp15_p = 10.0**(pfinal15[0] + 2 * error15)
    amp15_m = 10.0**(pfinal15[0] - 2 * error15)
    schlauch15_p = amp15_p * x0_15**(index15)
    schlauch15_m = amp15_m * x0_15**(index15)
    fit15_p = amp15 * x0_15**(index15 + error15_slope)
    fit15_m = amp15 * x0_15**(index15 - error15_slope)

    #fit 15overlap
    logx15_ol = np.log10(x15[mask15])
    logy15_ol = np.log10(y15[mask15])
    logyerr15_ol = err15[mask15] / y15[mask15]
    out15_ol = ls(errfunc,
                  pinit,
                  args=(logx15_ol, logy15_ol, logyerr15_ol),
                  loss='cauchy',
                  verbose=0)
    pfinal15_ol = out15_ol.x
    index15_ol = pfinal15_ol[1]
    amp15_ol = 10.0**pfinal15_ol[0]
    x0_15_ol = np.linspace(np.min(x15[mask15]), np.max(x15[mask15]),
                           x15[mask15].shape[0])
    residual15_ol = np.log10(y15[mask15]) - np.log10(
        amp15_ol * x15[mask15]**index15_ol)
    residual_stderror15_ol = np.sqrt(
        np.sum(residual15_ol**2) / x15[mask15].shape[0])
    chi_temp15_ol = np.sum(
        Dchisquared(logy15_ol, np.log10(amp15_ol * x15[mask15]**index15_ol),
                    logyerr15_ol))
    chisq_red15_ol = chi_temp15_ol / (x15[mask15].shape[0] - 2
                                      )  #(out15_ol.nfev-3)
    error15_ol = np.sqrt(np.sum(residual15_ol**2) /
                         x15[mask15].shape[0])  # * chisq_red15_ol)
    error15_slope_ol = error15_ol
    fit15_ol = amp15_ol * x0_15_ol**index15_ol
    fit15_ol_p = amp15_ol * x0_15_ol**(index15_ol + error15_ol)
    fit15_ol_m = amp15_ol * x0_15_ol**(index15_ol - error15_ol)

    #fit 43
    logx43 = np.log10(x43)
    logy43 = np.log10(y43)
    logyerr43 = err43 / y43
    out43 = ls(errfunc,
               pinit,
               args=(logx43, logy43, logyerr43),
               loss='cauchy',
               verbose=0)
    pfinal43 = out43.x
    index43 = pfinal43[1]
    amp43 = 10.0**pfinal43[0]
    x0_43 = np.linspace(np.min(x43), np.max(x43), x43.shape[0])
    residual43 = np.log10(y43) - np.log10(amp43 * x43**index43)
    #rel_residual43 = (np.log10(y43)-np.log10(amp43*x43**index43))/(np.log10(y43)+np.log10(amp43*x43**index43))
    residual_stderror43 = np.sqrt(np.sum(residual43**2) / x43.shape[0])
    chi_temp43 = np.sum(
        Dchisquared(logy43, np.log10(amp43 * x43**index43), logyerr43))
    chisq_red43 = chi_temp43 / (x43.shape[0] - 2)  #(out43.nfev-3)
    error43 = np.sqrt(np.sum(residual43**2) / x43.shape[0])  # * chisq_red43)
    error43_slope = error43
    fit43 = amp43 * x0_43**index43
    fit43_p = amp43 * x0_43**(index43 + error43_slope)
    fit43_m = amp43 * x0_43**(index43 - error43_slope)
    amp43_p = 10.0**(pfinal43[0] + 2 * error43)
    amp43_m = 10.0**(pfinal43[0] - 2 * error43)
    schlauch43_p = amp43_p * x0_43**(index43)
    schlauch43_m = amp43_m * x0_43**(index43)

    #fit 43 overlap
    logx43_ol = np.log10(x43[mask43])
    logy43_ol = np.log10(y43[mask43])
    logyerr43_ol = err43[mask43] / y43[mask43]
    out43_ol = ls(errfunc,
                  pinit,
                  args=(logx43_ol, logy43_ol, logyerr43_ol),
                  loss='cauchy',
                  verbose=0)
    pfinal43_ol = out43_ol.x
    index43_ol = pfinal43_ol[1]
    amp43_ol = 10.0**pfinal43_ol[0]
    x0_43_ol = np.linspace(np.min(x43[mask43]), np.max(x43[mask43]),
                           x43[mask43].shape[0])
    residual43_ol = np.log10(y43[mask43]) - np.log10(
        amp43_ol * x43[mask43]**index43_ol)
    residual_stderror43_ol = np.sqrt(
        np.sum(residual43_ol**2) / x43[mask43].shape[0])
    chi_temp43_ol = np.sum(
        Dchisquared(logy43_ol, np.log10(amp43_ol * x43[mask43]**index43_ol),
                    logyerr43_ol))
    chisq_red43_ol = chi_temp43_ol / (x43[mask43].shape[0] - 2
                                      )  #(out43_ol.nfev-3)
    error43_ol = np.sqrt(np.sum(residual43_ol**2) /
                         x43[mask43].shape[0])  # * chisq_red43_ol
    error43_slope_ol = error43_ol
    fit43_ol = amp43_ol * x0_43_ol**index43_ol
    fit43_ol_p = amp43_ol * x0_43_ol**(index43_ol + error43_ol)
    fit43_ol_m = amp43_ol * x0_43_ol**(index43_ol - error43_ol)

    label0_43 = str(
        Name[source_param]) + ', ' + str(43) + ' GHz' + ', ' + 'DOF: ' + str(
            x43.shape[0]) + ', ' + 'Epochs: ' + str(
                np.unique(d43[3]).shape[0]) + ', '
    label1_43 = jp + ' =' + str(np.round(index43, 2)) + str(r'$\pm$') + str(
        np.round(error43_slope, 2)) + ', ' + r'$\chi ^2 $=' + str(
            np.round(chi_temp43, 3)) + ', ' + r'$\chi ^2 _{red}$=' + str(
                np.round(chisq_red43, 3))
    label2_43 = jp + r'$_{overlap} =$' + str(
        np.round(index43_ol, 2)) + str(r'$\pm$') + str(
            np.round(error43_slope_ol, 2)) + ', ' + r'$\chi ^2 $=' + str(
                np.round(chi_temp43_ol,
                         3)) + ', ' + r'$\chi ^2 _{red}$=' + str(
                             np.round(chisq_red43_ol, 3))

    label0_15 = str(
        Name[source_param]) + ', ' + str(15) + ' GHz' + ', ' + 'DOF: ' + str(
            x15.shape[0]) + ', ' + 'Epochs: ' + str(
                np.unique(d15[3]).shape[0]) + ', '
    label1_15 = jp + ' =' + str(np.round(index15, 2)) + str(r'$\pm$') + str(
        np.round(error15_slope, 2)) + ', ' + r'$\chi ^2$=' + str(
            np.round(chi_temp15, 3)) + ', ' + r'$\chi ^2 _{red}$=' + str(
                np.round(chisq_red15, 3))
    label2_15 = jp + r'$_{overlap} =$' + str(
        np.round(index15_ol, 2)) + str(r'$\pm$') + str(
            np.round(error15_slope_ol, 2)) + ', ' + r'$\chi ^2$=' + str(
                np.round(chi_temp15_ol,
                         3)) + ', ' + r'$\chi ^2 _{red}$=' + str(
                             np.round(chisq_red15_ol, 3))

    fig, axs = plt.subplots(2, 2, sharex=True)

    axs[0, 0].axvspan(np.min(x43[mask43]),
                      np.max(x43),
                      alpha=0.5,
                      color='grey',
                      label='overlap region')
    ## plot 43 l and fit

    #axs[0,0].errorbar(x43,y43,yerr=err*y43,linewidth=0,elinewidth=0.2,marker='+',c='B',markersize=0.5,label = label0_43)

    norm43 = matplotlib.colors.Normalize(vmin=min(epoch43),
                                         vmax=max(epoch43),
                                         clip=True)
    mapper43 = cm.ScalarMappable(norm=norm43, cmap='viridis')
    ep_color43 = np.array([(mapper43.to_rgba(v)) for v in epoch43])

    for x, y, e, color in zip(x43, y43, err43, ep_color43):
        #axs[0,0].plot(x, y, 'o', color=color)
        axs[0, 0].errorbar(x,
                           y,
                           e,
                           marker='+',
                           elinewidth=0.2,
                           markersize=0.5,
                           color=color)

    axs[0, 0].loglog(x0_43,
                     fit43,
                     linestyle='--',
                     color='k',
                     linewidth=0.5,
                     label=label0_43 + label1_43)
    axs[0, 0].loglog(x0_43_ol,
                     fit43_ol,
                     linestyle=':',
                     color='grey',
                     label=label2_43)
    axs[0, 0].loglog(x0_43, fit43_p, linestyle='--', color='k', linewidth=0.5)
    axs[0, 0].loglog(x0_43, fit43_m, linestyle='--', color='k', linewidth=0.5)
    #axs[0,0].loglog(x0_43,schlauch43_p,linestyle=':',color='k',linewidth=0.5)
    #axs[0,0].loglog(x0_43,schlauch43_m,linestyle=':',color='k',linewidth=0.5)
    axs[0, 0].fill_between(x0_43, fit43_p, fit43_m, color='gainsboro')
    #axs[0,0].fill_between(x0_43,schlauch43_p,schlauch43_m,color = 'aquamarine')
    axs[0, 0].set_xlim(10**(-2), 30)
    axs[0, 0].set_ylim(np.min(y43) * (1 - 0.1), np.max(y15) + 1)
    axs[0, 0].set_yscale('log')
    axs[0, 0].set_xscale('log')
    axs[0, 0].set_ylabel(ylab)
    axs[0, 0].legend(loc=2, prop={'size': 3})
    ## plot 43 dispersion
    axs[1, 0].axvspan(np.min(x43[mask43]),
                      np.max(x43),
                      alpha=0.5,
                      color='grey')

    for x, y, color in zip(
            x43, Dchisquared(logy43, np.log10(amp43 * x43**index43),
                             logyerr43), ep_color43):
        #axs[0,0].plot(x, y, 'o', color=color)
        #axs[1,0].errorbar(x, y, e, marker='+',elinewidth=0.2,markersize=0.5, color=color)
        axs[1, 0].loglog(x,
                         y,
                         marker='+',
                         linewidth=0,
                         color=color,
                         markersize=2)

    #axs[1,0].loglog(x43,Dchisquared(logy43,np.log10(amp43*x43**index43),logyerr43),marker='+',linewidth=0,color = 'B',markersize=2)
    #axs[1,0].set_ylim(-1,1)
    axs[1, 0].set_xscale('log')
    axs[1, 0].set_xlim(10**(-2), 30)
    axs[1, 0].set_ylabel(r'$\Delta \chi ^2$')

    ##overlapregion  15
    axs[0, 1].axvspan(np.min(x15),
                      np.max(x15[mask15]),
                      alpha=0.5,
                      color='grey',
                      label='overlap region')

    ## plot 15 l and fit
    #axs[0,1].errorbar(x15,y15,yerr=err*y15,elinewidth=0.2,linewidth=0,marker='+',c='R',markersize=0.5,label = label0_15)

    norm15 = matplotlib.colors.Normalize(vmin=min(epoch15),
                                         vmax=max(epoch15),
                                         clip=True)
    mapper15 = cm.ScalarMappable(norm=norm43, cmap='plasma')
    ep_color15 = np.array([(mapper15.to_rgba(v)) for v in epoch15])

    for x, y, e, color in zip(x15, y15, err15, ep_color15):
        #axs[0,0].plot(x, y, 'o', color=color)
        axs[0, 1].errorbar(x,
                           y,
                           e,
                           marker='+',
                           elinewidth=0.2,
                           markersize=0.5,
                           color=color)

    axs[0, 1].loglog(x0_15,
                     fit15,
                     linestyle='--',
                     color='k',
                     linewidth=0.5,
                     label=label0_15 + label1_15)
    axs[0, 1].loglog(x0_15_ol,
                     fit15_ol,
                     linestyle=':',
                     color='grey',
                     label=label2_15)
    axs[0, 1].loglog(x0_15, fit15_p, linestyle='--', color='k', linewidth=0.5)
    axs[0, 1].loglog(x0_15, fit15_m, linestyle='--', color='k', linewidth=0.5)
    #axs[0,1].loglog(x0_15,schlauch15_p,linestyle=':',color='k',linewidth=0.5)
    #axs[0,1].loglog(x0_15,schlauch15_m,linestyle=':',color='k',linewidth=0.5)

    axs[0, 1].fill_between(x0_15, fit15_p, fit15_m, color='gainsboro')
    #axs[0,1].fill_between(x0_15,schlauch15_p,schlauch15_m,color = 'lightpink')
    axs[0, 1].set_xlim(10**(-2), 30)
    axs[0, 1].yaxis.tick_right()
    axs[0, 1].set_ylim(np.min(y43) * (1 - 0.1), np.max(y15) + 1)
    axs[0, 1].legend(loc=2, prop={'size': 3})
    axs[0, 0].set_yscale('log')
    axs[0, 0].set_xscale('log')

    ## plot 15 dispersion
    axs[1, 1].axvspan(np.min(x15),
                      np.max(x15[mask15]),
                      alpha=0.5,
                      color='grey')

    for x, y, color in zip(
            x15, Dchisquared(logy15, np.log10(amp15 * x15**index15),
                             logyerr15), ep_color15):
        #axs[0,0].plot(x, y, 'o', color=color)
        #axs[1,0].errorbar(x, y, e, marker='+',elinewidth=0.2,markersize=0.5, color=color)
        axs[1, 1].loglog(x,
                         y,
                         marker='+',
                         linewidth=0,
                         color=color,
                         markersize=2)
    #axs[1,1].loglog(x15,Dchisquared(logy15,np.log10(amp15*x15**index15),logyerr15),marker='+',linewidth=0,color='R',markersize=2)
    axs[1, 1].set_xscale('log')
    axs[1, 1].set_xlim(10**(-2), 30)
    axs[1, 1].yaxis.tick_right()

    fig.tight_layout()
    plt.subplots_adjust(hspace=0)
    plt.subplots_adjust(wspace=0.02)

    fig.add_subplot(111, frameon=False)
    plt.tick_params(labelcolor='none',
                    top=False,
                    bottom=False,
                    left=False,
                    right=False)
    plt.xlabel(xlab)

    plt.savefig(f'./paper_plots_test/{Name[source_param]}+_{jet_param}.pdf',
                dpi=500)
    plt.close()
    #0 index15,1 amp15,2 error15,3 chisq_red15,4 residual15,5 index43,6 amp43,
    #7 error43,8 chisq_red43,9 residual43,10 index15_ol,11 amp15_ol,12 error15_ol,
    #13 chisq_red15_ol,14 residual15_ol,15 index43_ol,16 amp43_ol,17 error43_ol,18 chisq_red43_ol,19 residual43_ol
    return (index15, amp15, error15, chisq_red15, residual15, index43, amp43,
            error43, chisq_red43, residual43, index15_ol, amp15_ol, error15_ol,
            chisq_red15_ol, residual15_ol, index43_ol, amp43_ol, error43_ol,
            chisq_red43_ol, residual43_ol)
 def fitRB(self, x, y):
     p0 = self.guess(x, y)
     res = ls(self.err, p0, args=(x, y))
     A, B, p = res.x
     return A, B, p
Exemple #25
0
 def fit(self, func):#expects a mfit.function
     residual = func.residual()
     p0 = func.p0
     xmin, xmax = np.where(self.x>=func.xmin)[0][0], np.where(self.x<=func.xmax)[0][-1]
     fitout = ls(residual, p0, args=(self.x[xmin:(xmax+1)], self.y[xmin:(xmax+1)]))
     func.p0, func.covariance = fitout[0], fitout[1]
Exemple #26
0
            if 'kqdl' in line[0]:
                kqdl = float(line[1])
            g.write('{} := {};\n'.format(line[0], line[1]))

    for i, v in enumerate(theta):
        if 'qf' in corr[i]:
            g.write('{} := {};\n'.format(corr[i], kqfl + v))
        else:
            g.write('{} := {};\n'.format(corr[i], kqdl + v))

    f.close()
    g.close()

    os.system("/home/laptop/cryring/madx < cryring.madx > ./out.dat")

    SP2 = 48  # header of twiss file
    betabpm = read_twiss('twiss.txt', SP2)

    index = [0, 2, 4, 5, 7]
    beta = [x for i, x in enumerate(betabpm) if i in index]
    metric = np.std(beta) / np.mean(beta)

    print('periodic beta is {}'.format(beta))
    print('set of parameters is {}'.format(theta))
    print('metric is {}'.format(metric))

    return metric**2


ls(metric_counter, theta0, xtol=10**(-5))