Running a Simulation - Carleton-SRL/SPOT GitHub Wiki

Introduction

Assuming you have successfully completed the initial software setup on your Windows 11 PC (or you are using the ground station), let's get set up to run a simulation. Simulations for SPOT are performed in MATLAB-Simulink, using fixed step solver. Note that simulations using variable step solvers are supported; you can switch between solvers via the GUI or using the Simulink Simulation Options.

If you are looking for a more detailed guide on the SPOT Simulink template, please check out this extensive wiki entry. Reading this will be helpful for anyone, but is not strictly required.

Getting Started

To get started, open up an instance of MATLAB 2024b and navigate to your SPOT working folder. It should look something like this:

To create a new project, run the Setup_Experiment.m script. This will open a prompt in which you can enter the name of your project. For this case, we will call the project "GitHubDemonstration".

[!WARNING] Using special characters and spaces in the project name is not supported..

Once "OK" has been clicked, all necessary files are copied from \SPOT\Template_Files\ and renamed according to the project name. While in your newly created project directory, open Run_Initializer.m. This script is mostly empty to start, and simply runs the main GUI - though it does also initialize some parameters for the robotic arm and has example functions for customizing the animations in the GUI. You can add any additional variables for your unique simulations in this script. The default code is shown below:

% The following script is the initializer for SPOT 4.1; in this script,
% users define all initials parameters and/or constants required for
% simulation and experiment.

clear;
clc;
close all force;

warning('off','all')

%% Start the graphical user interface or set the appropriate variables:

% No matter what, the GUI needs to be loaded
appHandle = GUI_v4_1_Main;

%% Place any custom variables or overwriting variables in this section

% As an example, here are the control parameters the manipulator.
% Set torque limits on joints

Tz_lim_sharm                   = .1; % Shoulder Joint [Nm]

Tz_lim_elarm                   = .1; % Elbow Joint [Nm]

Tz_lim_wrarm                   = .1; % Wrist Joint [Nm]

% Transpose Jacobian controller gains:

Kp = [0.08 0 0
      0    0.08 0
      0    0    0.002];
Kv = [0.05 0 0
      0    0.05 0
      0    0    0.005];

% Initialize the PID gains for the ARM:

Kp_sharm                       = 1.5;
Kd_sharm                       = 1.0;

Kp_elarm                       = 1.2;
Kd_elarm                       = 0.8;

Kp_wrarm                       = 1.0;
Kd_wrarm                       = 0.6;

% Define the model properties for the joint friction:
% Based on https://ieeexplore.ieee.org/document/1511048

%Shoulder
Gamma1_sh = 0.005; 
Gamma2_sh = 5;
Gamma3_sh = 40;
Gamma4_sh = 0.015; 
Gamma5_sh = 800; 
Gamma6_sh = 0.005;

%Elbow
Gamma1_el = 0.12; 
Gamma2_el = 5;
Gamma3_el = 10;
Gamma4_el = 0.039; 
Gamma5_el = 800;
Gamma6_el = 0.000001;

%Wrist
Gamma1_wr = 0.025;
Gamma2_wr = 5;
Gamma3_wr = 40;
Gamma4_wr = 0.029;
Gamma5_wr = 800; 
Gamma6_wr = 0.02;

%% This section of the code contains parameters should not be modified

% Set the PWM frequency
PWMFreq = 5; %[Hz]

%% Custom Draw Functions

% The registerDrawFcn function takes 3 inputs:
%
% 1: A name for the custom drawing to be added (must be unique).
%
% 2: A function handle for a function that returns a set of x and y values 
% that defines the geometry of what is to be drawn. This is defined by you,
% however, the inputs are fixed, and must be data and idx, in that order,
% where data is the dataClass object you typically work with for
% simulation/experiment data, and idx is the index of the current step in
% the data being displayed.
% 
% 3: A function handle for a function that determines how the data is
% drawn, standard functions include plot(), line(), and patch(). Custom
% functions can be made too, as long as they return a patch, line or
% similar graphics object.
%
% 4: A set of options for the type of object to be plotted as a cell array.
% Anything you'd pass as an option to function used as argument 2 will
% work.
%

% Examples
% 
% Example 1: Drawing a line using the line function
function [x,y] = drawLine(data, idx)
    theta = data.RED_Rz_rad.Data(idx);

    r = [0.5; 0];
    R = [cos(theta) -sin(theta);
         sin(theta) cos(theta)];
    r_rot = R*r;

    x = data.RED_Px_m.Data(idx) + [0 r_rot(1)];
    y = data.RED_Py_m.Data(idx) + [0 r_rot(2)];
end

appHandle.registerCustomDrawing("Line", @drawLine, @line, ...
    {'Color', 'red', 'LineStyle', '--'})

% Example 2: Drawing a circle using the patch function
function [x, y] = drawCircle(data, idx)
    t = linspace(0, 2*pi);

    r = 0.5;

    x = data.RED_Px_m.Data(idx) + r*cos(t);
    y = data.RED_Py_m.Data(idx) + r*sin(t);
end

appHandle.registerCustomDrawing("Circle", @drawCircle, @patch, ...
    {'FaceColor', 'red', 'EdgeColor', 'red', 'FaceAlpha', 0.1, 'LineStyle', '--'})

%% For those who want to run simulations without using the GUI:

% % Load previous GUI states using this public facing function
% appHandle.LoadDataPublicFcn(cd,'SampleGUIState.mat');
%
% % Set the diagram to run (must be set again after each load)
% appHandle.AvailableDiagramsDropDown.Value = "Template_v4_1_0_2024b_Jetson.slx";
% 
% % Ensure the diagram is loaded
% open(appHandle.AvailableDiagramsDropDown.Value);
% 
% % Edit active platforms
% appHandle.REDCheckBox.Value    = 1;
% appHandle.BLACKCheckBox.Value  = 0;
% appHandle.BLUECheckBox.Value   = 0;
% appHandle.ARMCheckBox.Value    = 0;
% 
% appHandle.ConfirmSettings();
% 
% % Edit initial conditions
% appHandle.SubAppInitialConditions.REDInitialX.Value  = 1.2;  % [m]
% appHandle.SubAppInitialConditions.REDInitialY.Value  = 1.2;  % [m]
% appHandle.SubAppInitialConditions.REDInitialTh.Value = 90;   % [deg]
% 
% appHandle.SubAppInitialConditions.UpdateInitialConditions();
% 
% % Edit mass properties
% appHandle.SubAppMassProperties.OverridePropertiesCheckBox.Value = 1;
% appHandle.SubAppMassProperties.MassRedEditField.Value = 12.035;    % [kg]
% appHandle.SubAppMassProperties.InertiaRedEditField.Value = 0.19854;% [kgm2]
% 
% appHandle.SubAppMassProperties.UpdateMassProperties();
% 
% % Edit phase durations
% appHandle.SubPhase1EditField.Value = 10;       % [s]
% appHandle.SubPhase2EditField.Value = 5;        % [s]
% appHandle.SubPhase3EditField.Value = 28;       % [s]
% appHandle.SubPhase4EditField.Value = 115;      % [s]
% appHandle.DurPhase0EditField.Value = 10;       % [s]
% appHandle.DurPhase1EditField.Value = 5;        % [s]
% appHandle.DurPhase2EditField.Value = 40;       % [s]
% appHandle.DurPhase4EditField.Value = 30;       % [s]
% appHandle.DurPhase5EditField.Value = 20;       % [s] 
% 
% appHandle.UpdateTimes();
% 
% % Execute a simulation
% appHandle.RunSimulationPublicFcn();
% 
% % Manipulate the simulation data
% figure()
% plot(dataClass.Time_s.Data, dataClass.RED_Px_m.Data,'-k')
% grid on
% hold on
% axis tight
% xlabel('Time [s]')
% ylabel('Position - X [m]')

Run the script, and the SPOT GUI should open.

Graphical User Interface Details

From the GUI, you can see and change most variables necessary for simulations and experiments. The GUI contains 6 tabs:

  • Initialize Parameters: Contains common initializing parameters (phase timings, mass properties, etc...).
  • Setup & Run Simulations: Contains settings related to simulations.
  • Setup & Run Experiments: Contains settings related for experiments.
  • Direct Hardware Controls: Contains controls for the hardware, for use outside experiments (debugging, enabling flotation, etc...).
  • Computer Vision Control: Contains options to connect to the Jetson Orin computer, as well as previewing the stereo camera.
  • Data Inspector: Contains a tool that let's you import and plot simulation and experiment data.

