-
Notifications
You must be signed in to change notification settings - Fork 2
/
Copy pathalma_ephem.py
485 lines (436 loc) · 17.1 KB
/
alma_ephem.py
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
#!/usr/bin/env python2
# -*- coding: utf-8 -*-
# Copyright (C) 2021 Andrew Bauer
# Copyright (C) 2014 Enno Rodegerdts
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License along
# with this program. If not, see <https://www.gnu.org/licenses/>.
# This contains a few functions that calculate values for the nautical almanac
# Standard library imports
import datetime
import sys
# Third party imports
import ephem # for sunrise/sunset, moonrise/moonset, planet magnitudes
# Local application imports
import config
ephem_venus = ephem.Venus()
ephem_mars = ephem.Mars()
ephem_jupiter = ephem.Jupiter()
ephem_saturn = ephem.Saturn()
#degree_sign= u'\N{DEGREE SIGN}'
#----------------------
# internal methods
#----------------------
def hhmm(date):
# turn an ephem.date (float) into a time string formatted hh:mm
tup = date.tuple()
hr = tup[-3]
# round >=30 seconds to next minute
min = tup[-2] + int(round((tup[-1]/60)+0.00001))
# nextday = False
if min == 60:
min = 0
hr += 1
if hr == 24:
hr = 0
# nextday = True # time rounded up into next day
time = '{:02d}:{:02d}'.format(hr,min) # time = "%02d:%02d" %(hr,min)
# return time, nextday
# NOTE: this function could easily return the information that rounding
# flipped into the next day, however this is not required here.
return time
def flag_msg(msg):
if config.logfileopen:
# if open - write to log file
config.writeLOG(msg + '\n')
else:
# otherwise - print to console
print(msg)
return
#------------------------------------------------
# Venus, Mars, Jupiter & Saturn calculations
#------------------------------------------------
def magnitudes(date): # used in planetstab(m)
# returns magitude for the navigational planets.
# (Skyfield 1.16 does not provide this)
obs = ephem.Observer()
#Venus
obs.date = date
ephem_venus.compute(date)
mag_venus = "{:0.1f}".format(ephem_venus.mag) # mag_venus = "%0.1f" %(ephem_venus.mag)
#Mars
obs.date = date
ephem_mars.compute(date)
mag_mars = "{:0.1f}".format(ephem_mars.mag) # mag_mars = "%0.1f" %(ephem_mars.mag)
#Jupiter
obs.date = date
ephem_jupiter.compute(date)
mag_jupiter = "{:0.1f}".format(ephem_jupiter.mag) # mag_jupiter = "%0.1f" %(ephem_jupiter.mag)
#Saturn
obs.date = date
ephem_saturn.compute(date)
mag_saturn = "{:0.1f}".format(ephem_saturn.mag) # mag_saturn = "%0.1f" %(ephem_saturn.mag)
return mag_venus,mag_mars,mag_jupiter,mag_saturn
#--------------------
# TWILIGHT table
#--------------------
def twilight(date, lat, hemisph): # used in twilighttab (section 1)
# Returns for given date and latitude(in full degrees):
# naut. and civil twilight (before sunrise), sunrise, sunset, civil and nautical twilight (after sunset).
# NOTE: 'twilight' is only called for every third day in the Full Almanac...
# ...therefore daily tracking of the sun state is not possible.
out = [0,0,0,0,0,0]
obs = ephem.Observer()
latitude = ephem.degrees('{}:00:00.0'.format(lat))
obs.lat = latitude
# first convert 'date' (a Python datetime.date) to a PyEphem date...
d = ephem.date(date) - 30 * ephem.second # search from 30 seconds before midnight
obs.date = d
obs.pressure = 0
s = ephem.Sun(obs)
s.compute(d)
r = s.radius
obs.horizon = ephem.degrees('-12')+r # Nautical twilight ...
try:
out[0] = hhmm(obs.next_rising(s)) # begin
except:
out[0] = '--:--'
obs.date = d
try:
out[5] = hhmm(obs.next_setting(s)) # end
except:
out[5] = '--:--'
if out[0] == '--:--' and out[5] == '--:--': # if neither begin nor end...
yn = midnightsun(date, hemisph)
out[0] = yn
out[5] = yn
#-----------------------------------------------------------
obs.horizon = ephem.degrees('-6')+r # Civil twilight...
obs.date = d
try:
out[1] = hhmm(obs.next_rising(s)) # begin
except:
out[1] = '--:--'
obs.date = d
try:
out[4] = hhmm(obs.next_setting(s)) # end
except:
out[4] = '--:--'
if out[1] == '--:--' and out[4] == '--:--': # if neither begin nor end...
yn = midnightsun(date, hemisph)
out[1] = yn
out[4] = yn
#-----------------------------------------------------------
obs.horizon = '-0:34'
obs.date = d
try:
out[2] = hhmm(obs.next_rising(s)) # sunrise
except:
out[2] = '--:--'
obs.date = d
try:
out[3] = hhmm(obs.next_setting(s)) # sunset
except:
out[3] = '--:--'
if out[2] == '--:--' and out[3] == '--:--': # if neither sunrise nor sunset...
yn = midnightsun(date, hemisph)
out[2] = yn
out[3] = yn
return out
def midnightsun(dt, hemisph):
# simple way to fudge whether the sun is up or down when there's no
# sunrise or sunset on date 'dt' depending on the hemisphere only.
# Note: this works for the chosen latitudes to be calculated.
sunup = False
n = dt.month
if n > 3 and n < 10: # if April to September inclusive
sunup = True
if hemisph == 'S':
sunup = not(sunup)
if sunup == True:
out = r'''\begin{tikzpicture}\draw (0,0) rectangle (12pt,4pt);\end{tikzpicture}'''
else:
out = r'''\rule{12Pt}{4Pt}'''
return out
#-------------------------
# MOONRISE/-SET table
#-------------------------
# create a list of 'moon above/below horizon' states per Latitude...
# None = unknown; True = above horizon (visible); False = below horizon (not visible)
moonvisible = [None] * 31 # moonvisible[0] up to moonvisible[30]
def moonrise_set(date, lat): # used in twilighttab (section 2)
# returns moonrise and moonset for the given date and latitude plus next 2 days:
# rise day 1, rise day 2, rise day 3, set day 1, set day 2, set day 3
# Additionally it also tracks the current state of the moon (above or below horizon)
i = config.lat.index(lat)
out = ['--:--','--:--','--:--','--:--','--:--','--:--'] # first event
out2 = ['--:--','--:--','--:--','--:--','--:--','--:--'] # second event on same day (rare)
obs = ephem.Observer()
latitude = ephem.degrees('{}:00:00.0'.format(lat))
obs.lat = latitude
obs.pressure = 0
obs.horizon = '-0:34'
# first convert 'date' (a Python datetime.date) to a PyEphem date...
d = ephem.date(date) - 30 * ephem.second # search from 30 seconds before midnight
obs.date = d
m = ephem.Moon(obs)
m.compute(d)
#-----------------------------------------------------------
# Moonrise/Moonset on 1st. day ...
try:
firstrising = obs.next_rising(m)
if firstrising-obs.date >= 1:
raise ValueError, 'event next day'
out[0] = hhmm(firstrising) # note: overflow to 00:00 next day is correct here
lastevent = firstrising
moonvisible[i] = True
except Exception: # includes NeverUpError and AlwaysUpError
out[0] = '--:--'
lastevent = 0
if out[0] != '--:--':
try:
nextr = obs.next_rising(m, start=firstrising)
if nextr-obs.date < 1:
out2[0] = hhmm(nextr) # note: overflow to 00:00 next day is correct here
lastevent = nextr
except UnboundLocalError:
pass
except ephem.NeverUpError:
pass
except ephem.AlwaysUpError:
pass
except Exception:
flag_msg("Oops! {} occured, line: {}".format(sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
obs.date = d
try:
firstsetting = obs.next_setting(m)
if firstsetting-obs.date >= 1:
raise ValueError, 'event next day'
out[3] = hhmm(firstsetting) # note: overflow to 00:00 next day is correct here
if firstsetting > lastevent:
lastevent = firstsetting
moonvisible[i] = False
except Exception: # includes NeverUpError and AlwaysUpError
out[3] = '--:--'
if out[3] != '--:--':
try:
nexts = obs.next_setting(m, start=firstsetting)
if nexts-obs.date < 1:
out2[3] = hhmm(nexts) # note: overflow to 00:00 next day is correct here
if nexts > lastevent:
moonvisible[i] = False
except UnboundLocalError:
pass
except ephem.NeverUpError:
pass
except ephem.AlwaysUpError:
pass
except Exception:
flag_msg("Oops! {} occured, line: {}".format(sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
if out[0] == '--:--' and out[3] == '--:--': # if neither moonrise nor moonset...
if moonvisible[i] == None:
getmoonstate(d, lat) # ...get moon state if unknown
out[0] = moonstate(i)
out[3] = moonstate(i)
#-----------------------------------------------------------
# Moonrise/Moonset on 2nd. day ...
d = ephem.date(date + datetime.timedelta(days=1)) - 30 * ephem.second
obs.date = d
m.compute(d)
try:
firstrising = obs.next_rising(m)
if firstrising-obs.date >= 1:
raise ValueError, 'event next day'
out[1] = hhmm(firstrising) # note: overflow to 00:00 next day is correct here
lastevent = firstrising
moonvisible[i] = True
except Exception: # includes NeverUpError and AlwaysUpError
out[1] = '--:--'
lastevent = 0
if out[1] != '--:--':
try:
nextr = obs.next_rising(m, start=firstrising)
if nextr-obs.date < 1:
out2[1] = hhmm(nextr) # note: overflow to 00:00 next day is correct here
lastevent = nextr
except UnboundLocalError:
pass
except ephem.NeverUpError:
pass
except ephem.AlwaysUpError:
pass
except Exception:
flag_msg("Oops! {} occured, line: {}".format(sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
obs.date = d
try:
firstsetting = obs.next_setting(m)
if firstsetting-obs.date >= 1:
raise ValueError, 'event next day'
out[4] = hhmm(firstsetting) # note: overflow to 00:00 next day is correct here
if firstsetting > lastevent:
lastevent = firstsetting
moonvisible[i] = False
except Exception: # includes NeverUpError and AlwaysUpError
out[4] = '--:--'
if out[4] != '--:--':
try:
nexts = obs.next_setting(m, start=firstsetting)
if nexts-obs.date < 1:
out2[4] = hhmm(nexts) # note: overflow to 00:00 next day is correct here
if nexts > lastevent:
moonvisible[i] = False
except UnboundLocalError:
pass
except ephem.NeverUpError:
pass
except ephem.AlwaysUpError:
pass
except Exception:
flag_msg("Oops! {} occured, line: {}".format(sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
if out[1] == '--:--' and out[4] == '--:--': # if neither moonrise nor moonset...
if moonvisible[i] == None:
getmoonstate(d, lat) # ...get moon state if unknown
out[1] = moonstate(i)
out[4] = moonstate(i)
#-----------------------------------------------------------
# Moonrise/Moonset on 3rd. day ...
d = ephem.date(date + datetime.timedelta(days=2)) - 30 * ephem.second
obs.date = d
m.compute(d)
try:
firstrising = obs.next_rising(m)
if firstrising-obs.date >= 1:
raise ValueError, 'event next day'
out[2] = hhmm(firstrising) # note: overflow to 00:00 next day is correct here
lastevent = firstrising
moonvisible[i] = True
except Exception: # includes NeverUpError and AlwaysUpError
out[2] = '--:--'
lastevent = 0
if out[2] != '--:--':
try:
nextr = obs.next_rising(m, start=firstrising)
if nextr-obs.date < 1:
out2[2] = hhmm(nextr) # note: overflow to 00:00 next day is correct here
lastevent = nextr
except UnboundLocalError:
pass
except ephem.NeverUpError:
pass
except ephem.AlwaysUpError:
pass
except Exception:
flag_msg("Oops! {} occured, line: {}".format(sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
obs.date = d
try:
firstsetting = obs.next_setting(m)
if firstsetting-obs.date >= 1:
raise ValueError, 'event next day'
out[5] = hhmm(firstsetting) # note: overflow to 00:00 next day is correct here
if firstsetting > lastevent:
lastevent = firstsetting
moonvisible[i] = False
except Exception: # includes NeverUpError and AlwaysUpError
out[5] = '--:--'
if out[5] != '--:--':
try:
nexts = obs.next_setting(m, start=firstsetting)
if nexts-obs.date < 1:
out2[5] = hhmm(nexts) # note: overflow to 00:00 next day is correct here
if nexts > lastevent:
moonvisible[i] = False
except UnboundLocalError:
pass
except ephem.NeverUpError:
pass
except ephem.AlwaysUpError:
pass
except Exception:
flag_msg("Oops! {} occured, line: {}".format(sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
if out[2] == '--:--' and out[5] == '--:--': # if neither moonrise nor moonset...
if moonvisible[i] == None:
getmoonstate(d, lat) # ...get moon state if unknown
out[2] = moonstate(i)
out[5] = moonstate(i)
return out, out2
def moonstate(ndx):
# return the current moonstate (if known)
out = '--:--'
if moonvisible[ndx] == True:
#out = 'UP'
#out = r'''\framebox(12,4){}'''
#out = r'''{\setlength{\fboxrule}{0.8pt}\setlength{\fboxsep}{0pt}\fbox{\makebox(12,4){}}}'''
#out = r'''{\setlength{\fboxrule}{0.8pt}\fbox{\parbox[c][0pt]{0pt}{ }}}'''
#out = r'''\includegraphics[scale=1.0]{./moonup.jpg}'''
out = r'''\begin{tikzpicture}\draw (0,0) rectangle (12pt,4pt);\end{tikzpicture}'''
if moonvisible[ndx] == False:
#out = 'DOWN'
out = r'''\rule{12Pt}{4Pt}'''
return out
def getmoonstate(d, lat):
# populate the moon state (visible or not) for the specified date & latitude
# note: the first parameter 'd' is already an ephem date 30 seconds before midnight
# note: getmoonstate is called when there is neither a moonrise nor a moonset on 'd'
i = config.lat.index(lat)
latitude = ephem.degrees('{}:00:00.0'.format(lat))
obs = ephem.Observer()
#d = ephem.date(date) - 30 * ephem.second
obs.pressure = 0
obs.horizon = '-0:34'
m = ephem.Moon(obs)
err = False
obs.date = d
obs.lat = latitude
m.compute(d)
nextrising = d + 100.0 # in case moonset but no next moonrise
nextsetting = d + 100.0 # in case moonrise but no next moonset
try:
nextrising = obs.next_rising(m)
except ephem.NeverUpError:
err = True
#print "nr NeverUp"
moonvisible[i] = False
except ephem.AlwaysUpError:
err = True
#print "nr AlwaysUp"
moonvisible[i] = True
except Exception:
flag_msg("Oops! moon nextR {}: {} occured, line: {}".format(i,sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
obs.date = d
if not(err): # note - 'nextrising' above *should* fail
try:
nextsetting = obs.next_setting(m)
except ephem.NeverUpError:
err = True
#print "ns NeverUp"
moonvisible[i] = False
except ephem.AlwaysUpError:
err = True
#print "ns AlwaysUp"
moonvisible[i] = True
except Exception:
flag_msg("Oops! moon nextS {}: {} occured, line: {}".format(i,sys.exc_info()[1],sys.exc_info()[2].tb_lineno))
sys.exc_clear() # only in Python 2
if not(err): # note - "err == True" *is* expected...
# however if we found both, which occured first?
moonvisible[i] = False
if nextrising > nextsetting:
moonvisible[i] = True
#print("{}".format(i), nextrising, nextsetting, moonvisible[i])
return