@nexgen-os/weather-files 0.0.0-stage → 0.4.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
package/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2026 Nexgen OS contributors
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,61 @@
1
- # Temporary Holding Version
1
+ # `@nexgen-os/weather-files` — EPW and TMY3 ⇄ hourly series
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Reads the weather files solar and building tools exchange — EPW (EnergyPlus
4
+ Weather: PVGIS, Meteonorm, climate.onebuilding.org, EnergyPlus) and TMY3
5
+ (the National Solar Radiation Database's CSV) — into hourly series dated at
6
+ their start in UTC, and writes series back as EPW, so that a PVsyst,
7
+ PV\*SOL, SAM, EnergyPlus or pvlib user reruns the same weather. MIT; no
8
+ dependency, no database, no network.
9
+
10
+ | File | `WeatherSeries` | Notes |
11
+ |---|---|---|
12
+ | global, direct normal, diffuse horizontal radiation (Wh/m² over the hour) | `ghi`, `dni`, `dhi`, `interval`, `1 hour`, W/m² | dated at the start of the hour, in UTC |
13
+ | dry-bulb temperature, wind speed | `temperature` (°C), `wind_speed` (m/s), `instant` | dated at the hour's stamp, in UTC |
14
+ | hour 1 to 24, local standard time | UTC, from the header's offset | daylight saving never applies in these files |
15
+ | months from several years (a typical year) | one calendar year, `options.year`, by default the latest year the months come from | `typical: true`, `years` |
16
+ | a real year | its own dates | `typical: false` |
17
+ | missing values (EPW 9999, 99.9, 999; TMY3 −9900) | left out, counted in `missing` | never filled |
18
+ | dew point, humidity, pressure, wind direction, albedo… | not carried yet, listed in `skipped` | written back as missing |
19
+ | `LOCATION` line, TMY3 station line | `location`: name, region, country as written, data source, station, latitude, longitude, offset, elevation | |
20
+
21
+ Each series names the unit the formats write it in, by its QUDT code
22
+ (`W-PER-M2`, `DEG_C`, `M-PER-SEC`); `writeEpw()` writes every hour of the
23
+ year, missing ones with the EPW codes, 29 February only when the series
24
+ have it.
25
+
26
+ ```ts
27
+ import { readEpw, writeEpw } from '@nexgen-os/weather-files';
28
+ import { importWeatherFile, exportWeatherYear } from '@nexgen-os/core';
29
+
30
+ const file = readEpw(text); // or readTmy3(text)
31
+ for (const w of file.warnings) console.warn(w.code, w.message);
32
+ await importWeatherFile(db, { organisationId, objectId: pointOrSite }, file, { sourceCode: 'pvgis' });
33
+
34
+ const epw = writeEpw(await exportWeatherYear(db, { objectId: pointOrSite, sourceCode: 'pvgis', kind: 'simulated',
35
+ name: 'typical year 2005-2020', year: file.year!, location: file.location }));
36
+ ```
37
+
38
+ What it never does: store a series, convert a unit, fill a missing value.
39
+ Into Nexgen OS, `importWeatherFile()` of `@nexgen-os/core` stores the series
40
+ on the object named — a weather point of the `weather` module or a participant —
41
+ through `store()`, converted by the `units` vocabulary, with the `sources`
42
+ row the caller names: a typical year `simulated` and named
43
+ `typical year <first>-<last>`, a real year `measured`; importing the same
44
+ file again replaces the values. `exportWeatherYear()` reads an object's
45
+ series back through `resample()` for `writeEpw()`.
46
+
47
+ ## The time offset is checked
48
+
49
+ A file states its offset from UTC and is read in it; the hour at which the
50
+ irradiance peaks is then compared with the solar noon of its longitude. A
51
+ file whose hours sit one or more hours away is reported as
52
+ `time_offset_suspect`, with the offset its irradiance implies. PVGIS writes
53
+ its EPW hours in UTC under a header that gives the local offset: read it
54
+ with `{ utcOffsetHours: 0 }`.
55
+
56
+ ## Refusals
57
+
58
+ `epw_unreadable`, `tmy3_unreadable` (not the format, or a row without a
59
+ date), `epw_subhourly_unsupported` (more than one record per hour),
60
+ `epw_duplicate_hour` / `tmy3_duplicate_hour` (the same hour twice),
61
+ `weather_file_unreadable` (no latitude, longitude or offset in the header).
@@ -0,0 +1,82 @@
1
+ export type WeatherQuantity = 'ghi' | 'dni' | 'dhi' | 'temperature' | 'wind_speed';
2
+ /** The quantities both formats carry, in the order they are returned. */
3
+ export declare const WEATHER_QUANTITIES: readonly WeatherQuantity[];
4
+ /** A value at the start of its hour (`interval`) or at its instant, in UTC. */
5
+ export interface WeatherPoint {
6
+ at: string;
7
+ value: number;
8
+ }
9
+ /** One quantity of a file as a series. */
10
+ export interface WeatherSeries {
11
+ quantity_code: string;
12
+ /** `interval` from `at` for one `step` (irradiance), `instant` at `at` (temperature, wind). */
13
+ value_kind: 'interval' | 'instant' | 'cumulative';
14
+ /** `1 hour`: both formats give one row per hour. */
15
+ step: string | null;
16
+ /** The unit the values are in, by its QUDT code: `W-PER-M2`, `DEG_C`, `M-PER-SEC`. */
17
+ unit?: string;
18
+ values: WeatherPoint[];
19
+ }
20
+ /** What `writeEpw()` writes: one calendar year of series at a location. */
21
+ export interface WeatherYear {
22
+ location: WeatherFileLocation;
23
+ series: WeatherSeries[];
24
+ year: number;
25
+ comment?: string;
26
+ }
27
+ export interface WeatherFileLocation {
28
+ name: string | null;
29
+ /** The state, province or region as the file writes it. */
30
+ region: string | null;
31
+ /** The country as the file writes it (a code or a name), never interpreted. */
32
+ country: string | null;
33
+ /** Where the data come from, as the file says (`ECMWF/ERA`, `TMY3`, a station network). */
34
+ data_source: string | null;
35
+ /** The station's identifier (WMO, USAF), when there is one. */
36
+ station_id: string | null;
37
+ lat: number;
38
+ lon: number;
39
+ /** Hours from UTC of the file's standard time, east positive: what its hours are read in. */
40
+ utc_offset_hours: number;
41
+ elevation_m: number | null;
42
+ }
43
+ export interface WeatherFileWarning {
44
+ code: 'time_offset_suspect';
45
+ message: string;
46
+ /** The offset the irradiance implies, hours from UTC. */
47
+ implied_utc_offset_hours: number;
48
+ }
49
+ export interface WeatherFile {
50
+ format: 'epw' | 'tmy3';
51
+ location: WeatherFileLocation;
52
+ /** One calendar year made of months from more than one year: a typical year, laid on `year`. */
53
+ typical: boolean;
54
+ /** The years the rows come from, in order. */
55
+ years: number[];
56
+ /** The calendar year a typical year was laid on; null for real years. */
57
+ year: number | null;
58
+ /** `ghi`, `dni`, `dhi` (W/m², hour intervals), `temperature` (°C) and `wind_speed` (m/s) (instants), when the file has them. */
59
+ series: WeatherSeries[];
60
+ /** Fields of the file that hold data and are not among the five quantities read. */
61
+ skipped: string[];
62
+ /** Values the file marks as missing, per quantity: left out. */
63
+ missing: Partial<Record<WeatherQuantity, number>>;
64
+ warnings: WeatherFileWarning[];
65
+ }
66
+ export interface ReadOptions {
67
+ /** The calendar year a typical year lands on. Default: the latest year it was made from. */
68
+ year?: number;
69
+ /** Overrides the header's time zone, hours from UTC (0 for a PVGIS EPW). */
70
+ utcOffsetHours?: number;
71
+ }
72
+ /** An EPW file as series dated at their start (intervals) or instant, in UTC. */
73
+ export declare function readEpw(text: string, options?: ReadOptions): WeatherFile;
74
+ /**
75
+ * Series written as an EPW file for one calendar year in the location's
76
+ * standard time: what PVsyst, PV*SOL, SAM, EnergyPlus or pvlib reads to
77
+ * rerun the same weather. Hours without a value are written missing; 29
78
+ * February is written only when the series have values that day.
79
+ */
80
+ export declare function writeEpw(input: WeatherYear): string;
81
+ /** A TMY3 file of the National Solar Radiation Database as series dated at their start (intervals) or instant, in UTC. */
82
+ export declare function readTmy3(text: string, options?: ReadOptions): WeatherFile;
package/dist/index.js ADDED
@@ -0,0 +1,358 @@
1
+ // Weather files ⇄ hourly series: EPW (EnergyPlus Weather) in and out, TMY3 in.
2
+ //
3
+ // EPW is how a typical year travels between solar and building tools: PVGIS,
4
+ // Meteonorm, climate.onebuilding.org and EnergyPlus write it, PVsyst, PV*SOL,
5
+ // SAM and pvlib read it. TMY3 is the CSV of the US National Solar Radiation
6
+ // Database that many older studies still carry. Both give one row per hour.
7
+ //
8
+ // Three conventions are kept straight here so that nobody downstream has to
9
+ // know them:
10
+ // - both formats stamp an hour at its END, in local STANDARD time (no
11
+ // daylight saving), hours 1 to 24; the series returned date an interval
12
+ // value (irradiance) at its start and an instant value (temperature,
13
+ // wind) at its instant, both in UTC;
14
+ // - a typical year is made of months from different years; it lands on one
15
+ // calendar year (`options.year`, by default the latest year it was made
16
+ // from), and says so (`typical`, `years`);
17
+ // - a missing value (EPW 9999, 99.9, 999; TMY3 -9900) is left out, never
18
+ // filled.
19
+ //
20
+ // The header's time zone is trusted, then checked: the hour of the
21
+ // irradiance-weighted noon is compared with the solar noon of the file's
22
+ // longitude, and a file whose hours are off by one or more is reported by
23
+ // name (`time_offset_suspect`) with the offset its irradiance implies. PVGIS
24
+ // writes its EPW hours in UTC under a header that gives the local offset;
25
+ // `utcOffsetHours: 0` reads such a file right.
26
+ //
27
+ // The library imports nothing, opens no connection and calls no network:
28
+ // what a file holds is returned as plain series, and storing them is an
29
+ // importer's job.
30
+ //
31
+ // SPDX-License-Identifier: MIT
32
+ /** The quantities both formats carry, in the order they are returned. */
33
+ export const WEATHER_QUANTITIES = ['ghi', 'dni', 'dhi', 'temperature', 'wind_speed'];
34
+ const HOUR_MS = 3_600_000;
35
+ const INTERVAL = ['ghi', 'dni', 'dhi'];
36
+ const ORDER = WEATHER_QUANTITIES;
37
+ /**
38
+ * The unit each quantity is written in by both formats, by its QUDT code:
39
+ * a reader converts from it. An hour's radiation in Wh/m² is the hour's
40
+ * mean irradiance in W/m².
41
+ */
42
+ const UNITS = { ghi: 'W-PER-M2', dni: 'W-PER-M2', dhi: 'W-PER-M2', temperature: 'DEG_C', wind_speed: 'M-PER-SEC' };
43
+ // ---------------------------------------------------------------------------
44
+ // EPW
45
+ // ---------------------------------------------------------------------------
46
+ /**
47
+ * EPW data fields after the date, minute and flags (field 6 onward), in
48
+ * order, with the value that marks them missing. Five are read; the others
49
+ * are written back as missing.
50
+ */
51
+ const EPW_FIELDS = [
52
+ { name: 'dry_bulb_temperature', quantity: 'temperature', missing: 99.9 },
53
+ { name: 'dew_point_temperature', missing: 99.9 },
54
+ { name: 'relative_humidity', missing: 999 },
55
+ { name: 'atmospheric_pressure', missing: 999999 },
56
+ { name: 'extraterrestrial_horizontal_radiation', missing: 9999 },
57
+ { name: 'extraterrestrial_direct_normal_radiation', missing: 9999 },
58
+ { name: 'horizontal_infrared_radiation', missing: 9999 },
59
+ { name: 'global_horizontal_radiation', quantity: 'ghi', missing: 9999 },
60
+ { name: 'direct_normal_radiation', quantity: 'dni', missing: 9999 },
61
+ { name: 'diffuse_horizontal_radiation', quantity: 'dhi', missing: 9999 },
62
+ { name: 'global_horizontal_illuminance', missing: 999999 },
63
+ { name: 'direct_normal_illuminance', missing: 999999 },
64
+ { name: 'diffuse_horizontal_illuminance', missing: 999999 },
65
+ { name: 'zenith_luminance', missing: 9999 },
66
+ { name: 'wind_direction', missing: 999 },
67
+ { name: 'wind_speed', quantity: 'wind_speed', missing: 999 },
68
+ { name: 'total_sky_cover', missing: 99 },
69
+ { name: 'opaque_sky_cover', missing: 99 },
70
+ { name: 'visibility', missing: 9999 },
71
+ { name: 'ceiling_height', missing: 99999 },
72
+ { name: 'present_weather_observation', missing: 9 },
73
+ { name: 'present_weather_codes', missing: 999999999 },
74
+ { name: 'precipitable_water', missing: 999 },
75
+ { name: 'aerosol_optical_depth', missing: 0.999 },
76
+ { name: 'snow_depth', missing: 999 },
77
+ { name: 'days_since_last_snowfall', missing: 99 },
78
+ { name: 'albedo', missing: 999 },
79
+ { name: 'liquid_precipitation_depth', missing: 999 },
80
+ { name: 'liquid_precipitation_quantity', missing: 99 },
81
+ ];
82
+ /** Fields that say nothing about the weather when they hold a value. */
83
+ const EPW_NOT_DATA = new Set(['present_weather_observation', 'present_weather_codes']);
84
+ const EPW_FLAGS = '?9?9?9?9E0?9?9?9?9?9?9?9?9?9?9?9?9?9?9?9*9*9?9?9?9';
85
+ /** An EPW file as series dated at their start (intervals) or instant, in UTC. */
86
+ export function readEpw(text, options = {}) {
87
+ const lines = text.replace(/^/, '').split(/\r?\n/);
88
+ const header = lines[0]?.split(',') ?? [];
89
+ if (header[0]?.trim().toUpperCase() !== 'LOCATION' || header.length < 10) {
90
+ throw new Error('epw_unreadable: the first line of an EPW file is LOCATION with nine fields');
91
+ }
92
+ const location = {
93
+ name: text_(header[1]),
94
+ region: text_(header[2]),
95
+ country: text_(header[3]),
96
+ data_source: text_(header[4]),
97
+ station_id: text_(header[5]),
98
+ lat: num(header[6], 'latitude'),
99
+ lon: num(header[7], 'longitude'),
100
+ utc_offset_hours: options.utcOffsetHours ?? num(header[8], 'time zone'),
101
+ elevation_m: Number.isFinite(Number(header[9])) ? Number(header[9]) : null,
102
+ };
103
+ const periods = lines.slice(1, 8).find((l) => /^DATA PERIODS/i.test(l));
104
+ const perHour = periods ? Number(periods.split(',')[2]) : 1;
105
+ if (perHour !== 1)
106
+ throw new Error(`epw_subhourly_unsupported: ${perHour} records per hour; the reader takes hourly files`);
107
+ const rows = [];
108
+ const seen = new Set();
109
+ for (const line of lines.slice(8)) {
110
+ if (!line.trim())
111
+ continue;
112
+ const f = line.split(',');
113
+ if (f.length < 6 + EPW_FIELDS.length - 2)
114
+ throw new Error(`epw_unreadable: a data row has ${f.length} fields: ${line.slice(0, 40)}`);
115
+ const values = {};
116
+ EPW_FIELDS.forEach((field, i) => {
117
+ const raw = f[6 + i];
118
+ const v = raw === undefined || raw.trim() === '' ? NaN : Number(raw);
119
+ const present = Number.isFinite(v) && v < field.missing;
120
+ if (field.quantity)
121
+ values[field.quantity] = present ? zero(v) : null;
122
+ else if (present && !EPW_NOT_DATA.has(field.name))
123
+ seen.add(field.name);
124
+ });
125
+ rows.push({ year: int(f[0]), month: int(f[1]), day: int(f[2]), hour: int(f[3]), values });
126
+ }
127
+ return toWeatherFile('epw', location, rows, [...seen], options);
128
+ }
129
+ /**
130
+ * Series written as an EPW file for one calendar year in the location's
131
+ * standard time: what PVsyst, PV*SOL, SAM, EnergyPlus or pvlib reads to
132
+ * rerun the same weather. Hours without a value are written missing; 29
133
+ * February is written only when the series have values that day.
134
+ */
135
+ export function writeEpw(input) {
136
+ const { location, year } = input;
137
+ const offsetMs = location.utc_offset_hours * HOUR_MS;
138
+ const byQuantity = new Map();
139
+ for (const s of input.series) {
140
+ byQuantity.set(s.quantity_code, new Map(s.values.map((p) => [Date.parse(p.at), p.value])));
141
+ }
142
+ const valueAt = (q, row) => {
143
+ const end = Date.UTC(row.y, row.m - 1, row.d, row.h) - offsetMs;
144
+ return byQuantity.get(q)?.get(INTERVAL.includes(q) ? end - HOUR_MS : end);
145
+ };
146
+ const leap = isLeap(year);
147
+ const out = [];
148
+ for (let m = 1; m <= 12; m++) {
149
+ for (let d = 1; d <= daysIn(year, m); d++) {
150
+ const hours = Array.from({ length: 24 }, (_, i) => ({ y: year, m, d, h: i + 1 }));
151
+ if (m === 2 && d === 29 && !hours.some((r) => ORDER.some((q) => valueAt(q, r) !== undefined)))
152
+ continue;
153
+ for (const r of hours) {
154
+ const fields = EPW_FIELDS.map((field) => {
155
+ const v = field.quantity ? valueAt(field.quantity, r) : undefined;
156
+ return v === undefined ? String(field.missing) : fmt(v);
157
+ });
158
+ out.push([year, m, d, r.h, 0, EPW_FLAGS, ...fields].join(','));
159
+ }
160
+ }
161
+ }
162
+ const febHas29 = out.some((l) => l.startsWith(`${year},2,29,`));
163
+ const weekday = new Date(Date.UTC(year, 0, 1)).toLocaleDateString('en-US', { weekday: 'long', timeZone: 'UTC' });
164
+ const field = (s) => (s ?? '-').replace(/,/g, ' ');
165
+ return [
166
+ ['LOCATION', field(location.name), field(location.region), field(location.country), field(location.data_source), field(location.station_id),
167
+ fmt(location.lat), fmt(location.lon), fmt(location.utc_offset_hours), location.elevation_m === null ? '0' : fmt(location.elevation_m)].join(','),
168
+ 'DESIGN CONDITIONS,0',
169
+ 'TYPICAL/EXTREME PERIODS,0',
170
+ 'GROUND TEMPERATURES,0',
171
+ `HOLIDAYS/DAYLIGHT SAVINGS,${leap && febHas29 ? 'Yes' : 'No'},0,0,0`,
172
+ `COMMENTS 1,${(input.comment ?? 'Written by @nexgen-os/weather-files').replace(/[\r\n]/g, ' ')}`,
173
+ 'COMMENTS 2,Hours in local standard time; missing values carry the EPW missing codes',
174
+ `DATA PERIODS,1,1,Data,${weekday},1/1,12/31`,
175
+ ...out,
176
+ ].join('\n') + '\n';
177
+ }
178
+ // ---------------------------------------------------------------------------
179
+ // TMY3
180
+ // ---------------------------------------------------------------------------
181
+ const TMY3_COLUMNS = {
182
+ ghi: 'GHI (W/m^2)',
183
+ dni: 'DNI (W/m^2)',
184
+ dhi: 'DHI (W/m^2)',
185
+ temperature: 'Dry-bulb (C)',
186
+ wind_speed: 'Wspd (m/s)',
187
+ };
188
+ const TMY3_SKIPPED = ['Dew-point (C)', 'RHum (%)', 'Pressure (mbar)', 'Wdir (degrees)', 'Alb (unitless)', 'Pwat (cm)', 'AOD (unitless)', 'Lprecip depth (mm)'];
189
+ /** A TMY3 file of the National Solar Radiation Database as series dated at their start (intervals) or instant, in UTC. */
190
+ export function readTmy3(text, options = {}) {
191
+ const lines = text.replace(/^/, '').split(/\r?\n/);
192
+ const meta = csv(lines[0] ?? '');
193
+ const columns = csv(lines[1] ?? '').map((c) => c.trim());
194
+ const at = (name) => columns.indexOf(name);
195
+ if (meta.length < 7 || at('Date (MM/DD/YYYY)') !== 0 || at('Time (HH:MM)') !== 1) {
196
+ throw new Error('tmy3_unreadable: a TMY3 file starts with the station line, then the column names Date (MM/DD/YYYY), Time (HH:MM), …');
197
+ }
198
+ const location = {
199
+ name: text_(meta[1]),
200
+ region: text_(meta[2]),
201
+ country: null,
202
+ data_source: 'TMY3',
203
+ station_id: text_(meta[0]),
204
+ lat: num(meta[4], 'latitude'),
205
+ lon: num(meta[5], 'longitude'),
206
+ utc_offset_hours: options.utcOffsetHours ?? num(meta[3], 'time zone'),
207
+ elevation_m: Number.isFinite(Number(meta[6])) ? Number(meta[6]) : null,
208
+ };
209
+ const index = Object.fromEntries(ORDER.map((q) => [q, at(TMY3_COLUMNS[q])]));
210
+ const seen = new Set();
211
+ const rows = [];
212
+ for (const line of lines.slice(2)) {
213
+ if (!line.trim())
214
+ continue;
215
+ const f = line.split(',');
216
+ const date = /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/.exec(f[0] ?? '');
217
+ const time = /^(\d{1,2}):00$/.exec(f[1] ?? '');
218
+ if (!date || !time)
219
+ throw new Error(`tmy3_unreadable: a row without a date and an hour: ${line.slice(0, 40)}`);
220
+ const values = {};
221
+ for (const q of ORDER) {
222
+ if (index[q] < 0)
223
+ continue;
224
+ const v = Number(f[index[q]]);
225
+ values[q] = Number.isFinite(v) && v > -9900 ? zero(v) : null;
226
+ }
227
+ for (const name of TMY3_SKIPPED) {
228
+ const i = at(name);
229
+ const v = i < 0 ? NaN : Number(f[i]);
230
+ if (Number.isFinite(v) && v > -9900)
231
+ seen.add(name);
232
+ }
233
+ rows.push({ year: Number(date[3]), month: Number(date[1]), day: Number(date[2]), hour: Number(time[1]), values });
234
+ }
235
+ return toWeatherFile('tmy3', location, rows, [...seen], options);
236
+ }
237
+ // ---------------------------------------------------------------------------
238
+ // Rows to series, shared by both readers
239
+ // ---------------------------------------------------------------------------
240
+ function toWeatherFile(format, location, rows, skipped, options) {
241
+ if (rows.length === 0)
242
+ throw new Error(`${format}_unreadable: no data row`);
243
+ const years = [...new Set(rows.map((r) => r.year))].sort((a, b) => a - b);
244
+ const typical = years.length > 1 && new Set(rows.map((r) => `${r.month}-${r.day}-${r.hour}`)).size === rows.length;
245
+ const year = typical ? options.year ?? years[years.length - 1] : null;
246
+ const offsetMs = location.utc_offset_hours * HOUR_MS;
247
+ const points = new Map(ORDER.map((q) => [q, []]));
248
+ const missing = {};
249
+ const instants = new Set();
250
+ for (const r of rows) {
251
+ if (r.hour < 1 || r.hour > 24 || r.month < 1 || r.month > 12 || r.day < 1 || r.day > 31) {
252
+ throw new Error(`${format}_unreadable: no such hour ${r.year}-${r.month}-${r.day} ${r.hour}`);
253
+ }
254
+ const y = year ?? r.year;
255
+ if (r.month === 2 && r.day === 29 && !isLeap(y))
256
+ continue;
257
+ const end = Date.UTC(y, r.month - 1, r.day, r.hour) - offsetMs;
258
+ if (instants.has(end))
259
+ throw new Error(`${format}_duplicate_hour: ${y}-${r.month}-${r.day} hour ${r.hour} comes twice`);
260
+ instants.add(end);
261
+ for (const q of ORDER) {
262
+ const v = r.values[q];
263
+ if (v === undefined)
264
+ continue;
265
+ if (v === null) {
266
+ missing[q] = (missing[q] ?? 0) + 1;
267
+ continue;
268
+ }
269
+ points.get(q).push({ at: new Date(INTERVAL.includes(q) ? end - HOUR_MS : end).toISOString(), value: v });
270
+ }
271
+ }
272
+ const series = ORDER.filter((q) => rows.some((r) => r.values[q] !== undefined)).map((q) => ({
273
+ quantity_code: q,
274
+ value_kind: INTERVAL.includes(q) ? 'interval' : 'instant',
275
+ step: '1 hour',
276
+ unit: UNITS[q],
277
+ values: points.get(q).sort((a, b) => a.at.localeCompare(b.at)),
278
+ }));
279
+ const warnings = [];
280
+ const implied = impliedOffset(rows, location);
281
+ if (implied !== null && implied !== location.utc_offset_hours) {
282
+ warnings.push({
283
+ code: 'time_offset_suspect',
284
+ message: `the irradiance peaks as if the hours were at UTC${implied >= 0 ? '+' : ''}${implied}, the file reads them at UTC${location.utc_offset_hours >= 0 ? '+' : ''}${location.utc_offset_hours}`,
285
+ implied_utc_offset_hours: implied,
286
+ });
287
+ }
288
+ return { format, location, typical, years, year, series, skipped, missing, warnings };
289
+ }
290
+ /**
291
+ * The offset the irradiance implies: the irradiance-weighted middle of the
292
+ * hours, against the solar noon of the longitude (12 h + offset − lon/15 in
293
+ * standard time, the equation of time averaging out over the days). Null
294
+ * without irradiance; the header's offset when they agree within half an hour.
295
+ */
296
+ function impliedOffset(rows, location) {
297
+ let weight = 0;
298
+ let sum = 0;
299
+ for (const r of rows) {
300
+ const g = r.values.ghi;
301
+ if (g === null || g === undefined || g <= 0)
302
+ continue;
303
+ weight += g;
304
+ sum += g * (r.hour - 0.5);
305
+ }
306
+ if (weight === 0)
307
+ return null;
308
+ const solarNoon = 12 + location.utc_offset_hours - location.lon / 15;
309
+ const shift = sum / weight - solarNoon;
310
+ return Math.abs(shift) <= 0.5 ? location.utc_offset_hours : location.utc_offset_hours + Math.round(shift);
311
+ }
312
+ // ---------------------------------------------------------------------------
313
+ // Small things
314
+ // ---------------------------------------------------------------------------
315
+ function text_(s) {
316
+ const t = (s ?? '').trim();
317
+ return t === '' || t === '-' || /^unknown$/i.test(t) ? null : t;
318
+ }
319
+ function num(s, what) {
320
+ const n = Number((s ?? '').trim());
321
+ if ((s ?? '').trim() === '' || !Number.isFinite(n))
322
+ throw new Error(`weather_file_unreadable: no ${what} in the header`);
323
+ return n;
324
+ }
325
+ function int(s) {
326
+ return Math.trunc(Number(s));
327
+ }
328
+ /** -0, which some writers print for a night value, is 0. */
329
+ function zero(v) {
330
+ return v === 0 ? 0 : v;
331
+ }
332
+ function fmt(v) {
333
+ return String(zero(Math.round(v * 1e4) / 1e4));
334
+ }
335
+ function isLeap(y) {
336
+ return (y % 4 === 0 && y % 100 !== 0) || y % 400 === 0;
337
+ }
338
+ function daysIn(y, m) {
339
+ return new Date(Date.UTC(y, m, 0)).getUTCDate();
340
+ }
341
+ /** One CSV line, double quotes honoured. */
342
+ function csv(line) {
343
+ const out = [];
344
+ let cur = '';
345
+ let quoted = false;
346
+ for (const c of line) {
347
+ if (c === '"')
348
+ quoted = !quoted;
349
+ else if (c === ',' && !quoted) {
350
+ out.push(cur);
351
+ cur = '';
352
+ }
353
+ else
354
+ cur += c;
355
+ }
356
+ out.push(cur);
357
+ return out;
358
+ }
package/package.json CHANGED
@@ -1,6 +1,34 @@
1
1
  {
2
2
  "name": "@nexgen-os/weather-files",
3
- "version": "0.0.0-stage",
4
- "stub": true,
5
- "description": "Temporary package placeholder for staged publishing"
6
- }
3
+ "version": "0.4.1",
4
+ "description": "EPW and TMY3 hourly weather files read into series dated at their start in UTC, and EPW written back. No database, no dependency.",
5
+ "license": "MIT",
6
+ "repository": {
7
+ "type": "git",
8
+ "url": "git+https://github.com/nexgen-os/nexgen-os.git",
9
+ "directory": "packages/formats/weather-files"
10
+ },
11
+ "publishConfig": {
12
+ "access": "public"
13
+ },
14
+ "type": "module",
15
+ "engines": {
16
+ "node": ">=20"
17
+ },
18
+ "files": [
19
+ "dist",
20
+ "README.md",
21
+ "LICENSE"
22
+ ],
23
+ "main": "./dist/index.js",
24
+ "types": "./dist/index.d.ts",
25
+ "exports": {
26
+ ".": {
27
+ "types": "./dist/index.d.ts",
28
+ "import": "./dist/index.js"
29
+ }
30
+ },
31
+ "scripts": {
32
+ "build": "tsc -p tsconfig.build.json"
33
+ }
34
+ }