.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples\plot_shortest_path_on_surface.py" .. LINE NUMBERS ARE GIVEN BELOW. .. only:: html .. note:: :class: sphx-glr-download-link-note :ref:`Go to the end ` to download the full example code. .. rst-class:: sphx-glr-example-title .. _sphx_glr_examples_plot_shortest_path_on_surface.py: Shortest Path on a Surface z = f(x, y) ====================================== Objectives ---------- - Show an example how to use scipy's *solve_bvp* to numerically solve a variational problem. - Compare this approach with the direct minimisation of the curve length, using *opty*. Description ----------- Find the shortest path on a surface defined by z = f(x, y) between two points A and B. The surface is such that the shortest path is not a function but a relation. Notes ----- - Good initial guesses are needed for both methods. - It shows that both method will only find local extrema (variational approach) / local minima (opty) - ``num_nodes`` play quite an important role - and larger is not always better. - The results of both approaches are very similar. .. GENERATED FROM PYTHON SOURCE LINES 33-44 .. code-block:: Python import numpy as np import sympy as sm import sympy.physics.mechanics as me import matplotlib.pyplot as plt from sympy.calculus.euler import euler_equations from scipy.integrate import solve_bvp from opty import Problem from opty.utils import MathJaxRepr from IPython.display import display, Math .. GENERATED FROM PYTHON SOURCE LINES 45-46 The surface. .. GENERATED FROM PYTHON SOURCE LINES 46-59 .. code-block:: Python num_nodes = 201 t = me.dynamicsymbols._t x, y = sm.symbols("x y", real=True) xh, yh = sm.symbols("xh yh", real=True) H, R, w, sigma = 6.0, 1.5, 0.3, 0.15 r = sm.sqrt(x**2 + y**2 + 1e-6) f_expr = (H*sm.exp(-(r - R)**2/w**2) * (1 - sm.exp(-(1 + x/r)/sigma)) + 0.25*sm.sin(2.0*x + 0.5*y)*sm.cos(1.7*y*x) + 0.6*sm.exp(-((x + 0.5)**2 + (y - 2.5)**2)/0.3) - 0.5*sm.exp(-((x - 0.3)**2 + (y + 2.4)**2)/0.4)) .. GENERATED FROM PYTHON SOURCE LINES 60-61 These derivatives are needed for the right hand side of the Euler equations. .. GENERATED FROM PYTHON SOURCE LINES 61-68 .. code-block:: Python f = sm.lambdify((x, y), f_expr, cse=True) fx = sm.lambdify((x, y), f_expr.diff(x), cse=True) fy = sm.lambdify((x, y), f_expr.diff(y), cse=True) fxx = sm.lambdify((x, y), f_expr.diff(x, 2), cse=True) fxy = sm.lambdify((x, y), f_expr.diff(x, y), cse=True) fyy = sm.lambdify((x, y), f_expr.diff(y, 2), cse=True) .. GENERATED FROM PYTHON SOURCE LINES 69-70 Needed below for opty. .. GENERATED FROM PYTHON SOURCE LINES 70-73 .. code-block:: Python f_expr_h = f_expr.subs({x: xh, y: yh}) # needed below for opty .. GENERATED FROM PYTHON SOURCE LINES 74-75 Plot the surface, the points A and B, and the straight line connecting them. .. GENERATED FROM PYTHON SOURCE LINES 75-114 .. code-block:: Python A = np.array([0.0, 0.0]) B = np.array([2.4, 0.0]) print(f"A({A[0]:.2f}, {A[1]:.2f}, {f(*A):.3f})") print(f"B({B[0]:.2f}, {B[1]:.2f}, {f(*B):.3f})") X, Y = np.meshgrid(np.linspace(-3, 3, 220), np.linspace(-3, 3, 220)) Z = f(X, Y) fig = plt.figure(figsize=(13, 5.2)) ax = fig.add_subplot(1, 2, 1, projection="3d") ax.plot_surface(X, Y, Z, cmap="terrain", linewidth=0, antialiased=True, alpha=0.3) ax.scatter(*A, f(*A), color="red", s=50) ax.scatter(*B, f(*B), color="yellow", s=50) ax.set_title("Surface z = f(x, y)") ax.view_init(38, -60) ax.set_xlabel("x") ax.set_ylabel("y") ax.set_zlabel("z") XX = np.linspace(A[0], B[0], num_nodes) YY = np.linspace(A[1], B[1], num_nodes) ZZ = f(XX, YY) ax.plot(XX, YY, ZZ, color="black", lw=1, linestyle="--") ax2 = fig.add_subplot(1, 2, 2) cs = ax2.contourf(X, Y, Z, 30, cmap="terrain") fig.colorbar(cs, ax=ax2, label="height z") ax2.contour(X, Y, Z, 30, colors="k", linewidths=0.3) ax2.plot(*A, "o", color="red", label="A") ax2.plot(*B, "o", color="yellow", label="B") ax2.plot([A[0], B[0]], [A[1], B[1]], color='black', lw=1, linestyle="--") ax2.set_aspect("equal") ax2.legend(loc="upper left") _ = ax2.set_title("Contour map") .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_001.png :alt: Surface z = f(x, y), Contour map :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_001.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none A(0.00, 0.00, -0.000) B(2.40, 0.00, -0.248) .. GENERATED FROM PYTHON SOURCE LINES 115-204 Solve the Problem using the Euler Equations ------------------------------------------- Some explanation on how to get the Euler equations for this problem. *Length of a curve on the surface* The curve in space is :math:`\mathbf r(t) = \big(x(t),\; y(t),\; f(x(t),y(t))\big)` :math:`|\dot{\mathbf r}|^2 = \dot x^2 + \dot y^2 + (f_x\dot x + f_y\dot y)^2 = E\,\dot x^2 + 2F\,\dot x\dot y + G\,\dot y^2` where :math:`E = 1 + f_x^2,\qquad F = f_x f_y,\qquad G = 1+f_y^2` The length of the curve is :math:`L[x,y, \dot x, \dot y] = \int_0^1 \sqrt{E\,\dot x^2 + 2F\, \dot x\dot y + G\,\dot y^2}\;dt , \qquad (x,y)(0)=A,\;(x,y)(1)=B` *From length to energy* One could apply Euler's equations directly to :math:`L`. There is a snag, however: :math:`L` does *not depend on how the curve is parametrised* (walking the same path slower or faster gives the same length). Consequently the Euler equations of :math:`L` are degenerate: they determine the *shape* of the curve but not its parametrisation, and *solve_bvp* canot solve this easily. The standard trick is to minimise the *energy* instead: (The (arbitrary) upper limit of integration is taken as 1, meaning the shortest path is traversed from t=0 to t=1. This determines :math:`\dot x` and :math:`\dot y`, and hence :math:`\dot z = f_x \dot x + f_y \dot y` along the path.) :math:`J[x,y, \dot x, \dot y] = \int_0^1 \Lambda\,dt,\qquad \Lambda(x,y,\dot x,\dot y) = \tfrac12\left(E\,\dot x^2 + 2F\,\dot x\dot y + G\,\dot y^2\right) = \tfrac12|\dot{\mathbf r}|^2` *Energy fixes the parametrisation* Write the speed as :math:`s(t) = |\dot{\mathbf r}(t)|`. Then :math:`L = \int_0^1 s\,dt, \qquad J = \tfrac12\int_0^1 s^2\,dt .` *Length cannot fix the parametrisation.* Re-time the curve by :math:`t = \varphi(\tau)` with :math:`\varphi` increasing from :math:`0` to :math:`1`. The speed becomes :math:`s(\varphi(\tau))\,\varphi'(\tau)`, but :math:`dt = \varphi'\,d\tau` cancels the factor :math:`\varphi'`, so :math:`L` is unchanged. If one curve minimises :math:`L`, every re-timed copy does too. *By the Cauchy–Schwarz inequality:* :math:`L^2 = \Big(\int_0^1 1\cdot s\,dt\Big)^2 \;\le\; \int_0^1 1^2\,dt \cdot\int_0^1 s^2\,dt = 2J ,` with (obviously) equality if :math:`s` is constant. Hence :math:`J \ge \tfrac12 L^2` for every curve: - for a fixed path (fixed :math:`L`), :math:`J` is smallest when the path is traversed at constant speed; - over all paths, the smallest possible value :math:`J = \tfrac12 L_{\min}^2` is reached by the shortest path traversed at constant speed. So minimising :math:`J` gives the same curve as minimising :math:`L`, *and* picks out one parametrisation: constant speed. *Euler equations.* For :math:`q \in \{x, y\}`, :math:`\frac{d}{dt}\frac{\partial \Lambda}{\partial \dot q} - \frac{\partial \Lambda}{\partial q} = 0` *Deriving the geodesic equations with SymPy* Derivation for a *general* function :math:`f` (an undefined SymPy Function), so the result holds for every surface. *Euler equations* produces the two Euler equations; they must be solved for the second derivatives :math:`\ddot x,\ddot y`. .. GENERATED FROM PYTHON SOURCE LINES 204-219 .. code-block:: Python X_, Y_ = sm.Function("x")(t), sm.Function("y")(t) F_ = sm.Function("f") zt = F_(X_, Y_) Lam = 1/2 * (X_.diff(t)**2 + Y_.diff(t)**2 + zt.diff(t)**2) # ½|r'|² EL = euler_equations(Lam, [X_, Y_], t) sol = sm.solve([eq.lhs for eq in EL], [X_.diff(t, 2), Y_.diff(t, 2)], dict=True)[0] xdd_general = sm.simplify(sol[X_.diff(t, 2)]) ydd_general = sm.simplify(sol[Y_.diff(t, 2)]) x_help = me.dynamicsymbols('x') y_help = me.dynamicsymbols('y') .. GENERATED FROM PYTHON SOURCE LINES 220-221 x equation. .. GENERATED FROM PYTHON SOURCE LINES 221-223 .. code-block:: Python MathJaxRepr(sm.Eq(x_help.diff(t, 2), xdd_general)) .. raw:: html
$$\ddot{x} = \frac{\left(- \frac{d^{2}}{d x^{2}} f{\left(x,y \right)} \dot{x}^{2} - \frac{d^{2}}{d y^{2}} f{\left(x,y \right)} \dot{y}^{2} - 2.0 \dot{x} \dot{y} \frac{d^{2}}{d yd x} f{\left(x,y \right)}\right) \frac{d}{d x} f{\left(x,y \right)}}{\left(\frac{d}{d x} f{\left(x,y \right)}\right)^{2} + \left(\frac{d}{d y} f{\left(x,y \right)}\right)^{2} + 1.0}$$


