-
Notifications
You must be signed in to change notification settings - Fork 169
/
Copy pathrules_level2_base.py
1372 lines (1168 loc) · 42.6 KB
/
rules_level2_base.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
"""Base classes which define the Level2 Associations"""
from collections import deque
import copy
import logging
from os.path import (
basename,
split,
splitext
)
import re
from jwst.associations import (
Association,
libpath
)
from jwst.associations.exceptions import AssociationNotValidError
from jwst.associations.lib.acid import ACID
from jwst.associations.lib.constraint import (
Constraint,
SimpleConstraint,
)
from jwst.associations.lib.dms_base import (
Constraint_TargetAcq,
DMSAttrConstraint,
DMSBaseMixin,
IMAGE2_NONSCIENCE_EXP_TYPES,
IMAGE2_SCIENCE_EXP_TYPES,
PRODUCT_NAME_DEFAULT,
SPEC2_SCIENCE_EXP_TYPES
)
from jwst.associations.lib.member import Member
from jwst.associations.lib.process_list import ListCategory
from jwst.associations.lib.prune import prune
from jwst.associations.lib.rules_level3_base import _EMPTY, DMS_Level3_Base
from jwst.associations.lib.rules_level3_base import Utility as Utility_Level3
from jwst.associations.lib.utilities import getattr_from_list, getattr_from_list_nofail
from jwst.associations.registry import RegistryMarker
from jwst.lib.suffix import remove_suffix
# Configure logging
logger = logging.getLogger(__name__)
logger.addHandler(logging.NullHandler())
__all__ = [
'_EMPTY',
'ASN_SCHEMA',
'AsnMixin_Lv2Image',
'AsnMixin_Lv2Nod',
'AsnMixin_Lv2Special',
'AsnMixin_Lv2Spectral',
'AsnMixin_Lv2WFSS',
'Constraint_Background',
'Constraint_Base',
'Constraint_ExtCal',
'Constraint_Image_Nonscience',
'Constraint_Image_Science',
'Constraint_Imprint',
'Constraint_Imprint_Special',
'Constraint_Mode',
'Constraint_Single_Science',
'Constraint_Special',
'Constraint_Spectral_Science',
'Constraint_Target',
'DMSLevel2bBase',
'DMSAttrConstraint',
'Utility'
]
# The schema that these associations must adhere to.
ASN_SCHEMA = RegistryMarker.schema(libpath('asn_schema_jw_level2b.json'))
# Flag to exposure type
FLAG_TO_EXPTYPE = {
'background': 'background',
}
# File templates
_DMS_POOLNAME_REGEX = r'jw(\d{5})_(\d{3})_(\d{8}[Tt]\d{6})_pool'
_LEVEL1B_REGEX = r'(?P<path>.+)(?P<type>_uncal)(?P<extension>\..+)'
# Key that uniquely identifies items.
KEY = 'expname'
class DMSLevel2bBase(DMSBaseMixin, Association):
"""Basic class for DMS Level2 associations."""
# Set the validation schema
schema_file = ASN_SCHEMA.schema
# Attribute values that are indicate the
# attribute is not specified.
INVALID_VALUES = _EMPTY
def __init__(self, *args, **kwargs):
super(DMSLevel2bBase, self).__init__(*args, **kwargs)
# Initialize validity checks
self.validity.update({
'has_science': {
'validated': False,
'check': lambda member: member['exptype'] == 'science'
},
'allowed_candidates': {
'validated': False,
'check': self.validate_candidates
}
})
# Other presumptions on the association
if 'constraints' not in self.data:
self.data['constraints'] = 'No constraints'
if 'asn_type' not in self.data:
self.data['asn_type'] = 'user_built'
if 'asn_id' not in self.data:
self.data['asn_id'] = 'a3001'
if 'asn_pool' not in self.data:
self.data['asn_pool'] = 'none'
def get_exposure_type(self, item, default='science'):
"""General Level 2 override of exposure type definition
The exposure type definition is overridden from the default
for the following cases:
- 'psf' -> 'science'
Parameters
----------
item : dict
The pool entry to determine the exposure type of
default : str or None
The default exposure type.
If None, routine will raise LookupError
Returns
-------
exposure_type
Always what is defined as `default`
"""
self.original_exposure_type = super(DMSLevel2bBase, self).get_exposure_type(item, default=default)
if self.original_exposure_type == 'psf':
return default
return self.original_exposure_type
def members_by_type(self, member_type):
"""Get list of members by their exposure type"""
member_type = member_type.lower()
try:
members = self.current_product['members']
except KeyError:
result = []
else:
result = [
member
for member in members
if member_type == member['exptype'].lower()
]
return result
def has_science(self):
"""Does association have a science member
-------
bool
True if it does.
"""
limit_reached = len(self.members_by_type('science')) >= 1
return limit_reached
def dms_product_name(self):
"""Define product name."""
try:
science = self.members_by_type('science')[0]
except IndexError:
return PRODUCT_NAME_DEFAULT
try:
science_path, ext = splitext(science['expname'])
except Exception:
return PRODUCT_NAME_DEFAULT
no_suffix_path, separator = remove_suffix(science_path)
return no_suffix_path
def make_member(self, item):
"""Create a member from the item
Parameters
----------
item : dict
The item to create member from.
Returns
-------
member : Member
The member
"""
# Set exposure error status.
try:
exposerr = item['exposerr']
except KeyError:
exposerr = None
# Create the member.
# The various `is_item_xxx` methods are used to determine whether the name
# should represent the form of the data product containing all integrations.
member = Member(
{
'expname': Utility.rename_to_level2a(
item['filename'],
use_integrations=(self.is_item_coron(item) |
# NIS_AMI used to use rate files;
# updated to use rateints
self.is_item_ami(item) |
self.is_item_tso(item)),
),
'exptype': self.get_exposure_type(item),
'exposerr': exposerr,
},
item=item
)
return member
def _init_hook(self, item):
"""Post-check and pre-add initialization"""
self.data['target'] = item['targetid']
self.data['program'] = '{:0>5s}'.format(item['program'])
self.data['asn_pool'] = basename(
item.meta['pool_file']
)
self.data['constraints'] = str(self.constraints)
self.data['asn_id'] = self.acid.id
self.new_product(self.dms_product_name())
def _add(self, item):
"""Add item to this association.
Parameters
----------
item : dict
The item to be adding.
"""
member = self.make_member(item)
if self.is_member(member):
return
members = self.current_product['members']
members.append(member)
self.update_validity(member)
# Update association state due to new member
self.update_asn()
def _add_items(self,
items,
meta=None,
product_name_func=None,
acid='o999',
**kwargs):
"""Force adding items to the association
Parameters
----------
items : [object[, ...]]
A list of items to make members of the association.
meta : dict
A dict to be merged into the association meta information.
The following are suggested to be assigned:
- `asn_type`
The type of association.
- `asn_rule`
The rule which created this association.
- `asn_pool`
The pool from which the exposures came from
- `program`
Originating observing program
product_name_func : func
Used if product name is 'undefined' using
the class's procedures.
acid : str
The association candidate id to use. Since Level2
associations require it, one must be specified.
Notes
-----
This is a low-level shortcut into adding members, such as file names,
to an association. All defined shortcuts and other initializations are
by-passed, resulting in a potentially unusable association.
`product_name_func` is used to define the product names instead of
the default methods. The call signature is:
product_name_func(item, idx)
where `item` is each item being added and `idx` is the count of items.
"""
if meta is None:
meta = {}
# Setup association candidate.
if acid.startswith('o'):
ac_type = 'observation'
elif acid.startswith('c'):
ac_type = 'background'
else:
raise ValueError(
'Invalid association id specified: "{}"'
'\n\tMust be of form "oXXX" or "c1XXX"'.format(acid)
)
self._acid = ACID((acid, ac_type))
# set the default exptype
exptype = 'science'
for idx, item in enumerate(items, start=1):
self.new_product()
members = self.current_product['members']
if isinstance(item, tuple):
expname = item[0]
else:
expname = item
# check to see if kwargs are passed and if exptype is given
if kwargs:
if 'with_exptype' in kwargs:
if item[1]:
exptype = item[1]
else:
exptype = 'science'
member = Member({
'expname': expname,
'exptype': exptype
}, item=item)
members.append(member)
self.update_validity(member)
self.update_asn()
# If a product name function is given, attempt
# to use.
if product_name_func is not None:
try:
self.current_product['name'] = product_name_func(item, idx)
except Exception:
logger.debug(
'Attempted use of product_name_func failed.'
' Default product name used.'
)
self.data.update(meta)
self.sequence = next(self._sequence)
def update_asn(self):
"""Update association info based on current members"""
super(DMSLevel2bBase, self).update_asn()
self.current_product['name'] = self.dms_product_name()
def validate_candidates(self, member):
"""Allow only OBSERVATION or BACKGROUND candidates
Parameters
----------
member : Member
Member being added. Ignored.
Returns
-------
True if candidate is OBSERVATION.
True if candidate is BACKGROUND and at least one
member is background.
Otherwise, False
"""
# If an observation, then we're good.
if self.acid.type.lower() == 'observation':
return True
# If a background, check that there is a background
# exposure
if self.acid.type.lower() == 'background':
for entry in self.current_product['members']:
if entry['exptype'].lower() == 'background':
return True
# If not background member, or some other candidate type,
# fail.
return False
def __repr__(self):
try:
file_name, json_repr = self.ioregistry['json'].dump(self)
except Exception:
return str(self.__class__)
return json_repr
def __str__(self):
"""Create human readable version of the association
"""
result = ['Association {:s}'.format(self.asn_name)]
# Parameters of the association
result.append(
' Parameters:'
' Product type: {asn_type:s}'
' Rule: {asn_rule:s}'
' Program: {program:s}'
' Target: {target:s}'
' Pool: {asn_pool:s}'.format(
asn_type=getattr(self.data, 'asn_type', 'indetermined'),
asn_rule=getattr(self.data, 'asn_rule', 'indetermined'),
program=getattr(self.data, 'program', 'indetermined'),
target=getattr(self.data, 'target', 'indetermined'),
asn_pool=getattr(self.data, 'asn_pool', 'indetermined'),
)
)
result.append(' {:s}'.format(str(self.constraints)))
# Products of the association
for product in self.data['products']:
result.append(
'\t{} with {} members'.format(
product['name'],
len(product['members'])
)
)
# That's all folks
result.append('\n')
return '\n'.join(result)
@RegistryMarker.utility
class Utility():
"""Utility functions that understand DMS Level 3 associations"""
@staticmethod
@RegistryMarker.callback('finalize')
def finalize(associations):
"""Check validity and duplications in an association list
Parameters
----------
associations:[association[, ...]]
List of associations
Returns
-------
finalized_associations : [association[, ...]]
The validated list of associations
"""
finalized_asns = []
lv2_asns = []
for asn in associations:
if isinstance(asn, DMSLevel2bBase):
finalized = asn.finalize()
if finalized is not None:
lv2_asns.extend(finalized)
else:
finalized_asns.append(asn)
# Having duplicate Level 2 associations is expected.
lv2_asns = prune(lv2_asns)
# Ensure sequencing is correct.
Utility_Level3.resequence(lv2_asns)
return finalized_asns + lv2_asns
@staticmethod
def merge_asns(associations):
"""merge level2 associations
Parameters
----------
associations : [asn(, ...)]
Associations to search for merging.
Returns
-------
associations : [association(, ...)]
List of associations, some of which may be merged.
"""
others = []
lv2_asns = []
for asn in associations:
if isinstance(asn, DMSLevel2bBase):
lv2_asns.append(asn)
else:
others.append(asn)
lv2_asns = Utility._merge_asns(lv2_asns)
return others + lv2_asns
@staticmethod
def rename_to_level2a(level1b_name, use_integrations=False):
"""Rename a Level 1b Exposure to another level
Parameters
----------
level1b_name : str
The Level 1b exposure name.
use_integrations : boolean
Use 'rateints' instead of 'rate' as the suffix.
Returns
-------
str
The Level 2a name
"""
match = re.match(_LEVEL1B_REGEX, level1b_name)
if match is None or match.group('type') != '_uncal':
logger.warning((
'Item FILENAME="{}" is not a Level 1b name. '
'Cannot transform to Level 2a.'
).format(
level1b_name
))
return level1b_name
suffix = 'rate'
if use_integrations:
suffix = 'rateints'
level2a_name = ''.join([
match.group('path'),
'_',
suffix,
match.group('extension')
])
return level2a_name
@staticmethod
def resequence(*args, **kwargs):
"""Resequence the numbers to conform to level 3 asns"""
return Utility_Level3.resequence(*args, **kwargs)
@staticmethod
def sort_by_candidate(asns):
"""Sort associations by candidate
Parameters
----------
asns: [Association[,...]]
List of associations
Returns
-------
sorted_by_candidate: [Associations[,...]]
New list of the associations sorted.
Notes
-----
The current definition of candidates allows strictly alphabetical
sorting:
aXXXX > cXXXX > oXXX
If this changes, a comparison function will need be implemented
"""
return sorted(asns, key=lambda asn: asn['asn_id'])
@staticmethod
def _merge_asns(asns):
"""Merge associations by `asn_type` and `asn_id`
Parameters
----------
associations : [asn(, ...)]
Associations to search for merging.
Returns
-------
associations : [association(, ...)]
List of associations, some of which may be merged.
"""
merged = {}
for asn in asns:
idx = '_'.join([asn['asn_type'], asn['asn_id']])
try:
current_asn = merged[idx]
except KeyError:
merged[idx] = asn
current_asn = asn
for product in asn['products']:
merge_occurred = False
for current_product in current_asn['products']:
if product['name'] == current_product['name']:
member_names = set([
member['expname']
for member in product['members']
])
current_member_names = [
member['expname']
for member in current_product['members']
]
new_names = member_names.difference(
current_member_names
)
new_members = [
member
for member in product['members']
if member['expname'] in new_names
]
current_product['members'].extend(new_members)
merge_occurred = True
if not merge_occurred:
current_asn['products'].append(product)
merged_asns = [
asn
for asn in merged.values()
]
return merged_asns
# -----------------
# Basic constraints
# -----------------
class Constraint_Base(Constraint):
"""Select on program and instrument"""
def __init__(self):
super(Constraint_Base, self).__init__([
DMSAttrConstraint(
name='program',
sources=['program']
),
DMSAttrConstraint(
name='is_tso',
sources=['tsovisit'],
required=False,
force_unique=True,
)
])
class Constraint_Background(DMSAttrConstraint):
"""Select backgrounds"""
def __init__(self):
super(Constraint_Background, self).__init__(
sources=['bkgdtarg'],
force_unique=False,
name='background',
force_reprocess=ListCategory.EXISTING,
only_on_match=True,
)
class Constraint_ExtCal(Constraint):
"""Remove any nis_extcals from the associations, they
are NOT to receive level-2b or level-3 processing!"""
def __init__(self):
super(Constraint_ExtCal, self).__init__(
[
DMSAttrConstraint(
name='exp_type',
sources=['exp_type'],
value='nis_extcal'
)
],
reduce=Constraint.notany
)
class Constraint_Imprint(Constraint):
"""Select on imprint exposures"""
def __init__(self):
super(Constraint_Imprint, self).__init__(
[
DMSAttrConstraint(
name='imprint',
sources=['is_imprt']
)
],
reprocess_on_match=True,
work_over=ListCategory.EXISTING,
)
class Constraint_Imprint_Special(Constraint):
"""Select on imprint exposures"""
def __init__(self, association=None):
# If an association is not provided, the check for original
# exposure type is ignored.
if association is None:
def sources(item):
return 'not imprint'
else:
def sources(item):
return association.original_exposure_type
super(Constraint_Imprint_Special, self).__init__(
[
DMSAttrConstraint(
name='imprint',
sources=['is_imprt'],
force_reprocess=ListCategory.EXISTING,
only_on_match=True,
),
DMSAttrConstraint(
name='mosaic_tile',
sources=['mostilno'],
),
SimpleConstraint(
value='imprint',
sources=sources,
test=lambda v1, v2: v1 != v2,
force_unique=False,
),
],
)
class Constraint_Mode(Constraint):
"""Select on instrument and optical path"""
def __init__(self):
super(Constraint_Mode, self).__init__([
DMSAttrConstraint(
name='instrument',
sources=['instrume']
),
DMSAttrConstraint(
name='detector',
sources=['detector']
),
DMSAttrConstraint(
name='opt_elem',
sources=['filter', 'band']
),
DMSAttrConstraint(
name='opt_elem2',
sources=['pupil', 'grating'],
required=False,
),
DMSAttrConstraint(
name='fxd_slit',
sources=['fxd_slit'],
required=False,
),
DMSAttrConstraint(
name='subarray',
sources=['subarray'],
required=False,
),
DMSAttrConstraint(
name='channel',
sources=['channel'],
required=False,
),
Constraint(
[
DMSAttrConstraint(
sources=['detector'],
value='nirspec'
),
DMSAttrConstraint(
sources=['filter'],
value='opaque'
),
],
reduce=Constraint.notany
),
Constraint(
[
DMSAttrConstraint(
sources=['detector'],
value='nrcblong'
),
DMSAttrConstraint(
sources=['exp_type'],
value='nrc_tsgrism'
)
],
reduce=Constraint.notall
),
Constraint(
[
DMSAttrConstraint(
sources=['visitype'],
value='.+wfsc.+',
),
],
reduce=Constraint.notany
),
DMSAttrConstraint(
name='slit',
sources=['fxd_slit'],
required=False,
)
])
class Constraint_Image_Science(DMSAttrConstraint):
"""Select on science images"""
def __init__(self):
super(Constraint_Image_Science, self).__init__(
name='exp_type',
sources=['exp_type'],
value='|'.join(IMAGE2_SCIENCE_EXP_TYPES)
)
class Constraint_Image_Nonscience(Constraint):
"""Select on non-science images"""
def __init__(self):
super(Constraint_Image_Nonscience, self).__init__(
[
Constraint_TargetAcq(),
DMSAttrConstraint(
name='non_science',
sources=['exp_type'],
value='|'.join(IMAGE2_NONSCIENCE_EXP_TYPES),
),
Constraint(
[
DMSAttrConstraint(
name='exp_type',
sources=['exp_type'],
value='nrs_msaspec'
),
DMSAttrConstraint(
sources=['msastate'],
value='primarypark_allopen'
),
DMSAttrConstraint(
sources=['grating'],
value='mirror'
)
]
)
],
reduce=Constraint.any
)
class Constraint_Single_Science(Constraint):
"""Allow only single science exposure
Parameters
----------
has_science_fn : func
Function to determine whether the association has a science member already.
No arguments are provided
exposure_type_fn : func
Function to determine the association exposure type of the item.
Should take a single argument of item.
sc_kwargs : dict
Keyword arguments to pass to the parent class `Constraint`
Notes
-----
The `has_science_fn` is further wrapped in a lambda function
to provide a closure. Otherwise if the function is a bound method,
that method may end up pointing to an instance that is not calling
this constraint.
"""
def __init__(self, has_science_fn, exposure_type_fn, **sc_kwargs):
super(Constraint_Single_Science, self).__init__(
[
SimpleConstraint(
value=True,
sources=lambda item: exposure_type_fn(item) == 'science',
),
SimpleConstraint(
value=False,
sources=lambda item: has_science_fn(),
),
],
**sc_kwargs
)
class Constraint_Special(DMSAttrConstraint):
"""Select on backgrounds and other auxiliary images"""
def __init__(self):
super(Constraint_Special, self).__init__(
name='is_special',
sources=[
'bkgdtarg',
'is_psf'
],
)
class Constraint_Spectral_Science(Constraint):
"""Select on spectral science
Parameters
exclude_exp_types : [exp_type[, ...]]
List of exposure types to not consider from
from the general list.
"""
def __init__(self, exclude_exp_types=None):
if exclude_exp_types is None:
general_science = SPEC2_SCIENCE_EXP_TYPES
else:
general_science = set(SPEC2_SCIENCE_EXP_TYPES).symmetric_difference(
exclude_exp_types
)
super(Constraint_Spectral_Science, self).__init__(
[
DMSAttrConstraint(
name='exp_type',
sources=['exp_type'],
value='|'.join(general_science)
)
],
reduce=Constraint.any
)
class Constraint_Target(Constraint):
"""Select on target id"""
def __init__(self):
constraints = [
Constraint([
DMSAttrConstraint(
name='acdirect',
sources=['asn_candidate'],
value=r"\[\('c\d{4}', 'direct_image'\)\]"
),
SimpleConstraint(
name='target',
sources=lambda item: '000'
)]),
DMSAttrConstraint(
name='target',
sources=['targetid'],
)
]
super(Constraint_Target, self).__init__(constraints, reduce=Constraint.any)
# ---------------------------------------------
# Mixins to define the broad category of rules.
# ---------------------------------------------
class AsnMixin_Lv2Image:
"""Level 2 Image association base"""
def _init_hook(self, item):
"""Post-check and pre-add initialization"""
super(AsnMixin_Lv2Image, self)._init_hook(item)
self.data['asn_type'] = 'image2'
class AsnMixin_Lv2Nod:
"""Associations that need to create nodding associations
For some spectrographic modes, background spectra are taken by
nodding between different slits, or internal slit positions.
The main associations rules will collect all the exposures of all the nods
into a single association. Then, on finalization, this one association
is split out into many associations, where each nod is, in turn, treated
as science, and the other nods are treated as background.
"""
@staticmethod
def nod_background_overlap(science_item, background_item):
"""
Check that a candidate background nod will not overlap with science.
For NIRSpec fixed slit or MOS data, this returns True if the
background candidate shares a primary dither point with the
science.
In addition, for NIRSpec fixed slit exposures taken with slit
S1600A1 in a 5-point nod pattern, this returns True when the
background candidate is in the next closest primary position
to the science.
For any other data, this function returns False (no overlap).
"""
# Get exp_type, needed for any data:
# if not present, return False
try:
exptype = str(science_item['exp_type']).lower()
except KeyError:
return False