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