001/*
002 * Zmanim Java API
003 * Copyright © 2004-2026 Eliyahu Hershfeld
004 *
005 * This library is free software; you can redistribute it and/or modify it under the terms of the GNU Lesser General
006 * Public License as published by the Free Software Foundation; version 2.1 of the License.
007 *
008 * This library is distributed in the hope that it will be useful,but WITHOUT ANY WARRANTY; without even the implied
009 * warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Lesser General Public License for more
010 * details.
011 * You should have received a copy of the GNU Lesser General Public License along with this library; if not, write to
012 * the Free Software Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA,
013 * or connect to: https://www.gnu.org/licenses/old-licenses/lgpl-2.1.html
014 */
015package com.kosherjava.zmanim.util;
016
017import java.time.ZoneOffset;
018import java.time.Instant;
019import java.time.LocalDate;
020import java.time.ZonedDateTime;
021
022/**
023 * Implementation of sunrise and sunset methods to calculate astronomical times based on the <a
024 * href="https://noaa.gov">NOAA</a> algorithm. This calculator uses the Java algorithm based on the implementation by <a
025 * href="https://noaa.gov">NOAA - National Oceanic and Atmospheric Administration</a>'s <a href =
026 * "https://www.srrb.noaa.gov/highlights/sunrise/sunrise.html">Surface Radiation Research Branch</a>. NOAA's <a
027 * href="https://www.srrb.noaa.gov/highlights/sunrise/solareqns.PDF">implementation</a> is based on equations from <a
028 * href="https://www.amazon.com/Astronomical-Table-Sun-Moon-Planets/dp/1942675038/">Astronomical Algorithms</a> by <a
029 * href="https://en.wikipedia.org/wiki/Jean_Meeus">Jean Meeus</a>. Added to the algorithm is an adjustment of the zenith
030 * to account for elevation. The algorithm can be found in the <a
031 * href="https://en.wikipedia.org/wiki/Sunrise_equation">Wikipedia Sunrise Equation</a> article.
032 * 
033 * @author © Eliyahu Hershfeld 2011 - 2026
034 */
035public class NOAACalculator extends AstronomicalCalculator {
036
037        /**
038         * {@inheritDoc} This calculator's results depend only on the arguments and on settings whose setters clear the cache.
039         */
040        @Override
041        protected boolean isResultCacheable() {
042                return true;
043        }
044        
045        /**
046         * The <a href="https://en.wikipedia.org/wiki/Julian_day">Julian day</a> of January 1, 2000, known as
047         * <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
048         */
049        private static final double JULIAN_DAY_JAN_1_2000 = 2451545.0;
050
051        /**
052         * Julian days per century.
053         */
054        private static final double JULIAN_DAYS_PER_CENTURY = 36525.0;
055        
056        /**
057         * An {@code enum} to indicate what type of solar event ({@link #SUNRISE SUNRISE}, {@link #SUNSET SUNSET},
058         * {@link #NOON NOON} or {@link #MIDNIGHT MIDNIGHT}) is being calculated.
059         * .
060         */
061        protected enum SolarEvent {
062                /**SUNRISE A solar event related to sunrise*/SUNRISE, /**SUNSET A solar event related to sunset*/SUNSET,
063                /**NOON A solar event related to noon*/NOON, /**MIDNIGHT A solar event related to midnight*/MIDNIGHT
064        }
065        
066        /**
067         * Default constructor of the NOAACalculator.
068         */
069        public NOAACalculator() {
070                super();
071        }
072
073        @Override
074        public String getCalculatorName() {
075                return "US National Oceanic and Atmospheric Administration Algorithm"; // Implementation of the Jean Meeus algorithm
076        }
077
078        @Override
079        public double getUTCSunrise(LocalDate dt, GeoLocation geoLocation, double zenith, boolean adjustForElevation) {
080                return getUTCSunRiseSet(dt, geoLocation, zenith, adjustForElevation,SolarEvent.SUNRISE);
081        }
082
083        @Override
084        public double getUTCSunset(LocalDate dt, GeoLocation geoLocation, double zenith, boolean adjustForElevation) {
085                return getUTCSunRiseSet(dt, geoLocation, zenith, adjustForElevation,SolarEvent.SUNSET);
086        }
087        
088        /**
089         * A method that calculates UTC sunrise or sunset as well as any time based on an angle above or below sunset and
090         * returns it as a {@code double} in 24-hour format. 5:45:00 AM will return 5.75.
091         * 
092         * @param localDate Used to calculate day of year.
093         * @param geoLocation The location information used for astronomical calculation of solar times.
094         * @param zenith the azimuth below the vertical zenith of 90&deg;. For sunset typically the {@link #adjustZenith zenith} used for
095         *         the calculation uses geometric zenith of 90&deg; and {@link #adjustZenith adjusts} this slightly to account for solar
096         *         refraction and the sun's radius. Another example would be
097         *         {@link com.kosherjava.zmanim.AstronomicalCalendar#getEndNauticalTwilight()} that passes
098         *         {@link com.kosherjava.zmanim.AstronomicalCalendar#NAUTICAL_ZENITH} to this method.
099         * @param adjustForElevation Should the time be adjusted for elevation
100         * @param solarEvent if the calculation is for {@link SolarEvent#SUNRISE} or {@link SolarEvent#SUNSET}
101         * @return The UTC time of sunrise or sunset in 24-hour format. 5:45:00 AM will return 5.75, while 5:45 PM will return 17.75. If
102         *         an error was encountered in the calculation (expected behavior for some locations such as near the poles,
103         *         {@link Double#NaN} will be returned.
104         * @see #getElevationAdjustment(double)
105         */
106        private double getUTCSunRiseSet(LocalDate localDate, GeoLocation geoLocation, double zenith, boolean adjustForElevation, 
107                        SolarEvent solarEvent) {
108                double elevation = 0;
109                if (adjustForElevation) {
110                        if (solarEvent == SolarEvent.SUNRISE) {
111                                elevation = geoLocation.getSunriseElevation();
112                        } else {
113                                elevation = geoLocation.getSunsetElevation();
114                        }
115                }
116                double adjustedZenith = adjustZenith(zenith, elevation, localDate);
117                double riseSet = getSunRiseSetUTC(localDate, geoLocation.getLatitude(), -geoLocation.getLongitude(),
118                                adjustedZenith, solarEvent);
119                riseSet = riseSet / 60;
120                return (riseSet % 24 + 24) % 24; // ensure that the time is >= 0 and < 24
121        }
122
123        /**
124         * Return the <a href="https://en.wikipedia.org/wiki/Julian_day">Julian day</a> from a Java {@code LocalDate}.
125         * 
126         * @param localDate The LocalDate
127         * @return the Julian day corresponding to the date Note: Number is returned for the start of the Julian day. Fractional days
128         *         / time should be added later.
129         */
130        private static double getJulianDay(LocalDate localDate) {
131                int year = localDate.getYear();
132                int month = localDate.getMonthValue();
133                int day = localDate.getDayOfMonth();
134
135                if (month <= 2) {
136                        year -= 1;
137                        month += 12;
138                }
139
140                int a = year / 100;
141                int b = 2 - a + a / 4;
142
143                return Math.floor(365.25 * (year + 4716)) + Math.floor(30.6001 * (month + 1)) + day + b - 1524.5;
144        }
145
146        /**
147         * Convert <a href="https://en.wikipedia.org/wiki/Julian_day">Julian day</a> to centuries since
148         * <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
149         * 
150         * @param julianDay the Julian Day to convert
151         * @return the centuries since 2000 Julian corresponding to the Julian Day
152         */
153        private static double getJulianCenturiesFromJulianDay(double julianDay) {
154                return (julianDay - JULIAN_DAY_JAN_1_2000) / JULIAN_DAYS_PER_CENTURY;
155        }
156
157        /**
158         * Returns the Geometric <a href="https://en.wikipedia.org/wiki/Mean_longitude">Mean Longitude</a> of the Sun.
159         * 
160         * @param julianCenturies the number of Julian centuries since
161         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
162         * @return the Geometric Mean Longitude of the Sun in degrees
163         */
164        private static double getSunGeometricMeanLongitude(double julianCenturies) {
165                double longitude = 280.46646 + julianCenturies * (36000.76983 + 0.0003032 * julianCenturies);
166                return (longitude % 360 + 360) % 360; // return a longitude is in the range of 0 - 360
167        }
168
169        /**
170         * Returns the Geometric <a href="https://en.wikipedia.org/wiki/Mean_anomaly">Mean Anomaly</a> of the Sun in degrees.
171         * 
172         * @param julianCenturies the number of Julian centuries since
173         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
174         * @return the Geometric Mean Anomaly of the Sun in degrees
175         */
176        private static double getSunGeometricMeanAnomaly(double julianCenturies) {
177                return 357.52911 + julianCenturies * (35999.05029 - 0.0001537 * julianCenturies);
178        }
179
180        /**
181         * Return the unitless <a href="https://en.wikipedia.org/wiki/Eccentricity_%28orbit%29">eccentricity of earth's orbit</a>.
182         * 
183         * @param julianCenturies the number of Julian centuries since
184         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
185         * @return the unitless eccentricity
186         */
187        private static double getEarthOrbitEccentricity(double julianCenturies) {
188                return 0.016708634 - julianCenturies * (0.000042037 + 0.0000001267 * julianCenturies);
189        }
190
191        /**
192         * Returns the <a href="https://en.wikipedia.org/wiki/Equation_of_the_center">equation of center</a> for the sun in degrees.
193         * 
194         * @param julianCenturies the number of Julian centuries since
195         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
196         * @return the equation of center for the sun in degrees
197         */
198        private static double getSunEquationOfCenter(double julianCenturies) {
199                double m = getSunGeometricMeanAnomaly(julianCenturies);
200                double sinm = sinDegrees(m);
201                double sin2m = sinDegrees(m + m);
202                double sin3m = sinDegrees(m + m + m);
203                return sinm * (1.914602 - julianCenturies * (0.004817 + 0.000014 * julianCenturies)) + sin2m
204                                * (0.019993 - 0.000101 * julianCenturies) + sin3m * 0.000289;
205        }
206
207        /**
208         * Return the <a href="https://en.wikipedia.org/wiki/True_longitude">true longitude</a> of the sun.
209         * 
210         * @param julianCenturies the number of Julian centuries since
211         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
212         * @return the sun's true longitude in degrees
213         */
214        private static double getSunTrueLongitude(double julianCenturies) {
215                double sunLongitude = getSunGeometricMeanLongitude(julianCenturies);
216                double center = getSunEquationOfCenter(julianCenturies); 
217                return sunLongitude + center;
218        }
219
220        /**
221         * Return the <a href="https://en.wikipedia.org/wiki/Apparent_longitude">apparent longitude</a> of the sun.
222         * 
223         * @param julianCenturies the number of Julian centuries since
224         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
225         * @return sun's apparent longitude in degrees
226         */
227        private static double getSunApparentLongitude(double julianCenturies) {
228                double sunTrueLongitude = getSunTrueLongitude(julianCenturies);
229                double omega = 125.04 - 1934.136 * julianCenturies;
230                return sunTrueLongitude - 0.00569 - 0.00478 * sinDegrees(omega);
231        }
232
233        /**
234         * Returns the mean <a href="https://en.wikipedia.org/wiki/Axial_tilt">obliquity of the ecliptic</a> (Axial tilt).
235         * 
236         * @param julianCenturies the number of Julian centuries since
237         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
238         * @return the mean obliquity in degrees
239         */
240        private static double getMeanObliquityOfEcliptic(double julianCenturies) {
241                double seconds = 21.448 - julianCenturies
242                                * (46.8150 + julianCenturies * (0.00059 - julianCenturies * (0.001813)));
243                return 23.0 + (26.0 + (seconds / 60.0)) / 60.0;
244        }
245
246        /**
247         * Returns the corrected <a href="https://en.wikipedia.org/wiki/Axial_tilt">obliquity of the ecliptic</a> (Axial tilt).
248         * 
249         * @param julianCenturies the number of Julian centuries since
250         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
251         * @return the corrected obliquity in degrees
252         */
253        private static double getObliquityCorrection(double julianCenturies) {
254                double obliquityOfEcliptic = getMeanObliquityOfEcliptic(julianCenturies);
255                double omega = 125.04 - 1934.136 * julianCenturies;
256                return obliquityOfEcliptic + 0.00256 * cosDegrees(omega);
257        }
258
259        /**
260         * Return the <a href="https://en.wikipedia.org/wiki/Declination">declination</a> of the sun.
261         * 
262         * @param julianCenturies the number of Julian centuries since
263         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
264         * @return the sun's declination in degrees
265         */
266        private static double getSunDeclination(double julianCenturies) {
267                double obliquityCorrection = getObliquityCorrection(julianCenturies);
268                double lambda = getSunApparentLongitude(julianCenturies);
269                double sint = sinDegrees(obliquityCorrection) * sinDegrees(lambda);
270                return asinDegrees(sint);
271        }
272
273        /**
274         * Return the <a href="https://en.wikipedia.org/wiki/Equation_of_time">Equation of Time</a> - the difference between
275         * true solar time and mean solar time
276         * 
277         * @param julianCenturies the number of Julian centuries since
278         *         <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
279         * @return equation of time in minutes of time
280         */
281        private static double getEquationOfTime(double julianCenturies) {
282                double epsilon = getObliquityCorrection(julianCenturies);
283                double geomMeanLongSun = getSunGeometricMeanLongitude(julianCenturies);
284                double eccentricityEarthOrbit = getEarthOrbitEccentricity(julianCenturies);
285                double geomMeanAnomalySun = getSunGeometricMeanAnomaly(julianCenturies);
286                double y = tanDegrees(epsilon / 2.0);
287                y *= y;
288                double sin2l0 =sinDegrees(2.0 * geomMeanLongSun);
289                double sinm = sinDegrees(geomMeanAnomalySun);
290                double cos2l0 = cosDegrees(2.0 * geomMeanLongSun);
291                double sin4l0 = sinDegrees(4.0 * geomMeanLongSun);
292                double sin2m = sinDegrees(2.0 * geomMeanAnomalySun);
293                double equationOfTime = y * sin2l0 - 2.0 * eccentricityEarthOrbit * sinm + 4.0 * eccentricityEarthOrbit * y
294                                * sinm * cos2l0 - 0.5 * y * y * sin4l0 - 1.25 * eccentricityEarthOrbit * eccentricityEarthOrbit * sin2m;
295                return Math.toDegrees(equationOfTime) * 4.0;
296        }
297        
298        /**
299         * Return the <a href="https://en.wikipedia.org/wiki/Hour_angle">hour angle</a> of the sun in
300         * <a href="https://en.wikipedia.org/wiki/Radian">radians</a> at for the latitude.
301         * 
302         * @param latitude the latitude of observer in degrees
303         * @param solarDeclination the declination angle of sun in degrees
304         * @param zenith the zenith
305         * @param solarEvent If the hour angle is for {@link SolarEvent#SUNRISE SUNRISE} or {@link SolarEvent#SUNSET SUNSET}
306         * @return hour angle of sunrise in <a href="https://en.wikipedia.org/wiki/Radian">radians</a>
307         */
308        private static double getSunHourAngle(double latitude, double solarDeclination, double zenith, SolarEvent solarEvent) {
309                double ratio = cosDegrees(zenith) / (cosDegrees(latitude) * cosDegrees(solarDeclination)) - tanDegrees(latitude)
310                                * tanDegrees(solarDeclination);
311                double hourAngle = Math.acos(ratio);
312                
313                if (solarEvent == SolarEvent.SUNSET) {
314                        hourAngle = -hourAngle;
315                }
316                return hourAngle;
317        }
318
319
320
321        @Override
322        public double getSolarElevation(Instant instant, GeoLocation geoLocation) {
323                return getSolarElevationAzimuth(instant, geoLocation, false);
324        }
325
326        @Override
327        public double getSolarAzimuth(Instant instant, GeoLocation geoLocation) {
328                return getSolarElevationAzimuth(instant, geoLocation, true);
329        }
330
331        /**
332         * Return the <a href="https://en.wikipedia.org/wiki/Celestial_coordinate_system">Solar Elevation</a> or
333         * <a href="https://en.wikipedia.org/wiki/Celestial_coordinate_system">Solar Azimuth</a> at the given location
334         * and time. Can be negative if the sun is below the horizon. Elevation is based on sea-level and is not
335         * adjusted for altitude.
336         * 
337         * @param instant date-time of calculation
338         * @param geoLocation The location for calculating the elevation or azimuth.
339         * @param isAzimuth true for azimuth, false for elevation
340         * @return solar elevation or azimuth in degrees.
341         * @see #getSolarElevation(Instant, GeoLocation)
342         * @see #getSolarAzimuth(Instant, GeoLocation)
343         */
344        private double getSolarElevationAzimuth(Instant instant, GeoLocation geoLocation, boolean isAzimuth) {
345                double lat = geoLocation.getLatitude();
346                double lon = geoLocation.getLongitude();
347                ZonedDateTime utc = instant.atZone(ZoneOffset.UTC);
348                double fractionalDay = (utc.getHour() + (utc.getMinute()
349                                + (utc.getSecond() + utc.getNano() / 1_000_000_000.0) / 60.0) / 60.0) / 24.0;
350                double jd = getJulianDay(utc.toLocalDate()) + fractionalDay;
351                double jc = getJulianCenturiesFromJulianDay(jd);
352                double decl = getSunDeclination(jc);
353                double eot = getEquationOfTime(jc);
354                double trueSolarTime = ((fractionalDay + eot / 1440.0 + lon / 360.0) + 2) % 1;
355                double hourAngle = trueSolarTime * 2 * Math.PI - Math.PI;
356                double cosZenith = sinDegrees(lat) * sinDegrees(decl) + cosDegrees(lat) * cosDegrees(decl) * Math.cos(hourAngle);
357                double zenithDeg = acosDegrees(Math.max(-1, Math.min(1, cosZenith)));
358                double elevation = (90.0 - zenithDeg) + adjustElevationForRefraction(90.0 - zenithDeg);
359                double azimuth;
360                double azDenom = cosDegrees(lat) * sinDegrees(zenithDeg);
361
362                if (Math.abs(azDenom) > 0.001) {
363                        double az = (sinDegrees(lat) * cosDegrees(zenithDeg) - sinDegrees(decl)) / azDenom;
364                        azimuth = 180 - acosDegrees(Math.max(-1, Math.min(1, az))) * (hourAngle > 0 ? -1 : 1);
365                } else {
366                        azimuth = lat > 0 ? 180 : 0;
367                }
368                return isAzimuth ? (azimuth + 360) % 360 : elevation;
369        }
370
371        
372        /**
373         * Apply refraction adjustment to solar elevation. 
374         * @param elevation the elevation to adjust.
375         * @return the adjusted elevation.
376         */
377        private double adjustElevationForRefraction(double elevation) {
378                if (elevation > 85.0) {
379                        return 0.0;
380                }
381                
382                double te = tanDegrees(elevation);
383                double correction;
384                
385                if (elevation > 5.0) {
386                        correction = 58.1 / te - 0.07 / Math.pow(te, 3) + 0.000086 / Math.pow(te, 5);
387                } else if (elevation > -0.575) {
388                        correction = 1735.0 + elevation * (-518.2 + elevation * (103.4 + elevation * (-12.79 + 0.711 * elevation)));
389                } else {
390                        correction = -20.774 / te;
391                }
392                return correction / 3600.0;
393        }
394        
395        /**
396         * {@inheritDoc}
397         * @see #getSolarNoonMidnightUTC(double, double, SolarEvent)
398         */
399        @Override
400        public double getUTCNoon(LocalDate localDate, GeoLocation geoLocation) {
401                double noon = getSolarNoonMidnightUTC(getJulianDay(localDate), -geoLocation.getLongitude(), SolarEvent.NOON);
402                noon = noon / 60;
403                return (noon % 24 + 24) % 24; // ensure that the time is >= 0 and < 24
404        }
405        
406        /**
407         * {@inheritDoc}
408         * @see #getSolarNoonMidnightUTC(double, double, SolarEvent)
409         */
410        @Override
411        public double getUTCMidnight(LocalDate localDate, GeoLocation geoLocation) {
412                double midnight = getSolarNoonMidnightUTC(getJulianDay(localDate), -geoLocation.getLongitude(), SolarEvent.MIDNIGHT);
413                midnight = midnight / 60;
414                return (midnight % 24 + 24) % 24; // ensure that the time is >= 0 and < 24
415        }
416
417        /**
418         * Return the <a href="https://en.wikipedia.org/wiki/Universal_Coordinated_Time">Universal Coordinated Time</a> (UTC) of the
419         * current day <a href="http://en.wikipedia.org/wiki/Noon#Solar_noon">solar noon</a> or the upcoming midnight (about 12 hours
420         * after solar noon) of the given day at the given location on earth.
421         * 
422         * @param julianDay The Julian day since <a href="https://en.wikipedia.org/wiki/Epoch_(astronomy)#J2000">J2000.0</a>.
423         * @param longitude The longitude of observer in degrees
424         * @param solarEvent If the calculation is for {@link SolarEvent#NOON NOON} or {@link SolarEvent#MIDNIGHT MIDNIGHT}
425         * @return The UTC time of sunset in 24-hour format. 12:45:00 AM will return 0.75 while 1:45:00 PM will return 13.75. If an error
426         *         was encountered in the calculation (expected behavior for some locations such as near the poles, {@link Double#NaN}
427         *         will be returned.
428         * @see #getUTCNoon(LocalDate, GeoLocation)
429         * @see #getUTCMidnight(LocalDate, GeoLocation)
430         */
431        private static double getSolarNoonMidnightUTC(double julianDay, double longitude, SolarEvent solarEvent) {
432                // no day-half shift: the loop epoch julianDay + solNoonUTC/1440 already lands on the event
433                // First pass for approximate solar noon to calculate equation of time
434                double tnoon = getJulianCenturiesFromJulianDay(julianDay + longitude / 360.0);
435                double equationOfTime = getEquationOfTime(tnoon);
436                double solNoonUTC = (longitude * 4) - equationOfTime; // minutes
437
438                // Refine the equation of time at the calculated transit time.
439                double newt;
440                for (int i = 0; i < 2; i++) {
441                        newt = getJulianCenturiesFromJulianDay(julianDay + solNoonUTC / 1440.0);
442                        equationOfTime = getEquationOfTime(newt);
443                        solNoonUTC = (solarEvent == SolarEvent.NOON ? 720 : 1440) + (longitude * 4) - equationOfTime;
444                }
445                return solNoonUTC;
446        }
447        
448        /**
449         * Return the <a href="https://en.wikipedia.org/wiki/Universal_Coordinated_Time">Universal Coordinated Time</a> (UTC)
450         * of sunrise or sunset in minutes for the given day at the given location on earth.
451         * @todo Possibly increase the number of passes for improved accuracy, especially in the Arctic areas.
452         * 
453         * @param localDate The {@code LocalDate}.
454         * @param latitude The latitude of observer in degrees
455         * @param longitude Longitude of observer in degrees
456         * @param zenith Zenith
457         * @param solarEvent If the calculation is for {@link SolarEvent#SUNRISE SUNRISE} or {@link SolarEvent#SUNSET SUNSET}
458         * @return The UTC time of sunrise or sunset in 24-hour format. 5:45:00 AM will return 5.75, while 5:45 PM will return 17.75. If
459         *         an error was encountered in the calculation (expected behavior for some locations such as near the poles,
460         *         {@link Double#NaN} will be returned.
461         */
462        private static double getSunRiseSetUTC(LocalDate localDate, double latitude, double longitude, double zenith,
463                        SolarEvent solarEvent) {
464                double julianDay = getJulianDay(localDate);
465
466                // Find the time of solar noon at the location, and use that declination.
467                // This is better than start of the Julian day
468                // TODO really not needed since the Julian day starts from local fixed noon. Changing this would be more
469                // efficient but would likely cause a very minor discrepancy in the calculated times (likely not reducing
470                // accuracy, just slightly different, thus potentially breaking test cases). Regardless, it would be within
471                // milliseconds.
472                double noonmin = getSolarNoonMidnightUTC(julianDay, longitude, SolarEvent.NOON);
473                double tnoon = getJulianCenturiesFromJulianDay(julianDay + noonmin / 1440.0);
474                // First calculates sunrise and approximate length of day
475                double equationOfTime = getEquationOfTime(tnoon);
476                double solarDeclination = getSunDeclination(tnoon);
477                double hourAngle = getSunHourAngle(latitude, solarDeclination, zenith, solarEvent);
478                if (Double.isNaN(hourAngle)) {
479                        // Using the Sun's declination at noon, the Sun never reaches this zenith today. But the declination changes
480                        // during the day (by up to about 0.2° in 12 hours), so the Sun may still just reach it around midnight, when it
481                        // is at its lowest. Before reporting that there is no event, try again with the declination and equation of time
482                        // at that solar midnight: the one before sunrise, or the one after sunset.
483                        double midnight = noonmin + (solarEvent == SolarEvent.SUNRISE ? -720 : 720);
484                        double tmidnight = getJulianCenturiesFromJulianDay(julianDay + midnight / 1440.0);
485                        equationOfTime = getEquationOfTime(tmidnight);
486                        solarDeclination = getSunDeclination(tmidnight);
487                        hourAngle = getSunHourAngle(latitude, solarDeclination, zenith, solarEvent);
488                }
489                double delta = longitude - Math.toDegrees(hourAngle);
490                double timeDiff = 4 * delta;
491                double timeUTC = 720 + timeDiff - equationOfTime;
492                // Second pass includes fractional Julian Day in gamma calc
493                double newt = getJulianCenturiesFromJulianDay(julianDay + timeUTC / 1440.0);
494                equationOfTime = getEquationOfTime(newt);
495                solarDeclination = getSunDeclination(newt);
496                hourAngle = getSunHourAngle(latitude, solarDeclination, zenith, solarEvent);
497                delta = longitude - Math.toDegrees(hourAngle);
498                timeDiff = 4 * delta;
499                timeUTC = 720 + timeDiff - equationOfTime;
500                return timeUTC;
501        }
502        
503        /**
504         * {@inheritDoc}
505         * The current implementation in this class only supports azimuth values of 90° (directly east) or 270° (directly west) that are
506         * directly needed in this library for the {@link com.kosherjava.zmanim.ComprehensiveZmanimCalendar#getPolarSunsetBenIshChai()}
507         * and {@link com.kosherjava.zmanim.ComprehensiveZmanimCalendar#getPolarSunriseBenIshChai()}.
508         * @throws IllegalArgumentException if the azimuth is not 90° or 270°.
509         * @todo complete the implementation for other azimuths. While not needed by this library, they may be of value to some projects.
510         *         There will be edge cases where the azimuth will occur more than once a day when based on the equation of time, the day
511         *         is shorter than 24 hours. In that case, the time for the first one will be returned.
512         */
513        public double getTimeAtAzimuth(LocalDate localDate, GeoLocation geoLocation, double targetAzimuth) {
514                if (targetAzimuth != 90.0 && targetAzimuth != 270.0) {
515                        throw new IllegalArgumentException(     "The targetAzimuth must be 90 or 270. Other azimuth values are not supported");
516                }
517
518                double julianDay = getJulianDay(localDate); 
519                double solarNoonBase = 0.5 - (geoLocation.getLongitude() / 360.0);
520                double dateTime = solarNoonBase + ((targetAzimuth == 90.0) ? 0.25 : 0.75);
521                
522                for (int i = 0; i < 3; i++) {
523                        double julianCenturies = getJulianCenturiesFromJulianDay(julianDay + dateTime);
524                        double ratio = tanDegrees(getSunDeclination(julianCenturies)) / tanDegrees(geoLocation.getLatitude());
525
526                        if (Double.isNaN(ratio) || ratio > 1.0 || ratio < -1.0) { // Handle Tropics, the Poles, and Equator line divisions
527                                return Double.NaN;
528                        }
529
530                        double offset = ((targetAzimuth == 90.0) ? -1.0 : 1.0) * (acosDegrees(ratio) / 360.0);
531                        dateTime = solarNoonBase + offset - (getEquationOfTime(julianCenturies) / 1440.0);
532                }
533                
534                return (dateTime * 24 % 24 + 24) % 24;
535        }
536}