def mean_gc_geostrophic(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')):
    #gc_datasets = Dataset.objects.filter(entry_title__contains='globcurrent',
    #                time_coverage_start__range=[datetime_start,
    #                datetime_end])
    shapeD = domain.shape()
    U = np.zeros((shapeD[0], shapeD[1], 1))
    fn = 'http://tds0.ifremer.fr/thredds/dodsC/CLS-L4-CURGEO_0M-ALT_OI_025-V02.0_FULL_TIME_SERIE'
    dt = datetime_start
    while dt <= datetime_end:
        expFn = '/vagrant/shared/test_data/globcurrent/eastward_geostrophic_current_velocity_%d-%02d-%02d.nc'%(dt.year, dt.month, dt.day)
        #n = Nansat(
        #    fn, date='%d-%02d-%02d'%(dt.year, dt.month, dt.day),
        #    bands=['eastward_geostrophic_current_velocity'])
        #n.export(expFn)
        n = Nansat(expFn, mapper='generic')
        n.reproject(domain, addmask=False)
        u = n['eastward_geostrophic_current_velocity']
        # OK:
        #plt.imshow(u)
        #plt.colorbar()
        #plt.show()
        if np.sum(np.isnan(u))==u.size:
            continue
        else:
            U = np.append(U, np.expand_dims(u, axis=2), axis=2)
        dt = dt + timezone.timedelta(days=1)
    meanU = np.nanmean(U, axis=2)
    nu = Nansat(array=meanU, domain=domain)
    nmap=Nansatmap(nu, resolution='h')
    nmap.pcolormesh(nu[1], vmin=-1.5, vmax=1.5, cmap='jet') #bwr
    nmap.add_colorbar()
    nmap.draw_continents()
    nmap.fig.savefig('/vagrant/shared/u_gc.png', bbox_inches='tight')
Beispiel #2
0
n.reproject(d)

w = Nansat(os.path.join(home,
        'conferences/ESABigData2014/demo_data/gfs20110222/gfs.t00z.master.grbf03'))

w.reproject(d)

L_560 = n['L_560']

L_560[L_560>90] = np.nan

u = w['U']

v = w['V']

nMap = Nansatmap(n, resolution='f')

nMap.pcolormesh(L_560, vmin=20, vmax=90)

nMap.quiver(u,v,quivectors=20)

nMap.add_colorbar()

nMap.drawgrid()

nMap.quiver(u,v,quivectors=20)

plt.suptitle('TOA radiance from MERIS image and wind direction, 2011.02.22')

nMap.save('20110222_L_560.png')
def plot_s1a_example(fsize='small'):
    test_data.get_sentinel1a(fsize=fsize)
    #w = SARWind(test_data.sentinel1a[fsize])
    w = BayesianWind(test_data.sentinel1a[fsize])
    cc = w.get_corners()
    lonmin = np.int(np.floor(np.min(cc[0])*100))/100.
    lonmax = np.int(np.ceil(np.max(cc[0])*100))/100.
    latmin = np.int(np.floor(np.min(cc[1])*100))/100.
    latmax = np.int(np.ceil(np.max(cc[1])*100))/100.
    w.reproject( Domain(NSR().wkt, ext='-lle %s %s %s %s -ts %s %s' %(lonmin,
        latmin, lonmax, latmax, (lonmax-lonmin)*110., (latmax-latmin)*110.) ) )
    #u = w['U']
    #v = w['V']
    windspeed = w['bspeed_modcmod']
    winddir = w['bdir_modcmod']
    u = -windspeed*np.sin((180.0 - winddir)*np.pi/180.0)
    v = windspeed*np.cos((180.0 - winddir)*np.pi/180.0)
    nmap = Nansatmap(w, resolution='h')
    nmap.pcolormesh(np.hypot(u,v), vmax=18)
    nmap.add_colorbar(fontsize=8)
    nmap.quiver(u, v, step=20)#, scale=1, width=0.001)
    nmap.draw_continents()
    nmap.drawgrid()
    #nmap.drawmeridians(np.arange(lonmin, lonmax, 5), labels=[False, False,
    #    True, False])
    #nmap.drawparallels(np.arange(latmin, latmax, 3), labels=[True, False,
    #    False, False])

    # set size of the figure (inches)
    #nmap.fig.set_figheight(20)
    #nmap.fig.set_figwidth(15)

    # save figure to a PNG file
    nmap.draw_continents()
    #plt.suptitle(
    #    'High resolution\nwind speed and direction\nfrom Sentinel-1A and ' \
    #        'NCEP\n%s' %w.time_coverage_start.isoformat(),
    #    fontsize=8
    #)

    #nmap.fig.savefig('s1a_wind_%s.png'%fsize, dpi=150, bbox_inches='tight')
    nmap.fig.savefig('s1a_bwind_%s.png'%fsize, dpi=150, bbox_inches='tight')
Beispiel #4
0
    def save_wind_map_image(
        self,
        fileName,
        scale=None,
        numArrowsRange=10,
        landmask=True,
        colorbar=True,
        cbar_fontsize=6,
        drawgrid=True,
        title=None,
        title_fontsize=10,
        edgecolor=None,
        quiverScaleCriteria=None,
        tight=True,
        **kwargs
    ):

        pcolormeshArgs = {"vmin": 0, "vmax": 20}
        for iKey in pcolormeshArgs.keys():
            if iKey in kwargs.keys():
                pcolormeshArgs[iKey] = kwargs.pop(iKey)

        quiverArgs = {
            "X": None,
            "Y": None,
            "U": None,
            "label": None,
            "labelpos": "E",
            "coordinates": "figure",
            "fontproperties": None,
            "width": None,
        }
        popKeys = []
        for iKey in quiverArgs:
            if "quiver_" + iKey in kwargs.keys():
                quiverArgs[iKey] = kwargs.pop("quiver_" + iKey)
            else:
                popKeys.append(iKey)
        for key in popKeys:
            quiverArgs.pop(key)

        nMap = Nansatmap(self, resolution="l", figsize=(5, 8))

        # use wind direction "to" for calculating u and v
        winddirection = np.mod(self["winddirection"] + 180, 360)
        windspeed = self["windspeed"]
        windspeedPcolor = np.copy(windspeed)

        # if data has non-value (dark blue), replace to Nan
        if edgecolor is not None:
            # Replace the edge color (dark blue) to white
            windspeedPcolor[windspeedPcolor == edgecolor] = np.NaN
        # Put colormesh
        nMap.pcolormesh(windspeedPcolor, **pcolormeshArgs)

        # apply landmask to windspeeds
        windspeed = np.ma.masked_where(self.watermask()[1] == 2, windspeed)

        # specify the number of quiver
        quiPixelSpacing = int(np.round(windspeed.shape[1] / numArrowsRange))
        numQuiX = int(self.vrt.dataset.RasterXSize / quiPixelSpacing)
        numQuiY = int(self.vrt.dataset.RasterYSize / quiPixelSpacing)

        # compute maximum wind speed on the sea
        maxSpeed = max(windspeed[windspeed.mask == False])
        # compute a scale for quiver lenght
        scale = None
        if quiverScaleCriteria is not None:
            for iKey in quiverScaleCriteria.keys():
                if eval(iKey % maxSpeed):
                    scale = quiverScaleCriteria[iKey]

        # Draw quivers
        Ux = np.sin(np.radians(winddirection)) * windspeed
        Vx = np.cos(np.radians(winddirection)) * windspeed
        nMap.quiver(Ux, Vx, scale=scale, quivectors=(numQuiY, numQuiX), **quiverArgs)

        if colorbar:
            nMap.add_colorbar(fontsize=cbar_fontsize)

        if drawgrid:
            nMap.drawgrid()

        if title is not None:
            plt.title(title, fontsize=title_fontsize)

        if tight:
            nMap.fig.tight_layout()

        nMap.save(fileName, landmask=landmask, **kwargs)
Beispiel #5
0
    def save_wind_map_image(self,
                            fileName,
                            scale=None,
                            numArrowsRange=10,
                            landmask=True,
                            colorbar=True,
                            cbar_fontsize=6,
                            drawgrid=True,
                            title=None,
                            title_fontsize=10,
                            edgecolor=None,
                            quiverScaleCriteria=None,
                            tight=True,
                            **kwargs):

        pcolormeshArgs = {'vmin': 0, 'vmax': 20}
        for iKey in pcolormeshArgs.keys():
            if iKey in kwargs.keys():
                pcolormeshArgs[iKey] = kwargs.pop(iKey)

        quiverArgs = {
            'X': None,
            'Y': None,
            'U': None,
            'label': None,
            'labelpos': 'E',
            'coordinates': 'figure',
            'fontproperties': None,
            'width': None
        }
        popKeys = []
        for iKey in quiverArgs:
            if 'quiver_' + iKey in kwargs.keys():
                quiverArgs[iKey] = kwargs.pop('quiver_' + iKey)
            else:
                popKeys.append(iKey)
        for key in popKeys:
            quiverArgs.pop(key)

        nMap = Nansatmap(self, resolution='l', figsize=(5, 8))

        # use wind direction "to" for calculating u and v
        winddirection = np.mod(self['winddirection'] + 180, 360)
        windspeed = self['windspeed']
        windspeedPcolor = np.copy(windspeed)

        # if data has non-value (dark blue), replace to Nan
        if edgecolor is not None:
            # Replace the edge color (dark blue) to white
            windspeedPcolor[windspeedPcolor == edgecolor] = np.NaN
        # Put colormesh
        nMap.pcolormesh(windspeedPcolor, **pcolormeshArgs)

        # apply landmask to windspeeds
        windspeed = np.ma.masked_where(
            self.watermask(tps=True)[1] == 2, windspeed)

        # specify the number of quiver
        quiPixelSpacing = int(np.round(windspeed.shape[1] / numArrowsRange))
        numQuiX = int(self.vrt.dataset.RasterXSize / quiPixelSpacing)
        numQuiY = int(self.vrt.dataset.RasterYSize / quiPixelSpacing)

        # compute maximum wind speed on the sea
        maxSpeed = max(windspeed[windspeed.mask == False])
        # compute a scale for quiver lenght
        scale = None
        if quiverScaleCriteria is not None:
            for iKey in quiverScaleCriteria.keys():
                if eval(iKey % maxSpeed):
                    scale = quiverScaleCriteria[iKey]

        # Draw quivers
        Ux = np.sin(np.radians(winddirection)) * windspeed
        Vx = np.cos(np.radians(winddirection)) * windspeed
        nMap.quiver(Ux,
                    Vx,
                    scale=scale,
                    quivectors=(numQuiY, numQuiX),
                    **quiverArgs)

        if colorbar:
            nMap.add_colorbar(fontsize=cbar_fontsize)

        if drawgrid:
            nMap.drawgrid()

        if title is not None:
            plt.title(title, fontsize=title_fontsize)

        if tight:
            nMap.fig.tight_layout()

        nMap.save(fileName, landmask=landmask, **kwargs)
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:
            dop = Doppler(uri.uri)
            # Consider skipping swath 1 and possibly 2...
            dop.reproject(domain)
            # TODO: HARDCODING - MUST BE IMPROVED
            satpass = dop.get_metadata(key='Originating file').split('/')[6]
            if satpass=='ascending':
                try:
                    v_ai = dop['Ur']
                    v_ai[np.abs(v_ai)>3] = np.nan
                except:
                    # subswath doesn't cover the given domain
                    continue
                # uncertainty:
                # 5 Hz - TODO: estimate this correctly...
                sigma_ai = -np.pi*np.ones(dop.shape())*5./(112*np.sin(dop['incidence_angle']*np.pi/180.)) 
                alpha_i = -dop['sensor_azimuth']*np.pi/180.
                Va = np.nansum(np.append(np.expand_dims(Va, 2),
                    np.expand_dims(v_ai/np.square(sigma_ai), 2), axis=2),
                    axis=2)
                ca = np.nansum(np.append(np.expand_dims(ca, 2),
                    np.expand_dims(np.cos(alpha_i)/np.square(sigma_ai), 2),
                    axis=2), axis=2)
                sa = np.nansum(np.append(np.expand_dims(sa, 2),
                    np.expand_dims(np.sin(alpha_i)/np.square(sigma_ai), 2),
                    axis=2), axis=2)
                sum_var_inv_a =np.nansum(np.append(np.expand_dims(sum_var_inv_a, 2),
                    np.expand_dims(1./np.square(sigma_ai), 2), axis=2),
                    axis=2)
            else:
                try:
                    v_dj = -dop['Ur']
                    v_dj[np.abs(v_dj)>3] = np.nan
                except:
                    # subswath doesn't cover the given domain
                    continue
                # 5 Hz - TODO: estimate this correctly...
                sigma_dj = -np.pi*np.ones(dop.shape())*5./(112*np.sin(dop['incidence_angle']*np.pi/180.)) 
                delta_j = (dop['sensor_azimuth']-180.)*np.pi/180.
                Vd = np.nansum(np.append(np.expand_dims(Vd, 2),
                    np.expand_dims(v_dj/np.square(sigma_dj), 2), axis=2),
                    axis=2)
                cd = np.nansum(np.append(np.expand_dims(cd, 2),
                    np.expand_dims(np.cos(delta_j)/np.square(sigma_dj), 2),
                    axis=2), axis=2)
                sd = np.nansum(np.append(np.expand_dims(sd, 2),
                    np.expand_dims(np.sin(delta_j)/np.square(sigma_dj), 2),
                    axis=2), axis=2)
                sum_var_inv_d = np.nansum(np.append(
                    np.expand_dims(sum_var_inv_d, 2), np.expand_dims(
                        1./np.square(sigma_ai), 2), axis=2), axis=2)

    u = (Va*sd + Vd*sa)/(sa*cd + sd*ca)
    v = (Va*cd - Vd*ca)/(sa*cd + sd*ca)
    sigma_u = np.sqrt(np.square(sd)*sum_var_inv_a +
            np.square(sa)*sum_var_inv_d) / (sa*cd + sd*ca)
    sigma_v = np.sqrt(np.square(cd)*sum_var_inv_a +
            np.square(ca)*sum_var_inv_d) / (sa*cd + sd*ca)
    nu = Nansat(array=u, domain=domain)
    nmap=Nansatmap(nu, resolution='h')
    nmap.pcolormesh(nu[1], vmin=-1.5, vmax=1.5, cmap='bwr')
    nmap.add_colorbar()
    nmap.draw_continents()
    nmap.fig.savefig('/vagrant/shared/unwasc.png', bbox_inches='tight')