예제 #1
0
    def __set__(self, instance, value):
        def set_value(new_value):
            if len(new_value) < self.minimum_length:
                msg = 'Attribute {} of class {} is an float list of size {},\n\t' \
                      'and must have size at least {}.'.format(
                        self.name, instance.__class__.__name__, value.size, self.minimum_length)
                if self.strict:
                    raise ValueError(msg)
                else:
                    logger.info(msg)
            if len(new_value) > self.maximum_length:
                msg = 'Attribute {} of class {} is a float list of size {},\n\t' \
                      'and must have size no larger than {}.'.format(
                        self.name, instance.__class__.__name__, value.size, self.maximum_length)
                if self.strict:
                    raise ValueError(msg)
                else:
                    logger.info(msg)
            self.data[instance] = new_value

        if super(FloatListDescriptor, self).__set__(instance, value):  # the None handler...kinda hacky
            return

        if isinstance(value, float):
            set_value([value, ])
        elif isinstance(value, ElementTree.Element):
            set_value([float(get_node_value(value)), ])
        elif isinstance(value, list):
            if len(value) == 0 or isinstance(value[0], float):
                set_value(value)
            elif isinstance(value[0], ElementTree.Element):
                set_value([float(get_node_value(nod)) for nod in value])
        else:
            raise TypeError(_type_text.format(self.name, instance.__class__.__name__, type(value)))
예제 #2
0
    def __set__(self, instance, value):
        def set_value(new_val):
            if len(new_val) < self.minimum_length:
                msg = 'Attribute {} of class {} is a double array of size {},\n\t' \
                      'and must have size at least {}.'.format(
                        self.name, instance.__class__.__name__, value.size, self.minimum_length)
                if self.strict:
                    raise ValueError(msg)
                else:
                    logger.error(msg)
            if len(new_val) > self.maximum_length:
                msg = 'Attribute {} of class {} is a double array of size {},\n\t' \
                      'and must have size no larger than {}.'.format(
                        self.name, instance.__class__.__name__, value.size, self.maximum_length)
                if self.strict:
                    raise ValueError(msg)
                else:
                    logger.error(msg)
            self.data[instance] = new_val

        if super(FloatArrayDescriptor, self).__set__(instance, value):  # the None handler...kinda hacky
            return

        if isinstance(value, numpy.ndarray):
            if not (len(value) == 1) and (numpy.dtype.name == 'float64'):
                raise ValueError('Only one-dimensional ndarrays of dtype float64 are supported here.')
            set_value(value)
        elif isinstance(value, ElementTree.Element):
            xml_ns = getattr(instance, '_xml_ns', None)
            # noinspection PyProtectedMember
            if hasattr(instance, '_child_xml_ns_key') and self.name in instance._child_xml_ns_key:
                # noinspection PyProtectedMember
                xml_ns_key = instance._child_xml_ns_key[self.name]
            else:
                xml_ns_key = getattr(instance, '_xml_ns_key', None)

            size = int_func(value.attrib['size'])
            child_nodes = find_children(value, self.child_tag, xml_ns, xml_ns_key)
            if len(child_nodes) != size:
                raise ValueError(
                    'Field {} of double array type functionality belonging to class {} got a ElementTree element '
                    'with size attribute {}, but has {} child nodes with tag {}.'.format(
                        self.name, instance.__class__.__name__, size, len(child_nodes), self.child_tag))
            new_value = numpy.empty((size,), dtype=numpy.float64)
            for i, node in enumerate(child_nodes):
                new_value[i] = float(get_node_value(node))
            set_value(new_value)
        elif isinstance(value, list):
            # user or json deserialization
            set_value(numpy.array(value, dtype=numpy.float64))
        else:
            raise TypeError(
                'Field {} of class {} got incompatible type {}.'.format(
                    self.name, instance.__class__.__name__, type(value)))
예제 #3
0
파일: blocks.py 프로젝트: ngageoint/sarpy
    def from_node(cls, node, xml_ns, ns_key=None, kwargs=None):
        dim1 = int(node.attrib['size'])
        dim2 = int(node.attrib['numLuts'])
        arr = numpy.zeros((dim1, dim2), dtype=numpy.uint16)

        lut_key = cls._child_xml_ns_key.get('LUTValues', ns_key)
        lut_nodes = find_children(node, 'LUTValues', xml_ns, lut_key)
        for i, lut_node in enumerate(lut_nodes):
            arr[:, i] = [str(el) for el in get_node_value(lut_node)]
        if numpy.max(arr) < 256:
            arr = numpy.cast[numpy.uint8](arr)
        return cls(LUTValues=arr)
