How to use the nansat.domain.Domain 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 / django-geo-spaas / geospaas / processing_sar_doppler / utils.py View on Github external
def calc_mean_doppler(datetime_start=timezone.datetime(2010,1,1,
    tzinfo=timezone.utc), datetime_end=timezone.datetime(2010,2,1,
    tzinfo=timezone.utc), domain=Domain(NSR().wkt, 
        '-te 10 -44 40 -30 -tr 0.05 0.05')):
    geometry = WKTReader().read(domain.get_border_wkt(nPoints=1000))
    ds = Dataset.objects.filter(entry_title__contains='Doppler',
            time_coverage_start__range=[datetime_start, datetime_end],
            geographic_location__geometry__intersects=geometry)
    Va = np.zeros(domain.shape())
    Vd = np.zeros(domain.shape())
    ca = np.zeros(domain.shape())
    cd = np.zeros(domain.shape())
    sa = np.zeros(domain.shape())
    sd = np.zeros(domain.shape())
    sum_var_inv_a = np.zeros(domain.shape())
    sum_var_inv_d = np.zeros(domain.shape())
    for dd in ds:
        uris = dd.dataseturi_set.filter(uri__endswith='nc')
        for uri in uris:
github nansencenter / nansat / nansat / domain.py View on Github external
template = '''
        \t{filename}
        \t\t{filename}1
        {borders}
        \t\t'''

        # test input options
        if xml_filename and not kml_filename:
            # if only input XML-file is given - convert it to KML

            # open XML, get all domains
            with open(xml_filename, 'rb') as xml_file:
                xml_domains = list(ElementTree(file=xml_file).getroot())

            # convert domains in XML into list of domains
            domains = [Domain(srs=xml_filename, ext=domain.attrib['name'])
                       for domain in xml_domains]

        elif not xml_filename and kml_filename:
            # if only output KML-file is given
            # then convert the current domain to KML
            domains = [self]

        else:
            # otherwise it is potentially error
            raise ValueError('Either xmlFileName(%s)\
             or kmlFileName(%s) are wrong' % (xml_filename, kml_filename))

        # get border of each domain and join them to a one string
        borders = ''.join([domain._get_border_kml() for domain in domains])
        # open KML, write the modified template
        with open(kml_filename, 'wt') as kml_file:
github nansencenter / nansat / nansat / domain.py View on Github external
"""

        combinations = [('te', 'lle', 4), ('ts', 'tr', 2)]
        extent_dict = {}
        for combination in combinations:
            try:
                option = re.findall(Domain._gen_regexp(*combination), extent_str)[0]
            except IndexError:
                raise ValueError(' must contains exactly 2 parameters '
                                  '("-te" or "-lle") and ("-ts" or "-tr")')
            key, extent_dict = Domain._add_to_dict(extent_dict, option)
            if key is 'te' or key is 'lle':
                Domain._validate_te_lle(extent_dict[key])
            elif key is 'ts' or key is 'tr':
                Domain._validate_ts_tr(extent_dict[key])

        return extent_dict
github nansencenter / django-geo-spaas / geospaas / processing_ascat_wind / managers.py View on Github external
def get_or_create(self, uri, reprocess=False, *args, **kwargs):
        # ingest file to db
        ds, created = super(DatasetManager, self).get_or_create(uri, *args,
                **kwargs)

        fn = nansat_filename(uri)

        n = Nansat(fn)

        # Reproject to leaflet projection
        xlon, xlat = n.get_corners()
        d = Domain(NSR(3857),
            '-lle %f %f %f %f -tr 1000 1000' % (
                xlon.min(), xlat.min(), xlon.max(), xlat.max()))
        n.reproject(d)

        # Get band numbers of required bands according to standard names
        speedBandNum = n._get_band_number({'standard_name': 'wind_speed'})
        dirBandNum = n._get_band_number({'standard_name': 'wind_from_direction'})
        
        # Get numpy arrays of the bands
        speed = n[speedBandNum]
        dir = n[dirBandNum]

        ## It probably wont work with nansatmap...
        #nmap = Nansatmap(n, resolution='l')
        #nmap.pcolormesh(speed, vmax=18)
        #nmap.quiver(-speed*np.sin(dir), speed*np.cos(dir), step=10, scale=300,
github nansencenter / django-geo-spaas / geospaas / processing_sar_nrcs / managers.py View on Github external
# set Dataset entry_title
        ds.entry_title = 'SAR NRCS'
        ds.save()

        # Unless reprocess==True, we may not need to do the following... (see
        # managers.py in sar doppler processor)
        #visExists = ... # check if visualization(s) already created
        #if visExists and not reprocess:
        #    warnings.warn('NO VISUALISATIONS CREATED - update managers.py')
        #    return ds, created

        n = Nansat(nansat_filename(uri))
        n.resize(pixelsize=500)
        lon, lat = n.get_corners()
        d = Domain(NSR(3857),
                   '-lle %f %f %f %f -tr 1000 1000' % (
                        lon.min(), lat.min(), lon.max(), lat.max()))
        n.reproject(d, eResampleAlg=1, tps=True)

        # Get all NRCS bands
        s0bands = []
        pp = []
        for key, value in n.bands().iteritems():
            try:
                if value['standard_name']==standard_name:
                    s0bands.append(key)
                    pp.append(value['polarization'])
            except KeyError:
                continue

        ''' Create data products
github nansencenter / nansat / nansat / nansat.py View on Github external
def __repr__(self):
        """Creates string with basic info about the Nansat object"""
        out_str = '{separator}{filename}{separator}Mapper: {mapper}{bands}{separator}{domain}'
        return out_str.format(separator=self.OUTPUT_SEPARATOR, filename=self.filename,
                              bands=self.list_bands(False), mapper=self.mapper,
                              domain=Domain.__repr__(self))
github nansencenter / nansat / nansat / domain.py View on Github external
Returns
        --------
        extentDict : dictionary
            has key ('te' or 'lle') and ('tr' or 'ts') and their values.

        Raises
        -------
        ValueError : occurs when the extent_str is improper

        """

        combinations = [('te', 'lle', 4), ('ts', 'tr', 2)]
        extent_dict = {}
        for combination in combinations:
            try:
                option = re.findall(Domain._gen_regexp(*combination), extent_str)[0]
            except IndexError:
                raise ValueError(' must contains exactly 2 parameters '
                                  '("-te" or "-lle") and ("-ts" or "-tr")')
            key, extent_dict = Domain._add_to_dict(extent_dict, option)
            if key is 'te' or key is 'lle':
                Domain._validate_te_lle(extent_dict[key])
            elif key is 'ts' or key is 'tr':
                Domain._validate_ts_tr(extent_dict[key])

        return extent_dict
