astronomy

package module
v1.0.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 7, 2026 License: MIT Imports: 6 Imported by: 0

README ΒΆ

πŸ”­ go-astronomy

Observer-aware Sun, Moon, star, and constellation positions for Go β€” altitude/azimuth, twilight bands, arc tracks, and moon phases for any (latitude, longitude, timezone, time).

Go Reference Go Report Card CI

go-astronomy computes where the Sun, Moon, and stars are in the sky for a given observer and instant. It emits degrees (altitude, azimuth) and time-progress β€” never pixels β€” so any consumer can drive an animated sky, a rise/set table, a twilight timeline, or a moon-phase widget from the same data.

It is designed for a service that computes a distinct sky per site visitor, so the API is stateless, deterministic, and concurrency-safe: time.Time is always a parameter, never captured at construction. The math is an in-house implementation of Jean Meeus' Astronomical Algorithms with no third-party ephemeris dependency (arcminute-class accuracy).

Status: v1.0.0. Everything below ships, and every signature shown matches go doc. One item is marked (roadmap) where it appears: blue-moon detection. Planets are out of scope for this release.

πŸš€ Quick start

Install:

go get github.com/Bugs5382/go-astronomy

Where is the Sun for an observer right now, and when does it rise and set today?

package main

import (
	"fmt"
	"time"

	"github.com/Bugs5382/go-astronomy"
	"github.com/Bugs5382/go-astronomy/earth"
)

func main() {
	tz, _ := time.LoadLocation("America/New_York")
	obs := astronomy.Observer{Lat: 40.678, Lng: -73.944, TZ: tz} // Brooklyn, NY
	now := time.Now().In(tz)

	// Earth vantage: geometric altitude/azimuth of the Sun's disc center.
	pos := earth.SunPosition(obs, now)
	fmt.Printf("sun alt=%.2fΒ° az=%.2fΒ°\n", pos.Altitude, pos.Azimuth)

	// Earth-bound traits: one civil day of twilight bands, resolved in obs.TZ.
	day, err := earth.NewSunTimes(obs, now)
	if err != nil {
		panic(err)
	}
	if noon, ok := day.SolarNoon(); ok {
		fmt.Println("solar noon:", noon.Format(time.Kitchen))
	}
}

The library returns (value, bool) / (value, error) where a value may be absent (for example, no sunrise during a polar day) β€” never -1 or false sentinels. Polar conditions are an explicit state (MidnightSun / PolarNight), never a nil panic.

Every returned error is a go-apperr coded error carrying a stable numeric code. Match a condition with errors.Is (for example earth.ErrInvalidLatitude) or recover the code with apperr.Code(err); astronomy.Errors() exposes the code registry (used for Present, Describe, and a Markdown code table). The library is quiet by default β€” it never logs on its own β€” but the registry has go-log wired as go-apperr's logger, so a service that renders a coded error with Registry.PresentContext gets a structured line correlated with its OpenTelemetry trace when one is active. OpenTelemetry is a transitive dependency only; this library never starts a tracer or exporter, so it stays dormant until the surrounding service turns it on.

