Exemplo n.º 1
0
def interpolation(x, y, kind):
    """Make the interpolation function"""
    assert scipy is not None, (
        'You must have scipy installed to use interpolation')
    order = None
    if len(y) < len(x):
        x = x[:len(y)]

    x, y = zip(*filter(lambda t: None not in t, zip(x, y)))

    if len(x) < 2:
        return ident
    if isinstance(kind, int):
        order = kind
    elif kind in KINDS:
        order = {
            'nearest': 0,
            'zero': 0,
            'slinear': 1,
            'quadratic': 2,
            'cubic': 3,
            'univariate': 3
        }[kind]
    if order and len(x) <= order:
        kind = len(x) - 1
    if kind == 'krogh':
        return interpolate.KroghInterpolator(x, y)
    elif kind == 'barycentric':
        return interpolate.BarycentricInterpolator(x, y)
    elif kind == 'univariate':
        return interpolate.InterpolatedUnivariateSpline(x, y)
    return interpolate.interp1d(x, y, kind=kind, bounds_error=False)
Exemplo n.º 2
0
def interpolation(x_axis,
                  y_axis,
                  x_value,
                  model='chip',
                  method=None,
                  is_function=False):
    methods = [
        'linear', 'nearest', 'zero', 'slinear', 'quadratic', 'cubic',
        'previous', 'next'
    ]
    # print(type(x_value),type(min(x_axis)))
    models = [
        'akima', 'chip', 'interp1d', 'cubicspline', 'krogh', 'barycentric'
    ]
    # print('x_axis => ',x_axis)

    result = None
    f = None
    if model is None or model == 'interp1d':
        if method in methods:
            f = interpolate.interp1d(x_axis, y_axis, kind=method)
        else:
            f = interpolate.interp1d(x_axis, y_axis, kind='cubic')

    elif model in models:
        if model == 'akima':
            f = interpolate.Akima1DInterpolator(x_axis, y_axis)

        elif model == 'chip':
            f = interpolate.PchipInterpolator(x_axis, y_axis)

        elif model == 'cubicspline':
            f = interpolate.CubicSpline(x_axis, y_axis)

        elif model == 'krogh':
            f = interpolate.KroghInterpolator(x_axis, y_axis)

        elif model == 'barycentric':
            f = interpolate.BarycentricInterpolator(x_axis, y_axis)
    else:
        f = interpolate.PchipInterpolator(x_axis, y_axis)

    if is_function == True:
        return f
    else:
        if not isinstance(x_value, list):
            # if x_value <min(x_axis) or x_value >max(x_axis):
            #    raise Exception('interpolation error: value requested is outside of range')
            #    return result
            try:
                result = float(f(x_value))
            except:
                return result

        else:
            result = list(map(lambda x: float(f(x)), x_value))

        return result
Exemplo n.º 3
0
def max_pos_PDF(PDF_bins, PDF):
    '''
    Returns max position of PDF
    '''

    #return  PDF_bins[PDF.argmax()]

    i_peak = PDF.argmax()
    i_min = np.maximum(0, i_peak - 1)
    i_max = i_min + 3

    if i_max > len(PDF_bins) - 1:
        i_max = np.minimum(i_peak + 1, len(PDF_bins) - 1)
        i_min = i_max - 3

    new_bins = np.arange(PDF_bins[i_min], PDF_bins[i_max], 0.001)
    inter = interpolate.KroghInterpolator(PDF_bins[i_min:i_max],
                                          PDF[i_min:i_max])

    PDF_inter = inter(new_bins)

    return new_bins[PDF_inter.argmax()]
Exemplo n.º 4
0
def main():
    parser = argparse.ArgumentParser()
    parser.add_argument("-d",
                        "--directory",
                        help="directory of relax running",
                        type=str,
                        default="matflow-running")

    args = parser.parse_args()

    # making traj: initial and current
    os.chdir(args.directory)
    dirs_int = []
    for i in os.listdir():
        if i.isdecimal() == True:
            dirs_int.append(int(i))
    total_images = max(dirs_int) + 1  # including initial and final

    for i in range(total_images):
        if i == 0 or i == (total_images - 1):
            os.system("sflow convert -i %.2d/POSCAR -o %.2d/POSCAR.xyz" %
                      (i, i))
        else:
            os.system("sflow convert -i %.2d/POSCAR -o %.2d/POSCAR.xyz" %
                      (i, i))
            os.system("sflow convert -i %.2d/CONTCAR -o %.2d/CONTCAR.xyz" %
                      (i, i))

    os.system("mkdir -p post-processing")

    for i in range(total_images):
        # initial traj
        if i == 0:
            os.system(
                "cat %.2d/POSCAR.xyz > post-processing/traj-initial.xyz" % (i))
        else:
            os.system(
                "cat %.2d/POSCAR.xyz >> post-processing/traj-initial.xyz" %
                (i))
        # current traj
        if i == 0:
            os.system(
                "cat %.2d/POSCAR.xyz > post-processing/traj-current.xyz" % (i))
        elif i == (total_images - 1):
            os.system(
                "cat %.2d/POSCAR.xyz >> post-processing/traj-current.xyz" %
                (i))
        else:
            os.system(
                "cat %.2d/CONTCAR.xyz >> post-processing/traj-current.xyz" %
                (i))
    # end making the traj

    # build the energy barrier plot
    import numpy as np
    import matplotlib.pyplot as plt

    import scipy.interpolate as spinterpolate

    os.system("nebresults.pl")

    neb_dat = np.loadtxt("neb.dat")

    # style: linear spline
    fun_dat = spinterpolate.interp1d(neb_dat[:, 1],
                                     neb_dat[:, 2],
                                     kind="linear")
    denser_x = np.linspace(neb_dat[:, 1].min(), neb_dat[:, 1].max(),
                           30 * len(neb_dat))
    plt.plot(denser_x, fun_dat(denser_x))
    plt.scatter(neb_dat[:, 1], neb_dat[:, 2], marker="o")
    plt.xlabel("Reaction Coordinate (Angstrom)")
    plt.ylabel("Energy (eV)")
    plt.savefig("post-processing/mep-style-linear-spline.png")
    plt.close()

    # style: slinear
    fun_dat = spinterpolate.interp1d(neb_dat[:, 1],
                                     neb_dat[:, 2],
                                     kind="slinear")
    denser_x = np.linspace(neb_dat[:, 1].min(), neb_dat[:, 1].max(),
                           30 * len(neb_dat))
    plt.plot(denser_x, fun_dat(denser_x))
    plt.scatter(neb_dat[:, 1], neb_dat[:, 2], marker="o")
    plt.xlabel("Reaction Coordinate (Angstrom)")
    plt.ylabel("Energy (eV)")
    plt.savefig("post-processing/mep-style-slinear-spline.png")
    plt.close()

    # style: cubic spline
    fun_dat = spinterpolate.interp1d(neb_dat[:, 1],
                                     neb_dat[:, 2],
                                     kind="quadratic")
    denser_x = np.linspace(neb_dat[:, 1].min(), neb_dat[:, 1].max(),
                           30 * len(neb_dat))
    plt.plot(denser_x, fun_dat(denser_x))
    plt.scatter(neb_dat[:, 1], neb_dat[:, 2], marker="o")
    plt.xlabel("Reaction Coordinate (Angstrom)")
    plt.ylabel("Energy (eV)")
    plt.savefig("post-processing/mep-style-quadratic-spline.png")
    plt.close()

    # style: cubic spline
    fun_dat = spinterpolate.interp1d(neb_dat[:, 1],
                                     neb_dat[:, 2],
                                     kind="cubic")
    denser_x = np.linspace(neb_dat[:, 1].min(), neb_dat[:, 1].max(),
                           30 * len(neb_dat))
    plt.plot(denser_x, fun_dat(denser_x))
    plt.scatter(neb_dat[:, 1], neb_dat[:, 2], marker="o")
    plt.xlabel("Reaction Coordinate (Angstrom)")
    plt.ylabel("Energy (eV)")
    plt.savefig("post-processing/mep-style-cubic-spline.png")
    plt.close()

    # style: 5 order spline
    fun_dat = spinterpolate.interp1d(neb_dat[:, 1], neb_dat[:, 2], kind=5)
    denser_x = np.linspace(neb_dat[:, 1].min(), neb_dat[:, 1].max(),
                           30 * len(neb_dat))
    plt.plot(denser_x, fun_dat(denser_x))
    plt.scatter(neb_dat[:, 1], neb_dat[:, 2], marker="o")
    plt.xlabel("Reaction Coordinate (Angstrom)")
    plt.ylabel("Energy (eV)")
    plt.savefig("post-processing/mep-style-5-order-spline.png")
    plt.close()

    # style: KroghInterpolator
    fun_dat = spinterpolate.KroghInterpolator(neb_dat[:, 1], neb_dat[:, 2])
    denser_x = np.linspace(neb_dat[:, 1].min(), neb_dat[:, 1].max(),
                           30 * len(neb_dat))
    plt.plot(denser_x, fun_dat(denser_x))
    plt.scatter(neb_dat[:, 1], neb_dat[:, 2], marker="o")
    plt.xlabel("Reaction Coordinate (Angstrom)")
    plt.ylabel("Energy (eV)")
    plt.savefig("post-processing/mep-style-kroghinterpolator.png")
    plt.close()
Exemplo n.º 5
0
f7 = interpolate.Akima1DInterpolator(t, y)
y7 = f7(tt)

# 区分的 3 次エルミート補間
# y8 = interpolate.pchip_interpolate(t, y, tt)でも結果は同じ
f8 = interpolate.PchipInterpolator(t, y)
y8 = f8(tt)

# 重心補間
# y9 = interpolate.barycentric_interpolate(t, y, tt)でも結果は同じ
f9 = interpolate.BarycentricInterpolator(t, y)
y9 = f9(tt)

# Krogh により提案された補間法
# y10 = interpolate.Krogh_interpolate(t, y, tt)でも結果は同じ
f10 = interpolate.KroghInterpolator(t, y)
y10 = f10(tt)

