summaryrefslogtreecommitdiff
path: root/lisp/calendar/solar.el
blob: 139ec0d16b8d0d26e2b6139986e736e14153be14 (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
;;; solar.el --- calendar functions for solar events.

;; Copyright (C) 1992 Free Software Foundation, Inc.

;; Author: Edward M. Reingold <reingold@cs.uiuc.edu>
;; Keywords: calendar
;; Human-Keywords: sunrise, sunset, equinox, solstice, calendar, diary,
;;	holidays

;; This file is part of GNU Emacs.

;; GNU Emacs is distributed in the hope that it will be useful,
;; but WITHOUT ANY WARRANTY.  No author or distributor
;; accepts responsibility to anyone for the consequences of using it
;; or for whether it serves any particular purpose or works at all,
;; unless he says so in writing.  Refer to the GNU Emacs General Public
;; License for full details.

;; Everyone is granted permission to copy, modify and redistribute
;; GNU Emacs, but only under the conditions described in the
;; GNU Emacs General Public License.   A copy of this license is
;; supposed to have been given to you along with GNU Emacs so you
;; can know your rights and responsibilities.  It should be in a
;; file named COPYING.  Among other things, the copyright notice
;; and this notice must be preserved on all copies.

;;; Commentary:

;; This collection of functions implements the features of calendar.el and
;; diary.el that deal with times of day, sunrise/sunset, and
;; eqinoxes/solstices.

;; Based on the ``Almanac for Computers 1984,'' prepared by the Nautical
;; Almanac Office, United States Naval Observatory, Washington, 1984 and
;; on ``Astronomical Formulae for Calculators,'' 3rd ed., by Jean Meeus,
;; Willmann-Bell, Inc., 1985.
;;
;; WARNINGS:
;;    1. SUNRISE/SUNSET calculations will be accurate only to +/- 2 minutes.
;;       Locations should be between +/- 65 degrees of latitude.
;;       Dates should be in the latter half of the 20th century.
;;
;;    2. Equinox/solstice times will be accurate only to +/- 15 minutes.

;; The author would be delighted to have an astronomically more sophisticated
;; person rewrite the code for the solar calculations in this file!

;; Comments, corrections, and improvements should be sent to
;;  Edward M. Reingold               Department of Computer Science
;;  (217) 333-6733                   University of Illinois at Urbana-Champaign
;;  reingold@cs.uiuc.edu             1304 West Springfield Avenue
;;                                   Urbana, Illinois 61801

;;; Code:

(if (fboundp 'atan)
    (require 'lisp-float-type)
  (error "Solar calculations impossible since floating point is unavailable."))

(require 'cal-dst)

;;;###autoload
(defvar calendar-time-display-form
  '(12-hours ":" minutes am-pm
    (if time-zone " (") time-zone (if time-zone ")"))
  "*The pseudo-pattern that governs the way a time of day is formatted.

A pseudo-pattern is a list of expressions that can involve the keywords
`12-hours', `24-hours', and `minutes',  all numbers in string form,
and `am-pm' and `time-zone',  both alphabetic strings.

For example, the form

  '(24-hours \":\" minutes
    (if time-zone \" (\") time-zone (if time-zone \")\"))

would give military-style times like `21:07 (UTC)'.")

;;;###autoload
(defvar calendar-latitude nil
  "*Latitude of `calendar-location-name' in degrees, + north, - south.
For example, 40.7 for New York City.")

;;;###autoload
(defvar calendar-longitude nil
  "*Longitude of `calendar-location-name' in degrees, + east, - west.
For example, -74.0 for New York City.")

;;;###autoload
(defvar calendar-location-name
  '(let ((float-output-format "%.1f"))
     (format "%s%s, %s%s"
	     (abs calendar-latitude)
	     (if (> calendar-latitude 0) "N" "S")
	     (abs calendar-longitude)
	     (if (> calendar-longitude 0) "E" "W")))
  "*Expression evaluating to name of `calendar-longitude', calendar-latitude'.
Default value is just the latitude, longitude pair.")

(defun solar-setup ()
  "Prompt user for latitude, longitude, and time zone."
  (beep)
  (if (not calendar-longitude)
      (setq calendar-longitude
            (solar-get-number
             "Enter longitude (decimal fraction; + east, - west): ")))
  (if (not calendar-latitude)
      (setq calendar-latitude
            (solar-get-number
             "Enter latitude (decimal fraction; + north, - south): ")))
  (if (not calendar-time-zone)
      (setq calendar-time-zone
            (solar-get-number
             "Enter difference from Coordinated Universal Time (in minutes): "))))

(defun solar-get-number (prompt)
  "Return a number from the minibuffer, prompting with PROMPT.
Returns nil if nothing was entered."
  (let ((x (read-string prompt "")))
    (if (not (string-equal x ""))
        (string-to-int x))))

(defun solar-sin-degrees (x)
  (sin (degrees-to-radians x)))

(defun solar-cosine-degrees (x)
  (cos (degrees-to-radians x)))

(defun solar-tangent-degrees (x)
  (tan (degrees-to-radians x)))

(defun solar-xy-to-quadrant (x y)
  "Determines the quadrant of the point X, Y."
  (if (> x 0)
      (if (> y 0) 1 4)
      (if (> y 0) 2 3)))

(defun solar-degrees-to-quadrant (angle)
  "Determines the quadrant of ANGLE."
  (1+ (truncate (/ (solar-mod angle 360.0) 90.0))))

(defun solar-arctan (x quad)
  "Arctangent of X in quadrant QUAD."
  (let ((deg (radians-to-degrees (atan x))))
    (cond ((equal quad 2)   (+ deg 180))
	  ((equal quad 3)   (+ deg 180))
	  ((equal quad 4)   (+ deg 360))
	  (t                deg))))

(defun solar-arccos (x)
  (let ((y (sqrt (- 1 (* x x)))))
    (solar-arctan (/ y x) (solar-xy-to-quadrant x y))))

(defun solar-arcsin (y)
  (let ((x (sqrt (- 1 (* y y)))))
    (solar-arctan (/ y x) (solar-xy-to-quadrant x y))))

(defun solar-mod (x y)
  "Returns X mod Y; value is *always* non-negative."
  (let ((v (% x y)))
    (if (> 0 v)
	(+ v y)
      v)))

(defconst solar-earth-inclination 23.441884 
  "Inclination of earth's equator to its solar orbit in degrees.")

(defconst solar-cos-inclination (solar-cosine-degrees solar-earth-inclination) 
  "Cosine of earth's inclination.")

(defconst solar-sin-inclination (solar-sin-degrees solar-earth-inclination)
  "Sine of earth's inclination.")

(defconst solar-earth-orbit-eccentricity 0.016718
  "Eccentricity of orbit of the earth around the sun.")

(defmacro solar-degrees-to-hours (deg)
  (list '/ deg 15))

(defmacro solar-hours-to-days (hour)
  (list '/ hour 24))

(defun solar-longitude-of-sun (day)
  "Longitude of the sun at DAY in the year."
  (let ((mean-anomaly (- (* 0.9856 day) 3.289)))
    (solar-mod (+ mean-anomaly 
		  (* 1.916 (solar-sin-degrees mean-anomaly))
		  (* 0.020 (solar-sin-degrees (* 2 mean-anomaly)))
		  282.634)
	       360)))

(defun solar-right-ascension (longitude)
  "Right ascension of the sun, given its LONGITUDE."
  (solar-degrees-to-hours
   (solar-arctan
    (* solar-cos-inclination (solar-tangent-degrees longitude))
    (solar-degrees-to-quadrant longitude))))

(defun solar-declination (longitude)
  "Declination of the sun, given its LONGITUDE."
  (solar-arcsin
   (* solar-sin-inclination
      (solar-sin-degrees longitude))))

(defun solar-sunrise (date)
  "Calculates the *standard* time of sunrise for Gregorian DATE for location
given by `calendar-latitude' and `calendar-longitude'.  Returns a decimal fraction
of hours.  Returns nil if the sun does not rise at that location on that day."
  (let* ((day-of-year (calendar-day-number date))
	 (approx-sunrise
          (+ day-of-year
             (solar-hours-to-days
              (-  6 (solar-degrees-to-hours calendar-longitude)))))
	 (solar-longitude-of-sun-at-sunrise
          (solar-longitude-of-sun approx-sunrise))
	 (solar-right-ascension-at-sunrise
          (solar-right-ascension solar-longitude-of-sun-at-sunrise))
	 (solar-declination-at-sunrise
          (solar-declination solar-longitude-of-sun-at-sunrise))
	 (cos-local-sunrise
          (/ (- (solar-cosine-degrees (+ 90 (/ 50.0 60.0)))
                (* (solar-sin-degrees solar-declination-at-sunrise)
                   (solar-sin-degrees calendar-latitude)))
             (* (solar-cosine-degrees solar-declination-at-sunrise)
                (solar-cosine-degrees calendar-latitude)))))
    (if (<= (abs cos-local-sunrise) 1);; otherwise, no sunrise that day
      (let* ((local-sunrise (solar-degrees-to-hours
                             (- 360 (solar-arccos cos-local-sunrise))))
             (local-mean-sunrise
	      (solar-mod (- (+ local-sunrise solar-right-ascension-at-sunrise)
			    (+ (* 0.065710 approx-sunrise)
			       6.622))
			 24)))
	(+ (- local-mean-sunrise (solar-degrees-to-hours calendar-longitude))
	   (/ calendar-time-zone 60.0))))))

(defun solar-sunset (date)
  "Calculates the *standard* time of sunset for Gregorian DATE for location
given by `calendar-latitude' and `calendar-longitude'.  Returns a decimal fractions
of hours.  Returns nil if the sun does not set at that location on that day."
  (let* ((day-of-year (calendar-day-number date))
	 (approx-sunset
          (+ day-of-year
             (solar-hours-to-days
              (- 18 (solar-degrees-to-hours calendar-longitude)))))
	 (solar-longitude-of-sun-at-sunset
          (solar-longitude-of-sun approx-sunset))
	 (solar-right-ascension-at-sunset
          (solar-right-ascension solar-longitude-of-sun-at-sunset))
	 (solar-declination-at-sunset
          (solar-declination solar-longitude-of-sun-at-sunset))
	 (cos-local-sunset
          (/ (- (solar-cosine-degrees (+ 90 (/ 50.0 60.0)))
                (* (solar-sin-degrees solar-declination-at-sunset)
                   (solar-sin-degrees calendar-latitude)))
             (* (solar-cosine-degrees solar-declination-at-sunset)
                (solar-cosine-degrees calendar-latitude)))))
    (if (<= (abs cos-local-sunset) 1);; otherwise, no sunset that day
      (let* ((local-sunset (solar-degrees-to-hours
                            (solar-arccos cos-local-sunset)))
             (local-mean-sunset
	      (solar-mod (- (+ local-sunset solar-right-ascension-at-sunset)
			    (+ (* 0.065710 approx-sunset) 6.622))
			 24)))
	(+ (- local-mean-sunset (solar-degrees-to-hours calendar-longitude))
	   (/ calendar-time-zone 60.0))))))

(defun solar-time-string (time date &optional style)
  "Printable form for decimal fraction *standard* TIME on DATE.
Optional parameter STYLE forces the time to be standard time when its value
is 'standard and daylight savings time (if available) when its value is
'daylight.

Format used is given by `calendar-time-display-form'.  Converted to daylight
savings time according to `calendar-daylight-savings-starts',
`calendar-daylight-savings-ends', `calendar-daylight-switchover-time', and
`calendar-daylight-savings-offset'."
  (let* ((year (extract-calendar-year date))
	 (time (round (* 60 time)))
	 (rounded-abs-date (+ (calendar-absolute-from-gregorian date)
			      (/ time 60.0 24.0)))
         (dst-starts (and calendar-daylight-savings-starts
                          (+ (calendar-absolute-from-gregorian
                              (eval calendar-daylight-savings-starts))
			     (/ calendar-daylight-savings-switchover-time
				60.0 24.0))))
         (dst-ends (and calendar-daylight-savings-ends
                        (+ (calendar-absolute-from-gregorian
                            (eval calendar-daylight-savings-ends))
			   (/ (- calendar-daylight-savings-switchover-time
				 calendar-daylight-time-offset)
			      60.0 24.0))))
	 (dst (and (not (eq style 'standard))
                   (or (eq style 'daylight)
                       (and dst-starts dst-ends
                            (or (and (< dst-starts dst-ends);; northern hemi.
                                     (<= dst-starts rounded-abs-date)
                                     (< rounded-abs-date dst-ends))
                                (and (< dst-ends dst-starts);; southern hemi.
                                     (or (< rounded-abs-date dst-ends)
                                         (<= dst-starts rounded-abs-date)))))
                       (and dst-starts (not dst-ends)
                            (<= dst-starts rounded-abs-date))
                       (and dst-ends (not dst-starts)
                            (< rounded-abs-date dst-ends)))))
	 (time-zone (if dst
			calendar-daylight-time-zone-name
			calendar-standard-time-zone-name))
	 (time (+ time (if dst calendar-daylight-time-offset 0)))
	 (24-hours (/ time 60))
	 (minutes (format "%02d" (% time 60)))
	 (12-hours (format "%d" (1+ (% (+ 24-hours 11) 12))))
	 (am-pm (if (>= 24-hours 12) "pm" "am"))
	 (24-hours (format "%02d" 24-hours)))
    (mapconcat 'eval calendar-time-display-form "")))

(defun solar-sunrise-sunset (date)
  "String giving local times of sunrise and sunset on Gregorian DATE."
  (let ((rise (solar-sunrise date))
	(set (solar-sunset date)))
    (format "%s, %s at %s"
	    (if rise
		(concat "Sunrise " (solar-time-string rise date))
	      "No sunrise")
	    (if set
		(concat "sunset " (solar-time-string set date))
	      "no sunset")
	    (eval calendar-location-name))))

(defun solar-apparent-longitude-of-sun (date)
  "Apparent longitude of the sun on Gregorian DATE."
  (let* ((time (/ (- (calendar-absolute-from-gregorian date) 
		     (calendar-absolute-from-gregorian '(1 0.5 1900)))
		  36525))
	 (l (+ 279.69668
	       (* 36000.76892 time)
	       (* 0.0003025 time time)))
	 (m (+ 358.47583
	       (* 35999.04975 time)
	       (* -0.000150 time time)
	       (* -0.0000033 time time time)))
	 (c (+ (* (+ 1.919460
		     (* -0.004789 time)
		     (* -0.000014 time time))
		  (solar-sin-degrees m))
	       (* (+ 0.020094
		     (* -0.000100 time))
		  (solar-sin-degrees (* 2 m)))
	       (* 0.000293
		  (solar-sin-degrees (* 3 m)))))
	 (L (+ l c))
	 (omega (+ 259.18
		   (* -1934.142 time)))
	 (app (+ L
		 -0.00569
		 (* -0.00479
		    (solar-sin-degrees omega)))))
    app))

(defun solar-ephemeris-correction (year)
  "Difference in minutes between Ephemeris time and UTC in YEAR.
Value is only an approximation."
  (let ((T (/ (- year 1900) 100.0)))
    (+ 0.41 (* 1.2053 T) (* 0.4992 T T))))

(defun solar-equinoxes/solstices (k year)
  "Date of equinox/solstice K for YEAR.  K=0, spring equinox; K=1, summer
solstice; K=2, fall equinox; K=3, winter solstice.  Accurate to within
several minutes."
  (let ((date (list (+ 3 (* k 3)) 21 year))
        app
	(correction 1000))
    (while (> correction 0.00001)
      (setq app (solar-mod (solar-apparent-longitude-of-sun date) 360.0))
      (setq correction (* 58 (solar-sin-degrees (- (* k 90) app))))
      (setq date (list (extract-calendar-month date)
		       (+ (extract-calendar-day date) correction)
		       year)))
    (list (extract-calendar-month date)
          (+ (extract-calendar-day date) (/ calendar-time-zone 60.0 24.0)
             (- (/ (solar-ephemeris-correction year) 60.0 24.0)))
          year)))

;;;###autoload
(defun sunrise-sunset (&optional arg)
  "Local time of sunrise and sunset for today.  Accurate to +/- 2 minutes.
If called with an optional prefix argument, prompts for date.

If called with an optional double prefix argument, prompts for longitude,
latitude, time zone, and date.

This function is suitable for execution in a .emacs file."
 (interactive "p")
 (if (and (< arg 16)
          (not (and calendar-latitude calendar-longitude calendar-time-zone)))
     (solar-setup))
 (let* ((calendar-longitude
         (if (< arg 16) calendar-longitude
           (solar-get-number
            "Enter longitude (decimal fraction; + east, - west): ")))
        (calendar-latitude
         (if (< arg 16) calendar-latitude
           (solar-get-number
            "Enter latitude (decimal fraction; + north, - south): ")))
        (calendar-time-zone
         (if (< arg 16) calendar-time-zone
           (solar-get-number
            "Enter difference from Coordinated Universal Time (in minutes): ")))
        (calendar-location-name
         (if (< arg 16) calendar-location-name
           (let ((float-output-format "%.1f"))
             (format "%s%s, %s%s"
                     (abs calendar-latitude)
                     (if (> calendar-latitude 0) "N" "S")
                     (abs calendar-longitude)
                     (if (> calendar-longitude 0) "E" "W")))))
        (calendar-standard-time-zone-name
         (if (< arg 16) calendar-standard-time-zone-name
           (cond ((= calendar-time-zone 0) "UTC")
                 ((< calendar-time-zone 0)
                     (format "UTC%dmin" calendar-time-zone))
                 (t  (format "UTC+%dmin" calendar-time-zone)))))
        (calendar-daylight-savings-starts
         (if (< arg 16) calendar-daylight-savings-starts))
        (calendar-daylight-savings-ends
         (if (< arg 16) calendar-daylight-savings-ends))
        (date (if (< arg 4) (calendar-current-date) (calendar-read-date)))
        (date-string (calendar-date-string date t))
        (time-string (solar-sunrise-sunset date))
        (msg (format "%s: %s" date-string time-string))
        (one-window (one-window-p t)))
   (if (<= (length msg) (screen-width))
       (message msg)
     (with-output-to-temp-buffer "*temp*"
       (princ (concat date-string "\n" time-string)))
     (message (substitute-command-keys
               (if one-window
                   (if pop-up-windows
                       "Type \\[delete-other-windows] to remove temp window."
                     "Type \\[switch-to-buffer] RET to remove temp window.")
                 "Type \\[switch-to-buffer-other-window] RET to restore old contents of temp window."))))))
 
(defun calendar-sunrise-sunset ()
  "Local time of sunrise and sunset for date under cursor.
Accurate to +/- 2 minutes."
  (interactive)
  (if (not (and calendar-latitude calendar-longitude calendar-time-zone))
      (solar-setup))
  (message
   (solar-sunrise-sunset
    (or (calendar-cursor-to-date)
	(error "Cursor is not on a date!")))))

(defun diary-sunrise-sunset ()
  "Local time of sunrise and sunset as a diary entry.
Accurate to +/- 2 minutes."
  (if (not (and calendar-latitude calendar-longitude calendar-time-zone))
      (solar-setup))
  (solar-sunrise-sunset date))

(defun diary-sabbath-candles ()
  "Local time of candle lighting diary entry--applies if date is a Friday.
No diary entry if there is no sunset on that date."
  (if (not (and calendar-latitude calendar-longitude calendar-time-zone))
      (solar-setup))
  (if (= (% (calendar-absolute-from-gregorian date) 7) 5);;  Friday
      (let* ((sunset (solar-sunset date))
	     (light (if sunset (- sunset (/ 18.0 60.0)))))
        (if light (format "%s Sabbath candle lighting"
                          (solar-time-string light date))))))

(defun solar-equinoxes-solstices ()
  "Date and time of equinoxes and solstices, if visible in the calendar window.
Requires floating point."
  (let ((m displayed-month)
        (y displayed-year))
    (increment-calendar-month m y (cond ((= 1 (% m 3)) -1)
					((= 2 (% m 3))  1)
					(t              0)))
    (let* ((calendar-standard-time-zone-name
            (if calendar-time-zone calendar-standard-time-zone-name "UTC"))
           (calendar-daylight-savings-starts
            (if calendar-time-zone calendar-daylight-savings-starts))
           (calendar-daylight-savings-ends
            (if calendar-time-zone calendar-daylight-savings-ends))
           (calendar-time-zone (if calendar-time-zone calendar-time-zone 0))
           (k (1- (/ m 3)))
	   (date (solar-equinoxes/solstices k y))
	   (day (extract-calendar-day date))
	   (time (* 24 (- day (truncate day))))
           ;; Time zone/DST can't move the date out of range,
           ;; so let solar-time-string do the conversion.
	   (date (list (extract-calendar-month date)
		       (truncate day)
		       (extract-calendar-year date))))
      (list (list date
		  (format "%s %s"
			  (cond ((= k 0)  "Vernal Equinox")
				((= k 1)  "Summer Solstice")
				((= k 2)  "Fall Equinox")
				((= k 3)  "Winter Solstice"))
			  (solar-time-string time date)))))))

(provide 'solar)

;;; solar.el ends here