✨ Features

  • β˜€οΈ Universal Sun physics β€” sun.ApparentDiameter / sun.ApparentSemidiameter give the Sun's apparent angular size for any distance in AU, from the semidiameter-at-1-AU constant. This is the only observer-independent part of the Sun, so any vantage body reuses it with its own distance.
  • πŸŒ… Earth vantage on the Sun β€” earth.SunPosition (geometric alt/az of the disc center, paired with apparent diameter) and earth.SunTrack (arc samples of {Time, Altitude, Azimuth, TimeProgress}). The alt/az, sidereal time, and Earth-Sun distance are all Earth-specific, so they live with the Earth vantage rather than in sun.
  • πŸŒ‡ Earth twilight bands β€” earth.NewSunTimes resolves one civil day in the observer's timezone with Earth refraction (βˆ’0.833Β° upper limb, Bennett): astronomical/nautical/civil dawn, sunrise, golden hour, day split at solar noon, golden hour, sunset, and the matching dusk bands. Each band is {from, to, seconds}.
  • πŸŒ— Moon (Luna) β€” earth/moon position and apparent position, next rise/set, the eight named phases, Age, Illumination, PhaseAngle, next new/full, and Track. PhaseAt names the phase from the Moon's elongation from the Sun rather than from its age, so the name follows the sky rather than a mean cycle length. Blue-moon detection is (roadmap). The Moon belongs to Earth; other bodies own their own moons.
  • ⭐ Stars β€” an embedded HYG-derived named-star catalog with RA/Dec and distance, projected to alt/az for the observer and instant.
  • 🌌 Constellations β€” constellation.FindAt looks up the constellation containing an RA/Dec over the IAU (Delporte/Roman) default dataset, with List and Lookup alongside it. The lookup machinery is universal; the dataset is consumer-overridable.
  • πŸ“ Discs, not points β€” Sun and Moon positions are the center of the disc, always paired with angular diameter, so a consumer can size the disc and compute alignment/overlap (eclipses, occultations) purely from the data.
  • πŸ–₯️ Pixel-agnostic projection β€” the project package maps (altitudeΒ°, azimuthΒ°, timeProgress) to (x, y) with selectable strategies (XMode = time-progress or azimuth; YMode = normalized-by-peak or geometric) and a configurable horizon anchor.
  • 🧭 Configurable segmentation β€” twilight thresholds and band labels are data. Earth defaults ship (βˆ’18/βˆ’12/βˆ’6Β°, golden hour, sunrise/sunset), and earth.NewSunTimesWith takes a Segmentation to redefine them wholesale.
  • πŸ•› Seamless midnight rollover β€” earth.SegmentAt answers "which band, and how far through it, at now" and stitches across midnight with no gap. Callers ask only for now, never for the previous or next day.
  • 🧡 Stateless & concurrency-safe β€” every call takes the observer and time.Time; nothing is captured at construction, so the same instance serves many visitors at once.

πŸ“‹ Requirements

  • Go >= 1.27

🧭 Architecture

Universal celestial geometry and per-body trait packages sit over an unexported internal/ math core. Only the Sun is universal to the solar system; per-body packages own that body's observer, atmosphere, and naming traits. Consumers import the universal packages plus the body package they need (earth, including earth/moon).

flowchart TD
    subgraph universal["universal geometry"]
      SUN["sun<br/>Position, Track"]
      STAR["star<br/>HYG catalog (RA/Dec + distance)"]
      CONST["constellation<br/>boundary lookup (IAU default)"]
    end

    subgraph earthPkg["earth (Earth-bound traits)"]
      EARTH["earth<br/>SunTimes, twilight bands,<br/>refraction, seasons, polar states"]
      MOON["earth/moon<br/>Luna: position, phases, rise/set, Track"]
    end

    subgraph internalPkg["internal (unexported math core)"]
      ANG["angles"]
      JUL["julian / sidereal / obliquity"]
      COORD["coordinates<br/>ecliptic ⇄ equatorial ⇄ horizontal"]
      PROJ["project<br/>alt/az/progress β†’ x/y"]
      EPH["ephemeris<br/>Meeus series: solar, lunar, precession, nutation"]
    end

    APP["your code / service"] --> SUN
    APP --> STAR
    APP --> CONST
    APP --> EARTH
    APP --> MOON

    EARTH --> SUN
    MOON --> COORD
    SUN --> COORD
    STAR --> COORD
    CONST --> COORD
    COORD --> ANG
    COORD --> JUL
    COORD --> EPH
    JUL --> EPH
    EARTH --> EPH
    MOON --> EPH

Adding a future body (for example, mars/ with its own moons and SunTimes equivalent) requires no change to sun.

πŸ› οΈ Working in the repo

The repo uses a Taskfile:

task build        # go build ./...
task test         # go test ./...
task test-cover   # go test ./... -cover
task fmt          # gofmt + goimports
task lint         # gofmt check, golangci-lint, yamllint
task license      # verify MIT headers (golic, dry run)
task license:fix  # inject any missing MIT headers

Plain go works too:

go build ./...
go test ./...

Commit discipline, AI-tell/emoji blocking, and the pre-push gofmt/vet/lint/test gate are enforced by the governance hooks. Install them once per clone:

bash .claude/hooks/install.sh

πŸ“š Documentation

Accuracy target is amateur / arcminute-class. The library omits nutation, Ξ”T, and leap seconds β€” they sit below that precision floor.

🀝 Contributing

