Automatic Control Knowledge Repository

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

Details for: "two mass floating bodies"

Name: two mass floating bodies (Key: AJ0PV)
Path: ackrep_data/system_models/two_mass_floating_bodies_system View on GitHub
Type: system_model
Short Description: A two-body floating system is considered. The above iron ball undergoes a magnetic force generated by a current. A CuZn ball below is attached to that iron ball by a spring with the spring constant kf.
Created: 2022-05-30
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:
#


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 = [0.02, 0.02, 0, 0]  # 0.02, 0.052, 0, 0]

    t_end = 2
    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--------------------------------------
    # plot of your data
    plt.plot(simulation_data.t, simulation_data.y[0], label="position of the iron ball in x-direction")
    plt.plot(simulation_data.t, simulation_data.y[1], label="position of the brass ball in x-direction")
    plt.plot(simulation_data.t, simulation_data.y[2], label="velocity of the iron ball in x-direction")
    plt.plot(simulation_data.t, simulation_data.y[3], label="velocity of the brass ball in x-direction")
    plt.xlabel("Time [s]")  # x-label
    plt.grid()
    plt.legend()

    # ---------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 = [14.623557063331738, 14.696058924396356, 16.881612845239694, 16.981880259096393]

    # ---------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 ackrep_core.system_model_management import GenericModel, import_parameters

# Import parameter_file
params = import_parameters()


# link to documentation with examples:
#


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

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

        # T = 10
        # f1 = 0.2 * sp.sin(self.t_symb) + 0.74
        # u_num_func = st.expr_to_func(self.t_symb, f1)

        # ---------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 = u_num_func(t)
            # u = 0.745

            if t < 0.25:
                u = 8.877
            else:
                u = 0.7

            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, x4 = self.xx_symb  # state components
        m1, m2, k1, k2, kf, g = self.pp_symb  # parameters

        u1 = self.uu_symb[0]  # inputs

        # define symbolic rhs functions
        dx1_dt = x3
        dx2_dt = x4
        dx3_dt = (g * m1 - u1 * k1 / (k2 + x1) ** 2 - kf * (x1 - x2)) / m1
        dx4_dt = (g * m2 + kf * (x1 - x2)) / m2

        # rhs functions list
        self.dxx_dt_symb = sp.Matrix([dx1_dt, dx2_dt, dx3_dt, dx4_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:
#


# set model name
model_name = "Two Mass Floating Bodies"


# ---------- create symbolic parameters
pp_symb = [m1, m2, k1, k2, kf, g] = sp.symbols("m1, m2, k1, k2, kf, 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)
m1_sf = 0.05  # mass of the iron ball in kg
m2_sf = 0.04  # mass of the brass ball in kg
k1_sf = 4e-5  # geometry constant
k2_sf = 0.005  # air gap of magnet in m
kf_sf = 10  # Spring constant in N/m
g_sf = 9.8  # acceleration of gravity in m/s^2


# list of symbolic parameter functions
# tailing "_sf" stands for "symbolic parameter function"
pp_sf = [m1_sf, m2_sf, k1_sf, k2_sf, kf_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 = [
    "mass of the iron ball",
    "mass of the brass ball",
    "geometry constant",
    "air gap of magnet",
    "spring constant",
    "acceleration of 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 = ["kg", "kg", "", "m", r"$\frac{N}{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:
design of a full observer to estimate all states of the system
design of a full state feedback controller to control position of the both balls
design of the LQ controller to control and stabilize position of the both balls
Extensive Material:
Download pdf
Result: Success.
Last Build: Checkout CI Build
Runtime: 3.1 (estimated: 10s)
Plot:

The image of the latest CI job is not available. This is a fallback image.