Automatic Control Knowledge Repository

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

Details for: "ball in tube"

Name: ball in tube (Key: SRSTF)
Path: ackrep_data/system_models/ball_in_tube_system View on GitHub
Type: system_model
Short Description: the position of a styrofoam ball in a vertical tube is controlled by a fan on the lower end of the tube
Created: 2022-09-12
Compatible Environment: default_conda_environment (Key: CDAMA)
Source Code [ / ] simulation.py
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 = [456, 0, 0]

    t_end = 10
    tt = np.linspace(0, t_end, 1000)
    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--------------------------------------

    # create figure + 2x2 axes array
    fig1, axs = plt.subplots(nrows=3, ncols=1, figsize=(12.8, 9.6))

    axs[0].plot(simulation_data.t, simulation_data.y[1])
    axs[0].set_ylabel("Height of the ball [m]")  # y-label
    axs[0].grid()

    axs[1].plot(simulation_data.t, simulation_data.y[2])
    axs[1].set_ylabel("Velocity of the ball [m/s]")  # y-label
    axs[1].grid()

    axs[2].plot(simulation_data.t, simulation_data.y[0])
    axs[2].set_ylabel("Rotation speed [U/min]")  # y-label
    axs[2].set_xlabel("Time [s]")  # x-Label
    axs[2].grid()

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

    plt.tight_layout()

    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 = [1965.06846972, 2.1096, 0.2131639]

    # ---------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

# from ipydex import IPS, activate_ips_on_exception
from random import randrange

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 = 1

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

        # ---------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
            """
            u = 120
            return [u]

        # ---------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

        # ---------start of edit section--------------------------------------
        x1, x2, x3 = self.xx_symb  # state components
        A_B, A_SP, m, g, T_M, k_M, k_V, k_L, n_0 = self.pp_symb  # parameters

        u1 = self.uu_symb[0]  # inputs

        # define symbolic rhs functions
        dx1_dt = -60 / T_M * x1 + k_M / T_M * u1 * 60**2
        dx2_dt = x3
        dx3_dt = k_L / m * ((k_V * (x1 + n_0) / 60 - A_B * x3) / A_SP) ** 2 - g

        # rhs functions matrix
        self.dxx_dt_symb = sp.Matrix([dx1_dt, dx2_dt, dx3_dt])
        # ---------end of edit section----------------------------------------

        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 = "Ball in tube"


# ---------- create symbolic parameters
pp_symb = [A_B, A_SP, m, g, T_M, k_M, k_V, k_L, n_0] = sp.symbols("A_B, A_SP, m, g, T_M, k_M, k_V, k_L, n_0", 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)
A_B_sf = 2.8274e-3
A_SP_sf = 0.4299e-3
m_sf = 2.8e-3
g_sf = 9.81
T_M_sf = 369e-3
k_M_sf = 0.273
k_V_sf = 12e-5  # 0.0001
k_L_sf = 2.823e-4
n_0_sf = 456

# list of symbolic parameter functions
# trailing "_sf" stands for "symbolic parameter function"
pp_sf = [A_B_sf, A_SP_sf, m_sf, g_sf, T_M_sf, k_M_sf, k_V_sf, k_L_sf, n_0_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 = [
    "ball cross-sectional area",
    "air gap cross-sectional area",
    "mass of the ball",
    "acceleration due to gravitation",
    "time constant",
    "amplification",
    "proportional factor",
    "parameter",
    "basic rotation speed",
]

# 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 = [
    r"$m^2$",
    r"$m^2$",
    "kg",
    r"$\frac{m}{s^2}$",
    "s",
    r"$s^{-1}$",
    r"$m^3$",
    r"$\frac{kg}{m}$",
    r"$\frac{U}{min}$",
]

# 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: 3.4 (estimated: 10s)