예제 #4
0
파일: blocks.py 프로젝트: ngageoint/sarpy
 def from_node(cls, node, xml_ns, ns_key=None, kwargs=None):
     num_phasings = int(node.attrib['numPhasings'])
     num_points = int(node.attrib['numPoints'])
     coefs = numpy.zeros((num_phasings+1, num_points+1), dtype=numpy.float64)
     ckey = cls._child_xml_ns_key.get('Coefs', ns_key)
     coef_nodes = find_children(node, 'Coef', xml_ns, ckey)
     for cnode in coef_nodes:
         ind1 = int(cnode.attrib['phasing'])
         ind2 = int(cnode.attrib['point'])
         val = float(get_node_value(cnode))
         coefs[ind1, ind2] = val
     return cls(Coefs=coefs)
예제 #5
0
 def from_node(cls, node, xml_ns, ns_key=None, kwargs=None):
     if kwargs is None:
         kwargs = OrderedDict()
     # parse the ModuleName
     mn_key = cls._child_xml_ns_key.get('ModuleName', ns_key)
     mn_node = find_first_child(node, 'ModuleName', xml_ns, mn_key)
     kwargs['ModuleName'] = get_node_value(mn_node)
     kwargs['name'] = mn_node.attrib.get('name', None)
     # parse the ProcessingModule children
     pm_key = cls._child_xml_ns_key.get('ProcessingModules', ns_key)
     kwargs['ProcessingModules'] = find_children(node, 'ProcessingModule', xml_ns, pm_key)
     return super(ProcessingModuleType, cls).from_node(node, xml_ns, ns_key=ns_key, kwargs=kwargs)
예제 #6
0
    def __set__(self, instance, value):
        def set_value(new_value):
            if len(new_value) < self.minimum_length:
                msg = 'Attribute {} of class {} is a string list of size {},\n\t' \
                      'and must have length at least {}.'.format(
                        self.name, instance.__class__.__name__, value.size, self.minimum_length)
                if self.strict:
                    raise ValueError(msg)
                else:
                    logger.error(msg)
            if len(new_value) > self.maximum_length:
                msg = 'Attribute {} of class {} is a string list of size {},\n\t' \
                      'and must have length no greater than {}.'.format(
                        self.name, instance.__class__.__name__, value.size, self.maximum_length)
                if self.strict:
                    raise ValueError(msg)
                else:
                    logger.error(msg)
            self.data[instance] = new_value

        if super(StringListDescriptor, self).__set__(instance, value):  # the None handler...kinda hacky
            return

        if isinstance(value, string_types):
            set_value([value, ])
        elif isinstance(value, ElementTree.Element):
            set_value([get_node_value(value), ])
        elif isinstance(value, list):
            if len(value) == 0 or isinstance(value[0], string_types):
                set_value(value)
            elif isinstance(value[0], ElementTree.Element):
                set_value([get_node_value(nod) for nod in value])
        else:
            raise TypeError(
                'Field {} of class {} got incompatible type {}.'.format(
                    self.name, instance.__class__.__name__, type(value)))
예제 #7
0
    def NODATA(self, value):
        if value is None:
            self._NODATA = None
            return

        if isinstance(value, ElementTree.Element):
            value = get_node_value(value)

        if isinstance(value, str):
            self._NODATA = value
        elif isinstance(value, bytes):
            self._NODATA = value.decode('utf-8')
        elif isinstance(value, int):
            raise NotImplementedError
        elif isinstance(value, float):
            raise NotImplementedError
        else:
            raise TypeError('Got unexpected type {}'.format(type(value)))
예제 #8
0
    def from_node(cls, node, xml_ns, ns_key=None, kwargs=None):
        if kwargs is None:
            kwargs = {}

        lut_key = cls._child_xml_ns_key.get('RemapLUT', ns_key)
        lut_node = find_first_child(node, 'RemapLUT', xml_ns, lut_key)
        if lut_node is not None:
            dim1 = int_func(lut_node.attrib['size'])
            arr = numpy.zeros((dim1, ), dtype=numpy.uint8)
            entries = get_node_value(lut_node).split()
            i = 0
            for entry in entries:
                if len(entry) == 0:
                    continue
                arr[i] = int(entry)
                i += 1
            kwargs['RemapLUT'] = arr
        return super(MonochromeDisplayRemapType, cls).from_node(node,
                                                                xml_ns,
                                                                ns_key=ns_key,
                                                                **kwargs)