github nansencenter / nansat / nansat / domain.py View on Github external
# If dataset and srs are given (but not ext):
        #   use AutoCreateWarpedVRT to determine bounds and resolution
        elif ds is not None and srs is not None:
            srs = NSR(srs)
            tmp_vrt = gdal.AutoCreateWarpedVRT(ds, None, srs.wkt)
            if tmp_vrt is None:
                raise NansatProjectionError('Could not warp the given dataset to the given SRS.')
            else:
                self.vrt = VRT.from_gdal_dataset(tmp_vrt)

        # If SpatialRef and extent string are given (but not dataset)
        elif srs is not None and ext is not None:
            srs = NSR(srs)
            # create full dictionary of parameters
            extent_dict = Domain._create_extent_dict(ext)

            # convert -lle to -te
            if 'lle' in extent_dict.keys():
                extent_dict = self._convert_extentDic(srs, extent_dict)

            # get size/extent from the created extent dictionary
            geo_transform, raster_x_size, raster_y_size = self._get_geotransform(extent_dict)
            # create VRT object with given geo-reference parameters
            self.vrt = VRT.from_dataset_params(x_size=raster_x_size, y_size=raster_y_size,
                                               geo_transform=geo_transform,
                                               projection=srs.wkt,
                                               gcps=[], gcp_projection='')
        elif 'lat' in kwargs and 'lon' in kwargs:
            warnings.warn('Domain(lon=lon, lat=lat) will be deprectaed!'
                          'Use Domain.from_lonlat()', NansatFutureWarning)
            # create self.vrt from given lat/lon
github nansencenter / nansat / nansat / domain.py View on Github external
# test input options
        if xmlFileName is not None and kmlFileName is None:
            # if only input XML-file is given - convert it to KML

            # open XML, get all domains
            xmlFile = file(xmlFileName, 'rb')
            kmlFileName = xmlFileName + '.kml'
            xmlDomains = ElementTree(file=xmlFile).getroot()
            xmlFile.close()

            # convert domains in XML into list of domains
            domains = []
            for xmlDomain in list(xmlDomains):
                # append Domain object to domains list
                domainName = xmlDomain.attrib['name']
                domains.append(Domain(srs=xmlFileName, ext=domainName))

        elif xmlFileName is None and kmlFileName is not None:
            # if only output KML-file is given
            # then convert the current domain to KML
            domains = [self]

        else:
            # otherwise it is potentially error
            raise OptionError('Either xmlFileName(%s)\
             or kmlFileName(%s) are wrong' % (xmlFileName, kmlFileName))

        # open KML, write header
        kmlFile = file(kmlFileName, 'wt')
        kmlFile.write('\n')
        kmlFile.write('