Coverage for astrocalc/cl_utils.py : 8%

Hot-keys on this page
r m x p toggle line displays
j k next/prev highlighted chunk
0 (zero) top of page
1 (one) first highlighted chunk
1#!/usr/bin/env python
2# encoding: utf-8
3"""
4Documentation for astrocalc can be found here: http://astrocalc.readthedocs.org
6Usage:
7 astrocalc [-c] coordflip <ra> <dec>
8 astrocalc sep <ra1> <dec1> <ra2> <dec2>
9 astrocalc timeflip <datetime>
10 astrocalc trans <ra> <dec> <north> <east>
11 astrocalc now mjd
12 astrocalc dist (-z | -m) <distVal> [--hc=hVal --wm=OmegaMatter --wv=OmegaVacuum]
14Commands:
15 coordflip flip coordinates between decimal degrees and sexegesimal and vice-versa
16 sep calculate the separation between two locations in the sky.
17 timeflip flip time between UT and MJD.
18 trans translate a location across the sky (north and east in arcsec)
19 now report current time in various formats
20 dist convert distance between mpc to z
22Variables:
23 ra, ra1, ra2 right-ascension in deciaml degrees or sexegesimal format
24 dec, dec1, dec2 declination in deciaml degrees or sexegesimal format
25 datetime modified julian date (mjd) or universal time (UT). UT can be formated 20150415113334.343 or "20150415 11:33:34.343" (spaces require quotes)
26 north, east vector components in arcsec
27 distVal a distance value in Mpc (-mpc) or redshift (-z)
28 hVal hubble constant value. Default=70 km/s/Mpc
29 OmegaMatter Omega Matter. Default=0.3
30 OmegaVacuum Omega Vacuum. Default=0.7
32Options:
33 init setup the astrocalc settings file for the first time
34 -v, --version show version
35 -h, --help show this help message
36 -m, --mpc distance in mpc
37 -z, --redshift redshift distance
38 -c, --cartesian convert to cartesian coordinates
39 -s, --settings <pathToSettingsFile> the settings file
40"""
41from __future__ import print_function
42from builtins import str
43import sys
44import os
45os.environ['TERM'] = 'vt100'
46import readline
47import glob
48import pickle
49from docopt import docopt
50from fundamentals import tools, times
51from astrocalc.coords import unit_conversion
53def tab_complete(text, state):
54 return (glob.glob(text + '*') + [None])[state]
56def main(arguments=None):
57 """
58 *The main function used when `cl_utils.py` is run as a single script from the cl, or when installed as a cl command*
59 """
60 from astrocalc.coords import unit_conversion
61 # setup the command-line util settings
62 su = tools(
63 arguments=arguments,
64 docString=__doc__,
65 logLevel="CRITICAL",
66 options_first=True,
67 projectName="astrocalc",
68 defaultSettingsFile=True
69 )
70 arguments, settings, log, dbConn = su.setup()
72 # tab completion for raw_input
73 readline.set_completer_delims(' \t\n;')
74 readline.parse_and_bind("tab: complete")
75 readline.set_completer(tab_complete)
77 # UNPACK REMAINING CL ARGUMENTS USING `EXEC` TO SETUP THE VARIABLE NAMES
78 # AUTOMATICALLY
79 a = {}
80 for arg, val in list(arguments.items()):
81 if arg[0] == "-":
82 varname = arg.replace("-", "") + "Flag"
83 else:
84 varname = arg.replace("<", "").replace(">", "")
85 a[varname] = val
86 if arg == "--dbConn":
87 dbConn = val
88 a["dbConn"] = val
89 log.debug('%s = %s' % (varname, val,))
91 ## START LOGGING ##
92 startTime = times.get_now_sql_datetime()
93 log.info(
94 '--- STARTING TO RUN THE cl_utils.py AT %s' %
95 (startTime,))
97 # set options interactively if user requests
98 if "interactiveFlag" in a and a["interactiveFlag"]:
100 # load previous settings
101 moduleDirectory = os.path.dirname(__file__) + "/resources"
102 pathToPickleFile = "%(moduleDirectory)s/previousSettings.p" % locals()
103 try:
104 with open(pathToPickleFile):
105 pass
106 previousSettingsExist = True
107 except:
108 previousSettingsExist = False
109 previousSettings = {}
110 if previousSettingsExist:
111 previousSettings = pickle.load(open(pathToPickleFile, "rb"))
113 # x-raw-input
114 # x-boolean-raw-input
115 # x-raw-input-with-default-value-from-previous-settings
117 # save the most recently used requests
118 pickleMeObjects = []
119 pickleMe = {}
120 theseLocals = locals()
121 for k in pickleMeObjects:
122 pickleMe[k] = theseLocals[k]
123 pickle.dump(pickleMe, open(pathToPickleFile, "wb"))
125 if a["init"]:
126 from os.path import expanduser
127 home = expanduser("~")
128 filepath = home + "/.config/astrocalc/astrocalc.yaml"
129 try:
130 cmd = """open %(filepath)s""" % locals()
131 p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
132 except:
133 pass
134 try:
135 cmd = """start %(filepath)s""" % locals()
136 p = Popen(cmd, stdout=PIPE, stderr=PIPE, shell=True)
137 except:
138 pass
139 return
141 coordflip = a["coordflip"]
142 sep = a["sep"]
143 timeflip = a["timeflip"]
144 trans = a["trans"]
145 now = a["now"]
146 dist = a["dist"]
147 ra = a["ra"]
148 ra1 = a["ra1"]
149 ra2 = a["ra2"]
150 dec = a["dec"]
151 dec1 = a["dec1"]
152 dec2 = a["dec2"]
153 datetime = a["datetime"]
154 north = a["north"], east
155 distVal = a["distVal"]
156 hVal = a["hVal"]
157 OmegaMatter = a["OmegaMatter"]
158 OmegaVacuum = a["OmegaVacuum"]
159 mpcFlag = a["mpcFlag"]
160 redshiftFlag = a["redshiftFlag"]
161 cartesianFlag = a["cartesianFlag"]
163 # CALL FUNCTIONS/OBJECTS
164 if coordflip:
166 if cartesianFlag:
167 converter = unit_conversion(
168 log=log
169 )
170 x, y, z = converter.ra_dec_to_cartesian(
171 ra="23 45 21.23232",
172 dec="+01:58:5.45341"
173 )
174 print(x, y, z)
175 return
177 try:
178 ra = float(ra)
179 dec = float(dec)
180 degree = True
181 except Exception as e:
182 degree = False
184 if degree is True:
185 converter = unit_conversion(
186 log=log
187 )
188 try:
189 ra = converter.ra_decimal_to_sexegesimal(
190 ra=ra,
191 delimiter=":"
192 )
193 dec = converter.dec_decimal_to_sexegesimal(
194 dec=dec,
195 delimiter=":"
196 )
197 except Exception as e:
198 print(e)
199 sys.exit(0)
201 print(ra, dec)
202 else:
203 converter = unit_conversion(
204 log=log
205 )
206 try:
207 ra = converter.ra_sexegesimal_to_decimal(
208 ra=ra
209 )
210 dec = converter.dec_sexegesimal_to_decimal(
211 dec=dec
212 )
213 except Exception as e:
214 print(e)
215 sys.exit(0)
216 print(ra, dec)
218 if sep:
219 from astrocalc.coords import separations
220 calculator = separations(
221 log=log,
222 ra1=ra1,
223 dec1=dec1,
224 ra2=ra2,
225 dec2=dec2,
226 )
227 angularSeparation, north, east = calculator.get()
228 print("""%(angularSeparation)s arcsec (%(north)s N, %(east)s E)""" % locals())
230 if timeflip:
231 try:
232 inputMjd = float(datetime)
233 if datetime[0] not in ["0", "1", "2"]:
234 inputMjd = True
235 else:
236 inputMjd = False
237 except:
238 inputMjd = False
239 from astrocalc.times import conversions
240 converter = conversions(
241 log=log
242 )
244 if inputMjd == False:
245 try:
246 mjd = converter.ut_datetime_to_mjd(utDatetime=datetime)
247 print(mjd)
248 except Exception as e:
249 print(e)
250 else:
251 try:
252 utDate = converter.mjd_to_ut_datetime(mjd=datetime)
253 print(utDate)
254 except Exception as e:
255 print(e)
257 if trans:
258 # TRANSLATE COORDINATES ACROSS SKY
259 from astrocalc.coords import translate
260 newRa, newDec = translate(
261 log=log,
262 ra=ra,
263 dec=dec,
264 northArcsec=float(north),
265 eastArcsec=float(east)
266 ).get()
267 from astrocalc.coords import unit_conversion
268 converter = unit_conversion(
269 log=log
270 )
271 ra = converter.ra_decimal_to_sexegesimal(
272 ra=newRa,
273 delimiter=":"
274 )
275 dec = converter.dec_decimal_to_sexegesimal(
276 dec=newDec,
277 delimiter=":"
278 )
280 print("%(newRa)s, %(newDec)s (%(ra)s, %(dec)s)" % locals())
282 if now:
283 from astrocalc.times import now
284 mjd = now(
285 log=log
286 ).get_mjd()
287 print(mjd)
289 if dist and redshiftFlag:
290 from astrocalc.distances import converter
291 c = converter(log=log)
292 if not hcFlag:
293 hcFlag = 70.
294 if not wmFlag:
295 wmFlag = 0.3
296 if not wvFlag:
297 wvFlag = 0.7
298 dists = c.redshift_to_distance(
299 z=float(distVal),
300 WM=float(wmFlag),
301 WV=float(wvFlag),
302 H0=float(hcFlag)
303 )
304 print("Distance Modulus: " + str(dists["dmod"]) + " mag")
305 print("Luminousity Distance: " + str(dists["dl_mpc"]) + " Mpc")
306 print("Angular Size Scale: " + str(dists["da_scale"]) + " kpc/arcsec")
307 print("Angular Size Distance: " + str(dists["da_mpc"]) + " Mpc")
308 print("Comoving Radial Distance: " + str(dists["dcmr_mpc"]) + " Mpc")
310 if dist and mpcFlag:
311 from astrocalc.distances import converter
312 c = converter(log=log)
313 z = c.distance_to_redshift(
314 mpc=float(distVal)
315 )
316 print("z = %(z)s" % locals())
318 if "dbConn" in locals() and dbConn:
319 dbConn.commit()
320 dbConn.close()
321 ## FINISH LOGGING ##
322 endTime = times.get_now_sql_datetime()
323 runningTime = times.calculate_time_difference(startTime, endTime)
324 log.info('-- FINISHED ATTEMPT TO RUN THE cl_utils.py AT %s (RUNTIME: %s) --' %
325 (endTime, runningTime, ))
327 return
329if __name__ == '__main__':
330 main()