-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathmain_code.m
More file actions
395 lines (305 loc) · 16.3 KB
/
main_code.m
File metadata and controls
395 lines (305 loc) · 16.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
%==========================================================================
% Interplanetary Trajectory Optimization for Planetary Defense Mission
% (Asteroid Kinetic Delfection)
%
% Lee Kin Thong
% Sept 22 2025
%==========================================================================
% You are free to use and modify the code, but you MUST cite the following
% papers:
%
% Lee, Kinthong, Hexi Baoyin, and Zhaokui Wang. "Trajectories optimization
% for asteroid kinetic deflection missions: Potential benefits of eccentric
% impacts." Acta Astronautica (2025).
%
% Lee, Kinthong, Zhengqing Fang, and Zhaokui Wang. "Investigation of the
% incremental benefits of eccentric collisions in kinetic deflection of
% potentially hazardous asteroids." Icarus 425 (2025): 116312.
%
% Feels free to contact me for any inquiry or cooperation!
% ktlee3819@gmail.com
%==========================================================================
% Deflecting Potentially Hazardous Asteroid (PHA) by using
% Impulsive-Continous-Low_Thrust Acceleration maneuver.
% Solve the opmiziming problem using Particle Swarm Optimization (PSO)
% The code is easily to be modified to solve any interplanetary trajectory
% optimization problem, by modifying the costfunction
%--------------------------------------------------------------------------
clear
% -------------------------------------------------------------------------
% --------------------------- Add Path ----------------------------------
% -------------------------------------------------------------------------
currentDir = fileparts(mfilename('fullpath'));
% Add all directory to path
addpath(genpath(currentDir))
% different path separators for Window(\), MacOS(/), and Linux(/)
if ispc
pathTosave = [fullfile(currentDir, 'output_result'),'\'];
else
pathTosave = [fullfile(currentDir, 'output_result'),'/'];
end
% Add path to kernel (to be used for SPICE)
% Specify the directory where your .bsp files are located
pathTokernel = fullfile(currentDir, 'code', 'kernel');
% -------------------------------------------------------------------------
% -------------------------------------------------------------------------
%-----------------------------Load Kernels---------------------------------
% -------------------------------------------------------------------------
% Load the kernels for SPICE
% Start the SPMD block for parallel execution (parloop)
spmd
% List all .bsp files in the directory
bspFiles = dir(fullfile(pathTokernel, '*.bsp'));
% List all .txt files in the directory
txtFiles = dir(fullfile(pathTokernel, '*.txt'));
% Combine the .bsp and .txt files into a single array
allFiles = [bspFiles; txtFiles];
% Iterate over all files to load them
for k = 1:length(allFiles)
% Construct the full path for each file
filePath = fullfile(pathTokernel, allFiles(k).name);
% Load the file using cspice_furnsh
cspice_furnsh(filePath);
end
end
% Load Kernels for non parfor loop
% List all .bsp files in the directory
bspFiles = dir(fullfile(pathTokernel, '*.bsp'));
% List all .txt files in the directory
txtFiles = dir(fullfile(pathTokernel, '*.txt'));
% Combine the .bsp and .txt files into a single array
allFiles = [bspFiles; txtFiles];
% Iterate over all files to load them
for k = 1:length(allFiles)
% Construct the full path for each file
filePath = fullfile(pathTokernel, allFiles(k).name);
% Load the file using cspice_furnsh
cspice_furnsh(filePath);
end
% -------------------------------------------------------------------------
% -------------------------------------------------------------------------
%------------------- Read data from PHA_table.xlsx ------------------------
% -------------------------------------------------------------------------
% Read PHA_table.xlsx
data = readtable('PHA_table');
% Extract PHA name and ID code
PHA_name = string(data.Object);
PHA_bsp = string(data.BSP_file_name); % example: 2099942: Apophis
% Extract year, month, and day from the 'Close_Approach_CA_Date' column
dateStrings = data.Close_Approach_CA_Date;
datePattern = '(\d{4})-(\w{3})-(\d{2})';
tokens = regexp(dateStrings, datePattern, 'tokens');
% Convert tokens to a matrix (each row corresponds to a match)
tokensMatrix = vertcat(tokens{:});
tokensMatrix = vertcat(tokensMatrix{:});
% Extract and convert each component
year_CA = str2double(tokensMatrix(:,1));
date_CA = str2double(tokensMatrix(:,3));
% Map the month abbreviations to month numbers and full names
monthAbbreviations = {'Jan', 'Feb', 'Mar', 'Apr', 'May', 'Jun', ...
'Jul', 'Aug', 'Sep', 'Oct', 'Nov', 'Dec'};
monthNumbers = 1:12;
monthFullNames = {'January', 'February', 'March', 'April', 'May', ...
'June', 'July', 'August', 'September', 'October', ...
'November', 'December'};
% Create containers.Map to map month abbreviations to month numbers
% and full names
monthNumMap = containers.Map(monthAbbreviations, monthNumbers);
monthNameMap = containers.Map(monthAbbreviations, monthFullNames);
% Convert month abbreviations to numbers and full names
month_CA_num = cell2mat(values(monthNumMap, tokensMatrix(:,2)));
month_CA_string = values(monthNameMap, tokensMatrix(:,2));
% -------------------------------------------------------------------------
% -------------------------------------------------------------------------
% --------------------------- Parameters ----------------------------------
% -------------------------------------------------------------------------
% Modify as your need
% Duration of Warning time
warning_years = 10; % years
% Parameters for collision model
PHA_mass = 2.7e10; % kg
beta = 3.61; % momentum enchancement coefficient
PHA_3D_model = 'Apophis_Model.obj'; % 3D Model of PHA
% Parameters for rocket
c_impulse = 3.09; % Exhaust velocity km/s, I = 315s
c_lowthrust = 29.78 ; % Exhaust velocity km/s I = 3035s
m0 = 10000; % Initial mass, kg
n0 = 18e-6 * 9.81 ; % thrust-to-mass ratio at t0, m/s^2
% Parameters for PSO
PSO_velocity_scale_factor = 0.5; % larger value for a highly dynamic systems.
ci = 1; % inertial weights, it will times (1+rand())/2 in PSO.m
cc = 1.49445; % cognitive weights, i will times rand() in PSO.m
cs = 1.49445; % social (stochastic) weights, it will times rand() in PSO.m
% -------------------------------------------------------------------------
% ----------------------------- Simulation --------------------------------
% -------------------------------------------------------------------------
% Simulation starts here:
% PHA number, as label in PHA_table.xlsx
for PHA = 1 : 1
% Is SOI date (the date PHA enter Earth's Sphere of Influence) available?
% if not, calculate it
if isnan(data.Date_SOI(PHA))
data.Date_SOI(PHA) = calculate_SOI(year_CA(PHA),month_CA_num(PHA),date_CA(PHA),PHA_bsp(PHA));
disp('done')
end
% COG or BIP strategy?
% 0 : 0, only COG strategy
% 1 : 1, only BIP strategy
% 0 : 1, for both COG & BIP, calculate COG first, then BIP
for is_BIP = 0 : 0
% ------------------------ Problem Definiton ------------------------------
problem.nVar = 17; % Number of Unknown (Decision) Variables
% Each particle's position has 17 dimensions, which in order:
% 5th polynomial coeffients of thetaIN、thetaOUT(12),
% Earth departure magnitude, RA angle, and DEC angle,
% launch date, impact date
% [thetaIN0, ..., thetaIN5, thetaOUT0, ..., thetaOUT5, Delta_V, RA,
% DEC, Mjday_launch, Mjday_impact]
% launch and impact date
launch_min = Mjday(year_CA(PHA) - warning_years, 1, 1);
launch_max = Mjday(year_CA(PHA), 1, 1);
impact_min = launch_min;
impact_max = launch_max;
% Calculate the Guess for thetaIN and thetaOUT coefficients
% thetaIN = thetaIN0 + thetaIN1 * t + thetaIN2* t^2 + ...
% + thetaIN5 * t^5
% Where the t is in unit of T_TU = 5022548.032 seconds,
% 2*PI T_TU = 365.25 days to avoid calculation exceed
% matlab's floating-point precision
thetaIN_coeff_value = [1e2, 1e1, 1e-2, 1e-3, 1e-4, 1e-5];
thetaOUT_coeff_value = [1e2, 1e1, 1e-2, 1e-3, 1e-4, 1e-5];
% The elements of position need to be bounded
% Min and Max value for Positions
problem.PositionMin = [-thetaIN_coeff_value, -thetaOUT_coeff_value, 0, -pi, -pi/2, launch_min, impact_min]; % Lower Bound of Decision Variables
problem.PositionMax = [thetaIN_coeff_value, thetaOUT_coeff_value, 20, pi, pi/2, launch_max, impact_max]; % Upper Bound of Decision Variables
% Min and Max value for Velocity
problem.VelocityMin = [-thetaIN_coeff_value.*PSO_velocity_scale_factor -thetaOUT_coeff_value.*PSO_velocity_scale_factor -5 -pi/2*PSO_velocity_scale_factor -pi/2*PSO_velocity_scale_factor -365 -365];
problem.VelocityMax = [thetaIN_coeff_value.*PSO_velocity_scale_factor thetaOUT_coeff_value.*PSO_velocity_scale_factor 5 pi/2*PSO_velocity_scale_factor pi/2*PSO_velocity_scale_factor 365 365];
% Target
problem.Target_name = char(PHA_name(PHA));
problem.Target = char(PHA_bsp(PHA)); % etc: 2099942 = Apophis
problem.mass_PHA = PHA_mass;
problem.date_SOI = data.Date_SOI(PHA); % Mjday
problem.date_CA = Mjday(year_CA(PHA),month_CA_num(PHA),date_CA(PHA));
problem.CA_distance = data.CADistanceMinimum_km_(PHA) * 1000 ; % m
% Parameters of collision model
problem.beta = beta;
problem.is_BIP = is_BIP;
problem.PHA_3D_model = PHA_3D_model;
% Read 3D models
[problem.vertices, problem.faces] = readObj(problem.PHA_3D_model);
% Parameter of engine
problem.c_impulse = c_impulse;
problem.c_lowthrust = c_lowthrust ;
problem.m0 = m0;
problem.n0 = n0 ;
% Cost Function J (or Objective Function)
% this cost_function.m is store in directory "code"
problem.CostFunction = @(x) cost_function(x,problem);
% Which strategy
if problem.is_BIP
strategy_name = 'BIP';
else
strategy_name = 'COG';
end
% Parameters of PSO
params.ci = ci;
params.cc = cc;
params.cs = cs;
% Parameters for First loop of PSO
params.MaxIte = 30; % Maximum Number of Iterations
params.nPop = 20; % Population Size (Swarm Size)
params.total_loops = 200; % Total loops
params.ShowIterInfo = false; % Flag for Showing Iteration Information
% Manually give value to one particle?
params.IsSpecificPosition = false;
% If true, give the specific position value to params.specificPosition:
% params.specificPosition is stored in (i x 17) format,
% where i represent the number of particles should be modified
% for example manually give one particle to a value:
% params.specificPosition = [1e+03,-1.07,-4.2e-03,1.6e-04,6.02e-05,-8.5e-06,-2.09e+02,-2.6,-3.8e-03,9.6e-04,6.2e-05,-9.9e-06,1.4,1e+00,-7e-01,5.9193023e+04,5.92893911e+04];
% -------------------------------------------------------------------------
% Display message
fprintf('Calculation for PHA %s with %s strategy starts:\n',PHA_name(PHA), strategy_name)
% Create empty
empty.pop = [];
empty.BestSol = [];
% ------------------ First loop of PSO, brief searching -------------------
fprintf('Calculating first loop for %s: \n', problem.Target_name)
out_first = repmat(empty, params.total_loops, 1);
DeflectionDistance_first = zeros(params.total_loops,1);
% Start timing
tic
for j = 1 : params.total_loops
% PSO run
out_first(j) = PSO(problem, params);
DeflectionDistance_first(j) = out_first(j).BestSol.DeflectionDistance;
% Progressbar
showProgress(j, params.total_loops)
end
% Index for Best Deflection Distance
[~,B1] = max(DeflectionDistance_first);
% Display Result
fprintf('Deflection Distance: %d , Interception Error: %d \n', out_first(B1).BestSol.DeflectionDistance, out_first(B1).BestSol.Interception);
% -------------------------------------------------------------------------
% -------------- Final loop of PSO, much detailed searching ---------------
% Plus minus 30 days of the best Launch Date as new search Date
% In this final loop, no need so much loops, usually one is enough
% higher nPop and MaxIte is set for final loop
% Manually give value to one particle?
params.IsSpecificPosition = true;
% Manually add the best position of first loop to one particle
params.specificPosition = out_first(B1).BestSol.Position;
params.total_loops = 1; % Total loops
params.MaxIte = 300; % Maximum Number of Iterations
params.nPop = 200;
params.ShowIterInfo = false; % Flag for Showing Iteration Informatin
fprintf('Calculation for final loop of PSO for %s starts: \n', problem.Target_name);
out_final = repmat(empty, params.total_loops, 1);
DeflectionDistance_final = zeros(params.total_loops,1);
for j = 1 : params.total_loops
% PSO run
out_final(j) = PSO(problem, params);
DeflectionDistance_final(j) = out_final(j).BestSol.DeflectionDistance;
end
% Index for best Deflection Distance
[~,B2] = max(DeflectionDistance_final);
% -------------------------------------------------------------------------
% Display result
fprintf('Deflection Distance: %d , Interception Error: %d \n', out_final(B2).BestSol.DeflectionDistance, out_final(B2).BestSol.Interception);
fprintf('\n')
% Store result into data
if problem.is_BIP
filename = [pathTosave,problem.Target_name, '_BIP.mat']; % Append .mat extension
% Convert Best Position to cell data
vectorAsString1 = sprintf('%.30e,', out_final(B2).BestSol.Position(1:16));
vectorAsString = ['[',vectorAsString1 sprintf('%.30e' , out_final(B2).BestSol.Position(17)),']'];
cellData = {vectorAsString};
data.BestPosition_BIP(PHA) = cellData;
data.BestDeflectionDistance_BIP(PHA) = out_final(B2).BestSol.DeflectionDistance;
data.Interception_Error_BIP(PHA) = out_final(B2).BestSol.Interception;
data.Interception_Angle_BIP(PHA) = out_final(B2).BestSol.InterceptionAngle;
data.Impact_Mass_BIP(PHA) = out_final(B2).BestSol.ImpactMass;
else
filename = [pathTosave,problem.Target_name, '_COG.mat']; % Append .mat extension
% Convert Best Position to cell data
vectorAsString1 = sprintf('%.30e,', out_final(B2).BestSol.Position(1:16));
vectorAsString = ['[',vectorAsString1 sprintf('%.30e' , out_final(B2).BestSol.Position(17)),']'];
cellData = {vectorAsString};
data.BestPosition_COG(PHA) =cellData;
data.BestDeflectionDistance_COG(PHA) = out_final(B2).BestSol.DeflectionDistance;
data.Interception_Error_COG(PHA) = out_final(B2).BestSol.Interception;
data.Interception_Angle_COG(PHA) = out_final(B2).BestSol.InterceptionAngle;
data.Impact_Mass_COG(PHA) = out_final(B2).BestSol.ImpactMass;
end
% save.mat file
save(filename,'out_final','out_first');
% Write table to .xlsx file (without relative Gain rate)
writetable(data,'temporary_result.xlsx')
end
toc
% Calculate Relative Gain rate
data.Gain_percent(PHA) = (data.BestDeflectionDistance_BIP(PHA) - data.BestDeflectionDistance_COG(PHA) ) / data.BestDeflectionDistance_COG(PHA) * 100;
% Write table to .xlsx file (with relative Gain rate)
writetable(data,'temporary_result.xlsx')
end