-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapp.js
More file actions
201 lines (168 loc) · 6.62 KB
/
Copy pathapp.js
File metadata and controls
201 lines (168 loc) · 6.62 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
/**
* Solar Gap Analysis Application
* Fetches NASA POWER API data and calculates max consecutive "no-sun" days.
*/
const UI = {
threshold: document.getElementById('threshold'),
startMonth: document.getElementById('startMonth'),
endMonth: document.getElementById('endMonth'),
locations: document.getElementById('locations'), // New: textarea for multiple locations
btn: document.getElementById('analyzeBtn'),
loader: document.getElementById('loader'),
resultsSection: document.getElementById('resultsSection'),
resultsBody: document.getElementById('resultsBody'),
allTimeMax: document.getElementById('allTimeMax'),
avgMaxGap: document.getElementById('avgMaxGap'),
};
UI.btn.addEventListener('click', async () => {
try {
const threshold = parseFloat(UI.threshold.value) / 1000; // Convert Wh to kWh
const startMonth = parseInt(UI.startMonth.value);
const endMonth = parseInt(UI.endMonth.value);
const locationStrings = UI.locations.value.split('\n').filter(s => s.trim().length > 0);
const allResults = [];
if (locationStrings.length === 0) {
throw new Error('Please enter at least one location.');
}
setLoading(true, `Starting analysis for ${locationStrings.length} locations...`);
for (let i = 0; i < locationStrings.length; i++) {
const locStr = locationStrings[i].trim();
const parts = locStr.split(/[\s,]+/).filter(p => p.length > 0);
if (parts.length < 2) continue;
const lat = parseFloat(parts[0]);
const lon = parseFloat(parts[1]);
if (isNaN(lat) || isNaN(lon)) {
throw new Error(`Invalid coordinates: "${locStr}"`);
}
setLoading(true, `Fetching data for location ${i + 1} of ${locationStrings.length} (${lat}, ${lon})...`);
const rawData = await fetchSolarData(lat, lon);
const locationResults = processSolarGaps(rawData, { lat, lon, threshold, startMonth, endMonth });
if (locationResults.length > 0) {
// Determine the longest gap across all years for this location
const worstYear = locationResults.reduce((prev, current) => (prev.maxGap > current.maxGap) ? prev : current);
allResults.push(worstYear);
}
}
if (allResults.length === 0) {
throw new Error('No data found for the selected range/locations.');
}
renderResults(allResults);
} catch (error) {
alert(`Error: ${error.message}`);
console.error(error);
} finally {
setLoading(false);
}
});
/**
* Fetches daily solar irradiance data from NASA POWER API
* @param {number} lat
* @param {number} lon
* @returns {Promise<Object>}
*/
async function fetchSolarData(lat, lon) {
const start = '19840101';
const end = '20241231';
const url = `https://power.larc.nasa.gov/api/temporal/daily/point?parameters=ALLSKY_SFC_SW_DWN&community=RE&longitude=${lon}&latitude=${lat}&start=${start}&end=${end}&format=JSON`;
const response = await fetch(url);
if (!response.ok) throw new Error('NASA API request failed');
return await response.json();
}
/**
* Processes the raw NASA data to find consecutive low-sun days
* @param {Object} rawData
* @param {Object} config
* @returns {Array} List of yearly results
*/
function processSolarGaps(rawData, config) {
const timeSeries = rawData.properties.parameter.ALLSKY_SFC_SW_DWN;
const years = {};
const results = [];
// Group data by year
for (const [dateStr, value] of Object.entries(timeSeries)) {
const year = dateStr.substring(0, 4);
const month = parseInt(dateStr.substring(4, 6)) - 1; // 0-indexed
// Filter by month range
if (isMonthInRange(month, config.startMonth, config.endMonth)) {
if (!years[year]) years[year] = [];
years[year].push({
date: dateStr,
value: value
});
}
}
// Calculate max consecutive gaps per year
for (const [year, dayList] of Object.entries(years)) {
let maxConsecutive = 0;
let currentConsecutive = 0;
dayList.forEach(day => {
// Check if day is below irradiance threshold
if (day.value < config.threshold) {
currentConsecutive++;
if (currentConsecutive > maxConsecutive) {
maxConsecutive = currentConsecutive;
}
} else {
currentConsecutive = 0;
}
});
results.push({
lat: config.lat,
lon: config.lon,
year: year,
maxGap: maxConsecutive,
range: `${getMonthName(config.startMonth)} - ${getMonthName(config.endMonth)}`
});
}
return results.sort((a, b) => b.year - a.year);
}
/**
* Check if a month index is within the user's selected range (handles wrap-around)
*/
function isMonthInRange(m, start, end) {
if (start <= end) {
return m >= start && m <= end;
} else {
// Wraps around new year (e.g. Oct to April)
return m >= start || m <= end;
}
}
/**
* Renders the results table and summary stats
*/
function renderResults(results) {
UI.resultsBody.innerHTML = '';
UI.resultsSection.style.display = 'block';
let totalMax = 0;
let sumGap = 0;
results.forEach(row => {
const tr = document.createElement('tr');
tr.innerHTML = `
<td>${row.lat.toFixed(4)}</td>
<td>${row.lon.toFixed(4)}</td>
<td style="font-weight: 600; color: ${row.maxGap > 0 ? 'var(--primary)' : 'var(--text-dim)'}">
${row.maxGap} ${row.maxGap === 1 ? 'day' : 'days'}
</td>
<td>Worst year: ${row.year} <small>(${row.range})</small></td>
`;
UI.resultsBody.appendChild(tr);
if (row.maxGap > totalMax) totalMax = row.maxGap;
sumGap += row.maxGap;
});
UI.allTimeMax.textContent = totalMax;
UI.avgMaxGap.textContent = (sumGap / results.length).toFixed(1);
UI.resultsSection.scrollIntoView({ behavior: 'smooth' });
}
function setLoading(isLoading, message = 'Processing...') {
UI.loader.style.display = isLoading ? 'flex' : 'none';
UI.btn.disabled = isLoading;
UI.btn.textContent = isLoading ? 'Processing...' : 'Analyze Historical Gaps';
if (message) {
const p = UI.loader.querySelector('p');
if (p) p.textContent = message;
}
}
function getMonthName(index) {
const names = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"];
return names[index];
}