Search code examples
python-3.xpyephem

PyEphem: How to test if an object is above the horizon?


I am writing a Python script that gives basic data for all the planets, the Sun and the Moon. My first function divides the planets between those that are above the horizon, and those that are not risen yet:

planets = {
    'mercury': ephem.Mercury(),
    'venus': ephem.Venus(),
    'mars': ephem.Mars(),
    'jupiter': ephem.Jupiter(),
    'saturn': ephem.Saturn(),
    'uranus': ephem.Uranus(),
    'neptune': ephem.Neptune()
}

def findVisiblePlanets(obs):
    visiblePlanets = dict()
    notVisiblePlanets = dict()
    for obj in planets:
        planets[obj].compute(obs)
        if planets[obj].alt > 0:
            visiblePlanets[obj] = planets[obj]
        else:
            notVisiblePlanets[obj] = planets[obj] 
    return (visiblePlanets, notVisiblePlanets)

This works alright, the tuple I receive from findVisiblePlanets corresponds corresponds to the actual sky for the given 'obs'.

But in another function, I need to test the altitude of each planet. If it's above 0, the script displays 'setting at xxx', and if it's under 0, the script displays 'rising at xxx'. Here is the code:

if bodies[obj].alt > 0:
    print(' Sets at', setTime.strftime('%H:%M:%S'), deltaSet)
else:
    print(' Rises at', riseTime.strftime('%H:%M:%S'), deltaRise)

So I'm using the exact same condition, except that this time it doesn't work. I am sure I have the correct object behind bodies[obj], as the script displays name, magnitude, distance, etc. But for some reason, the altitude (.alt) is always below 0, so the script only displays the rising time.

I tried print(bodies[obj].alt), and I receive a negative figure in the form of '-0:00:07.8' (example). I tried using int(bodies[obj].alt) for the comparison but this ends up being a 0. How can I test if the altitude is negative? Am I missing something obvious here?

Thanks for your help.


Solution

  • I thinkk I had a similar problem once. How I understand it pyephem forwards the time of your observer, when you call nextrising() or nextsetting() on a object. It somehow looks, at which timepoint the object is above/below the horizont for the first time. if you then call the bodie.alt it will always be this little bit below/above horizon.

    You have to store your observer time somehow and set it again after calculating setting/rising times.