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