mounttools.py
15.1 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
# -*- coding: utf-8 -*-
import math
import os
import sys
import serial.tools.list_ports
import requests
path = os.path.join(os.path.dirname(__file__), '..')
if path not in sys.path:
sys.path.append(path)
# --- celme imports
modulename = 'celme'
if modulename in dir():
del celme
if modulename not in dir():
import celme
# #####################################################################
# #####################################################################
# #####################################################################
# Class Mounttools
# #####################################################################
# #####################################################################
# This class included various tools
# decode_kwargs
# #####################################################################
class Mounttools:
_pi = math.pi
_d2r = _pi/180.0
_r2d = 180.0/_pi
def decode_kwargs(self, params_optional:dict, params_mandatory:dict, **kwargs)->dict:
""" Conversion of the kwargs into params
Conversion of the dictionary kwargs to another dictionary called params
according the prescriptions of keys and defauts values defined in the
two dictionaries params_optional and params_mandatory.
"""
# ========= change keys into upper strings
dics = dict()
for k,v in kwargs.items():
ku = str(k).upper()
if (type(v) is str):
v = v.strip()
dic = { ku : v }
dics.update(dic)
selected_parameters = dics
#print("dics={}".format(dics))
# ========= decode **kwargs
dico_param = {}
# ---
params = params_mandatory
for param_key in params:
if param_key in selected_parameters:
raw_value = selected_parameters[param_key]
type_conv = params[param_key][0]
if type_conv==float:
value = float(raw_value)
elif type_conv==int:
value = int(raw_value)
else:
value = raw_value
dico_param[param_key] = value
else:
msg = "{} not found amongst mandatory parameters ({})".format(param_key,params.keys())
raise Exception(msg)
# ---
params = params_optional
for param_key in params:
if param_key in selected_parameters:
raw_value = selected_parameters[param_key]
type_conv = params[param_key][0]
else:
raw_value = params[param_key][1]
type_conv = params[param_key][0]
if type_conv==float:
value = float(raw_value)
elif type_conv==int:
value = int(raw_value)
else:
value = raw_value
dico_param[param_key] = value
return dico_param
def decode_args_kwargs(self, arg_index:int, params_args:dict, params_optional:dict, *args, **kwargs)->dict:
""" Conversion of the args and kwargs into params
Conversion of the parameters args and dictionary kwargs to another dictionary called params
according the prescriptions of keys and defauts values defined in the
two dictionaries params_optional and params_mandatory.
"""
#print("arg_index={}".format(arg_index))
#print("params_args={}".format(params_args))
#print("params_optional={}".format(params_optional))
#print("*args={}".format(args))
#print("**kwargs={}".format(kwargs))
# ========= valid *args
argc = len(args)
valid = 1
if (argc==0):
valid = 0
msg = "No key specified ({})".format(params_args.keys())
else:
# --- Identify the selected motion type
selected_arg = args[arg_index].upper()
if selected_arg in params_args:
parameters = params_args[selected_arg]
else:
valid = 0
msg = "{} not found amongst args ({})".format(selected_arg,params_args.keys())
if valid==0:
raise Exception(msg)
# ========= valid **kwargs
valid = 0
#if (kwargc==0):
# raise Exception(res)
#print("3.*args={}".format(args))
#print("3.**kwargs={}".format(kwargs))
# ========= change keys into upper strings
dics = dict()
for k,v in kwargs.items():
ku = str(k).upper()
if (type(v) is str):
v = v.strip()
dic = { ku : v }
dics.update(dic)
selected_parameters = dics
#print("dics={}".format(dics))
# ========= decode **kwargs
valid = 0
dico_param = {}
dico_param["SELECTED_ARG"] = selected_arg
# --- input values of mandatory parameters
params = parameters["MANDATORY"]
#print(">>> params={}".format(params))
#print("*** selected_parameters={}".format(selected_parameters))
for param_key in params:
#print("** param_key={}".format(param_key))
if param_key in selected_parameters:
raw_value = selected_parameters[param_key]
type_conv = params[param_key][0]
#print("* type_conv={}".format(type_conv))
if type_conv==float:
value = float(raw_value)
elif type_conv==int:
value = int(raw_value)
else:
value = raw_value
dico_param[param_key] = value
else:
print("- TOTO")
msg = "{} not found amongst mandatory parameters ({})".format(param_key,params.keys())
raise Exception(msg)
# --- input or default values of optional parameters
params = params_optional
for parameter_key in parameters["OPTIONAL"]:
params[parameter_key] = parameters["OPTIONAL"][parameter_key]
for param_key in params:
if param_key in selected_parameters:
raw_value = selected_parameters[param_key]
type_conv = params[param_key][0]
else:
raw_value = params[param_key][1]
type_conv = params[param_key][0]
if type_conv==float:
value = float(raw_value)
elif type_conv==int:
value = int(raw_value)
else:
value = raw_value
dico_param[param_key] = value
return dico_param
def name2coord(self, *args):
found = 0
ra = 0
dec = 0
# ========= valid *args
argc = len(args)
name0 = ""
if (argc==0):
return found, ra, dec
else:
name0 = args[0].lower()
cwd = os.getcwd()
# --- star names
if found==0:
name0 = args[0].lower()
filename = cwd + "/catalogues/catagoto/etoiles_brillantes.txt"
#print("filename={}".format(filename))
with open(filename, 'r', errors='surrogateescape', newline='') as fid:
lignes = fid.read()
lignes = lignes.split("\n")
for ligne in lignes:
#print("{}".format(ligne))
name = ligne[0:21].strip().lower()
if name0==name:
found = 1
if found==0:
name = ligne[21:36].strip().lower()
if name0==name:
found = 1
if found==1:
#print("name0={} name={}".format(name0,name))
#print("ligne={}".format(ligne))
ra = ligne[36:38]+"h"+ligne[39:41]+"m"+ligne[42:47]+"s"
dec = ligne[52:55]+"d"+ligne[56:58]+"m"+ligne[59:63]+"s"
break
# --- Messier
if found==0:
name0 = args[0].upper()
filename = cwd + "/catalogues/catagoto/cat_messier.txt"
#print("filename={}".format(filename))
with open(filename, 'r', errors='surrogateescape', newline='') as fid:
lignes = fid.read()
lignes = lignes.split("\n")
for ligne in lignes:
#print("{}".format(ligne))
lligne = ligne.split()
if len(lligne)==0:
continue
name = lligne[0].strip().upper()
if name0==name:
found = 1
ra = lligne[1]+"h"+lligne[2]+"m"
dec = lligne[3]+"d"+lligne[4]+"m"
break
# --- NGC
if found==0:
name0 = args[0].upper()
filename = cwd + "/catalogues/catagoto/cat_ngc.txt"
#print("filename={}".format(filename))
with open(filename, 'r', errors='surrogateescape', newline='') as fid:
lignes = fid.read()
lignes = lignes.split("\n")
for ligne in lignes:
#print("{}".format(ligne))
lligne = ligne.split()
if len(lligne)==0:
continue
name = lligne[0].strip().upper()
if name0==name:
found = 1
ra = lligne[1]+"h"+lligne[2]+"m"
dec = lligne[3]+"d"+lligne[4]+"m"
break
# --- IC
if found==0:
name0 = args[0].upper()
filename = cwd + "/catalogues/catagoto/cat_ic.txt"
#print("filename={}".format(filename))
with open(filename, 'r', errors='surrogateescape', newline='') as fid:
lignes = fid.read()
lignes = lignes.split("\n")
for ligne in lignes:
#print("{}".format(ligne))
lligne = ligne.split()
name = lligne[0].strip().upper()
if len(lligne)==0:
continue
if name0==name:
found = 1
ra = lligne[1]+"h"+lligne[2]+"m"
dec = lligne[3]+"d"+lligne[4]+"m"
break
return found, ra, dec
def get_available_serial_ports(self):
"""
Return a list of available serial ports of the local computer
"""
# --
prefix_myserial_ports = ""
if sys.platform.startswith('win'):
prefix_myserial_ports = "//./"
elif sys.platform.startswith('linux') or sys.platform.startswith('cygwin'):
prefix_myserial_ports = ""
elif sys.platform.startswith('darwin'):
prefix_myserial_ports = ""
# --
serial_ports = serial.tools.list_ports.comports(include_links=False)
# --
available_serial_ports = []
for serial_port in serial_ports:
available_serial_port = prefix_myserial_ports + serial_port.device
available_serial_ports.append(available_serial_port)
return available_serial_ports
def vo_simbad(self, ident):
"""
Return ra,dec,J2000 according an object name using SImbad server
"""
found = 0
ident = ident.replace(" ","+")
url = "http://simbad.u-strasbg.fr/simbad/sim-basic?Ident={}&submit=SIMBAD+search".format(ident)
res = requests.get(url, timeout = 10)
if res.ok==False:
return {}
texte = res.text
k1 = texte.find("ICRS")
texte = texte[k1:]
ltexte = texte.split("\n")
if len(ltexte)>11:
radec = ltexte[11]
radecs = radec.split()
ra = radecs[0]+"h"+radecs[1]+"m"+"{:.3f}".format(float(radecs[2]))+"s"
dec = radecs[3]+"d"+radecs[4]+"m"+"{:.2f}".format(float(radecs[5]))+"s"
#cra = celme.Angle(ra).deg()
#cdec = celme.Angle(dec).deg()
found = 1
else:
ra = 0
dec = 0
return found, ra, dec
# #####################################################################
# #####################################################################
# #####################################################################
# Main
# #####################################################################
# #####################################################################
# #####################################################################
if __name__ == "__main__":
example = 5
print("Example = {}".format(example))
if example == 1:
def decode_test(**kwargs):
tools = Mounttools()
# --- Dicos of optional and mandatory parameters
params_optional = {}
params_optional["OUT_UNIT"] = (str,'m')
params_mandatory = {}
params_mandatory["VALUE"] = (float,1.0)
params_mandatory["INP_UNIT"] = (str,'m')
# --- Decode kwarg parameters
params = tools.decode_kwargs(params_optional, params_mandatory, **kwargs)
return params
# -- Now we call the function with default optional keys
params = decode_test(value=3.6, inp_unit="cm")
print("(1) params={}".format(params))
# -- Now we call the function with personal optional keys
params = decode_test(value=3.6, inp_unit="cm", out_unit="km")
print("(2) params={}".format(params))
if example == 2:
def decode_test(*args, **kwargs):
tools = Mounttools()
# --- Dicos of optional and mandatory parameters
#kwargc = len(kwargs)
#print("2.*args={} argc={}".format(args,argc))
#print("2.**kwargs={} kwargc={}".format(kwargs,kwargc))
# ========= Definition of motion_types
# --- Dico of motion types and their parameters
motion_types = {}
motion_types["OFFSET"] = {"MANDATORY" : {"OFFSET":[float,1.0], "VELOCITY":[float,1.0]}, "OPTIONAL" : {"DRIFT":[float,0.0]} }
motion_types["ABSOLUTE"] = {"MANDATORY" : {"POSITION":[float,0.0], "VELOCITY":[float,1.0]}, "OPTIONAL" : {"DRIFT":[float,0.0]} }
motion_types["CONTINUOUS"] = {"MANDATORY" : {"DRIFT":[float,0.0]}, "OPTIONAL" : {} }
# --- Dico of optional parameters for all motion types
params_optional = {"FRAME":(str,'inc')}
# --- Decode args and kwargs parameters
params = tools.decode_args_kwargs(0, motion_types, params_optional, *args, **kwargs)
return params
# -- Now we call the function with default optional keys
params = decode_test("absolute", position=130, velocity=-1.4)
print("(1) params={}".format(params))
if example == 3:
tools = Mounttools()
res = tools.name2coord("vega")
print("res={}".format(res))
if example == 4:
tools = Mounttools()
res = tools.get_available_serial_ports()
print("Available serial ports are {}".format(res))
if example == 5:
tools = Mounttools()
res = tools.vo_simbad("Messier 12")
print("res={}".format(res))