How to use the nansat.vrt.VRT.from_array 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_globcolour_l3b.py View on Github external
mask = np.zeros(varPro.shape, 'uint8')
                mask[:] = 1
                mask[varPro > 0] = 64

                # add VRT with array with data from projected variable
                self.band_vrts['mask'].append(VRT.from_array(mask))

                # add metadata to the dictionary
                metaDict.append({
                    'src': {'SourceFilename': (self.band_vrts['mask'][-1].
                                               filename),
                            'SourceBand':  1},
                    'dst': {'name': 'mask'}})

            # add VRT with array with data from projected variable
            self.band_vrts['lonlat'].append(VRT.from_array(varPro))

            # add metadata to the dictionary
            metaEntry = {
                'src': {'SourceFilename': self.band_vrts['lonlat'][-1].filename,
                        'SourceBand':  1},
                'dst': {'wkv': varWKV, 'original_name': varName}}

            # add wavelength for nLw
            longName = 'Fully normalised water leaving radiance'
            if longName in f.variables[varName].long_name:
                simWavelength = varName.split('L')[1].split('_mean')[0]
                metaEntry['dst']['suffix'] = simWavelength
                metaEntry['dst']['wavelength'] = simWavelength

            # add all metadata from NC-file
            for attr in var.ncattrs():
github nansencenter / nansat / nansat / mappers / envisat.py View on Github external
"""
        adsHeight = self.dsOffsetDict["NUM_DSR"]
        adsParams = self.allADSParams['list'][adsName]
        array = self.get_array_from_ADS(adsName)

        if not IMPORT_SCIPY:
            raise NansatReadError('ENVISAT data cannot be read because scipy is not installed...')

        # zoom the array
        array = scipy.ndimage.interpolation.zoom(array,
                                                 zoomSize / float(adsHeight),
                                                 order=1)

        # create VRT from the array
        adsVrt = VRT.from_array(array=array)
        # add "name" and "units" to band metadata
        bandMetadata = {"name": adsName, "units": adsParams['units']}
        adsVrt.dataset.GetRasterBand(1).SetMetadata(bandMetadata)

        return adsVrt
github nansencenter / nansat / nansat / mappers / mapper_asar.py View on Github external
# Add incidence angle and look direction through small VRT objects
        #####################################################################
        lon = self.get_array_from_ADS('first_line_longs')
        lat = self.get_array_from_ADS('first_line_lats')
        inc = self.get_array_from_ADS('first_line_incidence_angle')

        # Calculate SAR look direction (ASAR is always right-looking)
        look_direction = initial_bearing(lon[:, :-1], lat[:, :-1],
                                             lon[:, 1:], lat[:, 1:])
        # Interpolate to regain lost row
        look_direction = scipy.ndimage.interpolation.zoom(
            look_direction, (1, 11./10.))
        # Decompose, to avoid interpolation errors around 0 <-> 360
        look_direction_u = np.sin(np.deg2rad(look_direction))
        look_direction_v = np.cos(np.deg2rad(look_direction))
        look_u_VRT = VRT.from_array(look_direction_u)
        look_v_VRT = VRT.from_array(look_direction_v)

        # Note: If incidence angle and look direction are stored in
        #       same VRT, access time is about twice as large
        incVRT = VRT.from_array(inc)
        lookVRT = VRT.from_lonlat(lon, lat)
        lookVRT.create_band([{'SourceFilename': look_u_VRT.filename,
                               'SourceBand': 1},
                              {'SourceFilename': look_v_VRT.filename,
                               'SourceBand': 1}],
                             {'PixelFunctionType': 'UVToDirectionTo'})

        # Blow up bands to full size
        incVRT = incVRT.get_resized_vrt(gdalDataset.RasterXSize, gdalDataset.RasterYSize)
        lookVRT = lookVRT.get_resized_vrt(gdalDataset.RasterXSize, gdalDataset.RasterYSize)
        # Store VRTs so that they are accessible later
github nansencenter / nansat / nansat / mappers / mapper_radarsat2.py View on Github external
sat_heading = initial_bearing(lon[:, 1:], lat[:, 1:],
                                          lon[:, :-1], lat[:, :-1]) + 90
        else:
            print 'Can not decode pass direction: ' + str(passDirection)

        # Calculate SAR look direction
        look_direction = sat_heading + antennaPointing
        # Interpolate to regain lost row
        look_direction = np.mod(look_direction, 360)
        look_direction = scipy.ndimage.interpolation.zoom(
            look_direction, (1, 11./10.))
        # Decompose, to avoid interpolation errors around 0 <-> 360
        look_direction_u = np.sin(np.deg2rad(look_direction))
        look_direction_v = np.cos(np.deg2rad(look_direction))
        look_u_VRT = VRT.from_array(look_direction_u)
        look_v_VRT = VRT.from_array(look_direction_v)

        # Note: If incidence angle and look direction are stored in
        #       same VRT, access time is about twice as large
        lookVRT = VRT.from_lonlat(lon, lat)
        lookVRT.create_band(
            [{'SourceFilename': look_u_VRT.filename, 'SourceBand': 1},
             {'SourceFilename': look_v_VRT.filename, 'SourceBand': 1}],
            {'PixelFunctionType': 'UVToDirectionTo'})

        # Blow up to full size
        lookVRT = lookVRT.get_resized_vrt(gdalDataset.RasterXSize, gdalDataset.RasterYSize)
        # Store VRTs so that they are accessible later
        self.band_vrts['look_u_VRT'] = look_u_VRT
        self.band_vrts['look_v_VRT'] = look_v_VRT
        self.band_vrts['lookVRT'] = lookVRT
github nansencenter / nansat / nansat / vrt.py View on Github external
def hardcopy_bands(self):
        """Make 'hardcopy' of bands: evaluate array from band and put into original band"""
        bands = range(1, self.dataset.RasterCount+1)
        for i in bands:
            self.band_vrts[i] = VRT.from_array(self.dataset.GetRasterBand(i).ReadAsArray())

        node0 = Node.create(str(self.xml))
        for i, iNode1 in enumerate(node0.nodeList('VRTRasterBand')):
            iNode1.node('SourceFilename').value = self.band_vrts[i+1].filename
            iNode1.node('SourceBand').value = str(1)
        self.write_xml(node0.rawxml())
github nansencenter / nansat / nansat / nansat.py View on Github external
Examples
        --------
            >>> n.add_bands([array1, array2]) # add new bands, keep in memory

        """
        # replace empty parameters with list of empty dictionaries
        if parameters is None:
            parameters = [{}] * len(arrays)

        self.vrt = self.vrt.get_super_vrt()

        # create VRTs from arrays and generate band_metadata
        band_metadata = []
        for array, parameter in zip(arrays, parameters):
            vrt = VRT.from_array(array, nomem=nomem)
            band_metadata.append({
                'src': {'SourceFilename': vrt.filename, 'SourceBand': 1},
                'dst': parameter
                })
            self.vrt.band_vrts[vrt.filename] = vrt

        band_name = self.vrt.create_bands(band_metadata)
