Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
213 commits
Select commit Hold shift + click to select a range
6813e5e
- Chopped the quaternion to force the unit norm constant using the q0…
pabloplataa Jul 23, 2025
dce1e50
Updated constants based on the initial ASTRA v2 prototype.
pabloplataa Jul 23, 2025
f796286
Addition of Jacobian functions
pabloplataa Jul 23, 2025
446d144
Added explicit Jacobian functions in preparation for EKF generation, …
pabloplataa Jul 28, 2025
74cd5b2
Updated Simulink Model, Added basic reference and input saturation fu…
pabloplataa Jul 28, 2025
6133c64
Working Controls!
pabloplataa Jul 28, 2025
b8db2fe
Fixed Trajectory Gen
pabloplataa Jul 28, 2025
af286d3
Added a basic measurement model and corrected the C matrix
pabloplataa Jul 29, 2025
13a4eaa
Full LQG Controlled Simulation, Need to add more disturbances and con…
pabloplataa Jul 29, 2025
f1813f6
Added bias estimation and augmented state vector (still does not prop…
pabloplataa Jul 29, 2025
109a643
Working Bias Estimation and Filter + Full Flight control
pabloplataa Jul 30, 2025
447acee
Update to Jacobian Linearization in filter.
pabloplataa Jul 30, 2025
0fb6839
Saving everything before EKFv2 Updates
pabloplataa Sep 1, 2025
a73549a
Update 1: Removed online accelerometer bias estimation. Added basic p…
pabloplataa Sep 1, 2025
f04fb19
Attempt to move torwards IMU for predict step
pabloplataa Sep 1, 2025
9faa033
Back to normal (thank god)
pabloplataa Sep 2, 2025
5090be7
Added measurement Jacobian Generation
pabloplataa Sep 4, 2025
e33808d
Updated function generation calls
pabloplataa Sep 4, 2025
8026d30
Updated filter (hope it fucking work)
pabloplataa Sep 4, 2025
55c64c9
Might have to become an M-EKF smh
pabloplataa Sep 5, 2025
f9145c8
Shit STILL doesn't work
pabloplataa Sep 6, 2025
39c35de
Added missing files
pabloplataa Sep 6, 2025
2b2993f
Starting work on new simulation!
pabloplataa Oct 3, 2025
7e7c7d5
Added trajectory files
pabloplataa Oct 3, 2025
ff03e29
Added Simulation Files!
pabloplataa Oct 3, 2025
44a3d52
Delete trajectory directory
pabloplataa Oct 3, 2025
3f7b4e0
Added files
pabloplataa Oct 3, 2025
338748f
Back to cont. time LQR.
pabloplataa Oct 3, 2025
464eb73
General Simulink Sim Structure Complete. Need to fill in gaps and com…
pabloplataa Oct 4, 2025
aa325dc
Final Missing File
pabloplataa Oct 4, 2025
a0a1f37
Running full state estimator and simulation
pabloplataa Oct 4, 2025
05ba1c3
Final touches
pabloplataa Oct 5, 2025
e712df1
Abort and Wind Sim
AndyL07 Oct 11, 2025
58bd65e
Idk
pabloplataa Oct 12, 2025
ae51f75
Merge commit 'e712df1825af0d93ee3a1cb530bef8f05aad8620'
pabloplataa Oct 12, 2025
b11ec50
Removed files that should've been untracked
pabloplataa Oct 12, 2025
f7344c7
General clean-up, ground mode for disturbances, controls corrections
pabloplataa Oct 12, 2025
e7f26cb
Controller retuning
pabloplataa Oct 12, 2025
78346ad
Gust Model
AndyL07 Oct 15, 2025
5d568db
Comments removed
pabloplataa Oct 15, 2025
427ca5a
Merge commit '78346adec850a77e3195ac5ee7ea117e35d3ae87'
pabloplataa Oct 15, 2025
bb64812
Updated wind modeling
pabloplataa Oct 15, 2025
f496e74
Updated Abort Mode Logic
pabloplataa Oct 15, 2025
75e17ca
Last Change
pabloplataa Oct 15, 2025
34b6888
Full Est. State Feedback!
pabloplataa Oct 16, 2025
c1bbd62
God how does this even work wtf
pabloplataa Oct 16, 2025
204fb30
EKF Testing
pabloplataa Oct 16, 2025
17a837d
Wind Torques
AndyL07 Oct 16, 2025
0f70f52
Merge branch 'ASTRAv2_Simulation' of https://github.com/activecontrol…
AndyL07 Oct 16, 2025
9e46399
Corrections in filter to deal with additional torque from wind. Infla…
pabloplataa Oct 16, 2025
b46845d
Fixed Lever Arm for TVC and retuned based on performance. Also change…
pabloplataa Oct 16, 2025
0471ab1
Final commit
pabloplataa Oct 16, 2025
0ecdfdf
Getting ready to nuke the M-EKF and remove ang. rates from error state
pabloplataa Oct 16, 2025
e980c48
WORKDAY CHANGES TO SIMULATION THEORY:
pabloplataa Oct 18, 2025
06cb7c1
Final Sim Updates
pabloplataa Oct 18, 2025
5197212
Commit
pabloplataa Oct 21, 2025
195b1c2
Renamed SimFiles folder to Simulation.
pabloplataa Oct 23, 2025
3614e0a
Added Solve Input file and modified dynamics slightly
pabloplataa Oct 23, 2025
324fbfa
Added Controls test to .SLX file. Retuned ref generator and changed G…
pabloplataa Oct 23, 2025
4b5b86c
Retuning and stuff
pabloplataa Oct 25, 2025
af9aa85
Attempting to add accelerometer biases to filter.
pabloplataa Oct 25, 2025
6c5ce58
start C++ conversion
RobertJN64 Oct 25, 2025
c2805a9
Current working version - revert to this if need be.
pabloplataa Oct 26, 2025
71a571e
WE'RE SO CLOSE
pabloplataa Oct 26, 2025
71fd13d
ALMOST FUCKING THEREEEE
pabloplataa Oct 26, 2025
36dc4a8
Close as I could get it
pabloplataa Oct 26, 2025
1b292e6
Have not cracked it yet lmao
pabloplataa Oct 26, 2025
47bbefc
15 state filter - revert here if needed.
pabloplataa Oct 26, 2025
c26c2d5
After a long and painful two days, filter convergence when tested out…
pabloplataa Oct 26, 2025
173ac8c
After way more work than I want to admit to, there's a working filter:
pabloplataa Oct 27, 2025
3a1ec0c
include sample data
ayushc121 Oct 27, 2025
373e209
tried adding functionality to run main on a set of simulated inputs t…
ayushc121 Oct 28, 2025
cb94deb
added P, forgot about that
ayushc121 Oct 28, 2025
f8b72a7
Update main.cpp
ayushc121 Oct 28, 2025
f6077d7
Starting work on new GPS sensor model
pabloplataa Oct 28, 2025
251f857
After a week of work on this, reverting back to the old filter. Also …
pabloplataa Oct 28, 2025
be9e440
Beautiful 16 state filter with accel bias and gyro bias. REVERT HERE …
pabloplataa Oct 29, 2025
a1343a7
Halfway done w conversion
pabloplataa Oct 29, 2025
e723335
Saving current state - attempting revert to working 12 state filter
pabloplataa Oct 29, 2025
e09ebb6
Ok let's just test out the 100% old filter and revert to this if need…
pabloplataa Oct 29, 2025
c81a32f
Old filter loaded, converting to full quaternion estimation
pabloplataa Oct 29, 2025
6f52bfe
Back to a full state simulation after a while. Filter still somewhat …
pabloplataa Oct 29, 2025
d3a448d
First flight config filter. This will be left untouched for a while -…
pabloplataa Oct 29, 2025
57e0947
WORKING FILTER. 100% CONFIRMED. HARD REVRT TO HERE IF YOU NEED TO.
pabloplataa Oct 29, 2025
56c7277
Ok please I'm tired of updating this fucking thing
pabloplataa Oct 29, 2025
ff6855a
ASTRAv2 Multicheckpoint flight test example.
pabloplataa Oct 29, 2025
7875a14
ASTRAv2 Multi-Checkpoint Flight Demonstration
pabloplataa Oct 29, 2025
ec5018f
Added Plotting function and other cool stuff
pabloplataa Oct 29, 2025
d38bfab
updated C++ filter conversion
RobertJN64 Oct 30, 2025
f309b41
cleanup included files
RobertJN64 Oct 30, 2025
0746c9c
Merge branch 'ASTRAv2_Simulation' into patch-1
RobertJN64 Oct 30, 2025
894a740
Merge pull request #3 from ayushc121/patch-1
RobertJN64 Oct 30, 2025
215e265
Added plotting
pabloplataa Oct 30, 2025
c4f006f
update test wrapper to use new filter inputs
RobertJN64 Oct 30, 2025
353a4d8
new packet detection system for matlab comparison testing
RobertJN64 Oct 30, 2025
afc318c
Merge commit '353a4d8176235c763939c0d0550d6d32e9085698'
pabloplataa Oct 30, 2025
e59c889
Filter and controls retuning. New plots!
pabloplataa Oct 31, 2025
a3f4ca4
Actuator Disturbance
AndyL07 Oct 31, 2025
20d7db1
Messing around with tuning and stuff!
pabloplataa Oct 31, 2025
3750dd8
Commit Workday!
pabloplataa Nov 1, 2025
39c8a3c
cleanup git, support portenta upload delay script
RobertJN64 Nov 1, 2025
99ed644
funcs to export a matlab run
RobertJN64 Nov 1, 2025
d24c99b
off by one error in filter, fix matrix exp, init R matrix correctly, …
RobertJN64 Nov 1, 2025
4ed13fe
update C++ filter to keep up with matlab
RobertJN64 Nov 1, 2025
9498c12
testing C++ filter on portenta
RobertJN64 Nov 1, 2025
1b91f34
fix performance issues on portenta
RobertJN64 Nov 4, 2025
cbc51be
Position set to absolute zero when grounded
pabloplataa Nov 4, 2025
1b8c71e
De-tuning GPS works!
pabloplataa Nov 4, 2025
ec98dc5
Addition of a GMP + EMA step for the wind disturbance model, as to ma…
pabloplataa Nov 4, 2025
4e99d2d
Addition of two filter modes (full INS when GPS available, pure in-fl…
pabloplataa Nov 4, 2025
c377181
Re-tested all three flight modes (INS.RTK, INS, INTEGRATOR) and updat…
pabloplataa Nov 5, 2025
37a6634
Working everything - revert here if need be, adding prediction step i…
pabloplataa Nov 5, 2025
a064021
Revert "Working everything - revert here if need be, adding predictio…
pabloplataa Nov 5, 2025
630075c
Back to normal
pabloplataa Nov 5, 2025
0b7d53f
Perfect filter tuning let's use this for now!
pabloplataa Nov 5, 2025
8dc0de2
RTK switches and fixed pure integrator. Now matches RMS theory
pabloplataa Nov 6, 2025
468f351
update C++ filter to keep up with matlab version
RobertJN64 Nov 8, 2025
721790f
bugfix: forgot to return x_est from C++ filter
RobertJN64 Nov 8, 2025
ab98d36
changes to allow for testing controller output against simulated matl…
ayushc121 Nov 8, 2025
548bb80
minor fixes to full controller simulation harness
RobertJN64 Nov 8, 2025
c586445
Renamed the State Estimation folder to "Filtering"
pabloplataa Nov 11, 2025
6e751dd
Merge commit '548bb80e45a5a569da5a8784c9c88283c5f0240e'
pabloplataa Nov 11, 2025
a969ec3
Addition of ANF Filter Design File and RollTest Data + Redux script
pabloplataa Nov 11, 2025
f4650f8
More data!
pabloplataa Nov 11, 2025
32ef833
One more
pabloplataa Nov 11, 2025
ac40555
Who is Fourier anyways?
pabloplataa Nov 12, 2025
3639d0e
Idk too many changes today I can't even anymore
pabloplataa Nov 12, 2025
679dcf7
Addition of a Digital Sequential Notch Filter. Added a sample test fi…
pabloplataa Nov 13, 2025
feea947
ANF Filter Stage added to .slx. Currently turnt off for debugging and…
pabloplataa Nov 13, 2025
2ec5385
Filter survives the ANF sequence. Still in true state mode for stabil…
pabloplataa Nov 13, 2025
5b86951
Inclusion of ANF-S v2 into .slx file. Kalman Filter seems stable even…
pabloplataa Nov 13, 2025
700d7d1
Retuned the ANF-S filter Channels.
pabloplataa Nov 14, 2025
7c7b206
Overtuned ANF-S purposefully. Introducing 4deg of phase evenly across…
pabloplataa Nov 14, 2025
fa29bb0
Added roll control disturbance to the ActuatorDynamics.m file, Increa…
pabloplataa Nov 15, 2025
fe568fa
Now targeting 5cm underground for landing to assure landing even with…
pabloplataa Nov 15, 2025
9ab1730
PLEASE FOR THE LOVE OF GOD REVERT TO THIS IF IT IS NOT WORKING IN THE…
pabloplataa Nov 15, 2025
fed39a5
M-EKF With MAG BIASES if need be, revert here if you need to use it i…
pabloplataa Nov 15, 2025
b582a47
Changes
pabloplataa Nov 15, 2025
8044f3e
Revert "PLEASE FOR THE LOVE OF GOD REVERT TO THIS IF IT IS NOT WORKIN…
pabloplataa Nov 15, 2025
2a381be
Revert "Now targeting 5cm underground for landing to assure landing e…
pabloplataa Nov 15, 2025
947469f
Back to normal!!!!!!
pabloplataa Nov 15, 2025
be133fe
Refactored stuff around in the Simulation Folder and added a Stabilit…
pabloplataa Nov 18, 2025
cd4b834
Stability Analysis update
pabloplataa Nov 19, 2025
7ca850a
What even is controls
pabloplataa Nov 19, 2025
d2d0131
Pushing updates to compare function
pabloplataa Nov 20, 2025
c87ae6d
catch up with C++ verification work
RobertJN64 Nov 20, 2025
b6e4eea
update cpp constants
RobertJN64 Nov 20, 2025
892574a
add C++ ref generator mode
RobertJN64 Nov 20, 2025
1da7f45
ANF converted to C++
RobertJN64 Nov 20, 2025
3dd9e01
digital notch filter verified
RobertJN64 Nov 21, 2025
5c86575
verified C++ controller with digital notch filter
RobertJN64 Nov 21, 2025
fd36b00
saved sim run
RobertJN64 Nov 21, 2025
e4e1fcb
rename .hpp to .h to match the astra software
RobertJN64 Nov 21, 2025
42172b7
Massive changes to the digital filtering sequence, we now have 1 adap…
pabloplataa Nov 21, 2025
8093650
UPDATED FILTER
pabloplataa Nov 21, 2025
303af2a
Merge commit 'e4e1fcbd762ef5566a4b476dc1d16e35329ac7dc'
pabloplataa Nov 21, 2025
3eb2463
MERGE CONFLICT
pabloplataa Nov 21, 2025
dfdc8d9
filter conversion - working with very very slight thrust mismatch
RobertJN64 Nov 21, 2025
ec15292
Changes to Nonlinear Controller functions, Stability Analysis now run…
pabloplataa Nov 21, 2025
f729335
Plot changes in Stab Analysis
pabloplataa Nov 21, 2025
1bcc564
finish filter comparisons after re-conv
RobertJN64 Nov 21, 2025
137fe46
Moving files into cpp folder
pabloplataa Nov 21, 2025
b999370
Tuning for initial ASTRAv2 flight tests, Addition of redux script v1
pabloplataa Nov 23, 2025
33a9d55
Redux commit
pabloplataa Nov 23, 2025
b712dd2
Entire redux script with all November 22nd Tests
pabloplataa Nov 23, 2025
12ba116
More commits!
pabloplataa Nov 23, 2025
5db9132
Updates to stability and baseline tuning!
pabloplataa Nov 24, 2025
836ebc4
Added file paths
pabloplataa Nov 24, 2025
4c295b9
RSA file
pabloplataa Nov 24, 2025
dd5f33f
Implemented genetic algorithm for stability optimization
Alex-Kaufmann Nov 26, 2025
c895327
.slx commit
pabloplataa Nov 27, 2025
2cca33c
Changes pending merge conflict
pabloplataa Nov 27, 2025
a1bbc56
Merge commit 'dd5f33f482cb6be0df70e319c85703bc08883603'
pabloplataa Nov 27, 2025
e1f53bc
Changes to .slx
pabloplataa Nov 27, 2025
7a24825
Addition of perturbed dynamics mode, aswell as some negative root pro…
pabloplataa Nov 27, 2025
fdf8ce2
Pending changes to add q0 to nominal dynamics
pabloplataa Nov 27, 2025
0923035
Updated EoM's to produce full quaternion (DON'T REVERT HERE THIS DOES…
pabloplataa Nov 27, 2025
549ce93
A bunch of runs of GA and some changes to the mutation funciton
Alex-Kaufmann Nov 27, 2025
ec1fd7a
Finalized conversion to a full quaternion plant simulation. Updated G…
pabloplataa Nov 28, 2025
66a4061
Merge branch 'ASTRAv2_Simulation' of https://github.com/activecontrol…
Alex-Kaufmann Nov 28, 2025
cd4f036
Merge branch 'ASTRAv2_Simulation' of https://github.com/activecontrol…
Alex-Kaufmann Nov 28, 2025
3671e44
Current state of things
pabloplataa Nov 28, 2025
45d2ba2
Merge commit 'cd4f036eb590e1ffa7b4a8ee6dc6e94600292f20'
pabloplataa Nov 28, 2025
322cf42
Virst draft of Controls v2 code
pabloplataa Nov 29, 2025
16561cb
Stable Controller v2!
pabloplataa Nov 29, 2025
471f839
Controls v2 Full Flight Simulation
pabloplataa Nov 29, 2025
f31cffc
Working v2 Control Pre Integral Gains
pabloplataa Nov 29, 2025
b7798a5
New controller!
pabloplataa Nov 30, 2025
51a4f51
v2 controller C++ conversion (not tested)
RobertJN64 Dec 2, 2025
21bf9de
v2 controller test logic with updated constants
RobertJN64 Dec 2, 2025
1bd6695
updated constant export
RobertJN64 Dec 2, 2025
e5e0557
verify controller v2
RobertJN64 Dec 2, 2025
e86c4ed
Finalized GA for old pure LQR approach
Alex-Kaufmann Dec 6, 2025
9e75f4b
Merge branch 'Genetic_Algorithm_Implementation' into ASTRAv2_Simulation
Alex-Kaufmann Dec 6, 2025
69470e2
Merge branch 'ASTRAv2_Simulation' of https://github.com/activecontrol…
Alex-Kaufmann Dec 6, 2025
5f9e56c
Slight dynamics fixes
pabloplataa Dec 6, 2025
5cac257
GA Fix Attempts + Dynamics Fix
pabloplataa Dec 6, 2025
e8d35ce
Close as I could get
pabloplataa Dec 6, 2025
3afaf85
New vehicle constants
pabloplataa Dec 6, 2025
d8d9545
Commit before merging Pablo's GA changes from ASTRAv2_Simulation
Alex-Kaufmann Dec 6, 2025
5ffb2ce
Merge branch 'ASTRAv2_Simulation' into Genetic_Algorithm_Implementation
Alex-Kaufmann Dec 6, 2025
b8fbce9
Small controller changes
pabloplataa Dec 6, 2025
1c20830
Fully integrated GA with new controller
Alex-Kaufmann Dec 6, 2025
d6c31b4
Merge branch 'ASTRAv2_Simulation' into Genetic_Algorithm_Implementation
Alex-Kaufmann Dec 6, 2025
93ad1f0
GA Run 3k Pop
pabloplataa Dec 6, 2025
bba30f6
Added Dec 6th Data
pabloplataa Dec 7, 2025
c5a9ddb
Added Dec 6th Data
pabloplataa Dec 7, 2025
2b86495
Huge updates to almost everything. Revert here is accel bias addition…
pabloplataa Dec 8, 2025
9484539
BIG UPDATE:
pabloplataa Dec 8, 2025
7eadc65
ANF fix!
pabloplataa Dec 8, 2025
04d273e
.slx Update
pabloplataa Dec 8, 2025
aeb0a02
Data Redux
pabloplataa Dec 8, 2025
369782c
Autotuner coded + some testing
pabloplataa Dec 9, 2025
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
28 changes: 0 additions & 28 deletions .gitattributes

This file was deleted.

2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,2 +1,4 @@
**/*.slxc
**/.DS_Store
**/.slprj
slprj
39 changes: 39 additions & 0 deletions Actuators/ActuatorDynamics.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
function xdot = ActuatorDynamics(x, u, GND)
xdot = zeros(6, 1);
% Simple actuator model
% x(1) Theta
% x(2) Rate 1
% x(3) Phi 2
% x(4) Rate 2
% x(5) Thrust
% x(6) Roll

% Assume identical servos for gimbal
a = 400;
b = 35;

k1 = 1;
k2 = 1;

theta_error = k1 * (1 - cos(x(1)));
phi_error = k2 * (1 - cos(x(3)));

x(3) = x(3) - theta_error;
x(1) = x(1) - phi_error;

xdot(1:4) = [x(2);
a*(u(1) - x(1)) - b*x(2);
x(4);
a*(u(2) - x(3)) - b*x(4)];

% Assume first order response for thrust
tau = 0.15;
xdot(5) = (1/tau) * (u(3) - x(5));

% Since torque depends on thrust changes on two fans, response time is
% half that of thrust. We artificially add an error to the applied
% input, proportional to the squared magnitude of the thrust pct
roll_error = 0.05 * (u(3) / (1.5 * 9.8))^2 * (1 - GND);
xdot(6) = (1/(tau/2)) * (u(4) + roll_error - x(6));

end
55 changes: 55 additions & 0 deletions Actuators/ActuatorTest.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,55 @@
% Test code for actuator modeling responses
clear;
close all;

% Initialize time for simulation
res = 5000;
tmax = 10;
dt = tmax / res;
tsim = linspace(0,tmax,res);
norm = [pi/24; pi/24; 14; 15];

% Target step response to max values
start = 100;
utrg = [zeros(4, start), norm .* ones(4, res - start)];
usim = zeros(4,res);
xsim = zeros(6,res);

% Initialize data tables
theta_target = zeros(1, res);
phi_target = zeros(1, res);
theta_actual = zeros(1, res);
phi_actual = zeros(1, res);

% Simulation loop
for i = 2:1:res
theta_target(i) = norm(1); %* cos(tsim(i) * 1);
phi_target(i) = norm(2) * sin(tsim(i) * 1) * 0;
utrg(1:2, i) = [theta_target(i); phi_target(i)];

xsim(:,i) = xsim(:,i-1) + ActuatorDynamics(xsim(:,i-1), utrg(:, i), 1) * dt;
usim(:,i) = [xsim(1,i); xsim(3,i); xsim(5:6,i)];

theta_actual(:, i) = xsim(1, i);
phi_actual(:, i) = xsim(3, i);
end

% Plot results
figure;
plot(tsim, usim .* [180/pi; 180/pi; 1; 1]); hold on; grid on;
plot(tsim, utrg .* [180/pi; 180/pi; 1; 1], 'r--');
% plot(tsim, (utrg - usim) .* [180/pi; 180/pi; 1; 1]);
legend('Angle 1', 'Angle 2', 'Thrust', 'Torque');

figure;
subplot(2, 1, 1)
plot(theta_target, theta_actual); grid on;
title("Theta Target vs Actual")

subplot(2, 1, 2)
plot(phi_target, phi_actual); grid on;
title("Phi Target vs Actual")

figure;
plot(xsim(1,:), xsim(3,:), "b*");
axis equal
134 changes: 134 additions & 0 deletions Controls/ASTRAv2_Controller.m
Original file line number Diff line number Diff line change
@@ -0,0 +1,134 @@
% Version 2 Controller formulation for ASTRAv2. Structure consists of 3
% cascaded loops.
%
% First Loop is a P Loop in charge of Pos -> Vel commands.
%
% Second loop is a PI Loop in charge of Vel -> Acceleration commands, fitted
% with anti-windup and soft-gatingcbased on attitude error.
%
% Second loop is an LQRi Loop in charge of Target Attitude -> Gimbal +
% Torque commands. Integral action is fitted with anti-windup clamps and is
% self soft-gated.
% Tuning of the second loop is done by using a Genetic algorithm to
% maximize a Crossover Frequency vs. Disk Margin tradeoff on all actuator
% channels.
%
% By: Pablo Plata - 11/27/25 (Happy Thanksgiving!)
function [U, VEI] = ASTRAv2_Controller(PosTarget, X, constantsASTRA, t)

% Time Counter
persistent lastT VelErrorI AttErrorI lastAttError
if isempty(lastT)
lastT = 0;
VelErrorI = zeros(3,1);
AttErrorI = zeros(3,1);
lastAttError = zeros(3,1);
end
dT = t - lastT;
lastT = t;
K_Att = constantsASTRA.K_Att;

% Controller Limits
thrustMax = 1.5 * 9.8; %N
gimbalMax = pi/18;
InputBounds = [-gimbalMax gimbalMax;
-gimbalMax gimbalMax;
.4 * thrustMax thrustMax;
-pi/6 pi/6];
U = zeros(4,1);

%% First Loop (P Loop)
% Position Error Vector
PosError = PosTarget - X(5:7);

% Velocity Command
K_P = [0.56; 0.56; 0.65];
VelTarget = K_P .* PosError;

% Velocity Saturation Step
MaxVel = [1 1 1.5]';
VelTarget = max(min(VelTarget, MaxVel), -MaxVel);

%% Second Loop (PI Loop)
% Velocity Error Vector
VelError = VelTarget - X(8:10);

% Integral Accumulator
K_I = [2.3; 2.3; 5];
Leak = 0.35;
Clamp = [5; 5; 5];

% Normalize errors (0 to 1 scale)
MaxAttError = [0.05; 0.05; 0.3];
MaxVelError = [0.3; 0.3; 0.3];
NormAttErr = abs(lastAttError) ./ MaxAttError;
NormVelErr = abs(VelError) ./ MaxVelError;

% Combine errors (Vector magnitude)
TotalErrorMetric = NormAttErr + NormVelErr;

% Calculate Gate using Gaussian function
Gate = (1 - Leak) * exp(-2 * TotalErrorMetric.^2) + Leak;

% Integrator
K_I = K_I .* Gate;
VelErrorI = VelErrorI + K_I .* VelError .* dT;
VelErrorI = max(min(VelErrorI, Clamp), -Clamp);
K_P = [3.2; 3.2; 3.5];

% Acceleration Target
AccelTarget = K_P .* VelError + VelErrorI + [0; 0; constantsASTRA.g];

% Acceleration Saturation Step
MaxAccelUp = [2 2 15]';
MaxAccelDown = [-2 -2 4]';
AccelTarget = max(min(AccelTarget, MaxAccelUp), MaxAccelDown);

%% Kinematics Step
% Compute thrust target
TargetForce_I = constantsASTRA.m * AccelTarget;
U(3) = norm(TargetForce_I);

% Compute target attitude via GSP.
AccelTarget(3) = max(AccelTarget(3), constantsASTRA.g);
Z_b = AccelTarget / norm(AccelTarget);

% Heading reference (+X axis rolled to north)
HDGRef = [1; 0; 0];
Y_b = cross(Z_b, HDGRef);
Y_b = Y_b / norm(Y_b);

% Complete the triad
X_b = cross(Y_b, Z_b);

% Create DCM and convert to quaternion
DCM = [X_b Y_b Z_b];
TargetAtt = DCM_Quat_Conversion(DCM);

%% Third Loop (LQRi)
% Attitude Error computation
Q_Conj = [X(1); -X(2:4)];
AttError = HamiltonianProd(Q_Conj) * TargetAtt;
if AttError(1) < 0
AttError = -AttError;
end
lastAttError = AttError(2:4);

% Error accumulation and clamping
Clamp = [3; 3; 0.4];
AttErrorI = AttErrorI + AttError(2:4) .* dT;
AttErrorI = max(min(AttErrorI, Clamp), -Clamp);

% State vector and error
X_Err = [-AttError(2:4); X(11:13); AttErrorI];

% LQR Controller
U([1 2 4]) = -K_Att * X_Err;

%% Controls Saturation
uMax = InputBounds(:, 2);
uMin = InputBounds(:, 1);
U = min(max(U, uMin), uMax);
VEI = VelTarget;


Loading