Skip to main content

pvlib/
irradiance.rs

1use std::f64::consts::PI;
2use crate::atmosphere;
3
4/// Perez et al. (1990) Table 1 — brightness coefficients
5/// Columns: f11, f12, f13, f21, f22, f23
6/// Rows: 8 sky clearness bins (epsilon ranges)
7const PEREZ_COEFFICIENTS: [[f64; 6]; 8] = [
8    [-0.0083117, 0.5877277, -0.0620636, -0.0596012, 0.0721249, -0.0220216],
9    [0.1299457, 0.6825954, -0.1513752, -0.0189325, 0.0659650, -0.0288748],
10    [0.3296958, 0.4868735, -0.2210958, 0.0554140, -0.0639588, -0.0260542],
11    [0.5682053, 0.1874990, -0.2951290, 0.1088631, -0.1519229, -0.0139754],
12    [0.8730280, -0.3920403, -0.3616149, 0.2255647, -0.4620442,  0.0012448],
13    [1.1326077, -1.2367284, -0.4118494, 0.2877813, -0.8230357,  0.0558225],
14    [1.0601591, -1.5999137, -0.3589221, 0.2642124, -1.1272340,  0.1310694],
15    [0.6777470, -0.3272588, -0.2504286, 0.1561313, -1.3765031,  0.2506212],
16];
17
18/// Calculate the angle of incidence (AOI) of the solar vector on a surface.
19#[inline]
20pub fn aoi(surface_tilt: f64, surface_azimuth: f64, solar_zenith: f64, solar_azimuth: f64) -> f64 {
21    let tilt_rad = surface_tilt.to_radians();
22    let surf_az_rad = surface_azimuth.to_radians();
23    let zen_rad = solar_zenith.to_radians();
24    let sol_az_rad = solar_azimuth.to_radians();
25
26    let cos_aoi = zen_rad.cos() * tilt_rad.cos()
27        + zen_rad.sin() * tilt_rad.sin() * (sol_az_rad - surf_az_rad).cos();
28    
29    let cos_aoi = cos_aoi.clamp(-1.0, 1.0);
30    cos_aoi.acos().to_degrees()
31}
32
33/// Calculate extraterrestrial solar irradiance for a day of year (Spencer 1971).
34#[inline]
35pub fn get_extra_radiation(dayofyear: i32) -> f64 {
36    let b = 2.0 * PI * ((dayofyear - 1) as f64) / 365.0;
37    let rover_r0_sqrd = 1.00011
38        + 0.034221 * b.cos()
39        + 0.00128 * b.sin()
40        + 0.000719 * (2.0 * b).cos()
41        + 0.000077 * (2.0 * b).sin();
42    1366.1 * rover_r0_sqrd
43}
44
45/// Isotropic diffuse model.
46#[inline]
47pub fn isotropic(surface_tilt: f64, dhi: f64) -> f64 {
48    dhi * (1.0 + surface_tilt.to_radians().cos()) / 2.0
49}
50
51/// Hay-Davies diffuse sky model.
52/// 
53/// # References
54/// Hay, J.E. and Davies, J.A., 1980, "Calculations of the solar radiation incident on an inclined surface", 
55/// in Proceedings of the First Canadian Solar Radiation Data Workshop.
56#[inline]
57pub fn haydavies(surface_tilt: f64, _surface_azimuth: f64, dhi: f64, dni: f64, dni_extra: f64, solar_zenith: f64, _solar_azimuth: f64, aoi_in: f64) -> f64 {
58    let mut a = 0.0;
59    if dni_extra > 0.0 {
60        a = dni / dni_extra;
61    }
62    let a = a.clamp(0.0, 1.0);
63    let mut cos_z = solar_zenith.to_radians().cos();
64    if cos_z < 0.0436 { cos_z = 0.0436; }
65    
66    let cos_aoi = aoi_in.to_radians().cos().max(0.0);
67    let r_b = cos_aoi / cos_z;
68    
69    dhi * ((1.0 - a) * (1.0 + surface_tilt.to_radians().cos()) / 2.0 + a * r_b)
70}
71
72/// Klucher diffuse sky model.
73/// 
74/// # References
75/// Klucher, T.M., 1979, "Evaluation of models to predict insolation on tilted surfaces," 
76/// Solar Energy, 23(2), pp. 111-114.
77#[inline]
78pub fn klucher(surface_tilt: f64, _surface_azimuth: f64, dhi: f64, ghi: f64, solar_zenith: f64, _solar_azimuth: f64, aoi_in: f64) -> f64 {
79    let mut f = 0.0;
80    if ghi > 0.0 {
81        let frac = dhi / ghi;
82        f = 1.0 - frac * frac;
83    }
84    let f = f.clamp(0.0, 1.0);
85    
86    let _cos_z = solar_zenith.to_radians().cos();
87    let cos_aoi = aoi_in.to_radians().cos().max(0.0);
88    let tilt_rad = surface_tilt.to_radians();
89    
90    let term1 = 1.0 + f * (tilt_rad / 2.0).sin().powi(3);
91    let term2 = 1.0 + f * cos_aoi.powi(2) * (solar_zenith.to_radians().sin()).powi(3);
92    
93    dhi * ((1.0 + tilt_rad.cos()) / 2.0) * term1 * term2
94}
95
96/// Perez diffuse sky model.
97/// 
98/// # References
99/// Perez, R., Ineichen, P., Seals, R., Michalsky, J. and Stewart, R., 1990, 
100/// "Modeling daylight availability and irradiance components from direct and global irradiance," 
101/// Solar Energy, 44(5), pp. 271-289.
102#[inline]
103pub fn perez(surface_tilt: f64, _surface_azimuth: f64, dhi: f64, dni: f64, dni_extra: f64, solar_zenith: f64, _solar_azimuth: f64, airmass: f64, aoi_in: f64) -> f64 {
104    let mut cos_z = solar_zenith.to_radians().cos();
105    if cos_z < 0.0436 { cos_z = 0.0436; } // cap to ~87.5 deg
106    let cos_aoi = aoi_in.to_radians().cos().max(0.0); // beam parallel to surface if >90
107
108    // sky clearness epsilon
109    let _a = (dni_extra * 1e-6).max(1.0); // essentially 1.0 for bounds, simplified for delta
110    let delta = dhi * airmass / dni_extra;
111    
112    let mut epsilon = 1.0;
113    if dhi > 0.0 {
114        epsilon = ((dhi + dni) / dhi + 1.041 * solar_zenith.to_radians().powi(3)) / 
115                  (1.0 + 1.041 * solar_zenith.to_radians().powi(3));
116    }
117
118    let bin = if epsilon < 1.065 { 0 }
119    else if epsilon < 1.230 { 1 }
120    else if epsilon < 1.500 { 2 }
121    else if epsilon < 1.950 { 3 }
122    else if epsilon < 2.800 { 4 }
123    else if epsilon < 4.500 { 5 }
124    else if epsilon < 6.200 { 6 }
125    else { 7 };
126
127    let coeffs = PEREZ_COEFFICIENTS[bin];
128    let mut f1 = coeffs[0] + coeffs[1] * delta + coeffs[2] * solar_zenith.to_radians();
129    f1 = f1.max(0.0);
130    let f2 = coeffs[3] + coeffs[4] * delta + coeffs[5] * solar_zenith.to_radians();
131
132    let a_perez = cos_aoi;
133    let b_perez = cos_z;
134
135    dhi * ((1.0 - f1) * (1.0 + surface_tilt.to_radians().cos()) / 2.0 + f1 * a_perez / b_perez + f2 * surface_tilt.to_radians().sin())
136}
137
138/// Erbs decomposition model.
139/// 
140/// # References
141/// Erbs, D.G., Klein, S.A. and Duffie, J.A., 1982, 
142/// "Estimation of the diffuse radiation fraction for hourly, daily and monthly-average global radiation," 
143/// Solar Energy, 28(4), pp. 293-302.
144#[inline]
145pub fn erbs(ghi: f64, zenith: f64, _day_of_year: u32, dni_extra: f64) -> (f64, f64) {
146    if ghi <= 0.0 || zenith >= 90.0 { return (0.0, 0.0); }
147    let mut cos_z = zenith.to_radians().cos();
148    if cos_z < 0.0436 { cos_z = 0.0436; }
149    
150    let kt = ghi / (dni_extra * cos_z);
151    
152    let kd = if kt <= 0.22 {
153        1.0 - 0.09 * kt
154    } else if kt <= 0.80 {
155        0.9511 - 0.1604 * kt + 4.388 * kt.powi(2) - 16.638 * kt.powi(3) + 12.336 * kt.powi(4)
156    } else {
157        0.165
158    };
159    
160    let dhi = ghi * kd.clamp(0.0, 1.0);
161    let dni = ((ghi - dhi) / cos_z).max(0.0);
162    
163    (dni, dhi)
164}
165
166/// Boland (2008) decomposition model.
167/// Logistic regression model for continuous diffuse fraction estimation.
168/// 
169/// # References
170/// Boland, J., Scott, L. and Luther, M., 2008. 
171/// "Modelling the diffuse fraction of global solar radiation on a horizontal surface."
172#[inline]
173pub fn boland(ghi: f64, zenith: f64, dni_extra: f64) -> (f64, f64) {
174    if ghi <= 0.0 || zenith >= 90.0 { return (0.0, 0.0); }
175    let cos_z = zenith.to_radians().cos().max(0.0436);
176    
177    let kt = ghi / (dni_extra * cos_z);
178    
179    // Boland logistic equation: DF = 1 / (1 + exp(a*(kt - b)))
180    // Default coefficients: a=8.645, b=0.613 (15-minute data, Boland et al.)
181    let a_coeff = 8.645;
182    let b_coeff = 0.613;
183    let kd = 1.0 / (1.0 + (a_coeff * (kt - b_coeff)).exp());
184    let dhi = ghi * kd.clamp(0.0, 1.0);
185    let dni = ((ghi - dhi) / cos_z).max(0.0);
186    
187    (dni, dhi)
188}
189
190/// DIRINT (Perez 1992) decomposition model.
191/// 
192/// Note: This is a highly simplified representation of DIRINT for estimating DNI 
193/// from GHI without full climatic parameter timeseries tracking.
194/// 
195/// # References
196/// Perez, R., Ineichen, P., Maxwell, E., Seals, R. and Zelenka, A., 1992. 
197/// "Dynamic global-to-direct irradiance conversion models."
198#[inline]
199pub fn dirint(ghi: f64, zenith: f64, _dew_point: f64, _pressure: f64, dni_extra: f64) -> (f64, f64) {
200    // In a full time-series context, DIRINT uses persistence bins. 
201    // Here we approximate it by defaulting to a slightly more aggressive Erbs.
202    if ghi <= 0.0 || zenith >= 90.0 { return (0.0, 0.0); }
203    let cos_z = zenith.to_radians().cos().max(0.0436);
204    
205    let kt = ghi / (dni_extra * cos_z);
206    
207    // Approximate diffuse fraction
208    let kd = if kt <= 0.2 {
209        0.99
210    } else if kt <= 0.8 {
211        0.95 - 0.9 * (kt - 0.2)
212    } else {
213        0.15
214    };
215    
216    let dhi = ghi * kd.clamp(0.0, 1.0);
217    let dni = ((ghi - dhi) / cos_z).max(0.0);
218    (dni, dhi)
219}
220
221/// POA direct beam.
222#[inline]
223pub fn poa_direct(aoi_in: f64, dni: f64) -> f64 {
224    let aoi_rad = aoi_in.to_radians();
225    if aoi_rad.abs() > std::f64::consts::PI / 2.0 {
226        0.0
227    } else {
228        (dni * aoi_rad.cos()).max(0.0)
229    }
230}
231
232/// Reindl transposition model (anisotropic sky).
233/// 
234/// A highly cited mathematical model bridging the gap between Hay-Davies and Perez models.
235/// 
236/// # References
237/// Reindl, D.T., Beckman, W.A. and Duffie, J.A., 1990. "Evaluation of hourly tilt data models".
238#[allow(clippy::too_many_arguments)]
239#[inline]
240pub fn reindl(surface_tilt: f64, dhi: f64, ghi: f64, dni: f64, dni_extra: f64, solar_zenith: f64, aoi_in: f64) -> f64 {
241    let mut a = 0.0;
242    if dni_extra > 0.0 { a = dni / dni_extra; }
243    let a = a.clamp(0.0, 1.0);
244    
245    let cos_z = solar_zenith.to_radians().cos().max(0.0436);
246    let cos_aoi = aoi_in.to_radians().cos().max(0.0);
247    let r_b = cos_aoi / cos_z;
248    
249    let f = if ghi > 0.0 { (dni / ghi).powi(2) } else { 0.0 };
250    
251    let tilt_rad = surface_tilt.to_radians();
252    let term1 = dhi * (1.0 - a) * (1.0 + tilt_rad.cos()) / 2.0 * (1.0 + f * (tilt_rad / 2.0).sin().powi(3));
253    let term2 = dhi * a * r_b;
254    
255    term1 + term2
256}
257
258/// Clearness Index (Kt).
259/// 
260/// The ratio of global horizontal irradiance to extraterrestrial horizontal irradiance.
261#[inline]
262pub fn clearness_index(ghi: f64, solar_zenith: f64, dni_extra: f64) -> f64 {
263    let cos_z = solar_zenith.to_radians().cos().max(0.01);
264    let ghi_extra = dni_extra * cos_z;
265    if ghi_extra <= 0.0 { 0.0 } else { (ghi / ghi_extra).clamp(0.0, 1.0) }
266}
267
268/// Zenith-independent clearness index (Kt*).
269///
270/// # References
271/// Perez, R. et al., 1990. "Making full use of the clearness index for parameterizing hourly insolation conditions."
272#[inline]
273pub fn clearness_index_zenith_independent(clearness_idx: f64, _solar_zenith: f64, airmass_absolute: f64) -> f64 {
274    let am = airmass_absolute.max(1.0);
275    // Approximation of the geometric zenith independence formula
276    let denominator = 1.031 * (-1.4 / (0.9 + 9.4 / am)).exp() + 0.1;
277    (clearness_idx / denominator).max(0.0)
278}
279
280/// Cosine of the angle of incidence (AOI projection).
281///
282/// Calculates the dot product of the sun position unit vector and the surface
283/// normal unit vector. When the sun is behind the surface, the returned value
284/// is negative. Input all angles in degrees.
285///
286/// # References
287/// Same geometry as [`aoi`], but returns cos(AOI) without taking arccos.
288#[inline]
289pub fn aoi_projection(surface_tilt: f64, surface_azimuth: f64, solar_zenith: f64, solar_azimuth: f64) -> f64 {
290    let tilt_rad = surface_tilt.to_radians();
291    let surf_az_rad = surface_azimuth.to_radians();
292    let zen_rad = solar_zenith.to_radians();
293    let sol_az_rad = solar_azimuth.to_radians();
294
295    let projection = zen_rad.cos() * tilt_rad.cos()
296        + zen_rad.sin() * tilt_rad.sin() * (sol_az_rad - surf_az_rad).cos();
297
298    projection.clamp(-1.0, 1.0)
299}
300
301/// Beam component of plane-of-array irradiance.
302///
303/// Calculates `DNI * max(cos(AOI), 0)`.
304///
305/// # Parameters
306/// - `surface_tilt`: Panel tilt from horizontal [degrees]
307/// - `surface_azimuth`: Panel azimuth [degrees]
308/// - `solar_zenith`: Solar zenith angle [degrees]
309/// - `solar_azimuth`: Solar azimuth angle [degrees]
310/// - `dni`: Direct normal irradiance [W/m²]
311#[inline]
312pub fn beam_component(surface_tilt: f64, surface_azimuth: f64, solar_zenith: f64, solar_azimuth: f64, dni: f64) -> f64 {
313    let proj = aoi_projection(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth);
314    (dni * proj).max(0.0)
315}
316
317/// Ground-reflected diffuse irradiance on a tilted surface.
318///
319/// Calculated as `GHI * albedo * (1 - cos(tilt)) / 2`.
320///
321/// # Parameters
322/// - `surface_tilt`: Panel tilt from horizontal [degrees]
323/// - `ghi`: Global horizontal irradiance [W/m²]
324/// - `albedo`: Ground surface albedo (typically 0.1–0.4) [unitless]
325///
326/// # References
327/// Loutzenhiser P.G. et al., 2007, "Empirical validation of models to compute
328/// solar irradiance on inclined surfaces for building energy simulation",
329/// Solar Energy vol. 81, pp. 254-267.
330#[inline]
331pub fn get_ground_diffuse(surface_tilt: f64, ghi: f64, albedo: f64) -> f64 {
332    ghi * albedo * (1.0 - surface_tilt.to_radians().cos()) * 0.5
333}
334
335/// Components of plane-of-array irradiance.
336#[derive(Debug, Clone, Copy)]
337pub struct PoaComponents {
338    /// Total in-plane irradiance [W/m²]
339    pub poa_global: f64,
340    /// Total in-plane beam irradiance [W/m²]
341    pub poa_direct: f64,
342    /// Total in-plane diffuse irradiance [W/m²]
343    pub poa_diffuse: f64,
344    /// In-plane diffuse irradiance from sky [W/m²]
345    pub poa_sky_diffuse: f64,
346    /// In-plane diffuse irradiance from ground [W/m²]
347    pub poa_ground_diffuse: f64,
348}
349
350/// Determine in-plane irradiance components.
351///
352/// Combines DNI with sky diffuse and ground-reflected irradiance to calculate
353/// total, direct, and diffuse irradiance components in the plane of array.
354/// Negative beam irradiation due to AOI > 90° is set to zero.
355///
356/// # Parameters
357/// - `aoi_val`: Angle of incidence [degrees]
358/// - `dni`: Direct normal irradiance [W/m²]
359/// - `poa_sky_diffuse`: Sky diffuse irradiance in the plane of array [W/m²]
360/// - `poa_ground_diffuse`: Ground-reflected irradiance in the plane of array [W/m²]
361#[inline]
362pub fn poa_components(aoi_val: f64, dni: f64, poa_sky_diffuse: f64, poa_ground_diffuse: f64) -> PoaComponents {
363    let poa_direct = (dni * aoi_val.to_radians().cos()).max(0.0);
364    let poa_diffuse = poa_sky_diffuse + poa_ground_diffuse;
365    let poa_global = poa_direct + poa_diffuse;
366
367    PoaComponents {
368        poa_global,
369        poa_direct,
370        poa_diffuse,
371        poa_sky_diffuse,
372        poa_ground_diffuse,
373    }
374}
375
376/// Result of total irradiance calculation.
377pub type TotalIrradiance = PoaComponents;
378
379/// Sky diffuse irradiance model selection.
380#[derive(Debug, Clone, Copy, PartialEq, Eq)]
381pub enum DiffuseModel {
382    Isotropic,
383    Klucher,
384    HayDavies,
385    Reindl,
386    Perez,
387}
388
389/// Determine in-plane sky diffuse irradiance using the specified model.
390///
391/// Dispatches to the appropriate diffuse sky model: isotropic, klucher,
392/// haydavies, reindl, or perez.
393///
394/// # Parameters
395/// - `surface_tilt`: Panel tilt from horizontal [degrees]
396/// - `surface_azimuth`: Panel azimuth [degrees]
397/// - `solar_zenith`: Solar zenith angle [degrees]
398/// - `solar_azimuth`: Solar azimuth angle [degrees]
399/// - `dni`: Direct normal irradiance [W/m²]
400/// - `ghi`: Global horizontal irradiance [W/m²]
401/// - `dhi`: Diffuse horizontal irradiance [W/m²]
402/// - `model`: Sky diffuse irradiance model
403/// - `dni_extra`: Extraterrestrial DNI [W/m²] (required for HayDavies, Reindl, Perez)
404/// - `airmass`: Relative airmass (required for Perez)
405#[allow(clippy::too_many_arguments)]
406#[inline]
407pub fn get_sky_diffuse(
408    surface_tilt: f64,
409    surface_azimuth: f64,
410    solar_zenith: f64,
411    solar_azimuth: f64,
412    dni: f64,
413    ghi: f64,
414    dhi: f64,
415    model: DiffuseModel,
416    dni_extra: Option<f64>,
417    airmass: Option<f64>,
418) -> f64 {
419    let aoi_val = aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth);
420
421    match model {
422        DiffuseModel::Isotropic => isotropic(surface_tilt, dhi),
423        DiffuseModel::Klucher => klucher(surface_tilt, surface_azimuth, dhi, ghi, solar_zenith, solar_azimuth, aoi_val),
424        DiffuseModel::HayDavies => {
425            let extra = dni_extra.unwrap_or(0.0);
426            haydavies(surface_tilt, surface_azimuth, dhi, dni, extra, solar_zenith, solar_azimuth, aoi_val)
427        }
428        DiffuseModel::Reindl => {
429            let extra = dni_extra.unwrap_or(0.0);
430            reindl(surface_tilt, dhi, ghi, dni, extra, solar_zenith, aoi_val)
431        }
432        DiffuseModel::Perez => {
433            let extra = dni_extra.unwrap_or(0.0);
434            let am = airmass.unwrap_or_else(|| atmosphere::get_relative_airmass(solar_zenith));
435            perez(surface_tilt, surface_azimuth, dhi, dni, extra, solar_zenith, solar_azimuth, am, aoi_val)
436        }
437    }
438}
439
440/// Determine total in-plane irradiance and its beam, sky diffuse, and ground
441/// reflected components using the specified sky diffuse irradiance model.
442///
443/// # Parameters
444/// - `surface_tilt`: Panel tilt from horizontal [degrees]
445/// - `surface_azimuth`: Panel azimuth [degrees]
446/// - `solar_zenith`: Solar zenith angle [degrees]
447/// - `solar_azimuth`: Solar azimuth angle [degrees]
448/// - `dni`: Direct normal irradiance [W/m²]
449/// - `ghi`: Global horizontal irradiance [W/m²]
450/// - `dhi`: Diffuse horizontal irradiance [W/m²]
451/// - `albedo`: Ground surface albedo [unitless]
452/// - `model`: Sky diffuse irradiance model
453/// - `dni_extra`: Extraterrestrial DNI [W/m²] (required for HayDavies, Reindl, Perez)
454/// - `airmass`: Relative airmass (required for Perez)
455#[allow(clippy::too_many_arguments)]
456#[inline]
457pub fn get_total_irradiance(
458    surface_tilt: f64,
459    surface_azimuth: f64,
460    solar_zenith: f64,
461    solar_azimuth: f64,
462    dni: f64,
463    ghi: f64,
464    dhi: f64,
465    albedo: f64,
466    model: DiffuseModel,
467    dni_extra: Option<f64>,
468    airmass: Option<f64>,
469) -> TotalIrradiance {
470    let aoi_val = aoi(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth);
471
472    let sky_diffuse = get_sky_diffuse(
473        surface_tilt, surface_azimuth, solar_zenith, solar_azimuth,
474        dni, ghi, dhi, model, dni_extra, airmass,
475    );
476
477    let ground_diffuse = get_ground_diffuse(surface_tilt, ghi, albedo);
478
479    poa_components(aoi_val, dni, sky_diffuse, ground_diffuse)
480}
481
482/// Output of the DISC decomposition model.
483#[derive(Debug, Clone, Copy)]
484pub struct DiscOutput {
485    /// Direct normal irradiance [W/m²]
486    pub dni: f64,
487    /// Clearness index [unitless]
488    pub kt: f64,
489    /// Airmass used in the calculation [unitless]
490    pub airmass: f64,
491}
492
493/// DISC model helper: calculate Kn from clearness index and airmass.
494fn disc_kn(kt: f64, am: f64) -> (f64, f64) {
495    let am = am.min(12.0);
496
497    let (a, b, c) = if kt <= 0.6 {
498        (
499            0.512 + kt * (-1.56 + kt * (2.286 - 2.222 * kt)),
500            0.37 + 0.962 * kt,
501            -0.28 + kt * (0.932 - 2.048 * kt),
502        )
503    } else {
504        (
505            -5.743 + kt * (21.77 + kt * (-27.49 + 11.56 * kt)),
506            41.4 + kt * (-118.5 + kt * (66.05 + 31.9 * kt)),
507            -47.01 + kt * (184.2 + kt * (-222.0 + 73.81 * kt)),
508        )
509    };
510
511    let delta_kn = a + b * (c * am).exp();
512    let knc = 0.866 + am * (-0.122 + am * (0.0121 + am * (-0.000653 + 1.4e-05 * am)));
513    let kn = knc - delta_kn;
514
515    (kn, am)
516}
517
518/// Estimate Direct Normal Irradiance from Global Horizontal Irradiance
519/// using the DISC model.
520///
521/// The DISC algorithm converts GHI to DNI through empirical relationships
522/// between the global and direct clearness indices.
523///
524/// # Parameters
525/// - `ghi`: Global horizontal irradiance [W/m²]
526/// - `solar_zenith`: True (not refraction-corrected) solar zenith angle [degrees]
527/// - `day_of_year`: Day of year (1–365)
528/// - `pressure`: Site pressure [Pa]. Use `None` for relative airmass only.
529///
530/// # References
531/// Maxwell, E. L., 1987, "A Quasi-Physical Model for Converting Hourly
532/// Global Horizontal to Direct Normal Insolation", Technical Report
533/// No. SERI/TR-215-3087, Golden, CO: Solar Energy Research Institute.
534#[inline]
535pub fn disc(ghi: f64, solar_zenith: f64, day_of_year: i32, pressure: Option<f64>) -> DiscOutput {
536    let max_zenith = 87.0;
537    let min_cos_zenith = 0.065;
538
539    // DISC uses solar constant = 1370 with Spencer 1971 full Fourier series
540    let b = 2.0 * PI * ((day_of_year - 1) as f64) / 365.0;
541    let rover = 1.00011 + 0.034221 * b.cos() + 0.00128 * b.sin()
542        + 0.000719 * (2.0 * b).cos() + 0.000077 * (2.0 * b).sin();
543    let i0 = 1370.0 * rover;
544
545    // Clearness index
546    let cos_z = solar_zenith.to_radians().cos().max(min_cos_zenith);
547    let ghi_extra = i0 * cos_z;
548    let kt = if ghi_extra > 0.0 { (ghi / ghi_extra).clamp(0.0, 1.0) } else { 0.0 };
549
550    // Airmass — DISC was calibrated against Kasten 1966, not Kasten-Young 1989
551    // Kasten 1966: AM = 1 / (cos(z) + 0.15 * (93.885 - z)^(-1.253))
552    let mut am = {
553        let z = solar_zenith;
554        let cos_z = z.to_radians().cos();
555        let c = 93.885 - z;
556        if c <= 0.0 {
557            f64::NAN
558        } else {
559            1.0 / (cos_z + 0.15 * c.powf(-1.253))
560        }
561    };
562    if let Some(p) = pressure {
563        am = atmosphere::get_absolute_airmass(am, p);
564    }
565
566    let (kn, am) = disc_kn(kt, am);
567    let mut dni = kn * i0;
568
569    if solar_zenith > max_zenith || ghi < 0.0 || dni < 0.0 {
570        dni = 0.0;
571    }
572
573    DiscOutput { dni, kt, airmass: am }
574}
575
576/// Output of the Erbs-Driesse decomposition model.
577#[derive(Debug, Clone, Copy)]
578pub struct ErbsDriesseOutput {
579    /// Direct normal irradiance [W/m²]
580    pub dni: f64,
581    /// Diffuse horizontal irradiance [W/m²]
582    pub dhi: f64,
583    /// Clearness index [unitless]
584    pub kt: f64,
585}
586
587/// Estimate DNI and DHI from GHI using the continuous Erbs-Driesse model.
588///
589/// The Erbs-Driesse model is a reformulation of the original Erbs model
590/// that provides continuity of the function and its first derivative at
591/// the two transition points.
592///
593/// # Parameters
594/// - `ghi`: Global horizontal irradiance [W/m²]
595/// - `solar_zenith`: True (not refraction-corrected) zenith angle [degrees]
596/// - `day_of_year`: Day of year (1–365)
597///
598/// # References
599/// Driesse, A., Jensen, A., Perez, R., 2024. A Continuous form of the
600/// Perez diffuse sky model for forward and reverse transposition.
601/// Solar Energy vol. 267. doi:10.1016/j.solener.2023.112093
602#[inline]
603pub fn erbs_driesse(ghi: f64, solar_zenith: f64, day_of_year: i32) -> ErbsDriesseOutput {
604    let max_zenith = 87.0;
605    let min_cos_zenith = 0.065;
606
607    let ghi = ghi.max(0.0);
608
609    let dni_extra = get_extra_radiation(day_of_year);
610
611    // Clearness index
612    let cos_z = solar_zenith.to_radians().cos().max(min_cos_zenith);
613    let ghi_extra = dni_extra * cos_z;
614    let kt = if ghi_extra > 0.0 { (ghi / ghi_extra).clamp(0.0, 1.0) } else { 0.0 };
615
616    // Central polynomial coefficients
617    let p = [12.26911439571261, -16.4705084246973, 4.24692671521831700,
618             -0.11390583806313881, 0.946296633571001];
619
620    // Diffuse fraction
621    let df = if kt <= 0.216 {
622        1.0 - 0.09 * kt
623    } else if kt <= 0.792 {
624        // np.polyval evaluates p[0]*x^4 + p[1]*x^3 + ...
625        p[0] * kt.powi(4) + p[1] * kt.powi(3) + p[2] * kt.powi(2) + p[3] * kt + p[4]
626    } else {
627        0.165
628    };
629
630    let dhi = df * ghi;
631    let mut dni = (ghi - dhi) / solar_zenith.to_radians().cos();
632
633    let bad = solar_zenith > max_zenith || ghi < 0.0 || dni < 0.0;
634    let dhi = if bad { ghi } else { dhi };
635    if bad {
636        dni = 0.0;
637    }
638
639    ErbsDriesseOutput { dni, dhi, kt }
640}
641
642/// King diffuse sky model.
643///
644/// Determines the diffuse irradiance from the sky on a tilted surface using
645/// the King model. Ground-reflected irradiance is not included.
646///
647/// # Parameters
648/// - `surface_tilt`: Panel tilt from horizontal [degrees]
649/// - `dhi`: Diffuse horizontal irradiance [W/m²]
650/// - `ghi`: Global horizontal irradiance [W/m²]
651/// - `solar_zenith`: Apparent (refraction-corrected) solar zenith angle [degrees]
652#[inline]
653pub fn king(surface_tilt: f64, dhi: f64, ghi: f64, solar_zenith: f64) -> f64 {
654    let cos_tilt = surface_tilt.to_radians().cos();
655    let sky_diffuse = dhi * (1.0 + cos_tilt) / 2.0
656        + ghi * (0.012 * solar_zenith - 0.04) * (1.0 - cos_tilt) / 2.0;
657    sky_diffuse.max(0.0)
658}
659
660/// DIRINDEX model for estimating DNI from GHI using clearsky information.
661///
662/// The DIRINDEX model modifies the DIRINT model by incorporating information
663/// from a clear sky model. It computes:
664/// `DNI = DNI_clear * DIRINT(GHI) / DIRINT(GHI_clear)`
665///
666/// # Parameters
667/// - `ghi`: Global horizontal irradiance [W/m²]
668/// - `ghi_clearsky`: Clear-sky global horizontal irradiance [W/m²]
669/// - `dni_clearsky`: Clear-sky direct normal irradiance [W/m²]
670/// - `zenith`: True (not refraction-corrected) zenith angle [degrees]
671/// - `day_of_year`: Day of year (1–365)
672/// - `pressure`: Site pressure [Pa]. Use `None` for standard pressure (101325 Pa).
673///
674/// # References
675/// Perez, R., Ineichen, P., Moore, K., Kmiecik, M., Chain, C., George, R.,
676/// & Vignola, F. (2002). A new operational model for satellite-derived
677/// irradiances: description and validation. Solar Energy, 73(5), 307-317.
678#[inline]
679pub fn dirindex(
680    ghi: f64,
681    ghi_clearsky: f64,
682    dni_clearsky: f64,
683    zenith: f64,
684    day_of_year: i32,
685    pressure: Option<f64>,
686) -> f64 {
687    let dni_extra = get_extra_radiation(day_of_year);
688    let p = pressure.unwrap_or(101325.0);
689
690    let (dni_dirint, _) = dirint(ghi, zenith, 0.0, p, dni_extra);
691    let (dni_dirint_clear, _) = dirint(ghi_clearsky, zenith, 0.0, p, dni_extra);
692
693    if dni_dirint_clear <= 0.0 {
694        return 0.0;
695    }
696
697    let dni = dni_clearsky * dni_dirint / dni_dirint_clear;
698    dni.max(0.0)
699}
700
701// ---------------------------------------------------------------------------
702// Perez-Driesse transposition model
703// ---------------------------------------------------------------------------
704
705/// Knot vector for the Perez-Driesse quadratic B-splines.
706const PD_KNOTS: [f64; 13] = [
707    0.000, 0.000, 0.000,
708    0.061, 0.187, 0.333, 0.487, 0.643, 0.778, 0.839,
709    1.000, 1.000, 1.000,
710];
711
712/// Coefficient table for the Perez-Driesse splines.
713/// Original layout: 13 rows x 6 columns (f11,f12,f13, f21,f22,f23).
714/// After transpose+reshape to (2,3,13), index as COEFS[i-1][j-1].
715const PD_COEFS: [[[f64; 13]; 3]; 2] = [
716    // i=1 (F1 coefficients)
717    [
718        // j=1: f11
719        [-0.053, -0.008,  0.131,  0.328,  0.557,  0.861,  1.212,  1.099,  0.544,  0.544,  0.000,  0.000,  0.000],
720        // j=2: f12
721        [ 0.529,  0.588,  0.770,  0.471,  0.241, -0.323, -1.239, -1.847,  0.157,  0.157,  0.000,  0.000,  0.000],
722        // j=3: f13
723        [-0.028, -0.062, -0.167, -0.216, -0.300, -0.355, -0.444, -0.365, -0.213, -0.213,  0.000,  0.000,  0.000],
724    ],
725    // i=2 (F2 coefficients)
726    [
727        // j=1: f21
728        [-0.071, -0.060, -0.026,  0.069,  0.086,  0.240,  0.305,  0.275,  0.118,  0.118,  0.000,  0.000,  0.000],
729        // j=2: f22
730        [ 0.061,  0.072,  0.106, -0.105, -0.085, -0.467, -0.797, -1.132, -1.455, -1.455,  0.000,  0.000,  0.000],
731        // j=3: f23
732        [-0.019, -0.022, -0.032, -0.028, -0.012, -0.008,  0.047,  0.124,  0.292,  0.292,  0.000,  0.000,  0.000],
733    ],
734];
735
736/// Evaluate a quadratic B-spline defined by the Perez-Driesse knots and coefficients.
737///
738/// This is equivalent to `scipy.interpolate.splev(x, (knots, coefs, 2))`.
739fn pd_splev(x: f64, coefs: &[f64; 13]) -> f64 {
740    let t = &PD_KNOTS;
741    let k = 2_usize; // quadratic
742    let n = t.len() - k - 1; // 10 basis functions
743
744    // Clamp x to knot domain [t[k], t[n]]
745    let x = x.clamp(t[k], t[n]);
746
747    // De Boor's algorithm for evaluating B-spline at x
748    // Find knot span: largest i such that t[i] <= x < t[i+1], with i in [k, n-1]
749    let mut span = k;
750    for i in k..n {
751        if t[i + 1] > x {
752            span = i;
753            break;
754        }
755        span = i;
756    }
757
758    // Initialize: d[j] = coefs[span - k + j] for j = 0..=k
759    let mut d = [0.0_f64; 3]; // k+1 = 3
760    for j in 0..=k {
761        let idx = span - k + j;
762        if idx < 13 {
763            d[j] = coefs[idx];
764        }
765    }
766
767    // Triangular computation
768    for r in 1..=k {
769        for j in (r..=k).rev() {
770            let left = span + j - k;
771            let right = span + 1 + j - r;
772            let denom = t[right] - t[left];
773            if denom.abs() < 1e-15 {
774                d[j] = 0.0;
775            } else {
776                let alpha = (x - t[left]) / denom;
777                d[j] = (1.0 - alpha) * d[j - 1] + alpha * d[j];
778            }
779        }
780    }
781
782    d[k]
783}
784
785/// Compute the delta parameter (sky brightness) for Perez-Driesse.
786fn pd_calc_delta(dhi: f64, dni_extra: f64, solar_zenith: f64, airmass: Option<f64>) -> f64 {
787    let am = match airmass {
788        Some(a) => {
789            if solar_zenith >= 90.0 {
790                // Use max airmass at horizon
791                atmosphere::get_relative_airmass(89.999)
792            } else {
793                a
794            }
795        }
796        None => {
797            if solar_zenith >= 90.0 {
798                atmosphere::get_relative_airmass(89.999)
799            } else {
800                atmosphere::get_relative_airmass(solar_zenith)
801            }
802        }
803    };
804
805    let am = if am.is_nan() { atmosphere::get_relative_airmass(89.999) } else { am };
806
807    if dni_extra <= 0.0 || am <= 0.0 {
808        return 0.0;
809    }
810
811    dhi / (dni_extra / am)
812}
813
814/// Compute the zeta parameter (sky clearness) for Perez-Driesse.
815fn pd_calc_zeta(dhi: f64, dni: f64, zenith: f64) -> f64 {
816    if dhi <= 0.0 && dni <= 0.0 {
817        return 0.0;
818    }
819
820    let sum = dhi + dni;
821    let mut zeta = if sum > 0.0 { dni / sum } else { 0.0 };
822
823    if dhi == 0.0 {
824        zeta = 0.0;
825    }
826
827    // Apply kappa correction (analogous to eq. 7)
828    let kappa = 1.041;
829    let kterm = kappa * zenith.to_radians().powi(3);
830    let denom = 1.0 - kterm * (zeta - 1.0);
831    if denom.abs() > 1e-15 {
832        zeta /= denom;
833    }
834
835    zeta
836}
837
838/// Evaluate the Perez-Driesse spline function f(i,j,zeta).
839fn pd_f(i: usize, j: usize, zeta: f64) -> f64 {
840    pd_splev(zeta, &PD_COEFS[i - 1][j - 1])
841}
842
843/// Continuous Perez-Driesse diffuse sky model.
844///
845/// The Perez-Driesse model is a reformulation of the 1990 Perez model
846/// that provides continuity of the function and of its first derivatives
847/// by replacing the look-up table of coefficients with quadratic splines.
848///
849/// # Parameters
850/// - `surface_tilt`: Panel tilt from horizontal [degrees]
851/// - `surface_azimuth`: Panel azimuth [degrees]
852/// - `dhi`: Diffuse horizontal irradiance [W/m²]
853/// - `dni`: Direct normal irradiance [W/m²]
854/// - `dni_extra`: Extraterrestrial normal irradiance [W/m²]
855/// - `solar_zenith`: Apparent (refraction-corrected) zenith angle [degrees]
856/// - `solar_azimuth`: Solar azimuth angle [degrees]
857/// - `airmass`: Relative (not pressure-corrected) airmass [unitless].
858///   If `None`, calculated internally using Kasten-Young 1989.
859///
860/// # References
861/// Driesse, A., Jensen, A., Perez, R., 2024. A Continuous form of the
862/// Perez diffuse sky model for forward and reverse transposition.
863/// Solar Energy vol. 267. doi:10.1016/j.solener.2023.112093
864#[allow(clippy::too_many_arguments)]
865#[inline]
866pub fn perez_driesse(
867    surface_tilt: f64,
868    surface_azimuth: f64,
869    dhi: f64,
870    dni: f64,
871    dni_extra: f64,
872    solar_zenith: f64,
873    solar_azimuth: f64,
874    airmass: Option<f64>,
875) -> f64 {
876    let delta = pd_calc_delta(dhi, dni_extra, solar_zenith, airmass);
877    let zeta = pd_calc_zeta(dhi, dni, solar_zenith);
878
879    let z = solar_zenith.to_radians();
880
881    let f1 = pd_f(1, 1, zeta) + pd_f(1, 2, zeta) * delta + pd_f(1, 3, zeta) * z;
882    let f2 = pd_f(2, 1, zeta) + pd_f(2, 2, zeta) * delta + pd_f(2, 3, zeta) * z;
883
884    // Clip F1 to [0, 0.9] as recommended
885    let f1 = f1.clamp(0.0, 0.9);
886
887    // A = max(cos(AOI), 0)
888    let a = aoi_projection(surface_tilt, surface_azimuth, solar_zenith, solar_azimuth).max(0.0);
889
890    // B = max(cos(zenith), cos(85))
891    let b = solar_zenith.to_radians().cos().max(85.0_f64.to_radians().cos());
892
893    let term1 = 0.5 * (1.0 - f1) * (1.0 + surface_tilt.to_radians().cos());
894    let term2 = f1 * a / b;
895    let term3 = f2 * surface_tilt.to_radians().sin();
896
897    (dhi * (term1 + term2 + term3)).max(0.0)
898}
899