.. DO NOT EDIT. .. THIS FILE WAS AUTOMATICALLY GENERATED BY SPHINX-GALLERY. .. TO MAKE CHANGES, EDIT THE SOURCE PYTHON FILE: .. "examples/beginner/plot_pendulum_swing_up_fixed_duration.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_beginner_plot_pendulum_swing_up_fixed_duration.py: Fixed Duration Pendulum Swing Up ================================ Objective --------- - Show the use of opty with likely the simplest example possible. Introduction ------------ Given a compound pendulum that is driven by a torque about its joint axis, swing the pendulum from hanging down to standing up in a fixed amount of time using minimal input torque with a bounded torque magnitude. Notes ----- This example uses a fixed duration. There is an example which is mechanically identical to this one, but it uses a variable time interval, to get the pendulum up as fast as possible, given the torque limitations. .. GENERATED FROM PYTHON SOURCE LINES 28-35 .. code-block:: Python import numpy as np import sympy as sm from opty import Problem, create_objective_function import matplotlib.pyplot as plt import matplotlib.animation as animation .. GENERATED FROM PYTHON SOURCE LINES 36-37 Start with defining the fixed duration and number of nodes. .. GENERATED FROM PYTHON SOURCE LINES 37-41 .. code-block:: Python duration = 10.0 # seconds num_nodes = 501 interval_value = duration/(num_nodes - 1) .. GENERATED FROM PYTHON SOURCE LINES 42-43 Specify the symbolic equations of motion. .. GENERATED FROM PYTHON SOURCE LINES 43-54 .. code-block:: Python I, m, g, d, t = sm.symbols('I, m, g, d, t') theta, omega, T = sm.symbols('theta, omega, T', cls=sm.Function) state_symbols = (theta(t), omega(t)) constant_symbols = (I, m, g, d) specified_symbols = (T(t),) eom = sm.Matrix([theta(t).diff() - omega(t), I*omega(t).diff() + m*g*d*sm.sin(theta(t)) - T(t)]) sm.pprint(eom) .. rst-class:: sphx-glr-script-out .. code-block:: none ⎡ d ⎤ ⎢ -ω(t) + ──(θ(t)) ⎥ ⎢ dt ⎥ ⎢ ⎥ ⎢ d ⎥ ⎢I⋅──(ω(t)) + d⋅g⋅m⋅sin(θ(t)) - T(t)⎥ ⎣ dt ⎦ .. GENERATED FROM PYTHON SOURCE LINES 55-56 Specify the known system parameters. .. GENERATED FROM PYTHON SOURCE LINES 56-63 .. code-block:: Python par_map = { I: 1.0, m: 1.0, g: 9.81, d: 1.0, } .. GENERATED FROM PYTHON SOURCE LINES 64-66 Specify the objective function and it's gradient, in this case it calculates the area under the input torque curve over the simulation. .. GENERATED FROM PYTHON SOURCE LINES 66-74 .. code-block:: Python obj_func = sm.Integral(T(t)**2, t) sm.pprint(obj_func) obj, obj_grad = create_objective_function(obj_func, state_symbols, specified_symbols, tuple(), num_nodes, interval_value, time_symbol=t) .. rst-class:: sphx-glr-script-out .. code-block:: none ⌠ ⎮ 2 ⎮ T (t) dt ⌡ .. GENERATED FROM PYTHON SOURCE LINES 75-78 Specify the symbolic instance constraints, i.e. initial and end conditions, where the pendulum starts a zero degrees (hanging down) and ends at 180 degrees (standing up). .. GENERATED FROM PYTHON SOURCE LINES 78-86 .. code-block:: Python target_angle = np.pi # radians instance_constraints = ( theta(0.0), theta(duration) - target_angle, omega(0.0), omega(duration), ) .. GENERATED FROM PYTHON SOURCE LINES 87-88 Limit the torque to a maximum magnitude. .. GENERATED FROM PYTHON SOURCE LINES 88-90 .. code-block:: Python bounds = {T(t): (-2.0, 2.0)} .. GENERATED FROM PYTHON SOURCE LINES 91-92 Create an optimization problem. .. GENERATED FROM PYTHON SOURCE LINES 92-102 .. code-block:: Python prob = Problem(obj, obj_grad, eom, state_symbols, num_nodes, interval_value, known_parameter_map=par_map, instance_constraints=instance_constraints, bounds=bounds, time_symbol=t, backend='numpy') # Use a random positive initial guess. initial_guess = np.random.randn(prob.num_free) .. GENERATED FROM PYTHON SOURCE LINES 103-104 Find the optimal solution. .. GENERATED FROM PYTHON SOURCE LINES 104-108 .. code-block:: Python solution, info = prob.solve(initial_guess) print(info['status_msg']) print(info['obj_val']) .. 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).' 15.641553623553241 .. GENERATED FROM PYTHON SOURCE LINES 109-110 Plot the sparsity pattern of the Jacobian. .. GENERATED FROM PYTHON SOURCE LINES 110-112 .. code-block:: Python _ = prob.plot_jacobian_sparsity() .. image-sg:: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_001.png :alt: plot pendulum swing up fixed duration :srcset: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_001.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 113-114 Plot the optimal state and input trajectories. .. GENERATED FROM PYTHON SOURCE LINES 114-116 .. code-block:: Python _ = prob.plot_trajectories(solution) .. image-sg:: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_002.png :alt: State Trajectories, Input Trajectories :srcset: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_002.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 117-118 Plot the constraint violations. .. GENERATED FROM PYTHON SOURCE LINES 118-120 .. code-block:: Python _ = prob.plot_constraint_violations(solution) .. image-sg:: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_003.png :alt: Constraint violations :srcset: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_003.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 121-122 Plot the objective function as a function of optimizer iteration. .. GENERATED FROM PYTHON SOURCE LINES 122-124 .. code-block:: Python _ = prob.plot_objective_value() .. image-sg:: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_004.png :alt: Objective Value :srcset: /examples/beginner/images/sphx_glr_plot_pendulum_swing_up_fixed_duration_004.png :class: sphx-glr-single-img .. GENERATED FROM PYTHON SOURCE LINES 125-126 Animate the pendulum swing up. .. GENERATED FROM PYTHON SOURCE LINES 126-159 .. code-block:: Python time = prob.time_vector() angle = solution[:num_nodes] fig = plt.figure() ax = fig.add_subplot(111, aspect='equal', autoscale_on=False, xlim=(-2, 2), ylim=(-2, 2)) ax.grid() line, = ax.plot([], [], 'o-', lw=2) time_template = 'time = {:0.1f}s' time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes) def init(): line.set_data([], []) time_text.set_text('') return line, time_text def animate(i): x = [0, par_map[d]*np.sin(angle[i])] y = [0, -par_map[d]*np.cos(angle[i])] line.set_data(x, y) time_text.set_text(time_template.format(time[i])) return line, time_text ani = animation.FuncAnimation(fig, animate, range(0, num_nodes, 4), interval=int(interval_value*1000*4), blit=True, init_func=init) plt.show() .. container:: sphx-glr-animation .. raw:: html
.. rst-class:: sphx-glr-timing **Total running time of the script:** (0 minutes 42.985 seconds) .. _sphx_glr_download_examples_beginner_plot_pendulum_swing_up_fixed_duration.py: .. only:: html .. container:: sphx-glr-footer sphx-glr-footer-example .. container:: sphx-glr-download sphx-glr-download-jupyter :download:`Download Jupyter notebook: plot_pendulum_swing_up_fixed_duration.ipynb ` .. container:: sphx-glr-download sphx-glr-download-python :download:`Download Python source code: plot_pendulum_swing_up_fixed_duration.py ` .. container:: sphx-glr-download sphx-glr-download-zip :download:`Download zipped: plot_pendulum_swing_up_fixed_duration.zip ` .. only:: html .. rst-class:: sphx-glr-signature `Gallery generated by Sphinx-Gallery `_