-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathSolarPanelApp.m
More file actions
1518 lines (1341 loc) · 61.2 KB
/
Copy pathSolarPanelApp.m
File metadata and controls
1518 lines (1341 loc) · 61.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
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
classdef SolarPanelApp < handle
properties (Access = private)
Fig
MapAxes
MapRef % MapCellsReference from readBasemapImage
AddressField
LoadButton
AddPanelButton
TiltSlider
TiltLabel
DailyAxes
MonthlyAxes
TotalLabel
PanelListBox
DeletePanelButton
ZoomLevel double = 20
MapContextMenu
PanelContextMenu
IsPanning logical = false
PanStart = []
Latitude double = 42.3677
Longitude double = -71.0711
Panels = {} % ROI rectangle handles
PanelTilts = [] % per-panel tilt angles (degrees)
SunEdges = {} % line handles showing sun-facing edge
SelectedPanel = 0 % index of currently selected panel
OptimizeDropdown
RealisticCheckBox
ExportButton
SunArcHandles = {} % handles to sun path dot/label objects
SunArcVisible logical = true
SunArcAxes % transparent overlay axes for sun dots
end
methods
function app = SolarPanelApp()
addpath(fullfile(fileparts(mfilename('fullpath')), 'helpers'));
app.buildUI();
app.loadMap();
end
end
methods (Access = private)
function buildUI(app)
app.Fig = uifigure('Name', 'Solar Panel Planner', ...
'Position', [100 50 1300 820], ...
'Theme', 'dark');
mainGrid = uigridlayout(app.Fig, [2 2], ...
'RowHeight', {40, '1x'}, ...
'ColumnWidth', {'1x', 380}, ...
'Padding', 8, 'RowSpacing', 6, 'ColumnSpacing', 8);
% ── Top toolbar ──
topBar = uigridlayout(mainGrid, [1 6], ...
'RowHeight', {32}, ...
'ColumnWidth', {'1x', 80, 20, 110, 90, 105}, ...
'Padding', [10 4 10 4], 'ColumnSpacing', 8);
topBar.Layout.Row = 1;
topBar.Layout.Column = [1 2];
topBar.BackgroundColor = [0.14 0.14 0.16];
app.AddressField = uieditfield(topBar, 'text', ...
'Value', 'Museum of Science, 1 Science Pk, Boston, MA 02114', ...
'Placeholder', 'Enter address...');
app.LoadButton = uibutton(topBar, 'Text', 'Load', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.loadAddress), ...
'BackgroundColor', [0.22 0.45 0.7], 'FontColor', 'w');
% Spacer
uilabel(topBar, 'Text', '');
app.AddPanelButton = uibutton(topBar, 'Text', '+ Add Panel', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.addPanel), ...
'BackgroundColor', [0.18 0.55 0.34], 'FontColor', 'w', ...
'FontWeight', 'bold');
uibutton(topBar, 'Text', 'Clear All', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.clearPanels), ...
'BackgroundColor', [0.55 0.18 0.18], 'FontColor', 'w');
app.ExportButton = uibutton(topBar, 'Text', 'Export PDF', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.exportReport), ...
'BackgroundColor', [0.5 0.3 0.65], 'FontColor', 'w');
% ── Map axes ──
app.MapAxes = uiaxes(mainGrid);
app.MapAxes.Layout.Row = 2;
app.MapAxes.Layout.Column = 1;
axis(app.MapAxes, 'off');
app.MapAxes.Toolbar.Visible = 'on';
disableDefaultInteractivity(app.MapAxes);
% Overlay axes for sun sundial (fixed position, transparent)
app.SunArcAxes = uiaxes(mainGrid);
app.SunArcAxes.Layout.Row = 2;
app.SunArcAxes.Layout.Column = 1;
app.SunArcAxes.Color = 'none';
app.SunArcAxes.XColor = 'none';
app.SunArcAxes.YColor = 'none';
app.SunArcAxes.Toolbar.Visible = 'off';
app.SunArcAxes.HitTest = 'off';
app.SunArcAxes.PickableParts = 'none';
xlim(app.SunArcAxes, [0 1]);
ylim(app.SunArcAxes, [0 1]);
disableDefaultInteractivity(app.SunArcAxes);
app.Fig.WindowScrollWheelFcn = @(~,evt) app.safeCall(@() app.onScroll(evt));
app.Fig.WindowKeyPressFcn = @(~,evt) app.safeCall(@() app.onKeyPress(evt));
app.Fig.WindowButtonDownFcn = @(~,~) app.safeCall(@app.onMouseDown);
app.Fig.WindowButtonMotionFcn = @(~,~) app.safeCall(@app.onMouseMove);
app.Fig.WindowButtonUpFcn = @(~,~) app.safeCall(@app.onMouseUp);
% Context menu for empty map area
app.MapContextMenu = uicontextmenu(app.Fig);
uimenu(app.MapContextMenu, 'Text', 'Add Panel Here', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@app.addPanelAtClick));
uimenu(app.MapContextMenu, 'Text', 'Reset Zoom', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@app.resetZoom));
uimenu(app.MapContextMenu, 'Text', 'Toggle Sun Path', ...
'Separator', 'on', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@app.toggleSunArc));
app.MapAxes.ContextMenu = app.MapContextMenu;
% Context menu for panels (attached per-ROI)
app.PanelContextMenu = uicontextmenu(app.Fig);
uimenu(app.PanelContextMenu, 'Text', 'Delete Panel', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@app.deleteSelectedPanel));
uimenu(app.PanelContextMenu, 'Text', 'Duplicate Panel', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@app.duplicateSelectedPanel));
uimenu(app.PanelContextMenu, 'Text', 'Optimize This Panel', ...
'Separator', 'on', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@app.optimizeSelectedTilt));
uimenu(app.PanelContextMenu, 'Text', 'Face South (180°)', ...
'Separator', 'on', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@() app.setPanelAzimuth(180)));
uimenu(app.PanelContextMenu, 'Text', 'Face East (90°)', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@() app.setPanelAzimuth(90)));
uimenu(app.PanelContextMenu, 'Text', 'Face West (270°)', ...
'MenuSelectedFcn', @(~,~) app.safeCall(@() app.setPanelAzimuth(270)));
% ── Sidebar ──
sidebar = uigridlayout(mainGrid, [3 1], ...
'RowHeight', {120, 'fit', '1x'}, ...
'Padding', [8 8 8 8], 'RowSpacing', 10);
sidebar.Layout.Row = 2;
sidebar.Layout.Column = 2;
sidebar.BackgroundColor = [0.12 0.12 0.14];
% ── Section 1: Panel List ──
panelSection = uipanel(sidebar, ...
'Title', 'Panels', ...
'FontWeight', 'bold', ...
'BackgroundColor', [0.15 0.15 0.17]);
panelGrid = uigridlayout(panelSection, [2 1], ...
'RowHeight', {'1x', 30}, ...
'Padding', 6, 'RowSpacing', 6);
app.PanelListBox = uilistbox(panelGrid, ...
'Items', {}, ...
'FontColor', [0.85 0.85 0.85], ...
'BackgroundColor', [0.1 0.1 0.12], ...
'ValueChangedFcn', @(src,~) app.safeCall(@() app.onListSelection(src)));
btnRow = uigridlayout(panelGrid, [1 2], ...
'ColumnWidth', {'1x', '1x'}, 'Padding', 0, 'RowHeight', {28});
app.DeletePanelButton = uibutton(btnRow, 'Text', 'Delete Selected', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.deleteSelectedPanel), ...
'BackgroundColor', [0.5 0.15 0.15], 'FontColor', 'w', ...
'Enable', 'off');
uibutton(btnRow, 'Text', 'Clear All', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.clearPanels), ...
'BackgroundColor', [0.3 0.3 0.3], 'FontColor', 'w');
% ── Section 2: Tilt Control ──
tiltSection = uipanel(sidebar, ...
'Title', 'Tilt Control', ...
'FontWeight', 'bold', ...
'BackgroundColor', [0.15 0.15 0.17]);
tiltInner = uigridlayout(tiltSection, [2 1], ...
'RowHeight', {45, 28}, ...
'Padding', [10 6 10 4], 'RowSpacing', 6);
tiltSliderRow = uigridlayout(tiltInner, [1 2], ...
'ColumnWidth', {'1x', 45}, 'Padding', [8 0 4 0], 'RowHeight', {40});
app.TiltSlider = uislider(tiltSliderRow, ...
'Limits', [0 90], 'Value', 30, ...
'ValueChangedFcn', @(~,~) app.safeCall(@app.tiltChanged), ...
'MajorTicks', 0:30:90);
app.TiltLabel = uilabel(tiltSliderRow, 'Text', '30°', ...
'FontColor', [0.4 0.8 1], 'FontWeight', 'bold', ...
'HorizontalAlignment', 'center', 'FontSize', 14);
optRow = uigridlayout(tiltInner, [1 2], ...
'ColumnWidth', {'1x', 85}, 'Padding', 0, 'RowHeight', {26});
app.OptimizeDropdown = uidropdown(optRow, ...
'Items', {'Max total yield', 'Annual consistency', 'Consistent daily'}, ...
'Value', 'Max total yield');
uibutton(optRow, 'Text', 'Optimize', ...
'ButtonPushedFcn', @(~,~) app.safeCall(@app.optimizeTilt), ...
'BackgroundColor', [0.4 0.25 0.6], 'FontColor', 'w');
% ── Section 3: Energy Analysis (summary + charts) ──
chartSection = uipanel(sidebar, ...
'Title', 'Energy Analysis', ...
'FontWeight', 'bold', ...
'BackgroundColor', [0.15 0.15 0.17]);
chartGrid = uigridlayout(chartSection, [4 1], ...
'RowHeight', {22, '1x', '1x', 22}, ...
'Padding', [6 4 6 4], 'RowSpacing', 6);
app.TotalLabel = uilabel(chartGrid, 'Text', '', ...
'FontColor', [0.95 0.75 0.1], 'FontWeight', 'bold', 'FontSize', 13);
app.DailyAxes = uiaxes(chartGrid);
title(app.DailyAxes, 'Daily Power (Summer Solstice)');
xlabel(app.DailyAxes, 'Hour (UTC)');
ylabel(app.DailyAxes, 'W');
app.DailyAxes.Color = [0.08 0.08 0.1];
app.DailyAxes.XColor = [0.6 0.6 0.6];
app.DailyAxes.YColor = [0.6 0.6 0.6];
app.DailyAxes.Title.Color = [0.85 0.85 0.85];
app.DailyAxes.FontSize = 9;
app.MonthlyAxes = uiaxes(chartGrid);
title(app.MonthlyAxes, 'Monthly Energy');
xlabel(app.MonthlyAxes, 'Month');
ylabel(app.MonthlyAxes, 'kWh');
app.MonthlyAxes.Color = [0.08 0.08 0.1];
app.MonthlyAxes.XColor = [0.6 0.6 0.6];
app.MonthlyAxes.YColor = [0.6 0.6 0.6];
app.MonthlyAxes.Title.Color = [0.85 0.85 0.85];
app.MonthlyAxes.FontSize = 9;
app.RealisticCheckBox = uicheckbox(chartGrid, ...
'Text', 'Include weather, temperature & system losses', ...
'FontColor', [0.85 0.85 0.85], ...
'Value', true, ...
'ValueChangedFcn', @(~,~) app.safeCall(@app.updatePlots));
end
function safeCall(app, fn)
try
fn();
catch ex
uialert(app.Fig, ex.getReport('basic'), 'Error');
end
end
function loadAddress(app)
addr = app.AddressField.Value;
[lat, lon] = geocodeAddress(addr);
app.Latitude = lat;
app.Longitude = lon;
app.clearPanels();
app.loadMap();
end
function loadMap(app)
drawnow;
[A, R] = readBasemapImage('satellite', ...
[app.Latitude, app.Longitude], app.ZoomLevel, 2048);
app.MapRef = R;
cla(app.MapAxes);
mapshow(app.MapAxes, A, R);
axis(app.MapAxes, 'tight', 'off');
app.MapAxes.DataAspectRatio = [1 1 1];
% Assign context menu to the map image so right-click works
imgChildren = findobj(app.MapAxes.Children, 'Type', 'image');
if isempty(imgChildren)
imgChildren = findobj(app.MapAxes.Children, '-regexp', 'Type', '.*');
end
for i = 1:numel(imgChildren)
if isprop(imgChildren(i), 'ContextMenu')
imgChildren(i).ContextMenu = app.MapContextMenu;
end
end
app.drawSunArc();
end
function drawSunArc(app)
% Draw sundial-style dots in a fixed overlay, unaffected by zoom/pan.
for k = 1:numel(app.SunArcHandles)
if isvalid(app.SunArcHandles{k})
delete(app.SunArcHandles{k});
end
end
app.SunArcHandles = {};
% Center and radius in normalized [0,1] overlay coordinates
oxc = 0.5;
oyc = 0.5;
radius = 0.43;
% Compute average sun position and irradiance for each hour
hoursUTC = 0:23;
avgAz = zeros(size(hoursUTC));
avgEl = zeros(size(hoursUTC));
avgIrr = zeros(size(hoursUTC));
nValid = zeros(size(hoursUTC));
for m = 1:12
tm = datetime(2024, m, 15, 'TimeZone', 'UTC') + hours(hoursUTC);
[azm, elm] = sunPosition(app.Latitude, app.Longitude, tm);
above = elm > 0;
avgAz = avgAz + azm .* above;
avgEl = avgEl + elm .* above;
avgIrr = avgIrr + max(sind(elm), 0);
nValid = nValid + above;
end
hasData = nValid > 0;
avgAz(hasData) = avgAz(hasData) ./ nValid(hasData);
avgEl(hasData) = avgEl(hasData) ./ nValid(hasData);
avgIrr(hasData) = avgIrr(hasData) ./ 12;
maxIrr = max(avgIrr);
if maxIrr == 0, return; end
hold(app.SunArcAxes, 'on');
for h = 1:numel(hoursUTC)
if ~hasData(h) || avgEl(h) < 2, continue; end
az = avgAz(h);
% Azimuth: 0=N=up, 90=E=right, 180=S=down, 270=W=left
x = oxc + radius * sind(az);
y = oyc + radius * cosd(az);
normIrr = avgIrr(h) / maxIrr;
dotSize = 5 + 20 * normIrr;
dotColor = [1, 0.7 + 0.2*normIrr, 0.1 + 0.3*(1-normIrr)];
hDot = plot(app.SunArcAxes, x, y, 'o', ...
'MarkerSize', dotSize, ...
'MarkerFaceColor', dotColor, ...
'MarkerEdgeColor', 'none');
app.SunArcHandles{end+1} = hDot;
% Label every 3 local hours and the peak
localHour = mod(hoursUTC(h) - 5, 24);
if mod(localHour, 3) == 0 || normIrr > 0.9
if localHour == 0
lbl = '12am';
elseif localHour < 12
lbl = sprintf('%da', localHour);
elseif localHour == 12
lbl = '12p';
else
lbl = sprintf('%dp', localHour - 12);
end
hTxt = text(app.SunArcAxes, x, y - 0.03, lbl, ...
'Color', [0.9 0.8 0.3], 'FontSize', 8, ...
'HorizontalAlignment', 'center', ...
'FontWeight', 'bold');
app.SunArcHandles{end+1} = hTxt;
end
end
hold(app.SunArcAxes, 'off');
if ~app.SunArcVisible
for k = 1:numel(app.SunArcHandles)
if isvalid(app.SunArcHandles{k})
app.SunArcHandles{k}.Visible = 'off';
end
end
end
end
function toggleSunArc(app)
app.SunArcVisible = ~app.SunArcVisible;
vis = 'off';
if app.SunArcVisible, vis = 'on'; end
for k = 1:numel(app.SunArcHandles)
if isvalid(app.SunArcHandles{k})
app.SunArcHandles{k}.Visible = vis;
end
end
end
function onScroll(app, evt)
% Only zoom when cursor is over the map
cp = app.MapAxes.CurrentPoint;
xl = app.MapAxes.XLim;
yl = app.MapAxes.YLim;
if cp(1,1) < xl(1) || cp(1,1) > xl(2) || cp(1,2) < yl(1) || cp(1,2) > yl(2)
return;
end
factor = 1.3;
if evt.VerticalScrollCount > 0
s = factor; % scroll down = zoom out
else
s = 1/factor; % scroll up = zoom in
end
xl = app.MapAxes.XLim;
yl = app.MapAxes.YLim;
cx = mean(xl);
cy = mean(yl);
newW = diff(xl) * s;
newH = diff(yl) * s;
% Clamp: don't zoom in past ~30m view or out past loaded extent
maxW = diff(app.MapRef.XWorldLimits);
maxH = diff(app.MapRef.YWorldLimits);
minView = 30;
newW = max(min(newW, maxW), minView);
newH = max(min(newH, maxH), minView);
% Keep view within loaded image bounds
xLo = max(cx - newW/2, app.MapRef.XWorldLimits(1));
xHi = min(cx + newW/2, app.MapRef.XWorldLimits(2));
yLo = max(cy - newH/2, app.MapRef.YWorldLimits(1));
yHi = min(cy + newH/2, app.MapRef.YWorldLimits(2));
app.MapAxes.XLim = [xLo xHi];
app.MapAxes.YLim = [yLo yHi];
end
function onMouseDown(app)
% Only left-click pans; right-click is reserved for context menus
if ~strcmp(app.Fig.SelectionType, 'normal')
return;
end
% Only pan if click landed on the map image (not on a panel ROI)
obj = app.Fig.CurrentObject;
if isempty(obj), return; end
% If the clicked object is an ROI or child of an ROI, skip panning
objClass = class(obj);
if contains(objClass, 'images.roi') || contains(objClass, 'ROI')
return;
end
parent = obj;
for i = 1:5
if isprop(parent, 'Parent') && ~isempty(parent.Parent)
parent = parent.Parent;
if contains(class(parent), 'images.roi')
return;
end
else
break;
end
end
% Must be within the map axes bounds
cp = app.MapAxes.CurrentPoint;
xl = app.MapAxes.XLim;
yl = app.MapAxes.YLim;
if cp(1,1) < xl(1) || cp(1,1) > xl(2) || cp(1,2) < yl(1) || cp(1,2) > yl(2)
return;
end
app.PanStart = [cp(1,1), cp(1,2)];
app.IsPanning = true;
end
function onMouseMove(app)
if ~app.IsPanning || isempty(app.PanStart)
return;
end
cp = app.MapAxes.CurrentPoint;
dx = app.PanStart(1) - cp(1,1);
dy = app.PanStart(2) - cp(1,2);
xl = app.MapAxes.XLim + dx;
yl = app.MapAxes.YLim + dy;
% Clamp within loaded image
mapXL = app.MapRef.XWorldLimits;
mapYL = app.MapRef.YWorldLimits;
if xl(1) < mapXL(1), xl = xl - (xl(1) - mapXL(1)); end
if xl(2) > mapXL(2), xl = xl - (xl(2) - mapXL(2)); end
if yl(1) < mapYL(1), yl = yl - (yl(1) - mapYL(1)); end
if yl(2) > mapYL(2), yl = yl - (yl(2) - mapYL(2)); end
app.MapAxes.XLim = xl;
app.MapAxes.YLim = yl;
end
function onMouseUp(app)
app.IsPanning = false;
app.PanStart = [];
end
function tiltChanged(app)
tilt = app.TiltSlider.Value;
app.TiltLabel.Text = sprintf('%.0f°', tilt);
if app.SelectedPanel > 0 && app.SelectedPanel <= numel(app.PanelTilts)
app.PanelTilts(app.SelectedPanel) = tilt;
end
app.updatePlots();
end
function selectPanel(app, idx)
app.SelectedPanel = idx;
if idx > 0 && idx <= numel(app.PanelTilts)
app.TiltSlider.Value = app.PanelTilts(idx);
app.TiltLabel.Text = sprintf('%.0f°', app.PanelTilts(idx));
app.DeletePanelButton.Enable = 'on';
else
app.DeletePanelButton.Enable = 'off';
end
app.refreshPanelList();
app.updatePlots();
end
function onListSelection(app, src)
if isempty(src.Value)
return;
end
items = src.Items;
idx = find(strcmp(items, src.Value), 1);
if ~isempty(idx)
app.selectPanel(idx);
end
end
function deleteSelectedPanel(app)
idx = app.SelectedPanel;
if idx < 1 || idx > numel(app.Panels)
return;
end
if isvalid(app.Panels{idx}), delete(app.Panels{idx}); end
if idx <= numel(app.SunEdges) && isvalid(app.SunEdges{idx})
delete(app.SunEdges{idx});
end
app.Panels(idx) = [];
app.PanelTilts(idx) = [];
app.SunEdges(idx) = [];
if app.SelectedPanel > numel(app.Panels)
app.SelectedPanel = numel(app.Panels);
end
if app.SelectedPanel > 0
app.selectPanel(app.SelectedPanel);
else
app.DeletePanelButton.Enable = 'off';
end
app.refreshPanelList();
app.updatePlots();
end
function refreshPanelList(app)
items = cell(1, numel(app.Panels));
for k = 1:numel(app.Panels)
if isvalid(app.Panels{k})
[~, az] = app.panelGeometry(app.Panels{k});
items{k} = sprintf('Panel %d | Az: %.0f° | Tilt: %.0f°', ...
k, az, app.PanelTilts(k));
else
items{k} = sprintf('Panel %d (invalid)', k);
end
end
app.PanelListBox.Items = items;
if app.SelectedPanel > 0 && app.SelectedPanel <= numel(items)
app.PanelListBox.Value = items{app.SelectedPanel};
end
end
function addPanel(app)
if isempty(app.MapRef)
return;
end
n = numel(app.Panels) + 1;
% Place panel in the center of the current view
xl = app.MapAxes.XLim;
yl = app.MapAxes.YLim;
cx = mean(xl);
cy = mean(yl);
% Size panel to ~8% of visible extent so it's easy to grab
viewW = diff(xl);
viewH = diff(yl);
pw = viewW * 0.08;
ph = viewH * 0.05;
% Offset each panel slightly
offset = (n - 1) * pw * 0.4;
roi = drawrectangle(app.MapAxes, ...
'Position', [cx - pw/2 + offset, cy - ph/2 + offset, pw, ph], ...
'Color', [0 0.9 1], ...
'FaceAlpha', 0.3, ...
'LineWidth', 2, ...
'Rotatable', true, ...
'Label', sprintf('Panel %d', n), ...
'LabelVisible', 'hover');
panelIdx = n;
addlistener(roi, 'ROIMoved', @(~,~) app.safeCall(@() app.onPanelMoved(panelIdx)));
addlistener(roi, 'MovingROI', @(~,~) app.safeCall(@() app.onPanelMoving(panelIdx)));
addlistener(roi, 'ROIClicked', @(~,~) app.safeCall(@() app.selectPanel(panelIdx)));
roi.ContextMenu = app.PanelContextMenu;
app.Panels{n} = roi;
app.PanelTilts(n) = 30;
% Create sun-facing edge highlight (will be updated in updatePlots)
hold(app.MapAxes, 'on');
app.SunEdges{n} = plot(app.MapAxes, [0 0], [0 0], '-', ...
'Color', [1 0.8 0], 'LineWidth', 5);
hold(app.MapAxes, 'off');
app.selectPanel(n);
app.refreshPanelList();
app.updatePlots();
end
function onPanelMoving(app, idx)
if idx > 0 && idx <= numel(app.Panels) && isvalid(app.Panels{idx})
app.updateSunEdge(idx, app.Panels{idx});
app.refreshPanelList();
app.updatePlots();
end
end
function onPanelMoved(app, idx)
app.selectPanel(idx);
end
function clearPanels(app)
for k = 1:numel(app.Panels)
if isvalid(app.Panels{k}), delete(app.Panels{k}); end
end
for k = 1:numel(app.SunEdges)
if isvalid(app.SunEdges{k}), delete(app.SunEdges{k}); end
end
app.Panels = {};
app.PanelTilts = [];
app.SunEdges = {};
app.SelectedPanel = 0;
app.DeletePanelButton.Enable = 'off';
app.PanelListBox.Items = {};
cla(app.DailyAxes);
cla(app.MonthlyAxes);
app.TotalLabel.Text = '';
end
function updatePlots(app)
% Remove invalid panels and edge highlights
valid = cellfun(@isvalid, app.Panels);
for k = find(~valid)
if k <= numel(app.SunEdges) && isvalid(app.SunEdges{k})
delete(app.SunEdges{k});
end
end
app.Panels = app.Panels(valid);
app.PanelTilts = app.PanelTilts(valid);
app.SunEdges = app.SunEdges(valid);
app.refreshPanelList();
if isempty(app.Panels)
cla(app.DailyAxes);
cla(app.MonthlyAxes);
app.TotalLabel.Text = '';
return;
end
efficiency = 0.20;
t = datetime(2024, 6, 21, 'TimeZone', 'UTC') + hours(0:23);
[az, el] = sunPosition(app.Latitude, app.Longitude, t);
nv = app.lossArgs(t);
cla(app.DailyAxes);
hold(app.DailyAxes, 'on');
totalWatts = zeros(size(t));
colors = lines(numel(app.Panels));
for k = 1:numel(app.Panels)
roi = app.Panels{k};
[area, panelAz] = app.panelGeometry(roi);
tilt = app.PanelTilts(k);
% Update sun-facing edge highlight on map
app.updateSunEdge(k, roi);
w = solarPanelPower(efficiency, area, az, el, tilt, panelAz, nv{:});
totalWatts = totalWatts + w;
plot(app.DailyAxes, 0:23, w, 'Color', colors(k,:), ...
'LineWidth', 1.5, 'DisplayName', sprintf('P%d az=%.0f° t=%.0f°', k, panelAz, tilt));
end
if numel(app.Panels) > 1
plot(app.DailyAxes, 0:23, totalWatts, '--w', ...
'LineWidth', 2, 'DisplayName', 'Total');
end
hold(app.DailyAxes, 'off');
xlim(app.DailyAxes, [0 23]);
legend(app.DailyAxes, 'TextColor', [0.8 0.8 0.8], 'FontSize', 8, ...
'Location', 'northwest');
% Monthly (per-panel tracking for coloring)
N = numel(app.Panels);
daysPerMonth = [31 29 31 30 31 30 31 31 30 31 30 31];
monthlyTotal = zeros(1, 12);
panelAnnualKWh = zeros(1, N);
for m = 1:12
tm = datetime(2024, m, 15, 'TimeZone', 'UTC') + hours(0:23);
[azm, elm] = sunPosition(app.Latitude, app.Longitude, tm);
nvM = app.lossArgs(tm);
for k = 1:N
[area, panelAz] = app.panelGeometry(app.Panels{k});
tilt = app.PanelTilts(k);
w = solarPanelPower(efficiency, area, azm, elm, tilt, panelAz, nvM{:});
kwh = sum(w)/1000 * daysPerMonth(m);
monthlyTotal(m) = monthlyTotal(m) + kwh;
panelAnnualKWh(k) = panelAnnualKWh(k) + kwh;
end
end
cla(app.MonthlyAxes);
bar(app.MonthlyAxes, 1:12, monthlyTotal, ...
'FaceColor', [0.9 0.5 0.1], 'EdgeColor', 'none');
app.MonthlyAxes.XTick = 1:12;
app.MonthlyAxes.XTickLabel = {'J','F','M','A','M','J','J','A','S','O','N','D'};
xlim(app.MonthlyAxes, [0.5 12.5]);
% Color panels by absolute efficiency vs theoretical max for this latitude
% Theoretical max: 1 m² panel at optimal tilt (=latitude) facing south
optTilt = abs(app.Latitude);
idealKWhPerM2 = 0;
for m = 1:12
tm = datetime(2024, m, 15, 'TimeZone', 'UTC') + hours(0:23);
[azm, elm] = sunPosition(app.Latitude, app.Longitude, tm);
nvM = app.lossArgs(tm);
w = solarPanelPower(efficiency, 1, azm, elm, optTilt, 180, nvM{:});
idealKWhPerM2 = idealKWhPerM2 + sum(w)/1000 * daysPerMonth(m);
end
panelAreas = zeros(1, N);
for k = 1:N
[panelAreas(k), ~] = app.panelGeometry(app.Panels{k});
end
kwhPerM2 = panelAnnualKWh ./ max(panelAreas, 0.01);
for k = 1:N
roi = app.Panels{k};
if ~isvalid(roi), continue; end
if k == app.SelectedPanel
roi.Color = [0 0.9 1];
else
% 0 = no output, 1 = theoretical max
t_norm = min(kwhPerM2(k) / max(idealKWhPerM2, 0.01), 1);
% Dim orange (low) to bright orange (high)
c = [0.9, 0.3 + 0.5*t_norm, 0.1*(1-t_norm)];
roi.Color = c;
end
if panelAnnualKWh(k) >= 1000
roi.Label = sprintf('%.1f MWh', panelAnnualKWh(k)/1000);
else
roi.Label = sprintf('%.0f kWh', panelAnnualKWh(k));
end
roi.LabelVisible = 'on';
end
annualKWh = sum(panelAnnualKWh);
totalArea = 0;
for k = 1:N
[a, ~] = app.panelGeometry(app.Panels{k});
totalArea = totalArea + a;
end
if app.RealisticCheckBox.Value
% Compute clear-sky total to derive effective loss %
clearSkyKWh = 0;
for m = 1:12
tm = datetime(2024, m, 15, 'TimeZone', 'UTC') + hours(0:23);
[azm, elm] = sunPosition(app.Latitude, app.Longitude, tm);
for k = 1:N
[area, panelAz] = app.panelGeometry(app.Panels{k});
tilt = app.PanelTilts(k);
w = solarPanelPower(efficiency, area, azm, elm, tilt, panelAz, ...
'ClearSkyFraction', 1, 'SystemLoss', 0);
clearSkyKWh = clearSkyKWh + sum(w)/1000 * daysPerMonth(m);
end
end
lossPct = (1 - annualKWh / clearSkyKWh) * 100;
app.TotalLabel.Text = sprintf('%.1f kWh/day | %d panels | %.0f m² (%.0f%% losses)', ...
annualKWh / 365, N, totalArea, lossPct);
else
app.TotalLabel.Text = sprintf('%.1f kWh/day | %d panels | %.0f m² (no losses)', ...
annualKWh / 365, N, totalArea);
end
end
function optimizeTilt(app)
if isempty(app.Panels)
uialert(app.Fig, 'Add panels first.', 'No Panels');
return;
end
N = numel(app.Panels);
areas = zeros(1, N);
panelAzs = zeros(1, N);
for k = 1:N
[areas(k), panelAzs(k)] = app.panelGeometry(app.Panels{k});
end
objective = app.OptimizeDropdown.Value;
daysPerMonth = [31 29 31 30 31 30 31 31 30 31 30 31];
efficiency = 0.20;
if strcmp(objective, 'Max total yield')
fun = @(tilts) -app.jointAnnualEnergy(tilts, areas, panelAzs, daysPerMonth, efficiency);
elseif strcmp(objective, 'Annual consistency')
fun = @(tilts) -app.jointMinMonthEnergy(tilts, areas, panelAzs, daysPerMonth, efficiency);
else
fun = @(tilts) app.jointDailyVariance(tilts, areas, panelAzs, efficiency);
end
x0 = app.PanelTilts(:)';
lb = zeros(1, N);
ub = 90 * ones(1, N);
opts = optimset('Display', 'off', 'TolX', 0.5);
if N == 1
optTilts = fminbnd(@(t) fun(t), 0, 90);
else
% Bounded Nelder-Mead via penalty
penaltyFun = @(x) fun(min(max(x, lb), ub)) + ...
1e6 * sum(max(0, lb - x).^2 + max(0, x - ub).^2);
optTilts = fminsearch(penaltyFun, x0, opts);
optTilts = min(max(optTilts, 0), 90);
end
app.PanelTilts = optTilts;
if app.SelectedPanel > 0 && app.SelectedPanel <= N
app.TiltSlider.Value = optTilts(app.SelectedPanel);
app.TiltLabel.Text = sprintf('%.0f°', optTilts(app.SelectedPanel));
end
app.updatePlots();
end
function energy = jointAnnualEnergy(app, tilts, areas, panelAzs, daysPerMonth, efficiency)
energy = 0;
for m = 1:12
tm = datetime(2024, m, 15, 'TimeZone', 'UTC') + hours(0:23);
[azm, elm] = sunPosition(app.Latitude, app.Longitude, tm);
nvM = app.lossArgs(tm);
for k = 1:numel(tilts)
w = solarPanelPower(efficiency, areas(k), azm, elm, tilts(k), panelAzs(k), nvM{:});
energy = energy + sum(w)/1000 * daysPerMonth(m);
end
end
end
function minE = jointMinMonthEnergy(app, tilts, areas, panelAzs, daysPerMonth, efficiency)
monthly = zeros(1, 12);
for m = 1:12
tm = datetime(2024, m, 15, 'TimeZone', 'UTC') + hours(0:23);
[azm, elm] = sunPosition(app.Latitude, app.Longitude, tm);
nvM = app.lossArgs(tm);
for k = 1:numel(tilts)
w = solarPanelPower(efficiency, areas(k), azm, elm, tilts(k), panelAzs(k), nvM{:});
monthly(m) = monthly(m) + sum(w)/1000 * daysPerMonth(m);
end
end
minE = min(monthly);
end
function v = jointDailyVariance(app, tilts, areas, panelAzs, efficiency)
% Minimize variance of combined hourly power on summer solstice
t = datetime(2024, 6, 21, 'TimeZone', 'UTC') + hours(0:23);
[az, el] = sunPosition(app.Latitude, app.Longitude, t);
nv = app.lossArgs(t);
totalW = zeros(size(t));
for k = 1:numel(tilts)
totalW = totalW + solarPanelPower(efficiency, areas(k), az, el, tilts(k), panelAzs(k), nv{:});
end
% Only penalize variance during daylight hours
daylight = totalW > 0;
if any(daylight)
v = var(totalW(daylight));
else
v = 0;
end
end
function updateSunEdge(app, k, roi)
% Highlight the sun-facing edge (bottom edge of the rectangle).
% This rotates naturally with the panel so there's no
% directional confusion. Vertices order: BL, TL, TR, BR.
verts = roi.Vertices;
if k <= numel(app.SunEdges) && isvalid(app.SunEdges{k})
set(app.SunEdges{k}, ...
'XData', [verts(1,1), verts(4,1)], ...
'YData', [verts(1,2), verts(4,2)]);
end
end
function onKeyPress(app, evt)
% Skip hotkeys when typing in the address field
if isequal(app.Fig.CurrentObject, app.AddressField)
return;
end
switch evt.Key
case {'delete', 'backspace'}
app.deleteSelectedPanel();
case 'escape'
app.deselectPanel();
case 'a'
app.addPanel();
case 'o'
app.optimizeTilt();
case 'tab'
app.cyclePanel(evt);
case {'leftarrow', 'rightarrow', 'uparrow', 'downarrow'}
app.nudgePanel(evt);
case 'bracketleft'
app.rotateSelectedPanel(-5);
case 'bracketright'
app.rotateSelectedPanel(5);
case 'pageup'
app.adjustTilt(5);
case 'pagedown'
app.adjustTilt(-5);
end
end
function deselectPanel(app)
app.SelectedPanel = 0;
app.DeletePanelButton.Enable = 'off';
app.refreshPanelList();
app.updatePlots();
end
function cyclePanel(app, evt)
if isempty(app.Panels), return; end
if any(strcmp(evt.Modifier, 'shift'))
next = app.SelectedPanel - 1;
if next < 1, next = numel(app.Panels); end
else
next = app.SelectedPanel + 1;
if next > numel(app.Panels), next = 1; end
end
app.selectPanel(next);
end
function nudgePanel(app, evt)
idx = app.SelectedPanel;
if idx < 1 || idx > numel(app.Panels), return; end
roi = app.Panels{idx};
if ~isvalid(roi), return; end
% Nudge by 1% of current view
step = diff(app.MapAxes.XLim) * 0.01;
pos = roi.Position;
switch evt.Key
case 'leftarrow', pos(1) = pos(1) - step;
case 'rightarrow', pos(1) = pos(1) + step;
case 'uparrow', pos(2) = pos(2) + step;
case 'downarrow', pos(2) = pos(2) - step;
end
roi.Position = pos;
app.updatePlots();
end
function rotateSelectedPanel(app, deg)
idx = app.SelectedPanel;
if idx < 1 || idx > numel(app.Panels), return; end
roi = app.Panels{idx};
if ~isvalid(roi), return; end
roi.RotationAngle = roi.RotationAngle + deg;
app.updatePlots();
end
function adjustTilt(app, delta)
idx = app.SelectedPanel;
if idx < 1 || idx > numel(app.PanelTilts), return; end
newTilt = max(0, min(90, app.PanelTilts(idx) + delta));
app.PanelTilts(idx) = newTilt;
app.TiltSlider.Value = newTilt;
app.TiltLabel.Text = sprintf('%.0f°', newTilt);
app.updatePlots();
end
function resetZoom(app)
if isempty(app.MapRef), return; end
app.MapAxes.XLim = app.MapRef.XWorldLimits;
app.MapAxes.YLim = app.MapRef.YWorldLimits;
end
function addPanelAtClick(app)
% Add panel at the last right-click location
cp = app.MapAxes.CurrentPoint;
cx = cp(1,1);
cy = cp(1,2);
n = numel(app.Panels) + 1;
viewW = diff(app.MapAxes.XLim);
viewH = diff(app.MapAxes.YLim);
pw = viewW * 0.08;
ph = viewH * 0.05;