plt.figure(figsize=(12, 9))
plt.plot(t, y, "o")
plt.plot(tt, y1, "r", label="linear")
plt.plot(tt, y2, "b", label="quadratic")
plt.plot(tt, y3, "g", label="cubic")
plt.plot(tt, y4, "y", label="slinear")
plt.plot(tt, y5, "m", label="zero")
plt.plot(tt, y6, "c", label="nearest")
plt.plot(tt, y7, "--r", label="Akima")
plt.plot(tt, y8, "--b", label="Pchip")
plt.plot(tt, y9, "--g", label="Barycentric")
plt.plot(tt, y10, "--y", label="Krogh")
plt.legend()
Exemplo n.º 6
0
from scipy import interpolate
import numpy as np
import matplotlib.pyplot as plt

# Parametric Variable
t = np.linspace(0, 2 * np.pi, 5)
t_dense = np.linspace(0, 2. * np.pi, 100)

# We are creating a circle
x = np.cos(t)
y = np.sin(t)

# Make a spline with no boundary conditions:
spl_no_bc = interpolate.KroghInterpolator(t, np.c_[x, y])

# Plot the spline and the original points for reference
x_new, y_new = spl_no_bc(t_dense).T
plt.figure(0)
plt.plot(x, y, 'o')
plt.plot(x_new, y_new, '-')
plt.show(block=False)

# Now I'm going to f**k with the lists to set the endpoint first and second derivatives
# (this can actually be done at anypoint)

# The way to set derivatives is as follows:
#   To create a new knot in the spline, t must increase, never decrease
#   The first time a point is in the t list it creates a knot
#   The second time a point is in the t list it sets the 1st derivative at that knot
#   The third time a point is in the t list it sets the 2nd derivative at that knot
Exemplo n.º 7
0
    sys.stderr.write('N = 5: 3d Hermite-interpolation\n')
    f = interpolate.PchipInterpolator(t0, x0)
    x1 = f(t1)
elif n == 6:
    # Akima interpolate
    sys.stderr.write('N = 6: Akima-interpolation\n')
    f = interpolate.Akima1DInterpolator(t0, x0)
    x1 = f(t1)
elif n == 7:
    # Barycentric interpolate
    sys.stderr.write('N = 7: Barycentric-interpolation\n')
    f = interpolate.BarycentricInterpolator(t0, x0)
    x1 = f(t1)
elif n == 8:
    # Krogh interpolate
    sys.stderr.write('N = 8: Krogh-interpolation\n')
    f = interpolate.KroghInterpolator(t0, x0)
    x1 = f(t1)
elif n == 9:
    # lagrange interpolate
    sys.stderr.write('N = 9: Lagrange-interpolation\n')
    f = interpolate.lagrange(t0, x0)
    x1 = f(t1)
else:
    sys.stderr.write('! Argument N is not defined\n')
    sys.exit()

# Output
out = np.vstack((t1, x1))
np.savetxt(sys.stdout, out.T)
Exemplo n.º 8
0
Z3 = poly3(X)

plt.figure()
plt.plot(x, y, 'ro')
plt.plot(X, Z1, 'y', label='Lagrange Interpolate')
plt.plot(X, Z2, 'b', label='Cubic Spline')
plt.plot(X, Z3, 'r', label='Linear Spline')
plt.grid()
plt.legend()
plt.show()

#DD Gener.
#EJERCICIO 3
x = np.array([0, 0, 125, 125, 240, 240])
y = np.array([0, 0, 6500, 65, 13000, 70])
pkro1 = si.KroghInterpolator(x[0::2], y[0::2])
pkro2 = si.KroghInterpolator(x[0::2], y[1::2])

X = np.linspace(0, 240, 1001)

fig = plt.figure(1)
plt.plot(x[0::2], y[0::2], 'ro', label='datos')
plt.plot(X, pkro1(X))
plt.grid()
plt.show()

fig = plt.figure(2)
plt.plot(x[1::2], y[1::2], 'ro', label='datos')
plt.plot(X, pkro2(X))
plt.grid()
plt.show()
Exemplo n.º 9
0
    y[i] = org_func(x[i])

print('x = ', x)
print('y = ', y)

# Vandermonde行列生成
v_mat = np.zeros((n, n))
for i in range(0, n):
    for j in range(0, n):
        v_mat[i, j] = x[i]**j

print('V = ')
print(v_mat)

# new_y := V^(^1) * y
v_coef = slinalg.inv(v_mat) @ y
print('v_coef = ', np.flip(v_coef))

# Lagrange補間
l_poly = sipl.lagrange(x, y)
print('l_coef = ', l_poly.coef)

# Kroph補間
k_poly = sipl.KroghInterpolator(x, y)
print('k(x) = ', k_poly(x))
print('k\'(x) = ', k_poly.derivative(x, der=1))
print('k\'\'(x) = ', k_poly.derivative(x, der=2))

# 条件数
print('||mat_a||_2 * ||mat_a^(-1)|| = ',
      slinalg.norm(v_mat) * slinalg.norm(slinalg.inv(v_mat)))