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