from astrodata.Descriptors import DescriptorValue
from pprint import pformat
import sys


dval = DescriptorValue(10)

db = DescriptorValue(None)

print db.collapse_value()
print str(db)

ndict = {}
vdict = {}
complexdict = {}

for i in range(1,4):
    for nam in ["SCI", "VAR", "DQ"]:
        ndict[(nam,i)] = None
        vdict[(nam,i)] = 13
        complexdict[(nam,i)] = i*10
        
print "ndict = \n"
print pformat(ndict)
print "[]" * 10
print "vdict = \n"
print pformat(vdict)
print "[]"*10
print "complexdict = \n"
print pformat(complexdict)
print "[]"*10
예제 #2
0
 def pixel_scale(self, dataset, **args):
     # First try to calculate the pixel scale using the values of the WCS
     # matrix elements keywords
     #
     # Since this descriptor function accesses keywords in the headers of
     # the pixel data extensions, always construct a dictionary where the
     # key of the dictionary is an (EXTNAME, EXTVER) tuple.
     ret_pixel_scale_dict = {}
     
     # Determine the WCS matrix elements keywords from the global keyword
     # dictionary
     keyword1 = self.get_descriptor_key("key_cd11")
     keyword2 = self.get_descriptor_key("key_cd12")
     keyword3 = self.get_descriptor_key("key_cd21")
     keyword4 = self.get_descriptor_key("key_cd22")
     
     # Get the value of the WCS matrix elements keywords from the header of
     # each pixel data extension as a dictionary where the key of the
     # dictionary is an ("*", EXTVER) tuple
     cd_dict = gmu.get_key_value_dict(
         adinput=dataset, keyword=[keyword1, keyword2, keyword3, keyword4])
     
     cd11_dict = cd_dict[keyword1]
     cd12_dict = cd_dict[keyword2]
     cd21_dict = cd_dict[keyword3]
     cd22_dict = cd_dict[keyword4]
     
     if cd11_dict is None:
         # Get the pixel scale value using the value of the pixel scale
         # keyword in the PHU
         pixel_scale = self._get_pixel_scale_from_header(dataset=dataset)
         
         # Loop over the pixel data extensions in the dataset
         pixel_scale_dict = {}
         for ext in dataset[pixel_exts]:
             # Update the dictionary with the pixel_scale value
             pixel_scale_dict.update(
                 {(ext.extname(), ext.extver): pixel_scale})
         
         # Instantiate the DescriptorValue (DV) object
         dv = DescriptorValue(pixel_scale_dict)
         
         # Create a new dictionary where the key of the dictionary is an
         # EXTVER integer
         extver_dict = dv.collapse_by_extver()
         
         if not dv.validate_collapse_by_extver(extver_dict):
             # The validate_collapse_by_extver function returns False if the
             # values in the dictionary with the same EXTVER are not equal
             raise Errors.CollapseError()
         
         ret_pixel_scale_dict = pixel_scale_dict
     
     else:
         for ext_name_ver, cd11 in cd11_dict.iteritems():
             cd12 = None
             if cd12_dict is not None:
                 cd12 = cd12_dict[ext_name_ver]
             cd21 = None
             if cd21_dict is not None:
                 cd21 = cd21_dict[ext_name_ver]
             cd22 = None
             if cd22_dict is not None:
                 cd22 = cd22_dict[ext_name_ver]
             
             pixel_scale = None
             if not None in [cd11, cd12, cd21, cd22]:
                 # Calculate the pixel scale using the WCS matrix elements
                 pixel_scale = 3600 * (
                   math.sqrt(math.pow(cd11, 2) + math.pow(cd12, 2)) +
                   math.sqrt(math.pow(cd21, 2) + math.pow(cd22, 2))) / 2
             
             if pixel_scale is None or pixel_scale == 0.0:
                 # Get the pixel scale value using the value of the pixel
                 # scale keyword
                 pixel_scale = self._get_pixel_scale_from_header(
                     dataset=dataset)
             
             # Update the dictionary with the pixel scale value
             ret_pixel_scale_dict.update({ext_name_ver: pixel_scale})
     
     # Instantiate the return DescriptorValue (DV) object using the newly
     # created dictionary
     ret_dv = DescriptorValue(ret_pixel_scale_dict, name="pixel_scale",
                              ad=dataset)
     return ret_dv
