Skip to content

MATLAB server and interface that provides thrust feedback for a TUDAT application.

License

Notifications You must be signed in to change notification settings

decenter2021/tudat-matlab-thrust-feedback

Repository files navigation

πŸ›° tudat-matlab-thrust-feedback

🎯 Features

  • Thrust feedback of TUDAT application using MATLAB
  • Assess the performance of novel control solution developed in MATLAB to a single spacecraft / constellation of satellites
  • High-fidelity numerical propagation
  • Easy to implement control strategy in high-level MATLAB language
  • Seamless transition between high-fidelity simulation using TUDAT and simple propagation in MATLAB for debug puposes
  • Custom makefile to automate compilation, simulation, and post-processing

πŸš€ Index


πŸ’‘ Description

The tudat-matlab-thrust-feedback toolbox provides an interface between a C++ TUDAT application and MATLAB to define a thrust feedback control law. The architecture of the overall environment is shown below.

simulation_scheme drawio-2-2

The tudat-matlab-thrust-feedback toolbox supports the simulation of multiple spacecrafts, each with its own feedback control law. Thus, it is suitable to simulate and control large constellations of satellites, for instance.

Advantages of tudat-matlab-thrust-feedback over implementing a thrust feedback control law directly in the TUDAT application:

  • Faster and easier to debug and implement control laws in MATLAB
  • Fast and easy to implement the distributed computation of control laws for a large-number of spacecrafts (using the Parallel Computing Toolbox)
  • Run TUDAT and MATLAB application in separate machines (e.g. a computing server if the control-law evaluation is very intensive)
  • Novel control strategies are often developed in MATLAB

In few words:

Combine the high-fidelity fast propagation of TUDAT with the practicality of MATLAB


✍🏼 Authors

Leonardo Pedroso1 ORCID iD icon ORCID iD icon
Pedro Batista1 ORCID iD icon
1Institute for Systems and Robotics, Instituto Superior TΓ©cnico, Universidade de Lisboa, Portugal


✨ Contributors

Bruno MidΓ΅es github icon


πŸ“ž Contact

tudat-matlab-thrust-feedback toolbox is currently maintained by Leonardo Pedroso (leonardo.pedroso@tecnico.ulisboa.pt).


πŸ’Ώ Installation

To install tudat-matlab-thrust-feedback:

  • Clone or download the repository to the desired installation directory
  • Add folder src-tudat-matlab-thrust-feedback to the MATLAB path
addpath('[installation directory]/tudat-matlab-thrust-feedback/src-tudat-matlab-thrust-feedback');

🀝 Requisites

To use tudat-matlab-thrust-feedback:


πŸ“– Documentation

The documentation is divided into the following categories:

Setup thrust feedback in TUDAT

It is recommended to setup the thrust feedback in TUDAT from the template available in Example.

This template allows:

  • to define common MACROS between TUDAT and MATLAB in C header file
  • save the thrust data and spacecraft state automatically to a .mat file

For simulation data post-processing see Run a simulation.

The main steps for seting up the thrust feedback in TUDAT from sractch are shown below.

1. To include the tudat-matlab-thrust-feedback toolbox in the source code use:

#include "tudatThrustFeedbackMatlab.h"

2. Write the C++ TUDAT source for your application according to the documentation available.

3. To add thrust acceleration with feedback from MATLAB create a tudatThrustFeedbackMatlab object. The constructor follows

tudatThrustFeedbackMatlab( const unsigned int port, 
                           const unsigned int numberOfSatellites, 
                           const double epochControlUpdatePeriod,
                           const int evaluationsPerUpdatePeriod, 
                           const double isp_times_g0, 
                           double simulationEndEpoch = -1)

where

  • port: port of the local MATLAB server
  • numberOfSatellites: number of spacecrafts to provide thrust feedback
  • epochControlUpdatePeriod: interval of time between thrust feedback updates
  • evaluationsPerUpdatePeriod: number of numeric solver queries of the thrust vector per control sampling period
  • isp_times_g0: thruster specific impulse time standard gravity
  • simulationEndEpoch: epoch of simulation end (to display a progress bar)

Example: Create a tudatThrustFeedbackMatlab object

Macros:

// MATLAB server port
#define SERVER_PORT 6013
// Simulation end epoch (s)
#define EPOCH_END 1000
// Solver integration step (s)
#define EPOCH_SAMPLE 10
// Control update period (s)
#define EPOCH_CONTROL_UPDATE 10
// Thruster characteristics: Isp (s) and g0 (m/s^2)
#define SAT_ISP 1640
#define SAT_g0 9.81