Contributions are welcome β€” bug reports, fixes, new coverage, and docs improvements.

  1. 🍴 Fork the repo and create a topic branch (<type>/<issue#>-<slug>).
  2. βœ… Add tests for any behavior change. Run the suite with go test ./... (or task test).
  3. 🧹 Lint and format with task lint from the repo root (commits follow Conventional Commits).
  4. πŸš€ Open a PR. CI runs build, tests, and linters on every push.

πŸ™ Acknowledgements

  • Jean Meeus, Astronomical Algorithms β€” the algorithmic foundation. The series in internal/ephemeris were ported from soniakeys/meeus, which this library no longer depends on.
  • The HYG star database (Hipparcos-Yale-Gliese) β€” the source for the embedded star catalog, used under CC BY-SA 4.0.
  • The IAU constellation boundaries of EugΓ¨ne Delporte (1930), digitized by Nancy Roman (1987) as VizieR VI/42 β€” the source for the embedded boundary table.

See NOTICE for the full attribution and licensing of the embedded data.

πŸ“„ License

MIT

Documentation ΒΆ

Overview ΒΆ

Package astronomy is an observer-aware Go astronomy library: sun, moon, star, and constellation positions with twilight bands, arc tracks, and moon phases.

This root package holds the shared domain types (Observer, Horizontal, Position, AngularDiameter) used across the body-specific packages. The heavy math lives in unexported internal packages built on the meeus ephemeris algorithms.

Index ΒΆ

Constants ΒΆ

View Source
const (
	// CodeInvalidLatitude marks an observer latitude outside [-90, 90].
	CodeInvalidLatitude = 7001
	// CodeInvalidLongitude marks an observer longitude outside [-180, 180].
	CodeInvalidLongitude = 7002
	// CodeInvalidSegmentation marks a Segmentation whose levels are empty or not
	// in strictly ascending altitude order.
	CodeInvalidSegmentation = 7003
	// CodeInvalidMagnitudeRange marks a stellar magnitude query whose bright
	// bound is fainter than its faint bound, which can select no star.
	CodeInvalidMagnitudeRange = 7004
	// CodeInvalidCanvas marks a screen projection whose canvas width or height is
	// not positive, so it spans no pixels.
	CodeInvalidCanvas = 7005
	// CodeInvalidHorizonFraction marks a viewport whose horizon fraction is
	// outside [0, 1], so the horizon line would fall off the canvas.
	CodeInvalidHorizonFraction = 7006
	// CodeInvalidPeakAltitude marks a NormalizedByPeak projection whose peak
	// altitude is not positive, which cannot normalize an arch.
	CodeInvalidPeakAltitude = 7007
	// CodeInvalidFieldOfView marks an azimuth-based projection whose field of view
	// (Directional) or sunrise-to-sunset azimuth span (FullArc) is not positive.
	CodeInvalidFieldOfView = 7008
	// CodeInvalidElevationScale marks a Geometric projection whose elevation
	// degrees-per-pixel is not positive.
	CodeInvalidElevationScale = 7009
	// CodeXModeNotAzimuth marks a column-to-azimuth inverse query on a projection
	// whose horizontal mode is not azimuth-based, so no azimuth axis exists.
	CodeXModeNotAzimuth = 7010
)

Stable numeric error codes for the module. Each error-returning function wraps its cause with one of these via go-apperr, so a caller can recover the code with apperr.Code and branch on it without matching error strings. The values are part of the public contract: never renumber a code, only add new ones.

View Source
const ErrorServiceDigit = 7

ErrorServiceDigit is the leading digit that every go-astronomy error code shares, so a code is attributable to this module at a glance. It is the go-apperr service prefix for the module's code namespace.

Variables ΒΆ

This section is empty.

Functions ΒΆ

func Errors ΒΆ

func Errors() *apperr.Registry

Errors returns the module's go-apperr registry: the stable code table plus the presentation and logging policy around it. A consumer renders a coded error at its edge with Registry.Present (or PresentContext, which also drives the wired go-log logger) to obtain a sanitized, quotable message, looks a code up with Registry.Describe, or emits the whole table as Markdown with Registry.Markdown. The registry is built once and is safe for concurrent use.

Types ΒΆ

type AngularDiameter ΒΆ

type AngularDiameter float64

AngularDiameter is the apparent angular size of a body's disc, in degrees.

func (AngularDiameter) Radius ΒΆ

func (a AngularDiameter) Radius() float64

Radius returns half the angular diameter, in degrees.

type Horizontal ΒΆ

type Horizontal struct {
	Altitude float64
	Azimuth  float64
}

Horizontal is a direction in the local horizontal (alt-az) frame. Azimuth is measured clockwise from true north and Altitude is the angle above the horizon; both are in degrees. A negative Altitude is below the horizon.

func (Horizontal) AboveHorizon ΒΆ

func (h Horizontal) AboveHorizon() bool

AboveHorizon reports whether the direction is above the geometric horizon.

type Observer ΒΆ

type Observer struct {
	// Lat is the geographic latitude in degrees, positive north, in [-90, 90].
	Lat float64
	// Lng is the geographic longitude in degrees, positive east, in [-180, 180].
	Lng float64
	// TZ is the observer's local time zone. A nil value is treated as UTC.
	TZ *time.Location
}

Observer is a location on the Earth's surface for which celestial positions are computed. Time is never captured here; it is always supplied as a parameter to the calculation functions, keeping the library stateless.

func (Observer) Location ΒΆ

func (o Observer) Location() *time.Location

Location returns the observer's time zone, defaulting to UTC when TZ is nil.

type Position ΒΆ

type Position struct {
	Horizontal
	Diameter AngularDiameter
}

Position is the apparent placement of a body: the direction to the center of its disc paired with the disc's apparent angular size. Pairing the center with the angular diameter lets a consumer size and place the disc and reason about alignment and overlap between bodies.

Directories ΒΆ

Path Synopsis
Package constellation identifies which of the 88 IAU constellations a celestial position falls in, and lists the constellations.
Package constellation identifies which of the 88 IAU constellations a celestial position falls in, and lists the constellations.
Package earth adds Earth-bound conventions on top of the universal solar geometry in the sun package: named twilight bands, sunrise and sunset, solar noon, polar states, and atmospheric refraction.
Package earth adds Earth-bound conventions on top of the universal solar geometry in the sun package: named twilight bands, sunrise and sunset, solar noon, polar states, and atmospheric refraction.
moon
Package moon provides the Earth vantage on Luna, the Earth's moon: its topocentric horizontal position and apparent size, its phase and illumination, its rise and set for an observer, and an arc track over a time span.
Package moon provides the Earth vantage on Luna, the Earth's moon: its topocentric horizontal position and apparent size, its phase and illumination, its rise and set for an observer, and an arc track over a time span.
internal
angles
Package angles provides small, dependency-free helpers for working with angles expressed in degrees: conversion to and from radians, normalization into the range [0, 360), and clamping of declinations to [-90, 90].
Package angles provides small, dependency-free helpers for working with angles expressed in degrees: conversion to and from radians, normalization into the range [0, 360), and clamping of declinations to [-90, 90].
coordinates
Package coordinates converts celestial positions between the ecliptic, equatorial, and local horizontal (alt-az) frames.
Package coordinates converts celestial positions between the ecliptic, equatorial, and local horizontal (alt-az) frames.
ephemeris
Package ephemeris implements the astronomical series this library needs, ported directly rather than pulled in as a dependency.
Package ephemeris implements the astronomical series this library needs, ported directly rather than pulled in as a dependency.
julian
Package julian converts civil instants into the time quantities the ephemeris math depends on: the Julian Date, Greenwich and local mean sidereal time, and the mean obliquity of the ecliptic.
Package julian converts civil instants into the time quantities the ephemeris math depends on: the Julian Date, Greenwich and local mean sidereal time, and the mean obliquity of the ecliptic.
Package project maps already-computed celestial positions, expressed in degrees, to canvas pixels.
Package project maps already-computed celestial positions, expressed in degrees, to canvas pixels.
Package star provides a universal, observer-independent catalog of stars: the quantities that belong to a star itself, not to any vantage.
Package star provides a universal, observer-independent catalog of stars: the quantities that belong to a star itself, not to any vantage.
Package sun provides universal Sun physics: quantities that depend only on the Sun itself, not on any observer, atmosphere, or vantage body.
Package sun provides universal Sun physics: quantities that depend only on the Sun itself, not on any observer, atmosphere, or vantage body.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL