Automatic Control Knowledge Repository

You currently have javascript disabled. Some features will be unavailable. Please consider enabling javascript.

Details for: "double crane"

Name: double crane (Key: IMLSG)
Path: ackrep_data/system_models/double_crane_system View on GitHub
Type: system_model
Short Description: overhead double crane with two indipendent control units
Created: 2022-12-08
Compatible Environment: default_conda_environment (Key: CDAMA)
Source Code [ / ] simulation.py
from cProfile import label
import numpy as np
import system_model
from scipy.integrate import solve_ivp

from ackrep_core import ResultContainer
from ackrep_core.system_model_management import save_plot_in_dir
import matplotlib.pyplot as plt
import os

# link to documentation with examples: https://ackrep-doc.readthedocs.io/en/latest/devdoc/contributing_data.html


def simulate():
    """
    simulate the system model with scipy.integrate.solve_ivp

    :return: result of solve_ivp, might contains input function
    """

    model = system_model.Model()

    rhs_xx_pp_symb = model.get_rhs_symbolic()
    print("Computational Equations:\n")
    for i, eq in enumerate(rhs_xx_pp_symb):
        print(f"dot_x{i+1} =", eq)

    rhs = model.get_rhs_func()

    # ---------start of edit section--------------------------------------
    # initial state values
    xx0 = np.zeros(10)

    t_end = 3
    tt = np.linspace(0, t_end, 10000)
    simulation_data = solve_ivp(rhs, (0, t_end), xx0, t_eval=tt)

    # ---------end of edit section----------------------------------------

    save_plot(simulation_data)

    return simulation_data


def save_plot(simulation_data):
    """
    plot your data and save the plot
    access to data via: simulation_data.t   array of time values
                        simulation_data.y   array of data components
                        simulation_data.uu  array of input values

    :param simulation_data: simulation_data of system_model
    :return: None
    """
    # ---------start of edit section--------------------------------------
    fig1, axs = plt.subplots(nrows=10, ncols=1, figsize=(12.8, 9))

    # print in axes top left
    axs[0].plot(simulation_data.t, simulation_data.y[0])
    axs[0].set_ylabel("p1")  # y-label
    axs[0].grid()

    axs[1].plot(simulation_data.t, simulation_data.y[1])
    axs[1].set_ylabel("p2")  # y-label
    axs[1].grid()

    axs[2].plot(simulation_data.t, simulation_data.y[2])
    axs[2].set_ylabel("p3")  # y-label
    axs[2].grid()

    axs[3].plot(simulation_data.t, simulation_data.y[3])
    axs[3].set_ylabel("q1")  # y-label
    axs[3].grid()

    axs[4].plot(simulation_data.t, simulation_data.y[4])
    axs[4].set_ylabel("q2")  # y-label
    axs[4].grid()

    axs[5].plot(simulation_data.t, simulation_data.y[5])
    axs[5].set_ylabel(r"$dot{p}_1$")  # y-label
    axs[5].grid()

    axs[6].plot(simulation_data.t, simulation_data.y[6])
    axs[6].set_ylabel(r"$dot{p}_2$")  # y-label
    axs[6].grid()

    axs[7].plot(simulation_data.t, simulation_data.y[7])
    axs[7].set_ylabel(r"$dot{p}_3$")  # y-label
    axs[7].grid()

    axs[8].plot(simulation_data.t, simulation_data.y[8])
    axs[8].set_ylabel(r"$dot{q}_1$")  # y-label
    axs[8].grid()

    axs[9].plot(simulation_data.t, simulation_data.y[9])
    axs[9].set_ylabel(r"$dot{q}_2$")  # y-label
    axs[9].grid()
    # ---------end of edit section----------------------------------------

    plt.tight_layout()

    # plt.show()

    save_plot_in_dir()


def evaluate_simulation(simulation_data):
    """
    assert that the simulation results are as expected

    :param simulation_data: simulation_data of system_model
    :return:
    """
    # ---------start of edit section--------------------------------------
    # fill in final states of simulation to check your model
    # simulation_data.y[i][-1]
    expected_final_state = [0.0, -44.14499999999994, 0.0, 0.0, 0.0, 0.0, -29.429999999999964, 0.0, 0.0, 0.0]

    # ---------end of edit section----------------------------------------

    rc = ResultContainer(score=1.0)
    simulated_final_state = simulation_data.y[:, -1]
    rc.final_state_errors = [
        simulated_final_state[i] - expected_final_state[i] for i in np.arange(0, len(simulated_final_state))
    ]
    rc.success = np.allclose(expected_final_state, simulated_final_state, rtol=0, atol=1e-2)

    return rc
system_model.py
import sympy as sp
import symbtools as st
import importlib
import sys, os
import symbtools.modeltools as mt

# from ipydex import IPS, activate_ips_on_exception

from ackrep_core.system_model_management import GenericModel, import_parameters

# Import parameter_file
params = import_parameters()


# link to documentation with examples: https://ackrep-doc.readthedocs.io/en/latest/devdoc/contributing_data.html


class Model(GenericModel):
    def initialize(self):
        """
        this function is called by the constructor of GenericModel

        :return: None
        """

        # ---------start of edit section--------------------------------------
        # Define number of inputs -- MODEL DEPENDENT
        self.u_dim = 4

        # Set "sys_dim" to constant value, if system dimension is constant
        self.sys_dim = 10

        # ---------end of edit section----------------------------------------

        # check existence of params file
        self.has_params = True
        self.params = params

    # ----------- SET DEFAULT INPUT FUNCTION ---------- #
    # --------------- Only for non-autonomous Systems
    def uu_default_func(self):
        """
        define input function

        :return:(function with 2 args - t, xx_nv) default input function
        """

        # ---------start of edit section--------------------------------------
        def uu_rhs(t, xx_nv):
            """
            sequence of numerical input values

            :param t:(scalar or vector) time
            :param xx_nv:(vector or array of vectors) numeric state vector
            :return:(list) numeric inputs
            """
            u1 = 0
            u2 = 0
            # if 1 < t < 1.5:
            #     u3 = 0.5
            # else:
            u3 = 0
            # if 2 < t < 3:
            #     u4 = 1
            # else:
            u4 = 0

            return [u1, u2, u3, u4]

        # ---------end of edit section----------------------------------------

        return uu_rhs

    # ----------- SYMBOLIC RHS FUNCTION ---------- #

    def get_rhs_symbolic(self):
        """
        define symbolic rhs function

        :return: matrix of symbolic rhs-functions
        """
        if self.dxx_dt_symb is not None:
            return self.dxx_dt_symb

        x1, x2, x3, x4, x5, x6, x7, x8, x9, x10 = self.xx_symb  # state components
        xdot1, xdot2, xdot3, xdot4, xdot5 = sp.symbols("xdot1, xdot2, xdot3, xdot4, xdot5")
        xx = sp.Matrix([[x1], [x2], [x3], [x4], [x5]])

        s2, m1, m2, m3, J2, l0, l1, l2, g = self.pp_symb  # parameters

        u1, u2, u3, u4 = self.uu_symb  # inputs

        # unit vectors
        ex = sp.Matrix([1, 0])
        ey = sp.Matrix([0, 1])

        # basis 1 and 2 (cart positions)
        S1 = G1 = B1 = sp.Matrix([x4, 0])
        S3 = G6 = B2 = sp.Matrix([l0 + x5, 0])

        # center of gravity of load
        S2 = sp.Matrix([x1, x2])

        # suspension points of load
        G3 = S2 - mt.Rz(x3) * ex * s2
        G4 = S2 + mt.Rz(x3) * ex * s2

        # Time derivatives of centers of masses
        Sd1, Sd2, Sd3 = st.col_split(st.time_deriv(st.col_stack(S1, S2, S3), xx))

        # kinetic energy
        T1 = (m1 / 2 * Sd1.T * Sd1)[0]
        T2 = (m2 / 2 * Sd2.T * Sd2)[0] + J2 / 2 * (xdot3) ** 2
        T3 = (m3 / 2 * Sd3.T * Sd3)[0]

        T = T1 + T2 + T3

        # potential energy
        V = m2 * g * S2[1]

        Q1, Q2, Q3, Q4, Q5 = sp.symbols("Q1, Q2, Q3, Q4, Q5")
        QQ = sp.Matrix([[Q1], [Q2], [Q3], [Q4], [Q5]])
        mod = mt.generate_symbolic_model(T, V, xx, QQ)

        F1 = sp.Matrix([u1, 0])
        F2 = sp.Matrix([u2, 0])

        # unit vectors for ropes to split forces according to angles
        rope1 = G3 - S1
        rope2 = G4 - S3
        uv_rope1 = rope1 / sp.sqrt((rope1.T * rope1)[0])
        uv_rope2 = rope2 / sp.sqrt((rope2.T * rope2)[0])

        # simplify expressions by using l1, l2 as shortcuts
        uv_rope1 = rope1 / l1
        uv_rope2 = rope2 / l2

        F3 = uv_rope1 * u3
        F4 = uv_rope2 * u4

        ddelta_theta = st.symb_vector(f"\\delta\\theta_1:{6}")

        delta_S1 = S1 * 0
        delta_S3 = S3 * 0

        delta_G3 = G3 * 0
        delta_G4 = G4 * 0

        for theta, delta_theta in zip(xx, ddelta_theta):

            delta_S1 += S1.diff(theta) * delta_theta
            delta_S3 += S3.diff(theta) * delta_theta

            delta_G3 += G3.diff(theta) * delta_theta
            delta_G4 += G4.diff(theta) * delta_theta

        # simple part (carts)
        delta_W = delta_S1.T * F1 + delta_S3.T * F2

        # rope1 (F3 > 0 means rope is pushing from S1 towards G3)
        delta_W = delta_W + delta_G3.T * F3 - delta_S1.T * F3

        # rope2 (F4 > 0 means rope is pushing from S3 towards G4)
        delta_W = delta_W + delta_G4.T * F4 - delta_S3.T * F4

        QQ_expr = delta_W.jacobian(ddelta_theta).T

        mod.eqns = mod.eqns.subs(
            [(QQ[0], QQ_expr[0]), (QQ[1], QQ_expr[1]), (QQ[2], QQ_expr[2]), (QQ[3], QQ_expr[3]), (QQ[4], QQ_expr[4])]
        )

        mod.calc_state_eq(simplify=False)

        self.dxx_dt_symb = mod.state_eq.subs([(xdot1, x6), (xdot2, x7), (xdot3, x8), (xdot4, x9), (xdot5, x10)])

        return self.dxx_dt_symb
