How to use the nansat.node.Node function in nansat

To help you get started, we’ve selected a few nansat examples, based on popular ways it is used in public projects.

Secure your code as it's written. Use Snyk Code to scan source code in minutes - no build needed - and fix issues immediately.

github nansencenter / nansat / nansat / mappers / mapper_sentinel1_l1.py View on Github external
String with XML from calibration or noise files
        vectorListName : str
            tag of the element that contains lists with LUT values
        variable_names : list of str
            names of LUT variable to read
        pol : str
            HH, HV, etc

        Returns
        -------
        data : dict
            Calibration or noise data. Keys:
            The same as variable_names + 'pixel', 'line'
        """
        data = {}
        n = Node.create(xml)
        vecList = n.node(vectorListName)
        data['pixel'] = []
        data['line'] = []
        for var_name in variable_names:
            data[var_name+pol] = []
        xLengths = []
        for vec in vecList.children:
            xVec = list(map(int, vec['pixel'].split()))
            xLengths.append(len(xVec))
            data['pixel'].append(xVec)
            data['line'].append(int(vec['line']))
            for var_name in variable_names:
                data[var_name+pol].append(np.fromiter(vec[var_name].split(), float))

        # truncate data['pixel'] and var_name to minimum length for all rows
        minLength = np.min(xLengths)
github nansencenter / nansat / nansat / vrt.py View on Github external
def _remove_geotransform(self):
        """Remove GeoTransfomr from VRT Object

        Notes
        ---------
        The tag  is revoved from the VRT-file

        """
        # read XML content from VRT
        # find and remove GeoTransform
        node0 = Node.create(self.xml)
        node0.delNode('GeoTransform')
        # Write the modified elemements back into temporary VRT
        self.write_xml(node0.rawxml())
github nansencenter / nansat / nansat / vrt.py View on Github external
def get_subsampled_vrt(self, new_raster_x_size, new_raster_y_size, resample_alg):
        """Create VRT and replace step in the source"""

        subsamp_vrt = self.get_super_vrt()

        # Get XML content from VRT-file
        node0 = Node.create(str(subsamp_vrt.xml))

        # replace rasterXSize in 
        node0.replaceAttribute('rasterXSize', str(new_raster_x_size))
        node0.replaceAttribute('rasterYSize', str(new_raster_y_size))

        # replace xSize in  of each source
        for iNode1 in node0.nodeList('VRTRasterBand'):
            for sourceName in ['ComplexSource', 'SimpleSource']:
                for iNode2 in iNode1.nodeList(sourceName):
                    iNodeDstRect = iNode2.node('DstRect')
                    iNodeDstRect.replaceAttribute('xSize', str(new_raster_x_size))
                    iNodeDstRect.replaceAttribute('ySize', str(new_raster_y_size))
            # if method=-1, overwrite 'ComplexSource' to 'AveragedSource'
            if resample_alg == -1:
                iNode1.replaceTag('ComplexSource', 'AveragedSource')
                iNode1.replaceTag('SimpleSource', 'AveragedSource')
github nansencenter / nansat / nansat / mappers / mapper_sentinel1_l1.py View on Github external
Returns
        -------
        data : dict
            manifest data. Keys:
                time_coverage_start
                time_coverage_end
                platform_familyName
                platform_number

        """

        data = {}
        xml = self.read_vsi(input_file)
        # set time as acquisition start time
        n = Node.create(xml)
        meta = n.node('metadataSection')
        for nn in meta.children:
            if str(nn.getAttribute('ID')) == 'acquisitionPeriod':
                # get valid time
                data['time_coverage_start'] = parse((nn.node('metadataWrap').
                                                     node('xmlData').
                                                     node('safe:acquisitionPeriod')['safe:startTime']
                                                     )).isoformat()
                data['time_coverage_end'] = parse((nn.node('metadataWrap').
                                                   node('xmlData').
                                                   node('safe:acquisitionPeriod')['safe:stopTime']
                                                   )).isoformat()
            if str(nn.getAttribute('ID')) == 'platform':
                data['platform_family_name'] = str(nn.node('metadataWrap').
                                                     node('xmlData').
                                                     node('safe:platform')['safe:familyName'])
github nansencenter / nansat / nansat / mappers / mapper_landsat_highresolution.py View on Github external
# modify geoTarnsform for the highest resplution
        geoTransform = list(gdalDatasetTmp.GetGeoTransform())
        geoTransform[1] = float(geoTransform[1]) * ratio
        geoTransform[5] = float(geoTransform[5]) * ratio

        # create empty VRT dataset with geolocation only
        VRT.__init__(self, gdalDatasetTmp0)

        # add bands with metadata and corresponding values to the empty VRT
        self._create_bands(metaDict)

        # 8th band of LANDSAT8 is a double size band.
        # Reduce the size to same as the 1st band.
        vrtXML = self.read_xml()
        node0 = Node.create(vrtXML)
        node0.replaceAttribute('rasterXSize', str(xSize))
        node0.replaceAttribute('rasterYSize', str(ySize))
        self.write_xml(str(node0.rawxml()))

        # set new goeTransform
        if ratio != 1.0:
            self.dataset.SetGeoTransform(tuple(geoTransform))
github nansencenter / nansat / nansat / nansat.py View on Github external
ySize = RasterYSize - yOff

        extent = (int(xOff), int(yOff), int(xSize), int(ySize))
        self.logger.debug('xOff: %d, yOff: %d, xSize: %d, ySize: %d' % extent)

        # test if crop is too large
        if (xOff == 0 and xSize == RasterXSize and
                yOff == 0 and ySize == RasterYSize):
            self.logger.error(('WARNING! Cropping region is'
                               'larger or equal to image!'))
            return 2

        # create super VRT and get its XML
        self.vrt = self.vrt.get_super_vrt()
        xml = self.vrt.read_xml()
        node0 = Node.create(xml)

        # change size
        node0.node('VRTDataset').replaceAttribute('rasterXSize', str(xSize))
        node0.node('VRTDataset').replaceAttribute('rasterYSize', str(ySize))

        # replace x/y-Off and x/y-Size
        #   in  and  of each source
        for iNode1 in node0.nodeList('VRTRasterBand'):
            iNode2 = iNode1.node('ComplexSource')

            iNode3 = iNode2.node('SrcRect')
            iNode3.replaceAttribute('xOff', str(xOff))
            iNode3.replaceAttribute('yOff', str(yOff))
            iNode3.replaceAttribute('xSize', str(xSize))
            iNode3.replaceAttribute('ySize', str(ySize))
github nansencenter / nansat / nansat / nansat.py View on Github external
# temporary VRT for exporting
        exportVRT = self.vrt.copy()
        exportVRT.real = []
        exportVRT.imag = []

        # delete unnecessary bands
        if bands is not None:
            srcBands = np.arange(self.vrt.dataset.RasterCount) + 1
            dstBands = np.array(bands)
            mask = np.in1d(srcBands, dstBands)
            rmBands = srcBands[mask==False]
            exportVRT.delete_bands(rmBands.tolist())

        # Find complex data band
        complexBands = []
        node0 = Node.create(exportVRT.read_xml())
        for iBand in node0.nodeList('VRTRasterBand'):
            dataType = iBand.getAttribute('dataType')
            if dataType[0] == 'C':
                complexBands.append(int(iBand.getAttribute('band')))

        # if data includes complex data,
        # create two bands from real and imaginary data arrays
        if len(complexBands) != 0:
            for i in complexBands:
                bandMetadataR = self.get_metadata(bandID=i)
                bandMetadataR.pop('dataType')
                try:
                    bandMetadataR.pop('PixelFunctionType')
                except:
                    pass
                # Copy metadata and modify 'name' for real and imag bands
github nansencenter / nansat / nansat / node.py View on Github external
"""
        Create a Node representation, given either
        a string representation of an XML doc, or a dom.

        """
        if isinstance(dom, str):
            if os.path.exists(dom):
                # parse input file
                dom = xdm.parse(dom)
            else:
                # Strip all extraneous whitespace so that
                # text input is handled consistently:
                dom = re.sub('\s+', ' ', dom)
                dom = dom.replace('> ', '>')
                dom = dom.replace(' <', '<')
                return Node.create(xdm.parseString(str(dom)))

        # To pass test for python3, decoding of bytes object is requested
        if dom.nodeType == dom.DOCUMENT_NODE:
            return Node.create(dom.childNodes[0])
        if dom.nodeName == '#text':
            return
        node = Node(dom.nodeName)
        if dom.attributes:
            for name, val in dom.attributes.items():
                node.setAttribute(name, val)
        for n in dom.childNodes:
            if n.nodeType == n.TEXT_NODE and n.wholeText.strip():
                node.value = n.wholeText
            else:
                subnode = Node.create(n)
                if subnode:
github nansencenter / nansat / nansat / node.py View on Github external
# parse input file
                dom = xdm.parse(dom)
            else:
                # Strip all extraneous whitespace so that
                # text input is handled consistently:
                dom = re.sub('\s+', ' ', dom)
                dom = dom.replace('> ', '>')
                dom = dom.replace(' <', '<')
                return Node.create(xdm.parseString(str(dom)))

        # To pass test for python3, decoding of bytes object is requested
        if dom.nodeType == dom.DOCUMENT_NODE:
            return Node.create(dom.childNodes[0])
        if dom.nodeName == '#text':
            return
        node = Node(dom.nodeName)
        if dom.attributes:
            for name, val in dom.attributes.items():
                node.setAttribute(name, val)
        for n in dom.childNodes:
            if n.nodeType == n.TEXT_NODE and n.wholeText.strip():
                node.value = n.wholeText
            else:
                subnode = Node.create(n)
                if subnode:
                    node += subnode
        return node