There are also two toolbar options in the GUI, File, and Tools. At the moment, the File menu contains the following options:

  • Lab Links: Contains links to the various lab sites (Google Photos, Youtube Channel, etc...).

  • Help: Contains links to the various YouTube videos made for the lab.

  • Save GUI State: This allows users to save the current parameters in the GUI for later use.

  • Load GUI State: This allows users to load in a saved state.

  • Reset GUI Parameters to Default: This allows users to load in the default parameters for the GUI. Default parameters are saved in the Resources folder, under SPOTGUI_DEFAULTS.

  • Override Current Default Parameters: This allows users to take the current GUI states and save them as the new default values. This will overwrite the values currently in the SPOTGUI_DEFAULTS.

  • About: This is just the about page for the software.

Under the Tools menu there are the following options:

  • Add Path to Custom Library: This automatically adds the Custom_Library folder for the current working SPOT folder to the working path for MATLAB. This can be useful for troubleshooting.

  • Update SSH Information: This let's you change the SSH information for the three platforms and the vision computer, in case they every change for some reason (generally, these should never need to be changed).

Initialize Parameters

The first tab contains various options that users need to set up for any simulations or experiments. Users start by loading in the Simulink diagram that they want to run by selecting it from the dropdown menu:

Selecting the diagram will load it into memory and will open the diagram. Once the diagram has been selected and loaded, the next step is to confirm that the mass properties are correct. This can be done by clicking on the Open Mass Properties App. This will open the sub-app for setting up the mass properties:

From this sub-app, you can enter the information you collected if you measured new mass properties for the system. Normally, these options should not change unless you make changes to the hardware. If you want to simply override the calculations, you can check the Override Properties checkbox and then manually enter the desired masses and inertias.

Going back to the main application, the user must select what hardware is being used for the simulations and experiment by checking the boxes in the Active Hardware panel:

Having selected the desired hardware, the user can then click on the Open Initial Conditions App to modify the initial conditions of the simulation and experiment:

In this sub-app, you can set the drop, initial, and home states for the three platforms. These are defined as follows:

  • Drop: This only applies to simulations, and represents the starting location of the platforms - in other words, where you place them on the table before starting an experiment.

  • Initial: This is the location that the platforms will try to get to during Phase #2 of an experiment (see below for phase descriptions). Generally you want the initial and drop locations to be pretty close together.

  • Home: This is the location that the platforms will try to get to during Phase #4 and Phase #5 of the experiment; in other words, once the experiment phase is complete, where are the platforms going to go before shutting down.

You can also set the drop states for the arm attachment. There is no equivalent for the initial and home states for the arm - they are "hardcoded" into the diagram. Lastly, by clicking any of the Show ... buttons, you can visualize the initial conditions you have selected:

Once you are satisfied with the initial conditions, you can close the sub-app and return to the main app. Step #5 is to set the durations for the various experiment phases:

By default, the phases are as follows:

  • Phase #0: This phase is used to wait for data from the ground truth system.
  • Phase #1: This short phase is used to turn on the flotation.
  • Phase #2: During this phase, the platforms will all move to their initial locations using LQR controllers.
  • Phase #3: This is the main experiment phases. Users cannot directly edit the duration of this phase, and are instead required to edit the 4 sub-phase durations. Users can add sub-phases if desired, but will have to circumvent the use of the GUI to do so - this is generally reserved for more advanced users. If you require less than 4 sub-phases, you can set unused ones to a duration of 0 s.
  • Phase #4: During this phase, the platforms will all move to their home locations using LQR controllers.
  • Phase #5: During this phase, the platforms will hold their home positions.

There is also a phase #6, but this phase is used to stop flotation and there is no duration associated. It simply runs from the end of phase #5 until the end of the experiment. In simulation, the diagram is stopped after phase #5.

Finally, the users can tune the default control gains and thruster parameters in the Step #6: Control Law Tuning tab:

