PyEphem Documentation

repository·master·Indexed 21 days ago

https://github.com/brandon-rhodes/pyephem

A high-precision astronomy computation library for Python that uses C-based numeric routines from XEphem. It provides tools to calculate the positions of planets, moons, stars, and satellites, as well as observer-specific astronomical events. The library includes specialized types for handling astronomical angles (ephem.Angle), dates (ephem.Date), and coordinate systems (Equatorial, Ecliptic, and Galactic), along with utilities for processing Two-Line Element (TLE) data for satellites.

Tokens
16.7K
Snippets
63
Records
76
Agent score
74%

What's inside PyEphem

  1. Core features of PyEphem

    master

    PyEphem is a high-precision astronomy library that provides the following capabilities:

    • Celestial Body Tracking: High-precision orbital routines for the Moon, Sun, planets, and major moons. Supports custom orbital elements for comets, asteroids, or satellites.
    • Star Positions: Built-in positions for 94 bright stars.
    • Observer Location: Support for custom longitude, latitude, and altitude, or using a built-in database of 122 world cities. Includes atmospheric refraction compensation based on temperature and pressure.
    • Event Computation: Calculate when a body will rise, transit overhead, or set. Also computes equinoxes, solstices, and Moon phases.
    • Data Parsing: Parses XEphem file formats and standard TLE (Two-Line Element) formats for satellites.
    • Coordinate Conversions: Converts positions between equatorial, ecliptic, and galactic coordinate systems.
    • Time Conversions: Converts Ephemeris Time to local time and returns Julian Dates for any calendar date.
  2. Work with angles as floats and strings

    master

    PyEphem angles behave differently depending on how they are accessed:

    • As strings: When printed or passed to str(), they appear in human-readable astronomical formats (e.g., 22:04:47.4).
    • As floats: In mathematical operations, they act as standard Python floating-point numbers representing radians.

    Key Conversion Functions:

    • ephem.degrees(angle): Converts a radian float back into a printable degree string.
    • ephem.hours(angle): Converts a radian float back into a printable hours string (used for right ascension).
    • .norm: An attribute on an angle object that forces the value into the range of 0 to 2π.

    Setting Angles:

    • If you pass a string, it is interpreted as degrees (or hours for right ascension).
    • If you pass a float, it is interpreted as radians.
    import ephem
    
    u = ephem.Uranus('1871/3/13')
    
    # Access as string
    print(str(u.dec)) # '22:04:47.4'
    
    # Access as float (radians)
    print(float(u.dec)) # 0.385365877213
    
    # Convert math results back to printable degrees
    angle_result = 0.385365877213 + 1
    print(ephem.degrees(angle_result)) # '1:16:10.5'
  3. Important: The compute() method mutates in-place

    master
    The .compute() method mutates the object it is called on rather than returning a new object. Because it returns None, you cannot use it directly inside list comprehensions (e.g., [obj.compute(obs) for obj in objects] will result in a list of None values).
  4. Understand the ephem.Date type

    master

    PyEphem uses the ephem.Date type to represent dates and times. Internally, an ephem.Date is a subclass of the Python float, which allows for high precision in astronomical routines by avoiding the rounding errors that can occur when converting to Python's native datetime type.

    Key characteristics:

    • It behaves like a float (e.g., isinstance(d, float) is True).
    • It displays itself as a formatted date string when printed or converted via str().
    • It uses the modern Gregorian calendar by default, but automatically switches to the Julian calendar for dates prior to the Gregorian transition (e.g., around 1582).
    import ephem
    d = ephem.Date('1984/05/30 16:23:45.12')
    print(d)  # Output: 1984/5/30 16:23:45
    print(isinstance(d, float))  # Output: True
  5. Understand PyEphem coordinate systems and classes

    master

    PyEphem supports three main coordinate systems through specific classes. Each class instance contains three attributes: a primary angle, a secondary angle, and an epoch.

    SystemClassPrimary AttributeSecondary Attribute
    EquatorialEquatorialra (right ascension)dec (declination)
    EclipticEclipticlon (longitude)lat (latitude)
    GalacticGalacticlon (longitude)lat (latitude)

    To retrieve the angles as a tuple, use the .get() method, which returns the values in the order (primary, secondary).

  6. Work with Angles in degrees and hours

    master

    Many Body and Observer attributes return values as Angle objects.

    Key Characteristics:

    • Storage: Angles always store floating-point radians internally.
    • Behavior: They act like Python float objects for mathematical operations.
    • Display: They only display as degrees or hours when printed or formatted as strings.
    • Units: Most angles are in degrees, but Right Ascension is measured in hours.

    Creation and Conversion: Use ephem.degrees() for degree-based angles and ephem.hours() for hour-based angles (Right Ascension). You can provide radians, strings (e.g., '180:00:00', '5:37:30'), or floats to these functions.

    Normalization: When performing math that might push an angle out of standard bounds, use:

    • .norm: Returns the angle normalized to $[0, 2\pi)$.
    • .znorm: Returns the angle normalized to $[-\pi, \pi)$.
    >>> a = ephem.degrees(3.141593)  # float: radians
    >>> print(a)
    180:00:00.1
    >>> a = ephem.degrees('180:00:00')  # str: degrees
    >>> print(a)
    180:00:00.0
    >>> a
    3.141592653589793
    >>> h = ephem.hours('1:00:00')
    >>> deg = ephem.degrees(h)
    >>> print("1h right ascension = %s degrees" % deg)
    1h right ascension = 15:00:00.0 degrees
  7. Important: Angular units and math in PyEphem

    master

    PyEphem has specific behaviors regarding angular units that can cause confusion:

    1. Input Parsing: A string input like '1.23' is parsed as degrees (or hours for Right Ascension), but a float input like 1.23 is assumed to be in radians.
    2. Output/Math Discrepancy: When you print() an angle (like mars.az), it displays in degrees. However, when you perform mathematical operations on that same value, it behaves as radians. To force a value to be treated as a float for math, you can add 0.0 (e.g., mars.az + 0.0).
    # Example of the printing vs math behavior
    print(mars.az)         # Displays in degrees
    print(mars.az + 0.0)   # Performs math in radians
  8. Understand the three coordinate sets returned by PyEphem bodies

    master

    Every PyEphem "body" (planets, comets, asteroids, stars, etc.) returns three distinct sets of Right Ascension (RA) and Declination (Dec) coordinates. The specific set you should use depends on whether you are comparing positions to a star atlas or looking at the sky from a specific location on Earth.

    For General Celestial Bodies

    • a_ra, a_dec: Astrometric Geocentric Position. Use these for matching positions to a star atlas for a specific epoch.
    • g_ra, g_dec: Apparent Geocentric Position. The position for the epoch-of-date, adjusted for light-travel time and relativistic effects, but viewed from the center of the Earth.
    • ra, dec: Apparent Topocentric Position. The position as it appears from a specific location on Earth's surface. Note: This is only computed if you provide an Observer to the compute() method. If no Observer is provided, ra/dec will equal g_ra/g_dec.

    For Earth Satellites

    When computing the position of an Earth satellite using an Observer:

    • a_ra, a_dec: Astrometric Topocentric Position for the epoch of your Observer.
    • g_ra, g_dec: Apparent Geocentric Position (same as above).
    • ra, dec: Apparent Topocentric Position (same as above).
  9. Precision and Accuracy limitations

    master

    PyEphem uses 1980s-era astronomical models (like VSOP87 and the IAU 1980 model of Earth nutation). While fast and compact, this limits its accuracy to approximately 1 arcsecond.

    Recommendation:

    • For amateur astronomy, PyEphem is sufficient.
    • For high-precision requirements, use modern libraries like Skyfield or AstroPy.
  10. Convert between coordinate systems

    master

    PyEphem provides three coordinate classes for transformations. Each class has three properties: lon/ra, lat/dec, and epoch.

    • Equatorial: Uses ra (right ascension) and dec (declination).
    • Ecliptic: Uses lon (ecliptic longitude) and lat (ecliptic latitude).
    • Galactic: Uses lon (galactic longitude) and lat (galactic latitude).

    When creating a coordinate, you can pass a body, another coordinate, or a pair of raw angles (always provide longitude or right ascension first). If epoch= is not specified, it defaults to J2000 (or is copied from the source body/coordinate).

    >>> np = Equatorial('0', '90', epoch='2000')
    >>> g = Galactic(np)
    >>> print('%s %s' % (g.lon, g.lat))
    122:55:54.9 27:07:41.7
  11. Understand the impact of epoch on coordinates

    master
    The choice of epoch only affects absolute positions (Right Ascension and Declination). It does not affect local coordinates like Azimuth and Altitude. The Sun's position relative to an observer in Atlanta remains the same regardless of whether you use epoch 2000 or 1066 coordinates, as the epoch only changes how you name locations in the sky, not their physical orientation relative to the observer.
  12. Handle coordinate precession with the epoch parameter

    master

    Because the Earth's pole revolves (precession), the coordinate system (Right Ascension and Declination) shifts over time. When creating fixed objects, the catalog entry includes an epoch (the year the coordinates are accurate for).

    You can use the epoch= keyword parameter in compute() to translate coordinates into a different year's coordinate system without changing the date for which the position is calculated.

    >>> polaris.compute(epoch='2100')
    >>> print(polaris.a_dec)
    89:32:26.1