-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathGRIM_GUI.m
More file actions
2117 lines (1970 loc) · 88.5 KB
/
Copy pathGRIM_GUI.m
File metadata and controls
2117 lines (1970 loc) · 88.5 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
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
% ************************************************************
% GRIM(TM) - Generic Restoration Intelligent Milestone
% Version 3.0.0 (2026)
%
% A tool of the GriRes(TM) Suite
% (Grid Resilience Suite)
%
% Copyright (c) 2017-2026 Francis Yunhe Hou
% SPDX-License-Identifier: GPL-3.0-or-later
%
% Author: Dr. Francis Yunhe Hou
% Contact: yunhe.hou@gmail.com
% Website: https://github.com/GriRes/GRIM
%
% ============================================================
% LICENSE
% ============================================================
% This program is free software: you can redistribute it and/or
% modify it under the terms of the GNU General Public License as
% published by the Free Software Foundation, either version 3 of
% the License, or (at your option) any later version.
%
% This program is distributed in the hope that it will be useful,
% but WITHOUT ANY WARRANTY; without even the implied warranty of
% MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
% GNU General Public License for more details.
%
% You should have received a copy of the GNU General Public License
% along with this program. If not, see <https://www.gnu.org/licenses/>.
%
% DUAL LICENSING:
% This software is also available under a commercial license for
% closed-source or proprietary use where GPL terms cannot be met.
% Contact: yunhe.hou@gmail.com
%
% ============================================================
% AI-ASSISTED DEVELOPMENT NOTICE
% ============================================================
% Portions of this software were developed with the assistance of
% AI-based programming tools (including OpenAI ChatGPT, Anthropic
% Claude, and xAI Grok). All AI-generated code has been reviewed,
% tested, and validated by the author. The author assumes full
% responsibility for the correctness and quality of the final code.
%
% ============================================================
% HERITAGE & EVOLUTION
% ============================================================
% GRIM v3.0 is the open-source continuation and significant
% evolution of prior work on power system restoration decision
% support tools. It builds directly upon the Generic Restoration
% Milestone (GRM) methodology, originally developed and published in:
%
% Y. Hou et al., "Computation of Milestones for Decision Support
% during System Restoration," IEEE Trans. Power Syst., vol. 26,
% no. 3, pp. 1399-1409, Aug. 2011.
%
% Previous implementations include:
% HITS (Healing Touch for Power Systems) - open-source MATLAB
% toolbox, versions 1.0 and 2.0, developed by Prof. Zhijun Qin,
% released under the permissive 3-clause BSD license.
%
% ============================================================
% CITATION
% ============================================================
% If you use this software, please cite BOTH:
% [1] Y. Hou, C.-C. Liu, K. Sun, P. Zhang, S. Liu, and
% D. Mizumura, "Computation of Milestones for Decision
% Support during System Restoration," IEEE Trans. Power
% Syst., vol. 26, pp. 1399-1409, 2011.
% [2] K. Sun, Y. Hou, W. Sun, and J. Qi, Power System Control
% Under Cascading Failures, John Wiley & Sons, 2019.
%
% GRIM(TM) and GriRes(TM) are trademarks of Francis Yunhe Hou.
% ************************************************************
function GRIM_GUI()
% GRIM_GUI Unified control centre for the GRIM restoration toolbox
%
% Copyright (c) 2017-2026 Dr. Francis Yunhe Hou
% SPDX-License-Identifier: GPL-3.0-or-later
%% ===== Locate GRIM root =====
grimRoot = fileparts(mfilename('fullpath'));
if isempty(grimRoot), grimRoot = pwd; end
gridDataDir = fullfile(grimRoot, 'GridData');
monDir = fullfile(grimRoot, 'Monitoring');
%% ===== Application state =====
S.systems = {};
S.sysIdx = 1;
S.sysName = '';
S.running = false;
S.Grid = [];
S.hasResults = false;
S.modes = {'backtrack','greedy'};
S.modeNames = {'Backtrack (tries alternatives)', ...
'Greedy (fast single-path)'};
S.hCon = [];
S.animating = false;
S.animIdx = 0;
S.solveInfo = '';
S.childFigs = [];
S.solveTimer = [];
S.progFig = []; % uifigure for progress dialog
S.solveStartTic = [];
addpath(fullfile(grimRoot,'Config')); % ensure GRIM_Config is on path
S.config = GRIM_Config(); % solver configuration (passed as override)
scanSystems();
%% ===== Colour palette =====
C.bg = [0.067 0.075 0.102];
C.side = [0.086 0.098 0.133];
C.panel = [0.106 0.118 0.157];
C.card = [0.133 0.149 0.192];
C.input = [0.114 0.129 0.169];
C.accent = [0.000 0.545 0.647];
C.green = [0.118 0.573 0.345];
C.amber = [0.839 0.514 0.075];
C.red = [0.745 0.235 0.188];
C.blue = [0.149 0.447 0.776];
C.purple = [0.404 0.275 0.675];
C.txt = [0.843 0.867 0.910];
C.dim = [0.431 0.471 0.537];
C.menuTxtIdle = [0.65 0.68 0.74]; % brighter idle colour for menu labels
C.bdr = [0.176 0.196 0.255];
C.con = [0.043 0.051 0.071];
C.w = [1 1 1];
C.mile = [0.910 0.682 0.137];
C.load = [0.850 0.280 0.450];
resClrs = {C.accent,C.accent,C.mile,C.mile,C.mile,...
C.blue,C.blue,C.green,C.load};
C.btnMain = [0.235 0.537 0.635];
C.btnMainT = [1 1 1];
C.btnGray = [0.141 0.173 0.220];
C.btnTxt = [0.902 0.929 0.965];
C.btnViewT = [0.749 0.890 0.933];
C.btnDataT = [0.839 0.635 0.227];
C.btnExit = [0.557 0.247 0.271];
C.btnExitT = [0.750 0.420 0.440];
C.menuBg = [0.094 0.106 0.145];
C.menuHov = [0.133 0.149 0.192];
C.menuTxt = [0.843 0.867 0.910];
C.menuDrop = [0.114 0.129 0.169];
C.menuSep = [0.176 0.196 0.255];
%% ===== Main window =====
scr = get(0,'ScreenSize');
FW = min(1380, scr(3)-40);
FH = min(840, scr(4)-80);
fig = figure( ...
'Name',['GRIM' char(8482) ' v3.0.0 — Generic Restoration Intelligent Milestone'], ...
'NumberTitle','off','MenuBar','none','ToolBar','none', ...
'Color',C.bg,'Resize','off','DockControls','off', ...
'Position',[(scr(3)-FW)/2 (scr(4)-FH)/2 FW FH], ...
'CloseRequestFcn',@onCloseFig);
%% ===== Custom menu bar (modern flat style with hover) =====
MENU_H = 28;
menuY = FH - MENU_H;
uipanel(fig,'Units','pixels','Position',[0 menuY FW MENU_H], ...
'BackgroundColor',C.menuBg,'BorderType','none');
% Thin bottom accent line
uipanel(fig,'Units','pixels','Position',[0 menuY FW 1], ...
'BackgroundColor',[0.20 0.22 0.28],'BorderType','none');
% Menu definitions with icons (char(0) = no icon placeholder)
menuDefs = { ...
'File', 50, {
[char(9881) ' Generate Data...'], @(~,~)dataGenDlg()
'---', []
[char(9998) ' Edit System Data...'], @onDataEdit
'---', []
[char(10005) ' Exit Ctrl+Q'], @onExitBtn
}
'Settings', 68, {
[char(9881) ' Solver Settings...'], @onSettings
'---', []
[char(9851) ' Clear Monitoring Data...'], @onClearMonitoring
}
'Analysis', 74, {
[char(9654) ' Restoration Strategy Ctrl+R'], @onRun
'---', []
[char(9733) ' Power Trajectory'], @onPowerPlot
[char(9632) ' Step Viewer'], @onStepViewer
[char(9788) ' HTML Viewer...'], @onGenViewer
'---', []
[char(9776) ' View Report'], @onOpenReport
}
'Help', 46, {
[char(9432) ' User Guide'], @(~,~)userGuideDlg()
'---', []
[char(9679) ' About GRIM'], @(~,~)aboutDlg()
[char(10070) ' Citation Info'], @(~,~)citeDlg()
}
};
S.menuPanels = {};
S.menuBtns = {};
S.menuItemH = {}; % cell of arrays: item handles per menu
S.menuItemCB = {}; % cell of arrays: callbacks per menu
mx = 8;
ITEM_H = 26;
ITEM_FS = 10;
TOP_FS = 10;
SEP_H = 5;
for mi = 1:size(menuDefs,1)
label = menuDefs{mi,1};
mw = menuDefs{mi,2};
items = menuDefs{mi,3};
% Top-level button: minimal text, no visual button appearance
hBtn = uicontrol(fig,'Style','text','String',label, ...
'Position',[mx menuY+1 mw MENU_H-2], ...
'FontSize',TOP_FS,'FontName','Segoe UI','FontWeight','normal', ...
'BackgroundColor',C.menuBg,'ForegroundColor',C.menuTxtIdle, ...
'HorizontalAlignment','center','Enable','inactive', ...
'ButtonDownFcn',@(src,evt)toggleMenu(mi));
nItems = size(items, 1);
nSep = sum(cellfun(@(x)strcmp(x,'---'), items(:,1)));
nReal = nItems - nSep;
dropH = nReal * ITEM_H + nSep * SEP_H + 8;
dropW = 310;
dropX = max(mx, 2);
dropY = menuY - dropH;
hDrop = uipanel(fig,'Units','pixels', ...
'Position',[dropX dropY dropW dropH], ...
'BackgroundColor',C.menuDrop,'BorderType','line', ...
'HighlightColor',[0.22 0.24 0.30],'Visible','off');
itemH = [];
itemCB = {};
iy = dropH - 4;
for ii = 1:nItems
iLabel = items{ii,1};
iCB = items{ii,2};
if strcmp(iLabel,'---')
iy = iy - SEP_H;
uipanel(hDrop,'Units','pixels', ...
'Position',[12 iy+SEP_H/2-1 dropW-24 1], ...
'BackgroundColor',[0.20 0.22 0.28],'BorderType','none');
else
iy = iy - ITEM_H;
hItem = uicontrol(hDrop,'Style','text', ...
'String',[' ' iLabel], ...
'Position',[4 iy dropW-8 ITEM_H], ...
'FontSize',ITEM_FS,'FontName','Segoe UI', ...
'BackgroundColor',C.menuDrop,'ForegroundColor',C.menuTxt, ...
'HorizontalAlignment','left','Enable','inactive', ...
'ButtonDownFcn',@(src,evt)menuItemClick(mi, iCB, src, evt));
itemH(end+1) = hItem; %#ok<AGROW>
itemCB{end+1} = iCB; %#ok<AGROW>
end
end
S.menuBtns{mi} = hBtn;
S.menuPanels{mi} = hDrop;
S.menuItemH{mi} = itemH;
S.menuItemCB{mi} = itemCB;
mx = mx + mw + 2;
end
set(fig,'WindowButtonDownFcn',@onFigClick);
set(fig,'WindowButtonMotionFcn',@onFigMotion);
S.lastHoverItem = []; % track last highlighted item to reduce flicker
function toggleMenu(idx)
vis = get(S.menuPanels{idx},'Visible');
closeAllMenus();
if strcmp(vis,'off')
uistack(S.menuPanels{idx},'top');
set(S.menuPanels{idx},'Visible','on');
set(S.menuBtns{idx},'BackgroundColor',C.menuHov, ...
'ForegroundColor',C.menuTxt,'FontWeight','bold');
end
end
function menuItemClick(menuIdx, cb, src, evt) %#ok<INUSL>
closeAllMenus();
if ~isempty(cb), cb(src, evt); end
end
function closeAllMenus()
for ci2 = 1:numel(S.menuPanels)
set(S.menuPanels{ci2},'Visible','off');
set(S.menuBtns{ci2},'BackgroundColor',C.menuBg, ...
'ForegroundColor',C.menuTxtIdle,'FontWeight','normal');
end
% Reset hover state
if ~isempty(S.lastHoverItem) && ishandle(S.lastHoverItem)
set(S.lastHoverItem,'BackgroundColor',C.menuDrop, ...
'ForegroundColor',C.menuTxt);
end
S.lastHoverItem = [];
end
function onFigMotion(~,~)
% Hover highlighting for open dropdown items
if ~ishandle(fig); return; end
try
cp = get(fig,'CurrentPoint');
newHover = [];
for cm = 1:numel(S.menuPanels)
if ~ishandle(S.menuPanels{cm}); continue; end
if strcmp(get(S.menuPanels{cm},'Visible'),'on')
ppos = get(S.menuPanels{cm},'Position');
for ci = 1:numel(S.menuItemH{cm})
h = S.menuItemH{cm}(ci);
if ~ishandle(h); continue; end
ip = get(h,'Position');
% Convert item coords to figure coords
ax = ppos(1) + ip(1);
ay = ppos(2) + ip(2);
if cp(1)>=ax && cp(1)<=ax+ip(3) && ...
cp(2)>=ay && cp(2)<=ay+ip(4)
newHover = h;
break;
end
end
break; % only one menu open at a time
end
end
% Update highlight
changed = false;
if isempty(newHover) && isempty(S.lastHoverItem)
changed = false;
elseif isempty(newHover) || isempty(S.lastHoverItem)
changed = true;
elseif newHover ~= S.lastHoverItem
changed = true;
end
if changed
if ~isempty(S.lastHoverItem) && ishandle(S.lastHoverItem)
set(S.lastHoverItem,'BackgroundColor',C.menuDrop, ...
'ForegroundColor',C.menuTxt);
end
if ~isempty(newHover) && ishandle(newHover)
set(newHover,'BackgroundColor',[0.18 0.20 0.26], ...
'ForegroundColor',[1 1 1]);
end
S.lastHoverItem = newHover;
end
catch
% Silently ignore stale-handle errors during hover
end
end
function onFigClick(~,~)
cp = get(fig,'CurrentPoint');
for ci3 = 1:numel(S.menuPanels)
if strcmp(get(S.menuPanels{ci3},'Visible'),'on')
pos = get(S.menuPanels{ci3},'Position');
if cp(1)>=pos(1) && cp(1)<=pos(1)+pos(3) && ...
cp(2)>=pos(2) && cp(2)<=pos(2)+pos(4), return; end
bpos = get(S.menuBtns{ci3},'Position');
if cp(1)>=bpos(1) && cp(1)<=bpos(1)+bpos(3) && ...
cp(2)>=bpos(2) && cp(2)<=bpos(2)+bpos(4), return; end
end
end
closeAllMenus();
end
%% ===== Keyboard shortcuts =====
set(fig,'KeyPressFcn',@onKeyPress);
function onKeyPress(~,evt)
if ismember('control', evt.Modifier)
switch lower(evt.Key)
case 'q', onExitBtn([],[]);
case 'r', onRun([],[]);
end
end
end
%% ===== Header =====
HH = 72; SBH = 32; HDR_TOP = menuY;
uipanel(fig,'Units','pixels','Position',[0 HDR_TOP-3 FW 3], ...
'BackgroundColor',C.accent,'BorderType','none');
uipanel(fig,'Units','pixels','Position',[20 HDR_TOP-HH-2 FW-40 1], ...
'BackgroundColor',C.bdr,'BorderType','none');
%% ===== Status bar =====
uipanel(fig,'Units','pixels','Position',[0 0 FW SBH], ...
'BackgroundColor',C.side,'BorderType','none');
uipanel(fig,'Units','pixels','Position',[0 SBH FW 1], ...
'BackgroundColor',C.bdr,'BorderType','none');
S.hStat = uicontrol(fig,'Style','text','String','Ready', ...
'Position',[14 5 400 20],'FontSize',9,'FontName','Segoe UI', ...
'ForegroundColor',C.green,'BackgroundColor',C.side,'HorizontalAlignment','left');
if exist('loadcase','file'), mpT='MATPOWER: OK'; mpC=C.green;
else, mpT='MATPOWER: not found'; mpC=C.amber; end
uicontrol(fig,'Style','text','String',mpT, ...
'Position',[FW-200 5 180 20],'FontSize',9,'FontName','Segoe UI', ...
'ForegroundColor',mpC,'BackgroundColor',C.side,'HorizontalAlignment','right');
S.hNSys = uicontrol(fig,'Style','text', ...
'String',sprintf('Systems: %d',numel(S.systems)), ...
'Position',[FW-420 5 200 20],'FontSize',9,'FontName','Segoe UI', ...
'ForegroundColor',C.dim,'BackgroundColor',C.side,'HorizontalAlignment','right');
%% ===== Sidebar =====
cTop = HDR_TOP-HH-6; cBot = SBH+6; cH = cTop-cBot;
SX = 16; SW = 264;
uipanel(fig,'Units','pixels','Position',[SX cBot SW cH], ...
'BackgroundColor',C.side,'BorderType','line','HighlightColor',C.bdr);
bw = SW-32; yy = cBot+cH-36;
sideHdr(SX+16,yy,'SYSTEM');
yy = yy-28;
S.hSysPop = uicontrol(fig,'Style','popupmenu', ...
'String',sysPopList(),'Value',max(1,S.sysIdx), ...
'Position',[SX+16 yy bw 26],'FontSize',10,'FontName','Segoe UI', ...
'BackgroundColor',C.input,'ForegroundColor',C.txt,'Callback',@onSysChange);
yy = yy-32;
uicontrol(fig,'Style','pushbutton','String','Refresh List', ...
'Position',[SX+16 yy bw 28],'FontSize',9,'FontName','Segoe UI', ...
'BackgroundColor',C.btnGray,'ForegroundColor',C.btnTxt,'Callback',@onRefresh);
yy = yy-38;
sideHdr(SX+16,yy,'SOLVER MODE');
yy = yy-28;
S.hModePop = uicontrol(fig,'Style','popupmenu', ...
'String',S.modeNames,'Value',1, ...
'Position',[SX+16 yy bw 26],'FontSize',9,'FontName','Segoe UI', ...
'BackgroundColor',C.input,'ForegroundColor',C.txt);
yy = yy-34;
sideHdr(SX+16,yy,'CONFIG PROFILE');
yy = yy-28;
S.hCfgPop = uicontrol(fig,'Style','popupmenu', ...
'String',{'Default'},'Value',1, ...
'Position',[SX+16 yy bw 26],'FontSize',9,'FontName','Segoe UI', ...
'BackgroundColor',C.input,'ForegroundColor',C.txt, ...
'Callback',@onCfgProfileChange);
refreshCfgProfiles();
yy = yy-38;
sideHdr(SX+16,yy,'ANALYSIS');
btnsA = {
[char(9654) ' Generate Restoration Strategy'], C.btnMain, @onRun, 44, C.btnMainT
'Power Trajectory', C.btnGray, @onPowerPlot, 34, C.btnViewT
'Step Viewer', C.btnGray, @onStepViewer, 34, C.btnViewT
'HTML Viewer', C.btnGray, @onGenViewer, 34, C.btnViewT
'View Report', C.btnGray, @onOpenReport, 34, C.btnViewT
};
S.hBtnSolve = gobjects(1);
for k = 1:size(btnsA,1)
bh = btnsA{k,4}; yy = yy-bh-6;
hb = uicontrol(fig,'Style','pushbutton','String',btnsA{k,1}, ...
'Position',[SX+16 yy bw bh], ...
'FontSize',10,'FontWeight','bold','FontName','Segoe UI', ...
'BackgroundColor',btnsA{k,2},'ForegroundColor',btnsA{k,5}, ...
'Callback',btnsA{k,3});
if k==1, S.hBtnSolve = hb; end
end
yy = yy-20;
sideHdr(SX+16,yy,'DATA TOOLS');
btnsD = {
'Edit System Data', C.btnGray, @onDataEdit, 34, C.btnDataT
'Generate New Data', C.btnGray, @(~,~)dataGenDlg(), 34, C.btnDataT
};
for k = 1:size(btnsD,1)
bh = btnsD{k,4}; yy = yy-bh-6;
uicontrol(fig,'Style','pushbutton','String',btnsD{k,1}, ...
'Position',[SX+16 yy bw bh], ...
'FontSize',10,'FontWeight','bold','FontName','Segoe UI', ...
'BackgroundColor',btnsD{k,2},'ForegroundColor',btnsD{k,5}, ...
'Callback',btnsD{k,3});
end
uicontrol(fig,'Style','pushbutton','String',[char(10006) ' Exit GRIM'], ...
'Position',[SX+16 cBot+30 bw 34], ...
'FontSize',10,'FontWeight','bold','FontName','Segoe UI', ...
'BackgroundColor',C.btnExit,'ForegroundColor',C.btnExitT, ...
'Callback',@onExitBtn);
uicontrol(fig,'Style','text','String',[char(169) ' 2017-2026 Dr. Francis Yunhe Hou'], ...
'Position',[SX+16 cBot+8 bw 14],'FontSize',7,'FontName','Segoe UI', ...
'ForegroundColor',C.dim,'BackgroundColor',C.side,'HorizontalAlignment','center');
%% ===== Main content area =====
MX = SX+SW+12; MW = FW-MX-16;
sumH = 108; sumY = cBot+cH-sumH;
uipanel(fig,'Units','pixels','Position',[MX sumY MW sumH], ...
'Title',' SYSTEM OVERVIEW ','FontSize',9,'FontWeight','bold','FontName','Segoe UI', ...
'TitlePosition','lefttop','ForegroundColor',C.accent,'BackgroundColor',C.panel, ...
'HighlightColor',C.bdr);
cardL = {'Buses','Generators','Lines','Transformers','BS Gens','Critical Ld','Disp. Ld'};
nc = numel(cardL); cg = 6; cw = floor((MW-20-(nc-1)*cg)/nc); ch = sumH-42;
S.hCard = gobjects(1,nc);
for k = 1:nc
cx = MX+10+(k-1)*(cw+cg); cy = sumY+8;
uipanel(fig,'Units','pixels','Position',[cx cy cw ch], ...
'BackgroundColor',C.card,'BorderType','none');
uicontrol(fig,'Style','text','String',cardL{k}, ...
'Position',[cx+2 cy+ch-20 cw-4 14],'FontSize',7,'FontName','Segoe UI', ...
'ForegroundColor',C.dim,'BackgroundColor',C.card,'HorizontalAlignment','center');
S.hCard(k) = uicontrol(fig,'Style','text','String','--', ...
'Position',[cx+2 cy+4 cw-4 30],'FontSize',16,'FontWeight','bold','FontName','Consolas', ...
'ForegroundColor',C.txt,'BackgroundColor',C.card,'HorizontalAlignment','center');
end
resH = 100; resY = sumY-8-resH;
S.hResPanel = uipanel(fig,'Units','pixels','Position',[MX resY MW resH], ...
'Title',' RESULTS SUMMARY ','FontSize',9,'FontWeight','bold','FontName','Segoe UI', ...
'TitlePosition','lefttop','ForegroundColor',C.mile,'BackgroundColor',C.panel, ...
'HighlightColor',C.bdr);
resL = {'Steps','Time(min)','M1: Start','M2: Crank','M3: MinOut', ...
'Buses On','Gens On','Gen(pu)','Load(pu)'};
nr = numel(resL); rg = 5; rw = floor((MW-20-(nr-1)*rg)/nr); rh = resH-42;
S.hRes = gobjects(1,nr);
for k = 1:nr
rx = MX+10+(k-1)*(rw+rg); ry = resY+8;
uipanel(fig,'Units','pixels','Position',[rx ry rw rh], ...
'BackgroundColor',C.card,'BorderType','none');
uicontrol(fig,'Style','text','String',resL{k}, ...
'Position',[rx+2 ry+rh-18 rw-4 12],'FontSize',7,'FontName','Segoe UI', ...
'ForegroundColor',C.dim,'BackgroundColor',C.card,'HorizontalAlignment','center');
S.hRes(k) = uicontrol(fig,'Style','text','String','--', ...
'Position',[rx+2 ry+2 rw-4 26],'FontSize',14,'FontWeight','bold','FontName','Consolas', ...
'ForegroundColor',C.dim,'BackgroundColor',C.card,'HorizontalAlignment','center');
end
banH = 30; banY = resY-6-banH;
uipanel(fig,'Units','pixels','Position',[MX banY MW banH], ...
'BackgroundColor',C.panel,'BorderType','line','HighlightColor',C.bdr);
S.hOutcome = uicontrol(fig,'Style','text', ...
'String',' No results yet — run solver to generate', ...
'Position',[MX+6 banY+3 MW-12 banH-6], ...
'FontSize',11,'FontWeight','bold','FontName','Segoe UI', ...
'ForegroundColor',C.dim,'BackgroundColor',C.panel,'HorizontalAlignment','left');
conY = cBot; conH = banY-6-conY;
uipanel(fig,'Units','pixels','Position',[MX conY MW conH], ...
'Title',' CONSOLE ','FontSize',9,'FontWeight','bold','FontName','Segoe UI', ...
'TitlePosition','lefttop','ForegroundColor',C.accent,'BackgroundColor',C.panel, ...
'HighlightColor',C.bdr);
conIX = MX+6; conIY = conY+6; conIW = MW-12; conIH = conH-32;
S.hCon = uicontrol(fig,'Style','listbox', ...
'Max',2,'Min',0,'Value',[], ...
'String',welcomeText(), ...
'Position',[conIX conIY conIW conIH], ...
'FontSize',9,'FontName','Consolas', ...
'ForegroundColor',C.green,'BackgroundColor',C.con,'Enable','on');
%% ===== Header text with logo =====
logoFile52 = fullfile(grimRoot,'Config','grim_logo_52.png');
txtX = 28; % default if no logo
if exist(logoFile52,'file')
logoErr = '';
logoImg52 = [];
try logoImg52 = imread(logoFile52);
catch ME, logoErr = ['imread: ' ME.message]; end
if isempty(logoErr) && ~isempty(logoImg52)
try
imgH = size(logoImg52,1); imgW = size(logoImg52,2);
% Position axes to match actual image aspect ratio
axY = HDR_TOP - HH + round((56-imgH)/2) + 2;
hLogoAx = axes('Parent',fig,'Units','pixels', ...
'Position',[22 axY imgW imgH], ...
'Visible','off');
image('CData',logoImg52,'Parent',hLogoAx);
set(hLogoAx,'XTick',[],'YTick',[], ...
'XLim',[0.5 imgW+0.5],'YLim',[0.5 imgH+0.5], ...
'YDir','reverse','Visible','off');
uistack(hLogoAx,'top');
txtX = 22 + imgW + 6;
catch ME, logoErr = ['axes/image: ' ME.message];
end
end
if ~isempty(logoErr)
fprintf('GRIM_GUI logo: %s\n', logoErr);
end
else
fprintf('GRIM_GUI logo: file not found: %s\n', logoFile52);
end
% GRIM (large) + TM (superscript)
uicontrol(fig,'Style','text','String','GRIM', ...
'Position',[txtX HDR_TOP-HH+14 150 52], ...
'FontSize',32,'FontWeight','bold','FontName','Consolas', ...
'ForegroundColor',C.accent,'BackgroundColor',C.bg,'HorizontalAlignment','left');
uicontrol(fig,'Style','text','String',char(8482), ...
'Position',[txtX+122 HDR_TOP-HH+40 30 22], ...
'FontSize',14,'FontWeight','bold','FontName','Segoe UI', ...
'ForegroundColor',C.accent,'BackgroundColor',C.bg,'HorizontalAlignment','left');
uicontrol(fig,'Style','text','String','Generic Restoration Intelligent Milestone', ...
'Position',[txtX+170 HDR_TOP-HH+28 430 22], ...
'FontSize',13,'FontWeight','bold','FontName','Segoe UI', ...
'ForegroundColor',C.txt,'BackgroundColor',C.bg,'HorizontalAlignment','left');
uicontrol(fig,'Style','text', ...
'String',['V3.0.0 | A tool of the GriRes' char(8482) ' Suite (Grid Resilience Suite)'], ...
'Position',[txtX+170 HDR_TOP-HH+8 500 18], ...
'FontSize',9,'FontName','Segoe UI', ...
'ForegroundColor',C.dim,'BackgroundColor',C.bg,'HorizontalAlignment','left');
%% ===== Initial setup =====
setupPaths();
if ~isempty(S.systems)
S.sysName = S.systems{S.sysIdx};
loadSystemInfo();
end
%% ============================================================
%% CALLBACKS
%% ============================================================
% ---- Settings menu callbacks ----
function refreshCfgProfiles()
cfgDir2 = fullfile(grimRoot, 'Config');
items = {'Default'};
if exist(cfgDir2,'dir')
mats = dir(fullfile(cfgDir2, '*.mat'));
for km = 1:length(mats)
[~, fn] = fileparts(mats(km).name);
items{end+1} = fn; %#ok<AGROW>
end
end
set(S.hCfgPop, 'String', items, 'Value', 1);
end
function onCfgProfileChange(~,~)
items = get(S.hCfgPop, 'String');
idx = get(S.hCfgPop, 'Value');
sel = items{idx};
if strcmp(sel, 'Default')
S.config = GRIM_Config();
cLog('Config: reset to Default.');
else
cfgDir2 = fullfile(grimRoot, 'Config');
fp = fullfile(cfgDir2, [sel '.mat']);
if exist(fp, 'file')
tmp = load(fp);
if isfield(tmp, 'grimConfig')
S.config = tmp.grimConfig;
% Fill missing fields from default
def = GRIM_Config();
fns = fieldnames(def);
for fi = 1:length(fns)
if ~isfield(S.config, fns{fi})
S.config.(fns{fi}) = def.(fns{fi});
end
end
cLog(sprintf('Config: loaded "%s".', sel));
else
cLog(sprintf('Config: "%s.mat" is not a valid config file.', sel));
set(S.hCfgPop, 'Value', 1);
end
end
end
end
function onSettings(~,~)
newCfg = GRIM_Settings(S.config);
S.config = newCfg;
refreshCfgProfiles();
cLog('Settings updated.');
end
function onClearMonitoring(~,~)
if ~exist(monDir,'dir')
cLog('Monitoring folder does not exist.');
return;
end
ch = questdlg( ...
sprintf('Delete all files in:\n%s\n\nThis cannot be undone.', monDir), ...
'Clear Monitoring Data', 'Delete All', 'Cancel', 'Cancel');
if strcmp(ch, 'Delete All')
fList = dir(fullfile(monDir, '*'));
nDel = 0;
for fi = 1:length(fList)
if fList(fi).isdir; continue; end
try delete(fullfile(monDir, fList(fi).name)); nDel = nDel+1;
catch, end
end
cLog(sprintf('Cleared %d files from Monitoring/', nDel));
setStat(sprintf('Monitoring data cleared (%d files)', nDel), C.green);
end
end
function onExitBtn(~,~)
if S.running, confirmExit('Solver is still running. Exit anyway?');
else, confirmExit('Exit GRIM?'); end
end
function confirmExit(msg)
dW = 360; dH = 150;
df = figure('Name','Confirm Exit','NumberTitle','off', ...
'MenuBar','none','ToolBar','none','Color',C.bg, ...
'Resize','off','WindowStyle','modal', ...
'Position',[(scr(3)-dW)/2 (scr(4)-dH)/2 dW dH]);
uipanel(df,'Units','pixels','Position',[0 dH-3 dW 3], ...
'BackgroundColor',C.red,'BorderType','none');
uicontrol(df,'Style','text','String',msg, ...
'Position',[20 70 dW-40 40], ...
'FontSize',13,'FontWeight','bold','FontName','Segoe UI', ...
'ForegroundColor',C.txt,'BackgroundColor',C.bg,'HorizontalAlignment','center');
uicontrol(df,'Style','pushbutton','String','Exit', ...
'Position',[dW/2-130 18 120 36], ...
'FontSize',11,'FontWeight','bold','FontName','Segoe UI', ...
'BackgroundColor',C.red,'ForegroundColor',C.w, ...
'Callback',@(~,~)doExit(df));
uicontrol(df,'Style','pushbutton','String','Cancel', ...
'Position',[dW/2+10 18 120 36], ...
'FontSize',11,'FontWeight','bold','FontName','Segoe UI', ...
'BackgroundColor',C.card,'ForegroundColor',C.txt, ...
'Callback',@(~,~)delete(df));
end
function doExit(dlgFig)
try delete(dlgFig); catch, end
cleanupAndClose();
end
function onCloseFig(~,~)
if S.running, confirmExit('Solver is still running. Exit anyway?');
else, cleanupAndClose(); end
end
function cleanupAndClose()
S.animating = false;
S.running = false;
% Close progress dialog if open
if ~isempty(S.progFig)
try delete(S.progFig); catch, end
S.progFig = [];
end
if ~isempty(S.solveTimer)
try stop(S.solveTimer); catch, end
try delete(S.solveTimer); catch, end
S.solveTimer = [];
end
try
allTimers = timerfindall;
for ti = 1:numel(allTimers)
try
tName = get(allTimers(ti),'Tag');
if contains(tName,'GRIM') || isempty(tName)
stop(allTimers(ti)); delete(allTimers(ti));
end
catch
try stop(allTimers(ti)); catch, end
try delete(allTimers(ti)); catch, end
end
end
catch, end
S.childFigs(~ishandle(S.childFigs)) = [];
for ci4 = 1:numel(S.childFigs)
try delete(S.childFigs(ci4)); catch, end
end
try
allFigs = findall(0,'Type','figure');
for fi = 1:numel(allFigs)
nm = get(allFigs(fi),'Name');
if ~isempty(nm) && startsWith(nm,'GRIM') && allFigs(fi)~=fig
try delete(allFigs(fi)); catch, end
end
end
catch, end
try delete(fig); catch, end
end
function onSysChange(~,~)
v = get(S.hSysPop,'Value');
if v <= numel(S.systems)
S.sysIdx = v; S.sysName = S.systems{v};
loadSystemInfo();
cLog(sprintf('System: %s', S.sysName));
end
end
function onRefresh(~,~)
scanSystems();
set(S.hSysPop,'String',sysPopList(),'Value',max(1,S.sysIdx));
set(S.hNSys,'String',sprintf('Systems: %d',numel(S.systems)));
if ~isempty(S.systems)
S.sysIdx = min(S.sysIdx, numel(S.systems));
S.sysName = S.systems{S.sysIdx};
loadSystemInfo();
else
clearCards(); clearResults();
end
cLog('System list refreshed.');
end
%% ================================================================
%% SOLVE — uifigure + uihtml with JS elapsed timer
%% Progress window stays open until Results Summary is populated.
%% ================================================================
function onRun(~,~)
if isempty(S.sysName), cLog('ERROR: No system selected.'); return; end
if S.running, cLog('Solver already running.'); return; end
if ~exist('GRIM_Run','file'), cLog('ERROR: GRIM_Run.m not found.'); return; end
sName = S.sysName;
sMode = S.modes{get(S.hModePop,'Value')};
S.running = true;
set(S.hBtnSolve,'Enable','off','String',' Solving...');
set(fig,'Pointer','watch');
setStat(sprintf('Solving %s (%s) ...', sName, sMode), C.amber);
clearResults();
S.solveInfo = sprintf('%s (%s)', sName, sMode);
set(S.hOutcome,'String', ...
sprintf(' Solving %s %s ... please wait', char(8212), S.solveInfo), ...
'ForegroundColor', C.amber);
drawnow;
sep = repmat(char(9552),1,52);
cLog(sep);
cLog(sprintf(' GRIM_Run(''%s'', ''%s'', true, configOverride)', sName, sMode));
cLog(sep);
drawnow;
% Config override as local variable (evalc runs in caller workspace)
GRIM_GUI_cfgOvr__ = S.config; %#ok<NASGU>
cmd = sprintf('GRIM_Run(''%s'',''%s'',true,GRIM_GUI_cfgOvr__)', sName, sMode);
S.solveStartTic = tic;
% ============================================================
% Progress window — uifigure + uihtml
% JS elapsed timer runs in Chromium (CEF), independent of
% MATLAB main thread blocking in evalc().
% Window stays open until Results Summary is fully populated.
% ============================================================
try
scr2 = get(0,'ScreenSize');
pw = 460; ph = 240;
spinHtml = [ ...
'<html><body style="margin:0;padding:0;' ...
'background:#111319;height:100vh;' ...
'font-family:Segoe UI,Arial,sans-serif;overflow:hidden;">' ...
'<div style="height:3px;width:100%;' ...
'background:linear-gradient(90deg,#008b96,#1b7a85)"></div>' ...
'<div style="display:flex;flex-direction:column;' ...
'align-items:center;justify-content:center;' ...
'height:calc(100vh - 3px)">' ...
'<style>' ...
'@keyframes spin{from{transform:rotate(0deg)}' ...
'to{transform:rotate(360deg)}}' ...
'@keyframes pulse{0%,100%{opacity:.35}50%{opacity:1}}' ...
'</style>' ...
'<div style="width:48px;height:48px;' ...
'border:4px solid #1b2135;border-top-color:#008b96;' ...
'border-radius:50%;animation:spin .8s linear infinite"></div>' ...
'<div style="color:#d7dde8;font-size:15px;font-weight:bold;' ...
'margin-top:18px">Generating Restoration Strategy</div>' ...
'<div style="color:#6e7789;font-size:12px;margin-top:8px">' ...
'Solving ' sName ' (' sMode ')</div>' ...
'<div id="elapsed" style="color:#008b96;font-size:26px;' ...
'font-weight:bold;font-family:Consolas,monospace;' ...
'margin-top:16px;letter-spacing:2px">00:00</div>' ...
'<div style="color:#6e7789;font-size:10px;margin-top:10px;' ...
'animation:pulse 2s ease-in-out infinite">' ...
'Please wait ' char(8212) ' this may take a while</div>' ...
'</div>' ...
'<script>' ...
'var t0=Date.now();' ...
'setInterval(function(){' ...
'var e=Math.floor((Date.now()-t0)/1000);' ...
'var h=Math.floor(e/3600);' ...
'var m=Math.floor((e%3600)/60);' ...
'var s=e%60;' ...
'var str;' ...
'if(h>0){str=(h<10?"0":"")+h+":"+(m<10?"0":"")+m+":"+(s<10?"0":"")+s}' ...
'else{str=(m<10?"0":"")+m+":"+(s<10?"0":"")+s}' ...
'document.getElementById("elapsed").textContent=str;' ...
'},1000);' ...
'</script>' ...
'</body></html>'];
tmpHtml = fullfile(tempdir, 'grim_progress.html');
fid3 = fopen(tmpHtml,'w','n','UTF-8');
fwrite(fid3, spinHtml, 'char');
fclose(fid3);
S.progFig = uifigure( ...
'Name','GRIM — Solving', ...
'Position',[round((scr2(3)-pw)/2) round((scr2(4)-ph)/2) pw ph], ...
'Color',[0.067 0.075 0.102], ...
'Resize','off', ...
'CloseRequestFcn',@(~,~)0); % block accidental close
try
uihtml(S.progFig,'HTMLSource',tmpHtml, ...
'Position',[0 0 pw ph]);
catch
% pre-R2019b fallback: static label, no animation
uilabel(S.progFig, ...
'Text',sprintf('Solving %s (%s) ...\n\nPlease wait', sName, sMode), ...
'Position',[30 30 pw-60 ph-60], ...
'FontSize',14,'FontColor',[0.843 0.867 0.910], ...
'BackgroundColor',[0.067 0.075 0.102], ...
'HorizontalAlignment','center','WordWrap','on');
end
drawnow;
pause(0.6); % let CEF fully render before blocking
catch
S.progFig = [];
end
runOK = false;
output = '';
runErr = [];
isInterrupt = false;
try
output = evalc(cmd);
runOK = true;
catch ME
runErr = ME;
if strcmp(ME.identifier,'MATLAB:interrupt') || ...
contains(ME.message,'terminated','IgnoreCase',true) || ...
contains(ME.message,'interrupt','IgnoreCase',true)
isInterrupt = true;
end
end
% Clean up temp config variable from base workspace
% (config override was local variable, no base cleanup needed)
% NOTE: progress window is NOT closed here.
% It stays open until Results Summary is fully populated below.
% ---- Elapsed time ----
if ~isempty(S.solveStartTic), solveElapsed = toc(S.solveStartTic);
else, solveElapsed = 0; end
if solveElapsed < 60
etStr = sprintf('%.1fs', solveElapsed);
elseif solveElapsed < 3600
etStr = sprintf('%dm %02ds', floor(solveElapsed/60), round(mod(solveElapsed,60)));
else
etStr = sprintf('%.1fh', solveElapsed/3600);
end
% ---- Log solver output ----
if ~isempty(output)
outLines = strsplit(output, {char(10), char(13)});
for li = 1:numel(outLines)
t = outLines{li};
if ~isempty(strtrim(t)), cLogRaw(t); end
end
end
cLog(sep);
cLog(sprintf(' Elapsed: %s', etStr));
% ---- Process results ----
if runOK
resFile = fullfile(monDir, sprintf('GRIM_results_%s.mat', sName));
if exist(resFile,'file')
d = load(resFile);
S.Grid = d.Grid; S.hasResults = true;
try populateResults();
catch ME_pop, cLog(sprintf('WARNING: populateResults failed: %s', ME_pop.message));
end
G2 = S.Grid;
ns = findLastValidStep(G2);
if ns == 0
nGenAll = numel(G2.Generator.ID);
nBusAll = numel(G2.Bus.ID);
cLog('');
cLog([char(9888) ' NO SOLUTION ' char(9888)]);
cLog(' Solver stopped without completing any step.');
setStat([char(9888) ' No solution found (' etStr ')'], C.amber);
set(S.hOutcome,'String', ...
sprintf(' %s NO SOLUTION %s Solver could not complete any step (%d gens, %d buses) [%s]', ...
char(9679), char(8212), nGenAll, nBusAll, etStr), ...
'ForegroundColor', C.amber);
set(S.hResPanel,'ForegroundColor', C.amber);
else
fn = sprintf('Step_%d', ns);
nGenOn = sum(G2.Generator.IsOn.(fn));
nGenAll = numel(G2.Generator.ID);
nBusOn = sum(G2.Bus.IsOn.(fn));
nBusAll = numel(G2.Bus.ID);
cLog('');
if nGenOn==nGenAll && nBusOn==nBusAll
cLog([char(9733) char(9733) char(9733) ...
' RESTORATION COMPLETE ' ...
char(9733) char(9733) char(9733)]);
cLog(sprintf(' All %d generators online, all %d buses energized.', nGenAll, nBusAll));
setStat(sprintf('%s Complete — %d/%d gens, %d/%d buses [%s]', ...
char(10004), nGenOn, nGenAll, nBusOn, nBusAll, etStr), C.green);
setOutcome(nGenOn,nGenAll,nBusOn,nBusAll,'complete');
elseif nGenOn==nGenAll
cLog([char(9733) ' ALL GENERATORS STARTED ' char(9733)]);
cLog(sprintf(' %d/%d buses energized.', nBusOn,nBusAll));
setStat(sprintf('%s Done — %d/%d gens, %d/%d buses [%s]', ...