From e7bf4d221aea910e1ac09441fe7d9cb91fa90ef4 Mon Sep 17 00:00:00 2001 From: Don Cross Date: Sat, 28 Oct 2023 16:27:57 -0400 Subject: [PATCH] Go: added function RefractionAngle --- generate/template/astronomy.go | 54 ++++++++++++++++++++++++++++ source/golang/README.md | 64 +++++++++++++++++++-------------- source/golang/astronomy.go | 54 ++++++++++++++++++++++++++++ source/golang/astronomy_test.go | 18 +++++++++- 4 files changed, 162 insertions(+), 28 deletions(-) diff --git a/generate/template/astronomy.go b/generate/template/astronomy.go index 62af1490..916e9020 100644 --- a/generate/template/astronomy.go +++ b/generate/template/astronomy.go @@ -589,6 +589,56 @@ const ( JplHorizonsRefraction ) +// RefractionAngle calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. +// Given an altitude angle and a refraction option, calculates +// the amount of "lift" caused by atmospheric refraction. +// This is the number of degrees higher in the sky an object appears +// due to the lensing of the Earth's atmosphere. +// This function works best near sea level. +// To correct for higher elevations, call Atmosphere for that +// elevation and multiply the refraction angle by the resulting relative density. +// The refraction parameter specifies which refraction correction to use. +// If set to NormalRefraction, uses a well-behaved refraction model that works well for +// all valid values (-90 to +90) of altitude. +// If set to JplHorizonsRefraction, this function returns a value compatible with the JPL Horizons tool. +// This is provided for internal unit tests that compare against JPL Horizons data. +// Any other value, including NoRefraction, causes this function to return 0.0. +// The return value is a non-negative value expressed in degrees of refraction above the horizontal. +func RefractionAngle(refraction Refraction, altitude float64) float64 { + if altitude < -90.0 || altitude > +90.0 { + return 0.0 // no attempt to correct an invalid altitude + } + var refr float64 + if refraction == NormalRefraction || refraction == JplHorizonsRefraction { + // http://extras.springer.com/1999/978-1-4471-0555-8/chap4/horizons/horizons.pdf + // JPL Horizons says it uses refraction algorithm from + // Meeus "Astronomical Algorithms", 1991, p. 101-102. + // I found the following Go implementation: + // https://github.com/soniakeys/meeus/blob/master/v3/refraction/refract.go + // This is a translation from the function "Saemundsson" there. + // I found experimentally that JPL Horizons clamps the angle to 1 degree below the horizon. + // This is important because the 'refr' formula below goes crazy near hd = -5.11. + hd := altitude + if hd < -1.0 { + hd = -1.0 + } + + refr = (1.02 / dtan(hd+10.3/(hd+5.11))) / 60.0 + + if refraction == NormalRefraction && altitude < -1.0 { + // In "normal" mode we gradually reduce refraction toward the nadir + // so that we never get an altitude angle less than -90 degrees. + // When horizon angle is -1 degrees, the factor is exactly 1. + // As altitude approaches -90 (the nadir), the fraction approaches 0 linearly. + refr *= (altitude + 90.0) / 89.0 + } + } else { + // No refraction, or the refraction option is invalid. + refr = 0.0 + } + return refr +} + // AtmosphereInfo contains information about idealized atmospheric variables at a given elevation. type AtmosphereInfo struct { Pressure float64 // atmospheric pressure in pascals @@ -875,6 +925,10 @@ func dsin(degrees float64) float64 { return math.Sin(RadiansFromDegrees(degrees)) } +func dtan(degrees float64) float64 { + return math.Tan(RadiansFromDegrees(degrees)) +} + func obscuration(a, b, c float64) float64 { if a <= 0.0 { panic("Radius of first disc must be positive.") diff --git a/source/golang/README.md b/source/golang/README.md index 5c659139..3e1282a5 100644 --- a/source/golang/README.md +++ b/source/golang/README.md @@ -22,6 +22,7 @@ It provides a suite of well\-tested functions for calculating positions of the S - [func ObserverGravity\(latitude, height float64\) float64](<#ObserverGravity>) - [func PlanetOrbitalPeriod\(body Body\) float64](<#PlanetOrbitalPeriod>) - [func RadiansFromDegrees\(degrees float64\) float64](<#RadiansFromDegrees>) +- [func RefractionAngle\(refraction Refraction, altitude float64\) float64](<#RefractionAngle>) - [func SiderealTime\(time \*AstroTime\) float64](<#SiderealTime>) - [type AstroMoonQuarter](<#AstroMoonQuarter>) - [type AstroSearchFunc](<#AstroSearchFunc>) @@ -162,7 +163,7 @@ const ( ``` -## func [AngleBetween]() +## func [AngleBetween]() ```go func AngleBetween(avec AstroVector, bvec AstroVector) float64 @@ -180,7 +181,7 @@ func DaysFromCalendar(year, month, day, hour, minute int, second float64) float6 -## func [DefineStar]() +## func [DefineStar]() ```go func DefineStar(body Body, ra, dec, distanceLightYears float64) error @@ -189,7 +190,7 @@ func DefineStar(body Body, ra, dec, distanceLightYears float64) error -## func [DegreesFromRadians]() +## func [DegreesFromRadians]() ```go func DegreesFromRadians(radians float64) float64 @@ -207,7 +208,7 @@ func Dot(a, b AstroVector) float64 Returns the scalar dot product of two vectors. -## func [MassProduct]() +## func [MassProduct]() ```go func MassProduct(body Body) float64 @@ -216,7 +217,7 @@ func MassProduct(body Body) float64 Returns the product of mass and universal gravitational constant of a Solar System body. For problems involving the gravitational interactions of Solar System bodies, it is helpful to know the product GM, where G = the universal gravitational constant and M = the mass of the body. In practice, GM is known to a higher precision than either G or M alone, and thus using the product results in the most accurate results. This function returns the product GM in the units au^3/day^2. The values come from page 10 of a JPL memorandum regarding the DE405/LE405 ephemeris: https://web.archive.org/web/20120220062549/http://iau-comm4.jpl.nasa.gov/de405iom/de405iom.pdf -## func [ObserverGravity]() +## func [ObserverGravity]() ```go func ObserverGravity(latitude, height float64) float64 @@ -225,7 +226,7 @@ func ObserverGravity(latitude, height float64) float64 Calculates the gravitational acceleration experienced by an observer on the Earth. This function implements the WGS 84 Ellipsoidal Gravity Formula. The result is a combination of inward gravitational acceleration with outward centrifugal acceleration, as experienced by an observer in the Earth's rotating frame of reference. The resulting value increases toward the Earth's poles and decreases toward the equator, consistent with changes of the weight measured by a spring scale of a fixed mass moved to different latitudes and heights on the Earth. The latitude is of the observer in degrees north or south of the equator. By formula symmetry, positive latitudes give the same answer as negative latitudes, so the sign does not matter. The height is specified above the sea level geoid in meters. No range checking is done; however, accuracy is only valid in the range 0 to 100000 meters. The return value is the gravitational acceleration expressed in meters per second squared. -## func [PlanetOrbitalPeriod]() +## func [PlanetOrbitalPeriod]() ```go func PlanetOrbitalPeriod(body Body) float64 @@ -234,7 +235,7 @@ func PlanetOrbitalPeriod(body Body) float64 PlanetOrbitalPeriod returns the average number of days it takes for a planet to orbit the Sun. -## func [RadiansFromDegrees]() +## func [RadiansFromDegrees]() ```go func RadiansFromDegrees(degrees float64) float64 @@ -242,8 +243,17 @@ func RadiansFromDegrees(degrees float64) float64 RadiansFromDegrees converts an angle expressed in degrees to an angle expressed in radians. + +## func [RefractionAngle]() + +```go +func RefractionAngle(refraction Refraction, altitude float64) float64 +``` + +RefractionAngle calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. Given an altitude angle and a refraction option, calculates the amount of "lift" caused by atmospheric refraction. This is the number of degrees higher in the sky an object appears due to the lensing of the Earth's atmosphere. This function works best near sea level. To correct for higher elevations, call Atmosphere for that elevation and multiply the refraction angle by the resulting relative density. The refraction parameter specifies which refraction correction to use. If set to NormalRefraction, uses a well\-behaved refraction model that works well for all valid values \(\-90 to \+90\) of altitude. If set to JplHorizonsRefraction, this function returns a value compatible with the JPL Horizons tool. This is provided for internal unit tests that compare against JPL Horizons data. Any other value, including NoRefraction, causes this function to return 0.0. The return value is a non\-negative value expressed in degrees of refraction above the horizontal. + -## func [SiderealTime]() +## func [SiderealTime]() ```go func SiderealTime(time *AstroTime) float64 @@ -252,7 +262,7 @@ func SiderealTime(time *AstroTime) float64 Given a date and time, SiderealTime calculates the rotation of the Earth, represented by the equatorial angle of the Greenwich prime meridian with respect to distant stars \(not the Sun, which moves relative to background stars by almost one degree per day\). This angle is called Greenwich Apparent Sidereal Time \(GAST\). GAST is measured in sidereal hours in the half\-open range \[0, 24\). When GAST = 0, it means the prime meridian is aligned with the of\-date equinox, corrected at that time for precession and nutation of the Earth's axis. In this context, the "equinox" is the direction in space where the Earth's orbital plane \(the ecliptic\) intersects with the plane of the Earth's equator, at the location on the Earth's orbit of the \(seasonal\) March equinox. As the Earth rotates, GAST increases from 0 up to 24 sidereal hours, then starts over at 0. To convert to degrees, multiply the return value by 15. As an optimization, this function caches the sidereal time value in the time parameter. The value is reused later as needed, to avoid redundant calculations. -## type [AstroMoonQuarter]() +## type [AstroMoonQuarter]() @@ -264,7 +274,7 @@ type AstroMoonQuarter struct { ``` -## type [AstroSearchFunc]() +## type [AstroSearchFunc]() @@ -371,7 +381,7 @@ type AstroVector struct { ``` -### func [GeoMoon]() +### func [GeoMoon]() ```go func GeoMoon(time AstroTime) AstroVector @@ -380,7 +390,7 @@ func GeoMoon(time AstroTime) AstroVector GeoMoon calculates the equatorial geocentric position of the Moon at a given time. The returned vector indicates the Moon's center relative to the Earth's center. The vector components are expressed in AU \(astronomical units\). The coordinates are oriented with respect to the Earth's equator at the J2000 epoch. In Astronomy Engine, this orientation is called EQJ. -### func [RotateVector]() +### func [RotateVector]() ```go func RotateVector(rotation RotationMatrix, vector AstroVector) AstroVector @@ -398,7 +408,7 @@ func (vec AstroVector) Length() float64 Returns the length of vec expressed in the same distance units as vec's components. -## type [AtmosphereInfo]() +## type [AtmosphereInfo]() AtmosphereInfo contains information about idealized atmospheric variables at a given elevation. @@ -420,7 +430,7 @@ func Atmosphere(elevationMeters float64) (AtmosphereInfo, error) Atmosphere calculates U.S. Standard Atmosphere \(1976\) variables as a function of elevation. elevationMeters is the elevation above sea level at which to calculate atmospheric variables. It must be in the range \-500 to \+100000 or an error will occur. 1. COESA, U.S. Standard Atmosphere, 1976, U.S. Government Printing Office, Washington, DC, 1976. 2. Jursa, A. S., Ed., Handbook of Geophysics and the Space Environment, Air Force Geophysics Laboratory, 1985. See: https://hbcp.chemnetbase.com/faces/documents/14_12/14_12_0001.xhtml https://ntrs.nasa.gov/api/citations/19770009539/downloads/19770009539.pdf https://www.ngdc.noaa.gov/stp/space-weather/online-publications/miscellaneous/us-standard-atmosphere-1976/us-standard-atmosphere_st76-1562_noaa.pdf -## type [AxisInfo]() +## type [AxisInfo]() @@ -468,7 +478,7 @@ func CalendarFromDays(ut float64) (*CalendarDateTime, error) CalendarFromDays converts a J2000 day value to a Gregorian calendar date and time. -## type [DeltaTimeFunc]() +## type [DeltaTimeFunc]() @@ -513,7 +523,7 @@ type Equatorial struct { ``` -## type [JupiterMoonsInfo]() +## type [JupiterMoonsInfo]() @@ -527,7 +537,7 @@ type JupiterMoonsInfo struct { ``` -### func [JupiterMoons]() +### func [JupiterMoons]() ```go func JupiterMoons(time AstroTime) JupiterMoonsInfo @@ -536,7 +546,7 @@ func JupiterMoons(time AstroTime) JupiterMoonsInfo Calculates Jovicentric positoins and velocities of Jupiter's largest 4 moons. Calculates position and velocity vectors for Jupiter's moons Io, Europa, Ganymede, and Callisto, at the given date and time. The vectors are jovicentric \(relative to the center of Jupiter\). Their orientation is the Earth's equatorial system at the J2000 epoch \(EQJ\). The position components are expressed in astronomical units \(AU\), and the velocity components are in AU/day. To convert to heliocentric position vectors, call HelioVector with Jupiter as the body to get Jupiter's heliocentric position, then add the jovicentric moon positions. Likewise, you can call \#Astronomy.GeoVector to convert to geocentric positions; however, you will have to manually correct for light travel time from the Jupiter system to Earth to figure out what time to pass to \`JupiterMoons\` to get an accurate picture of how Jupiter and its moons look from Earth. -## type [LibrationInfo]() +## type [LibrationInfo]() @@ -552,7 +562,7 @@ type LibrationInfo struct { ``` -## type [NodeEventInfo]() +## type [NodeEventInfo]() @@ -564,7 +574,7 @@ type NodeEventInfo struct { ``` -## type [NodeEventKind]() +## type [NodeEventKind]() @@ -616,7 +626,7 @@ type RotationMatrix struct { ``` -### func [CombineRotation]() +### func [CombineRotation]() ```go func CombineRotation(a, b RotationMatrix) RotationMatrix @@ -643,7 +653,7 @@ func InverseRotation(rotation RotationMatrix) RotationMatrix Calculates the inverse of a rotation matrix. Given a rotation matrix that performs some coordinate transform, this function returns the matrix that reverses that transform. -### func [Pivot]() +### func [Pivot]() ```go func Pivot(rotation RotationMatrix, axis int, angle float64) (*RotationMatrix, error) @@ -652,7 +662,7 @@ func Pivot(rotation RotationMatrix, axis int, angle float64) (*RotationMatrix, e Pivot re\-orients a rotation matrix by pivoting it by an angle around one of its axes. Given a rotation matrix, a selected coordinate axis, and an angle in degrees, this function pivots the rotation matrix by that angle around that coordinate axis. For example, if you have rotation matrix that converts ecliptic coordinates \(ECL\) to horizontal coordinates \(HOR\), but you really want to convert ECL to the orientation of a telescope camera pointed at a given body, you can use Pivot twice: \(1\) pivot around the zenith axis by the body's azimuth, then \(2\) pivot around the western axis by the body's altitude angle. The resulting rotation matrix will then reorient ECL coordinates to the orientation of your telescope camera. The axis parameter is an integer that selects which axis to pivot about: 0=x, 1=y, 2=z. The angle parameter is an angle in degrees indicating the amount of rotation around the specified axis. Positive angles indicate rotation counterclockwise as seen from the positive direction along that axis, looking towards the origin point of the orientation system. Any finite number of degrees is allowed, but best precision will result from keeping angle in the range \[\-360, \+360\]. -### func [RotationEqdEqj]() +### func [RotationEqdEqj]() ```go func RotationEqdEqj(time *AstroTime) RotationMatrix @@ -661,7 +671,7 @@ func RotationEqdEqj(time *AstroTime) RotationMatrix Calculates a rotation matrix that converts equator\-of\-date \(EQD\) to J2000 mean equator \(EQJ\). -## type [SearchContext]() +## type [SearchContext]() @@ -672,7 +682,7 @@ type SearchContext interface { ``` -## type [SeasonsInfo]() +## type [SeasonsInfo]() @@ -716,7 +726,7 @@ type StateVector struct { ``` -### func [RotateState]() +### func [RotateState]() ```go func RotateState(rotation RotationMatrix, state StateVector) StateVector @@ -743,7 +753,7 @@ func (state StateVector) Velocity() AstroVector Position returns the velocity vector inside a state vector. -## type [TimeFormat]() +## type [TimeFormat]() diff --git a/source/golang/astronomy.go b/source/golang/astronomy.go index f95f5eb8..720bbf2b 100644 --- a/source/golang/astronomy.go +++ b/source/golang/astronomy.go @@ -589,6 +589,56 @@ const ( JplHorizonsRefraction ) +// RefractionAngle calculates the amount of "lift" to an altitude angle caused by atmospheric refraction. +// Given an altitude angle and a refraction option, calculates +// the amount of "lift" caused by atmospheric refraction. +// This is the number of degrees higher in the sky an object appears +// due to the lensing of the Earth's atmosphere. +// This function works best near sea level. +// To correct for higher elevations, call Atmosphere for that +// elevation and multiply the refraction angle by the resulting relative density. +// The refraction parameter specifies which refraction correction to use. +// If set to NormalRefraction, uses a well-behaved refraction model that works well for +// all valid values (-90 to +90) of altitude. +// If set to JplHorizonsRefraction, this function returns a value compatible with the JPL Horizons tool. +// This is provided for internal unit tests that compare against JPL Horizons data. +// Any other value, including NoRefraction, causes this function to return 0.0. +// The return value is a non-negative value expressed in degrees of refraction above the horizontal. +func RefractionAngle(refraction Refraction, altitude float64) float64 { + if altitude < -90.0 || altitude > +90.0 { + return 0.0 // no attempt to correct an invalid altitude + } + var refr float64 + if refraction == NormalRefraction || refraction == JplHorizonsRefraction { + // http://extras.springer.com/1999/978-1-4471-0555-8/chap4/horizons/horizons.pdf + // JPL Horizons says it uses refraction algorithm from + // Meeus "Astronomical Algorithms", 1991, p. 101-102. + // I found the following Go implementation: + // https://github.com/soniakeys/meeus/blob/master/v3/refraction/refract.go + // This is a translation from the function "Saemundsson" there. + // I found experimentally that JPL Horizons clamps the angle to 1 degree below the horizon. + // This is important because the 'refr' formula below goes crazy near hd = -5.11. + hd := altitude + if hd < -1.0 { + hd = -1.0 + } + + refr = (1.02 / dtan(hd+10.3/(hd+5.11))) / 60.0 + + if refraction == NormalRefraction && altitude < -1.0 { + // In "normal" mode we gradually reduce refraction toward the nadir + // so that we never get an altitude angle less than -90 degrees. + // When horizon angle is -1 degrees, the factor is exactly 1. + // As altitude approaches -90 (the nadir), the fraction approaches 0 linearly. + refr *= (altitude + 90.0) / 89.0 + } + } else { + // No refraction, or the refraction option is invalid. + refr = 0.0 + } + return refr +} + // AtmosphereInfo contains information about idealized atmospheric variables at a given elevation. type AtmosphereInfo struct { Pressure float64 // atmospheric pressure in pascals @@ -875,6 +925,10 @@ func dsin(degrees float64) float64 { return math.Sin(RadiansFromDegrees(degrees)) } +func dtan(degrees float64) float64 { + return math.Tan(RadiansFromDegrees(degrees)) +} + func obscuration(a, b, c float64) float64 { if a <= 0.0 { panic("Radius of first disc must be positive.") diff --git a/source/golang/astronomy_test.go b/source/golang/astronomy_test.go index 04f6964e..5f7555e6 100644 --- a/source/golang/astronomy_test.go +++ b/source/golang/astronomy_test.go @@ -376,5 +376,21 @@ func TestObserverGravity(t *testing.T) { gravityCheck(t, 88.0000, 0.0, 9.832121) gravityCheck(t, 89.0000, 0.0, 9.832169) gravityCheck(t, 90.0000, 0.0, 9.832185) - +} + +func refractionCheck(t *testing.T, refraction Refraction, altitude, expected float64) { + actual := RefractionAngle(refraction, altitude) + diff := math.Abs(expected - actual) + if diff > 1.0e-16 { + t.Errorf("Refraction discrepancy = %g", diff) + } +} + +func TestRefraction(t *testing.T) { + refractionCheck(t, NormalRefraction, 0.0, 0.4830321230741662) + refractionCheck(t, NoRefraction, 0.0, 0.0) + refractionCheck(t, NormalRefraction, 10.0, 0.09012801338558875) + refractionCheck(t, NormalRefraction, 20.0, 0.04568673807086863) + refractionCheck(t, NormalRefraction, -80.0, 0.0726495079641601) + refractionCheck(t, NormalRefraction, -90.0, 0.0) }