Create tudatThrustFeedbackMatlab object using a fixed-step RK4 solver (5 queries per integration step)

// Select number of spacecraft
unsigned int numberOfSatellites = 1584;
// Create tudatThrustFeedbackMatlab object
std::shared_ptr <tudatThrustFeedbackMatlab> ttfm = 
    std::make_shared <tudatThrustFeedbackMatlab(SERVER_PORT,
                                                numberOfSatellites,
                                                EPOCH_CONTROL_UPDATE,
                                                5*EPOCH_CONTROL_UPDATE/EPOCH_SAMPLE,
                                                SAT_ISP*SAT_g0,
                                                EPOCH_END);

4. To setup the acceleration model for each spacecraft: First, assign sequential numeric ids to each spacecraft (starting at 0).

Second, bind a function for spacecraft i to thrustFeedbackWrapper method:

// Bind thrust feedback wrapper for each spacecraft
std::function <Eigen::Vector3d(const double)> thrustFeedbackSati =
    std::bind(&tudatThrustFeedbackMatlab::thrustFeedbackWrapper, 
              ttfm, 
              std::placeholders::_1,
              i,
              bodies.getMap());

where

  • bodies is the SystemOfBodies object of the simulation environment

Third, create a ThrustAccelerationSettings for each spacecraft with thrustFeedbackSati and add it to the acceleration map.

Example: Setup the acceleration models for a constellation of numberOfSatellitessatellites. Thrust defined in TNW frame relative to the Earth.

// ---------- Create planets objects ----------
SystemOfBodies bodies = (...)

// ---------- Create vehicle object ----------
std::string currentSatelliteName;
for (unsigned int i = 0; i < numberOfSatellites; i++){
    currentSatelliteName =  "sat" + boost::lexical_cast< std::string >(i);
    bodies.createEmptyBody(currentSatelliteName);
    bodies.at(currentSatelliteName) = std::make_shared< simulation_setup::Body >( );
}

// ---------- Setup acceleration models ----------
SelectedAccelerationMap accelerationMap;
std::vector <std::string> bodiesToPropagate;
std::vector <std::string> centralBodies;

// Set thrust accelerations for each satellite.
for ( unsigned int i = 0; i < numberOfSatellites; i++ ){
    currentSatelliteName = "sat" + boost::lexical_cast< std::string >( i );
    std::map<std::string, std::vector<std::shared_ptr<AccelerationSettings>>> accelerationsOfCurrentSatellite;
    // Set acceleration of gravity, solar radiation pressure, atmospheric drag, third body, ...
    // (...)
    std::function <Eigen::Vector3d(const double)> thrustFeedback = 
        std::bind(&tudatThrustFeedbackMatlab::thrustFeedbackWrapper, 
                  ttfm, 
                  std::placeholders::_1,
                  i,
                  bodies.getMap());
    accelerationsOfCurrentSatellite[currentSatelliteName] = 
        {std::make_shared<ThrustAccelerationSettings>(thrustFeedback,
                                                      SAT_ISP,
                                                      tnw_thrust_frame,
                                                      "Earth")};
    // Push satellite acceleration map
    accelerationMap[currentSatelliteName] = accelerationsOfCurrentSatellite;
    // Define body to propagate
    bodiesToPropagate.push_back(currentSatelliteName);
    // Define central body
    centralBodies.push_back("Earth");
}
// Create acceleration models and propagation settings
basic_astrodynamics::AccelerationMap accelerationModelMap = 
    createAccelerationModelsMap(bodies,accelerationMap,bodiesToPropagate,centralBodies);

See Example for a complete example.


Setup thrust feedback in MATLAB

It is recommended to setup the thrust feedback in MATLAB, from the template available in Example.

This template allows:

  • to define common MACROS between TUDAT and MATLAB in C header file
  • transition seamlessly between TUDAT simulation and a simplistic matlab simulation (for debug purposes)

The main steps for seting up the thrust feedback in MATLAB from sractch are shown below.

1. Setup MATLAB UDP server to listen for feedback requests

% Setup server
% Output position-velocity-mass as vector: flag = 0 | Output as matrix: flag = 1
tudat = tudatMatlabServer(port,addr,N,flag);
% Setup cleanup
tudatCleanUp = onCleanup(@()tudat.delete());
% Wait for tudat-app
tudat.waitForClient();