예제 #9
0
 def from_node(cls, node, xml_ns, ns_key=None, kwargs=None):
     lut_key = cls._child_xml_ns_key.get('RemapLUT', ns_key)
     lut_node = find_first_child(node, 'RemapLUT', xml_ns, lut_key)
     if lut_node is not None:
         dim1 = int_func(lut_node.attrib['size'])
         dim2 = 3
         arr = numpy.zeros((dim1, dim2), dtype=numpy.uint16)
         entries = get_node_value(lut_node).split()
         i = 0
         for entry in entries:
             if len(entry) == 0:
                 continue
             sentry = entry.split(',')
             if len(sentry) != 3:
                 logger.error(
                     'Parsing RemapLUT is likely compromised.\n\t'
                     'Got entry {}, which we are skipping.'.format(entry))
                 continue
             arr[i, :] = [int(el) for el in entry]
             i += 1
         if numpy.max(arr) < 256:
             arr = numpy.cast[numpy.uint8](arr)
         return cls(RemapLUT=arr)
     return cls()
예제 #10
0
 def _get_value(node, tag, xml_ns, ns_key):
     t_node = find_first_child(node, tag, xml_ns, ns_key)
     if t_node is None:
         return None
     else:
         return float(get_node_value(t_node))
예제 #11
0
파일: MatchInfo.py 프로젝트: kirkjens/sarpy
    def _from_node_0_5(cls, node, xml_ns, ns_key):
        """
        Helper method, not really for public usage. For XML deserialization from SICD version prior to 1.0.

        Parameters
        ----------
        node : ElementTree.Element
            dom element for serialized class instance
        xml_ns : dict
            The xml namespace dictionary
        ns_key : str
            The namespace key in the dictionary
        Returns
        -------
        Serializable
            corresponding class instance
        """
        def get_element(tid, cid, cname, params):
            return {
                'TypeID': tid,
                'CurrentIndex': cid,
                'MatchCollections': [
                    {
                        'CoreName': cname,
                        'Parameters': params
                    },
                ]
            }

        # Note that this is NOT converting the MatchType.MatchCollection in spirit.
        # There isn't enough structure to guarantee that you actually can. This will
        # always yield MatchType.MatchCollection length 1, because the collection details are stuffed
        # into the parameters free form, while CurrentIndex is extracted and actually yields the
        # collection index number (likely larger than 1). This is at least confusing, but more likely
        # completely misleading.
        match_types = []

        coll_key = cls._child_xml_ns_key.get('Collect', ns_key)
        cnodes = find_children(node, 'Collect', xml_ns, coll_key)
        for cnode in cnodes:  # assumed non-empty
            # this describes one series of collects, possibly with more than one MatchType = TypeID
            # It is not clear how it would be possible to deconflict a repeat of MatchType between
            # Collect tags, so I will not.
            core_key = cls._child_xml_ns_key.get('CoreName', ns_key)
            core_name = get_node_value(
                find_first_child(cnode, 'CoreName', xml_ns, core_key))
            current_index = None
            parameters = []

            pkey = cls._child_xml_ns_key.get('Parameters', ns_key)
            pnodes = find_children(cnode, 'Parameter', xml_ns, pkey)
            for pnode in pnodes:
                name = pnode.attrib['name']
                value = get_node_value(pnode)
                if name == 'CURRENT_INSTANCE':
                    current_index = int(
                        value)  # extract the current index (and exclude)
                else:
                    parameters.append({
                        'name': name,
                        'value': value
                    })  # copy the parameter
            if current_index is None:
                continue  # I don't know what we would do?
            mt_key = cls._child_xml_ns_key.get('MatchType', ns_key)
            mtypes = find_children(cnode, 'MatchType', xml_ns, mt_key)
            for tnode in mtypes:
                type_id = get_node_value(tnode)
                match_types.append(
                    get_element(type_id, current_index, core_name, parameters))
        if len(match_types) > 0:
            # noinspection PyTypeChecker
            return cls(MatchTypes=match_types)
        else:
            return None