-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathMVPtoolkit.py
1633 lines (1453 loc) · 77.4 KB
/
MVPtoolkit.py
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
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
print('starting ...')
import requests
import jdcal
import datetime
import numpy as np
import matplotlib.pyplot as plt
import telnetlib
import re
import os
from pprint import pprint
from mpl_toolkits.mplot3d import Axes3D
from mpl_toolkits.mplot3d.proj3d import proj_transform
from matplotlib.text import Annotation
from matplotlib import colors
from matplotlib import pyplot as plt
import matplotlib.dates as mdates
from matplotlib.ticker import LinearLocator
from pathlib import Path
import pickle
try:
import tkinter
from tkinter.colorchooser import *
from tkinter import ttk
from tkcalendar import DateEntry,Calendar
from tkinter import filedialog
except:
import Tkinter
from Tkinter.colorchooser import *
from Tkinter import ttk
from tkcalendar import DateEntry,Calendar
from Tkinter import filedialog
import operator
import csv
import configparser,ast
pykep_installed = True
try:
from pykep import lambert_problem, ic2par
# import somethingwhichdoescertainlynotexist
except:
pykep_installed = False
from matplotlib.backends.backend_tkagg import FigureCanvasTkAgg, NavigationToolbar2Tk
from matplotlib.ticker import ScalarFormatter
# Implement the appearance Matplotlib key bindings.
from matplotlib.backend_bases import key_press_handler
#fix for freezing needs multiprocessing freeze support:
import multiprocessing
#all the menues for tools and other things
from ToplevelMenues import preference_menu_toplevel, about_popup_toplevel, porkchop_menu_toplevel, lambert_menu_toplevel, distance_menu_toplevel, custom_object_menu_toplevel, artist_menu_toplevel
class celestial_artist:
def __init__(self,id,orbit,pos,date,name,text,keplers):
self.id = id
self.orbit_artist = None
self.position_artist = None
self.annotation_artist = None
self.orbit = orbit
self.pos = pos
self.date = date
self.color = None
self.name = name
self.displayname = name
self.info_text = text
self.moon = False
self.center_body = [0,0,0] #sun in this referencesystem
self.keplers = keplers
class Annotation3D(Annotation):
'''Annotate the point xyz with text s'''
def __init__(self, s, xyz, *args, **kwargs):
Annotation.__init__(self,s, xy=(0,0), *args, **kwargs)
self._verts3d = xyz
def draw(self, renderer):
xs3d, ys3d, zs3d = self._verts3d
xs, ys, zs = proj_transform(xs3d, ys3d, zs3d, renderer.M)
self.xy=(xs,ys)
Annotation.draw(self, renderer)
class MVP_application:
def __init__(self, master,pykep_installed):
self.master = master
self.master.withdraw()
#check if OS is windows or not
if os.name == 'nt':
self.is_Windows = True
else:
self.is_Windows = False
self.pykep_installed = pykep_installed
self.AUinKM = 149597870.691 #km/AU
self.G = 6.673e-20 / np.power(self.AUinKM,3) #km³/kg*s²
self.GM_sun = 1.3271244018e11 / np.power(self.AUinKM,3) #AU³ /s²
self.M_sun = self.GM_sun / self.G
self.GM_sun = self.GM_sun.tolist()
self.index = 0
self.kepler_dict = {}
self.planet_positions = []
self.position_coordinates = []
self.HOST = 'horizons.jpl.nasa.gov'
self.port = '6775'
self.filename = 'DBNumbers'
self.filename2 = 'smallbodies'
self.cursor = 'tcross'
self.turn_cursor = 'exchange'
self.zoom_cursor = 'sizing'
self.JPL_numbers = []
self.orbit_colors = []
self.equinox_artists = []
self.list = []
self.current_objects = []
self.sun = celestial_artist(0,None,[0,0,0],None,'sun','sun',None)
self.current_center_object = self.sun
#variables for porkchop menu
self.pulse_direction_var = tkinter.StringVar()
self.pulse_direction_var.set('prograde')
self.porkchop_radiobuttons = []
self.dV_var = tkinter.StringVar()
self.dV_var.set('launch')
#license
with open('LICENSE','r') as f:
self.license_text = f.read()
self.version = 'v0.5.2w'
self.default_colors = ['#191919','#7f7f7f','#ffffff','#000000']
self.resolution = 1600
self.set_default_colors()
self.gridlinewidth = 0.2
self.textsize = 8
self.markersize = 7
self.orbit_linewidth = 1
self.refplane_linewidth = 0.3
self.text_xoffset = 0
self.text_yoffset = 4
self.destroy_was_called = False
self.cancel_was_pushed = False
self.check_config()
self.valid_format_list = ['png','jpeg', 'jpg', 'svg', 'pdf', 'pgf', 'ps', 'raw', 'rgba', 'eps', 'svgz', 'tif', 'tiff']
self.valid_formats = [('','*.'+format) for format in self.valid_format_list]
self.view_cid = None
self.formatter = ScalarFormatter(useMathText=True,useOffset=True)
self.dt = datetime.datetime.now()
self.dates = []
self.julian_date = "'" + str(sum(jdcal.gcal2jd(self.dt.year, self.dt.month, self.dt.day))) + "'"
self.order_of_keplers = ['eccentricity','periapsis_distance','inclination','Omega','omega','Tp','n','mean_anomaly','true_anomaly','a','apoapsis_distance','sidereal_period']
self.objects = ["'399'","'499'","'-143205'"] #earth,mars,Tesla roadster, ... ceres : ,"'5993'"
self.batchfile = {"COMMAND": "'399'","CENTER": "'500@10'","MAKE_EPHEM": "'YES'","TABLE_TYPE": "'ELEMENTS'","TLIST":self.julian_date,"OUT_UNITS": "'AU-D'","REF_PLANE": "'ECLIPTIC'","REF_SYSTEM": "'J2000'","TP_TYPE": "'ABSOLUTE'","ELEM_LABELS": "'YES'","CSV_FORMAT": "'YES'","OBJ_DATA": "'YES'"}
self.batchfile_timerange = {"COMMAND": "'399'","CENTER": "'500@10'","MAKE_EPHEM": "'YES'","TABLE_TYPE": "'VECTORS'","START_TIME": '',"STOP_TIME": '',"STEP_SIZE": '1 d',"OUT_UNITS": "'AU-D'","REF_PLANE": "'ECLIPTIC'","REF_SYSTEM": "'J2000'","VECT_CORR":"'NONE'","VEC_LABELS": "'NO'","VEC_DELTA_T": "'NO'","CSV_FORMAT": "'YES'","OBJ_DATA": "'NO'","VEC_TABLE": "'2'"}
self.my_file = Path("./"+self.filename+'.pkl')
self.my_file2 = Path("./"+self.filename2+'.csv')
self.search_term = tkinter.StringVar()
self.search_term.set('')
self.search_term.trace("w", lambda name, index, mode: self.update_listbox())
self.prog_var = tkinter.DoubleVar(value = 0)
self.check_db()
self.fig = plt.figure(facecolor = self.custom_color)
self.fig.subplots_adjust(left=0.01, right=0.99, bottom=0.01, top=0.99)
self.master.wm_title("MVP toolkit - Mission Visualisation and Planning")
self.notebook_frame = ttk.Frame(self.master,borderwidth=2)
self.notebook_frame.grid(row=0,column=0,columnspan=10,rowspan=12,sticky=tkinter.N+tkinter.W+tkinter.E+tkinter.S)
self.notebook_frame.columnconfigure(0,weight=1)
self.notebook_frame.rowconfigure(0,weight=1)
self.notebook = ttk.Notebook(self.notebook_frame)
self.canvas_frame = ttk.Frame(self.notebook)
self.canvas_frame.grid(row=0,column=0,columnspan=10,rowspan=12,sticky=tkinter.N+tkinter.W+tkinter.E+tkinter.S)
self.canvas_frame.rowconfigure(0, weight=1)
self.canvas_frame.columnconfigure(0, weight=1)
self.canvas = FigureCanvasTkAgg(self.fig, master=self.canvas_frame) # A tk.DrawingArea.
self.notebook.add(self.canvas_frame,text="orbits")
self.porkchop_frames = []
self.notebook.grid(row=0,column=0,sticky=tkinter.N+tkinter.W+tkinter.E+tkinter.S)
self.notebook.columnconfigure(0,weight=1)
self.notebook.rowconfigure(0,weight=1)
self.pick_event_cid = self.fig.canvas.mpl_connect('pick_event',self.clicked_on)
self.canvas.get_tk_widget().bind('<ButtonPress-1>',self.canvas_mouseturn,add='+')
self.canvas.get_tk_widget().bind('<ButtonPress-3>',self.canvas_mousezoom,add='+')
self.canvas.get_tk_widget().bind('<ButtonRelease-3>',self.canvas_mouserelease,add='+')
self.canvas.get_tk_widget().bind('<ButtonRelease-1>',self.canvas_mouserelease,add='+')
self.canvas.get_tk_widget().config(cursor=self.cursor)
plt.rcParams['savefig.facecolor']= 'w'
plt.rcParams['grid.color'] = self.gridcolor
plt.rcParams['grid.linewidth'] = self.gridlinewidth
self.ax = self.fig.gca(projection = '3d',facecolor = self.custom_color,proj_type = 'ortho')
self.canvas.get_tk_widget().grid(row=0,column=0,sticky=tkinter.N+tkinter.W+tkinter.E+tkinter.S)
self.viewbuttons_frame = tkinter.Frame(master= self.canvas.get_tk_widget())
self.viewbuttons_frame.place(rely=1,relx=0,anchor=tkinter.SW)
# self.equinox_cid = self.ax.callbacks.connect('xlim_changed',self.scale_equinox)
self.menubar = tkinter.Menu(self.master)
self.filemenu = tkinter.Menu(self.menubar,tearoff = 0)
self.filemenu.add_command(label="export figure as", command=self.save_file_as)
self.filemenu.add_command(label="save plot", command=self.save_object_list)
self.filemenu.add_command(label="load plot", command=self.load_object_list)
self.filemenu.add_command(label="preferences", command=self.call_preferences_menu)
self.filemenu.add_separator()
self.filemenu.add_command(label="Exit", command=self.master.quit)
self.tools_menu = tkinter.Menu(self.menubar,tearoff = 0)
self.tools_menu.add_command(label='calculate rendezvous (lambert solver)', command=self.call_lambert_menue)
self.tools_menu.add_command(label='generate porkchop-plot', command=self.call_porkchop_menu)
self.tools_menu.add_command(label='add custom object', command=self.call_custom_object_menu)
self.tools_menu.add_command(label='plot linear distance over time', command=self.call_distance_menu)
self.about_menu = tkinter.Menu(self.menubar,tearoff = 0)
self.about_menu.add_command(label= 'about', command = self.call_about_popup)
self.menubar.add_cascade(label='file',menu=self.filemenu)
self.menubar.add_cascade(label='tools',menu=self.tools_menu)
self.menubar.add_cascade(label='about', menu = self.about_menu)
self.master.config(menu=self.menubar)
self.button1 = tkinter.Button(master=self.master, text="new Plot", command=lambda : self.refresh_plot(True))
self.button1.grid(row=3,column=11,columnspan=2,sticky=tkinter.N+tkinter.W+tkinter.E)
self.button2 = tkinter.Button(master=self.master, text="add to Plot", command=lambda : self.refresh_plot(False))
self.button2.grid(row=4,column=11,columnspan=2,sticky=tkinter.N+tkinter.W+tkinter.E)
self.topview_button = tkinter.Button(master=self.viewbuttons_frame,text='TOP',borderwidth = 3, command=lambda:self.change_view('top'))
self.topview_button.configure(width=3,height=1)
self.topview_button.grid(row=0,column=0)
self.rightview_button = tkinter.Button(master=self.viewbuttons_frame,text='XZ',borderwidth = 3, command=lambda:self.change_view('XZ'))
self.rightview_button.configure(width=3,height=1)
self.rightview_button.grid(row=0,column=1)
self.xyzview_button = tkinter.Button(master=self.viewbuttons_frame,text='XYZ',borderwidth = 3,command=lambda:self.change_view('XYZ'))
self.xyzview_button.configure(width=3,height=1)
self.xyzview_button.grid(row=0,column=3)
self.sun_button = tkinter.Button(master=self.viewbuttons_frame,text='sun',borderwidth = 3,command=lambda:self.set_camera_center([0,0,0]))
self.sun_button.configure(width=3,height=1)
self.sun_button.grid(row=0,column=4)
self.listbox = tkinter.Listbox(master=self.master,selectmode=tkinter.MULTIPLE,exportselection=False)
self.listbox.grid(row=0,column=11,columnspan=2,sticky=tkinter.N+tkinter.W+tkinter.E+tkinter.S)
tkinter.Label(master=self.master,text= 'type search term:').grid(row=1,column=11,sticky=tkinter.N+tkinter.W)
self.search_box = tkinter.Entry(master=self.master, textvariable=self.search_term)
self.search_box.grid(row=1,column=12,sticky=tkinter.N+tkinter.W)
self.calendar_widget = Calendar(self.master,font="Arial 18", selectmode='day',cursor="hand1", year=self.dt.year, month=self.dt.month, day=self.dt.day)
self.calendar_widget.grid(row=5,column=11,columnspan=2,sticky=tkinter.N+tkinter.W+tkinter.E+tkinter.S)
self.refplane_var = tkinter.IntVar(value=0)
self.annot_var = tkinter.IntVar(value=0)
self.axis_var = tkinter.IntVar(value=1)
self.proj_var = tkinter.IntVar(value=0)
self.refplane_checkbutton = tkinter.Checkbutton(master=self.master,text='referenceplane lines',variable = self.refplane_var,command=self.redraw_current_objects).grid(row=6,column=11,sticky=tkinter.N+tkinter.W)
self.annot_checkbutton = tkinter.Checkbutton(master=self.master,text='show date at objectposition',variable = self.annot_var,command=self.redraw_current_objects).grid(row=6,column=12,sticky=tkinter.N+tkinter.W)
self.axis_checkbutton = tkinter.Checkbutton(master=self.master,text='show coordinate axis',variable = self.axis_var,command=self.toggle_axis).grid(row=7,column=11,sticky=tkinter.N+tkinter.W)
self.proj_checkbutton = tkinter.Checkbutton(master=self.master,text='perspective projection',variable = self.proj_var,command=self.toggle_proj).grid(row=7,column=12,sticky=tkinter.N+tkinter.W)
self.prog_bar_frame = tkinter.Frame(self.master,)
self.prog_bar = tkinter.ttk.Progressbar(self.prog_bar_frame,orient='horizontal',length=200,mode='determinate')
self.prog_bar.pack(side=tkinter.LEFT,expand=True,fill=tkinter.X)
self.prog_bar_cancel_button = tkinter.Button(self.prog_bar_frame,text='cancel',command=self.cancel_current_task,state=tkinter.DISABLED)
self.prog_bar_cancel_button.pack(side=tkinter.RIGHT,anchor = tkinter.E)
self.prog_bar_frame.grid(row=8,column=11,columnspan=2,sticky=tkinter.S+tkinter.W+tkinter.E)
for k,v in self.JPL_numbers.items():
self.listbox.insert(tkinter.END,v)
self.canvas.draw()
self.master.deiconify()
self.nu = np.linspace(0,2*np.pi,self.resolution)
orbits,positions = self.request_keplers(self.objects,self.batchfile)
if orbits == False:
pass
else:
# self.current_objects = {'orbits':orbits,'positions':positions}
self.plot_orbits(self.ax,self.current_objects,refresh_canvas=True,refplane_var=self.refplane_var.get())
# self.current_objects['dates'] = dates
# self.current_objects['colors'] = colors
# self.current_objects['artists'] = artists
self.master.protocol("WM_DELETE_WINDOW", self.on_closing)
def cancel_current_task(self):
self.cancel_was_pushed = True
def call_about_popup(self):
about_popup = about_popup_toplevel(self)
def set_default_colors(self,redraw=False,buttons=None):
'''sets colors to default, if buttons handed over: colors them accordingly'''
self.custom_color = self.default_colors[0]
self.gridcolor = self.default_colors[1]
self.text_color = self.default_colors[2]
self.pane_color = self.default_colors[3]
if redraw:
self.redraw_current_objects()
counter = 0
for b in buttons:
b.configure(bg=self.default_colors[counter])
counter = counter + 1
def check_config(self):
'''check if config exists, makes default config if not'''
if self.is_Windows:
file = os.getenv('APPDATA')
file = file + r"\MVPtoolkit\config.ini"
print(file)
config = configparser.ConfigParser()
if os.path.exists(file):
print(r'config found, reading from ~APPDATA~\config.ini')
config.read(file)
self.custom_color = config['appearance']['custom_color']
self.gridcolor = config['appearance']['gridcolor']
self.text_color = config['appearance']['text_color']
self.pane_color = config['appearance']['pane_color']
self.gridlinewidth = float(config['appearance']['gridlinewidth'])
self.textsize = float(config['appearance']['textsize'])
self.markersize = float(config['appearance']['markersize'])
self.orbit_linewidth = float(config['appearance']['orbit_linewidth'])
self.refplane_linewidth = float(config['appearance']['refplane_linewidth'])
self.text_xoffset = float(config['appearance']['text_xoffset'])
self.text_yoffset = float(config['appearance']['text_yoffset'])
else:
print(r'no config found, generating new ~APPDATA~\config.ini')
self.update_config()
else:
file = Path("./config.ini")
config = configparser.ConfigParser()
if file.is_file():
print('config found, reading from ./config.ini')
config.read('config.ini')
self.custom_color = config['appearance']['custom_color']
self.gridcolor = config['appearance']['gridcolor']
self.text_color = config['appearance']['text_color']
self.pane_color = config['appearance']['pane_color']
self.gridlinewidth = float(config['appearance']['gridlinewidth'])
self.textsize = float(config['appearance']['textsize'])
self.markersize = float(config['appearance']['markersize'])
self.orbit_linewidth = float(config['appearance']['orbit_linewidth'])
self.refplane_linewidth = float(config['appearance']['refplane_linewidth'])
self.text_xoffset = float(config['appearance']['text_xoffset'])
self.text_yoffset = float(config['appearance']['text_yoffset'])
else:
print('no config found, generating new ./config.ini')
self.update_config()
def update_config(self):
'''update configfile with current memory variables'''
config = configparser.ConfigParser()
config['appearance'] = \
{\
'custom_color':str(self.custom_color), 'gridcolor':str(self.gridcolor),\
'gridlinewidth':str(self.gridlinewidth), 'textsize':str(self.textsize), 'markersize':str(self.markersize),\
'orbit_linewidth':str(self.orbit_linewidth), 'refplane_linewidth':str(self.refplane_linewidth),\
'text_xoffset':str(self.text_xoffset), 'text_yoffset':str(self.text_yoffset), 'text_color':str(self.text_color),\
'pane_color':str(self.pane_color)
}
if self.is_Windows:
dir = os.getenv('APPDATA')
file = dir+ r"\MVPtoolkit\config.ini"
if not os.path.exists(os.path.dirname(file)):
os.makedirs(os.path.dirname(file))
with open(file, 'w') as configfile:
config.write(configfile)
else:
with open('config.ini', 'w') as configfile:
config.write(configfile)
def canvas_mouseturn(self,event):
self.canvas.get_tk_widget().config(cursor=self.turn_cursor)
def canvas_mousezoom(self,event):
self.canvas.get_tk_widget().config(cursor=self.zoom_cursor)
def canvas_mouserelease(self,event):
self.canvas.get_tk_widget().config(cursor=self.cursor)
def hex_to_rgb(self,h,alpha=1):
'''takes hex color code and returns rgb-alpha tuple'''
try:
h = h.strip('#')
except:
return h
h = tuple(int(h[i:i+2], 16) for i in (0, 2 ,4))
h = (h[0]/255,h[1]/255,h[2]/255,alpha)
return h
def save_file_as(self):
'''saves figure (currently redraws figure and toggles visibility of axis to true)'''
dir = filedialog.asksaveasfilename(defaultextension=".png", filetypes = self.valid_formats)
if dir == '' or dir == ():
return
self.fig.canvas.mpl_disconnect(self.view_cid)
plt.sca(self.ax)
try:
plt.savefig(dir,facecolor=self.custom_color)
print(dir)
except ValueError:
self.error_message('unsupported format','Supported formats are :\n {0}'.format( str(self.valid_format_list).strip('[').strip(']') ))
# self.axis_visibility(None,'z',True)
# self.axis_visibility(None,'y',True)
'''does weird stuff with the image (artifacts)'''
# ps = self.canvas.get_tk_widget().postscript(colormode='color')
# img = Image.open(io.BytesIO(ps.encode('utf-8')))
# img.save(dir)
def save_object_list(self):
dir = filedialog.asksaveasfilename(filetypes = [("pickle files","*.pckl")])
if dir == '' or dir == ():
return
self.save_obj(self.current_objects,dir=dir)
def load_object_list(self):
dir = filedialog.askopenfilename(filetypes = [("pickle files","*.pckl")])
if dir == '' or dir == ():
return
self.current_objects = self.load_obj(dir=dir)
self.redraw_current_objects()
def get_color(self,b,parent):
color=askcolor(b.cget('bg'),parent=parent)
print(color)
if None in color:
return
b.configure(bg=color[1])
def call_preferences_menu(self):
'''call toplevel menu to adjust config file'''
preference_menu = preference_menu_toplevel(self)
def update_config_vars(self,custom_color_button,grid_color_button,text_color_button,pane_color_button,textsize_var):
'''get colors of preference buttons, update config file and redraw figure with new colors'''
self.custom_color = custom_color_button.cget('bg')
self.gridcolor = grid_color_button.cget('bg')
self.text_color = text_color_button.cget('bg')
self.pane_color = pane_color_button.cget('bg')
self.textsize = float(textsize_var)
self.update_config()
self.redraw_current_objects()
def annotate3D(self,ax, s, *args, **kwargs):
'''add anotation text s to to Axes3d ax'''
tag = Annotation3D(s, *args, **kwargs)
ax.add_artist(tag)
return tag
def rot_x(self,phi):
'''returns rotational matrix around x, phi in rad'''
return np.array([[1,0,0],[0,np.cos(phi),-np.sin(phi)],[0,np.sin(phi),np.cos(phi)]])
def rot_z(self,rho):
'''returns rotational matrix around z, rho in rad'''
return np.array([[np.cos(rho),-np.sin(rho),0],[np.sin(rho),np.cos(rho),0],[0,0,1]])
def change_view(self,view):
'''sets the view angles of the plot and toggles visibility of the perpendicular axis to False until plot is moved/refreshed '''
if view == "top":
self.axis_visibility(event = None,axis='z',visible=False) #produces clicking on artist beeing unresponsive
self.ax.view_init(90,-90)
self.view_cid = self.fig.canvas.mpl_connect('draw_event',lambda event: self.axis_visibility(event,axis='z',visible=True))
elif view == "XZ":
self.axis_visibility(event = None,axis='y',visible=False) #produces clicking on artist beeing unresponsives
self.ax.view_init(0,-90)
self.view_cid = self.fig.canvas.mpl_connect('draw_event',lambda event: self.axis_visibility(event,axis='y',visible=True))
elif view == "XYZ":
self.ax.view_init(45,-45)
self.canvas.draw()
def axis_visibility(self,event,axis,visible):
if axis == 'z':
self.ax.set_zticklabels(self.ax.get_zticklabels(),visible=visible)
self.ax.set_zlabel(self.ax.get_zlabel(),visible=visible)
# if visible:
# self.ax.tick_params(axis='z', colors=self.text_color)
# else:
# self.ax.tick_params(axis='z', colors=self.custom_color)
elif axis == 'y':
self.ax.set_yticklabels(self.ax.get_yticklabels(),visible=visible)
self.ax.set_ylabel(self.ax.get_ylabel(),visible=visible)
elif axis == 'x':
self.ax.set_xticklabels(self.ax.get_xticklabels(),visible=visible)
self.ax.set_xlabel(self.ax.get_xlabel(),visible=visible)
if self.view_cid != None:
self.fig.canvas.mpl_disconnect(self.view_cid)
def scale_equinox(self,event):
'''function to draw a scaling vector-arrow on the x-axis(equinox)'''
self.fig.canvas.mpl_disconnect(self.equinox_cid)
if len(self.equinox_artists)>0:
for i in range(0,len(self.equinox_artists)):
if i == 3:
self.equinox_artists[i].remove()
continue
self.equinox_artists[i][0].remove()
self.equinox_artists = []
xlim = self.ax.get_xlim()
length = 0.15 *xlim[1]
self.equinox_artists.append(self.ax.plot([0,length] , [0,0],[0,0],color=self.text_color,linewidth=self.refplane_linewidth))
self.equinox_artists.append(self.ax.plot([length,0.7*length],[0,0.05*length],[0,0.05*length],color=self.text_color,linewidth=self.refplane_linewidth))
self.equinox_artists.append(self.ax.plot([length,0.7*length],[0,-0.05*length],[0,-0.05*length],color=self.text_color,linewidth=self.refplane_linewidth))
self.equinox_artists.append(self.annotate3D(self.ax, s='vernal equinox', xyz=[length,0,0], fontsize=self.textsize, xytext=(self.text_xoffset,-self.text_yoffset),textcoords='offset points', ha='center',va='top',color = self.text_color))
self.equinox_cid = self.ax.callbacks.connect('xlim_changed',self.scale_equinox)
def orbit_position(self,a,e,Omega,i,omega,true_anomaly=False,comp_true_anomaly=False):
'''calculate orbit 3x1 radius vector'''
if not(true_anomaly==False):
p = a * (1-(e**2))
r = p/(1+e*np.cos(true_anomaly))
r = np.array([np.multiply(r,np.cos(true_anomaly)) , np.multiply(r,np.sin(true_anomaly)), np.zeros(len(true_anomaly))])
r = np.matmul(self.rot_z(omega),r)
r = np.matmul(self.rot_x(i),r)
r = np.matmul(self.rot_z(Omega),r)
elif e <=1:
# e = 1 atually wrong, here just to prevent crash, exact eccentricity of 1 should not happen
p = a * (1-(e**2))
r = p/(1+e*np.cos(self.nu))
r = np.array([np.multiply(r,np.cos(self.nu)) , np.multiply(r,np.sin(self.nu)), np.zeros(len(self.nu))])
r = np.matmul(self.rot_z(omega),r)
r = np.matmul(self.rot_x(i),r)
r = np.matmul(self.rot_z(Omega),r)
elif e >1:
# if comp_true_anomaly > 2:
# print('first case')
# plot_range = 3*np.pi/4
# if plot_range <= np.abs(comp_true_anomaly):
# plot_range = np.abs(comp_true_anomaly)
# else:
# print('second case')
# plot_range = 3/4 * np.pi -np.pi
# if plot_range > np.abs(comp_true_anomaly):
# plot_range = np.abs(comp_true_anomaly)
if comp_true_anomaly >= 3*np.pi/4:
if comp_true_anomaly > np.pi:
plot_range = np.abs(comp_true_anomaly - 2*np.pi)
# plot_range = np.arccos(-1/e)
else:
plot_range = comp_true_anomaly
else:
plot_range = 3*np.pi/4
nu = np.linspace(-plot_range,plot_range,self.resolution)
p = a * (1-(e**2))
r = p/(1+e*np.cos(nu))
r = np.array([np.multiply(r,np.cos(nu)) , np.multiply(r,np.sin(nu)), np.zeros(len(nu))])
r = np.matmul(self.rot_z(omega),r)
r = np.matmul(self.rot_x(i),r)
r = np.matmul(self.rot_z(Omega),r)
return r
def axisEqual3D(self,ax):
'''fix for axis equal bug in 3D (z wont equal)'''
extents = np.array([getattr(ax, 'get_{}lim'.format(dim))() for dim in 'xyz'])
sz = extents[:,1] - extents[:,0]
centers = np.mean(extents, axis=1)
maxsize = max(abs(sz))
r = maxsize/2
for ctr, dim in zip(centers, 'xyz'):
getattr(ax, 'set_{}lim'.format(dim))(ctr - r, ctr + r)
def save_obj(self,obj, name=None, dir = None ):
if dir == None:
with open('./' + name + '.pkl', 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
else:
with open(dir , 'wb') as f:
pickle.dump(obj, f, pickle.HIGHEST_PROTOCOL)
def load_obj(self,name=None, dir = None):
if dir == None:
with open('./' + name + '.pkl', 'rb') as f:
return pickle.load(f)
else:
with open(dir , 'rb') as f:
return pickle.load(f)
def _quit(self):
self.master.destroy() # stops mainloop
# root.destroy() # this is necessary on Windows to prevent
# Fatal Python Error: PyEval_RestoreThread: NULL tstate
def sort_vals(self,dictionary):
'''sort dictionary values'''
sorted_x = sorted(dictionary.items(), key=operator.itemgetter(1))
return dict(sorted_x)
def get_selected(self):
'''get selected items from listbox'''
user_choice = []
index_list = map(int,self.listbox.curselection())
for i in index_list:
user_choice.append(self.listbox.get(i))
return user_choice
def refresh_plot(self,clear_axis = True):
'''new plot, dismisses existing objects if clear_axis == True'''
print('refreshing')
if clear_axis:
self.current_objects = []
self.objects = []
objects = self.get_selected()
objects = [self.JPL_name2num[object] for object in objects]
self.objects.extend(objects)
orbits,positions = self.request_keplers(objects,self.batchfile)
self.prog_bar_cancel_button['state'] = tkinter.DISABLED
if orbits == False:
pass
else:
self.plot_orbits(self.ax,self.current_objects,refresh_canvas = True,refplane_var=self.refplane_var.get())
def shade_hex_color(self,hexcolor,shade_value=0.4):
''' shade a hex color by shade_value
(shade_value is the perecntage of the input color to shade)
'''
RGB = self.hex_to_rgb(hexcolor)
R = int(RGB[0]*255 - shade_value*RGB[0]*255)
G = int(RGB[1]*255 - shade_value*RGB[1]*255)
B = int(RGB[2]*255 - shade_value*RGB[2]*255)
hexR = R.to_bytes(((R.bit_length() + 7) // 8),"big").hex()
hexG = G.to_bytes(((G.bit_length() + 7) // 8),"big").hex()
hexB = B.to_bytes(((B.bit_length() + 7) // 8),"big").hex()
shaded_color = '#{0}{1}{2}'.format(hexR,hexG,hexB)
return shaded_color
def plot_orbits(self,ax,objects,refresh_canvas=True,refplane_var = 1):
'''plots orbits, positions and annotations'''
self.ax.cla()
# plt.rcParams['savefig.facecolor']= self.custom_color
plt.rcParams['grid.color'] = self.gridcolor
plt.rcParams['grid.linewidth'] = self.gridlinewidth
self.fig.set(facecolor = self.custom_color)
self.ax.set(facecolor = self.custom_color)
ax.scatter(0,0,0,marker='o',s = 20,color='yellow')
self.annotate3D(ax, s='sun', xyz=[0,0,0], fontsize=self.textsize, xytext=(self.text_xoffset,self.text_yoffset),textcoords='offset points', ha='center',va='bottom',color ="white")
ax.set_xlabel('X axis in AU')
ax.set_ylabel('Y axis in AU')
ax.set_zlabel('Z axis in AU')
ax.xaxis.label.set_color(self.text_color)
ax.yaxis.label.set_color(self.text_color)
ax.zaxis.label.set_color(self.text_color)
ax.tick_params(axis='x', colors=self.text_color)
ax.tick_params(axis='y', colors=self.text_color)
ax.tick_params(axis='z', colors=self.text_color)
ax.w_xaxis.set_pane_color(self.hex_to_rgb(self.pane_color))
ax.w_yaxis.set_pane_color(self.hex_to_rgb(self.pane_color))
ax.w_zaxis.set_pane_color(self.hex_to_rgb(self.pane_color))
for object in objects:
if None in object.orbit:
continue
orbit = object.orbit
pos = object.pos
object.orbit_artist= []
if object.moon:
threshold = object.center_body[2]
else:
threshold = 0
orbit_pos = np.array(orbit)
orbit_neg = np.array(orbit)
positive = orbit_pos[2] > threshold
negative = orbit_pos[2] <= threshold
orbit_neg[0][negative] = np.nan
orbit_neg[1][negative] = np.nan
orbit_neg[2][negative] = np.nan
orbit_pos[0][positive] = np.nan
orbit_pos[1][positive] = np.nan
orbit_pos[2][positive] = np.nan
if object.color == None:
color = next(self.ax._get_lines.prop_cycler)['color']
object.color = color
object.orbit_artist.append(ax.plot(orbit_neg[0],orbit_neg[1],orbit_neg[2],linewidth=self.orbit_linewidth,clip_on=False,color=object.color))
object.orbit_artist.append(ax.plot(orbit_pos[0],orbit_pos[1],orbit_pos[2],linewidth=self.orbit_linewidth,clip_on=False,color=self.shade_hex_color(object.color)))
else:
object.orbit_artist.append(ax.plot(orbit_neg[0],orbit_neg[1],orbit_neg[2],linewidth=self.orbit_linewidth,clip_on=False,color=object.color))
object.orbit_artist.append(ax.plot(orbit_pos[0],orbit_pos[1],orbit_pos[2],linewidth=self.orbit_linewidth,clip_on=False,color=self.shade_hex_color(object.color)))
if refplane_var == 1:
counter = 0
for x,y,z in zip(*object.orbit.tolist()):
if (counter%20 == 0):
ax.plot([x,x],[y,y],[z,threshold],'white',linewidth=self.refplane_linewidth,clip_on=False)
counter = counter + 1
if object.id == None:
object.position_artist = self.ax.plot(pos[0],pos[1],pos[2], marker='*', MarkerSize=self.markersize,MarkerFaceColor=object.color ,markeredgecolor = object.color ,clip_on=False,picker=5)
else:
object.position_artist = self.ax.plot(pos[0],pos[1],pos[2], marker='o', MarkerSize=self.markersize,MarkerFaceColor=object.color ,markeredgecolor = object.color ,clip_on=False,picker=5)
object.annotation_artist = self.annotate3D(ax, s=object.displayname, xyz=[pos[0],pos[1],pos[2]], fontsize=self.textsize, xytext=(self.text_xoffset,self.text_yoffset),textcoords='offset points', ha='center',va='bottom',color = self.text_color,clip_on=False)
if self.annot_var.get() == 1:
self.annotate3D(ax, s=str(object.date), xyz=[pos[0],pos[1],pos[2]], fontsize=self.textsize, xytext=(self.text_xoffset,-self.text_yoffset),textcoords='offset points', ha='center',va='top',color = self.text_color,clip_on=False)
# # # recompute the ax.dataLim
# # ax.relim()
# # # update ax.viewLim using the new dataLim
# # ax.autoscale(True)
#
self.axisEqual3D(ax)
self.set_camera_center(self.current_center_object.pos)
# self.formatter.set_scientific(True)
# self.ax.xaxis.set_major_formatter(self.formatter)
# self.ax.yaxis.set_major_formatter(self.formatter)
# self.scale_equinox(None)
# ylim = self.ax.get_ylim()
# xlim = self.ax.get_xlim()
# self.ax.plot([20*xlim[0],20*xlim[1]],[0,0],[0,0],linewidth=0.3,clip_on=False,color='white')
# self.ax.plot([0,0],[20*ylim[0],20*ylim[1]],[0,0],linewidth=0.3,clip_on=False,color='white')
if self.axis_var.get() == 1:
self.ax.set_axis_on()
else:
self.ax.set_axis_off()
if refresh_canvas:
self.canvas.draw()
return # marker_artists,orbit_colors,dates
def ask_ok_popup(self, title, question):
return tkinter.messagebox.askokcancel(title, question)
def on_closing(self):
if self.ask_ok_popup("Quit", "Do you want to quit?"):
self.destroy_was_called = True
self.master.quit()
self.master.destroy()
def error_message(self,title,message):
'''generates an error message-popup with generic title and message'''
tkinter.messagebox.showerror(title,message)
def request_keplers(self,objects,batchfile,errors=0):
'''requests kepler elements from HORIZONS-batch-interface for objects'''
self.prog_bar_cancel_button['state'] = tkinter.NORMAL
print('requesting keplers for selected items')
orbits = []
positions = []
kepler_dict = {}
self.prog_bar["maximum"] = len(objects)
moon = False
count = 0
objects = sorted(objects,reverse=True)
for object in objects:
batchfile['COMMAND'] = object
object_stripped = object.strip("'")
parent_position = [0,0,0]
if len(object_stripped) == 3:
if int(object_stripped[1:3]) != 99:
#its a moon, query with centerbody instead of sun
# x99 is majorbody with x 1 to 9 representing mercury, venus, earth, mars .... , x01 is first moon of x, x02 second,...
center_body = "'" + object_stripped[0] + "99'"
batchfile['CENTER'] = "'500@" + center_body[1:5]
moon = True
else:
#no moon! reset to sun as center
batchfile['CENTER'] = "'500@10'"
moon = False
self.dt = self.calendar_widget.selection_get()
batchfile['TLIST'] = "'" + str(sum(jdcal.gcal2jd(self.dt.year, self.dt.month, self.dt.day))) + "'"
try:
r = requests.get("https://ssd.jpl.nasa.gov/horizons_batch.cgi?batch=1", params = batchfile)
except (requests.exceptions.ConnectionError,requests.exceptions.Timeout):
print('connection failed, retrying...')
if errors<=2:
return self.request_keplers(objects,batchfile,errors = errors+1)
self.error_message('Connection Error','Could not reach the Server, please check your internet connection.')
return False,False
# print(r.text)
count = count + 1
if self.destroy_was_called:
return
if self.cancel_was_pushed:
self.cancel_was_pushed = False
self.prog_bar["value"] = 0
self.prog_bar_cancel_button['state'] = tkinter.DISABLED
self.redraw_current_objects()
return False,False
self.prog_bar["value"] = count
self.prog_bar.update()
if 'No ephemeris for target' in r.text:
print('No ephemeris for target{0} at date {1}'.format(self.JPL_numbers[object],self.dt))
self.error_message('DB Error','No ephemeris for target {0} at date {1}'.format(self.JPL_numbers[object],self.dt))
orbit = [None,None]
position = [None,None]
orbits.append([None,None])
positions.append([None,None])
elif 'is out of bounds, no action taken' in r.text:
print('{0} is out of bounds, no action taken (couldnt find {1} in batch interface of JPL horizonss)'.format(self.JPL_numbers[object],object))
self.error_message('DB Error','{0} is out of bounds, no action taken (couldnt find {1} in batch interface of JPL horizonss)'.format(self.JPL_numbers[object],object))
orbit = [None,None]
position = [None,None]
orbits.append([None,None])
positions.append([None,None])
elif 'No such record, positive values only' in r.text:
print('No record for {0}({1}), positive values only'.format(object,self.JPL_numbers[object]))
self.error_message('DB Error','No record for {0}({1}), positive values only'.format(object,self.JPL_numbers[object]))
orbit = [None,None]
position = [None,None]
orbits.append([None,None])
positions.append([None,None])
else:
keplers = r.text.split('$$SOE')[1].split('$$EOE')[0].replace(' ','').split(',')
del keplers[0:2]
del keplers[-1]
keplers = [float(element) for element in keplers]
for i in range(len(keplers)):
kepler_dict[self.order_of_keplers[i]] = keplers[i]
kepler_dict['Omega'] = np.deg2rad(kepler_dict['Omega'])
kepler_dict['inclination'] = np.deg2rad(kepler_dict['inclination'])
kepler_dict['omega'] = np.deg2rad(kepler_dict['omega'])
kepler_dict['true_anomaly'] = np.deg2rad(kepler_dict['true_anomaly'])
# print('\n\n{0}:\n'.format(self.JPL_numbers[object]))
# pprint(kepler_dict)
orbit = self.orbit_position(kepler_dict['a'],kepler_dict['eccentricity'],kepler_dict['Omega'],kepler_dict['inclination'],kepler_dict['omega'] , comp_true_anomaly=kepler_dict['true_anomaly'] )
position = self.orbit_position(kepler_dict['a'],kepler_dict['eccentricity'],kepler_dict['Omega'],kepler_dict['inclination'],kepler_dict['omega'],[kepler_dict['true_anomaly']])
orbits.append(orbit)
positions.append(position)
added = False
found = False
if moon:
for obj in self.current_objects:
if obj.id == center_body:
orbit = orbit + obj.pos
parent_position = obj.pos
position = position + parent_position
found = True
break
if not found:
if self.ask_ok_popup("Centerbody Missing", "The centerbody of the queried moon is not currently on the plot, add it to the query list?"):
objects.append("'" + object_stripped[0] + "99'")
return self.request_keplers(objects,self.batchfile)
else:
continue
self.current_objects.append(celestial_artist(object,orbit,position,self.dt,self.JPL_numbers[object],r.text,kepler_dict))
self.current_objects[-1].moon = moon
self.current_objects[-1].center_body = parent_position
return orbits,positions
def update_listbox(self):
'''update listbox according to search term'''
search_term = self.search_term.get()
selected_items = self.get_selected()
self.listbox.delete(0,tkinter.END)
for k,v in self.JPL_numbers.items():
if search_term.lower() in v.lower() and not (search_term.lower() in selected_items):
self.listbox.insert(tkinter.END,v)
for item in selected_items:
self.listbox.insert(0,item)
self.listbox.selection_set(0)
return True
def toggle_axis(self):
''' function to toggle coordinate axes'''
if self.axis_var.get() == 1:
self.ax.set_axis_on()
self.canvas.draw()
else:
self.ax.set_axis_off()
self.canvas.draw()
def redraw_current_objects(self):
'''just redrawing the plot to accept user changes to appearance'''
self.plot_orbits(self.ax,self.current_objects,refplane_var=self.refplane_var.get())
def toggle_proj(self):
if self.proj_var.get() == 1:
self.ax.set_proj_type('persp')
else:
self.ax.set_proj_type('ortho')
self.canvas.draw()
def clicked_on(self,event):
'''takes pick event of object'''
# artist_dir = dir(event.artist)
# pprint(arist_dir)
for object in self.current_objects:
if object.position_artist[0].get_label() == event.artist.get_label():
name= object.name
selected_object = object
print('clicked {0}'.format(name))
# for object in self.current_objects:
# object.position_artist[0].set_markeredgecolor(object.position_artist[0].get_markerfacecolor())
# selected_object.position_artist[0].set_markeredgecolor('white')
if event.mouseevent.button == 1:
self.current_center_object = selected_object
self.set_camera_center(selected_object.pos)
elif event.mouseevent.button == 3:
self.call_artist_menu(selected_object)
def set_camera_center(self,pos):
'''centers camera around pos = [x,y,z]'''
if np.array_equal(pos,[0,0,0]):
self.current_center_object = self.sun
ylim = self.ax.get_ylim()
xlim = self.ax.get_xlim()
zlim = self.ax.get_zlim()
xlim = xlim[1]-xlim[0]
ylim = ylim[1]-ylim[0]
zlim = zlim[1]-zlim[0]
max = np.amax([ylim,xlim,zlim])/2
self.ax.set_xlim([-max+pos[0], max+pos[0]])
self.ax.set_ylim([-max+pos[1], max+pos[1]])
self.ax.set_zlim([-max+pos[2], max+pos[2]])
self.canvas.draw()
def call_artist_menu(self,object):
''' call popup menu to alter artist color and name or remove artist'''
artist_menu = artist_menu_toplevel(self,object)
def remove_artist(self,object,top):
try:
object.position_artist[0].remove()
except ValueError:
top.destroy()
self.error_message('Artist error','Object is already removed!')
return
stripped_id = object.id.strip("'")
#check if object has moons on plot and remove them first
if (len(stripped_id) == 3) and (stripped_id[1:3] == '99'):
for obj in self.current_objects:
if (stripped_id[0] == obj.id.strip("'")[0]) and (not(obj.id.strip("'")[1:3] == '99')):
print('found moon {0}, removing it together with {1}'.format(obj.displayname,object.displayname))
obj.position_artist[0].remove()
for art in obj.orbit_artist:
art[0].remove()
obj.annotation_artist.remove()
index = 0
for o in self.current_objects:
if o.position_artist[0].get_label() == obj.position_artist[0].get_label():
self.current_objects.pop(index)
break
index = index + 1
#remove artist
for artist in object.orbit_artist:
artist[0].remove()
object.annotation_artist.remove()
index = 0
for obj in self.current_objects:
if obj.position_artist[0].get_label() == object.position_artist[0].get_label():
self.current_objects.pop(index)
break
index = index + 1
self.redraw_current_objects()
top.destroy()
def destroy_toplevel(self,top):
self.master.deiconify()
top.destroy()
def update_artist(self,object,artist_color_button,displayname,top):
object.color = artist_color_button.cget('bg')
print(object.color)
object.displayname = displayname
self.redraw_current_objects()
self.master.deiconify()
top.destroy()
def check_db(self):
'''checks if DB file exists, if not, queries HORIZONS socket service to extract major bodies'''
if not self.my_file.is_file():
#telnet session to extract Major Bodies dict
tn = telnetlib.Telnet(self.HOST,self.port)
print('waiting for Horizons socket service')
tn.read_until("Horizons>".encode('UTF-8'))
print('Querying Major Bodies')
tn.write('MB\n'.encode('UTF-8'))
list = str(tn.read_until('0'.encode('UTF-8')))
list = list[-2] + str(tn.read_until('Number'.encode('UTF-8')))[1:]
tn.close()
list = str(list)
JPL_numbers = list.split()
list = []
ID = True