where

  • port: server port
  • addr: server address
  • N: number of spacecrafts
  • flag = 0: position-velocity-mass of all spacecraft is concatenated in a single vector for state feedback
  • flag = 1: position-velocity-mass of all spacecraft are the columns of matrix for state feedback

Example: Setup MATLAB UDP server

N = 1584;
port = 6013;
addr = '127.0.0.1';
% Setup server
tudat = tudatMatlabServer(port,addr,N,flag);
% Setup cleanup
tudatCleanUp = onCleanup(@()tudat.delete());
% Wait for tudat-app
tudat.waitForClient();

2. Wait for to feedback requests with

[t,x_t,state] = tudat.getRequest();

where

  • t: epoch of feedback request
  • x_t: state for feedback of all satellites (output defined by falg in step 1)
  • state: if $\neq 0$ TUDAT simulation is finished and the server may be terminated

3. Compute the actuation and send it to TUDAT with

% Implement control law
%u_t = f(t,x_t)  
% Send feedback
tudat.sendResponse(u_t); 

where

  • u_t: concatenation of the thrust vectors of all spacecrafts

4. Terminate the server using

if state 
    clear tudatCleanUp;
end

Run a simulation

To run a simulation, we simply have to:

  • compile TUDAT C++ app using the tudat-bundle
  • run the MATLAB script and setup the feedback server
  • afterwards, run the TUDAT executable

To automate this process a template of a makefile is available. To setup this makefile for your needs you have to set some variables in the beginning of the makefile:

# -------------- Set paths -----------------------------------------------------
# Matlab dirs
matlab-exe := /usr/local/MATLAB/R2021b/bin/matlab
# Tudat installation specific variables
tudat-bundle-dir := /mnt/nfs/home/lpedroso/tudat-bundle
# Tudat app specific variables
tudat-matlab-feedback-dir := ../src-tudat-matlab-thrust-feedback
cpp-src := tudat-app.cpp
matlab-feedback-src := matlab_app
matlab-check-control-cycles := 5
# ------------------------------------------------------------------------------

where

  • matlab-exe: path of MATLAB app
  • tudat-bundle-dir: path of tudat-bundle installation directory
  • tudat-matlab-feedback-dir: path of tudat-matlab-thrust-feedback toolbox source code
  • cpp-src: *.cpptudat app source code
  • matlab-feedback-src: *.m MATLAB script
  • matlab-check-control-cycles: number of control cycles to be run when testing matlab-feedback-src for errors

The available targets and their descriptions can be checked using

$ make help
all: 		 Compile tudat app
tudat:		 Compile tudat app
matlab-check: Perform matlab check
run: 		 Run tudat app and matlab server
run-tudat: 	 Run tudat app
output: 		 Save output results to .mat file and zip raw output files alongside with the source code and logs
clean: 		 Clean output results, logs, and compiled objects (.zip of past simualtions are not deleted)

To run a simulation makinh use of this makefile:

1. Compile TUDAT app with

$ make tudat
(...)
[100%] Linking CXX executable ../../bin/tudat-app
make[3]: Leaving directory '/mnt/nfs/home/lpedroso/tudat-bundle/build'
[100%] Built target tudat-app
make[2]: Leaving directory '/mnt/nfs/home/lpedroso/tudat-bundle/build'
make[1]: Leaving directory '/mnt/nfs/home/lpedroso/tudat-bundle/build'
cp /mnt/nfs/home/lpedroso/tudat-bundle/build/tudat/bin/tudat-app ./ # Retrieve app

Warning: Ignore the massive dump of warnings concerning the use of old-style cast during compilation

2. (Optional) Check matlab sript for errors:

$ make matlab-check 
@MATLAB server: Defining nominal constellation.
@MATLAB server: Retrieving simulation parameters.
@MATLAB server: Initializing thrust feedback controller.
@MATLAB server: Thrust feedback controller waiting for requests.
[======================================================================] 100.00 %
Elapsed time is 7.017307 seconds.

It runs a simulation propagated in MATLAB for $(matlab-check-control-cycles) as defined in the makefile to catch any errors in the MATLAB script.

3. Run the simulation:

$ make run
@Tudat: Creating MATLAB thrust feedback object for 30 satellites.
@Tudat: Entered establish connection UDP.
@Tudat: Sent ping.
@Tudat: MATLAB UDP connection established.
Started simulation.
Dependent variables being saved, output vector contains: 
Vector entry, Vector contents
[======================================================================] 100 %
Saving results.
Simulation complete.

