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