-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathalignment.py
1993 lines (1634 loc) · 107 KB
/
alignment.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
"""Classes and function to support focal plane alignment of space observatories.
Authors
-------
Tony Sohn
Original script by Johannes Sahlmann
Use
---
Used by the jwst_fpa.py script
"""
import os
import copy
import pickle
from collections import OrderedDict
import numpy as np
import matplotlib.pyplot as plt
import astropy.units as u
from astropy.time import Time
from astropy.table import Table, vstack, hstack
import pysiaf
import pystortion
from pystortion.utils import plot_spatial_difference
alignment_definition_attributes = {'default': ['V3IdlYAngle', 'V2Ref', 'V3Ref']}
alignment_parameter_mapping = OrderedDict(
{'default': {'v3_angle': 'V3IdlYAngle', 'v2_position': 'V2Ref', 'v3_position': 'V3Ref'},
'unit': {'v3_angle': u.deg, 'v2_position': u.arcsec, 'v3_position': u.arcsec},
'default_inverse': {'V3IdlYAngle': 'v3_angle', 'V2Ref':'v2_position', 'V3Ref':'v3_position'}})
class AlignmentObservation(object):
"""Class for focal plane alignment obervations for JWST
attributes:
reference_catalog : Absolute reference catalog of stars
star_catalog : Observed catalog of stars
"""
def __init__(self, instrument):
self.instrument = instrument
self.fpa_name_seed = '{}'.format(self.instrument)
def compute_v2v3(self, aperture, V3IdlYAngle_deg=None, V2Ref_arcsec=None, V3Ref_arcsec=None, verbose=False,
method='planar_approximation', use_tel_boresight=True, input_coordinates='tangent_plane'):
"""Perform (x_idl, y_idl) -> (v2, v3) transformation (tangent and spherical).
It is assumed that self.star_catalog['x_idl_arcsec'] are planar coordinates.
"""
if method == 'planar_approximation':
if V2Ref_arcsec is None:
V2Ref_arcsec = aperture.V2Ref
if V3Ref_arcsec is None:
V3Ref_arcsec = aperture.V3Ref
if V3IdlYAngle_deg is None:
V3IdlYAngle_deg = aperture.V3IdlYAngle
self.star_catalog['v2_tangent_arcsec'], self.star_catalog['v3_tangent_arcsec'] = aperture.idl_to_tel(
np.array(self.star_catalog['x_idl_arcsec']), np.array(self.star_catalog['y_idl_arcsec']),
V3IdlYAngle_deg, V2Ref_arcsec, V3Ref_arcsec, method=method, input_coordinates=input_coordinates,
output_coordinates='tangent_plane')
self.star_catalog['v2_tangent_deg'] = self.star_catalog['v2_tangent_arcsec'] / 3600.
self.star_catalog['v3_tangent_deg'] = self.star_catalog['v3_tangent_arcsec'] / 3600.
# V2V3_tangent_plane -> V2V3_spherical , perform the tangent-plane de-projection of
# the catalog stars,
if use_tel_boresight is False:
# reference point for projection is the local V2/V3 reference point of the
# aperture OR AN EXTERNALLY SET VALUE
self.reference_point_deg = np.array([V2Ref_arcsec / 3600., V3Ref_arcsec / 3600.])
else:
self.reference_point_deg = np.array([0., 0.])
self.star_catalog['v2_spherical_deg'], self.star_catalog[
'v3_spherical_deg'] = pysiaf.projection.deproject_from_tangent_plane(
np.array(self.star_catalog['v2_tangent_deg']), np.array(self.star_catalog['v3_tangent_deg']),
self.reference_point_deg[0], self.reference_point_deg[1])
if use_tel_boresight is False:
# subtract reference point to get back into absolute coordinates
self.star_catalog['v2_spherical_deg'] = self.star_catalog['v2_spherical_deg'] - \
self.reference_point_deg[0]
self.star_catalog['v3_spherical_deg'] = self.star_catalog['v3_spherical_deg'] - \
self.reference_point_deg[1]
if aperture.InstrName == 'NIRISS':
print('ATTENTION: special fix for NIRISS required')
self.star_catalog['v2_spherical_deg'] -= 360.
self.star_catalog['v2_spherical_arcsec'] = self.star_catalog['v2_spherical_deg'] * 3600.
self.star_catalog['v3_spherical_arcsec'] = self.star_catalog['v3_spherical_deg'] * 3600.
elif method == 'spherical_transformation':
table = copy.deepcopy(self.star_catalog)
table = compute_idl_to_tel_in_table(table, aperture, V3IdlYAngle_deg=V3IdlYAngle_deg,
V2Ref_arcsec=V2Ref_arcsec, V3Ref_arcsec=V3Ref_arcsec, method=method,
use_tel_boresight=use_tel_boresight)
self.star_catalog = table
class AlignmentObservationCollection(object):
"""Class for an alignment observation collection,
e.g. from one or several focal plane alignment programs
2017-10-10 JSA STScI/AURA
"""
def __init__(self, observations):
self.observations = np.array(observations)
self.set_basic_properties()
def set_basic_properties(self):
self.n_observations = len(self.observations)
T = Table()
for key in self.observations[0].fpa_data.meta.keys():
value_list = []
for j in range(self.n_observations):
if key in self.observations[j].fpa_data.meta.keys():
value_list.append(self.observations[j].fpa_data.meta[key])
else: # HST FGS case
value_list.append(None)
T[key] = value_list
# try:
# T[key] = [self.observations[j].fpa_data.meta[key] for j in range(
# self.n_observations)]
# except KeyError as e:
# print('Setting {} to None (error {})'.format(key, e))
# T[key] = None
for key in ['AperName', 'AperType']:
T[key] = [getattr(self.observations[j].aperture, key) for j in range(self.n_observations)]
T['number_of_matched_stars'] = [len(self.observations[j].star_catalog_matched) for j in
range(self.n_observations)]
self.T = T
self.T['MJD'] = Time(self.T['EPOCH']).mjd
def delete_observations(self, index):
"""Delete observations specified by index
:param index:
:return:
"""
self.observations = np.delete(self.observations, index)
self.n_observations = len(self.observations)
self.T.remove_rows(index)
def duplicate_observation(self, index):
"""Duplicate one observation."""
duplicated_observation = copy.deepcopy(self.observations[index])
self.observations = np.hstack((self.observations, duplicated_observation))
self.n_observations = len(self.observations)
self.T.add_row(self.T[index])
self.T['duplicate'] = np.zeros(len(self.T))
duplicate_index = len(self.T) - 1
self.T['duplicate'][duplicate_index] = 1
return duplicate_index
def select_observations(self, index):
"""Select observations specified by index."""
delete_index = np.setdiff1d(np.arange(self.n_observations), index)
self.delete_observations(delete_index)
def sort_by(self, column_name):
"""Sort table T and obsrvations by a certain column
Parameters
----------
column_name
Returns
-------
"""
if column_name not in self.T.colnames:
raise RuntimeError('Column {} not valid'.format(column_name))
sorted_index = np.argsort(np.array(self.T[column_name]))
self.T = self.T[sorted_index]
self.observations = self.observations[sorted_index]
def group_by(self, column_name):
"""
:param column_name:
attribute table T will be expanded to hold group_id
:return:
"""
self.T['group_id'] = np.zeros(self.n_observations).astype(np.int)
if (column_name == 'obs_id'):
# special obsid that removes the parallel sequence id
self.T['obsid_special'] = ['{}{}'.format(s[0:16], s[17:26]) for s in self.T['DATAFILE']]
for jj, key in enumerate(np.array(self.T.group_by('obsid_special').groups.keys)):
self.T['group_id'][np.where(np.array(self.T['obsid_special'])==key[0])[0]] = jj
else:
tmp_group_id = 0
# for val in np.unique(self.T[column_name])[::-1]:
for val in np.unique(self.T[column_name]):
index = np.where(self.T[column_name] == val)[0]
self.T['group_id'][index] = tmp_group_id
tmp_group_id += 1
def generate_attitude_groups(self, threshold_hours=0.3):
##################
#### NOT USED ####
##################
"""Create attitude groups of near-contemporaneous camera images to constrain attitude.
Returns
-------
"""
self.T['attitude_group'] = -1
self.T['attitude_id'] = 'undefined'
self.sort_by('MJD')
group_ids = np.unique(np.array(self.T['group_id']))
for group_id in group_ids:
valid_index = np.where((self.T['group_id'] == group_id))[0]
# threshold to separate attitude groups (based on time of observation)
break_index = np.where(np.diff(self.T['MJD'][valid_index] * 24) > threshold_hours)[0] + 1
if not break_index:
# if only one group
self.T['attitude_group'] = 0
else:
for index in break_index:
self.T['attitude_group'][valid_index[0:index]] = 0
self.T['attitude_group'][valid_index[index:]] = 1
for i in valid_index:
self.T['attitude_id'][i] = '{}-{}'.format(self.T['group_id'][i], self.T['attitude_group'][i])
def assign_alignment_reference_aperture(self, reference_aperture_name):
"""Given a grouped obs collection, the alignment reference aperture is identified by the
reference_aperture_name.
:param reference_aperture_name:
:return:
"""
self.T['alignment_reference'] = np.zeros(self.n_observations).astype(np.int)
for group_id in np.unique(self.T['group_id']):
# select only first element of rows matching criteria (alignment reference has to be
# unique for every group)
index = np.where((self.T['group_id'] == group_id) & (self.T['AperName'] == reference_aperture_name))[0]
if type(index) == list:
index = index[0]
self.T['alignment_reference'][index] = 1
def apply_focal_plane_calibration(obs_collection, apertures_to_calibrate, calibrated_data,
verbose=True, field_selection='calibrated',
calibrated_obs_collection=None):
"""This is for modifying the (V2Ref, V3Ref, V3IdlYAngle) params of the apertures
to apply the results from a previous alignment run.
Set the alignment parameters for the apertures_to_calibrate as determined in an independent calibration run.
Parameters
----------
obs_collection
apertures_to_calibrate
calibrated_data
Returns
-------
"""
for tmp_j, tmp_aperture_name in enumerate(obs_collection.T['AperName']):
if tmp_aperture_name in apertures_to_calibrate:
calibration_index = np.where((np.int(obs_collection.T['PROPOSID'][tmp_j]) == np.array(calibrated_data['PROPOSID'])) &
(np.array(calibrated_data['AperName']) == tmp_aperture_name))[0] # &
# (np.int(obs_collection.T['EPOCHNUMBER'][tmp_j]) == np.array(calibrated_data['EPOCHNUMBER'])))[0]
print('++++++++++++++ APPLYING CALIBRATION ++++++++++++++')
if verbose:
print('Applying calibration as mean of')
calibrated_data['DATE-OBS PROGRAM_VISIT APERTURE CHIP {0}_V2Ref {0}_V3Ref {0}_V3IdlYAngle'.format(
field_selection).split()][calibration_index].pprint()
alignment_parameter_set = obs_collection.T['align_params'][calibration_index[0]] # 'default' or 'hst_fgs'
for key, attribute in alignment_parameter_mapping[alignment_parameter_set].items():
mean_value = np.mean(calibrated_data['{}_{}'.format(field_selection, attribute)][calibration_index])
print('Setting {} from {:2.3f} to {:2.3f} (average of {} samples) for alignment_reference_aperture '
'{}'.format(attribute, getattr(obs_collection.observations[tmp_j].aperture, attribute), mean_value,
len(calibration_index), tmp_aperture_name))
setattr(obs_collection.observations[tmp_j].aperture, attribute, mean_value)
# transfer distortion coefficients to allow skipping the alignment during the next attitude determination
if calibrated_obs_collection is not None:
subset_index = 0 # take the deep or shallow exposure
assert calibrated_obs_collection.T['AperName'][calibration_index[subset_index]] == obs_collection.T['AperName'][tmp_j]
obs_collection.observations[tmp_j].distortion_dict = calibrated_obs_collection.observations[calibration_index[subset_index]].distortion_dict
return obs_collection
def compute_idl_to_tel_in_table(input_table, aperture, V3IdlYAngle_deg=None, V2Ref_arcsec=None, V3Ref_arcsec=None,
verbose=False, method='planar_approximation', distortion_correction=None,
use_tel_boresight=True, input_coordinates=None):
"""Perform IDL -> V2V3_tangent transformation and deprojection to V2V3_spherical.
The input table must have columns named 'x_idl_arcsec' and 'y_idl_arcsec'.
Parameters
----------
input_table
aperture
V3IdlYAngle_deg
V2Ref_arcsec
V3Ref_arcsec
verbose
method
distortion_correction : dict
Allows correction for distortion before determining alignment parameters
use_tel_boresight : bool
if True, the V2=0, V3=0 origin of the tel coordinate system us used as deprojection point
if False, the aperture's V2Ref, V3Ref parameters are used
Returns
-------
"""
table = copy.deepcopy(input_table)
for colname in 'v2_tangent_arcsec v3_tangent_arcsec v2_spherical_deg v3_spherical_deg v2_spherical_arcsec v3_spherical_arcsec v2_tangent_deg v3_tangent_deg'.split():
if colname in table.colnames:
table.remove_column(colname)
if 'x_idl_arcsec' not in table.colnames:
raise ValueError('IDL coordinates not in table or wrong column name')
if method == 'planar_approximation':
table['v2_tangent_arcsec'], table['v3_tangent_arcsec'] = aperture.idl_to_tel(np.array(table['x_idl_arcsec']),
np.array(table['y_idl_arcsec']), V3IdlYAngle_deg=V3IdlYAngle_deg, V2Ref_arcsec=V2Ref_arcsec, V3Ref_arcsec=V3Ref_arcsec, method=method, input_coordinates='tangent_plane', output_coordinates='tangent_plane')
if distortion_correction is not None:
# correct for distortion
fieldname_dict = distortion_correction['fieldname_dict']
x_original = np.array(table[fieldname_dict['star_catalog']['position_1']]) # == 'v2_tangent_arcsec'
y_original = np.array(table[fieldname_dict['star_catalog']['position_2']])
table['v2_tangent_arcsec'], table['v3_tangent_arcsec'] = distortion_correction[
'coefficients'].apply_polynomial_transformation(distortion_correction['evaluation_frame_number'],
x_original, y_original)
if 0:
distortion_correction['coefficients'].plotDistortion(distortion_correction['evaluation_frame_number'],
'', '', distortion_correction['reference_point_for_projection'], save_plot=0)
table['v2_tangent_deg'] = table['v2_tangent_arcsec'] / 3600.
table['v3_tangent_deg'] = table['v3_tangent_arcsec'] / 3600.
# V2V3_tangent_plane -> V2V3_spherical , perform the tangent-plane de-projection of the
# catalog stars,
# reference point for projection is the local V2/V3 reference point of the aperture the
# tel boresight
if use_tel_boresight is False:
reference_point_deg = np.array([aperture.V2Ref / 3600., aperture.V3Ref / 3600.])
else:
reference_point_deg = np.array([0., 0.])
if verbose:
print('Reference point position {0:3.8f} / {1:3.8f} arcsec'.format(
reference_point_deg[0] * u.deg.to(u.arcsec), reference_point_deg[1] * u.deg.to(u.arcsec)))
table['v2_spherical_deg'], table['v3_spherical_deg'] = pysiaf.projection.deproject_from_tangent_plane(
np.array(table['v2_tangent_deg']), np.array(table['v3_tangent_deg']), reference_point_deg[0],
reference_point_deg[1])
if use_tel_boresight is False:
# subtract reference point to get back into absolute coordinates
table['v2_spherical_deg'] = table['v2_spherical_deg'] - reference_point_deg[0]
table['v3_spherical_deg'] = table['v3_spherical_deg'] - reference_point_deg[1]
table['v2_spherical_deg'][table['v2_spherical_deg'].data > 180.] -= 360.
elif method == 'spherical_transformation':
v2_spherical_arcsec, v3_spherical_arcsec = aperture.idl_to_tel(np.array(table['x_idl_arcsec']),
np.array(table['y_idl_arcsec']), V3IdlYAngle_deg=V3IdlYAngle_deg, V2Ref_arcsec=V2Ref_arcsec,
V3Ref_arcsec=V3Ref_arcsec, method='spherical_transformation', input_coordinates='tangent_plane', output_coordinates='spherical')
v2_spherical_deg, v3_spherical_deg = v2_spherical_arcsec / 3600., v3_spherical_arcsec / 3600.
table['v2_spherical_deg'], table['v3_spherical_deg'] = v2_spherical_deg, v3_spherical_deg
# tangent plane projection using boresight
table['v2_tangent_deg'], table['v3_tangent_deg'] = pysiaf.projection.project_to_tangent_plane(v2_spherical_deg, v3_spherical_deg,
0., 0.)
table['v2_tangent_arcsec'], table['v3_tangent_arcsec'] = table['v2_tangent_deg'] * 3600., table[
'v3_tangent_deg'] * 3600.
if distortion_correction is not None:
# correct for distortion
fieldname_dict = distortion_correction['fieldname_dict']
x_original = np.array(table[fieldname_dict['star_catalog']['position_1']]) # == 'v2_tangent_arcsec'
y_original = np.array(table[fieldname_dict['star_catalog']['position_2']])
table['v2_tangent_arcsec'], table['v3_tangent_arcsec'] = distortion_correction[
'coefficients'].apply_polynomial_transformation(distortion_correction['evaluation_frame_number'],
x_original, y_original)
table['v2_tangent_deg'] = table['v2_tangent_arcsec'] / 3600.
table['v3_tangent_deg'] = table['v3_tangent_arcsec'] / 3600.
table['v2_spherical_deg'][table['v2_spherical_deg'].data > 180.] -= 360.
elif method == 'spherical':
if aperture.AperName in ['FGS1', 'FGS2', 'FGS3']:
input_coordinates = 'cartesian'
else:
input_coordinates = 'polar'
table['v2_spherical_arcsec'], table['v3_spherical_arcsec'] = \
aperture.idl_to_tel(np.array(table['x_idl_arcsec']),
np.array(table['y_idl_arcsec']), V3IdlYAngle_deg=V3IdlYAngle_deg,
V2Ref_arcsec=V2Ref_arcsec, V3Ref_arcsec=V3Ref_arcsec,
method=method, input_coordinates=input_coordinates,
output_coordinates='polar')
table['v2_spherical_deg'], table['v3_spherical_deg'] = \
table['v2_spherical_arcsec']/3600., table['v3_spherical_arcsec']/3600.
if distortion_correction is not None:
# correct for distortion
fieldname_dict = distortion_correction['fieldname_dict']
v2_name = fieldname_dict['star_catalog']['position_1'] # == 'v2_spherical_arcsec'
v3_name = fieldname_dict['star_catalog']['position_2'] # == 'v3_spherical_arcsec'
x_original = np.array(table[v2_name])
y_original = np.array(table[v3_name])
table[v2_name], table[v3_name] = distortion_correction['coefficients'].apply_polynomial_transformation(
distortion_correction['evaluation_frame_number'], x_original, y_original)
table['v2_spherical_deg'] = table[v2_name] / 3600.
table['v3_spherical_deg'] = table[v3_name] / 3600.
table['v2_spherical_deg'][table['v2_spherical_deg'].data > 180.] -= 360.
if 'v2_spherical_arcsec' not in table.colnames:
table['v2_spherical_arcsec'], table['v3_spherical_arcsec'] = table['v2_spherical_deg']*3600., table['v3_spherical_deg']*3600
return table
def compute_sky_to_tel_in_table(table, attitude, aperture, verbose=False, use_tel_boresight=True):
"""Perform Ra/Dec -> V2V3_spherical transformation and projection to V2V3_tangent.
The input table must have columns named 'ra' and 'dec'.
:param table:
:param attitude:
:param aperture:
:param verbose:
:return:
####
#### Consider adding DVA correction here
####
"""
if 'ra' not in table.colnames:
raise ValueError('sky coordinates not in table or wrong column name')
###
### TBD: DVA should be applied here.
###
table['v2_spherical_arcsec'], table['v3_spherical_arcsec'] = \
pysiaf.rotations.getv2v3(attitude,
np.array(table['ra']),
np.array(table['dec']))
if use_tel_boresight is False:
# use V2/V3 REF of aperture as reference point for tangent-plane projection of catalog
reference_point_deg = np.array([aperture.V2Ref / 3600., aperture.V3Ref / 3600.])
else:
# use boresight, V2=0, V3=0
reference_point_deg = np.array([0., 0.])
if verbose:
print('Reference point position RA/Dec {0:3.8f} / {1:3.8f}'.format(reference_point_deg[0] * u.deg.to(u.arcsec),
reference_point_deg[1] * u.deg.to(u.arcsec)))
table['v2_tangent_deg'], table['v3_tangent_deg'] = pysiaf.projection.project_to_tangent_plane(
np.array(table['v2_spherical_arcsec'] / 3600.), np.array(table['v3_spherical_arcsec'] / 3600.),
reference_point_deg[0], reference_point_deg[1])
if use_tel_boresight is False:
# add back the projection reference point to get absolute V2V3 coordinates
table['v2_tangent_deg'] = table['v2_tangent_deg'] + reference_point_deg[0]
table['v3_tangent_deg'] = table['v3_tangent_deg'] + reference_point_deg[1]
table['v2_tangent_arcsec'] = table['v2_tangent_deg'] * 3600.
table['v3_tangent_arcsec'] = table['v3_tangent_deg'] * 3600.
return table
def compute_tel_to_idl_in_table(table, aperture, use_tel_boresight=True, method='planar_approximation'):
"""perform tangent plane projection from V2V3_spherical V2V3_tangent
then transform to to Ideal
The input table must have columns named 'v2_spherical_arcsec' and 'v3_spherical_arcsec'
:param table:
:param aperture:
:param V3IdlYAngle_deg:
:param V2Ref_arcsec:
:param V3Ref_arcsec:
:param verbose:
:return:
"""
if 'v2_spherical_arcsec' not in table.colnames:
raise ValueError('Tel coordinates not in table or wrong column name')
if 'v2_spherical_deg' not in table.colnames:
table['v2_spherical_deg'] = table['v2_spherical_arcsec'] / 3600.
table['v3_spherical_deg'] = table['v3_spherical_arcsec'] / 3600.
if use_tel_boresight is False:
reference_point_deg = np.array([aperture.V2Ref / 3600., aperture.V3Ref / 3600.])
else:
reference_point_deg = np.array([0., 0.])
if method == 'planar_approximation':
table['v2_tangent_deg'], table['v3_tangent_deg'] = pysiaf.projection.project_to_tangent_plane(np.array(table['v2_spherical_deg']), np.array(table['v3_spherical_deg']), reference_point_deg[0], reference_point_deg[1])
table['v2_tangent_arcsec'] = table['v2_tangent_deg'] * 3600.
table['v3_tangent_arcsec'] = table['v3_tangent_deg'] * 3600.
table['x_idl_arcsec'], table['y_idl_arcsec'] = aperture.tel_to_idl(table['v2_tangent_arcsec'],
table['v3_tangent_arcsec'],
method=method,
output_coordinates='tangent_plane')
elif method == 'spherical_transformation':
table['x_idl_arcsec'], table['y_idl_arcsec'] = aperture.tel_to_idl(table['v2_spherical_arcsec'],
table['v3_spherical_arcsec'],
method=method,
output_coordinates='tangent_plane')
return table
def determine_aperture_error(obs, reference_obs, obs_index, reference_observation_index,
alignment_reference_aperture=None, maximum_number_of_iterations=100, attenuation_factor=0.9,
fractional_threshold_for_iterations=0.01, verbose=False, k=4, plot_residuals=False,
reference_frame_number=0, evaluation_frame_number=1,
reference_point_setting='auto', rotation_name='Rotation in Y',
plot_dir=None, distortion_correction=None, idl_tel_method='spherical',
use_tel_boresight=False, parameters={}):
"""Use a polynomial fit to determine the aperture error.
This returns corrected values of V2Ref, V3Ref, V3IdlYAngle of the obs.aperture.
Iterative polynomial fit to determine corrections to V2Ref, V3Ref, V3IdlYAngle (attitude remains
fixed).
Parameters
----------
obs : AlignmentObservation instance
The observation to be processed
reference_obs : AlignmentObservation instance
The alignment reference observation. This is the observation that needs to be processed
first.
obs_index : int
index of obs in AlignmentObservationCollection
reference_observation_index : int
index of reference_obs in AlignmentObservationCollection
maximum_number_of_iterations : int
When to stop iterating.
attenuation_factor : float
Gain applied to interative corrections.
fractional_threshold_for_iterations : float
determines when the iteration has converged by comparing the uncertainty of the correction
to the correction amplitude.
iteration stops when np.abs(correction) < fractional_threshold_for_iterations * uncertainty
verbose : bool
Verbosity
k : int
Parameter that defines the polynomial degree for distortion fitting
plot_residuals : bool
Whether to make residual figures.
reference_frame_number : int
evaluation_frame_number : int
reference_point : numpy array
rotation_name : str
plot_dir : str
distortion_correction : dict
Allows correction for distortion before determining alignment parameters
Returns
-------
"""
iteration_number = 0
converged = False
if reference_point_setting == 'auto':
use_fiducial_as_reference_point = True
# this shifts the origin (center of rotation) for the distortion fit from
# v2,v3=0,0 to the fiducial point of the aperture to mitigate correlation
# between offsets and rotation
reference_point = np.array(
[[obs.aperture.V2Ref_original, obs.aperture.V3Ref_original], [obs.aperture.V2Ref_original, obs.aperture.V3Ref_original]])
else:
reference_point = reference_point_setting
for j in np.arange(maximum_number_of_iterations):
if verbose:
print('{}\nIteration {}'.format('~' * 10, iteration_number))
# initialize alignment parameters
if iteration_number == 0:
if obs_index == reference_observation_index:
# Processing reference observation. Setting alignment parameters directly.
V3IdlYAngle_deg = obs.aperture.V3IdlYAngle
V2Ref_arcsec = obs.aperture.V2Ref
V3Ref_arcsec = obs.aperture.V3Ref
else:
# Setting alignment parameters relative to reference observation.
# use and calibrate relative V2V3 parameters between actual and reference aperture
relative_V3IdlYAngle_deg = obs.aperture.V3IdlYAngle - reference_obs.aperture.V3IdlYAngle
relative_V2Ref_arcsec = obs.aperture.V2Ref - reference_obs.aperture.V2Ref
relative_V3Ref_arcsec = obs.aperture.V3Ref - reference_obs.aperture.V3Ref
V3IdlYAngle_deg = reference_obs.aperture.V3IdlYAngle_corrected + relative_V3IdlYAngle_deg
V2Ref_arcsec = reference_obs.aperture.V2Ref_corrected + relative_V2Ref_arcsec
V3Ref_arcsec = reference_obs.aperture.V3Ref_corrected + relative_V3Ref_arcsec
if verbose:
print(relative_V2Ref_arcsec, '=', obs.aperture.V2Ref, reference_obs.aperture.V2Ref)
print(V2Ref_arcsec, '=', reference_obs.aperture.V2Ref_corrected, relative_V2Ref_arcsec)
else:
# use parameters determined in previous iteration to determine correction terms
if hasattr(obs.aperture, '_fgs_use_rearranged_alignment_parameters') is False:
obs.aperture._fgs_use_rearranged_alignment_parameters = None
# not HST-FGS case
current_rotation_deg, current_shift_in_X, current_shift_in_Y, converged, sigma_current_rotation_deg, \
sigma_current_shift_in_X, sigma_current_shift_in_Y = determine_corrections(lazAC, fractional_threshold_for_iterations, rotation_name)
# compute correction terms
correction_V3IdlYAngle_deg = attenuation_factor * current_rotation_deg
correction_V2Ref_arcsec = attenuation_factor * current_shift_in_X
correction_V3Ref_arcsec = attenuation_factor * current_shift_in_Y
# apply correction terms
V2Ref_arcsec += correction_V2Ref_arcsec
V3Ref_arcsec += correction_V3Ref_arcsec
V3IdlYAngle_deg += correction_V3IdlYAngle_deg
if verbose:
print('correction_V2Ref_arcsec = {}'.format(correction_V2Ref_arcsec))
print('correction_V3Ref_arcsec = {}'.format(correction_V3Ref_arcsec))
print('correction_V3IdlYAngle_deg = {}'.format(correction_V3IdlYAngle_deg))
if converged:
print('Corrections to apertures: Iterations converged after {} steps'.format(iteration_number))
break
if verbose:
print('V2Ref_arcsec = {}'.format(V2Ref_arcsec))
print('V3Ref_arcsec = {}'.format(V3Ref_arcsec))
print('V3IdlYAngle_deg = {}'.format(V3IdlYAngle_deg))
# prepare data for distortion fit
obs.star_catalog_matched = compute_idl_to_tel_in_table(obs.star_catalog_matched, obs.aperture,
V3IdlYAngle_deg=V3IdlYAngle_deg,
V2Ref_arcsec=V2Ref_arcsec,
V3Ref_arcsec=V3Ref_arcsec,
distortion_correction=distortion_correction,
method=idl_tel_method,
use_tel_boresight=use_tel_boresight)
mp = pystortion.distortion.prepare_multi_epoch_astrometry(obs.star_catalog_matched, obs.reference_catalog_matched,
fieldname_dict=obs.fieldname_dict)
# perform distortion fit
lazAC, index_masked_stars = pystortion.distortion.fit_distortion_general(mp, k,
eliminate_omc_outliers_iteratively=1,
outlier_rejection_level_sigma=3.,
reference_frame_number=reference_frame_number,
evaluation_frame_number=evaluation_frame_number,
reference_point=reference_point,
verbose=verbose)
# convert to easily read parameters
lazAC.human_readable_solution_parameters = pystortion.distortion.compute_rot_scale_skew(lazAC, i=evaluation_frame_number)
iteration_number += 1
# after iteration converged or reached maximum number of iterations
if iteration_number == (maximum_number_of_iterations - 1):
raise RuntimeWarning('Iterative aperture correction did not converge')
else:
### if plot_residuals:
### # show the residuals of the last distortion fit
### xy_unit = u.arcsec
### xy_scale = u.arcsecond.to(xy_unit)
### xy_unitStr = xy_unit.to_string()
### name_seed = obs.fpa_name_seed + '_k{:d}'.format(k)
### # lazAC.display_results(evaluation_frame_number=evaluation_frame_number,
### # scale_factor_for_residuals=1., displayCorrelations=0, nformat='f')
### lazAC.plotResiduals(evaluation_frame_number, plot_dir, name_seed,
### omc_scale=u.arcsecond.to(u.milliarcsecond), save_plot=True, omc_unit='mas',
### xy_scale=xy_scale, xy_unit=xy_unitStr, bins=10, title=obs.aperture.AperName)
# store the uncertainties in the determined parameters by setting attributes of obs,
attribute_mapping = {'rotation_deg': rotation_name, 'shift_in_X': 'Shift in X', 'shift_in_Y': 'Shift in Y', }
values = lazAC.human_readable_solution_parameters['values']
names = lazAC.human_readable_solution_parameters['names'].tolist()
for key in attribute_mapping:
setattr(obs, 'sigma_current_{}'.format(key), values[names.index(attribute_mapping[key])][1])
if index_masked_stars is None:
obs.number_of_used_stars_for_aperture_correction = copy.deepcopy(obs.number_of_matched_stars)
else:
obs.number_of_used_stars_for_aperture_correction = copy.deepcopy(obs.number_of_matched_stars) - len(
index_masked_stars)
obs.aperture.V3IdlYAngle_corrected = V3IdlYAngle_deg
obs.aperture.V2Ref_corrected = V2Ref_arcsec
obs.aperture.V3Ref_corrected = V3Ref_arcsec
obs.lazAC = lazAC
for attribute in ['V3IdlYAngle', 'V2Ref', 'V3Ref']:
original = getattr(obs.aperture, '{}'.format(attribute))
corrected = getattr(obs.aperture, '{}_corrected'.format(attribute))
print('Corrections to apertures: {} original: {:3.4f} \t corrected {:3.4f} \t difference {'
':3.4f}'.format(attribute, original, corrected, corrected - original))
distortion_dict = {'fieldname_dict' : obs.fieldname_dict,
'coefficients' : lazAC,
'evaluation_frame_number': parameters['evaluation_frame_number']}
obs.distortion_dict = distortion_dict
return
def determine_attitude(obs_set, parameters):
"""Return a refined attitude estimate.
Iterative polynomial fit to determine corrections to RA_V1, DEC_V1, and PA_V3,
while aperture alignment SIAF parameters (V2Ref, V3Ref, V3IdlYangle) remain fixed.
If obs_set contains several apertures, the attitude_defining_aperture is kept
fixed and temporary alignments are made to the remaining apertures.
Parameters
----------
obs_set : AlignmentObservationCollection
A collection of observations to use for attitude determination.
parameters : dict
Dictionary of configuration parameters, contains:
- attitude_defining_aperture : str
- maximum_number_of_iterations : int
- attenuation_factor : float
- fractional_threshold_for_iterations : float
determines when the iteration has converged by comparing the uncertainty of the
correction
to the correction amplitude.
iteration stops when np.abs(correction) < fractional_threshold_for_iterations *
uncertainty
- verbose : bool
- k_attitude_determination : int
- reference_frame_number
- evaluation_frame_number
- reference_point
- rotation_name
- use_v1_pointing : bool
if True, the attitude is determined at the V-frame origin
if False, the attitude is determined at the aperture's fiducial point
Returns
-------
attitude_dict : dict
Dictionary holding results of attitude determination
"""
perform_alignment_update = parameters['perform_temporary_alignment_update']
perform_distortion_correction = parameters['perform_temporary_distortion_correction']
if perform_alignment_update is False:
perform_distortion_correction = False
obs_set = copy.deepcopy(obs_set)
aperture_names = np.array(obs_set.T['AperName'])
unique_aperture_names = np.unique(aperture_names)
if len(unique_aperture_names) != obs_set.n_observations:
raise RuntimeError('Attitude set has duplicate apertures.')
k = parameters['k_attitude_determination']
verbose = parameters['verbose']
use_tel_boresight = parameters['use_tel_boresight']
attenuation_factor = parameters['attenuation_factor']
maximum_number_of_iterations = parameters['maximum_number_of_iterations']
attitude_defining_aperture_name = parameters['attitude_defining_aperture_name']
attitude_defining_aperture_index = np.where(aperture_names == attitude_defining_aperture_name)[0][0]
attitude_defining_obs = obs_set.observations[attitude_defining_aperture_index]
attitude_defining_aperture = attitude_defining_obs.aperture
print('='*80)
print('determine_attitude: received obs_set with {} observations'.format(obs_set.n_observations))
print('determine_attitude: attitude-defining aperture is {}'.format(attitude_defining_aperture_name))
print('='*80)
print()
# Make sure that attitude_defining_aperture is processed first
# Order observations by increasing separation from attitude_defining_aperture
separation_tel_arcsec = np.zeros(obs_set.n_observations)
for j in range(obs_set.n_observations):
aperture = obs_set.observations[j].aperture
separation_tel_arcsec[j] = np.sqrt((attitude_defining_aperture.V2Ref - aperture.V2Ref) ** 2 + \
(attitude_defining_aperture.V3Ref - aperture.V3Ref) ** 2)
attitude_order_index = np.argsort(separation_tel_arcsec)
# Derive initial attitude using the boresight info of the first observation
V2Ref = 0.
V3Ref = 0.
ra_attitude_deg = attitude_defining_obs.fpa_data.meta['pointing_ra_v1']
dec_attitude_deg = attitude_defining_obs.fpa_data.meta['pointing_dec_v1']
pa_attitude_deg = attitude_defining_obs.fpa_data.meta['pointing_pa_v3']
initial_ra_attitude_deg = copy.deepcopy(ra_attitude_deg)
initial_dec_attitude_deg = copy.deepcopy(dec_attitude_deg)
initial_pa_attitude_deg = copy.deepcopy(pa_attitude_deg)
fieldname_dict = attitude_defining_obs.fieldname_dict
attitude = pysiaf.rotations.attitude(0., 0., ra_attitude_deg, dec_attitude_deg, pa_attitude_deg)
for i, index in enumerate(attitude_order_index):
# With i increasing, the number of used observations increases
obs_indices = attitude_order_index[0:i + 1]
used_apertures = [name for name in aperture_names[obs_indices]]
print()
print('Attitude determination with {} apertures: {}'.format(len(obs_indices), used_apertures))
print()
iteration_number = 0
# Determine and correct for alignment parameters of individual apertures using current attitude
skip_temporary_alignment_for_aligned_apertures = parameters['skip_temporary_alignment_for_aligned_apertures']
skipped_apertures = parameters['apertures_to_calibrate']
# [STS] This part will run under default settings.
# [STS] But do we need below if using only FGS1_FULL??? *TBD*
if perform_alignment_update:
print('+' * 40)
for align_index in obs_indices:
if verbose:
print('determine_attitude: Intermediate alignment of {}'.format(aperture_names[align_index]))
align_obs = copy.deepcopy(obs_set.observations[align_index])
if (skip_temporary_alignment_for_aligned_apertures is True) & (align_obs.aperture.AperName in skipped_apertures):
print('Skipping temporary alignment of {}. Using previously determined alignment and distortion.'.format(align_obs.aperture.AperName))
distortion_dict = align_obs.distortion_dict
for attribute in 'V2Ref V3Ref V3IdlYAngle'.split():
setattr(align_obs.aperture, '{}_corrected'.format(attribute), getattr(align_obs.aperture, '{}'.format(attribute)))
obs_set.observations[align_index].aperture = align_obs.aperture
else:
#print(align_obs.aperture.AperName)
# get V2/V3 tangent plane coordinates of reference stars
align_obs.reference_catalog_matched = compute_sky_to_tel_in_table(align_obs.reference_catalog_matched, attitude,
align_obs.aperture, use_tel_boresight=use_tel_boresight)
# here, attitude-def and alignment-ref aperture are set the same
alignment_reference_obs = copy.deepcopy(attitude_defining_obs)
alignment_reference_observation_index = attitude_defining_aperture_index
if verbose:
print('Attitude defining aperture = {}; '
'Alignment reference aperture = {}; '
'Current aperture = {}'.format(
attitude_defining_obs.aperture.AperName,
alignment_reference_obs.aperture.AperName,
align_obs.aperture.AperName))
plot_residuals = parameters['plot_residuals']
plot_dir = parameters['plot_dir']
# align aperture
determine_aperture_error(align_obs, alignment_reference_obs, align_index,
alignment_reference_observation_index,
plot_residuals=plot_residuals,
plot_dir=plot_dir, verbose=verbose,
idl_tel_method=parameters['idl_tel_method'],
use_tel_boresight=parameters['use_tel_boresight'],
reference_point_setting=parameters['reference_point_setting'],
fractional_threshold_for_iterations=parameters['fractional_threshold_for_iterations'],
parameters=parameters)
# transfer parameters of aligned aperture to observation set used for attitude
# determination
# no correction applied for reference aperture
if verbose:
print('-'*20)
obs_set.observations[align_index].aperture = align_obs.aperture
if align_index != attitude_defining_aperture_index:
if verbose:
print('Updating {} with temporary alignment parameters.'.format(
align_obs.aperture.AperName))
alignment_attributes = alignment_definition_attributes['default']
for attribute in alignment_attributes:
corrected = getattr(align_obs.aperture, '{}_corrected'.format(attribute))
setattr(obs_set.observations[align_index].aperture, '{}'.format(attribute), corrected)
else:
if verbose:
print('No update of {} temporary alignment parameters (att-def and align-ref aperture).'.format(align_obs.aperture.AperName))
# attach current distortion solution
obs_set.observations[align_index].distortion_dict = align_obs.distortion_dict
else:
alignment_reference_obs = copy.deepcopy(attitude_defining_obs)
print('+'*20)
print('Determine refined attitude estimate:')
# determine the current attitude
### This is the MAIN LOOP for determining attitude [STS]
for j in np.arange(maximum_number_of_iterations):
if verbose:
print('Iteration {}'.format(iteration_number))
if iteration_number > 0:
ra_attitude_deg += correction_ra_attitude_deg
dec_attitude_deg += correction_dec_attitude_deg
pa_attitude_deg += correction_V3IdlYAngle_deg
# Update the attitude using the corrected (ra, dec, pa)
attitude = pysiaf.rotations.attitude(V2Ref, V3Ref, ra_attitude_deg, dec_attitude_deg, pa_attitude_deg)
reference_catalog = vstack([compute_sky_to_tel_in_table(
obs.reference_catalog_matched,
attitude,
obs.aperture,
use_tel_boresight=parameters['use_tel_boresight'])
for obs in obs_set.observations[obs_indices]], metadata_conflicts='silent')
if perform_distortion_correction:
star_catalog = vstack([compute_idl_to_tel_in_table(obs.star_catalog_matched, obs.aperture,
distortion_correction=obs.distortion_dict,
use_tel_boresight=parameters['use_tel_boresight'],
method=parameters['idl_tel_method']) for obs in
obs_set.observations[obs_indices]], metadata_conflicts='silent')
else:
star_catalog = vstack([compute_idl_to_tel_in_table(obs.star_catalog_matched, obs.aperture,
use_tel_boresight=parameters['use_tel_boresight'],
method=parameters['idl_tel_method']) for obs in
obs_set.observations[obs_indices]], metadata_conflicts='silent')
mp = pystortion.distortion.prepare_multi_epoch_astrometry(star_catalog, reference_catalog,
fieldname_dict=fieldname_dict)
# make sure to use consistent distortion reference point
#reference_point = obs.distortion_dict['reference_point']
#########################################
#use_v1_pointing = True
#########################################
if parameters['use_v1_pointing']:
# here the reference point has to be on the V1 axis
reference_point = np.array([[0., 0.], [0., 0.]])
lazAC, index_masked_stars = \
pystortion.distortion.fit_distortion_general(mp, k,
eliminate_omc_outliers_iteratively=
parameters['eliminate_omc_outliers_iteratively'],
outlier_rejection_level_sigma=
parameters['outlier_rejection_level_sigma'],
reference_frame_number=
parameters['reference_frame_number'],
evaluation_frame_number=
parameters['evaluation_frame_number'],
reference_point=reference_point,
verbose=False)
# verbose=parameters['verbose'])
lazAC.human_readable_solution_parameters = \
pystortion.distortion.compute_rot_scale_skew(
lazAC, i=parameters['evaluation_frame_number'])
current_rotation_deg, current_shift_in_X, current_shift_in_Y, converged, \
sigma_current_rotation_deg, sigma_current_shift_in_X, sigma_current_shift_in_Y = \
determine_corrections(lazAC, parameters['fractional_threshold_for_iterations'],