A new terminal window is opens to run the MATLAB script, which outputs:

@MATLAB server: Setting up feedback server.
@MATLAB server: Starting MATLAB server.
@MATLAB server: Hosted at 127.0.0.1:6013.
@MATLAB server: Waiting for Tudat client.
@MATLAB server: Client connected.
@MATLAB server: Defining nominal constellation.
@MATLAB server: Retrieving simulation parameters.
@MATLAB server: Initializing thrust feedback controller.
@MATLAB server: Thrust feedback controller waiting for requests.
Elapsed time is 85.911747 seconds.
@MATLAB server: Thrust feedback controller has been terminated.

If the simulation is successfull:

  • status logs are available at /logs
  • the thrust force and state of each spacecraft for each interation step are saved as .dat files in /output

4. Process simulation results

To atomaticaly process the simulation results run

$ make output
(...)
adding: output/stateSat9.dat (deflated 56%)
adding: output/output.mat (deflated 0%)
adding: tudat-app.cpp (deflated 78%)
adding: tudat-matlab-parameters.h (deflated 60%)
adding: matlab_app.m (deflated 65%) 
adding: matlab_feedback_routine.m (deflated 33%)
adding: plot_simulation.m (deflated 67%) 
adding: makefile (deflated 63%)
adding: logs/cmake-tudat-app.log (deflated 85%)
adding: logs/get-tudat-output.log (deflated 69%)
adding: logs/matlab-check.log (deflated 71%)
adding: logs/run-matlab-server.log (deflated 70%)
adding: logs/run-tudat-app.log (deflated 99%)

The simulation results become available as

  • /output/output.mat with state and thrust evolution throughout the simulation
  • zip file in /output with all the raw simulation results and source code

5. (Optional) Clean simulation results

After having archived all the simulation results, you can delete

  • the TUDAT executable
  • the logs in /logs/
  • output results in /output

with

$ make clean
Do you really want to delete all output results, logs, and executables? [y/n]
y
rm -rf /mnt/nfs/home/lpedroso/tudat-bundle/tudat/tudat-applications/tudat-app # Clean build directory
rm -f tudat-app # Clean tudat-app
rm -f ./output/*.dat
rm -f ./output/*.mat
rm -f ./output/*.txt
rm -rf ./logs
rm -f *.asv

Warning: The .zip archives in /output are not deleted during make clean


πŸ¦† Example

The example in /example can be used a template to use the tudat-matlab-thrust-feedback toolbox. All the source files are thoroughly commented.

The C header /example/tudat-matlab-parameters.cpp is used to define a set of common macros used by TUDAT and MATLAB

The TUDAT source code /example/tudat-app.cpp is written according to Setup thrust feedback in TUDAT

The MATLAB feedback script is dived into two parts:

  • /example/matlab_app.m: setup server, simulation environment, and define controller parameters according to Setup thrust feedback in MATLAB
  • /example/matlab_feedback_routine.m: implement the control policy, i.e., compute the actuation of every spacecraft acording to the position-velocity-mass vectors and time-intant

For debug puposes, you can run the simulation directly in MATLAB with a simplistic propagation taking into account:

  • Point-mass gravity of the Earth
  • Effect of $J_2$
  • Linearized atmospheric drag

To run it:

  • set the variable tudatSimulation to false in /example/matlab_app.m
  • run script /example/matlab_app.m dirctely in MATLAB

In this example, a LEO constellation of 30 satellites is simulated. A dummy feedback law is used, which after half of an orbital period sets a constant thrust along the velocity vector.

The example can be run according to Run a simulation. The simulation results for satellite 13 are shown below

a_polar_sat13 a_sat13 e_sat13 i_sat13 Omega_sat13 m_sat13


✨ Contributing

The community is encouraged to contribute with

  • Suggestions
  • Addition of tools

To contribute to tudat-matlab-thrust-feedback


πŸ“„ License

MIT License


πŸ’₯ References

Pedroso, L., Batista, P. 2022. Distributed Decentralized Receding Horizon Control for Very Large-Scale Networks with Application to Satellite Mega-Constellations Station-Keeping [not published yet]

About

MATLAB server and interface that provides thrust feedback for a TUDAT application.

Resources

License

Stars

Watchers

Forks