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