-
Notifications
You must be signed in to change notification settings - Fork 15
/
PPA.py
1521 lines (1428 loc) · 57.9 KB
/
PPA.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
# -*- coding: utf-8 -*-
"""
Created on Sun Oct 12 22:40:05 2014
@author: Themos Tsikas, Jack Richmond
"""
import sys
import time
class RequestError(Exception):
'''
An exception that happens when talking to the plate solver
'''
pass
def json2python(json):
'''
translates JSON to python
'''
import ujson
try:
return ujson.loads(json)
except:
pass
return None
def python2json(pyd):
'''
translates python to JSON
'''
import ujson
return ujson.dumps(pyd)
class NovaClient(object):
'''
nova.astrometry.net client
'''
default_url = 'http://nova.astrometry.net/api/'
def __init__(self, apiurl=default_url):
self.session = None
self.apiurl = apiurl
def get_url(self, service):
'''
constructs URL for a plate-solver service
'''
return self.apiurl + service
def send_request(self, service, args={}, file_args=None):
'''
service: string
args: dict
'''
from email.mime.base import MIMEBase
from email.mime.multipart import MIMEMultipart
from email.encoders import encode_noop
from urllib2 import urlopen
from urllib2 import Request
from urllib2 import HTTPError
from urllib import urlencode
from email.mime.application import MIMEApplication
if self.session is not None:
args.update({'session': self.session})
# print 'Python:', (args)
json = python2json(args)
# print 'Sending json:', json
url = self.get_url(service)
print 'Sending to URL:', url
# If we're sending a file, format a multipart/form-data
if file_args is not None:
ma1 = MIMEBase('text', 'plain')
ma1.add_header('Content-disposition',
'form-data; name="request-json"')
ma1.set_payload(json)
ma2 = MIMEApplication(file_args[1], 'octet-stream', encode_noop)
ma2.add_header('Content-disposition',
'form-data; name="file"; filename="%s"'
% file_args[0])
# msg.add_header('Content-Disposition', 'attachment',
# filename='bud.gif')
# msg.add_header('Content-Disposition', 'attachment',
# filename=('iso-8859-1', '', 'FuSballer.ppt'))
mpa = MIMEMultipart('form-data', None, [ma1, ma2])
# Makie a custom generator to format it the way we need.
from cStringIO import StringIO
from email.generator import Generator
class MyGenerator(Generator):
'''
not sure why we need this, copied from nova's example code
'''
def __init__(self, fp, root=True):
Generator.__init__(self, fp, mangle_from_=False,
maxheaderlen=0)
self.root = root
def _write_headers(self, msg):
# We don't want to write the top-level headers;
# they go into Request(headers) instead.
if self.root:
return
# We need to use \r\n line-terminator, but Generator
# doesn't provide the flexibility to override, so we
# have to copy-n-paste-n-modify.
for hoo, voo in msg.items():
print >> self._fp, ('%s: %s\r\n' % (hoo, voo)),
# A blank line always separates headers from body
print >> self._fp, '\r\n',
# The _write_multipart method calls "clone" for the
# subparts. We hijack that, setting root=False
def clone(self, fp):
return MyGenerator(fp, root=False)
fpo = StringIO()
gen = MyGenerator(fpo)
gen.flatten(mpa)
data = fpo.getvalue()
headers = {'Content-type': mpa.get('Content-type')}
else:
# Else send x-www-form-encoded
data = {'request-json': json}
# print 'Sending form data:', data
data = urlencode(data)
# print 'Sending data:', data
headers = {}
request = Request(url=url, headers=headers, data=data)
try:
fle = urlopen(request)
txt = fle.read()
# DEBUG print 'Got json:', txt
result = json2python(txt)
# DEBUG print 'Got result:', result
stat = result.get('status')
# DEBUG print 'Got status:', stat
if stat == 'error':
errstr = result.get('errormessage', '(none)')
raise RequestError('server error message: ' + errstr)
return result
except HTTPError, err:
print 'HTTPError', err
txt = err.read()
open('err.html', 'wb').write(txt)
print 'Wrote error text to err.html'
def login(self, apikey):
'''
Logs us into the plate-solver and gets a session key
'''
import string
args = {'apikey': string.strip(apikey)}
result = self.send_request('login', args)
sess = result.get('session')
print 'Got session:', sess
if not sess:
raise RequestError('no session in result')
self.session = sess
def _get_upload_args(self, **kwargs):
'''
returns the specified solving options
'''
args = {}
lkdt = [('allow_commercial_use', 'd', str),
('allow_modifications', 'd', str),
('publicly_visible', 'y', str),
('scale_units', None, str),
('scale_type', None, str),
('scale_lower', None, float),
('scale_upper', None, float),
('scale_est', None, float),
('scale_err', None, float),
('center_ra', None, float),
('center_dec', None, float),
('radius', None, float),
('downsample_factor', None, int),
('tweak_order', None, int),
('crpix_center', None, bool), ]
for key, default, typ in lkdt:
# image_width, image_height
if key in kwargs:
val = kwargs.pop(key)
val = typ(val)
args.update({key: val})
elif default is not None:
args.update({key: default})
# print 'Upload args:', args
return args
def upload(self, fne, **kwargs):
'''
uploads an image file
'''
args = self._get_upload_args(**kwargs)
try:
fle = open(fne, 'rb')
result = self.send_request('upload', args, (fne, fle.read()))
return result
except IOError:
print 'File %s does not exist' % fne
raise
def myjobs(self):
'''
queries server for our jobs
'''
result = self.send_request('myjobs/')
return result['jobs']
def job_status(self, job_id, justdict=False):
'''
queries server to see if a job is finished
'''
result = self.send_request('jobs/%s' % job_id)
if justdict:
return result
stat = result.get('status')
if stat == 'success':
return stat
return stat
def sub_status(self, sub_id, justdict=False):
'''
queries server for submission status
'''
result = self.send_request('submissions/%s' % sub_id)
if justdict:
return result
return result.get('status')
def jobs_by_tag(self, tag, exact):
'''
not sure what that does
'''
from urllib import quote
exact_option = 'exact=yes' if exact else ''
result = self.send_request('jobs_by_tag?query=%s&%s'
% (quote(tag.strip()), exact_option), {}, )
return result
def stat_bar(self, txt):
'''
Update the Status bar
'''
self.stat_msg = txt
self.wstat.config(text=self.stat_msg)
self.wstat.update()
def limg2wcs(self, filename, wcsfn, hint):
import os
import time
t_start = time.time()
if (('OSTYPE' in os.environ and os.environ['OSTYPE']=='linux') or
(os.uname()[0]=='Linux') or
('OSTYPE' in os.environ and os.environ['OSTYPE']=='darwin') or
('OS' in os.environ and os.environ['OS'] =='Windows_NT')):
# Cygwin local or Linux local
if True:
# first rough estimate of scale
print '___________________________________________________________'
cmd = 'solve-field -b ' + self.local_configfile.get()
if self.havescale and self.restrict_scale.get()==1:
up_lim = self.scale*1.05
lo_lim = self.scale*0.95
cmd = cmd + (' -u app -L %.2f -H %.2f ' % (lo_lim, up_lim))
else:
cmd = cmd + ' -u ' + self.local_scale_units.get()
cmd = cmd + (' -L %.2f' % self.local_scale_low.get())
cmd = cmd + (' -H %.2f' % self.local_scale_hi.get())
if self.local_downscale.get() != 1:
cmd = cmd + (' -z %d' % self.local_downscale.get())
cmd = cmd + ' ' + self.local_xtra.get()
cmd = cmd + ' -O '
cmd = cmd + ' \\"%s\\"'
template = ((self.local_shell.get() % cmd))
# print template
cmd = (template % filename)
print cmd
os.system(cmd)
self.update_scale(hint)
print '___________________________________________________________'
self.update_solved_labels(hint, 'active')
stat_bar(self, 'Idle')
print 'local solve time ' + str(time.time()-t_start)
print '___________________________________________________________'
def img2wcs(self, ankey, filename, wcsfn, hint):
'''
Plate solves one image
'''
import optparse
import time
from urllib2 import urlopen
t_start = time.time()
parser = optparse.OptionParser()
parser.add_option('--server', dest='server',
default=NovaClient.default_url,
help='Set server base URL (eg, %default)')
parser.add_option('--apikey', '-k', dest='apikey',
help='API key for Astrometry.net web service; if not' +
'given will check AN_API_KEY environment variable')
parser.add_option('--upload', '-u', dest='upload', help='Upload a file')
parser.add_option('--wait', '-w', dest='wait', action='store_true',
help='After submitting, monitor job status')
parser.add_option('--wcs', dest='wcs',
help='Download resulting wcs.fits file, saving to ' +
'given filename; implies --wait if --urlupload or' +
'--upload')
parser.add_option('--kmz', dest='kmz',
help='Download resulting kmz file, saving to given ' +
'filename; implies --wait if --urlupload or --upload')
parser.add_option('--urlupload', '-U', dest='upload_url',
help='Upload a file at specified url')
parser.add_option('--scale-units', dest='scale_units',
choices=('arcsecperpix', 'arcminwidth', 'degwidth',
'focalmm'),
help='Units for scale estimate')
parser.add_option('--scale-lower', dest='scale_lower', type=float,
help='Scale lower-bound')
parser.add_option('--scale-upper', dest='scale_upper', type=float,
help='Scale upper-bound')
parser.add_option('--scale-est', dest='scale_est', type=float,
help='Scale estimate')
parser.add_option('--scale-err', dest='scale_err', type=float,
help='Scale estimate error (in PERCENT), eg "10" if' +
'you estimate can be off by 10%')
parser.add_option('--ra', dest='center_ra', type=float, help='RA center')
parser.add_option('--dec', dest='center_dec', type=float,
help='Dec center')
parser.add_option('--radius', dest='radius', type=float,
help='Search radius around RA,Dec center')
parser.add_option('--downsample', dest='downsample_factor', type=int,
help='Downsample image by this factor')
parser.add_option('--parity', dest='parity', choices=('0', '1'),
help='Parity (flip) of image')
parser.add_option('--tweak-order', dest='tweak_order', type=int,
help='SIP distortion order (default: 2)')
parser.add_option('--crpix-center', dest='crpix_center',
action='store_true', default=None,
help='Set reference point to center of image?')
parser.add_option('--sdss', dest='sdss_wcs', nargs=2,
help='Plot SDSS image for the given WCS file; write ' +
'plot to given PNG filename')
parser.add_option('--galex', dest='galex_wcs', nargs=2,
help='Plot GALEX image for the given WCS file; write' +
'plot to given PNG filename')
parser.add_option('--substatus', '-s', dest='sub_id',
help='Get status of a submission')
parser.add_option('--jobstatus', '-j', dest='job_id',
help='Get status of a job')
parser.add_option('--jobs', '-J', dest='myjobs', action='store_true',
help='Get all my jobs')
parser.add_option('--jobsbyexacttag', '-T', dest='jobs_by_exact_tag',
help='Get a list of jobs associated with a given' +
'tag--exact match')
parser.add_option('--jobsbytag', '-t', dest='jobs_by_tag',
help='Get a list of jobs associated with a given tag')
parser.add_option('--private', '-p', dest='public', action='store_const',
const='n', default='y',
help='Hide this submission from other users')
parser.add_option('--allow_mod_sa', '-m', dest='allow_mod',
action='store_const', const='sa', default='d',
help='Select license to allow derivative works of ' +
'submission, but only if shared under same conditions ' +
'of original license')
parser.add_option('--no_mod', '-M', dest='allow_mod', action='store_const',
const='n', default='d',
help='Select license to disallow derivative works of ' +
'submission')
parser.add_option('--no_commercial', '-c', dest='allow_commercial',
action='store_const', const='n', default='d',
help='Select license to disallow commercial use of' +
' submission')
# load opt with defaults, as above
opt, args = parser.parse_args([''.split()])
# add given arguments
opt.wcs = wcsfn
opt.apikey = ankey
opt.upload = filename
if self.havescale and self.restrict_scale.get() == 1:
opt.scale_units = 'arcsecperpix'
opt.scale_est = ('%.2f' % self.scale)
opt.scale_err = 5
# DEBUG print opt
print 'with estimated scale', opt.scale_est
args = {}
args['apiurl'] = opt.server
clnt = NovaClient(**args)
try:
clnt.login(opt.apikey)
except RequestError, URLError:
stat_bar(self, ("Couldn't log on to nova.astrometry.net " +
'- Check the API key'))
return
if opt.upload or opt.upload_url:
if opt.wcs or opt.kmz:
opt.wait = True
kwargs = dict()
if opt.scale_lower and opt.scale_upper:
kwargs.update(scale_lower=opt.scale_lower,
scale_upper=opt.scale_upper,
scale_type='ul')
elif opt.scale_est and opt.scale_err:
kwargs.update(scale_est=opt.scale_est,
scale_err=opt.scale_err,
scale_type='ev')
elif opt.scale_lower or opt.scale_upper:
kwargs.update(scale_type='ul')
if opt.scale_lower:
kwargs.update(scale_lower=opt.scale_lower)
if opt.scale_upper:
kwargs.update(scale_upper=opt.scale_upper)
for key in ['scale_units', 'center_ra', 'center_dec', 'radius',
'downsample_factor', 'tweak_order', 'crpix_center', ]:
if getattr(opt, key) is not None:
kwargs[key] = getattr(opt, key)
if opt.parity is not None:
kwargs.update(parity=int(opt.parity))
if opt.upload:
upres = clnt.upload(opt.upload, **kwargs)
stat = upres['status']
if stat != 'success':
print 'Upload failed: status', stat
print upres
sys.exit(-1)
opt.sub_id = upres['subid']
if opt.wait:
if opt.job_id is None:
if opt.sub_id is None:
print "Can't --wait without a submission id or job id!"
sys.exit(-1)
while True:
stat = clnt.sub_status(opt.sub_id, justdict=True)
# print 'Got status:', stat
jobs = stat.get('jobs', [])
if len(jobs):
for j in jobs:
if j is not None:
break
if j is not None:
print 'Selecting job id', j
opt.job_id = j
break
time.sleep(5)
success = False
while True:
stat = clnt.job_status(opt.job_id, justdict=True)
# print 'Got job status:', stat
# TODO : stat may be None! should recover
if stat.get('status', '') in ['success']:
success = (stat['status'] == 'success')
break
time.sleep(5)
if success:
clnt.job_status(opt.job_id)
retrieveurls = []
if opt.wcs:
# We don't need the API for this, just construct URL
url = opt.server.replace('/api/', '/wcs_file/%i' % opt.job_id)
retrieveurls.append((url, opt.wcs))
for url, fne in retrieveurls:
print 'Retrieving file from', url
fle = urlopen(url)
txt = fle.read()
wfl = open(fne, 'wb')
wfl.write(txt)
wfl.close()
print 'Wrote to', fne
self.update_solved_labels(hint, 'active')
stat_bar(self,'Idle')
print 'nova solve time ' + str(time.time()-t_start)
print '___________________________________________________________'
opt.job_id = None
opt.sub_id = None
if opt.sub_id:
print clnt.sub_status(opt.sub_id)
if opt.job_id:
print clnt.job_status(opt.job_id)
if opt.jobs_by_tag:
tag = opt.jobs_by_tag
print clnt.jobs_by_tag(tag, None)
if opt.jobs_by_exact_tag:
tag = opt.jobs_by_exact_tag
print clnt.jobs_by_tag(tag, 'yes')
if opt.myjobs:
jobs = clnt.myjobs()
print jobs
from Tkinter import Frame, Tk, Menu, Label, Entry, PhotoImage
from Tkinter import Scrollbar, Toplevel, Canvas, Radiobutton
from Tkinter import StringVar, IntVar, DoubleVar
from Tkinter import Button, LabelFrame, Checkbutton, Scale
from Tkinter import HORIZONTAL
def help_f():
'''
Our help window
'''
import tkMessageBox
tkMessageBox.showinfo("Help", "Still to come...")
def about_f():
'''
our about window
'''
import tkMessageBox
tkMessageBox.showinfo('About',
'PhotoPolarAlign v1.0.4 \n' +
'Copyright © 2014 Themos Tsikas, ' +
'Jack Richmond')
def scale_frm_wcs(fn):
from astropy.io import fits
hdu = fits.open(fn)
head = hdu[0].header
return scale_frm_header(head)
def parity_frm_header(head):
'''
look in the plate-solution header for the parity information
'''
try:
# nova's wcs files have the parity in the comments
comments = head['COMMENT']
size = (len(comments))
for i in range(0, size):
if comments[i][0:6] == 'parity':
tkns = comments[i].split(' ')
return int(tkns[1])
except KeyError:
return 1
def scale_frm_header(head):
'''
look in the plate-solution header for the scale information
'''
try:
# nova's wcs files have the scale in the comments
comments = head['COMMENT']
size = (len(comments))
for i in range(0, size):
if comments[i][0:5] == 'scale':
tkns = comments[i].split(' ')
return float(tkns[1])
except KeyError:
try:
# AstroArt's wcs files have it CDELT1 (deg/pixel)
cdelt1 = abs(head['CDELT1'])
return float(cdelt1)*60.0*60.0
except KeyError:
return 1.0
def dec_frm_header(head):
'''
look in header for width and height of image
'''
# nova's and AstroArt's wcs files have CRVAL2
dec = head['CRVAL2']
return dec
def wid_hei_frm_header(head):
'''
look in header for width and height of image
'''
try:
# nova's wcs files have IMAGEW / IMAGEH
width = head['IMAGEW']
height = head['IMAGEH']
return width, height
except KeyError:
try:
# AstroArt's fits files have NAXIS1 / NAXIS2
width = head['NAXIS1']
height = head['NAXIS2']
return width, height
except KeyError:
return 0, 0
def decdeg2dms(dd):
mnt,sec = divmod(dd*3600,60)
deg,mnt = divmod(mnt,60)
return deg,mnt,sec
def cross(crd, img, colour):
'''
Annotate with a cross for the RA axis
'''
from PIL import ImageDraw
draw = ImageDraw.Draw(img)
coords = crd[0]
ax1 = coords[0]
ay1 = coords[1]
draw.line((ax1 - 30, ay1 - 30) + (ax1 + 30, ay1 + 30),
fill=colour, width=3)
draw.line((ax1 + 30, ay1 - 30) + (ax1 - 30, ay1 + 30),
fill=colour, width=3)
def circle(centre, img, colour, name):
'''
Annotate with a circle
'''
from PIL import ImageFont, ImageDraw
font = ImageFont.load('symb24.pil')
draw = ImageDraw.Draw(img)
cen = centre[0]
ax1 = cen[0]
ay1 = cen[1]
draw.ellipse((ax1 - 20, ay1 - 20, ax1 + 20, ay1 + 20),
fill=None, outline=colour)
draw.text((ax1 + 30, ay1), name, fill=colour, font=font)
def cpcircle(centre, img, scl):
'''
Annotate with target circles
'''
from PIL import ImageFont, ImageDraw
font = ImageFont.load('helvR24.pil')
draw = ImageDraw.Draw(img)
cen = centre[0]
ax1 = cen[0]
ay1 = cen[1]
number = [5, 10, 20, 40]
for i in number:
rad = (i*60)/scl
draw.ellipse((ax1 - rad, ay1 - rad, ax1 + rad, ay1 + rad),
fill=None, outline='Green')
draw.text((ax1 + (rad*26)/36, ay1 + (rad*26/36)), str(i),
font=font)
draw.line((ax1 - 30, ay1) + (ax1 - 4, ay1), fill='Green', width=2)
draw.line((ax1 +4, ay1) + (ax1 + 30, ay1), fill='Green', width=2)
draw.line((ax1, ay1 - 30) + (ax1, ay1 - 4),fill='Green', width=2)
draw.line((ax1, ay1 + 4) + (ax1, ay1 + 30),fill='Green', width=2)
class PhotoPolarAlign(Frame):
'''
Our application as a class
'''
def write_config_file(self):
'''
Update the user preferences file
'''
# the API key
if not self.config.has_section('nova'):
self.config.add_section('nova')
self.config.set('nova', 'apikey', self.apikey.get())
# the image directory
if not self.config.has_section('file'):
self.config.add_section('file')
self.config.set('file', 'imgdir', self.imgdir)
# the geometry
if not self.config.has_section('appearance'):
self.config.add_section('appearance')
self.config.set('appearance', 'geometry',
self.myparent.winfo_geometry())
# the operating options
if not self.config.has_section('operations'):
self.config.add_section('operations')
self.config.set('operations','restrict scale',
self.restrict_scale.get())
# the local solve options
if not self.config.has_section('local'):
self.config.add_section('local')
self.config.set('local','shell',
self.local_shell.get())
self.config.set('local','downscale',
self.local_downscale.get())
self.config.set('local','configfile',
self.local_configfile.get())
self.config.set('local','scale_units',
self.local_scale_units.get())
self.config.set('local','scale_low',
self.local_scale_low.get())
self.config.set('local','scale_hi',
self.local_scale_hi.get())
self.config.set('local','xtra',
self.local_xtra.get())
#
with open(self.cfgfn, 'w') as cfgfile:
self.config.write(cfgfile)
cfgfile.close()
def settings_destroy(self):
'''
User asked to close the Settings
'''
self.write_config_file()
self.wvar4.configure(text=('%.3s...........' % self.apikey.get()))
self.settings_win.destroy()
def settings_open(self):
'''
Our Settings window
'''
# create child window
win = Toplevel()
self.settings_win = win
win.geometry('480x600')
win.title('Settings')
# get the API key information
frm = LabelFrame(win, borderwidth=2, relief='ridge', text='nova.astrometry.net')
frm.pack(side='top', ipadx=20, padx=20, fill='x')
nxt = Label(frm, text='API Key')
nxt.grid(row=0, column=0, pady=4, sticky='w')
nxt = Entry(frm, textvariable=self.apikey)
nxt.grid(row=0, column=1, pady=4)
nxt = Label(frm, text='Restrict scale')
nxt.grid(row=1, column=0, pady=4, sticky='w')
nxt = Checkbutton(frm, var=self.restrict_scale)
nxt.grid(row=1, column=1, pady=4)
frm = LabelFrame(win, borderwidth=2, relief='ridge', text='Local solver Configuration')
frm.pack(side='top', ipadx=20, padx=20, fill='x')
nxt = Label(frm, text='shell')
nxt.grid(row=0, column=0, pady=4, sticky='w')
nxt = Entry(frm, textvariable=self.local_shell,width=0)
nxt.grid(row=0, column=1, pady=4, sticky='we', columnspan=2)
ifrm = Frame(frm,bd=0)
ifrm.grid(row=1, column=0, pady=4, sticky='w', columnspan=3)
nxt = Label(ifrm, text='downscale')
nxt.pack(side='left')
nxt = Radiobutton(ifrm, variable=self.local_downscale,value='1',text='1')
nxt.pack(side='left')
nxt = Radiobutton(ifrm, variable=self.local_downscale,value='2',text='2')
nxt.pack(side='left')
nxt = Radiobutton(ifrm, variable=self.local_downscale,value='4',text='4')
nxt.pack(side='left')
nxt = Label(frm, text='configfile')
nxt.grid(row=2, column=0, pady=4, sticky='w')
nxt = Entry(frm, textvariable=self.local_configfile, width=0)
nxt.grid(row=2, column=1, pady=4,sticky='we', columnspan=2)
ifrm = Frame(frm,bd=0)
ifrm.grid(row=3, column=0, pady=4, sticky='w', columnspan=3)
nxt = Label(ifrm, text='scale_units')
nxt.pack(side='left')
nxt = Radiobutton(ifrm, variable=self.local_scale_units,value='arcsecperpix',text='arcsec/pix')
nxt.pack(side='left')
nxt = Radiobutton(ifrm, variable=self.local_scale_units,value='degwidth',text='degrees width')
nxt.pack(side='left')
nxt = Radiobutton(ifrm, variable=self.local_scale_units,value='arcminwidth',text='arcminutes width')
nxt.pack(side='left')
nxt = Label(frm, text='scale_low')
nxt.grid(row=4, column=0, pady=4, sticky='w')
nxt = Scale(frm, from_=0, to_=40, orient=HORIZONTAL,
variable=self.local_scale_low, showvalue=0, digits=4,
sliderlength=10, length=300, resolution=0.1)
nxt.grid(row=4, column=1, pady=4)
nxt = Entry(frm, textvariable=self.local_scale_low, width=8)
nxt.grid(row=4, column=2, pady=4)
nxt = Label(frm, text='scale_hi')
nxt.grid(row=5, column=0, pady=4, sticky='w')
nxt = Scale(frm, from_=0, to_=120, orient=HORIZONTAL,
variable=self.local_scale_hi, showvalue=0, digits=4,
sliderlength=10, length=300, resolution=0.1)
nxt.grid(row=5, column=1, pady=4)
nxt = Entry(frm, textvariable=self.local_scale_hi, width=8)
nxt.grid(row=5, column=2, pady=4)
nxt = Label(frm, text='extra')
nxt.grid(row=6, column=0, pady=4, sticky='w')
nxt = Entry(frm, textvariable=self.local_xtra, width=40)
nxt.grid(row=6, column=1, pady=4, sticky='we', columnspan=2)
nxt = Button(frm, text='Read from AstroTortilla configuration',
command=self.slurpAT)
nxt.grid(row=7, column=0, pady=4, sticky='we', columnspan=3)
Button(win, text='OK', command=self.settings_destroy).pack(pady=4)
def quit_method(self):
'''
User wants to quit
'''
self.write_config_file()
self.myparent.destroy()
def happy_with(self, wcs, img):
'''
check that .wcs (wcs) is compatible with .jpg (img)
'''
import os
from os.path import exists
if exists(wcs):
# DBG print wcs, 'exists'
# check timestamps
# DBG print os.stat(wcs).st_atime, os.stat(wcs).st_mtime, os.stat(wcs).st_ctime, 'wcs'
# DBG print os.stat(img).st_atime, os.stat(img).st_mtime, os.stat(img).st_ctime, 'img'
if os.stat(wcs).st_mtime> os.stat(img).st_mtime:
return True
return False
def get_file(self, hint):
'''
User wants to select an image file
'''
import tkFileDialog
from os.path import splitext, dirname, basename
options = {}
options['filetypes'] = [('JPEG files', '.jpg .jpeg .JPG .JPEG'),
('all files', '.*')]
options['initialdir'] = self.imgdir
titles = {}
titles['v'] = 'The vertical image of the Celestial Pole region'
titles['h'] = 'The horizontal image of the Celestial Pole region'
titles['i'] = 'The horizontal image after Alt/Az adjustment'
options['title'] = titles[hint]
img = tkFileDialog.askopenfilename(**options)
if img:
wcs = splitext(img)[0] + '.wcs'
if self.happy_with(wcs, img):
self.update_solved_labels(hint, 'active')
else:
self.update_solved_labels(hint, 'disabled')
self.imgdir = dirname(img)
if hint == 'v':
self.vimg_fn = img
self.vwcs_fn = wcs
self.havev = True
self.wvar1.configure(text=basename(img))
self.wvfn.configure(bg='green', activebackground='green')
elif hint == 'h':
self.himg_fn = img
self.hwcs_fn = wcs
self.haveh = True
self.wvar2.configure(text=basename(img))
self.whfn.configure(bg='green', activebackground='green')
elif hint == 'i':
self.iimg_fn = img
self.iwcs_fn = wcs
self.havei = True
self.wvar3.configure(text=basename(img))
self.wifn.configure(bg='green', activebackground='green')
def update_scale(self, hint):
try:
if hint == 'v':
self.scale = scale_frm_wcs(self.vwcs_fn)
elif hint == 'h':
self.scale = scale_frm_wcs(self.hwcs_fn)
elif hint == 'i':
self.scale = scale_frm_wcs(self.iwcs_fn)
self.havescale = True
self.wvar5.configure(text=('%.2f' % self.scale))
except:
self.havescale = False
self.wvar5.configure(text='--.--')
return
def solve(self, hint, solver):
'''
Solve an image
'''
if hint == 'h' or hint == 'v':
if self.vimg_fn == self.himg_fn:
stat_bar(self, ('Image filenames coincide - Check the Image ' +
'filenames'))
return
if hint == 'h':
aimg = self.himg_fn
awcs = self.hwcs_fn
if hint == 'v':
aimg = self.vimg_fn
awcs = self.vwcs_fn
if hint == 'i':
aimg = self.iimg_fn
awcs = self.iwcs_fn
try:
open(aimg)
except IOError:
stat_bar(self, ("couldn't open the image - Check the Image " +
'filename' + aimg))
return
stat_bar(self, 'Solving image...')
if solver=='nova':
img2wcs(self, self.apikey.get(), aimg, awcs, hint)
if solver=='local':
limg2wcs(self, aimg, awcs, hint)
self.update_scale(hint)
def update_display(self, cpcrd, the_scale):
'''
update Computed displayed quantities
'''
import numpy
axis = self.axis
x1a = axis[0]
y1a = axis[1]
x2a = cpcrd[0][0]
y2a = cpcrd[0][1]
self.scale = the_scale
self.havescale = True
self.wvar5.configure(text=('%.2f' % the_scale))
self.wvar6.configure(text=str(int(x1a))+','+str(int(y1a)))
self.wvar7.configure(text=(str(int(x2a)) +',' + str(int(y2a))))
err = the_scale*numpy.sqrt((x1a-x2a)**2 + (y1a-y2a)**2)/60.0
self.wvar8.configure(text=('%.2f' % err))
if x2a > x1a:
inst = 'Right '
else:
inst = 'Left '
ddeg = abs(x2a - x1a)*the_scale/3600.0
inst = inst + ('%02d:%02d:%02d' % decdeg2dms(ddeg))
self.wvar9.configure(text=inst)
if y2a > y1a:
inst = inst + ' Down '
else:
inst = inst + ' Up '
ddeg = abs(y2a - y1a)*the_scale/3600.0
inst = inst + ('%02d:%02d:%02d' % decdeg2dms(ddeg))
self.wvar9.configure(text=inst)
def annotate_imp(self):
'''
Annotate the improvement image
'''
from PIL import Image
from astropy.time import Time
from astropy.coordinates import SkyCoord
from astropy.coordinates import FK5
from astropy.io import fits
from astropy import wcs
import numpy
from os.path import splitext
if self.iimg_fn == self.himg_fn:
stat_bar(self, ('Image filenames coincide - Check the Image ' +
'filenames'))
return
try:
imi = Image.open(self.iimg_fn)
# Load the FITS hdulist using astropy.io.fits
hdulisti = fits.open(self.iwcs_fn)
hdulisth = fits.open(self.hwcs_fn)
except IOError:
return
axis = self.axis
try:
axis[0]
except:
stat_bar(self,"don't know where Polar Axis is - Find Polar Axis")
return
stat_bar(self, 'Annotating...')
headi = hdulisti[0].header
headh = hdulisth[0].header
wcsi = wcs.WCS(headi)
now = Time.now()
if self.hemi == 'N':
cp = SkyCoord(ra=0, dec=90, frame='fk5', unit='deg', equinox=now)
else:
cp = SkyCoord(ra=0, dec=-90, frame='fk5', unit='deg', equinox=now)
cpj2000 = cp.transform_to(FK5(equinox='J2000'))
cpskycrd = numpy.array([[cpj2000.ra.deg, cpj2000.dec.deg]],
numpy.float_)
cpcrdi = wcsi.wcs_world2pix(cpskycrd, 1)
scalei = scale_frm_header(headi)
widthi, heighti = wid_hei_frm_header(headi)
if wid_hei_frm_header(headi) != wid_hei_frm_header(headh) :
stat_bar(self,'Incompatible image dimensions...')
return
if parity_frm_header(headi) == 0 :
stat_bar(self,'Wrong parity...')
return
self.update_display(cpcrdi, scalei)
cpcircle(cpcrdi, imi, scalei)
cross([axis], imi, 'Red')
if self.hemi == 'N':
poli = wcsi.wcs_world2pix(self.polaris, 1)
lami = wcsi.wcs_world2pix(self.lam, 1)
circle(poli, imi, 'White', 'a')
circle(lami, imi, 'Orange', 'l')
left = int(min(cpcrdi[0][0], poli[0][0], lami[0][0], axis[0]))
right = int(max(cpcrdi[0][0], poli[0][0], lami[0][0], axis[0]))
bottom = int(min(cpcrdi[0][1], poli[0][1], lami[0][1], axis[1]))
top = int(max(cpcrdi[0][1], poli[0][1], lami[0][1], axis[1]))
else:
ori = wcsi.wcs_world2pix(self.chi, 1)
whi = wcsi.wcs_world2pix(self.sigma, 1)
rei = wcsi.wcs_world2pix(self.red, 1)
circle(whi, imi, 'White', 's')
circle(ori, imi, 'Orange', 'c')
circle(rei, imi, 'Red', '!')