예제 #3
0
def determine_inputs(input_a=None, input_b=None):
    """
    When either the add, div, mult or sub functions are called, input_a is
    always the input AstroData object that will have the operation applied to
    it:
    
      add  --> input_a + input_b
      div  --> input_a / input_b
      mult --> input_a * input_b
      sub  --> input_a - input_b
    
    This helper function determines what input_b is so that the operation can
    be executed appropriately. Possible options include another AstroData
    object, a dictionary, list, float or integer or a DescriptorValue (DV)
    object.
    
    In those cases where input_b is another AstroData object, the size of the
    data are checked to ensure they are the same so that the operation can be
    performed.
    
    In those cases where input_b is a dictionary, list, float, integer or a
    DescriptorValue object, create and return a dictionary where the key of the
    dictionary is an EXTVER integer.
    
    """
    # If input_b is a dictionary or a DescriptorValue (DV) object, return a
    # dictionary where the key of the dictionary is an EXTVER integer
    if (isinstance(input_b, astrodata.Descriptors.DescriptorValue) or
        isinstance(input_b, dict)):
        
        if isinstance(input_b, dict):
            # Instantiate a DV object using the input dictionary
            dv = DescriptorValue(input_b)
        else:
            dv = input_b
        
        # Create a dictionary where the key of the dictionary is an EXTVER
        # integer
        extver_dict = dv.collapse_by_extver()
        
        if not dv.validate_collapse_by_extver(extver_dict):
            # The validate_collapse_by_extver function returns False if the
            # values in the dictionary with the same EXTVER are not equal.
            # However, in this case only the values for the science extensions
            # are required.
            sci_dict = dict(
                (k, v) for k, v in input_b.iteritems() if k[0] == SCI)
            
            # Instantiate a new DV object using the dictionary containing only
            # the values for the science extensions 
            new_dv = DescriptorValue(sci_dict)
            
            # Create a dictionary where the key of the dictionary is an EXTVER
            # integer
            extver_dict = new_dv.collapse_by_extver()
        
        return_value = extver_dict
    
    # If input_b is a single float or a single integer, create a dictionary
    # where the key of the dictionary is an EXTVER integer for each science
    # extension and the value is the single float or single integer
    elif isinstance(input_b, float) or isinstance(input_b, int):
        
        return_value = {}
        for ext in input_a[SCI]:
            
            # Retrieve the extension number for this extension
            extver = ext.extver()
            
            # Add the single float or single integer to the dictionary for
            # this extension
            return_value.update({extver: input_b})
    
    # If input_b is a list, create a dictionary where the key of the dictionary
    # is an EXTVER integer for each science extension and the value is taken
    # sequentially from the list
    elif isinstance(input_b, list):
        
        return_value = {}
        for ext in input_a[SCI]:
            
            # Retrieve the extension number for this extension
            extver = ext.extver()
            
            # Add the appropriate element of the list to the dictionary for
            # this extension
            return_value.update({extver: input_b[extver-1]})
    
    # Check to see if input_b is an AstroData object
    elif isinstance(input_b, astrodata.AstroData):
        
        for ext in input_a[SCI]:
            
            # Retrieve the extension number for this extension
            extver = ext.extver()
            
            # Make sure that the pixel data arrays are same size/shape
            if (input_a[(SCI, extver)].data.shape !=
                input_b[(SCI, extver)].data.shape):
                msg = ("The input science extensions "
                       "%(input_a)s[%(SCI)s,%(EXTVER)d] and "
                       "%(input_b)s[%(SCI)s,%(EXTVER)d] are not the same "
                       "size" % (
                    {"input_a": input_a.filename, "input_b":input_b.filename,
                     "SCI": SCI, "EXTVER": extver}))
                raise Errors.Error(msg)
            
            # Return the AstroData object
            return_value = input_b
    
    else:
        raise Errors.Error("Unknown type for input_b")
    
    return return_value