The last panel is Step #7: Set Sampling Rate, and it contains the sampling rate for the simulation and experiment. This number represents the time step between each execution of the logic loop in Simulink. So, the default of 20 Hz means that every 0.05 seconds your control law, path planer, etc... will run. Generally, users should not change this value.

[!WARNING] The current gains are tuned for 20 Hz experiments and a thruster PWM frequency of 5 Hz. Retuning the diagram is not recommended unless you are looking for a specific behavior from the spacecraft. The values currently being used are generally good for minimizing air waste, at the cost of inferior position tracking.

Setup & Run Simulations

Moving on to the Setup & Run Simulations tab, users can now run a simulation before they conduct any experiments. Here is an overview of the tab options:

There are three panels in this tab: Simulation Settings, Animation Options, and Run Simulation. In the Simulation Settings panel, users can change the solver type and the solver name. Fixed-step and variable-step are both supported - however, when running an experiment the solver type is automatically forced to fixed-step and the solver name is forced to be ode4. If you are running a variable-step simulation, you can change the basic performance settings in this tab.

Once you are happy with your settings, simply click Start Simulation to run your Simulink diagram. Please be aware that sometimes simulations can take longer then expected due to the logic being used in the diagram. This is especially true if you are running simulations with the arm involved - if your arm controller is not robust enough, the simulation will have a tendency to "explode".

Once the simulation is complete, you'll have new options available to you, including Animation Options. You can set the animation speed (which is a continuous slider from "fast" to "slow"), you can hit Play Animation to see the result of the simulation, you can hit Pause Animation to pause the animation, Stop Animation to stop the animation, and you can Save Simulation Data to save your simulation data to the Saved Data directory. You can also use the Animation Scrubber to scrub through the simulation to a specific point in time, and lastly you can use the Skip To feature to jump directly to a precise time. If you hit Stop Animation, the next time you start the animation it will start from the beginning.

Under the Animation Options panel, you also have the ability to add the following options by default:

  • Show Docking Cone/Show Solar Panels/Show Docking Port: Checking these will shows the corresponding components during the animation.

  • Show Path Trace: Checking this will show a trace of where the spacecraft have been over time in the x-y plane.

  • Custom Drawings: These are the custom functions defined in the initializer. These allow you to extend the animations, if you want. Most users are unlikely to bother with this option.

  • Create Video: If this option is checked before you click on Play Animation, then it will create and save a .avi video of the simulation.

Back to the Run Simulation panel, when you select the Save Simulation Data button, the data will be saved to a timeseries, and a dialog box will indicate where the data was saved to:

You can now inspect the data using whatever approach is preferred. The Carleton-SRL GitHub has a GetStarted repository that contains useful code for generating publication quality figures. Alternatively, for quick inspections, the built-in Data Inspector can be used.

Data Inspector

The Data Inspector tab is intended to be used for quick data checking of SPOT data, and will not work for other data types.

In this tab, you can load up to two datasets at the same time (usually one for simulation data and one for experimental data). Once a data file has been loaded, the dropdown boxes for the x-axis and y-axis will be populated with the fields of the timeseries. Usually the x-axis is time, but you can select whichever parameter you want. For this example, we will load in the simulation that was performed above:

With the data loaded, the dropdown menus become populated:

Simply use the dropdown menus to pick the x-y data pairing you want to plot. Let's do Time_s vs. RED_Px_m as an example. Once selected, click on the Show Fig. #1 button to plot the data:

By default, you can now select another parameter (let's say RED_Py_m) and click on Show Fig. #1 again to overplot new data on top of the previous data.

This can be disabled by unchecking the Allow Overplot option on the right-hand side. Alternatively, you can also clear the figure using the Clear Figure button before plotting. The inspector also let's you export figures using the Export to PDF option, but this will not generate a publication quality figure and is intended for creating quick plots. Users can also change the labels for the axis here:

And users can also set viewing ranges for the plots using the Figure Options on the right-hand side. Changes to the plot ranges require you to click the Apply Ranges button.

Next Step

If you have satisfactory simulation results, you are now ready to book an experiment timeslot.

Click here to go HOME