solar_positioning/lib.rs
1//! # Solar Positioning Library
2//!
3//! High-accuracy solar positioning algorithms for calculating sun position and sunrise/sunset times.
4
5#![cfg_attr(not(feature = "std"), no_std)]
6//!
7//! This library provides implementations of two complementary solar positioning algorithms:
8//! - **SPA** (Solar Position Algorithm): NREL's authoritative algorithm (±0.0003°, years -2000 to 6000)
9//! - **Grena3**: Simplified algorithm (±0.01°, years 2010-2110, ~10x faster)
10//!
11//! In addition, it provides an estimator for Delta T (ΔT) values based on the work of F. Espenak & J. Meeus.
12//!
13//! ## Features
14//!
15//! - Multiple configurations: `std` or `no_std`, with or without `chrono`, math via native or `libm`
16//! - Maximum accuracy: Authentic NREL SPA implementation, validated against reference data
17//! - Performance optimized: Split functions for bulk calculations (SPA only)
18//! - Thread-safe: Stateless, immutable data structures
19//!
20//! ## Feature Flags
21//!
22//! - `std` (default): Use standard library for native math functions (usually faster than `libm`)
23//! - `chrono` (default): Enable `DateTime<Tz>` based convenience API
24//! - `libm`: Use pure Rust math for `no_std` environments
25//!
26//! **Configuration examples:**
27//! ```toml
28//! # Default: std + chrono (most convenient)
29//! solar-positioning = "0.3"
30//!
31//! # Minimal std (no chrono, smallest dependency tree)
32//! solar-positioning = { version = "0.3", default-features = false, features = ["std"] }
33//!
34//! # no_std + chrono (embedded with DateTime support)
35//! solar-positioning = { version = "0.3", default-features = false, features = ["libm", "chrono"] }
36//!
37//! # Minimal no_std (pure numeric API)
38//! solar-positioning = { version = "0.3", default-features = false, features = ["libm"] }
39//! ```
40//!
41//! ## References
42//!
43//! - Reda, I.; Andreas, A. (2003). Solar position algorithm for solar radiation applications.
44//! Solar Energy, 76(5), 577-589. DOI: <http://dx.doi.org/10.1016/j.solener.2003.12.003>
45//! - Grena, R. (2012). Five new algorithms for the computation of sun position from 2010 to 2110.
46//! Solar Energy, 86(5), 1323-1337. DOI: <http://dx.doi.org/10.1016/j.solener.2012.01.024>
47//!
48//! ## Quick Start
49//!
50//! ### Solar Position (with chrono)
51//! ```rust
52//! # #[cfg(feature = "chrono")] {
53//! use solar_positioning::{spa, RefractionCorrection, time::DeltaT};
54//! use chrono::{DateTime, FixedOffset};
55//!
56//! // Calculate sun position for Vienna at noon
57//! let datetime = "2026-06-21T12:00:00+02:00".parse::<DateTime<FixedOffset>>().unwrap();
58//! let position = spa::solar_position(
59//! datetime,
60//! 48.21, // Vienna latitude
61//! 16.37, // Vienna longitude
62//! 190.0, // elevation (meters)
63//! DeltaT::estimate_from_date_like(datetime).unwrap(), // delta T
64//! Some(RefractionCorrection::standard())
65//! ).unwrap();
66//!
67//! println!("Azimuth: {:.3}°", position.azimuth());
68//! println!("Elevation: {:.3}°", position.elevation_angle());
69//! # }
70//! ```
71//!
72//! ### Solar Position (numeric API, no chrono)
73//! ```rust
74//! use solar_positioning::{spa, time::JulianDate, RefractionCorrection};
75//!
76//! // Create Julian date from UTC components (2026-06-21 12:00:00 UTC + 69s ΔT)
77//! let jd = JulianDate::from_utc(2026, 6, 21, 12, 0, 0.0, 69.0).unwrap();
78//!
79//! // Calculate sun position (works in both std and no_std)
80//! let position = spa::solar_position_from_julian(
81//! jd,
82//! 48.21, // Vienna latitude
83//! 16.37, // Vienna longitude
84//! 190.0, // elevation (meters)
85//! Some(RefractionCorrection::standard())
86//! ).unwrap();
87//!
88//! println!("Azimuth: {:.3}°", position.azimuth());
89//! println!("Elevation: {:.3}°", position.elevation_angle());
90//! ```
91//!
92//! ### Sunrise and Sunset (requires chrono)
93//! ```rust
94//! # #[cfg(feature = "chrono")] {
95//! use solar_positioning::{spa, Horizon, time::DeltaT};
96//! use chrono::{DateTime, FixedOffset};
97//!
98//! // Calculate sunrise/sunset for San Francisco
99//! let date = "2026-06-21T00:00:00-07:00".parse::<DateTime<FixedOffset>>().unwrap();
100//! let result = spa::sunrise_sunset_for_horizon(
101//! date,
102//! 37.7749, // San Francisco latitude
103//! -122.4194, // San Francisco longitude
104//! DeltaT::estimate_from_date_like(date).unwrap(),
105//! Horizon::SunriseSunset
106//! ).unwrap();
107//!
108//! match result {
109//! solar_positioning::SunriseResult::RegularDay { sunrise, transit, sunset } => {
110//! println!("Sunrise: {}", sunrise);
111//! println!("Solar noon: {}", transit);
112//! println!("Sunset: {}", sunset);
113//! }
114//! _ => println!("No sunrise/sunset (polar day/night)"),
115//! }
116//! # }
117//! ```
118//!
119//! ## Algorithms
120//!
121//! ### SPA (Solar Position Algorithm)
122//!
123//! Based on the NREL algorithm by Reda & Andreas (2003). Provides the highest accuracy
124//! with uncertainties of ±0.0003 degrees, suitable for applications requiring precise
125//! solar positioning over long time periods.
126//!
127//! ### Grena3
128//!
129//! A simplified algorithm optimized for years 2010-2110. Approximately 10 times faster
130//! than SPA while maintaining good accuracy (maximum error 0.01°).
131//!
132//! ## Coordinate System
133//!
134//! - **Azimuth**: 0° = North, measured clockwise (0° to 360°)
135//! - **Zenith angle**: 0° = directly overhead (zenith), 90° = horizon (0° to 180°)
136//! - **Elevation angle**: 0° = horizon, 90° = directly overhead (-90° to +90°)
137
138#![deny(missing_docs)]
139#![deny(unsafe_code)]
140#![warn(clippy::pedantic, clippy::nursery, clippy::cargo, clippy::all)]
141#![allow(
142 clippy::module_name_repetitions,
143 clippy::cast_possible_truncation,
144 clippy::cast_precision_loss,
145 clippy::cargo_common_metadata,
146 clippy::multiple_crate_versions, // Acceptable for dev-dependencies
147 clippy::float_cmp, // Exact comparisons of mathematical constants in tests
148 clippy::incompatible_msrv, // Functions work fine in 1.70, const context only needs 1.85+
149)]
150
151// Public API exports
152pub use crate::error::{Error, Result};
153#[cfg(feature = "chrono")]
154pub use crate::spa::spa_time_dependent_parts;
155pub use crate::spa::{spa_with_time_dependent_parts, SpaTimeDependent};
156pub use crate::types::{Horizon, RefractionCorrection, SolarPosition, SunriseResult};
157
158// Algorithm modules
159pub mod grena3;
160pub mod spa;
161
162// Core modules
163pub mod error;
164pub mod types;
165
166// Internal modules
167mod math;
168
169// Public modules
170pub mod time;
171
172#[cfg(all(test, feature = "chrono"))]
173mod tests {
174 use super::*;
175 use chrono::{DateTime, FixedOffset, TimeZone, Utc};
176
177 #[test]
178 fn test_basic_spa_calculation() {
179 // Test with different timezone types
180 let datetime_fixed = "2023-06-21T12:00:00-07:00"
181 .parse::<DateTime<FixedOffset>>()
182 .unwrap();
183 let datetime_utc = Utc.with_ymd_and_hms(2023, 6, 21, 19, 0, 0).unwrap();
184
185 let position1 = spa::solar_position(
186 datetime_fixed,
187 37.7749,
188 -122.4194,
189 0.0,
190 69.0,
191 Some(RefractionCorrection::standard()),
192 )
193 .unwrap();
194 let position2 = spa::solar_position(
195 datetime_utc,
196 37.7749,
197 -122.4194,
198 0.0,
199 69.0,
200 Some(RefractionCorrection::standard()),
201 )
202 .unwrap();
203
204 // Both should produce identical results
205 assert!((position1.azimuth() - position2.azimuth()).abs() < 1e-10);
206 assert!((position1.zenith_angle() - position2.zenith_angle()).abs() < 1e-10);
207
208 assert!(position1.azimuth() >= 0.0);
209 assert!(position1.azimuth() <= 360.0);
210 assert!(position1.zenith_angle() >= 0.0);
211 assert!(position1.zenith_angle() <= 180.0);
212 }
213
214 #[test]
215 fn test_basic_grena3_calculation() {
216 use chrono::{DateTime, FixedOffset, TimeZone, Utc};
217
218 let datetime_fixed = "2023-06-21T12:00:00-07:00"
219 .parse::<DateTime<FixedOffset>>()
220 .unwrap();
221 let datetime_utc = Utc.with_ymd_and_hms(2023, 6, 21, 19, 0, 0).unwrap();
222
223 let position1 = grena3::solar_position(
224 datetime_fixed,
225 37.7749,
226 -122.4194,
227 69.0,
228 Some(RefractionCorrection::new(1013.25, 15.0).unwrap()),
229 )
230 .unwrap();
231
232 let position2 = grena3::solar_position(
233 datetime_utc,
234 37.7749,
235 -122.4194,
236 69.0,
237 Some(RefractionCorrection::new(1013.25, 15.0).unwrap()),
238 )
239 .unwrap();
240
241 // Both should produce identical results
242 assert!((position1.azimuth() - position2.azimuth()).abs() < 1e-6);
243 assert!((position1.zenith_angle() - position2.zenith_angle()).abs() < 1e-6);
244
245 assert!(position1.azimuth() >= 0.0);
246 assert!(position1.azimuth() <= 360.0);
247 assert!(position1.zenith_angle() >= 0.0);
248 assert!(position1.zenith_angle() <= 180.0);
249 }
250}