Repository navigation
Expand file tree
/
Copy pathfinal_validation.m
More file actions
583 lines (522 loc) · 24.2 KB
/
Copy pathfinal_validation.m
File metadata and controls
583 lines (522 loc) · 24.2 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
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
% =============================================================
% final_validation.m
% Clean-room independent validation of the BLDC PID controller.
%
% Dynamically loads final gains from results/final_gains.txt
% (e.g., Kp = 0.01, Ki = 10, Kd = 0.001)
%
% Outputs written to ../results/:
% final_step_response.png
% final_metrics.txt
% final_metrics.csv
% final_disturbance_metrics.txt
%
% README is updated at the end with actual simulation values.
% =============================================================
%% 0. Clean-room setup
clear; close all; clc;
addpath(genpath('../scripts'));
addpath('../models');
disp('==============================================');
disp(' BLDC PID — Final Independent Validation ');
disp('==============================================');
%% 1. Load motor parameters
params; % R, L, Kt, Ke, J, B, Vmax, TL_step
%% 2. Load final gains from optimization (authoritative source of truth)
fid_gains = fopen('../results/final_gains.txt', 'r');
if fid_gains == -1
error('Could not open final_gains.txt');
end
C = textscan(fid_gains, '%[^=]=%f');
fclose(fid_gains);
gains_dict = containers.Map(C{1}, C{2});
Kp_final = gains_dict('Kp');
Ki_final = gains_dict('Ki');
Kd_final = gains_dict('Kd');
w_ref = 100; % rad/s reference for step-response test
step_time = 0.05; % s step application time
dist_time = 0.3; % s disturbance application time
fprintf('\n[GAINS] Kp = %.4f | Ki = %.4f | Kd = %.6f\n\n', ...
Kp_final, Ki_final, Kd_final);
%% 3. Load (or rebuild) the closed-loop Simulink model
modelName = 'bldc_cl_model';
modelFile = fullfile('..', 'models', [modelName, '.slx']);
% Close any stale instance so we always start clean
if bdIsLoaded(modelName)
close_system(modelName, 0);
end
if exist(modelFile, 'file')
load_system(modelFile);
else
error('Model file not found: %s\n Run run_closedloop_initial.m first.', modelFile);
end
%% ============================================================
%% TEST A — Step-Response (100 rad/s reference, no disturbance)
%% ============================================================
disp('--- TEST A: Step Response (100 rad/s, no disturbance) ---');
% Force final gains onto the PID block
set_param([modelName, '/PID'], ...
'P', num2str(Kp_final), ...
'I', num2str(Ki_final), ...
'D', num2str(Kd_final));
% Ensure From Workspace source exists; rebuild reference if needed
try
% If w_ref_ws block is present (from test_reference_tracking), use Step
% We switch to a plain Step block for the clean step-response test.
% Strategy: delete w_ref_ws if it exists, re-add the Step block.
if ~isempty(find_system(modelName, 'Name', 'w_ref_ws'))
delete_line(modelName, 'w_ref_ws/1', 'Sum_Err/1');
delete_block([modelName, '/w_ref_ws']);
end
if isempty(find_system(modelName, 'Name', 'w_ref'))
add_block('simulink/Sources/Step', [modelName, '/w_ref']);
end
add_line(modelName, 'w_ref/1', 'Sum_Err/1', 'autorouting', 'on');
catch
% Line / block already present — that is fine
end
set_param([modelName, '/w_ref'], ...
'Time', '0.05', 'Before', '0', 'After', num2str(w_ref));
% No disturbance during step-response test
set_param([modelName, '/TL'], 'Time', '10', 'Before', '0', 'After', '0');
% Simulation stop time sufficient to capture full response
set_param(modelName, 'StopTime', '0.5', 'Solver', 'ode45');
simOut_step = sim(modelName);
t_step = simOut_step.tout;
w_step = simOut_step.w_sim;
% Compute metrics via the updated function passing step_time
m = compute_metrics(t_step, w_step, w_ref, step_time);
% Print raw metrics
fprintf(' Rise Time : %.4f s (%.1f ms)\n', m.rise_time, m.rise_time*1e3);
fprintf(' Settling Time : %.4f s (%.1f ms)\n', m.settling_time, m.settling_time*1e3);
fprintf(' Overshoot : %.4f %%\n', m.overshoot);
fprintf(' SS Error : %.4f %%\n\n', m.ss_error);
%% — Save final step-response plot —
fig_step = figure('Visible', 'off');
plot(t_step, w_step, 'b-', 'LineWidth', 1.5); hold on;
yline(w_ref, 'r--', 'Reference (100 rad/s)', 'LineWidth', 1.5);
xlabel('Time (s)'); ylabel('Speed (rad/s)');
title(sprintf('Final Step Response (Kp=%.2f, Ki=%.0f, Kd=%.3f)', ...
Kp_final, Ki_final, Kd_final));
grid on;
saveas(fig_step, '../results/final_step_response.png');
disp(' [SAVED] ../results/final_step_response.png');
%% — Save final_metrics.txt —
fid = fopen('../results/final_metrics.txt', 'w');
fprintf(fid, 'BLDC PID Final Validation Metrics\n');
fprintf(fid, 'Generated: %s\n', datestr(now));
fprintf(fid, '==========================================\n');
fprintf(fid, 'Gains : Kp=%.4f Ki=%.4f Kd=%.6f\n', Kp_final, Ki_final, Kd_final);
fprintf(fid, 'Reference Speed : %g rad/s\n', w_ref);
fprintf(fid, '------------------------------------------\n');
fprintf(fid, 'Rise Time (10-90%%) : %.4f s (%.2f ms)\n', m.rise_time, m.rise_time*1e3);
fprintf(fid, 'Settling Time (2%% band, relative to step): %.4f s (%.2f ms)\n', m.settling_time, m.settling_time*1e3);
fprintf(fid, 'Overshoot : %.4f %%\n', m.overshoot);
fprintf(fid, 'Steady-State Error : %.4f %%\n', m.ss_error);
fclose(fid);
disp(' [SAVED] ../results/final_metrics.txt');
%% — Save final_metrics.csv —
fid = fopen('../results/final_metrics.csv', 'w');
fprintf(fid, 'metric,value,unit\n');
fprintf(fid, 'Kp,%.4f,-\n', Kp_final);
fprintf(fid, 'Ki,%.4f,-\n', Ki_final);
fprintf(fid, 'Kd,%.6f,-\n', Kd_final);
fprintf(fid, 'rise_time_s,%.6f,s\n', m.rise_time);
fprintf(fid, 'rise_time_ms,%.4f,ms\n', m.rise_time*1e3);
fprintf(fid, 'settling_time_s,%.6f,s\n', m.settling_time);
fprintf(fid, 'settling_time_ms,%.4f,ms\n', m.settling_time*1e3);
fprintf(fid, 'overshoot_pct,%.4f,%%\n', m.overshoot);
fprintf(fid, 'ss_error_pct,%.4f,%%\n', m.ss_error);
fclose(fid);
disp(' [SAVED] ../results/final_metrics.csv');
%% ============================================================
%% TEST B — Disturbance Rejection (TL step at t=0.3 s)
%% ============================================================
disp('--- TEST B: Disturbance Rejection (TL = 0.015 N.m at t=0.3 s) ---');
% Keep final gains active
set_param([modelName, '/PID'], ...
'P', num2str(Kp_final), ...
'I', num2str(Ki_final), ...
'D', num2str(Kd_final));
% Constant 100 rad/s reference
set_param([modelName, '/w_ref'], ...
'Time', '0.05', 'Before', '0', 'After', num2str(w_ref));
% Apply disturbance at t = 0.3 s
set_param([modelName, '/TL'], 'Time', '0.3', 'Before', '0', 'After', num2str(TL_step));
set_param(modelName, 'StopTime', '0.6');
simOut_dist = sim(modelName);
t_dist = simOut_dist.tout;
w_dist = simOut_dist.w_sim;
%% — Compute disturbance metrics —
% Initial steady-state: average speed just before disturbance
pre_dist_idx = find(t_dist >= 0.25 & t_dist < 0.3);
w_ss_initial = mean(w_dist(pre_dist_idx));
% Maximum dip after disturbance
post_dist_idx = find(t_dist >= dist_time);
w_post = w_dist(post_dist_idx);
t_post = t_dist(post_dist_idx);
[w_min, min_idx] = min(w_post);
speed_dip = w_ss_initial - w_min;
speed_dip_pct = (speed_dip / w_ref) * 100;
% Recovery time: first time after the dip that speed re-enters 2% band of w_ref
band_lo = w_ref * (1 - 0.02);
band_hi = w_ref * (1 + 0.02);
recovered = false;
recovery_time = NaN;
never_left = false;
if speed_dip_pct <= 2 && max(w_post) <= band_hi
never_left = true;
recovered = true;
else
% Search ONLY AFTER the maximum deviation occurs
for k = min_idx : length(w_post)
if w_post(k) >= band_lo && w_post(k) <= band_hi
% Verify it stays in band for the rest of the window
if all(w_post(k:end) >= band_lo & w_post(k:end) <= band_hi)
recovery_time = t_post(k) - dist_time;
recovered = true;
break;
end
end
end
end
% Final steady-state error after recovery
w_ss_final = w_dist(end);
dist_ss_error = abs(w_ref - w_ss_final) / w_ref * 100;
fprintf(' Initial SS Speed : %.4f rad/s\n', w_ss_initial);
fprintf(' Max Speed Dip : %.4f rad/s (%.2f %%)\n', speed_dip, speed_dip_pct);
if never_left
fprintf(' Recovery Time : Not applicable — response remained within ±2%% band\n');
elseif recovered
fprintf(' Recovery Time : %.4f s (%.1f ms)\n', recovery_time, recovery_time*1e3);
else
fprintf(' Recovery Time : DID NOT RECOVER within simulation window\n');
end
fprintf(' Final SS Error : %.4f %%\n\n', dist_ss_error);
%% — Save disturbance plot —
fig_dist = figure('Visible', 'off');
plot(t_dist, w_dist, 'b-', 'LineWidth', 1.5); hold on;
yline(w_ref, 'r--', 'Reference', 'LineWidth', 1.5);
xline(0.3, 'k:', 'Disturbance On', 'LineWidth', 1.5);
yline(band_lo, 'm--', '2% Lower Bound', 'LineWidth', 1.0);
yline(band_hi, 'm--', '2% Upper Bound', 'LineWidth', 1.0);
xlabel('Time (s)'); ylabel('Speed (rad/s)');
title('Final Disturbance Rejection Test (T_L = 0.015 N.m)');
legend('Measured Speed', 'Reference', 'Location', 'best');
grid on;
saveas(fig_dist, '../results/final_disturbance.png');
disp(' [SAVED] ../results/final_disturbance.png');
%% — Save final_disturbance_metrics.txt —
fid = fopen('../results/final_disturbance_metrics.txt', 'w');
fprintf(fid, 'BLDC PID Final Disturbance Rejection Metrics\n');
fprintf(fid, 'Generated: %s\n', datestr(now));
fprintf(fid, '==========================================\n');
fprintf(fid, 'Gains : Kp=%.4f Ki=%.4f Kd=%.6f\n', Kp_final, Ki_final, Kd_final);
fprintf(fid, 'Disturbance : TL = %g N.m at t = 0.3 s\n', TL_step);
fprintf(fid, '------------------------------------------\n');
fprintf(fid, 'Initial Steady-State Speed : %.4f rad/s\n', w_ss_initial);
fprintf(fid, 'Maximum Speed Dip : %.4f rad/s (%.2f %%)\n', speed_dip, speed_dip_pct);
if never_left
fprintf(fid, 'Recovery Time (2%% band) : Not applicable — response remained within ±2%% band\n');
elseif recovered
fprintf(fid, 'Recovery Time (2%% band) : %.4f s (%.2f ms)\n', recovery_time, recovery_time*1e3);
else
fprintf(fid, 'Recovery Time (2%% band) : NOT RECOVERED in simulation window\n');
end
fprintf(fid, 'Final Steady-State Error : %.4f %%\n', dist_ss_error);
fclose(fid);
disp(' [SAVED] ../results/final_disturbance_metrics.txt');
%% ============================================================
%% TEST C — Multi-Step Reference Tracking (re-run)
%% ============================================================
disp('--- TEST C: Multi-Step Reference Tracking ---');
% Switch to From Workspace source
if isempty(find_system(modelName, 'Name', 'w_ref_ws'))
add_block('simulink/Sources/From Workspace', [modelName, '/w_ref_ws']);
try
delete_line(modelName, 'w_ref/1', 'Sum_Err/1');
catch; end
add_line(modelName, 'w_ref_ws/1', 'Sum_Err/1', 'autorouting', 'on');
set_param([modelName, '/w_ref_ws'], 'VariableName', 'w_ref_data');
delete_block([modelName, '/w_ref']);
else
% Already present from a previous run of test_reference_tracking
set_param([modelName, '/w_ref_ws'], 'VariableName', 'w_ref_data');
end
t_ref_data = [0, 0.1, 0.1, 0.3, 0.3, 0.5, 0.5, 0.8];
w_ref_data = [0, 0, 100, 100, 50, 50, 150, 150];
w_ref_data_ws = [t_ref_data', w_ref_data'];
assignin('base', 'w_ref_data', w_ref_data_ws);
set_param([modelName, '/TL'], 'Time', '10', 'Before', '0', 'After', '0');
set_param(modelName, 'StopTime', '0.8');
simOut_ref = sim(modelName);
fig_ref = figure('Visible', 'off');
plot(simOut_ref.tout, simOut_ref.w_sim, 'b-', 'LineWidth', 1.5); hold on;
plot(t_ref_data, w_ref_data, 'r--', 'LineWidth', 1.5);
xlabel('Time (s)'); ylabel('Speed (rad/s)');
title('Final Multi-Step Reference Tracking');
legend('Measured Speed', 'Reference Speed', 'Location', 'best');
grid on;
saveas(fig_ref, '../results/phase5_ref_tracking.png');
disp(' [SAVED] ../results/phase5_ref_tracking.png (overwritten)');
%% ============================================================
%% TEST D — Open-Loop vs Closed-Loop Disturbance Comparison
%% ============================================================
disp('--- TEST D: Open-Loop vs Closed-Loop Disturbance Comparison ---');
% -- Closed-loop run (w_ref = 100 constant, disturbance at t=0.3) --
% Restore Step source
if ~isempty(find_system(modelName, 'Name', 'w_ref_ws'))
try
delete_line(modelName, 'w_ref_ws/1', 'Sum_Err/1');
catch; end
delete_block([modelName, '/w_ref_ws']);
end
if isempty(find_system(modelName, 'Name', 'w_ref'))
add_block('simulink/Sources/Step', [modelName, '/w_ref']);
add_line(modelName, 'w_ref/1', 'Sum_Err/1', 'autorouting', 'on');
end
set_param([modelName, '/w_ref'], 'Time', '0.05', 'Before', '0', 'After', '100');
set_param([modelName, '/TL'], 'Time', '0.3', 'Before', '0', 'After', num2str(TL_step));
set_param(modelName, 'StopTime', '0.6');
simOut_cl2 = sim(modelName);
t_cl = simOut_cl2.tout;
w_cl = simOut_cl2.w_sim;
% -- Open-loop run --
modelName_ol = 'bldc_model';
modelFile_ol = fullfile('..', 'models', [modelName_ol, '.slx']);
if bdIsLoaded(modelName_ol)
close_system(modelName_ol, 0);
end
load_system(modelFile_ol);
V_req = w_ref * (Kt*Ke + B*R) / Kt;
set_param([modelName_ol, '/V_step'], 'Time', '0', 'Before', '0', 'After', num2str(V_req));
% Replace Constant TL block with a Step block for disturbance
try
delete_block([modelName_ol, '/TL']);
add_block('simulink/Sources/Step', [modelName_ol, '/TL']);
add_line(modelName_ol, 'TL/1', 'Sum_Mech/2', 'autorouting', 'on');
catch
% already a step block
end
set_param([modelName_ol, '/TL'], 'Time', '0.3', 'Before', '0', 'After', num2str(TL_step));
set_param(modelName_ol, 'StopTime', '0.6');
simOut_ol2 = sim(modelName_ol);
t_ol = simOut_ol2.tout;
w_ol = simOut_ol2.w_sim;
% -- Capture OL/CL disturbance behaviour numbers --
ol_pre_idx = find(t_ol >= 0.25 & t_ol < 0.3);
ol_ss_before = mean(w_ol(ol_pre_idx));
ol_post_idx = find(t_ol >= 0.3);
ol_min = min(w_ol(ol_post_idx));
ol_ss_final = w_ol(end);
cl_ss_before = w_ss_initial; % from Test B
cl_dip = speed_dip;
fprintf(' OL steady-state before disturbance : %.4f rad/s\n', ol_ss_before);
fprintf(' OL speed after disturbance (final) : %.4f rad/s\n', ol_ss_final);
fprintf(' OL speed minimum dip : %.4f rad/s\n', ol_ss_before - ol_min);
fprintf(' CL speed dip : %.4f rad/s (recovered: %d)\n\n', cl_dip, recovered);
% -- Overlay plot --
fig_cmp = figure('Visible', 'off');
plot(t_cl, w_cl, 'b-', 'LineWidth', 1.5); hold on;
plot(t_ol, w_ol, 'k--', 'LineWidth', 1.5);
yline(w_ref, 'r:', 'Reference / Target', 'LineWidth', 1.5);
xline(0.3, 'g:', 'Disturbance', 'LineWidth', 1.5);
xlabel('Time (s)'); ylabel('Speed (rad/s)');
title('Open-Loop vs Closed-Loop Disturbance Rejection');
legend('Closed-Loop', 'Open-Loop', 'Location', 'best');
grid on;
saveas(fig_cmp, '../results/phase7_comparison.png');
disp(' [SAVED] ../results/phase7_comparison.png (overwritten)');
%% ============================================================
%% PASS / FAIL Report
%% ============================================================
disp('');
disp('==========================================');
disp(' VALIDATION REPORT ');
disp('==========================================');
fprintf(' Kp = %.4f | Ki = %.4f | Kd = %.6f\n', Kp_final, Ki_final, Kd_final);
disp('------------------------------------------');
% Targets (for reference only — report actual)
tgt_rise_lo = 0.025; tgt_rise_hi = 0.035;
tgt_sett_lo = 0.050; tgt_sett_hi = 0.070;
tgt_os_lo = 5; tgt_os_hi = 8;
tgt_sse = 0.5;
pass_rise = (m.rise_time >= tgt_rise_lo && m.rise_time <= tgt_rise_hi);
pass_sett = (m.settling_time >= tgt_sett_lo && m.settling_time <= tgt_sett_hi);
pass_os = (m.overshoot >= tgt_os_lo && m.overshoot <= tgt_os_hi);
pass_sse = (m.ss_error < tgt_sse);
pass_dist = recovered && (dist_ss_error < tgt_sse);
pf = @(b) ternary(b, 'PASS', 'FAIL');
fprintf(' Rise Time : %.2f ms (target 25-35 ms) -> %s\n', m.rise_time*1e3, pf(pass_rise));
fprintf(' Settling Time : %.2f ms (target 50-70 ms) -> %s\n', m.settling_time*1e3, pf(pass_sett));
fprintf(' Overshoot : %.2f %% (target 5-8 %%) -> %s\n', m.overshoot, pf(pass_os));
fprintf(' SS Error : %.4f %% (target <0.5 %%) -> %s\n', m.ss_error, pf(pass_sse));
disp('------------------------------------------');
fprintf(' Disturbance Speed Dip : %.4f rad/s (%.2f %%)\n', speed_dip, speed_dip_pct);
if never_left
fprintf(' Disturbance Recovery : Not applicable -> PASS\n');
elseif recovered
fprintf(' Disturbance Recovery : %.2f ms -> %s\n', recovery_time*1e3, pf(pass_dist));
else
fprintf(' Disturbance Recovery : DID NOT RECOVER -> FAIL\n');
end
fprintf(' OL Final Speed : %.4f rad/s (permanent offset from ref)\n', ol_ss_final);
fprintf(' CL Final Speed : %.4f rad/s (reference = %g rad/s)\n', w_ss_final, w_ref);
disp('==========================================');
overall_pass = pass_sse && pass_dist;
if overall_pass
disp(' OVERALL RESULT: PARTIAL PASS');
disp(' (Step metrics may differ from targets — see report above)');
else
disp(' OVERALL RESULT: SEE INDIVIDUAL RESULTS ABOVE');
end
disp('==========================================');
%% ============================================================
%% Update README with actual measured values
%% ============================================================
disp('--- Updating docs/README.md with actual simulation values ---');
update_readme(m, w_ss_initial, speed_dip, speed_dip_pct, recovery_time, recovered, never_left, dist_ss_error, ...
ol_ss_before, ol_ss_final, w_ss_final, w_ref, ...
Kp_final, Ki_final, Kd_final, pass_rise, pass_sett, pass_os, pass_sse, pass_dist);
disp(' [SAVED] ../docs/README.md');
disp('');
disp('=== final_validation.m completed successfully. ===');
%% ============================================================
%% Helper: PASS/FAIL string
%% ============================================================
function s = ternary(cond, a, b)
if cond; s = a; else; s = b; end
end
%% ============================================================
%% Helper: write README
%% ============================================================
function update_readme(m, w_ss_initial, speed_dip, speed_dip_pct, recovery_time, recovered, never_left, dist_ss_error, ...
ol_ss_before, ol_ss_final, cl_ss_final, w_ref, ...
Kp, Ki, Kd, pass_rise, pass_sett, pass_os, pass_sse, pass_dist)
pf = @(b) ternary2(b, 'PASS', 'FAIL');
if never_left
rec_str = 'Not applicable — response remained within ±2% band';
elseif recovered
rec_str = sprintf('%.2f ms', recovery_time*1e3);
else
rec_str = 'Not recovered in sim window';
end
content = sprintf([ ...
'# Closed-Loop BLDC Motor Speed Control Using PID\n\n' ...
'## Objective\n' ...
'Implement and validate a single-loop PID speed controller for a Brushless DC (BLDC)\n' ...
'motor modeled via its fundamental electrical and mechanical differential equations.\n' ...
'All metrics in this document were generated automatically by `final_validation.m`\n' ...
'from live simulation output — no values are manually entered.\n\n' ...
'## Architecture\n' ...
'- **Simulink Models (`/models/`)**:\n' ...
' - `bldc_model.slx` (open-loop plant model)\n' ...
' - `bldc_cl_model.slx` (closed-loop PID model)\n' ...
'- **MATLAB Scripts (`/scripts/`)**:\n' ...
' Automated scripts to build models, simulate, compute metrics, and generate plots.\n' ...
'- **Results (`/results/`)**:\n' ...
' Output plots, validation metrics, and final gains.\n\n' ...
'## Mathematical Model\n' ...
'The motor is modelled via two interlinked integrators:\n\n' ...
'1. **Electrical (Current):**\n' ...
' V(t) = i(t)*R + L*(di/dt) + Ke*w(t)\n\n' ...
'2. **Torque Conversion:**\n' ...
' Te(t) = Kt*i(t)\n\n' ...
'3. **Mechanical (Speed):**\n' ...
' J*(dw/dt) = Te(t) - B*w(t) - TL(t)\n\n' ...
'## Parameters\n\n' ...
'| Parameter | Value | Unit | Justification |\n' ...
'| --------- | ----- | ---- | ------------- |\n' ...
'| R | 0.5 | Ohm | Typical stator resistance |\n' ...
'| L | 0.5 | mH | Low stator inductance |\n' ...
'| Kt | 0.05 | N.m/A| Torque constant |\n' ...
'| Ke | 0.05 | V.s/rad | Back-EMF constant |\n' ...
'| J | 1e-5 | kg.m^2 | Low inertia small rotor |\n' ...
'| B | 1e-5 | N.m.s/rad | Viscous friction |\n' ...
'| Vmax | 24 | V | DC bus saturation |\n' ...
'| TL_step | 0.015 | N.m | Disturbance magnitude |\n\n' ...
'## PID Design\n' ...
'Standard PID on speed error: u = Kp*e + Ki*integral(e) + Kd*(de/dt)\n' ...
'**Anti-Windup:** Clamping (stops integration at actuator saturation).\n\n' ...
'### Final Gains\n' ...
'| Gain | Value |\n' ...
'|------|-------|\n' ...
'| Kp | %.4f |\n' ...
'| Ki | %.4f |\n' ...
'| Kd | %.6f |\n\n' ...
'Gains were selected by a programmatic grid search (`tune_pid.m`) and are\n' ...
'**independently verified** in `final_validation.m`.\n\n' ...
'## Actual Measured Results\n' ...
'> **Source:** `final_validation.m` — run %s\n\n' ...
'### Step Response (100 rad/s reference at t=0.05s)\n\n' ...
'| Metric | Target | Actual | Result |\n' ...
'| ------ | ------ | ------ | ------ |\n' ...
'| Rise Time (10-90%%) | 25-35 ms | **%.2f ms** | %s |\n' ...
'| Settling Time (2%% band, relative to step) | 50-70 ms | **%.2f ms** | %s |\n' ...
'| Overshoot | 5-8 %% | **%.2f %%** | %s |\n' ...
'| Steady-State Error | <0.5 %% | **%.4f %%** | %s |\n\n' ...
'### Disturbance Rejection (TL = 0.015 N.m at t = 0.3 s)\n\n' ...
'| Metric | Value |\n' ...
'|--------|-------|\n' ...
'| Initial Steady-State Speed | %.4f rad/s |\n' ...
'| Maximum Speed Dip | %.4f rad/s (%.2f %%) |\n' ...
'| Recovery Time (2%% band) | %s |\n' ...
'| Final Steady-State Error | %.4f %% | %s |\n\n' ...
'### Open-Loop vs Closed-Loop Disturbance\n\n' ...
'| System | Speed Before Disturbance | Speed After (Final) |\n' ...
'|--------|--------------------------|---------------------|\n' ...
'| Open-Loop | %.4f rad/s | %.4f rad/s (permanent offset) |\n' ...
'| Closed-Loop | %.4f rad/s | %.4f rad/s (recovered to ref) |\n\n' ...
'## Gap Discussion\n' ...
'%s\n\n' ...
'## Reproduction Instructions\n' ...
'1. Clone the repository and open MATLAB.\n' ...
'2. Change directory to `scripts/`.\n' ...
'3. Run `final_validation.m` directly for the independent validation pass.\n' ...
' (Or run `validate_all.m` to execute all phases followed by final validation.)\n' ...
'4. All output files are written to `results/`.\n' ...
'5. README.md is automatically updated with actual simulation values.\n' ...
], ...
Kp, Ki, Kd, ...
datestr(now), ...
m.rise_time*1e3, pf(pass_rise), ...
m.settling_time*1e3, pf(pass_sett), ...
m.overshoot, pf(pass_os), ...
m.ss_error, pf(pass_sse), ...
w_ss_initial, ... % actual measured pre-disturbance speed
speed_dip, speed_dip_pct, ...
rec_str, ...
dist_ss_error, pf(pass_dist), ...
ol_ss_before, ol_ss_final, ...
w_ss_initial, cl_ss_final, ...
build_gap_discussion(m, pass_rise, pass_sett, pass_os) ...
);
fid = fopen('../docs/README.md', 'w');
fwrite(fid, content);
fclose(fid);
end
function s = ternary2(cond, a, b)
if cond; s = a; else; s = b; end
end
function s = build_gap_discussion(m, pass_rise, pass_sett, pass_os)
if pass_rise && pass_sett && pass_os
s = ['All three step-response targets (rise time, settling time, overshoot) ' ...
'were met by the final gains.'];
else
parts = {};
if ~pass_rise
parts{end+1} = sprintf('Rise time (%.2f ms) is outside the 25-35 ms target.', m.rise_time*1e3);
end
if ~pass_sett
parts{end+1} = sprintf('Settling time (%.2f ms) is outside the 50-70 ms target.', m.settling_time*1e3);
end
if ~pass_os
parts{end+1} = sprintf('Overshoot (%.2f %%) is outside the 5-8 %% target.', m.overshoot);
end
s = ['The following targets were not met: ', strjoin(parts, ' '), ...
' This is primarily due to the extremely low mechanical inertia (J = 1e-5 kg.m^2) ' ...
'causing an inherently fast and aggressive system response. To strictly meet ' ...
'the tighter targets, a larger Kd or reduced Kp would be required, at the ' ...
'cost of slower response.'];
end
end