parameters.py
import sys
import os
import numpy as np
import sympy as sp

import tabulate as tab


# link to documentation with examples: https://ackrep-doc.readthedocs.io/en/latest/devdoc/contributing_data.html


# set model name
model_name = "overhead crane"


# ---------- create symbolic parameters
pp_symb = [s2, m1, m2, m3, J2, l0, l1, l2, g] = sp.symbols("s2, m1, m2, m3, J2, l0, l1, l2, g", real=True)


# ---------- create symbolic parameter functions
# parameter values can be constant/fixed values OR set in relation to other parameters (for example: a = 2*b)
s2_sf = 0.15
m1_sf = 0.45
m2_sf = 0.557
m3_sf = 0.45
J2_sf = 0.000221
l0_sf = 0.5
l1_sf = 0.4
l2_sf = 0.3
g_sf = 9.81

# list of symbolic parameter functions
# tailing "_sf" stands for "symbolic parameter function"
pp_sf = [s2_sf, m1_sf, m2_sf, m3_sf, J2_sf, l0_sf, l1_sf, l2_sf, g_sf]


#  ---------- list for substitution
# -- entries are tuples like: (independent symbolic parameter, numerical value)
pp_subs_list = []


# OPTONAL: Dictionary which defines how certain variables shall be written
# in the table - key: Symbolic Variable, Value: LaTeX Representation/Code
# useful for example for complex variables: {Z: r"\underline{Z}"}
latex_names = {}


# ---------- Define LaTeX table

# Define table header
# DON'T CHANGE FOLLOWING ENTRIES: "Symbol", "Value"
tabular_header = ["Parameter Name", "Symbol", "Value", "Unit"]

# Define column text alignments
col_alignment = ["left", "center", "left", "center"]


# Define Entries of all columns before the Symbol-Column
# --- Entries need to be latex code
col_1 = [
    "center of gravity distance of the load",
    "mass of trolley 1",
    "mass of load",
    "mass of trolley 2",
    "moment of inertia of the load",
    "initial distance between the trolleys",
    "length of rope 1",
    "length of rope 2",
    "acceleration due to gravity",
]

# contains all lists of the columns before the "Symbol" Column
# --- Empty list, if there are no columns before the "Symbol" Column
start_columns_list = [col_1]


# Define Entries of the columns after the Value-Column
# --- Entries need to be latex code
col_4 = ["m", "kg", "kg", "kg", r"$kg \cdot m^2$", "m", "m", "m", r"$\frac{m}{s^2}$"]

# contains all lists of columns after the FIX ENTRIES
# --- Empty list, if there are no columns after the "Value" column
end_columns_list = [col_4]

Related Problems:
Extensive Material:
Download pdf
Result: Success.
Last Build: Checkout CI Build
Runtime: 4.4 (estimated: 10s)