.. GENERATED FROM PYTHON SOURCE LINES 224-225 y equation. .. GENERATED FROM PYTHON SOURCE LINES 225-227 .. code-block:: Python MathJaxRepr(sm.Eq(y_help.diff(t, 2), ydd_general)) .. raw:: html
$$\ddot{y} = \frac{\left(- \frac{d^{2}}{d x^{2}} f{\left(x,y \right)} \dot{x}^{2} - \frac{d^{2}}{d y^{2}} f{\left(x,y \right)} \dot{y}^{2} - 2.0 \dot{x} \dot{y} \frac{d^{2}}{d yd x} f{\left(x,y \right)}\right) \frac{d}{d y} f{\left(x,y \right)}}{\left(\frac{d}{d x} f{\left(x,y \right)}\right)^{2} + \left(\frac{d}{d y} f{\left(x,y \right)}\right)^{2} + 1.0}$$


.. GENERATED FROM PYTHON SOURCE LINES 228-248 *Solving the boundary value problem with solve_bvp* *solve_bvp* needs a first-order system. With the state vector :math:`\mathbf u = (x,\; y,\; v_x,\; v_y),\qquad v_x = \dot x,\; v_y=\dot y` the system is with :math:`Q :=f_{xx} \dot{x}^2 + 2f_{xy} \dot{x} \cdot \dot{y} + f_{yy} \dot{y}^2` :math:`\dot x = v_x,\quad \dot y = v_y,\quad \dot v_x = -\frac{f_x Q}{1+f_x^2+f_y^2},\quad \dot v_y = -\frac{f_y Q}{1+f_x^2+f_y^2}` (see the print outs above, with :math:`\dot v_x := \ddot x` and :math:`\dot v_y := \ddot y`) with *four boundary conditions* (two at each end): :math:`x(0)=x_A,\; y(0)=y_A,\; x(1)=x_B,\; y(1)=y_B` .. GENERATED FROM PYTHON SOURCE LINES 248-273 .. code-block:: Python def geodesic_rhs(t, u): # right-hand side of the geodesic ODE; u has shape (4, m), m being the # number of initial mesh points. X, Y, VX, VY = u gx, gy = fx(X, Y), fy(X, Y) Qv = fxx(X, Y)*VX**2 + 2*fxy(X, Y)*VX*VY + fyy(X, Y)*VY**2 k = Qv / (1 + gx**2 + gy**2) return np.vstack([VX, VY, -gx*k, -gy*k]) def boundary_conditions(ua, ub): # residuals that must vanish: position at t=0 is A, at t=1 is B return np.array([ua[0] - A[0], ua[1] - A[1], ub[0] - B[0], ub[1] - B[1]]) def curve_length(sol, n=4000): # length in 3D of the curve described by a solve_bvp solution tt = np.linspace(0, 1, n) X, Y = sol.sol(tt)[:2] P = np.vstack([X, Y, f(X, Y)]) return np.sum(np.linalg.norm(np.diff(P, axis=1), axis=0)) .. GENERATED FROM PYTHON SOURCE LINES 274-286 Two initial guesses: - above the obstruction, side = 1 - below the obstraction, side = -1 Initial guess that leaves the ring through the gap at :math:`\theta = \pi`, goes around the outside of the ring and ends at B. - side = +1: around the top - side = -1: around the bottom .. GENERATED FROM PYTHON SOURCE LINES 286-306 .. code-block:: Python t_mesh = np.linspace(0, 1, num_nodes) def hook_guess(t_mesh, A, B, R, margin=0.5, side=+1): r_A, r_B = np.hypot(*A), np.hypot(*B) r_out = R + margin # radius just outside the ridge th_B = np.arctan2(B[1], B[0]) th_end = th_B if side > 0 else th_B + 2*np.pi s = t_mesh # radius: rises quickly to r_out, stays there, ends at r_B r = r_A + (r_out - r_A)*(1 - (1 - s)**6) + (r_B - r_out)*s**6 # angle: stays near pi (the gap) while the radius grows, then sweeps to B th = np.pi + (th_end - np.pi)*s**2 X, Y = r*np.cos(th), r*np.sin(th) X += (A[0] - X[0])*(1 - s) + (B[0] - X[-1])*s # hit A and B exactly Y += (A[1] - Y[0])*(1 - s) + (B[1] - Y[-1])*s return np.vstack([X, Y, np.gradient(X, s), np.gradient(Y, s)]) .. GENERATED FROM PYTHON SOURCE LINES 307-308 Solve the boundary value problem for both initial guesses. .. GENERATED FROM PYTHON SOURCE LINES 308-332 .. code-block:: Python sol_list = [] length_list = [] guess_list = [] for side in [+1, -1]: guess = hook_guess(t_mesh, A, B, R, side=side) sol = solve_bvp(geodesic_rhs, boundary_conditions, t_mesh, guess, tol=1e-8, max_nodes=50000) print(sol.message, f"mesh nodes used: {sol.x.size:,}") print(f"length of geodesic, going {'up' if side > 0 else 'down'} :" f" {curve_length(sol):.5f}") sol_list.append(sol) length_list.append(curve_length(sol)) guess_list.append(guess) # Length of the straight line connecting A and B on the surface XX = np.linspace(A[0], B[0], num_nodes) YY = np.linspace(A[1], B[1], num_nodes) ZZ = f(XX, YY) P = np.vstack([XX, YY, ZZ]) laenge = np.sum(np.linalg.norm(np.diff(P, axis=1), axis=0)) length_list.append(laenge) print(f"length of straight line: {laenge:.5f}") length_np = np.array(length_list) .. rst-class:: sphx-glr-script-out .. code-block:: none The algorithm converged to the desired accuracy. mesh nodes used: 7,466 length of geodesic, going up : 8.25026 The algorithm converged to the desired accuracy. mesh nodes used: 6,796 length of geodesic, going down : 8.13249 length of straight line: 13.26116 .. GENERATED FROM PYTHON SOURCE LINES 333-334 Plot the geodesics and the straight line on the surface. .. GENERATED FROM PYTHON SOURCE LINES 334-378 .. code-block:: Python print(f"A({A[0]:.2f}/{A[1]:.2f}/{f(*A):.3f})") print(f"B({B[0]:.2f}/{B[1]:.2f}/{f(*B):.3f})") X, Y = np.meshgrid(np.linspace(-3, 3, 220), np.linspace(-3, 3, 220)) Z = f(X, Y) fig, ax = plt.subplots(1, 2, figsize=(13, 5.2)) for i in range(2): ax2 = ax[i] cs = ax2.contourf(X, Y, Z, 30, cmap="terrain") fig.colorbar(cs, ax=ax2, label="height z") ax2.contour(X, Y, Z, 30, colors="k", linewidths=0.3) ax2.plot(*A, "o", color="red", label="A") ax2.plot(*B, "o", color="green", label="B") ax2.plot([A[0], B[0]], [A[1], B[1]], "w--", lw=1) ax2.set_aspect("equal") ax2.legend(loc="upper left") ax[0].set_title(f"length of upper geodesic: {length_list[0]:.5f} \n" f"length of lower geodesic: {length_list[1]:.5f} \n" f"length of straight line: {length_list[2]:.5f}" ) farben = ["red", "black"] # colors for the geodesics tt = np.linspace(0, 1, 200) for i, sol in enumerate(sol_list): xs, ys = sol.sol(tt)[:2] ax[0].plot(xs, ys, lw=1, label="geodesic", color=farben[i]) ax[0].legend(loc="upper left") length_list_guesses = [] for i, guess in enumerate(guess_list): xs, ys = guess[:2] ZZ = f(xs, ys) P = np.vstack([xs, ys, ZZ]) length = np.sum(np.linalg.norm(np.diff(P, axis=1), axis=0)) ax[1].plot(xs, ys, lw=1, label="initial guess", color=farben[i]) length_list_guesses.append(length) ax[1].legend(loc="upper left") _ = ax[1].set_title(f"length of upper guess: {length_list_guesses[0]:.5f} \n" f"length of lower guess: {length_list_guesses[1]:.5f} \n" f"length of straight line: {length_list[2]:.5f}") .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_002.png :alt: length of upper geodesic: 8.25026 length of lower geodesic: 8.13249 length of straight line: 13.26116, length of upper guess: 8.78357 length of lower guess: 8.99582 length of straight line: 13.26116 :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_002.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none A(0.00/0.00/-0.000) B(2.40/0.00/-0.248) .. GENERATED FROM PYTHON SOURCE LINES 379-382 This confirms, as stated above, that the energy is minimised with constant speed. *solve_bvp* selects the constant speed so that the trajectory is travelled in 1 sec. (See the boundary conditions above) .. GENERATED FROM PYTHON SOURCE LINES 382-403 .. code-block:: Python namen = ['upper geodesic', 'lower geodesic'] fig, ax = plt.subplots(1, 2, figsize=(12, 3), layout="constrained") for i, sol in enumerate(sol_list): xs, ys, uxs, uys = sol.sol(tt) uzs = fx(xs, ys) * uxs + fy(xs, ys) * uys speed = np.sqrt(uxs**2 + uys**2 + uzs**2) delta = (np.max(speed) - np.min(speed)) ax[i].plot(tt, speed, label=r"$\sqrt{u_x^2 + u_y^2 + u_z^2} \approx$ " + f"{np.mean(speed):.3f}" + r" $\frac{m}{s}$") ax[i].plot(tt, uxs, label='uxs') ax[i].plot(tt, uys, label='uys') ax[i].plot(tt, uzs, label='uzs') ax[i].set_xlabel("Time") ax[i].set_ylabel("Speed") ax[i].set_title(f'Speed components and total speed of {namen[i]}, \n' "max deviation of total speed from being constant: " f"{delta:.3e}") _ = ax[i].legend() .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_003.png :alt: Speed components and total speed of upper geodesic, max deviation of total speed from being constant: 3.693e-11, Speed components and total speed of lower geodesic, max deviation of total speed from being constant: 2.117e-10 :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 404-411 Use opty -------- If the point travels at constant speed and the travel time is to be minimized, the path selected must be the shortest one possible. Set up the equations of motion. .. GENERATED FROM PYTHON SOURCE LINES 411-428 .. code-block:: Python x, y, z, ux, uy, uz = me.dynamicsymbols('x y z ux uy uz') r = sm.sqrt(x**2 + y**2 + 1.e-12) v = sm.symbols('v') hill = me.msubs(f_expr_h, {xh: x, yh: y}) eom = sm.Matrix([ x.diff(t) - ux, y.diff(t) - uy, z.diff(t) - uz, ux**2 + uy**2 + uz**2 - v**2, # constant speed z - hill, # surface constraint ]) hill_lam = sm.lambdify((x, y), hill) .. GENERATED FROM PYTHON SOURCE LINES 429-430 Set up a Problem instance. .. GENERATED FROM PYTHON SOURCE LINES 430-476 .. code-block:: Python num_nodes = 201 h = sm.symbols('h') state_symbols = [x, y, z, ux, uy, uz] t0, tf = 0.0, h * (num_nodes - 1) interval_value = h par_map = {} par_map[v] = 10.0 instance_constraints = [ x.func(t0) - A[0], y.func(t0) - A[1], z.func(t0) - hill_lam(A[0], A[1]), x.func(tf) - B[0], y.func(tf) - B[1], ] bounds = {h: (0.0, 1.0)} def obj(free): return free[-1] def obj_grad(free): grad = np.zeros_like(free) grad[-1] = 1.0 return grad # Set up Problem. prob = Problem( obj, obj_grad, eom, state_symbols, num_nodes, h, time_symbol=t, known_parameter_map=par_map, instance_constraints=instance_constraints, bounds=bounds, ) print(prob.num_free) .. rst-class:: sphx-glr-script-out .. code-block:: none 1207 .. GENERATED FROM PYTHON SOURCE LINES 477-478 Solve the Problem for both initial guesses. .. GENERATED FROM PYTHON SOURCE LINES 478-516 .. code-block:: Python t_mesh = np.linspace(0, 1, num_nodes) sol_list = [] length_list = [] guess_list = [] for side in [1, -1]: guess = hook_guess(t_mesh, A, B, R, side=side) x_guess = guess[0, :] y_guess = guess[1, :] z_guess = hill_lam(x_guess, y_guess) # Get a good initial guess for the time step h # Also not really needed for convergence, I leave it here so one can # see how to estimate the time step from the initial guess # for the path length. P = np.vstack([x_guess, y_guess, z_guess]) L_guess = np.sum(np.linalg.norm(np.diff(P, axis=1), axis=0)) h_guess = L_guess / ((num_nodes - 1) * par_map[v]) # Guess of the velocities based on the initial guess for the positions # and time step. Not really needed for convergence. U = np.diff(P, axis=1, prepend=P[:, :1]) / h_guess # shape (3, N) ux_guess, uy_guess, uz_guess = U # This would also give convergence. # ux_guess = np.zeros_like(ux_guess) # uy_guess = np.zeros_like(uy_guess) # uz_guess = np.zeros_like(uz_guess) initial_guess = np.concatenate([x_guess, y_guess, z_guess, ux_guess, uy_guess, uz_guess, [0.01]]) sol, info = prob.solve(initial_guess) print(info['status_msg']) sol_list.append(sol) guess_list.append(guess) .. rst-class:: sphx-glr-script-out .. code-block:: none b'Algorithm terminated successfully at a locally optimal point, satisfying the convergence tolerances (can be specified by options).' b'Algorithm terminated successfully at a locally optimal point, satisfying the convergence tolerances (can be specified by options).' .. GENERATED FROM PYTHON SOURCE LINES 517-518 Plot the objective value of one solution, the other likely looks similar. .. GENERATED FROM PYTHON SOURCE LINES 518-521 .. code-block:: Python _ = prob.plot_objective_value() print(f'step size = {sol_list[0][-1]:.3e}') .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_004.png :alt: Objective Value :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_004.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none step size = 4.125e-03 .. GENERATED FROM PYTHON SOURCE LINES 522-523 Plot the constraint violations of the first solution only. .. GENERATED FROM PYTHON SOURCE LINES 523-526 .. code-block:: Python _ = prob.plot_constraint_violations(sol_list[0], subplots=True) .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_005.png :alt: Constraint violations :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_005.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 527-528 Plot the trajectories of the first solution only. .. GENERATED FROM PYTHON SOURCE LINES 528-530 .. code-block:: Python _ = prob.plot_trajectories(sol_list[0]) .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_006.png :alt: State Trajectories :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_006.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 531-532 Plot the solutions. .. GENERATED FROM PYTHON SOURCE LINES 532-545 .. code-block:: Python names = ["upper geodesic", "lower geodesic"] length_list = [] for i in range(2): solution, *_ = prob.parse_free(sol_list[i]) XX = solution[0, :] YY = solution[1, :] ZZ = f(XX, YY) P = np.vstack([XX, YY, ZZ]) laenge = np.sum(np.linalg.norm(np.diff(P, axis=1), axis=0)) length_list.append(laenge) print(f"length of {names[i]}: {laenge:.5f}. " rf"L_{{opty}} - L_{{solve bvp}} = {laenge - length_np[i]:.3e}") .. rst-class:: sphx-glr-script-out .. code-block:: none length of upper geodesic: 8.24959. L_{opty} - L_{solve bvp} = -6.686e-04 length of lower geodesic: 8.13182. L_{opty} - L_{solve bvp} = -6.725e-04 .. GENERATED FROM PYTHON SOURCE LINES 546-587 .. code-block:: Python print(f"A({A[0]:.2f}/{A[1]:.2f}/{f(*A):.3f})") print(f"B({B[0]:.2f}/{B[1]:.2f}/{f(*B):.3f})") X, Y = np.meshgrid(np.linspace(-3, 3, 220), np.linspace(-3, 3, 220)) Z = f(X, Y) fig, ax = plt.subplots(1, 2, figsize=(13, 5.2), layout="constrained") for i in (0, 1): ax2 = ax[i] cs = ax2.contourf(X, Y, Z, 30, cmap="terrain") fig.colorbar(cs, ax=ax2, label="height z") ax2.contour(X, Y, Z, 30, colors="k", linewidths=0.3) ax2.plot(*A, "o", color="red", label="A") ax2.plot(*B, "o", color="green", label="B") ax2.plot([A[0], B[0]], [A[1], B[1]], "w--", lw=1) ax2.set_aspect("equal") ax2.legend(loc="upper left") ax[0].set_title(f"length of upper geodesic: {length_list[0]:.5f} \n" f"length of lower geodesic: {length_list[1]:.5f} \n") farben = ["red", "black"] # colors for the geodesics tt = np.linspace(0, 1, 200) for i, sol in enumerate(sol_list): solution, *_ = prob.parse_free(sol) xs, ys = solution[0, :], solution[1, :] ax[0].plot(xs, ys, lw=1, label="geodesic", color=farben[i]) ax[0].legend(loc="upper left") length_list_guesses = [] for i, guess in enumerate(guess_list): xs, ys = guess[0, :], guess[1, :] ZZ = f(xs, ys) P = np.vstack([xs, ys, ZZ]) length = np.sum(np.linalg.norm(np.diff(P, axis=1), axis=0)) ax[1].plot(xs, ys, lw=1, label="initial guess", color=farben[i]) length_list_guesses.append(length) ax[1].legend(loc="upper left") _ = ax[1].set_title(f"length of upper guess: {length_list_guesses[0]:.5f} \n" f"length of lower guess: {length_list_guesses[1]:.5f} \n") .. image-sg:: /examples/images/sphx_glr_plot_shortest_path_on_surface_007.png :alt: length of upper geodesic: 8.24959 length of lower geodesic: 8.13182 , length of upper guess: 8.78357 length of lower guess: 8.99582 :srcset: /examples/images/sphx_glr_plot_shortest_path_on_surface_007.png :class: sphx-glr-single-img .. rst-class:: sphx-glr-script-out .. code-block:: none A(0.00/0.00/-0.000) B(2.40/0.00/-0.248) .. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 14.257 seconds) .. _sphx_glr_download_examples_plot_shortest_path_on_surface.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_shortest_path_on_surface.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_shortest_path_on_surface.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_shortest_path_on_surface.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_