github nansencenter / nansat / nansat / vrt.py View on Github external
add_gcps : bool
            Add GCPs to dataset
        **kwargs : dict
            arguments for VRT() and VRT._lonlat2gcps

        Notes
        -------
        self - adds all VRT attributes
        self.dataset - sets size and georeference
        self.geolocation - add Geolocation object with all attributes

        """
        VRT.__init__(self, lon.shape[1], lon.shape[0], **kwargs)
        if add_gcps:
            self.dataset.SetGCPs(VRT._lonlat2gcps(lon, lat, **kwargs), NSR().wkt)
        self._add_geolocation(Geolocation(VRT.from_array(lon), VRT.from_array(lat)))
        self.dataset.SetMetadataItem(str('filename'), self.filename)
        self.dataset.FlushCache()
github nansencenter / nansat / nansat / vrt.py View on Github external
i = self._find_complex_band()
        if i is None:
            return

        band = self.dataset.GetRasterBand(i)
        band_array = band.ReadAsArray()
        band_metadata_orig = remove_keys(band.GetMetadata(), rm_metadata)
        band_name_orig = band_metadata_orig.get('name', 'complex_%003d'%i)
        # Copy metadata, modify 'name' and create VRTs for real and imag parts of each band
        band_description = []
        for part in ['real', 'imag']:
            band_metadata = band_metadata_orig.copy()
            band_name = band_name_orig + '_' + part
            band_metadata['name'] = band_name
            self.band_vrts[band_name] = VRT.from_array(eval('band_array.' + part))
            band_description.append({'src': {
                     'SourceFilename': self.band_vrts[band_name].filename,
                     'SourceBand':  1},
                     'dst': band_metadata})
        # create bands with parts
        self.create_bands(band_description)
        # delete the complex band
        self.delete_band(i)
        # find and split more complex bands
        self.split_complex_bands()
github nansencenter / nansat / nansat / mappers / mapper_sentinel1_l1.py View on Github external
variable names that should be converted to VRTs
        pol : str
            HH, HV, etc
        resize : bool
            Shall VRT be zoomed to full size?
        resample_alg : int
            Index of resampling algorithm. See VRT.get_resized_vrt()

        Returns
        -------
        vrts : dict with (resized) VRTs

        """
        vrts = {}
        for var_name in variable_names:
            vrts[var_name+pol] = VRT.from_array(data[var_name+pol])
            if resize:
                vrts[var_name+pol] = vrts[var_name+pol].get_resized_vrt(self.dataset.RasterXSize,
                                                                        self.dataset.RasterYSize,
                                                                        resample_alg)
        return vrts
github nansencenter / openwind / nansat_mappers / mapper_quikscat.py View on Github external
raise ValueError('Cannot find latitude band')
        lat = band_lat.ReadAsArray()

        band_lon = self.dataset.GetRasterBand(self._longitude_band_number(gdal_dataset))
        # Check that it is actually longitudes
        if not band_lon.GetMetadata()['standard_name'] == 'longitude':
            raise ValueError('Cannot find longitude band')
        lon = band_lon.ReadAsArray()

        # Apply correction of longitudes (they are defined on 0:360 degrees but also contain
        # negative values)
        # TODO: consider making this core to nansat - different ways of defining longitudes
        # (-180:180 og 0:360 degrees) often cause problems...
        lon = np.mod(lon+180., 360.) - 180.

        self.band_vrts['new_lon_VRT'] = VRT.from_array(lon)

        self.dataset.SetProjection(NSR().wkt)

        self.dataset.SetGCPs(VRT._lonlat2gcps(lon, lat, n_gcps=400), NSR().wkt)

        # Add geolocation from correct longitudes and latitudes
        self._add_geolocation(
                Geolocation(self.band_vrts['new_lon_VRT'], self, x_band=1, y_band=self._latitude_band_number(gdal_dataset))
            )

        # Get dictionary describing the instrument and platform according to
        # the GCMD keywords
        mm = pti.get_gcmd_instrument('seawinds')
        ee = pti.get_gcmd_platform('quikscat')

        # TODO: Validate that the found instrument and platform are indeed what