def get_key_value_dict(adinput=None, keyword=None, dict_key_extver=False):
    """
    The get_key_value_dict() function works similarly to the AstroData
    get_key_value() and phu_get_key_value() member functions in that if the
    value of the keyword for each pixel data extension is None, None is
    returned and the reason why the value is None is stored in the
    exception_info attribute of the AstroData object.
    
    :param adinput: the AstroData object
    :type adinput: AstroData
    
    :param keyword: the keyword(s) to access in the pixel data extensions of
                    the AstroData object
    :type keyword: string or list of strings
    
    :rtype: dictionary
    :return: if a single keyword is supplied to the keyword parameter, the key
             of the return dictionary is the ('*', EXTVER) tuple and the value
             is the value of the keyword from the header of the pixel data
             extension of the input AstroData object with that EXTVER. If
             multiple keywords are supplied to the keyword parameter, the key
             of the return dictionary is the name of the keyword as supplied to
             the keyword parameter and the value is a dictionary, where the key
             of the dictionary is the ('*', EXTVER) tuple and the value is the
             value of the keyword from the header of the pixel data extension
             of the input AstroData object with that EXTVER.
    
    """
    # Since this helper function accesses keywords in the headers of the pixel
    # data extensions, first construct a dictionary where the key of the
    # dictionary is an (EXTNAME, EXTVER) tuple
    all_keyword_value_dict = {}
    final_keyword_value_dict = {}

    # The validate_input function ensures that the input is not None and
    # returns a list containing one or more inputs
    keyword_list = gt.validate_input(input=keyword)

    return_dictionary = False

    # Loop over the pixel data extensions in the dataset
    for ext in adinput[pixel_exts]:

        # Loop over each keyword in the input keyword list
        for keyword in keyword_list:

            # Get the value of the keyword from the header of each pixel data
            # extension
            value = ext.get_key_value(keyword)

            if value is None:
                # The get_key_value() function returns None if a value cannot
                # be found and stores the exception info. Store the last
                # occurance of the exception to the dataset.
                if hasattr(ext, "exception_info"):
                    setattr(adinput, "exception_info", ext.exception_info)

            if keyword in all_keyword_value_dict:
                # Update the dictionary with the value
                all_keyword_value_dict[keyword].update({(ext.extname(), ext.extver()): value})
            else:
                all_keyword_value_dict.update({keyword: {(ext.extname(), ext.extver()): value}})

    for keyword, keyword_value_dict in all_keyword_value_dict.iteritems():
        try:
            if keyword_value_dict == {}:
                # If the dictionary is still empty, the AstroData object has no
                # pixel data extensions
                raise Errors.CorruptDataError()

            unique_values = set(keyword_value_dict.values())
            if len(unique_values) == 1 and None in unique_values:
                # The value of the keyword was not found for any of the pixel
                # data extensions (all the values in the dictionary are equal
                # to None)
                raise adinput.exception_info

            # Instantiate the DescriptorValue (DV) object
            dv = DescriptorValue(keyword_value_dict)

            # Create a new dictionary where the key of the dictionary is an
            # EXTVER integer
            extver_dict = dv.collapse_by_extver()

            if not dv.validate_collapse_by_extver(extver_dict):
                # The validate_collapse_by_extver function returns False if the
                # values in the dictionary with the same EXTVER are not equal
                raise Errors.CollapseError()

            if dict_key_extver:
                # Return the dictionary where the key of the dictionary is an
                # EXTVER integer
                ret_dict = extver_dict
            else:
                # Instantiate a new DV object using the newly created
                # dictionary and get the dictionary where the key of the
                # dictionary is an ("*", EXTVER) tuple
                new_dv = DescriptorValue(extver_dict)
                ret_dict = new_dv.as_dict()

        except:
            setattr(adinput, "exception_info", sys.exc_info()[1])
            ret_dict = None

        # Construct the dictionary of dictionaries
        final_keyword_value_dict.update({keyword: ret_dict})

    if len(final_keyword_value_dict) == 1:
        return final_keyword_value_dict.values()[0]
    else:
        return final_keyword_value_dict