コード例 #1
0
def main():
    f = np.exp
    a, b = 0.0, 2.0
    hs = np.logspace(1, -5, 7, base=2)
    fig, ax = plt.subplots(1, 1, sharex='all', sharey='all')

    approx_func = integrator_factory(f, a, b, 2)
    make_richardson_plot(ax, approx_func=approx_func, hs=hs, exact=np.exp(2.0) - 1, m=4)
    plt.savefig('./figures/q8.pdf')
コード例 #2
0
def integral():
    x0s = np.array([-2, -1, 0, 1, 2])
    f0s = np.array([4, 2, 4, 2, 3], dtype=int)

    poly = lagrange_basis_polynomial_factory(x0s, f0s)
    xs = np.linspace(-2, 2, 100)
    fig, (ax_trap, ax_simp) = plt.subplots(2,
                                           1,
                                           sharex='all',
                                           sharey='all',
                                           tight_layout=True,
                                           figsize=plt.figaspect(1 / 2))
    ax_trap.plot(xs, poly(xs), color='tab:blue', linewidth=3)
    ax_simp.plot(xs, poly(xs), color='tab:blue', linewidth=3)
    x0s = np.linspace(-2, 2, 9)

    integral_trapezium = trapezium(poly, -2, 2, 8)
    integral_simpson = simpson(poly, -2, 2, 4)

    ax_trap.plot(x0s, poly(x0s), 'o', color='tab:red')
    ax_simp.plot(x0s, poly(x0s), 'o', color='tab:green')

    for x1s in np.vstack([x0s[0:-2:2], x0s[1:-1:2], x0s[2::2]]).T:
        newpoly = lagrange_basis_polynomial_factory(x1s, poly(x1s))
        ax_trap.plot(x1s, newpoly(x1s), color='tab:red')
        ax_trap.fill_between(x1s[:2],
                             newpoly(x1s[:2]),
                             0,
                             color='tab:red',
                             alpha=0.3)
        ax_trap.fill_between(x1s[1:],
                             newpoly(x1s[1:]),
                             0,
                             color='tab:red',
                             alpha=0.3)
        x1s = np.linspace(x1s[0], x1s[-1], 100)
        ax_simp.plot(x1s, newpoly(x1s), color='tab:green')
        ax_simp.fill_between(x1s,
                             newpoly(x1s),
                             0,
                             color='tab:green',
                             alpha=0.3)

    ax_trap.text(0.4, 1.5,
                 rf'$I_{{\text{{trapezium}}}}={integral_trapezium:.3f}$')
    ax_simp.text(0.4, 1.5, rf'$I_{{\text{{simpson}}}}={integral_simpson:.3f}$')
    for ax in (ax_trap, ax_simp):
        ax.set_xlim([-2, 2])
        ax.set_ylim([0, 4.4])
        ax.set_xticks([-2, 0, 2])
        ax.set_yticks([0, 4])
    plt.show()
コード例 #3
0
def main():
    fig, axes = plt.subplots(1, 2, figsize=plt.figaspect(1 / 2))
    kappa, e = 1.0, 1.0
    bs = np.logspace(-1, 1, 100)

    thetas = np.linspace(0.0, np.pi, 1000)
    theta_coulomb = compute_angle_coulomb(bs, e, kappa)
    sigma_coulomb = compute_differential_cross_section_coulomb(
        theta_coulomb, e, kappa)
    axes[0].plot(theta_coulomb, bs, 'k-.', label='Coulomb')
    axes[1].plot(theta_coulomb, np.log(sigma_coulomb), 'k-.', label='Coulomb')

    f, df = yukawa, yukawa_derivative
    for alpha in [0.1, 1]:
        fargs = (
            kappa,
            alpha,
        )
        thetas, sigmas = compute_differential_cross_section(
            bs, e, f, df, fargs)
        axes[0].plot(thetas, bs, '.-', label=fr'$\alpha={alpha}$')
        axes[1].plot(thetas, np.log(sigmas), '.-', label=fr'$\alpha={alpha}$')

    f, df = lennard_jones, lennard_jones_derivative
    for epsilon in [0.1, 1]:
        fargs = (
            1.0,
            epsilon,
        )
        thetas, sigmas = compute_differential_cross_section(
            bs, e, f, df, fargs)
        thetas = thetas - np.rint(thetas / 2 / np.pi) * 2 * np.pi
        axes[0].plot(thetas, bs, '.-', label=fr'$\epsilon={epsilon}$')
        axes[1].plot(thetas,
                     np.log(sigmas),
                     '.-',
                     label=fr'$\epsilon={epsilon}$')

    axes[1].legend()
    axes[0].set_ylabel(r'$\text{impact parameter}$')
    axes[0].set_xlabel(r'$\text{polar scattering angle, }\theta$')
    axes[1].set_xlabel(r'$\text{polar scattering angle, }\theta$')
    axes[1].set_ylabel(
        r'$\text{log differential cross section, }\log{d\sigma/d\Omega}$')
    plt.show()
コード例 #4
0
def main():
    x = 2
    f = func
    df_exact = dfunc(x)
    d2f_exact = d2func(x)

    h = 1
    tols = np.logspace(0, -57, 58, base=2)
    df_approxs = [adaptive_first(f, x, h, tol) for tol in tols]
    df_errors = abs(df_approxs - df_exact)
    d2f_approxs = [adaptive_second(f, x, h, tol) for tol in tols]
    d2f_errors = abs(d2f_approxs - d2f_exact)

    fig, ax = plt.subplots(1, 1, tight_layout=True)
    ax.plot(tols, df_errors, label='first central')
    ax.plot(tols, d2f_errors, label='second central')
    ax.set_xscale('log')
    ax.set_xlabel('tolerance')
    ax.set_yscale('log')
    ax.set_ylabel('actual error')
    ax.legend()
    plt.savefig('./figures/icp5.pdf')
コード例 #5
0
def main():
    f = np.sin
    x = 1.0
    hs = np.logspace(1, -26, 281, base=2)
    fig, axes = plt.subplots(2,
                             1,
                             sharex='all',
                             sharey='all',
                             tight_layout=True)

    make_richardson_plot(axes[0],
                         approx_func=delta1_factory(f, x),
                         hs=hs,
                         exact=np.cos(x),
                         m=2)
    make_richardson_plot(axes[1],
                         approx_func=delta2_factory(f, x),
                         hs=hs,
                         exact=-np.sin(x),
                         m=2)
    for ax in axes:
        ax.plot(hs, 2**-53 * x / hs, 'r--', label=r'$2^{-53}\times x/h$')
        ax.plot(hs, 2**-53 * x / hs / hs, 'r--', label=r'$2^{-53}\times x/h$')
    plt.savefig('./figures/icp3_4.pdf')
コード例 #6
0
def main():
    from plotting import plt
    from pair_potential import slow_pair_potential, faster_pair_potential, fast_pair_potential
    from pair_potential.lj_potential import lennard_jones_potential, vectorised_lennard_jones_potential

    atom_counts = [10, 20, 50, 100, 200, 500, 1000]
    configurations = [
        make_random_configuration(atoms) for atoms in atom_counts
    ]
    pair_potential_functions = [
        slow_pair_potential, faster_pair_potential, fast_pair_potential
    ]
    potential_functions = [
        lennard_jones_potential, lennard_jones_potential,
        vectorised_lennard_jones_potential
    ]
    labels = ['slow', 'faster', 'fast']

    arguments = zip(pair_potential_functions, potential_functions)
    timings = np.array([
        time_to_calculate_energy(ppf, pf, x) for (ppf, pf) in arguments
        for x in configurations
    ],
                       dtype=float).reshape(3, -1)
    fmt = 'timings for {:n} particles:\nslow\t{:.2f} s\nfaster\t{:.2f} s\nfast\t{:.2f} s'
    print(fmt.format(atom_counts[-1], *timings[:, -1]))

    fig, ax = plt.subplots(1, 1)
    for label, timing in zip(labels, timings):
        ax.plot(atom_counts, timing, 'o-', label=label)
    ax.legend()
    ax.set_xlabel('number of atoms')
    ax.set_ylabel('run time/ s')
    ax.set_xscale('log')
    ax.set_yscale('log')
    plt.savefig('./pair_potential_timings.pdf')
コード例 #7
0
    # Get the input constraints along the refTraj
    pendSys.ctrlInput = dynSys.constraints.boxInputCstrLFBG(
        thisRepr, refTraj, 1, *getUlims())

    # Get a quadratic Lyapunov function, initialize it and perform some simulations
    lyapF = lyap.quadraticLyapunovFunction(pendSys)
    lyapF.P, K = lyapF.lqrP(np.identity(2), np.identity(1), refTraj.getX(0.))
    lyapF.alpha = 20.

    lyapF.P = myMath.normalizeEllip(lyapF.P) * 5.

    xInit = plot.getV(lyapF.P,
                      n=30, alpha=lyapF.alpha, endPoint=False) + refTraj.getX(
                          0.)  #regular points on surface

    ff, aa = plt.subplots(1, 2, figsize=[1 + 2 * 4, 4])

    plot.plotEllipse(aa[0], refTraj.getX(0.), lyapF.P, 1., faceAlpha=0.)

    #Get the integration function
    #def __call__(self, x:np.ndarray, u_:Union[np.ndarray,Callable], t:float=0., restrictInput:bool=True, mode:List[int]=[0,0], x0:np.ndarray=False):
    fInt = lambda t, x: pendSys(x,
                                u=lambda x, t: ndot(-K, x - refTraj.getX(t)),
                                t=t,
                                x0=refTraj.getX(t))
    maxStep = 0.1

    # Define an end
    fTerminalConv = lambda t, x: float(
        lyapF.evalV(x.reshape(
            (lyapF.nq, -1)) - refTraj.getX(t), kd=False)) - 1e-5
コード例 #8
0
    X1 = X[y == 1, :]
    X2 = -X[y == 0, :]

    X2 = X2[:40]  # different size X1 and X2

    n, m = X1.shape[0], X2.shape[0]

    r = np.ones(n) / n
    c = np.ones(m) / m

    M = distance_matrix(X1, X2)

    P, d = compute_optimal_transport(M, r, c, lam=30, epsilon=1e-5)

    fig, (ax1, ax2, ax) = plt.subplots(ncols=3)
    ax.scatter(X1[:, 0], X1[:, 1], color=blue)
    ax.scatter(X2[:, 0], X2[:, 1], color=orange)

    for i in range(n):
        for j in range(m):
            ax.plot([X1[i, 0], X2[j, 0]], [X1[i, 1], X2[j, 1]],
                    color=red,
                    alpha=P[i, j] * n)

    ax.set_title('Optimal matching')

    ax1.imshow(M)
    ax1.set_title('Cost matrix')

    ax2.imshow(P)
コード例 #9
0
def standard_plot(*args):
    return plt.subplots(*args, figsize=plt.figaspect(1 / 2), tight_layout=True)
コード例 #10
0
    X1 = X[y==1,:]
    X2 = -X[y==0,:]

    X2 = X2[:40]  # different size X1 and X2

    n, m = X1.shape[0], X2.shape[0]

    r = np.ones(n) / n
    c = np.ones(m) / m

    M = distance_matrix(X1, X2)

    P, d = compute_optimal_transport(M, r, c, lam=30, epsilon=1e-5)

    fig, (ax1, ax2, ax) = plt.subplots(ncols=3)
    ax.scatter(X1[:,0], X1[:,1], color=blue)
    ax.scatter(X2[:,0], X2[:,1], color=orange)

    for i in range(n):
        for j in range(m):
            ax.plot([X1[i,0], X2[j,0]], [X1[i,1], X2[j,1]], color=red,
                    alpha=P[i,j] * n)

    ax.set_title('Optimal matching')

    ax1.imshow(M)
    ax1.set_title('Cost matrix')

    ax2.imshow(P)
    ax2.set_title('Transport matrix')
コード例 #11
0
ファイル: testQuadratic.py プロジェクト: schlepil/temps
while abs(ndot(sep[[0], :], sep[[1], :].T)) < .4:
    sep = np.random.rand(2, 2) - .5
    sep /= norm(sep, axis=1, keepdims=True)
compSize = [(np.random.rand(2, ) - .5) * 1. for _ in range(sep.shape[0])]

x = plot.getV(P, n=101, alpha=alpha)

quadratV = lyap.quadraticLyapunovFunction(pendSys, P, alpha)
pieceQuadratV = lyap.piecewiseQuadraticLyapunovFunction(pendSys, P, alpha)
pieceQuadratV.setPlanesAndComp(sep, compSize)

y = pieceQuadratV.sphere2Ellip(
    x.copy()
)  # This is incorrect as the points can change sector during transformation -> iterate?

ff, aa = plt.subplots(1, 1)
plot.myQuiver(aa, np.zeros((2, 2)), sep.T * .5, c='k')

for k in range(sep.shape[0]):
    ppSep = np.hstack(
        (ndot(plot.Rot(np.pi / 2.),
              sep[[k], :].T), ndot(plot.Rot(-np.pi / 2.), sep[[k], :].T)))
    aa.plot(ppSep[0, :], ppSep[1, :], '-b')

aa.plot(x[0, :], x[1, :], '.-g')
aa.plot(y[0, :], y[1, :], '.-r')

aa.axis('equal')

ff, aa = plt.subplots(1, 2, figsize=(1 + 2 * 4, 4))