-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathmodsView.py
1932 lines (1588 loc) · 62.8 KB
/
modsView.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
#!/usr/bin/env python
#
# Typical System: /usr/bin/env python
# LBT MODS runtime: /lbt/mods_runtime/anaconda/bin/python
'''
modsView - View a MODS target acquisition (.acq) or imaging (.img) script
Description
-----------
Reads the contents of a MODS target acquisition (.acq) or the target
acquisition blocks of a MODS imaging (.img) script, and displays the
results on a ds9 window, overlaying the MODS focal plane on a
digitized sky survey image of the target field. It also finds and
overlays catalog stars and their R magnitudes.
It tests to see if the guide star is inside the guide patrol field
given the instrument rotator angle. If there are any telescope
offsets as part of the target acquisition, it will test the location
of the guide star after the offset to verify that it is still inside
the MODS guide patrol field.
Uses the Python ds9 module to interact with a named DS9 window. The
window is launched as needed, turning off all of the IRAF imtool
pipes so a person running IRAF will not step on this display (and
vis-versa).
Creates a temporary modsView.reg file containing the DS9 region file
used to draw the MODS focal plane on the screen.
It can also be used to create a PNG-format finder chart by using the
--finder option.
Dependencies
------------
Requires your system have SAOImage DS9 installed and running
https://sites.google.com/cfa.harvard.edu/saoimageds9
Starting with version 3 we are using the SAMP messaging protocol
(https://www.ivoa.net/documents/SAMP/) to interact with ds9 as pyds9 is
no longer supported. We are adopting the astropy.samp implementation
(https://docs.astropy.org/en/stable/samp/) for development. Note that a
parallel SAMP/ds9 development is in progress at LBTO and later revisions
will likely converge on that as the base ds9 interface. All still a
work-in-progress. This version is designed to be mostly self-contained.
Distribution
------------
The primary distribution is now on GitHub
github.com/rwpogge/modsView
Author
------
R. Pogge, OSU Astronomy Department
First version: 2012 May 4
Modification History
--------------------
2012 May 04 - first beta release, does only guide-star checking
and *very* minimal syntax checks. [rwp/osu]
2012 May 06 - first experiments with interactive mode, added a
number of functions [rwp/osu]
2012 May 20 - Added probe shadow option (--shadow) and plot OBJNAME
label or suppress with --nolabel [rwp/osu]
2012 Oct 01 - Experimental interactive version, call it 1.0.0...
2012 Nov 08 - Added ability to use B magnitudes in catalogs instead
of just R, and introduced the --find option to give an
R_mag-sorted list of candidate guide stars to pick from
interactively (type number at prompt) [rwp/osu]
2012 Nov 28 - added NOMAD1 catalog support as default [rwp/osu]
2012 Dec 03 - restored --rotate function [rwp/osu]
2012 Dec 18 - fixed bug in display of the instrument rotator sweep
and long-slit positions after offsets [rwp/osu]
2012 Dec 19 - minor patch, exception catching for python 2.7
(raises exception of you try to close a catalog pane that
is already closed - python 2.6 doesn't care) [rwp/osu]
2013 Jan 7 - minor bug if nonsensical min/max magnitude ranges set
[rwp/osu]
2013 Mar 19 - bugs in the offseting logic [rwp/osu]
2013 Apr 11 - Allow for no + sign on Decs in MMS files (not strictly
permitted, but apparent can happen), and fixed a
previously undetected bug in guide probe shaddow
rendering under RA/Dec offsets [rwp/osu]
2014 Feb 23 - adjusted guide patrol field size for changes in
maximum Y stage travel limits with the WFS hotspot
offset. Found conflicting limits in different parts of
the program resulting in the patrol field being drawn
too large, and tests failing to alert a star just outside
the effective guide patrol field. [rwp/osu]
2014 Apr 28 - Start of binocular MODS hooks, including support for the
different MODS1 and MODS2 AGw parameters [rwp/osu]
2015 Nov 20 - First v2.0 release for MODS1 or MODS2 use [rwp/osu]
2016 Oct 11 - MODS1 and 2 have the same AGw WFS configuration as of
October 2016, so old MODS1 offset hotspot has been removed,
and --mods1/mods2 is no longer required [rwp/osu]
2016 Oct 15 - Minor mods for pyds9 vs ds9 back compatibility [rwp/osu]
2018 May 22 - Support for experimental SNS masks [rwp/osu]
2018 Jul 22 - Patches for Python 3 & MacOS operation, first release
using GitHub [rwp/osu]
2018 Sep 05 - fixed input/raw_input problem P2/3 issue [rwp/osu]
2019 Nov 24 - Updated AGw patrol field coordinates [rwp/osu]
2022 Nov 11 - Updated for changes in XPA with ds9 version 8.x [rwp/osu]
2025 Feb 05 - Switched to astropy.samp to use SAMP for ds9 interface [rwp/osu]
2025 Feb 07 - Cleanup in ds9 interaction, various bug fixes [rwp/osu]
'''
import sys
import os
import math
import getopt
import subprocess
import shlex
import time
# makes paths agnostic of OS (mostly)
from pathlib import Path
# for the star catalogs
from operator import itemgetter
# input vs raw_input for Python 3/2 compatibility
try:
input = raw_input
except NameError:
pass
# Version number and date, update as needed
versNum = '3.0.3'
versDate = '2025-02-07'
# Some useful global defaults (mostly so we can report them in usage)
lbtScale = 0.600 # LBT focal plane scale in mm/arcsec
minRMag = 16.5 # Typical guide star R magnitude limits for the MODS AGw unit
maxRMag = 12.0
minBMag = 16.5 # Typical guide star B magnitude limits for the MODS AGw unit
maxBMag = 11.0
fsFoV = 5.5 # Radius of the focal station field-of-view in arcminutes
defCatalog = 'nomad' # default is the NOMAD1 Catalog, other option is ub1=USNO-B1
defAGwFilt = 'R' # default AGw guide camera filter is 'R'
defServer = 'stsci' # default is the STScI image server
defSurvey = 'all' # default is the STScI composite survey image catalog
#---------------------------------------------------------------------------
#
# internal functions and classes
#
from astropy.samp import SAMPIntegratedClient, SAMPHubError
from astropy.coordinates import SkyCoord, Angle
import astropy.units as u
import time
# DS9 class
class DS9():
'''
DS9 interaction class to replace using pyds9 with SAMP interaction
'''
def __init__(self,ds9ID):
'''
Initialize a DS9 class instance
Parameters
----------
ds9ID : string
name of the ds9 instance we will create.
Raises
------
ValueError
raised if bad inputs are provided.
RuntimeError
raised if unrecoverable errors occur..
Returns
-------
None.
'''
if len(ds9ID) == 0:
raise ValueError("required argument ds9ID missing")
self.ds9ID = ds9ID
self.launchWait = 5 # time to wait for ds9 launch in seconds
# instantiate a SAMPIntegratedClient instance
self.ds9 = SAMPIntegratedClient(name=f"myDS9_{ds9ID}",description="myDS9 instance")
self.connected = self.ds9.is_connected
self.clientID = None
self.haveDS9 = False
self.ds9cmd = f"ds9 -samp -xpa no -fifo none -port none -unix none -title {self.ds9ID}"
try:
self.ds9.connect()
self.connected = self.ds9.is_connected
self.clientID = self.getID()
if self.clientID:
self.haveDS9 = True
else:
subprocess.Popen(shlex.split(self.ds9cmd))
time.sleep(self.launchWait)
self.clientID = self.getID()
if not self.clientID:
raise RuntimeError(f"Failed to start ds9 for {self.ds9ID}, aborting")
else:
self.connected = self.ds9.is_connected
except SAMPHubError:
subprocess.Popen(shlex.split(self.ds9cmd))
time.sleep(self.launchWait)
try:
self.ds9.connect()
self.clientID = self.getID()
if not self.clientID:
raise RuntimeError(f"Failed to start ds9 for {self.ds9ID}, aborting")
else:
self.haveDS9 = True
self.connected = self.ds9.is_connected
except Exception as exp:
raise RuntimeError(f"Cannot connect to a samp hub or ds9: {exp}")
except Exception as exp:
raise RuntimeError(f"DS9 startup failed with exception: {exp}")
def getID(self):
'''
Get the samp hub client ID corresponding to the ds9 instance we need
Returns
-------
clientID : string
SAMP client ID of the ds9 instance of interest
Description
-----------
Uses the astropy.samp get_registered_client() and get_methdata()
methods to find the named ds9 window of interest. The name
attached to a ds9 process with the -title command-line argument
is in the samp.name metadata parameter. We require an exact
case match.
'''
if not self.ds9.is_connected:
return None
for clientID in self.ds9.get_registered_clients():
cliMD = self.ds9.get_metadata(clientID)
if "samp.name" in cliMD:
if cliMD["samp.name"] == self.ds9ID:
self.clientID = clientID
return self.clientID
return None
def set(self,*args):
'''
Send a commmand to the ds9 instance
Parameters
----------
*args : string(s)
SAOImage ds9 set command string(s) to send
Raises
------
ValueError
if bad information is provided
RuntimeError
if there are unrecoverable runtime errors
Returns
-------
None.
Description
-----------
Executes one or more ds9.set commands on the current named
ds9 app. If more than one set command is desired, put them
separated by commas.
'''
if len(args) == 0:
return
if not self.haveDS9:
raise RuntimeError(f"named ds9 instance {self.ds9ID} not connected")
for cmdStr in args:
if len(cmdStr) > 0:
try:
sampRet = self.ds9.ecall_and_wait(self.clientID,"ds9.set","10",cmd=cmdStr)
except Exception as exp:
raise ValueError(f"set() error: {exp}")
if sampRet["samp.status"] != "samp.ok":
raise RuntimeError(f"ds9 set command returned error: {sampRet}")
def get(self,cmdStr):
'''
Execute a ds9 get directive to the ds9 instance
Parameters
----------
cmdStr : string
SAOImage ds9 get command to send.
Raises
------
RuntimeError
if there are unrecoverable errors.
Returns
-------
dictionary
SAMP dictionary with the return from the ds9.get command.
Description
-----------
Sends the attached ds9 instance a ds9.get command and waits
for the response or timeout. Because get delivers a response
that presumably the user wants to act upon, unlike set() this
method only supports one get directive at a time.
See Also
--------
getCursKey() for a function that uses this for cursor interaction
'''
if len(cmdStr) == 0:
return None
if self.haveDS9:
try:
sampRet = self.ds9.ecall_and_wait(self.clientID,"ds9.get","0",cmd=cmdStr)
except Exception as exp:
raise RuntimeError(f"get() error: {exp}")
if sampRet['samp.status'] == 'samp.ok':
if "samp.result" in sampRet:
if "value" in sampRet["samp.result"]:
return sampRet["samp.result"]["value"]
else:
return sampRet["samp.result"]
else:
return sampRet
else:
raise RuntimeError(f"ds9 get command {cmdStr} error: {sampRet}")
else:
raise RuntimeError(f"named ds9 instances {self.ds9ID} not connected")
def getCursKey(self,prompt=None,coords="image"):
'''
Put an interactive cursor on the image and wait for a key press,
returning coordinates and the key pressed.
Parameters
----------
prompt : string, optional
Prompt to show on stdout at the start. The default is None.
coords : string, optional
coordinates to return, must be one of "image", "fk5", "wcs fk5", or
"wcs galactic", The default is "image".
Raises
------
RuntimeError
if unrecoverable errors occur in execution.
Returns
-------
key : string
The key hit (also space if spacebar, etc.)
cursX : float
the X coordinate of the cursor when key was hit
cursY : float
the Y coordinate of the cursor when key was hit
Description
-----------
A wrapper for "iexam key coordinate image", or substitute
one of (fk5,wcs fk5,wsc galactic) if alternatives given.
* "image" returns pixel coordinates (default)
* "fk5" returns ra/dec in decimal hours/degrees
Returns the key hit, does not respond to mouse click.
'''
if not prompt:
print(f"Put cursor on the {self.ds9ID} display image and hit any key")
else:
print(f"{prompt}")
try:
cursData = self.get(f"iexam key coordinate {coords}")
except Exception as exp:
raise RuntimeError(f"iexam returned error: {exp}")
cursBits = cursData.split(' ')
if len(cursBits) == 3:
return cursBits[0],float(cursBits[1]),float(cursBits[2])
else:
return cursData
def alive(self):
'''
See if the ds9 client is active
Returns
-------
bool
True if active, False if not
'''
try:
self.ds9.enotify(self.clientID,"samp.app.ping")
return True
except:
return False
#------------------
#
# replacements for coordinate conversions using astropy
#
def rdToStd(ra,dec,ra0,dec0):
'''
compute offset from (ra0,dec0) to (ra,dec) in arcsec
Parameters
----------
ra : float
destination right ascension in decimal hours
dec : float
destination declination in decimal degrees
ra0 : float
origin right ascension in decimal hours
dec0 : float
origin declination in decimal degrees
Returns
-------
xi : float
RA offset from ra0 to ra in arcseconds on the standard plane
eta : float
Dec offset from dec0 to dec in arcseconds on the standard plane.
See Also
--------
`stdToRD` for the reverse offset
'''
rd0 = SkyCoord(ra0*u.hour,dec0*u.deg,frame="icrs")
rd = SkyCoord(ra*u.hour,dec*u.deg,frame="icrs")
xi, eta = rd0.spherical_offsets_to(rd)
return xi.to(u.arcsec).value,eta.to(u.arcsec).value
def stdToRD(xi,eta,ra0,dec0):
'''
convert standard coordinates (xi,eta) on the standard plane to RA/Dec
Parameters
----------
xi : float
RA offset from ra0 on the standard plane in decimal arcseconds.
eta : float
Dec offset from dec0 on the standard plane in decimal arcseconds.
ra0 : float
Right ascension of the reference (tangent) point in decimal hours
dec0 : float
Declination of the reference (tangent) point in decimal degrees
Returns
-------
ra
Right ascension of the offset position in decimal hours.
dec
Declination of the offset position in decimal degrees.
See Also
--------
`rdToStd` for the reverse offset
'''
rd0 = SkyCoord(ra0*u.hour,dec0*u.deg,frame="icrs")
newRD = rd0.spherical_offsets_by(xi*u.arcsec,eta*u.arcsec)
return newRD.ra.value/15.0, newRD.dec.value
def dec2sex(decAng,precision=2,sign=False):
'''
Convert decimal angle into a sexigesmial string
Parameters
----------
decAng : float
angle, either degrees or hours.
precision : int, optional
precision of the seconds part. The default is 2.
sign : boolean, optional
include + sign if decAng>0. The default is False (no + sign).
Returns
-------
string
Sexigesimal string representation of decAng with a colon (:)
separator.
See Also
--------
sex2dec
'''
return Angle(decAng,unit=u.deg).to_string(sep=":",precision=precision,pad=True,alwayssign=sign)
def sex2dec(sexStr,precision=8):
'''
Convert a sexigesimal string to decimal
Parameters
----------
sexStr : string
sexigesimal representation of an angle (see Notes)
precision : integer, optional
precision of the conversion. The default is 8 figures beyond the decimal point.
Returns
-------
float
decimal representation of the sexigesimal string
Notes
-----
If the string is in 12h13m18.23s format, the "h" will make sure the
conversion preserves units of hours. Correctly recognizes strings
that don't use the colon (:) separator, so 12:13:14.15 = 12d13m14.15s
and 12:13:14.15 = 12h13m14.5s preserve correct hours or degrees units
on the conversion to decimal format.
See Also
--------
dec2sex
'''
if "h" in sexStr:
units = u.hour
else:
units = u.deg
return float(Angle(sexStr,unit=units).to_string(decimal=True,precision=precision))
def inTriangle(x1,y1,x2,y2,x3,y3,x,y):
'''
Test to determine if (x,y) are inside a triangle
Parameters
----------
x1 : float
x coordinate of triangle vertex 1.
y1 : float
y coordinate of triangle vertex 1.
x2 : float
x coordinate of triangle vertex 2.
y2 : float
y coordinate of triangle vertex 2.
x3 : float
x coordinate of triangle vertex 3.
y3 : float
y coordinate of triangle vertex 3.
x : float
x coordinate to test.
y : float
y coordinate to test.
Returns
-------
bool
True if (x,y) are inside the triangle, False if they are outside
Description
-----------
Solves this classic geometry problem by transforming the
coordinates of the triangle vertices and the test point into the
barycentric coordinate system of the triangle.
A very lucid description of the problem is in the Wikipedia
article on the barycentric coordinate system:
https://en.wikipedia.org/wiki/Barycentric_coordinate_system_(mathematics)
'''
n1 = (y2-y3)*(x -x3) + (x3-x2)*(y -y3)
d1 = (y2-y3)*(x1-x3) + (x3-x2)*(y1-y3)
n2 = (y3-y1)*(x -x3) + (x1-x3)*(y -y3)
d2 = (y2-y3)*(x1-x3) + (x3-x2)*(y1-y3)
if d1 != 0.0:
lam1 = n1/d1
else:
lam1 = 0.0
if d2 !=0.0:
lam2 = n2/d2
else:
lam2 = 0.0
lam3 = 1 - lam1 - lam2
if (lam1<0.0 or lam2<0.0 or lam3<0.0):
return False
else:
return True
def inBox(x,y,rect,rotAng):
'''
Test to determine if (x,y) are inside a rectangular box including rotation
Parameters
----------
x : float
x coordinate to test.
y : float
y coordinate to test.
rect : float list
rectange with center (xc,yc) and size (dx,dy).
rotAng : float
rotation angle for the box about (0,0).
Returns
-------
bool
True if (x,y) are in the box, False if they are outside.
Description
-----------
Creats a box from the center (xc,yc) and size (dx,dy) but allows
rotation of the box about the (0,0) origin of the (xc,yc) coordinates.
It then divides the box diagonally into 2 triangles and uses the
`inTriangle()` function to make the test.
See Also
--------
inTriangle() and rotXY()
'''
(xc,yc,dx,dy) = rect
# Coordinates of the center and rectangle vertices after rotation
(xr0,yr0)=rotXY(xc,yc,-posAng)
(xr1,yr1)=rotXY(xc-dx/2,yc-dy/2,-rotAng)
(xr2,yr2)=rotXY(xc+dx/2,yc-dy/2,-rotAng)
(xr3,yr3)=rotXY(xc+dx/2,yc+dy/2,-rotAng)
(xr4,yr4)=rotXY(xc-dx/2,yc+dy/2,-rotAng)
# Slice the box diagonally into two triangles and test if
# (x,y) are in one or other triangle
if inTriangle(xr1,yr1,xr2,yr2,xr3,yr3,x,y) or inTriangle(xr1,yr1,xr3,yr3,xr4,yr4,x,y):
return True
else:
return False
def rotXY(x,y,rotAng):
'''
rotate (x,y) relative to the origin (0,0)
Parameters
----------
x : float
x position relative to x=0.
y : float
y position relative to y=0
rotAng : float
rotation angle in degrees about (0,0).
Returns
-------
xr : float
rotated x coordinate.
yr : float
rotate y coordinate.
Description
-----------
Convenience function to evaluate the standard Cartesian 2D
coordinate system rotation. Note that for applying this to
astronomical standard coordinates (xi,eta), the helicity of rotAng
has the opposite sign of celestial position angle (e.g., to compute
xi,eta when rotating by position angle posAng, use rotAng=-posAng).
'''
if rotAng==0.0 or rotAng==-0.0:
return x, y
else:
sinPA = math.sin(math.radians(rotAng))
cosPA = math.cos(math.radians(rotAng))
xr = x*cosPA - y*sinPA
yr = x*sinPA + y*cosPA
return xr, yr
def parseMMS(file):
'''
Parse a MODS Mask Specification (MMS) file
Parameters
----------
file : string
name of the MMS file to open and parse.
Returns
-------
ra : float
Right ascencsion in decimal hours.
dec : float
Declination in decimal degrees.
swid : float
slit width in arcseconds.
slen : float
slit lengthin arcseconds.
srot : float
slit rotation angle in decimal degrees.
Description
-----------
Opens and reads in the contents of a MODS mask design (MMS) file,
and extracts the coordinates and dimensions of the slits,
returning them as useful floating-point representations. The
trick lies in reading the MMS file's coding for slit RA/Dec
coordinates:
RA format: INS.TARGnnn.ALPHA 203448.232
Dec format: INS.TARGnnn.DELTA -001415.123
'''
ra = []
dec = []
swid = []
slen = []
srot = []
F = open(file, 'r')
M = F.readlines()[::]
F.close()
numRef = 0
for i in range(len(M)):
inStr = M[i].strip()
if not inStr.startswith('#') and len(inStr)>0: # ignore comments and blank lines
(param,datum) = inStr.split()
(slitType,targID,field) = param.split('.')
if slitType == 'INS':
if targID=='RSLIT' and field=='NUMBER':
numRef = int(datum)
firstTarget = 100+numRef+1 # first non-reference slit ID number
elif targID[0:4] == 'TARG':
targNum = int(targID[4:])
if targNum >= firstTarget:
if field == 'ALPHA':
raStr = datum
sexStr = f"{raStr[0:2]}:{raStr[2:4]}:{raStr[4:]}"
ra.append(sex2dec(sexStr))
elif field == 'DELTA':
decStr = datum
if decStr[0] == '-' or decStr[0]=='+':
sexStr = f"{decStr[0:3]}:{decStr[3:5]}:{decStr[5:]}"
else:
sexStr = f"{decStr[0:2]}:{decStr[2:4]}:{decStr[4:]}"
dec.append(sex2dec(sexStr))
elif field == 'WID':
swid.append(float(datum))
elif field == 'LEN':
slen.append(float(datum))
elif field == 'ROT':
srot.append(float(datum))
return ra, dec, swid, slen, srot
def findStar(ra,dec,catRAd,catDec,radius):
'''
find a star in a star catalog given RA/Dec coordinates within search radius
Parameters
----------
ra : float
right ascension in decimal degrees.
dec : float
declination in decimal degrees.
catRAd : float list
star catalog RA list.
catDec : float list
star catalog Dec list.
radius : float
search radius for matches in arcseconds
Returns
-------
index : integer
array index of the star in the catalog closest to (ra,dec).
'''
if len(catRAd)==0:
return -1
for i in range(len(catRAd)):
dist = math.sqrt(math.pow(ra-catRAd[i],2) + math.pow(dec-catDec[i],2))
if i==0:
dmin = dist
iFound = 0
else:
if dist<dmin:
iFound = i
dmin = dist
darcs = 3600.0*dmin
if darcs < radius:
return iFound
else:
return -1
def loadCat(catFile):
'''
load a star catalog into working arrays
Parameters
----------
catFile : string
Name of the star catalog to load.
Returns
-------
numStars : integer
number of stars in the catalog.
catID : string
catalog identifier (e.g., USNO-B1.0).
catRAd : float list
catalog star RAs in decial degrees.
catDec : float list
catalog star declinations in decimal degrees.
catBmag : float list
catalog star B magnitudes.
catRmag : float list
catalog star R magnitudes.
catName : string
catalog star names.
Description
-----------
Open and parse a star catalog downloaded from a catalog
server by the ds9 instance with the ds9 set command
`catalog export tsv catFile`
'''
SC=open(catFile,'r')
catLines = SC.readlines()[::]
SC.close()
catRAd = []
catDec = []
catRmag = []
catBmag = []
catName = []
catID = "None"
numStars = len(catLines)-1
for i in range(len(catLines)):
catBits = catLines[i].split('\t') # split on tabs
if i==0: # first line is the header, get the element count
numItems = len(catBits)
catID = catBits[2]
else:
catRAd.append(float(catBits[0]))
catDec.append(float(catBits[1]))
catName.append(catBits[2])
if catID.upper() == 'NOMAD1':
try:
catRmag.append(float(catBits[15]))
except ValueError:
catRmag.append(99.99)
try:
catBmag.append(float(catBits[11]))
except ValueError:
catBmag.append(99.99)
else:
catRmag.append(float(catBits[numItems-2]))
try:
catBmag.append(float(catBits[numItems-3]))
except ValueError:
catBmag.append(99.99) # placeholder if B is blank in catalog
return numStars,catID,catRAd,catDec,catBmag,catRmag,catName
def drawMODS(objName,target,posAng,gstar,slitMask,offRD,offXY,mmsFile,gprobe,boxSize):
'''
Create the MODS instrument overlay as a DS9 regions file
Parameters
----------
objName : string
object name.
target : float list
object RA/Dec in decimal hours/degrees.
posAng : float
mask celestial position angle in decimal degrees, +=North to East.
gstar : float list
guide star RA/Dec in decimal hours/degrees.
slitMask : string
slit mask ID.
offRD : float list
offset position RA/Dec in decimal arcseconds (RADEC).
offXY : float lost
offset position in detector XY decimal arcseconds (DETXY).
mmsFile : string
filename of a MODS Mask Specification (MMS) file
gprobe : boolean
if True include the approximate guide probe shadow outline.
boxSize : int
Size of the image display box in decimal arcminutes.
Returns
-------
None.
Description
-----------
Draws the full MODS footprint on the image displayed in the ds9
window using the ds9 regions file utility. If changes need to
be made to the footprint, they are made here.
'''
# MODS science field at PA=0 (center and width/height in arcsec).
(sciX,sciY) = (0,0)
# MODS guide patrol field at PA=0 (center and width/height in arcsec)
(gpfX,gpfY) = (0,-150.0)
(gpfW,gpfH) = (290,300)
(xr0,yr0) = rotXY(gpfX,gpfY,-posAng)
gsBox = (gpfX,gpfY,gpfW,gpfH)
# Nominal guide probe shadow region (center & dimensions) relative to
# the guide star position in arcsec in (xi,eta) coordinates.
(gpsX,gpsY) = (35,0)
(gpsW,gpsH) = (150,85)
# Guide probe carrier arm shadow
(armX,armY) = (76,-105)
(armW,armH) = (80,125)
# Guide Field of View position & dimensions relative to the guide star.
# Both MODS have a 40x40-arcsec FoV
(gcX,gcY) = (0.042,0.404) # really a slight offset (0.042,0.404)
(gcW,gcH) = (40,40)
# Centers of the facility long-slit mask segments in arcsec
slitCen = [-126,-63,0,63,126]
# Process Arguments
# Target RA/Dec
(targRA,targDec) = target
targRAd = 15.0*targRA
# Guide Star? If not, turn off guide star plotting features
if gstar==None: