diff --git a/src/Titano.Core/Math/SolarPosition.cs b/src/Titano.Core/Math/SolarPosition.cs new file mode 100644 index 00000000..bfa7eb16 --- /dev/null +++ b/src/Titano.Core/Math/SolarPosition.cs @@ -0,0 +1,219 @@ +namespace Titano.Core.Mathematics; + +/// Light condition by solar elevation (geometric centre of the disc). +public enum DayPhase +{ + /// Sun below −18°. + Night, + + /// −18° to −12°. + AstronomicalTwilight, + + /// −12° to −6°. + NauticalTwilight, + + /// −6° to sunrise/sunset (−0.833°). + CivilTwilight, + + /// Sun up but below 6°. + GoldenHour, + + /// Sun at or above 6°. + Day, +} + +/// Sun position for an instant and place. +/// Apparent elevation in degrees, corrected for standard atmospheric refraction. +/// Degrees clockwise from true north. +/// Elevation without refraction, in degrees (used for twilight limits). +/// Solar declination in degrees. +/// Apparent minus mean solar time, in minutes. +public readonly record struct SolarCoordinates(double Elevation, double Azimuth, double GeometricElevation, double Declination, double EquationOfTimeMinutes) +{ + public DayPhase Phase => SolarPosition.Classify(GeometricElevation); +} + +/// Sun events of one local solar day, all in UTC; null when the event does not occur (polar day/night). +public sealed record SolarDay( + DateOnly Date, + DateTime SolarNoon, + DateTime? Sunrise, + DateTime? Sunset, + DateTime? CivilDawn, + DateTime? CivilDusk, + DateTime? NauticalDawn, + DateTime? NauticalDusk, + DateTime? AstronomicalDawn, + DateTime? AstronomicalDusk); + +/// +/// Solar position and rise/set times with the NOAA Solar Calculator equations (after Meeus, "Astronomical +/// Algorithms"). Event times are refined iteratively at the event instant; accuracy is about one minute for +/// latitudes within ±72°. Longitudes are east-positive, latitudes north-positive, times UTC. +/// +public static class SolarPosition +{ + /// Geometric elevation of the disc centre at apparent sunrise/sunset (34′ refraction + 16′ semi-diameter). + public const double SunriseElevation = -0.833; + + public const double CivilTwilightElevation = -6; + public const double NauticalTwilightElevation = -12; + public const double AstronomicalTwilightElevation = -18; + public const double GoldenHourElevation = 6; + + private const double Deg = Math.PI / 180; + private static readonly DateTime J2000 = new(2000, 1, 1, 12, 0, 0, DateTimeKind.Utc); + + /// Sun position at (a value of unspecified kind is taken as UTC). + public static SolarCoordinates Compute(DateTime utc, double latitude, double longitude) + { + ValidateLocation(latitude, longitude); + var sun = Ephemeris(utc); + var minutes = utc.TimeOfDay.TotalMinutes; + var trueSolarTime = Mod(minutes + sun.EquationOfTime + 4 * longitude, 1440); + var hourAngle = trueSolarTime / 4 - 180; + + var phi = latitude * Deg; + var delta = sun.Declination * Deg; + var cosZenith = Math.Clamp(Math.Sin(phi) * Math.Sin(delta) + Math.Cos(phi) * Math.Cos(delta) * Math.Cos(hourAngle * Deg), -1, 1); + var zenith = Math.Acos(cosZenith); + var geometric = 90 - zenith / Deg; + + double azimuth; + var denominator = Math.Cos(phi) * Math.Sin(zenith); + if (Math.Abs(denominator) < 1e-12) + { + azimuth = latitude > 0 ? 180 : 0; + } + else + { + var a = Math.Acos(Math.Clamp((Math.Sin(phi) * cosZenith - Math.Sin(delta)) / denominator, -1, 1)) / Deg; + azimuth = hourAngle > 0 ? Mod(a + 180, 360) : Mod(540 - a, 360); + } + return new SolarCoordinates(geometric + Refraction(geometric), azimuth, geometric, sun.Declination, sun.EquationOfTime); + } + + /// Day phase from the geometric elevation in degrees. + public static DayPhase Classify(double geometricElevation) => geometricElevation switch + { + < AstronomicalTwilightElevation => DayPhase.Night, + < NauticalTwilightElevation => DayPhase.AstronomicalTwilight, + < CivilTwilightElevation => DayPhase.NauticalTwilight, + < SunriseElevation => DayPhase.CivilTwilight, + < GoldenHourElevation => DayPhase.GoldenHour, + _ => DayPhase.Day, + }; + + public static DayPhase Phase(DateTime utc, double latitude, double longitude) => Compute(utc, latitude, longitude).Phase; + + /// All rise/set and twilight events of the local solar day (the day whose solar + /// noon falls on that calendar date at the given longitude). + public static SolarDay Events(DateOnly date, double latitude, double longitude) + { + ValidateLocation(latitude, longitude); + return new SolarDay( + date, + SolarNoon(date, longitude), + EventTime(date, latitude, longitude, SunriseElevation, rising: true), + EventTime(date, latitude, longitude, SunriseElevation, rising: false), + EventTime(date, latitude, longitude, CivilTwilightElevation, rising: true), + EventTime(date, latitude, longitude, CivilTwilightElevation, rising: false), + EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: true), + EventTime(date, latitude, longitude, NauticalTwilightElevation, rising: false), + EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: true), + EventTime(date, latitude, longitude, AstronomicalTwilightElevation, rising: false)); + } + + /// UTC solar noon (upper transit) of the local solar day. + public static DateTime SolarNoon(DateOnly date, double longitude) + { + var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var minutes = 720 - 4 * longitude; + for (var i = 0; i < 3; i++) + minutes = 720 - 4 * longitude - Ephemeris(midnight.AddMinutes(minutes)).EquationOfTime; + return midnight.AddMinutes(minutes); + } + + /// + /// UTC time at which the sun's geometric centre crosses degrees on the given + /// local solar day, rising (morning) or setting (evening); null when it stays above or below all day. + /// + public static DateTime? EventTime(DateOnly date, double latitude, double longitude, double elevation, bool rising) + { + ValidateLocation(latitude, longitude); + var midnight = date.ToDateTime(TimeOnly.MinValue, DateTimeKind.Utc); + var minutes = 720 - 4 * longitude; + for (var i = 0; i < 4; i++) + { + var sun = Ephemeris(midnight.AddMinutes(minutes)); + var hourAngle = HourAngle(latitude, sun.Declination, elevation); + if (double.IsNaN(hourAngle)) return null; + var noon = 720 - 4 * longitude - sun.EquationOfTime; + minutes = noon + (rising ? -4 : 4) * hourAngle; + } + return midnight.AddMinutes(minutes); + } + + private static double HourAngle(double latitude, double declination, double elevation) + { + var phi = latitude * Deg; + var delta = declination * Deg; + var cosH = (Math.Cos((90 - elevation) * Deg) - Math.Sin(phi) * Math.Sin(delta)) / (Math.Cos(phi) * Math.Cos(delta)); + return cosH is < -1 or > 1 || double.IsNaN(cosH) ? double.NaN : Math.Acos(cosH) / Deg; + } + + /// NOAA approximation of standard atmospheric refraction, in degrees, for a geometric elevation. + private static double Refraction(double elevation) + { + if (elevation > 85) return 0; + var t = Math.Tan(elevation * Deg); + var arcSeconds = elevation switch + { + > 5 => 58.1 / t - 0.07 / (t * t * t) + 0.000086 / Math.Pow(t, 5), + > -0.575 => 1735 + elevation * (-518.2 + elevation * (103.4 + elevation * (-12.79 + elevation * 0.711))), + _ => -20.772 / t, + }; + return arcSeconds / 3600; + } + + private readonly record struct Sun(double Declination, double EquationOfTime); + + private static Sun Ephemeris(DateTime utc) + { + var julianDay = 2451545.0 + (DateTime.SpecifyKind(utc, DateTimeKind.Utc) - J2000).TotalDays; + var t = (julianDay - 2451545.0) / 36525.0; + var meanLongitude = Mod(280.46646 + t * (36000.76983 + t * 0.0003032), 360); + var meanAnomaly = 357.52911 + t * (35999.05029 - 0.0001537 * t); + var eccentricity = 0.016708634 - t * (0.000042037 + 0.0000001267 * t); + var m = meanAnomaly * Deg; + var center = Math.Sin(m) * (1.914602 - t * (0.004817 + 0.000014 * t)) + + Math.Sin(2 * m) * (0.019993 - 0.000101 * t) + + Math.Sin(3 * m) * 0.000289; + var trueLongitude = meanLongitude + center; + var omega = (125.04 - 1934.136 * t) * Deg; + var apparentLongitude = trueLongitude - 0.00569 - 0.00478 * Math.Sin(omega); + var meanObliquity = 23 + (26 + (21.448 - t * (46.815 + t * (0.00059 - t * 0.001813))) / 60) / 60; + var obliquity = (meanObliquity + 0.00256 * Math.Cos(omega)) * Deg; + var declination = Math.Asin(Math.Sin(obliquity) * Math.Sin(apparentLongitude * Deg)) / Deg; + + var y = Math.Tan(obliquity / 2); + y *= y; + var l0 = meanLongitude * Deg; + var e = eccentricity; + var equationOfTime = 4 / Deg * (y * Math.Sin(2 * l0) - 2 * e * Math.Sin(m) + 4 * e * y * Math.Sin(m) * Math.Cos(2 * l0) + - 0.5 * y * y * Math.Sin(4 * l0) - 1.25 * e * e * Math.Sin(2 * m)); + return new Sun(declination, equationOfTime); + } + + private static double Mod(double value, double modulus) + { + var r = value % modulus; + return r < 0 ? r + modulus : r; + } + + private static void ValidateLocation(double latitude, double longitude) + { + if (!(latitude >= -90 && latitude <= 90)) throw new ArgumentOutOfRangeException(nameof(latitude)); + if (!(longitude >= -180 && longitude <= 180)) throw new ArgumentOutOfRangeException(nameof(longitude)); + } +} diff --git a/tests/Titano.Core.Tests/Math/SolarPositionTests.cs b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs new file mode 100644 index 00000000..a81f514b --- /dev/null +++ b/tests/Titano.Core.Tests/Math/SolarPositionTests.cs @@ -0,0 +1,104 @@ +using System.Globalization; +using Titano.Core.Mathematics; +using Titano.Testing; + +namespace Titano.Core.Tests.Mathematics; + +/// +/// Reference values are NOAA Solar Calculator results (spreadsheet equations as implemented by the +/// astral package, cross-checked against PyEphem/VSOP87 to within 35 s), UTC, for the local solar day. +/// +public sealed class SolarPositionTests +{ + private const double OneMinute = 60; + + [Theory] + [Case("Greenwich summer", 51.4769, -0.0005, "2024-06-21", "03:43:13", "20:20:36", "02:54:34", "21:09:14", "01:40:14", "22:23:33", null, null)] + [Case("Greenwich winter", 51.4769, -0.0005, "2024-12-21", "08:03:42", "15:52:56", "07:22:37", "16:34:01", "06:39:40", "17:16:58", "05:58:57", "17:57:41")] + [Case("New York equinox", 40.7128, -74.0060, "2024-03-20", "10:58:42", "23:08:28", "10:30:54", "23:36:20", "09:59:06", "+00:08:13", "09:26:36", "+00:40:50")] + [Case("Sydney winter", -33.8688, 151.2093, "2024-06-21", "-21:00:18", "06:53:41", "-20:32:02", "07:21:57", "-20:00:56", "07:53:03", "-19:30:30", "08:23:28")] + [Case("Quito equinox", -0.1807, -78.4678, "2024-09-22", "11:03:17", "23:09:26", "10:42:14", "23:30:29", "10:18:21", "23:54:22", "09:54:23", "+00:18:19")] + [Case("Tromso March", 69.6492, 18.9553, "2024-03-01", "06:08:32", "15:46:01", "05:06:36", "16:48:12", "03:57:47", "17:57:27", "02:44:21", "19:11:43")] + // The sun grazes −6° here, so tiny ephemeris differences move the crossing by minutes: astral's single-pass + // NOAA value is 77 s early, while the iterated NOAA solution and PyEphem agree on 08:31:31 / 12:53:21. + [Case("Tromso polar night", 69.6492, 18.9553, "2024-12-21", null, null, "08:31:31", "12:53:21", "06:46:35", "14:38:21", "05:28:22", "15:56:34")] + [Case("Tromso midnight sun", 69.6492, 18.9553, "2024-06-21", null, null, null, null, null, null, null, null)] + [Case("Golden NREL SPA site", 39.742476, -105.1786, "2003-10-17", "13:12:57", "+00:18:36", "12:45:10", "+00:46:21", "12:13:59", "+01:17:30", "11:42:47", "+01:48:39")] + public void EventsMatchNoaaWithinOneMinute(string place, double latitude, double longitude, string date, + string? sunrise, string? sunset, string? civilDawn, string? civilDusk, string? nauticalDawn, string? nauticalDusk, string? astroDawn, string? astroDusk) + { + var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture); + var events = SolarPosition.Events(day, latitude, longitude); + Check(place + " sunrise", day, sunrise, events.Sunrise); + Check(place + " sunset", day, sunset, events.Sunset); + Check(place + " civil dawn", day, civilDawn, events.CivilDawn); + Check(place + " civil dusk", day, civilDusk, events.CivilDusk); + Check(place + " nautical dawn", day, nauticalDawn, events.NauticalDawn); + Check(place + " nautical dusk", day, nauticalDusk, events.NauticalDusk); + Check(place + " astronomical dawn", day, astroDawn, events.AstronomicalDawn); + Check(place + " astronomical dusk", day, astroDusk, events.AstronomicalDusk); + } + + [Theory] + [Case(51.4769, -0.0005, "2024-06-21", "12:01:49")] + [Case(-33.8688, 151.2093, "2024-06-21", "01:56:58")] + [Case(39.742476, -105.1786, "2003-10-17", "18:46:14")] + public void SolarNoonMatchesNoaa(double latitude, double longitude, string date, string noon) + { + _ = latitude; + var day = DateOnly.ParseExact(date, "yyyy-MM-dd", CultureInfo.InvariantCulture); + Check("noon", day, noon, SolarPosition.SolarNoon(day, longitude)); + } + + [Theory] + [Case(39.742476, -105.1786, "2003-10-17T19:30:30", 39.8914, 39.8721, 194.3426)] + [Case(51.4769, -0.0005, "2024-06-21T12:00:00", 61.9665, 61.9579, 179.0598)] + [Case(-33.8688, 151.2093, "2024-01-15T06:30:00", 30.7712, 30.7442, 263.8208)] + [Case(35.6762, 139.6503, "2024-09-01T21:00:00", 8.4899, 8.3861, 86.3181)] + [Case(64.1466, -21.9426, "2024-12-01T15:00:00", 1.9248, 1.6140, 203.7679)] + public void PositionMatchesNoaa(double latitude, double longitude, string utc, double elevation, double geometric, double azimuth) + { + var time = DateTime.SpecifyKind(DateTime.ParseExact(utc, "yyyy-MM-ddTHH:mm:ss", CultureInfo.InvariantCulture), DateTimeKind.Utc); + var sun = SolarPosition.Compute(time, latitude, longitude); + Assert.Approximately(geometric, sun.GeometricElevation, 0.01); + Assert.Approximately(elevation, sun.Elevation, 0.01); + Assert.Approximately(azimuth, sun.Azimuth, 0.01); + } + + [Theory] + [Case(10.0, DayPhase.Day)] + [Case(3.0, DayPhase.GoldenHour)] + [Case(-0.5, DayPhase.GoldenHour)] + [Case(-3.0, DayPhase.CivilTwilight)] + [Case(-8.0, DayPhase.NauticalTwilight)] + [Case(-15.0, DayPhase.AstronomicalTwilight)] + [Case(-30.0, DayPhase.Night)] + public void ClassifiesElevation(double elevation, DayPhase expected) => Assert.Equal(expected, SolarPosition.Classify(elevation)); + + [Test] + public void PhaseFollowsTheEvents() + { + var day = new DateOnly(2024, 12, 21); + var events = SolarPosition.Events(day, 51.4769, -0.0005); + Assert.Equal(DayPhase.Day, SolarPosition.Phase(events.SolarNoon, 51.4769, -0.0005)); + Assert.Equal(DayPhase.GoldenHour, SolarPosition.Phase(events.Sunset!.Value.AddMinutes(-5), 51.4769, -0.0005)); + Assert.Equal(DayPhase.CivilTwilight, SolarPosition.Phase(events.Sunset!.Value.AddMinutes(5), 51.4769, -0.0005)); + Assert.Equal(DayPhase.Night, SolarPosition.Phase(events.AstronomicalDusk!.Value.AddMinutes(5), 51.4769, -0.0005)); + Assert.Throws(() => SolarPosition.Compute(DateTime.UtcNow, 91, 0)); + } + + /// Expected "HH:mm:ss" on ; a leading '-' or '+' means the previous or next UTC day. + private static void Check(string label, DateOnly day, string? expected, DateTime? actual) + { + if (expected is null) + { + Assert.Null(actual); + return; + } + var offsetDays = expected[0] switch { '-' => -1, '+' => 1, _ => 0 }; + var clock = TimeOnly.ParseExact(expected.TrimStart('+', '-'), "HH:mm:ss", CultureInfo.InvariantCulture); + var reference = day.AddDays(offsetDays).ToDateTime(clock, DateTimeKind.Utc); + var value = Assert.NotNull(actual, label); + Assert.Approximately(0, (value - reference).TotalSeconds, OneMinute, label); + } +}