blob: b0b6bda3843ef09b299a54be70e3615b02891dbc [file] [log] [blame]
Jungshik Shin87232d82017-05-13 21:10:13 -07001// © 2016 and later: Unicode, Inc. and others.
Jungshik Shin5feb9ad2016-10-21 12:52:48 -07002// License & terms of use: http://www.unicode.org/copyright.html
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00003/************************************************************************
4 * Copyright (C) 1996-2012, International Business Machines Corporation
5 * and others. All Rights Reserved.
6 ************************************************************************
7 * 2003-nov-07 srl Port from Java
8 */
9
10#include "astro.h"
11
12#if !UCONFIG_NO_FORMATTING
13
14#include "unicode/calendar.h"
15#include <math.h>
16#include <float.h>
17#include "unicode/putil.h"
18#include "uhash.h"
19#include "umutex.h"
20#include "ucln_in.h"
21#include "putilimp.h"
22#include <stdio.h> // for toString()
23
24#if defined (PI)
25#undef PI
26#endif
27
28#ifdef U_DEBUG_ASTRO
29# include "uresimp.h" // for debugging
30
31static void debug_astro_loc(const char *f, int32_t l)
32{
33 fprintf(stderr, "%s:%d: ", f, l);
34}
35
36static void debug_astro_msg(const char *pat, ...)
37{
38 va_list ap;
39 va_start(ap, pat);
40 vfprintf(stderr, pat, ap);
41 fflush(stderr);
42}
43#include "unicode/datefmt.h"
44#include "unicode/ustring.h"
45static const char * debug_astro_date(UDate d) {
46 static char gStrBuf[1024];
47 static DateFormat *df = NULL;
48 if(df == NULL) {
49 df = DateFormat::createDateTimeInstance(DateFormat::MEDIUM, DateFormat::MEDIUM, Locale::getUS());
50 df->adoptTimeZone(TimeZone::getGMT()->clone());
51 }
52 UnicodeString str;
53 df->format(d,str);
54 u_austrncpy(gStrBuf,str.getTerminatedBuffer(),sizeof(gStrBuf)-1);
55 return gStrBuf;
56}
57
58// must use double parens, i.e.: U_DEBUG_ASTRO_MSG(("four is: %d",4));
59#define U_DEBUG_ASTRO_MSG(x) {debug_astro_loc(__FILE__,__LINE__);debug_astro_msg x;}
60#else
61#define U_DEBUG_ASTRO_MSG(x)
62#endif
63
64static inline UBool isINVALID(double d) {
65 return(uprv_isNaN(d));
66}
67
Frank Tang69c72a62019-04-03 21:41:21 -070068static icu::UMutex *ccLock() {
69 static icu::UMutex *m = new icu::UMutex();
70 return m;
71}
jshin@chromium.org6f31ac32014-03-26 22:15:14 +000072
73U_CDECL_BEGIN
74static UBool calendar_astro_cleanup(void) {
75 return TRUE;
76}
77U_CDECL_END
78
79U_NAMESPACE_BEGIN
80
81/**
82 * The number of standard hours in one sidereal day.
83 * Approximately 24.93.
84 * @internal
85 * @deprecated ICU 2.4. This class may be removed or modified.
86 */
87#define SIDEREAL_DAY (23.93446960027)
88
89/**
90 * The number of sidereal hours in one mean solar day.
91 * Approximately 24.07.
92 * @internal
93 * @deprecated ICU 2.4. This class may be removed or modified.
94 */
95#define SOLAR_DAY (24.065709816)
96
97/**
98 * The average number of solar days from one new moon to the next. This is the time
99 * it takes for the moon to return the same ecliptic longitude as the sun.
100 * It is longer than the sidereal month because the sun's longitude increases
101 * during the year due to the revolution of the earth around the sun.
102 * Approximately 29.53.
103 *
104 * @see #SIDEREAL_MONTH
105 * @internal
106 * @deprecated ICU 2.4. This class may be removed or modified.
107 */
108const double CalendarAstronomer::SYNODIC_MONTH = 29.530588853;
109
110/**
111 * The average number of days it takes
112 * for the moon to return to the same ecliptic longitude relative to the
113 * stellar background. This is referred to as the sidereal month.
114 * It is shorter than the synodic month due to
115 * the revolution of the earth around the sun.
116 * Approximately 27.32.
117 *
118 * @see #SYNODIC_MONTH
119 * @internal
120 * @deprecated ICU 2.4. This class may be removed or modified.
121 */
122#define SIDEREAL_MONTH 27.32166
123
124/**
125 * The average number number of days between successive vernal equinoxes.
126 * Due to the precession of the earth's
127 * axis, this is not precisely the same as the sidereal year.
128 * Approximately 365.24
129 *
130 * @see #SIDEREAL_YEAR
131 * @internal
132 * @deprecated ICU 2.4. This class may be removed or modified.
133 */
134#define TROPICAL_YEAR 365.242191
135
136/**
137 * The average number of days it takes
138 * for the sun to return to the same position against the fixed stellar
139 * background. This is the duration of one orbit of the earth about the sun
140 * as it would appear to an outside observer.
141 * Due to the precession of the earth's
142 * axis, this is not precisely the same as the tropical year.
143 * Approximately 365.25.
144 *
145 * @see #TROPICAL_YEAR
146 * @internal
147 * @deprecated ICU 2.4. This class may be removed or modified.
148 */
149#define SIDEREAL_YEAR 365.25636
150
151//-------------------------------------------------------------------------
152// Time-related constants
153//-------------------------------------------------------------------------
154
155/**
156 * The number of milliseconds in one second.
157 * @internal
158 * @deprecated ICU 2.4. This class may be removed or modified.
159 */
160#define SECOND_MS U_MILLIS_PER_SECOND
161
162/**
163 * The number of milliseconds in one minute.
164 * @internal
165 * @deprecated ICU 2.4. This class may be removed or modified.
166 */
167#define MINUTE_MS U_MILLIS_PER_MINUTE
168
169/**
170 * The number of milliseconds in one hour.
171 * @internal
172 * @deprecated ICU 2.4. This class may be removed or modified.
173 */
174#define HOUR_MS U_MILLIS_PER_HOUR
175
176/**
177 * The number of milliseconds in one day.
178 * @internal
179 * @deprecated ICU 2.4. This class may be removed or modified.
180 */
181#define DAY_MS U_MILLIS_PER_DAY
182
183/**
184 * The start of the julian day numbering scheme used by astronomers, which
185 * is 1/1/4713 BC (Julian), 12:00 GMT. This is given as the number of milliseconds
186 * since 1/1/1970 AD (Gregorian), a negative number.
187 * Note that julian day numbers and
188 * the Julian calendar are <em>not</em> the same thing. Also note that
189 * julian days start at <em>noon</em>, not midnight.
190 * @internal
191 * @deprecated ICU 2.4. This class may be removed or modified.
192 */
193#define JULIAN_EPOCH_MS -210866760000000.0
194
195
196/**
197 * Milliseconds value for 0.0 January 2000 AD.
198 */
199#define EPOCH_2000_MS 946598400000.0
200
201//-------------------------------------------------------------------------
202// Assorted private data used for conversions
203//-------------------------------------------------------------------------
204
205// My own copies of these so compilers are more likely to optimize them away
206const double CalendarAstronomer::PI = 3.14159265358979323846;
207
208#define CalendarAstronomer_PI2 (CalendarAstronomer::PI*2.0)
209#define RAD_HOUR ( 12 / CalendarAstronomer::PI ) // radians -> hours
210#define DEG_RAD ( CalendarAstronomer::PI / 180 ) // degrees -> radians
211#define RAD_DEG ( 180 / CalendarAstronomer::PI ) // radians -> degrees
212
213/***
214 * Given 'value', add or subtract 'range' until 0 <= 'value' < range.
215 * The modulus operator.
216 */
217inline static double normalize(double value, double range) {
218 return value - range * ClockMath::floorDivide(value, range);
219}
220
221/**
222 * Normalize an angle so that it's in the range 0 - 2pi.
223 * For positive angles this is just (angle % 2pi), but the Java
224 * mod operator doesn't work that way for negative numbers....
225 */
226inline static double norm2PI(double angle) {
227 return normalize(angle, CalendarAstronomer::PI * 2.0);
228}
229
230/**
231 * Normalize an angle into the range -PI - PI
232 */
233inline static double normPI(double angle) {
234 return normalize(angle + CalendarAstronomer::PI, CalendarAstronomer::PI * 2.0) - CalendarAstronomer::PI;
235}
236
237//-------------------------------------------------------------------------
238// Constructors
239//-------------------------------------------------------------------------
240
241/**
242 * Construct a new <code>CalendarAstronomer</code> object that is initialized to
243 * the current date and time.
244 * @internal
245 * @deprecated ICU 2.4. This class may be removed or modified.
246 */
247CalendarAstronomer::CalendarAstronomer():
248 fTime(Calendar::getNow()), fLongitude(0.0), fLatitude(0.0), fGmtOffset(0.0), moonPosition(0,0), moonPositionSet(FALSE) {
249 clearCache();
250}
251
252/**
253 * Construct a new <code>CalendarAstronomer</code> object that is initialized to
254 * the specified date and time.
255 * @internal
256 * @deprecated ICU 2.4. This class may be removed or modified.
257 */
258CalendarAstronomer::CalendarAstronomer(UDate d): fTime(d), fLongitude(0.0), fLatitude(0.0), fGmtOffset(0.0), moonPosition(0,0), moonPositionSet(FALSE) {
259 clearCache();
260}
261
262/**
263 * Construct a new <code>CalendarAstronomer</code> object with the given
264 * latitude and longitude. The object's time is set to the current
265 * date and time.
266 * <p>
267 * @param longitude The desired longitude, in <em>degrees</em> east of
268 * the Greenwich meridian.
269 *
270 * @param latitude The desired latitude, in <em>degrees</em>. Positive
271 * values signify North, negative South.
272 *
273 * @see java.util.Date#getTime()
274 * @internal
275 * @deprecated ICU 2.4. This class may be removed or modified.
276 */
277CalendarAstronomer::CalendarAstronomer(double longitude, double latitude) :
278 fTime(Calendar::getNow()), moonPosition(0,0), moonPositionSet(FALSE) {
279 fLongitude = normPI(longitude * (double)DEG_RAD);
280 fLatitude = normPI(latitude * (double)DEG_RAD);
281 fGmtOffset = (double)(fLongitude * 24. * (double)HOUR_MS / (double)CalendarAstronomer_PI2);
282 clearCache();
283}
284
285CalendarAstronomer::~CalendarAstronomer()
286{
287}
288
289//-------------------------------------------------------------------------
290// Time and date getters and setters
291//-------------------------------------------------------------------------
292
293/**
294 * Set the current date and time of this <code>CalendarAstronomer</code> object. All
295 * astronomical calculations are performed based on this time setting.
296 *
297 * @param aTime the date and time, expressed as the number of milliseconds since
298 * 1/1/1970 0:00 GMT (Gregorian).
299 *
300 * @see #setDate
301 * @see #getTime
302 * @internal
303 * @deprecated ICU 2.4. This class may be removed or modified.
304 */
305void CalendarAstronomer::setTime(UDate aTime) {
306 fTime = aTime;
307 U_DEBUG_ASTRO_MSG(("setTime(%.1lf, %sL)\n", aTime, debug_astro_date(aTime+fGmtOffset)));
308 clearCache();
309}
310
311/**
312 * Set the current date and time of this <code>CalendarAstronomer</code> object. All
313 * astronomical calculations are performed based on this time setting.
314 *
315 * @param jdn the desired time, expressed as a "julian day number",
316 * which is the number of elapsed days since
317 * 1/1/4713 BC (Julian), 12:00 GMT. Note that julian day
318 * numbers start at <em>noon</em>. To get the jdn for
319 * the corresponding midnight, subtract 0.5.
320 *
321 * @see #getJulianDay
322 * @see #JULIAN_EPOCH_MS
323 * @internal
324 * @deprecated ICU 2.4. This class may be removed or modified.
325 */
326void CalendarAstronomer::setJulianDay(double jdn) {
327 fTime = (double)(jdn * DAY_MS) + JULIAN_EPOCH_MS;
328 clearCache();
329 julianDay = jdn;
330}
331
332/**
333 * Get the current time of this <code>CalendarAstronomer</code> object,
334 * represented as the number of milliseconds since
335 * 1/1/1970 AD 0:00 GMT (Gregorian).
336 *
337 * @see #setTime
338 * @see #getDate
339 * @internal
340 * @deprecated ICU 2.4. This class may be removed or modified.
341 */
342UDate CalendarAstronomer::getTime() {
343 return fTime;
344}
345
346/**
347 * Get the current time of this <code>CalendarAstronomer</code> object,
348 * expressed as a "julian day number", which is the number of elapsed
349 * days since 1/1/4713 BC (Julian), 12:00 GMT.
350 *
351 * @see #setJulianDay
352 * @see #JULIAN_EPOCH_MS
353 * @internal
354 * @deprecated ICU 2.4. This class may be removed or modified.
355 */
356double CalendarAstronomer::getJulianDay() {
357 if (isINVALID(julianDay)) {
358 julianDay = (fTime - (double)JULIAN_EPOCH_MS) / (double)DAY_MS;
359 }
360 return julianDay;
361}
362
363/**
364 * Return this object's time expressed in julian centuries:
365 * the number of centuries after 1/1/1900 AD, 12:00 GMT
366 *
367 * @see #getJulianDay
368 * @internal
369 * @deprecated ICU 2.4. This class may be removed or modified.
370 */
371double CalendarAstronomer::getJulianCentury() {
372 if (isINVALID(julianCentury)) {
373 julianCentury = (getJulianDay() - 2415020.0) / 36525.0;
374 }
375 return julianCentury;
376}
377
378/**
379 * Returns the current Greenwich sidereal time, measured in hours
380 * @internal
381 * @deprecated ICU 2.4. This class may be removed or modified.
382 */
383double CalendarAstronomer::getGreenwichSidereal() {
384 if (isINVALID(siderealTime)) {
385 // See page 86 of "Practial Astronomy with your Calculator",
386 // by Peter Duffet-Smith, for details on the algorithm.
387
388 double UT = normalize(fTime/(double)HOUR_MS, 24.);
389
390 siderealTime = normalize(getSiderealOffset() + UT*1.002737909, 24.);
391 }
392 return siderealTime;
393}
394
395double CalendarAstronomer::getSiderealOffset() {
396 if (isINVALID(siderealT0)) {
397 double JD = uprv_floor(getJulianDay() - 0.5) + 0.5;
398 double S = JD - 2451545.0;
399 double T = S / 36525.0;
400 siderealT0 = normalize(6.697374558 + 2400.051336*T + 0.000025862*T*T, 24);
401 }
402 return siderealT0;
403}
404
405/**
406 * Returns the current local sidereal time, measured in hours
407 * @internal
408 * @deprecated ICU 2.4. This class may be removed or modified.
409 */
410double CalendarAstronomer::getLocalSidereal() {
411 return normalize(getGreenwichSidereal() + (fGmtOffset/(double)HOUR_MS), 24.);
412}
413
414/**
415 * Converts local sidereal time to Universal Time.
416 *
417 * @param lst The Local Sidereal Time, in hours since sidereal midnight
418 * on this object's current date.
419 *
420 * @return The corresponding Universal Time, in milliseconds since
421 * 1 Jan 1970, GMT.
422 */
423double CalendarAstronomer::lstToUT(double lst) {
424 // Convert to local mean time
425 double lt = normalize((lst - getSiderealOffset()) * 0.9972695663, 24);
426
427 // Then find local midnight on this day
428 double base = (DAY_MS * ClockMath::floorDivide(fTime + fGmtOffset,(double)DAY_MS)) - fGmtOffset;
429
430 //out(" lt =" + lt + " hours");
431 //out(" base=" + new Date(base));
432
433 return base + (long)(lt * HOUR_MS);
434}
435
436
437//-------------------------------------------------------------------------
438// Coordinate transformations, all based on the current time of this object
439//-------------------------------------------------------------------------
440
441/**
442 * Convert from ecliptic to equatorial coordinates.
443 *
444 * @param ecliptic A point in the sky in ecliptic coordinates.
445 * @return The corresponding point in equatorial coordinates.
446 * @internal
447 * @deprecated ICU 2.4. This class may be removed or modified.
448 */
449CalendarAstronomer::Equatorial& CalendarAstronomer::eclipticToEquatorial(CalendarAstronomer::Equatorial& result, const CalendarAstronomer::Ecliptic& ecliptic)
450{
451 return eclipticToEquatorial(result, ecliptic.longitude, ecliptic.latitude);
452}
453
454/**
455 * Convert from ecliptic to equatorial coordinates.
456 *
457 * @param eclipLong The ecliptic longitude
458 * @param eclipLat The ecliptic latitude
459 *
460 * @return The corresponding point in equatorial coordinates.
461 * @internal
462 * @deprecated ICU 2.4. This class may be removed or modified.
463 */
464CalendarAstronomer::Equatorial& CalendarAstronomer::eclipticToEquatorial(CalendarAstronomer::Equatorial& result, double eclipLong, double eclipLat)
465{
466 // See page 42 of "Practial Astronomy with your Calculator",
467 // by Peter Duffet-Smith, for details on the algorithm.
468
469 double obliq = eclipticObliquity();
470 double sinE = ::sin(obliq);
471 double cosE = cos(obliq);
472
473 double sinL = ::sin(eclipLong);
474 double cosL = cos(eclipLong);
475
476 double sinB = ::sin(eclipLat);
477 double cosB = cos(eclipLat);
478 double tanB = tan(eclipLat);
479
480 result.set(atan2(sinL*cosE - tanB*sinE, cosL),
481 asin(sinB*cosE + cosB*sinE*sinL) );
482 return result;
483}
484
485/**
486 * Convert from ecliptic longitude to equatorial coordinates.
487 *
488 * @param eclipLong The ecliptic longitude
489 *
490 * @return The corresponding point in equatorial coordinates.
491 * @internal
492 * @deprecated ICU 2.4. This class may be removed or modified.
493 */
494CalendarAstronomer::Equatorial& CalendarAstronomer::eclipticToEquatorial(CalendarAstronomer::Equatorial& result, double eclipLong)
495{
496 return eclipticToEquatorial(result, eclipLong, 0); // TODO: optimize
497}
498
499/**
500 * @internal
501 * @deprecated ICU 2.4. This class may be removed or modified.
502 */
503CalendarAstronomer::Horizon& CalendarAstronomer::eclipticToHorizon(CalendarAstronomer::Horizon& result, double eclipLong)
504{
505 Equatorial equatorial;
506 eclipticToEquatorial(equatorial, eclipLong);
507
508 double H = getLocalSidereal()*CalendarAstronomer::PI/12 - equatorial.ascension; // Hour-angle
509
510 double sinH = ::sin(H);
511 double cosH = cos(H);
512 double sinD = ::sin(equatorial.declination);
513 double cosD = cos(equatorial.declination);
514 double sinL = ::sin(fLatitude);
515 double cosL = cos(fLatitude);
516
517 double altitude = asin(sinD*sinL + cosD*cosL*cosH);
518 double azimuth = atan2(-cosD*cosL*sinH, sinD - sinL * ::sin(altitude));
519
520 result.set(azimuth, altitude);
521 return result;
522}
523
524
525//-------------------------------------------------------------------------
526// The Sun
527//-------------------------------------------------------------------------
528
529//
530// Parameters of the Sun's orbit as of the epoch Jan 0.0 1990
531// Angles are in radians (after multiplying by CalendarAstronomer::PI/180)
532//
533#define JD_EPOCH 2447891.5 // Julian day of epoch
534
535#define SUN_ETA_G (279.403303 * CalendarAstronomer::PI/180) // Ecliptic longitude at epoch
536#define SUN_OMEGA_G (282.768422 * CalendarAstronomer::PI/180) // Ecliptic longitude of perigee
537#define SUN_E 0.016713 // Eccentricity of orbit
538//double sunR0 1.495585e8 // Semi-major axis in KM
539//double sunTheta0 (0.533128 * CalendarAstronomer::PI/180) // Angular diameter at R0
540
541// The following three methods, which compute the sun parameters
542// given above for an arbitrary epoch (whatever time the object is
543// set to), make only a small difference as compared to using the
544// above constants. E.g., Sunset times might differ by ~12
545// seconds. Furthermore, the eta-g computation is befuddled by
546// Duffet-Smith's incorrect coefficients (p.86). I've corrected
547// the first-order coefficient but the others may be off too - no
548// way of knowing without consulting another source.
549
550// /**
551// * Return the sun's ecliptic longitude at perigee for the current time.
552// * See Duffett-Smith, p. 86.
553// * @return radians
554// */
555// private double getSunOmegaG() {
556// double T = getJulianCentury();
557// return (281.2208444 + (1.719175 + 0.000452778*T)*T) * DEG_RAD;
558// }
559
560// /**
561// * Return the sun's ecliptic longitude for the current time.
562// * See Duffett-Smith, p. 86.
563// * @return radians
564// */
565// private double getSunEtaG() {
566// double T = getJulianCentury();
567// //return (279.6966778 + (36000.76892 + 0.0003025*T)*T) * DEG_RAD;
568// //
569// // The above line is from Duffett-Smith, and yields manifestly wrong
570// // results. The below constant is derived empirically to match the
571// // constant he gives for the 1990 EPOCH.
572// //
573// return (279.6966778 + (-0.3262541582718024 + 0.0003025*T)*T) * DEG_RAD;
574// }
575
576// /**
577// * Return the sun's eccentricity of orbit for the current time.
578// * See Duffett-Smith, p. 86.
579// * @return double
580// */
581// private double getSunE() {
582// double T = getJulianCentury();
583// return 0.01675104 - (0.0000418 + 0.000000126*T)*T;
584// }
585
586/**
587 * Find the "true anomaly" (longitude) of an object from
588 * its mean anomaly and the eccentricity of its orbit. This uses
589 * an iterative solution to Kepler's equation.
590 *
591 * @param meanAnomaly The object's longitude calculated as if it were in
592 * a regular, circular orbit, measured in radians
593 * from the point of perigee.
594 *
595 * @param eccentricity The eccentricity of the orbit
596 *
597 * @return The true anomaly (longitude) measured in radians
598 */
599static double trueAnomaly(double meanAnomaly, double eccentricity)
600{
601 // First, solve Kepler's equation iteratively
602 // Duffett-Smith, p.90
603 double delta;
604 double E = meanAnomaly;
605 do {
606 delta = E - eccentricity * ::sin(E) - meanAnomaly;
607 E = E - delta / (1 - eccentricity * ::cos(E));
608 }
609 while (uprv_fabs(delta) > 1e-5); // epsilon = 1e-5 rad
610
611 return 2.0 * ::atan( ::tan(E/2) * ::sqrt( (1+eccentricity)
612 /(1-eccentricity) ) );
613}
614
615/**
616 * The longitude of the sun at the time specified by this object.
617 * The longitude is measured in radians along the ecliptic
618 * from the "first point of Aries," the point at which the ecliptic
619 * crosses the earth's equatorial plane at the vernal equinox.
620 * <p>
621 * Currently, this method uses an approximation of the two-body Kepler's
622 * equation for the earth and the sun. It does not take into account the
623 * perturbations caused by the other planets, the moon, etc.
624 * @internal
625 * @deprecated ICU 2.4. This class may be removed or modified.
626 */
627double CalendarAstronomer::getSunLongitude()
628{
629 // See page 86 of "Practial Astronomy with your Calculator",
630 // by Peter Duffet-Smith, for details on the algorithm.
631
632 if (isINVALID(sunLongitude)) {
633 getSunLongitude(getJulianDay(), sunLongitude, meanAnomalySun);
634 }
635 return sunLongitude;
636}
637
638/**
639 * TODO Make this public when the entire class is package-private.
640 */
641/*public*/ void CalendarAstronomer::getSunLongitude(double jDay, double &longitude, double &meanAnomaly)
642{
643 // See page 86 of "Practial Astronomy with your Calculator",
644 // by Peter Duffet-Smith, for details on the algorithm.
645
646 double day = jDay - JD_EPOCH; // Days since epoch
647
648 // Find the angular distance the sun in a fictitious
649 // circular orbit has travelled since the epoch.
650 double epochAngle = norm2PI(CalendarAstronomer_PI2/TROPICAL_YEAR*day);
651
652 // The epoch wasn't at the sun's perigee; find the angular distance
653 // since perigee, which is called the "mean anomaly"
654 meanAnomaly = norm2PI(epochAngle + SUN_ETA_G - SUN_OMEGA_G);
655
656 // Now find the "true anomaly", e.g. the real solar longitude
657 // by solving Kepler's equation for an elliptical orbit
658 // NOTE: The 3rd ed. of the book lists omega_g and eta_g in different
659 // equations; omega_g is to be correct.
660 longitude = norm2PI(trueAnomaly(meanAnomaly, SUN_E) + SUN_OMEGA_G);
661}
662
663/**
664 * The position of the sun at this object's current date and time,
665 * in equatorial coordinates.
666 * @internal
667 * @deprecated ICU 2.4. This class may be removed or modified.
668 */
669CalendarAstronomer::Equatorial& CalendarAstronomer::getSunPosition(CalendarAstronomer::Equatorial& result) {
670 return eclipticToEquatorial(result, getSunLongitude(), 0);
671}
672
673
674/**
675 * Constant representing the vernal equinox.
676 * For use with {@link #getSunTime getSunTime}.
677 * Note: In this case, "vernal" refers to the northern hemisphere's seasons.
678 * @internal
679 * @deprecated ICU 2.4. This class may be removed or modified.
680 */
681/*double CalendarAstronomer::VERNAL_EQUINOX() {
682 return 0;
683}*/
684
685/**
686 * Constant representing the summer solstice.
687 * For use with {@link #getSunTime getSunTime}.
688 * Note: In this case, "summer" refers to the northern hemisphere's seasons.
689 * @internal
690 * @deprecated ICU 2.4. This class may be removed or modified.
691 */
692double CalendarAstronomer::SUMMER_SOLSTICE() {
693 return (CalendarAstronomer::PI/2);
694}
695
696/**
697 * Constant representing the autumnal equinox.
698 * For use with {@link #getSunTime getSunTime}.
699 * Note: In this case, "autumn" refers to the northern hemisphere's seasons.
700 * @internal
701 * @deprecated ICU 2.4. This class may be removed or modified.
702 */
703/*double CalendarAstronomer::AUTUMN_EQUINOX() {
704 return (CalendarAstronomer::PI);
705}*/
706
707/**
708 * Constant representing the winter solstice.
709 * For use with {@link #getSunTime getSunTime}.
710 * Note: In this case, "winter" refers to the northern hemisphere's seasons.
711 * @internal
712 * @deprecated ICU 2.4. This class may be removed or modified.
713 */
714double CalendarAstronomer::WINTER_SOLSTICE() {
715 return ((CalendarAstronomer::PI*3)/2);
716}
717
718CalendarAstronomer::AngleFunc::~AngleFunc() {}
719
720/**
721 * Find the next time at which the sun's ecliptic longitude will have
722 * the desired value.
723 * @internal
724 * @deprecated ICU 2.4. This class may be removed or modified.
725 */
726class SunTimeAngleFunc : public CalendarAstronomer::AngleFunc {
727public:
728 virtual ~SunTimeAngleFunc();
729 virtual double eval(CalendarAstronomer& a) { return a.getSunLongitude(); }
730};
731
732SunTimeAngleFunc::~SunTimeAngleFunc() {}
733
734UDate CalendarAstronomer::getSunTime(double desired, UBool next)
735{
736 SunTimeAngleFunc func;
737 return timeOfAngle( func,
738 desired,
739 TROPICAL_YEAR,
740 MINUTE_MS,
741 next);
742}
743
744CalendarAstronomer::CoordFunc::~CoordFunc() {}
745
746class RiseSetCoordFunc : public CalendarAstronomer::CoordFunc {
747public:
748 virtual ~RiseSetCoordFunc();
749 virtual void eval(CalendarAstronomer::Equatorial& result, CalendarAstronomer&a) { a.getSunPosition(result); }
750};
751
752RiseSetCoordFunc::~RiseSetCoordFunc() {}
753
754UDate CalendarAstronomer::getSunRiseSet(UBool rise)
755{
756 UDate t0 = fTime;
757
758 // Make a rough guess: 6am or 6pm local time on the current day
759 double noon = ClockMath::floorDivide(fTime + fGmtOffset, (double)DAY_MS)*DAY_MS - fGmtOffset + (12*HOUR_MS);
760
761 U_DEBUG_ASTRO_MSG(("Noon=%.2lf, %sL, gmtoff %.2lf\n", noon, debug_astro_date(noon+fGmtOffset), fGmtOffset));
762 setTime(noon + ((rise ? -6 : 6) * HOUR_MS));
763 U_DEBUG_ASTRO_MSG(("added %.2lf ms as a guess,\n", ((rise ? -6. : 6.) * HOUR_MS)));
764
765 RiseSetCoordFunc func;
766 double t = riseOrSet(func,
767 rise,
768 .533 * DEG_RAD, // Angular Diameter
769 34. /60.0 * DEG_RAD, // Refraction correction
770 MINUTE_MS / 12.); // Desired accuracy
771
772 setTime(t0);
773 return t;
774}
775
776// Commented out - currently unused. ICU 2.6, Alan
777// //-------------------------------------------------------------------------
778// // Alternate Sun Rise/Set
779// // See Duffett-Smith p.93
780// //-------------------------------------------------------------------------
781//
782// // This yields worse results (as compared to USNO data) than getSunRiseSet().
783// /**
784// * TODO Make this when the entire class is package-private.
785// */
786// /*public*/ long getSunRiseSet2(boolean rise) {
787// // 1. Calculate coordinates of the sun's center for midnight
788// double jd = uprv_floor(getJulianDay() - 0.5) + 0.5;
789// double[] sl = getSunLongitude(jd);// double lambda1 = sl[0];
790// Equatorial pos1 = eclipticToEquatorial(lambda1, 0);
791//
792// // 2. Add ... to lambda to get position 24 hours later
793// double lambda2 = lambda1 + 0.985647*DEG_RAD;
794// Equatorial pos2 = eclipticToEquatorial(lambda2, 0);
795//
796// // 3. Calculate LSTs of rising and setting for these two positions
797// double tanL = ::tan(fLatitude);
798// double H = ::acos(-tanL * ::tan(pos1.declination));
799// double lst1r = (CalendarAstronomer_PI2 + pos1.ascension - H) * 24 / CalendarAstronomer_PI2;
800// double lst1s = (pos1.ascension + H) * 24 / CalendarAstronomer_PI2;
801// H = ::acos(-tanL * ::tan(pos2.declination));
802// double lst2r = (CalendarAstronomer_PI2-H + pos2.ascension ) * 24 / CalendarAstronomer_PI2;
803// double lst2s = (H + pos2.ascension ) * 24 / CalendarAstronomer_PI2;
804// if (lst1r > 24) lst1r -= 24;
805// if (lst1s > 24) lst1s -= 24;
806// if (lst2r > 24) lst2r -= 24;
807// if (lst2s > 24) lst2s -= 24;
808//
809// // 4. Convert LSTs to GSTs. If GST1 > GST2, add 24 to GST2.
810// double gst1r = lstToGst(lst1r);
811// double gst1s = lstToGst(lst1s);
812// double gst2r = lstToGst(lst2r);
813// double gst2s = lstToGst(lst2s);
814// if (gst1r > gst2r) gst2r += 24;
815// if (gst1s > gst2s) gst2s += 24;
816//
817// // 5. Calculate GST at 0h UT of this date
818// double t00 = utToGst(0);
819//
820// // 6. Calculate GST at 0h on the observer's longitude
821// double offset = ::round(fLongitude*12/PI); // p.95 step 6; he _rounds_ to nearest 15 deg.
822// double t00p = t00 - offset*1.002737909;
823// if (t00p < 0) t00p += 24; // do NOT normalize
824//
825// // 7. Adjust
826// if (gst1r < t00p) {
827// gst1r += 24;
828// gst2r += 24;
829// }
830// if (gst1s < t00p) {
831// gst1s += 24;
832// gst2s += 24;
833// }
834//
835// // 8.
836// double gstr = (24.07*gst1r-t00*(gst2r-gst1r))/(24.07+gst1r-gst2r);
837// double gsts = (24.07*gst1s-t00*(gst2s-gst1s))/(24.07+gst1s-gst2s);
838//
839// // 9. Correct for parallax, refraction, and sun's diameter
840// double dec = (pos1.declination + pos2.declination) / 2;
841// double psi = ::acos(sin(fLatitude) / cos(dec));
842// double x = 0.830725 * DEG_RAD; // parallax+refraction+diameter
843// double y = ::asin(sin(x) / ::sin(psi)) * RAD_DEG;
844// double delta_t = 240 * y / cos(dec) / 3600; // hours
845//
846// // 10. Add correction to GSTs, subtract from GSTr
847// gstr -= delta_t;
848// gsts += delta_t;
849//
850// // 11. Convert GST to UT and then to local civil time
851// double ut = gstToUt(rise ? gstr : gsts);
852// //System.out.println((rise?"rise=":"set=") + ut + ", delta_t=" + delta_t);
853// long midnight = DAY_MS * (time / DAY_MS); // Find UT midnight on this day
854// return midnight + (long) (ut * 3600000);
855// }
856
857// Commented out - currently unused. ICU 2.6, Alan
858// /**
859// * Convert local sidereal time to Greenwich sidereal time.
860// * Section 15. Duffett-Smith p.21
861// * @param lst in hours (0..24)
862// * @return GST in hours (0..24)
863// */
864// double lstToGst(double lst) {
865// double delta = fLongitude * 24 / CalendarAstronomer_PI2;
866// return normalize(lst - delta, 24);
867// }
868
869// Commented out - currently unused. ICU 2.6, Alan
870// /**
871// * Convert UT to GST on this date.
872// * Section 12. Duffett-Smith p.17
873// * @param ut in hours
874// * @return GST in hours
875// */
876// double utToGst(double ut) {
877// return normalize(getT0() + ut*1.002737909, 24);
878// }
879
880// Commented out - currently unused. ICU 2.6, Alan
881// /**
882// * Convert GST to UT on this date.
883// * Section 13. Duffett-Smith p.18
884// * @param gst in hours
885// * @return UT in hours
886// */
887// double gstToUt(double gst) {
888// return normalize(gst - getT0(), 24) * 0.9972695663;
889// }
890
891// Commented out - currently unused. ICU 2.6, Alan
892// double getT0() {
893// // Common computation for UT <=> GST
894//
895// // Find JD for 0h UT
896// double jd = uprv_floor(getJulianDay() - 0.5) + 0.5;
897//
898// double s = jd - 2451545.0;
899// double t = s / 36525.0;
900// double t0 = 6.697374558 + (2400.051336 + 0.000025862*t)*t;
901// return t0;
902// }
903
904// Commented out - currently unused. ICU 2.6, Alan
905// //-------------------------------------------------------------------------
906// // Alternate Sun Rise/Set
907// // See sci.astro FAQ
908// // http://www.faqs.org/faqs/astronomy/faq/part3/section-5.html
909// //-------------------------------------------------------------------------
910//
911// // Note: This method appears to produce inferior accuracy as
912// // compared to getSunRiseSet().
913//
914// /**
915// * TODO Make this when the entire class is package-private.
916// */
917// /*public*/ long getSunRiseSet3(boolean rise) {
918//
919// // Compute day number for 0.0 Jan 2000 epoch
920// double d = (double)(time - EPOCH_2000_MS) / DAY_MS;
921//
922// // Now compute the Local Sidereal Time, LST:
923// //
924// double LST = 98.9818 + 0.985647352 * d + /*UT*15 + long*/
925// fLongitude*RAD_DEG;
926// //
927// // (east long. positive). Note that LST is here expressed in degrees,
928// // where 15 degrees corresponds to one hour. Since LST really is an angle,
929// // it's convenient to use one unit---degrees---throughout.
930//
931// // COMPUTING THE SUN'S POSITION
932// // ----------------------------
933// //
934// // To be able to compute the Sun's rise/set times, you need to be able to
935// // compute the Sun's position at any time. First compute the "day
936// // number" d as outlined above, for the desired moment. Next compute:
937// //
938// double oblecl = 23.4393 - 3.563E-7 * d;
939// //
940// double w = 282.9404 + 4.70935E-5 * d;
941// double M = 356.0470 + 0.9856002585 * d;
942// double e = 0.016709 - 1.151E-9 * d;
943// //
944// // This is the obliquity of the ecliptic, plus some of the elements of
945// // the Sun's apparent orbit (i.e., really the Earth's orbit): w =
946// // argument of perihelion, M = mean anomaly, e = eccentricity.
947// // Semi-major axis is here assumed to be exactly 1.0 (while not strictly
948// // true, this is still an accurate approximation). Next compute E, the
949// // eccentric anomaly:
950// //
951// double E = M + e*(180/PI) * ::sin(M*DEG_RAD) * ( 1.0 + e*cos(M*DEG_RAD) );
952// //
953// // where E and M are in degrees. This is it---no further iterations are
954// // needed because we know e has a sufficiently small value. Next compute
955// // the true anomaly, v, and the distance, r:
956// //
957// /* r * cos(v) = */ double A = cos(E*DEG_RAD) - e;
958// /* r * ::sin(v) = */ double B = ::sqrt(1 - e*e) * ::sin(E*DEG_RAD);
959// //
960// // and
961// //
962// // r = sqrt( A*A + B*B )
963// double v = ::atan2( B, A )*RAD_DEG;
964// //
965// // The Sun's true longitude, slon, can now be computed:
966// //
967// double slon = v + w;
968// //
969// // Since the Sun is always at the ecliptic (or at least very very close to
970// // it), we can use simplified formulae to convert slon (the Sun's ecliptic
971// // longitude) to sRA and sDec (the Sun's RA and Dec):
972// //
973// // ::sin(slon) * cos(oblecl)
974// // tan(sRA) = -------------------------
975// // cos(slon)
976// //
977// // ::sin(sDec) = ::sin(oblecl) * ::sin(slon)
978// //
979// // As was the case when computing az, the Azimuth, if possible use an
980// // atan2() function to compute sRA.
981//
982// double sRA = ::atan2(sin(slon*DEG_RAD) * cos(oblecl*DEG_RAD), cos(slon*DEG_RAD))*RAD_DEG;
983//
984// double sin_sDec = ::sin(oblecl*DEG_RAD) * ::sin(slon*DEG_RAD);
985// double sDec = ::asin(sin_sDec)*RAD_DEG;
986//
987// // COMPUTING RISE AND SET TIMES
988// // ----------------------------
989// //
990// // To compute when an object rises or sets, you must compute when it
991// // passes the meridian and the HA of rise/set. Then the rise time is
992// // the meridian time minus HA for rise/set, and the set time is the
993// // meridian time plus the HA for rise/set.
994// //
995// // To find the meridian time, compute the Local Sidereal Time at 0h local
996// // time (or 0h UT if you prefer to work in UT) as outlined above---name
997// // that quantity LST0. The Meridian Time, MT, will now be:
998// //
999// // MT = RA - LST0
1000// double MT = normalize(sRA - LST, 360);
1001// //
1002// // where "RA" is the object's Right Ascension (in degrees!). If negative,
1003// // add 360 deg to MT. If the object is the Sun, leave the time as it is,
1004// // but if it's stellar, multiply MT by 365.2422/366.2422, to convert from
1005// // sidereal to solar time. Now, compute HA for rise/set, name that
1006// // quantity HA0:
1007// //
1008// // ::sin(h0) - ::sin(lat) * ::sin(Dec)
1009// // cos(HA0) = ---------------------------------
1010// // cos(lat) * cos(Dec)
1011// //
1012// // where h0 is the altitude selected to represent rise/set. For a purely
1013// // mathematical horizon, set h0 = 0 and simplify to:
1014// //
1015// // cos(HA0) = - tan(lat) * tan(Dec)
1016// //
1017// // If you want to account for refraction on the atmosphere, set h0 = -35/60
1018// // degrees (-35 arc minutes), and if you want to compute the rise/set times
1019// // for the Sun's upper limb, set h0 = -50/60 (-50 arc minutes).
1020// //
1021// double h0 = -50/60 * DEG_RAD;
1022//
1023// double HA0 = ::acos(
1024// (sin(h0) - ::sin(fLatitude) * sin_sDec) /
1025// (cos(fLatitude) * cos(sDec*DEG_RAD)))*RAD_DEG;
1026//
1027// // When HA0 has been computed, leave it as it is for the Sun but multiply
1028// // by 365.2422/366.2422 for stellar objects, to convert from sidereal to
1029// // solar time. Finally compute:
1030// //
1031// // Rise time = MT - HA0
1032// // Set time = MT + HA0
1033// //
1034// // convert the times from degrees to hours by dividing by 15.
1035// //
1036// // If you'd like to check that your calculations are accurate or just
1037// // need a quick result, check the USNO's Sun or Moon Rise/Set Table,
1038// // <URL:http://aa.usno.navy.mil/AA/data/docs/RS_OneYear.html>.
1039//
1040// double result = MT + (rise ? -HA0 : HA0); // in degrees
1041//
1042// // Find UT midnight on this day
1043// long midnight = DAY_MS * (time / DAY_MS);
1044//
1045// return midnight + (long) (result * 3600000 / 15);
1046// }
1047
1048//-------------------------------------------------------------------------
1049// The Moon
1050//-------------------------------------------------------------------------
1051
1052#define moonL0 (318.351648 * CalendarAstronomer::PI/180 ) // Mean long. at epoch
1053#define moonP0 ( 36.340410 * CalendarAstronomer::PI/180 ) // Mean long. of perigee
1054#define moonN0 ( 318.510107 * CalendarAstronomer::PI/180 ) // Mean long. of node
1055#define moonI ( 5.145366 * CalendarAstronomer::PI/180 ) // Inclination of orbit
1056#define moonE ( 0.054900 ) // Eccentricity of orbit
1057
1058// These aren't used right now
1059#define moonA ( 3.84401e5 ) // semi-major axis (km)
1060#define moonT0 ( 0.5181 * CalendarAstronomer::PI/180 ) // Angular size at distance A
1061#define moonPi ( 0.9507 * CalendarAstronomer::PI/180 ) // Parallax at distance A
1062
1063/**
1064 * The position of the moon at the time set on this
1065 * object, in equatorial coordinates.
1066 * @internal
1067 * @deprecated ICU 2.4. This class may be removed or modified.
1068 */
1069const CalendarAstronomer::Equatorial& CalendarAstronomer::getMoonPosition()
1070{
1071 //
1072 // See page 142 of "Practial Astronomy with your Calculator",
1073 // by Peter Duffet-Smith, for details on the algorithm.
1074 //
1075 if (moonPositionSet == FALSE) {
1076 // Calculate the solar longitude. Has the side effect of
1077 // filling in "meanAnomalySun" as well.
1078 getSunLongitude();
1079
1080 //
1081 // Find the # of days since the epoch of our orbital parameters.
1082 // TODO: Convert the time of day portion into ephemeris time
1083 //
1084 double day = getJulianDay() - JD_EPOCH; // Days since epoch
1085
1086 // Calculate the mean longitude and anomaly of the moon, based on
1087 // a circular orbit. Similar to the corresponding solar calculation.
1088 double meanLongitude = norm2PI(13.1763966*PI/180*day + moonL0);
1089 meanAnomalyMoon = norm2PI(meanLongitude - 0.1114041*PI/180 * day - moonP0);
1090
1091 //
1092 // Calculate the following corrections:
1093 // Evection: the sun's gravity affects the moon's eccentricity
1094 // Annual Eqn: variation in the effect due to earth-sun distance
1095 // A3: correction factor (for ???)
1096 //
1097 double evection = 1.2739*PI/180 * ::sin(2 * (meanLongitude - sunLongitude)
1098 - meanAnomalyMoon);
1099 double annual = 0.1858*PI/180 * ::sin(meanAnomalySun);
1100 double a3 = 0.3700*PI/180 * ::sin(meanAnomalySun);
1101
1102 meanAnomalyMoon += evection - annual - a3;
1103
1104 //
1105 // More correction factors:
1106 // center equation of the center correction
1107 // a4 yet another error correction (???)
1108 //
1109 // TODO: Skip the equation of the center correction and solve Kepler's eqn?
1110 //
1111 double center = 6.2886*PI/180 * ::sin(meanAnomalyMoon);
1112 double a4 = 0.2140*PI/180 * ::sin(2 * meanAnomalyMoon);
1113
1114 // Now find the moon's corrected longitude
1115 moonLongitude = meanLongitude + evection + center - annual + a4;
1116
1117 //
1118 // And finally, find the variation, caused by the fact that the sun's
1119 // gravitational pull on the moon varies depending on which side of
1120 // the earth the moon is on
1121 //
1122 double variation = 0.6583*CalendarAstronomer::PI/180 * ::sin(2*(moonLongitude - sunLongitude));
1123
1124 moonLongitude += variation;
1125
1126 //
1127 // What we've calculated so far is the moon's longitude in the plane
1128 // of its own orbit. Now map to the ecliptic to get the latitude
1129 // and longitude. First we need to find the longitude of the ascending
1130 // node, the position on the ecliptic where it is crossed by the moon's
1131 // orbit as it crosses from the southern to the northern hemisphere.
1132 //
1133 double nodeLongitude = norm2PI(moonN0 - 0.0529539*PI/180 * day);
1134
1135 nodeLongitude -= 0.16*PI/180 * ::sin(meanAnomalySun);
1136
1137 double y = ::sin(moonLongitude - nodeLongitude);
1138 double x = cos(moonLongitude - nodeLongitude);
1139
1140 moonEclipLong = ::atan2(y*cos(moonI), x) + nodeLongitude;
1141 double moonEclipLat = ::asin(y * ::sin(moonI));
1142
1143 eclipticToEquatorial(moonPosition, moonEclipLong, moonEclipLat);
1144 moonPositionSet = TRUE;
1145 }
1146 return moonPosition;
1147}
1148
1149/**
1150 * The "age" of the moon at the time specified in this object.
1151 * This is really the angle between the
1152 * current ecliptic longitudes of the sun and the moon,
1153 * measured in radians.
1154 *
1155 * @see #getMoonPhase
1156 * @internal
1157 * @deprecated ICU 2.4. This class may be removed or modified.
1158 */
1159double CalendarAstronomer::getMoonAge() {
1160 // See page 147 of "Practial Astronomy with your Calculator",
1161 // by Peter Duffet-Smith, for details on the algorithm.
1162 //
1163 // Force the moon's position to be calculated. We're going to use
1164 // some the intermediate results cached during that calculation.
1165 //
1166 getMoonPosition();
1167
1168 return norm2PI(moonEclipLong - sunLongitude);
1169}
1170
1171/**
1172 * Calculate the phase of the moon at the time set in this object.
1173 * The returned phase is a <code>double</code> in the range
1174 * <code>0 <= phase < 1</code>, interpreted as follows:
1175 * <ul>
1176 * <li>0.00: New moon
1177 * <li>0.25: First quarter
1178 * <li>0.50: Full moon
1179 * <li>0.75: Last quarter
1180 * </ul>
1181 *
1182 * @see #getMoonAge
1183 * @internal
1184 * @deprecated ICU 2.4. This class may be removed or modified.
1185 */
1186double CalendarAstronomer::getMoonPhase() {
1187 // See page 147 of "Practial Astronomy with your Calculator",
1188 // by Peter Duffet-Smith, for details on the algorithm.
1189 return 0.5 * (1 - cos(getMoonAge()));
1190}
1191
1192/**
1193 * Constant representing a new moon.
1194 * For use with {@link #getMoonTime getMoonTime}
1195 * @internal
1196 * @deprecated ICU 2.4. This class may be removed or modified.
1197 */
1198const CalendarAstronomer::MoonAge CalendarAstronomer::NEW_MOON() {
1199 return CalendarAstronomer::MoonAge(0);
1200}
1201
1202/**
1203 * Constant representing the moon's first quarter.
1204 * For use with {@link #getMoonTime getMoonTime}
1205 * @internal
1206 * @deprecated ICU 2.4. This class may be removed or modified.
1207 */
1208/*const CalendarAstronomer::MoonAge CalendarAstronomer::FIRST_QUARTER() {
1209 return CalendarAstronomer::MoonAge(CalendarAstronomer::PI/2);
1210}*/
1211
1212/**
1213 * Constant representing a full moon.
1214 * For use with {@link #getMoonTime getMoonTime}
1215 * @internal
1216 * @deprecated ICU 2.4. This class may be removed or modified.
1217 */
1218const CalendarAstronomer::MoonAge CalendarAstronomer::FULL_MOON() {
1219 return CalendarAstronomer::MoonAge(CalendarAstronomer::PI);
1220}
1221/**
1222 * Constant representing the moon's last quarter.
1223 * For use with {@link #getMoonTime getMoonTime}
1224 * @internal
1225 * @deprecated ICU 2.4. This class may be removed or modified.
1226 */
1227
1228class MoonTimeAngleFunc : public CalendarAstronomer::AngleFunc {
1229public:
1230 virtual ~MoonTimeAngleFunc();
1231 virtual double eval(CalendarAstronomer&a) { return a.getMoonAge(); }
1232};
1233
1234MoonTimeAngleFunc::~MoonTimeAngleFunc() {}
1235
1236/*const CalendarAstronomer::MoonAge CalendarAstronomer::LAST_QUARTER() {
1237 return CalendarAstronomer::MoonAge((CalendarAstronomer::PI*3)/2);
1238}*/
1239
1240/**
1241 * Find the next or previous time at which the Moon's ecliptic
1242 * longitude will have the desired value.
1243 * <p>
1244 * @param desired The desired longitude.
1245 * @param next <tt>true</tt> if the next occurrance of the phase
1246 * is desired, <tt>false</tt> for the previous occurrance.
1247 * @internal
1248 * @deprecated ICU 2.4. This class may be removed or modified.
1249 */
1250UDate CalendarAstronomer::getMoonTime(double desired, UBool next)
1251{
1252 MoonTimeAngleFunc func;
1253 return timeOfAngle( func,
1254 desired,
1255 SYNODIC_MONTH,
1256 MINUTE_MS,
1257 next);
1258}
1259
1260/**
1261 * Find the next or previous time at which the moon will be in the
1262 * desired phase.
1263 * <p>
1264 * @param desired The desired phase of the moon.
1265 * @param next <tt>true</tt> if the next occurrance of the phase
1266 * is desired, <tt>false</tt> for the previous occurrance.
1267 * @internal
1268 * @deprecated ICU 2.4. This class may be removed or modified.
1269 */
1270UDate CalendarAstronomer::getMoonTime(const CalendarAstronomer::MoonAge& desired, UBool next) {
1271 return getMoonTime(desired.value, next);
1272}
1273
1274class MoonRiseSetCoordFunc : public CalendarAstronomer::CoordFunc {
1275public:
1276 virtual ~MoonRiseSetCoordFunc();
1277 virtual void eval(CalendarAstronomer::Equatorial& result, CalendarAstronomer&a) { result = a.getMoonPosition(); }
1278};
1279
1280MoonRiseSetCoordFunc::~MoonRiseSetCoordFunc() {}
1281
1282/**
1283 * Returns the time (GMT) of sunrise or sunset on the local date to which
1284 * this calendar is currently set.
1285 * @internal
1286 * @deprecated ICU 2.4. This class may be removed or modified.
1287 */
1288UDate CalendarAstronomer::getMoonRiseSet(UBool rise)
1289{
1290 MoonRiseSetCoordFunc func;
1291 return riseOrSet(func,
1292 rise,
1293 .533 * DEG_RAD, // Angular Diameter
1294 34 /60.0 * DEG_RAD, // Refraction correction
1295 MINUTE_MS); // Desired accuracy
1296}
1297
1298//-------------------------------------------------------------------------
1299// Interpolation methods for finding the time at which a given event occurs
1300//-------------------------------------------------------------------------
1301
1302UDate CalendarAstronomer::timeOfAngle(AngleFunc& func, double desired,
1303 double periodDays, double epsilon, UBool next)
1304{
1305 // Find the value of the function at the current time
1306 double lastAngle = func.eval(*this);
1307
1308 // Find out how far we are from the desired angle
1309 double deltaAngle = norm2PI(desired - lastAngle) ;
1310
1311 // Using the average period, estimate the next (or previous) time at
1312 // which the desired angle occurs.
1313 double deltaT = (deltaAngle + (next ? 0.0 : - CalendarAstronomer_PI2 )) * (periodDays*DAY_MS) / CalendarAstronomer_PI2;
1314
1315 double lastDeltaT = deltaT; // Liu
1316 UDate startTime = fTime; // Liu
1317
1318 setTime(fTime + uprv_ceil(deltaT));
1319
1320 // Now iterate until we get the error below epsilon. Throughout
1321 // this loop we use normPI to get values in the range -Pi to Pi,
1322 // since we're using them as correction factors rather than absolute angles.
1323 do {
1324 // Evaluate the function at the time we've estimated
1325 double angle = func.eval(*this);
1326
1327 // Find the # of milliseconds per radian at this point on the curve
1328 double factor = uprv_fabs(deltaT / normPI(angle-lastAngle));
1329
1330 // Correct the time estimate based on how far off the angle is
1331 deltaT = normPI(desired - angle) * factor;
1332
1333 // HACK:
1334 //
1335 // If abs(deltaT) begins to diverge we need to quit this loop.
1336 // This only appears to happen when attempting to locate, for
1337 // example, a new moon on the day of the new moon. E.g.:
1338 //
1339 // This result is correct:
1340 // newMoon(7508(Mon Jul 23 00:00:00 CST 1990,false))=
1341 // Sun Jul 22 10:57:41 CST 1990
1342 //
1343 // But attempting to make the same call a day earlier causes deltaT
1344 // to diverge:
1345 // CalendarAstronomer.timeOfAngle() diverging: 1.348508727575625E9 ->
1346 // 1.3649828540224032E9
1347 // newMoon(7507(Sun Jul 22 00:00:00 CST 1990,false))=
1348 // Sun Jul 08 13:56:15 CST 1990
1349 //
1350 // As a temporary solution, we catch this specific condition and
1351 // adjust our start time by one eighth period days (either forward
1352 // or backward) and try again.
1353 // Liu 11/9/00
1354 if (uprv_fabs(deltaT) > uprv_fabs(lastDeltaT)) {
1355 double delta = uprv_ceil (periodDays * DAY_MS / 8.0);
1356 setTime(startTime + (next ? delta : -delta));
1357 return timeOfAngle(func, desired, periodDays, epsilon, next);
1358 }
1359
1360 lastDeltaT = deltaT;
1361 lastAngle = angle;
1362
1363 setTime(fTime + uprv_ceil(deltaT));
1364 }
1365 while (uprv_fabs(deltaT) > epsilon);
1366
1367 return fTime;
1368}
1369
1370UDate CalendarAstronomer::riseOrSet(CoordFunc& func, UBool rise,
1371 double diameter, double refraction,
1372 double epsilon)
1373{
1374 Equatorial pos;
1375 double tanL = ::tan(fLatitude);
1376 double deltaT = 0;
1377 int32_t count = 0;
1378
1379 //
1380 // Calculate the object's position at the current time, then use that
1381 // position to calculate the time of rising or setting. The position
1382 // will be different at that time, so iterate until the error is allowable.
1383 //
1384 U_DEBUG_ASTRO_MSG(("setup rise=%s, dia=%.3lf, ref=%.3lf, eps=%.3lf\n",
1385 rise?"T":"F", diameter, refraction, epsilon));
1386 do {
1387 // See "Practical Astronomy With Your Calculator, section 33.
1388 func.eval(pos, *this);
1389 double angle = ::acos(-tanL * ::tan(pos.declination));
1390 double lst = ((rise ? CalendarAstronomer_PI2-angle : angle) + pos.ascension ) * 24 / CalendarAstronomer_PI2;
1391
1392 // Convert from LST to Universal Time.
1393 UDate newTime = lstToUT( lst );
1394
1395 deltaT = newTime - fTime;
1396 setTime(newTime);
1397 U_DEBUG_ASTRO_MSG(("%d] dT=%.3lf, angle=%.3lf, lst=%.3lf, A=%.3lf/D=%.3lf\n",
1398 count, deltaT, angle, lst, pos.ascension, pos.declination));
1399 }
1400 while (++ count < 5 && uprv_fabs(deltaT) > epsilon);
1401
1402 // Calculate the correction due to refraction and the object's angular diameter
1403 double cosD = ::cos(pos.declination);
1404 double psi = ::acos(sin(fLatitude) / cosD);
1405 double x = diameter / 2 + refraction;
1406 double y = ::asin(sin(x) / ::sin(psi));
1407 long delta = (long)((240 * y * RAD_DEG / cosD)*SECOND_MS);
1408
1409 return fTime + (rise ? -delta : delta);
1410}
1411 /**
1412 * Return the obliquity of the ecliptic (the angle between the ecliptic
1413 * and the earth's equator) at the current time. This varies due to
1414 * the precession of the earth's axis.
1415 *
1416 * @return the obliquity of the ecliptic relative to the equator,
1417 * measured in radians.
1418 */
1419double CalendarAstronomer::eclipticObliquity() {
1420 if (isINVALID(eclipObliquity)) {
1421 const double epoch = 2451545.0; // 2000 AD, January 1.5
1422
1423 double T = (getJulianDay() - epoch) / 36525;
1424
1425 eclipObliquity = 23.439292
1426 - 46.815/3600 * T
1427 - 0.0006/3600 * T*T
1428 + 0.00181/3600 * T*T*T;
1429
1430 eclipObliquity *= DEG_RAD;
1431 }
1432 return eclipObliquity;
1433}
1434
1435
1436//-------------------------------------------------------------------------
1437// Private data
1438//-------------------------------------------------------------------------
1439void CalendarAstronomer::clearCache() {
1440 const double INVALID = uprv_getNaN();
1441
1442 julianDay = INVALID;
1443 julianCentury = INVALID;
1444 sunLongitude = INVALID;
1445 meanAnomalySun = INVALID;
1446 moonLongitude = INVALID;
1447 moonEclipLong = INVALID;
1448 meanAnomalyMoon = INVALID;
1449 eclipObliquity = INVALID;
1450 siderealTime = INVALID;
1451 siderealT0 = INVALID;
1452 moonPositionSet = FALSE;
1453}
1454
1455//private static void out(String s) {
1456// System.out.println(s);
1457//}
1458
1459//private static String deg(double rad) {
1460// return Double.toString(rad * RAD_DEG);
1461//}
1462
1463//private static String hours(long ms) {
1464// return Double.toString((double)ms / HOUR_MS) + " hours";
1465//}
1466
1467/**
1468 * @internal
1469 * @deprecated ICU 2.4. This class may be removed or modified.
1470 */
1471/*UDate CalendarAstronomer::local(UDate localMillis) {
1472 // TODO - srl ?
1473 TimeZone *tz = TimeZone::createDefault();
1474 int32_t rawOffset;
1475 int32_t dstOffset;
1476 UErrorCode status = U_ZERO_ERROR;
1477 tz->getOffset(localMillis, TRUE, rawOffset, dstOffset, status);
1478 delete tz;
1479 return localMillis - rawOffset;
1480}*/
1481
1482// Debugging functions
1483UnicodeString CalendarAstronomer::Ecliptic::toString() const
1484{
1485#ifdef U_DEBUG_ASTRO
1486 char tmp[800];
1487 sprintf(tmp, "[%.5f,%.5f]", longitude*RAD_DEG, latitude*RAD_DEG);
1488 return UnicodeString(tmp, "");
1489#else
1490 return UnicodeString();
1491#endif
1492}
1493
1494UnicodeString CalendarAstronomer::Equatorial::toString() const
1495{
1496#ifdef U_DEBUG_ASTRO
1497 char tmp[400];
1498 sprintf(tmp, "%f,%f",
1499 (ascension*RAD_DEG), (declination*RAD_DEG));
1500 return UnicodeString(tmp, "");
1501#else
1502 return UnicodeString();
1503#endif
1504}
1505
1506UnicodeString CalendarAstronomer::Horizon::toString() const
1507{
1508#ifdef U_DEBUG_ASTRO
1509 char tmp[800];
1510 sprintf(tmp, "[%.5f,%.5f]", altitude*RAD_DEG, azimuth*RAD_DEG);
1511 return UnicodeString(tmp, "");
1512#else
1513 return UnicodeString();
1514#endif
1515}
1516
1517
1518// static private String radToHms(double angle) {
1519// int hrs = (int) (angle*RAD_HOUR);
1520// int min = (int)((angle*RAD_HOUR - hrs) * 60);
1521// int sec = (int)((angle*RAD_HOUR - hrs - min/60.0) * 3600);
1522
1523// return Integer.toString(hrs) + "h" + min + "m" + sec + "s";
1524// }
1525
1526// static private String radToDms(double angle) {
1527// int deg = (int) (angle*RAD_DEG);
1528// int min = (int)((angle*RAD_DEG - deg) * 60);
1529// int sec = (int)((angle*RAD_DEG - deg - min/60.0) * 3600);
1530
1531// return Integer.toString(deg) + "\u00b0" + min + "'" + sec + "\"";
1532// }
1533
1534// =============== Calendar Cache ================
1535
1536void CalendarCache::createCache(CalendarCache** cache, UErrorCode& status) {
1537 ucln_i18n_registerCleanup(UCLN_I18N_ASTRO_CALENDAR, calendar_astro_cleanup);
1538 if(cache == NULL) {
1539 status = U_MEMORY_ALLOCATION_ERROR;
1540 } else {
1541 *cache = new CalendarCache(32, status);
1542 if(U_FAILURE(status)) {
1543 delete *cache;
1544 *cache = NULL;
1545 }
1546 }
1547}
1548
1549int32_t CalendarCache::get(CalendarCache** cache, int32_t key, UErrorCode &status) {
1550 int32_t res;
1551
1552 if(U_FAILURE(status)) {
1553 return 0;
1554 }
Frank Tang69c72a62019-04-03 21:41:21 -07001555 umtx_lock(ccLock());
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00001556
1557 if(*cache == NULL) {
1558 createCache(cache, status);
1559 if(U_FAILURE(status)) {
Frank Tang69c72a62019-04-03 21:41:21 -07001560 umtx_unlock(ccLock());
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00001561 return 0;
1562 }
1563 }
1564
1565 res = uhash_igeti((*cache)->fTable, key);
1566 U_DEBUG_ASTRO_MSG(("%p: GET: [%d] == %d\n", (*cache)->fTable, key, res));
1567
Frank Tang69c72a62019-04-03 21:41:21 -07001568 umtx_unlock(ccLock());
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00001569 return res;
1570}
1571
1572void CalendarCache::put(CalendarCache** cache, int32_t key, int32_t value, UErrorCode &status) {
1573 if(U_FAILURE(status)) {
1574 return;
1575 }
Frank Tang69c72a62019-04-03 21:41:21 -07001576 umtx_lock(ccLock());
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00001577
1578 if(*cache == NULL) {
1579 createCache(cache, status);
1580 if(U_FAILURE(status)) {
Frank Tang69c72a62019-04-03 21:41:21 -07001581 umtx_unlock(ccLock());
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00001582 return;
1583 }
1584 }
1585
1586 uhash_iputi((*cache)->fTable, key, value, &status);
1587 U_DEBUG_ASTRO_MSG(("%p: PUT: [%d] := %d\n", (*cache)->fTable, key, value));
1588
Frank Tang69c72a62019-04-03 21:41:21 -07001589 umtx_unlock(ccLock());
jshin@chromium.org6f31ac32014-03-26 22:15:14 +00001590}
1591
1592CalendarCache::CalendarCache(int32_t size, UErrorCode &status) {
1593 fTable = uhash_openSize(uhash_hashLong, uhash_compareLong, NULL, size, &status);
1594 U_DEBUG_ASTRO_MSG(("%p: Opening.\n", fTable));
1595}
1596
1597CalendarCache::~CalendarCache() {
1598 if(fTable != NULL) {
1599 U_DEBUG_ASTRO_MSG(("%p: Closing.\n", fTable));
1600 uhash_close(fTable);
1601 }
1602}
1603
1604U_NAMESPACE_END
1605
1606#endif // !UCONFIG_NO_FORMATTING