Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save thespacedoctor/353a2f0cf1c60e7a6e7767919dd852fa to your computer and use it in GitHub Desktop.
Save thespacedoctor/353a2f0cf1c60e7a6e7767919dd852fa to your computer and use it in GitHub Desktop.
[Generate an Ephemeris Grid of Planets and Natural Satellites in the Solar-System] #solar_system #planet #moon
#!/usr/local/bin/python
# encoding: utf-8
"""
*Generate a 15 year grid of planetary moon positions (from ~Hawaii) for ATLAS HKO and MLO (and PanSTARRS) transient matching *
:Author:
David Young
:Date Created:
January 23, 2019
Usage:
generate_hawaii_plantary_moon_position_grid
Options:
-h, --help show this help message
-v, --version show version
-s, --settings the settings file
"""
################# GLOBAL IMPORTS ####################
import sys
import os
from fundamentals import tools
import codecs
from fundamentals.renderer import list_of_dictionaries
def main(arguments=None):
"""
*The main function used when ``generate_hawaii_plantary_moon_position_grid.py`` is run as a single script from the cl*
"""
# SETUP THE COMMAND-LINE UTIL SETTINGS
su = tools(
arguments=arguments,
docString=__doc__,
logLevel="WARNING",
options_first=False,
projectName=False
)
arguments, settings, log, dbConn = su.setup()
# UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
# AUTOMATICALLY
for arg, val in arguments.iteritems():
if arg[0] == "-":
varname = arg.replace("-", "") + "Flag"
else:
varname = arg.replace("<", "").replace(">", "")
if isinstance(val, str) or isinstance(val, unicode):
exec(varname + " = '%s'" % (val,))
else:
exec(varname + " = %s" % (val,))
if arg == "--dbConn":
dbConn = val
log.debug('%s = %s' % (varname, val,))
# GRID'S MOON LIST
moonList = read_moons(log=log)
# GRID'S EPOCH LIST
mjdList = generate_mjd_list(log, "2012-01-01", "2027-01-01")
# FOR EACH MOON GENERATE A CSV GRID FILE
for moon in moonList:
get_moon_positions(log, moon, mjdList)
return
def read_moons(
log):
"""*read the csv list of moons found in same directory as this script*
**Key Arguments:**
- ``log`` -- logger
**Return:**
- ``moonList`` -- a list of the moon names
"""
log.debug('starting the ``read_moons`` function')
# PATH TO CSV FILE
scriptDirectory = os.path.dirname(__file__)
if len(scriptDirectory):
csvFilePath = scriptDirectory + "/solar_system_planet_moon_list.csv"
else:
csvFilePath = "solar_system_planet_moon_list.csv"
readFile = codecs.open(csvFilePath, encoding='utf-8', mode='r')
try:
log.debug("attempting to open the file %s" % (csvFilePath,))
readFile = codecs.open(csvFilePath, encoding='utf-8', mode='r')
thisData = readFile.read()
readFile.close()
except IOError, e:
message = 'could not open the file %s' % (csvFilePath,)
log.critical(message)
raise IOError(message)
readFile.close()
# GRID MOON LIST
moonList = []
for line in thisData.split("\n"):
if (len(line.split(",")) > 1 and line.split(",")[1].strip() > 1):
moonList.append(line.split(",")[1].strip())
elif len(line.split(",")[0].strip()) > 1:
moonList.append(line.split(",")[0].strip())
log.debug('completed the ``read_moons`` function')
return moonList
def get_moon_positions(
log,
moon,
mjdList):
"""*ping JPL to get the positions of the moon for 15 years at a 1 days resolution from HKO obs*
**Key Arguments:**
- ``log`` -- logger
- ``moon`` -- the name of the moon
- ``mjdList`` -- the list of MJDs to generate the positions for
**Return:**
- ``positionGrid`` -- a list of epoch, RA, DEC
"""
log.debug('starting the ``get_moon_positions`` function')
moon = moon.lower()
from rockfinder import jpl_horizons_ephemeris
from fundamentals.renderer import list_of_dictionaries
# SPLIT THE MJS LIST
batchSize = 500
total = len(mjdList)
batches = int(total / batchSize)
start = 0
end = 0
theseBatches = []
for i in range(batches + 1):
end = end + batchSize
start = i * batchSize
thisBatch = mjdList[start:end]
theseBatches.append(thisBatch)
bigList = []
for batch in theseBatches:
eph = jpl_horizons_ephemeris(
log=log,
objectId=moon,
mjd=batch,
verbose=False,
obscode="T05"
)
bigList += eph
import time
time.sleep(3)
# GRAB PARAMETERS WE NEED
trimmedList = []
trimmedList[:] = [{"objectId": t["objectId"], "mjd": t["mjd"], "ra_deg": t[
"ra_deg"], "dec_deg": t["dec_deg"], "apparent_mag": t["apparent_mag"], } for t in bigList]
dataSet = list_of_dictionaries(
log=log,
listOfDictionaries=trimmedList,
# use re.compile('^[0-9]{4}-[0-9]{2}-[0-9]{2}T') for mysql
reDatetime=False
)
moonName = trimmedList[0]["objectId"].lower().replace(" ", "_")
positionGrid = dataSet.csv(
filepath="moon_ephemerides/%(moonName)s.csv" % locals())
log.debug('completed the ``get_moon_positions`` function')
return positionGrid
def generate_mjd_list(
log,
startDate,
endDate):
"""*generate a list of MJDs between 2 dates at a resolution of 0.1 days*
**Key Arguments:**
- ``log`` -- logger
- ``startDate`` -- the start date (UT), e.g. 2012-01-01
- ``endDate`` -- the end date (UT), e.g. 2012-01-01
**Return:**
- ``mjdList`` -- the list of MJDs
"""
log.debug('starting the ``generate_mjd_list`` function')
from astrocalc.times import conversions
# ASTROCALC CONVERTER
converter = conversions(
log=log
)
mjdStart = int(
float(converter.ut_datetime_to_mjd(utDatetime=startDate)))
mjdEnd = int(float(converter.ut_datetime_to_mjd(utDatetime=endDate)))
mjdList = [x / 10. for x in range(mjdStart * 10, mjdEnd * 10)]
log.debug('completed the ``generate_mjd_list`` function')
return mjdList
if __name__ == '__main__':
main()
Mercury 199
Venus 299
Mars 499
Jupiter 599
Saturn 699
Uranus 799
Neptune 899
Pluto 999
Phobos
Deimos
Io 501
Europa 502
Ganymede
Callisto
Amalthea
Thebe
Adrastea
Metis
Himalia
Elara
Pasiphae
Sinope
Lysithea
Carme
Ananke
Leda
Callirrhoe
Themisto
Megaclite
Taygete
Chaldene
Harpalyke
Kalyke
Iocaste
Erinome
Isonoe
Praxidike
Autonoe
Thyone
Hermippe
Aitne
Eurydome
Euanthe
Euporie
Orthosie
Sponde
Kale
Pasithee
Hegemone
Mneme
Aoede
Thelxinoe
Arche
Kallichore
Helike
Carpo
Eukelade
Cyllene
Kore
Herse
2000J11
2003J2
2003J3
2003J4
2003J5
2003J9
2003J10
2003J12
2003J15
2003J16
2003J18
2003J19
2003J23
2010J1
2010J2
2011J1
2011J2
Mimas
Enceladus
Tethys
Dione
Rhea
Titan 606
Hyperion
Iapetus
Phoebe
Janus
Epimetheus
Helene
Telesto
Calypso
Atlas
Prometheus
Pandora
Pan 618
Methone
Pallene
Polydeuces
Daphnis
Anthe 649
Aegaeon
Ymir
Paaliaq
Tarvos
Ijiraq
Suttungr
Kiviuq
Mundilfari
Albiorix
Skathi
Erriapus
Siarnaq
Thrymr
Narvi
Aegir
Bebhionn
Bergelmir
Bestla
Farbauti
Fenrir
Fornjot
Hati
Hyrrokkin
Kari
Loge
Skoll
Surtur
Jarnsaxa
Greip
Tarqeq
2004S7
2004S12
2004S13
2004S17
2006S1
2006S3
2007S2
2007S3
Ariel
Umbriel
Titania
Oberon
Miranda
Cordelia
Ophelia
Bianca
Cressida
Desdemona
Juliet
Portia
Rosalind
Belinda
Puck
Perdita
Mab
Cupid
Caliban
Sycorax
Prospero
Setebos
Stephano
Trinculo
Francisco
Margaret
Ferdinand
Triton
Nereid
Naiad
Thalassa
Despina
Galatea
Larissa
Proteus
S2004N1
Halimede
Psamathe
Sao
Laomedeia
Neso
Charon
Nix 902
Hydra
Kerberos
Styx
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment