Beispiel #1
0
            continue

        if contcode != geocountries[iso]['continentcode']:
            continue

        if contcode not in continents:
            continents[contcode] = {'lats': [], 'lons': []}

        continents[contcode]['lats'].append(float(row[5]))
        continents[contcode]['lons'].append(float(row[6]))

geocont = geocontinents[contcode]
m = Basemap(projection='mill',
            lon_0=geocont['lon'],
            lat_0=geocont['lat'],
            llcrnrlon=geocont['bbox']['w'],
            llcrnrlat=geocont['bbox']['s'],
            urcrnrlon=geocont['bbox']['e'],
            urcrnrlat=geocont['bbox']['n'])

# no visible border around map
m.drawmapboundary(fill_color='#ffffff', linewidth=0.0)

cont = continents[contcode]
x, y = m(cont['lons'], cont['lats'])
m.scatter(x, y, 1, marker='.', color='#325CA9')

fig = plt.gcf()
fig.set_alpha(.7)
fig.set_size_inches(36, 24)
Beispiel #2
0
    def plot_global_map(self):
        """
        Plot global map of event and stations
        """

        # import basemap here due to error
        from mpl_toolkits.basemap import Basemap

        # ax = plt.subplot(211)
        plt.title(self.cmtsource.eventname)
        m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(-90., 120., 30.))
        m.drawmeridians(np.arange(0., 420., 60.))
        m.drawmapboundary()

        x, y = m(self.sta_lon, self.sta_lat)

        #print(self.sta_lon,self.sta_lat)
        #print(self.metas)
        #print(len(self.metas),len(self.sta_lon))
        #print(w)

        plt.scatter(x,
                    y,
                    s=30,
                    c='red',
                    cmap='afmhot',
                    marker="^",
                    edgecolor="k",
                    linewidth=0.3,
                    zorder=3)

        cmt_lat = self.cmtsource.latitude
        cmt_lon = self.cmtsource.longitude
        focmecs = get_cmt_par(self.cmtsource)[:6]
        ax = plt.gca()
        if self.mode == 'regional':
            minlon = min(self.sta_lon)
            maxlon = max(self.sta_lon)
            minlat = min(self.sta_lat)
            maxlat = max(self.sta_lat)
            padding = 0.2
            m.drawparallels(np.arange(-90., 120., padding),
                            labels=[1, 1, 0, 0],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.drawmeridians(np.arange(0., 420., padding),
                            labels=[0, 0, 1, 1],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.etopo()
            ax.set_xlim(minlon - padding, maxlon + padding)
            ax.set_ylim(minlat - padding, maxlat + padding)
            width_beach = min((maxlon + 2 * padding - minlon) / (40 * padding),
                              (maxlat + 2 * padding - minlat) / (40 * padding))
        else:
            width_beach = 20
        bb = beach(focmecs,
                   xy=(cmt_lon, cmt_lat),
                   width=width_beach,
                   linewidth=1,
                   alpha=1.0)
        bb.set_zorder(10)
        ax.add_collection(bb)
plottimeseries = 0

figdir = "/home/ctroupin/DataOceano/MyOcean/figures/mooring/NRT/"
figdir2 = "/home/ctroupin/Projects/201501_InsTAC/MaterialQ2/"

#mooringdir = "/home/ctroupin/DataOceano/MyOcean/INSITU_MED_TS_REP_OBSERVATIONS_013_041/history/mooring/"
mooringdir = "/home/ctroupin/DataOceano/MyOcean/INSITU_MED_NRT_OBSERVATIONS_013_035/history/mooring/"
mooringlist = sorted(glob.glob(mooringdir + '*.nc'))

coordinates = np.array((-6.75, 37., 29, 46.))
dlon, dlat = 5., 3.

m = Basemap(projection='merc',
            llcrnrlon=coordinates[0],
            llcrnrlat=coordinates[2],
            urcrnrlon=coordinates[1],
            urcrnrlat=coordinates[3],
            lat_ts=0.5 * (coordinates[2] + coordinates[3]),
            resolution='h')

if doplot == 1:
    fig = plt.figure()
    ax = fig.add_subplot(111)
    m.ax = ax

    for moorings in mooringlist:
        print moorings

        with netCDF4.Dataset(moorings) as nc:
            lon = nc.variables['LONGITUDE'][:]
            lat = nc.variables['LATITUDE'][:]
Beispiel #4
0
def run(FILE_NAME):

    DATAFIELD_NAME = '89.0V_Res.5B_TB_(not-resampled)'

    if USE_NETCDF4:
        from netCDF4 import Dataset
        nc = Dataset(FILE_NAME)

        data = nc.variables[DATAFIELD_NAME][:].astype(np.float64)
        latitude = nc.variables['Latitude'][:]
        longitude = nc.variables['Longitude'][:]
    
        # Replace the filled value with NaN, replace with a masked array.
        # Apply the scaling equation.  These attributes are named in a VERY
        # non-standard manner.
        scale_factor = getattr(nc.variables[DATAFIELD_NAME], 'SCALE FACTOR')
        add_offset = nc.variables[DATAFIELD_NAME].OFFSET

    else:
        from pyhdf.SD import SD, SDC
        hdf = SD(FILE_NAME, SDC.READ)

        # Read dataset.
        data2D = hdf.select(DATAFIELD_NAME)
        data = data2D[:,:].astype(np.float64)

        # Read geolocation dataset.
		# This product has multiple 'Latitude' and 'Longitude' pair under different groups.
        lat = hdf.select(hdf.reftoindex(192)) # Use HDFView to get ref number 192.
        latitude = lat[:,:]
        lon = hdf.select(hdf.reftoindex(194)) # Use HDFView to get ref number 194.
        longitude = lon[:,:]

        # Retrieve attributes.
        attrs = data2D.attributes(full=1)
        sfa=attrs["SCALE FACTOR"]
        scale_factor = sfa[0]        
        aoa=attrs["OFFSET"]
        add_offset = aoa[0]
        
    data[data == -32768] = np.nan
    data = data * scale_factor + add_offset
    datam = np.ma.masked_array(data, np.isnan(data))

    units = "degrees K"
    long_name = DATAFIELD_NAME

    # Since the swath starts near the south pole, but also extends over the
    # north pole, the equidistant cylindrical becomes a possibly poor choice
    # for a projection.  We show the full global map plus a limited polar map.
    fig = plt.figure(figsize=(15, 6))
    ax1 = plt.subplot(1, 2, 1)
    m = Basemap(projection='cyl', resolution='l',
                llcrnrlat=-90, urcrnrlat=90,
                llcrnrlon=-180, urcrnrlon=180)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(-90, 91, 30), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180, 181., 45), labels=[0, 0, 0, 1])
    m.pcolormesh(longitude, latitude, datam, latlon=True)

    ax2 = plt.subplot(1, 2, 2)
    m = Basemap(projection='npstere', resolution='l',
                boundinglat=65, lon_0=0)
    m.drawcoastlines(linewidth=0.5)
    m.drawparallels(np.arange(60, 81, 10), labels=[1, 0, 0, 0])
    m.drawmeridians(np.arange(-180., 181., 30.), labels=[1, 0, 0, 1])
    m.pcolormesh(longitude, latitude, datam, latlon=True)

    cax = plt.axes([0.92, 0.1, 0.03, 0.8])
    cb = plt.colorbar(cax=cax)
    cb.set_label(units)
    

    basename = os.path.basename(FILE_NAME)
    fig = plt.gcf()
    fig.suptitle('{0}\n{1}'.format(basename, long_name))
    # plt.show()
    pngfile = "{0}.py.png".format(basename)
    fig.savefig(pngfile)
Beispiel #5
0
#------------------------------------------------

# time step for ploting is 24 hours (once every day)
Nt = len(pasv_mean[:, 0, 0])
print(Nt)

i = 0
while i < Nt:
    plt.figure(figsize=(7, 9))

    plt.subplot(2, 1, 2)
    #ax = fig.add_axes([0.1,0.1,0.4,0.4])

    m = Basemap(projection='cyl',
                llcrnrlat=-90,
                urcrnrlat=90,
                llcrnrlon=-180,
                urcrnrlon=180)
    m.drawcoastlines()
    m.drawparallels(np.arange(-90., 91., 30.))
    m.drawmeridians(np.arange(-180., 181., 60.))
    m.drawmapboundary(fill_color='white')

    parallels = np.arange(-90., 90, 30.)
    m.drawparallels(parallels, labels=[1, 0, 0, 0], fontsize=8)
    meridians = np.arange(-180., -180., 60.)
    m.drawmeridians(meridians, labels=[0, 0, 0, 1], fontsize=8)
    #m.drawcountries()

    # for geos =====================
    ny = pasv_mean.shape[1]
Beispiel #6
0
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
from matplotlib.path import Path
import matplotlib.patches as patches

fig = plt.figure()

ax1 = plt.subplot2grid((2, 2), (0, 0))
ax2 = plt.subplot2grid((2, 2), (1, 0))
ax3 = plt.subplot2grid((2, 2), (0, 1), rowspan=2)

map1 = Basemap(projection='ortho', lon_0=0, lat_0=40, ax=ax1)

map1.drawmapboundary(fill_color='#9999FF')
map1.fillcontinents(color='#ddaa66', lake_color='#9999FF')
map1.drawcoastlines()

map2 = Basemap(projection='cyl',
               llcrnrlon=-15,
               llcrnrlat=30,
               urcrnrlon=15.,
               urcrnrlat=50.,
               resolution='i',
               ax=ax2)

map2.drawmapboundary(fill_color='#9999FF')
map2.fillcontinents(color='#ddaa66', lake_color='#9999FF')
map2.drawcoastlines()

map3 = Basemap(llcrnrlon=-1.,
               llcrnrlat=37.5,
Beispiel #7
0
array = gd.ReadAsArray()
# get lat/lon coordinates from DEM file.
coords = gd.GetGeoTransform()
nlons = array.shape[1]
nlats = array.shape[0]
delon = coords[1]
delat = coords[5]
lons = coords[0] + delon * np.arange(nlons)
lats = coords[3] + delat * np.arange(nlats)[::-1]  # reverse lats
# setup figure.
fig = plt.figure(figsize=(11, 6))
# setup basemap instance.
m = Basemap(llcrnrlon=-119,
            llcrnrlat=22,
            urcrnrlon=-64,
            urcrnrlat=49,
            projection='lcc',
            lat_1=33,
            lat_2=45,
            lon_0=-95)
# create masked array, reversing data in latitude direction
# (so that data is oriented in increasing latitude, as transform_scalar requires).
topoin = ma.masked_values(array[::-1, :], -999.)
# transform DEM data to a 4 km native projection grid
nx = int((m.xmax - m.xmin) / 4000.) + 1
ny = int((m.ymax - m.ymin) / 4000.) + 1
topodat = m.transform_scalar(topoin, lons, lats, nx, ny, masked=True)
# plot DEM image on map.
im = m.imshow(topodat, cmap=cm.GMT_haxby_r)
# draw meridians and parallels.
m.drawparallels(np.arange(20, 71, 10), labels=[1, 0, 1, 0])
m.drawmeridians(np.arange(-120, -40, 10), labels=[0, 1, 0, 1])
Beispiel #8
0
    if sys.hexversion > 0x03000000:
        return input(prompt)
    else:
        return raw_input(prompt)


# create Basemap instance for Orthographic (satellite view) projection.
lon_0 = float(get_input('enter reference longitude (lon_0):'))
lat_0 = float(get_input('enter reference latitude (lat_0):'))

# map with land/sea mask plotted
fig = plt.figure()
resolution = 'l'
grid = 5
m = Basemap(projection='ortho',
            lon_0=lon_0,
            lat_0=lat_0,
            resolution=resolution)
# land coral, oceans aqua.
# lakes=True means plot inland lakes with ocean color.
# resolution = 5 (default) means use 5 min dataset (can use 2.5)
m.drawcoastlines()
m.drawlsmask(land_color='coral',ocean_color='aqua', lakes=True,\
        resolution=resolution,grid=grid)
# draw parallels and meridians.
m.drawparallels(np.arange(-90., 120., 30.))
m.drawmeridians(np.arange(0., 420., 60.))
m.drawmapboundary()
plt.title('Orthographic Map Centered on Lon=%s, Lat=%s' % (lon_0, lat_0))

# map with continents drawn and filled (continent filling fails for
# lon=-120,lat=60).
Beispiel #9
0
def plot_anomaly(z, title, outname, lon, lat, colorbar=True):

    fig = plt.figure(figsize=(9, 6.5))

    # some plot parameters
    llim = -6
    ulim = 6
    lby = 1
    tby = 1
    levs = np.arange(llim, ulim + lby, lby)
    cticks = np.arange(llim, ulim + tby, tby)

    # make cyclic for plotting (add the first longitude + its data to the end)
    ibase, ilon = addcyclic(z, lon)
    icbase, iclon = addcyclic(z, lon)

    # set up grid for plotting
    glon, glat = np.meshgrid(ilon, lat)

    cmap = cm.bwr
    cnorm = colors.Normalize(cmap, clip=False)
    cmap.set_under(color=cmap(0.0), alpha=1.0)
    cmap.set_over(color=cmap(1.0), alpha=1.0)

    # lat/lon boundaries for regions
    llat = -90
    ulat = 90
    llon = -180
    ulon = 180

    map = Basemap(projection='cyl',
                  llcrnrlat=llat,
                  urcrnrlat=ulat,
                  llcrnrlon=llon,
                  urcrnrlon=ulon,
                  fix_aspect=False)
    # cylindrical is regular in latitude/longitude so no complicated mapping onto map coordinates
    x, y = map(glon, glat)

    cols = ccol.custom_colors('grads')

    plt_ax = fig.add_axes([0.12, 0.27, 0.83,
                           0.65])  # left, bottom, width, height
    cplot = map.contourf(x,
                         y,
                         ibase,
                         levs,
                         extend="both",
                         cmap=cols,
                         ax=plt_ax)
    # plot coastlines, draw label meridians and parallels.
    map.drawcoastlines(linewidth=1, color="black")
    #map.drawcountries(linewidth=0.5,color="black")
    #map.drawstates()
    map.drawparallels(np.arange(-90, 100, 30),
                      labels=[1, 0, 0, 0],
                      fontsize=26,
                      linewidth=0)
    map.drawmeridians(np.arange(-180, 240, 60),
                      labels=[0, 0, 0, 1],
                      fontsize=26,
                      linewidth=0)
    map.drawmapboundary()
    plt.title(title, fontsize=30, weight='bold')
    #plt.figtext(0.12,0.93,plotlett, size=30, weight='bold')

    ##print 'ok4'
    #if zsig!=0:
    #   # Shade OUT non-significance
    #   itvals,itlon = addcyclic(zsig['tvals'],lon)
    #   for m in range(len(itlon)-1):
    #      for n in range(len(lat)-1):
    #         print m, len(itlon)-1
    #         if(itvals[n,m]<zsig['pval']):
    #            x1 = itlon[m]
    #            x2 = itlon[m+1]
    #            y1 = lat[n]
    #            y2 = lat[n+1]
    #            plt.fill([x1,x2,x2,x1],[y1,y1,y2,y2],edgecolor='grey',fill=False,hatch='//',linewidth=0)
    #            plt.fill([x1,x2,x2,x1],[y1,y1,y2,y2],edgecolor='grey',fill=False,hatch='\\',linewidth=0)

    if colorbar:
        cbar_ax = fig.add_axes([0.12, 0.13, 0.83, 0.04])
        cbar = plt.colorbar(cplot,
                            cax=cbar_ax,
                            orientation='horizontal',
                            ticks=cticks)
        cbar.set_label('$^{\circ}$C', size=26)  #,labelpad=-0.09)
        cbar.ax.tick_params(labelsize=24)
    plt.savefig(outdir + outname + '.png')
    plt.close()
Beispiel #10
0
    def _map_init(self, showArea=None, ax=None):
        '''
        地图底图
        '''
        if showArea == "China":
            self.projection = "aea"
            m = Basemap(# width=5500000, height=4900000,
                        projection=self.projection, \
                        lat_1=25., lat_2=47, lon_0=105, lat_0=35,
                        resolution=self.resolution, ax=ax,
                        llcrnrlon=78, llcrnrlat=13,
                        urcrnrlon=146, urcrnrlat=51)

        elif showArea == "SouthPole":
            self.projection = "spaeqd"
            m = Basemap(projection=self.projection, boundinglat=-58, lon_0=180,
                        resolution=self.resolution, ax=ax)

        elif showArea == "NorthPole":
            self.projection = "npaeqd"
            m = Basemap(projection=self.projection, boundinglat=58, lon_0=0,
                        resolution=self.resolution, ax=ax)

        elif showArea == "South":
            self.projection = "ortho"
            m = Basemap(projection=self.projection, lon_0=-40, lat_0=-65,
                        resolution=self.resolution, ax=ax)

        elif showArea == "North":
            self.projection = "ortho"
            m = Basemap(projection=self.projection, lon_0=140, lat_0=65,
                        resolution=self.resolution, ax=ax)

        elif len(self.box) == 4:
            # 矩形
            nlat, slat, wlon, elon = self.box
            m = Basemap(llcrnrlon=wlon, llcrnrlat=slat,
                        urcrnrlon=elon, urcrnrlat=nlat,
                        projection=self.projection,
                        lat_1=25., lat_2=47, lon_0=105, lat_0=35,
                        resolution=self.resolution, ax=ax)

        elif len(self.box) == 2:
            lat0, lon0 = self.box
            self.projection = "ortho"
            m = Basemap(projection=self.projection, lon_0=lon0, lat_0=lat0, resolution=self.resolution, ax=ax)

        # 背景颜色
        if self.show_bg_color:
            m.fillcontinents(color=self.color_land, lake_color=self.color_ocean)
            m.drawmapboundary(fill_color=self.color_ocean)

        # draw parallels
        if self.projection in ["ortho"]:
            labels = [0, 0, 0, 0]
        else:
            labels = [1, 0, 0, 1]

        fnt = get_DV_Font(self.fontName)
        fnt.set_size(self.fontsize_tick)
        if self.delat is not None:
            parallels = np.arange(0., 91., self.delat).tolist() + \
                      np.arange(-self.delat, -91., -self.delat).tolist()
            m.drawparallels(parallels, linewidth=self.lw_latlon, labels=labels, color=self.color_latlon,
                            dashes=[100, .0001], fontproperties=fnt, textcolor=self.color_ticker,
                            latmax=90, zorder=10)
            m.drawparallels(parallels, linewidth=self.lw_latlon, labels=labels, color=self.color_latlon,
                            dashes=[100, .0001], fontproperties=fnt, textcolor=self.color_ticker,
                            latmax=90, zorder=10)

        # draw meridians
        if self.delon is not None:
            meridians = np.arange(0., 181., self.delon).tolist() + \
                        np.arange(-self.delon, -180., -self.delon).tolist()
            m.drawmeridians(meridians, linewidth=self.lw_latlon, labels=labels, color=self.color_latlon,
                            dashes=[100, .0001], fontproperties=fnt, textcolor=self.color_ticker,
                            latmax=90, zorder=10)
            m.drawmeridians(meridians, linewidth=self.lw_latlon, labels=labels, color=self.color_latlon,
                            dashes=[100, .0001], fontproperties=fnt, textcolor=self.color_ticker,
                            latmax=90, zorder=10)

        # 边框粗细
        ax_self = plt.gca()
        if self.projection == "ortho":
            # set earth no edge line
            for eachpatch in ax_self.patches:
                eachpatch.set_linewidth(EDGE_LW)
                eachpatch.set_edgecolor(self.color_ticker)
        else:
            spines = ax_self.spines
            for eachspine in spines:
                spines[eachspine].set_linewidth(EDGE_LW)

        return m
Beispiel #11
0
    def draw_boundary(self):
        '''
        边界线
        '''
        if self.show_china_boundary :
            self.m.readshapefile(os.path.join(selfPath, u'SHP/国界'), 'china',
                    linewidth=self.lw_boundray,
                    color=self.color_contry)

        if self.show_coastlines:
            # 画 海岸线
            self.m.drawcoastlines(linewidth=self.lw_boundray, color=self.color_coast)

        if self.show_countries:
            # 画 国境线
            self.m.drawcountries(linewidth=self.lw_boundray, color=self.color_contry)

        if self.show_china_province:
            # 画省线
#             self.m.readshapefile(os.path.join(selfPath, 'SHP/CHN_adm1'), 'province',
#                                  linewidth=0.2, color=color_contry)
            self.m.readshapefile(os.path.join(selfPath, u'SHP/省界'), 'province',
                        linewidth=self.lw_boundray,
                        color=self.color_contry)

        if self.show_china_county:
            # 画省线
#             self.m.readshapefile(os.path.join(selfPath, 'SHP/CHN_adm1'), 'province',
#                                  linewidth=0.2, color=color_contry)
            self.m.readshapefile(os.path.join(selfPath, u'SHP/中国县市'), 'province',
                        linewidth=self.lw_boundray * 0.8,
                        color=self.color_contry)

        if self.show_north_pole or self.show_south_pole:
            self._setLatsLabelWithinFig()

        if self.show_china:
            # 画南海 十段线
            ax = plt.gca()
            axins = zoomed_inset_axes(ax, 0.55, loc=4, borderpad=0.4)
            axins.set_xlim(105, 125)
            axins.set_ylim(5, 25)

            plt.xticks(visible=False)
            plt.yticks(visible=False)

            map2 = Basemap(projection='aea',
                    lat_1=25., lat_2=47, lon_0=105, lat_0=35,
                    resolution=self.resolution, ax=axins,
                    llcrnrlon=106, llcrnrlat=2,
                    urcrnrlon=124, urcrnrlat=25)

            if self.show_coastlines:
                map2.drawcoastlines(linewidth=self.lw_boundray, color=self.color_coast)

            if self.show_bg_color:
                map2.fillcontinents(color=self.color_land, lake_color=self.color_ocean)
                map2.drawmapboundary(fill_color=self.color_ocean)

            map2.readshapefile(os.path.join(selfPath, u'SHP/国界'), 'china',
                               linewidth=self.lw_boundray, color=self.color_contry)

            self.m2 = map2
            self.ax2 = axins

            # box line width
            spines = axins.spines
            for eachspine in spines:
                spines[eachspine].set_linewidth(EDGE_LW * 0.9)
Beispiel #12
0
def draw_map(map_type, geo_dict, filename, headless):
    import matplotlib as mpl
    if headless:
        mpl.use("Agg")
    import matplotlib.pyplot as plt
    from mpl_toolkits.basemap import Basemap

    ## Map stuff ##
    plt.figure(figsize=(16, 9), dpi=100, frameon=False, tight_layout=True)
    lon_r = 0
    lon_l = 0

    if map_type == 'NA':
        m = Basemap(llcrnrlon=-119,
                    llcrnrlat=22,
                    urcrnrlon=-54,
                    urcrnrlat=55,
                    projection='lcc',
                    resolution='l',
                    lat_1=32,
                    lat_2=45,
                    lon_0=-95)
        lon_r = 66.0
        lon_l = -124.0
    elif map_type == 'EU':
        m = Basemap(llcrnrlon=-15.,
                    llcrnrlat=20,
                    urcrnrlon=75.,
                    urcrnrlat=70,
                    projection='lcc',
                    resolution='l',
                    lat_1=30,
                    lat_2=60,
                    lon_0=35.)
        lon_r = 50.83
        lon_l = -69.03

    elif map_type == 'World':
        m = Basemap(projection='robin',
                    lat_0=0,
                    lon_0=-100,
                    resolution='l',
                    area_thresh=100000.0)
        m.drawmeridians(np.arange(0, 360, 30))
        m.drawparallels(np.arange(-90, 90, 30))
        lon_r = 180
        lon_l = -180.0

    # remove line in legend
    mpl.rcParams['legend.handlelength'] = 0
    m.drawmapboundary(fill_color='#1F1F1F')
    m.drawcoastlines()
    m.drawstates()
    m.drawcountries()
    m.fillcontinents(color='#3C3C3C', lake_color='#1F1F1F')

    for key, values in geo_dict.items():
        # add Accuracy as plot/marker size, change play count to del_s value.
        for data in values:
            if key == SERVER_FRIENDLY:
                color = '#FFAC05'
                marker = '*'
                markersize = 10
                zord = 3
                alph = 1
            else:
                if data['platform'] in PLATFORM_COLORS:
                    color = PLATFORM_COLORS[data['platform']]
                else:
                    color = DEFAULT_COLOR
                    print(
                        'Platform: {} is missing from PLATFORM_COLORS. Using DEFAULT_COLOR.'
                        .format(data['platform']))
                marker = '.'
                if data['play_count'] >= 100:
                    markersize = (data['play_count'] * .1)
                elif data['play_count'] <= 2:
                    markersize = 2
                else:
                    markersize = 2
                zord = 2
                alph = 0.4
            px, py = m(float(data['lon']), float(data['lat']))
            x, y = m(
                [float(data['lon']), float(SERVER_LON)],
                [float(data['lat']), float(SERVER_LAT)])
            legend = 'Location: {}, {},  User: {}\nPlatform: {}, IP: {}, Play Count: {}'.format(
                data['city'], data['region'], key, data['platform'],
                data['ip'], data['play_count'])
            # Keeping lines inside the Location. Plots outside Location will still be in legend

            if float(data['lon']) != float(SERVER_LON) and float(data['lat']) != float(SERVER_LAT) and \
                                    lon_l < float(data['lon']) < lon_r:
                # Drawing lines from Server location to client location
                if data['location_count'] > 1:
                    lines = m.plot(x,
                                   y,
                                   marker=marker,
                                   color=color,
                                   markersize=0,
                                   label=legend,
                                   alpha=.6,
                                   zorder=zord,
                                   linewidth=2)
                    # Adding dash sequence to 2nd, 3rd, etc lines from same city,state
                    for line in lines:
                        line.set_solid_capstyle('round')
                        dashes = [
                            x * data['location_count'] for x in [5, 8, 5, 8]
                        ]
                        line.set_dashes(dashes)

                else:
                    lines = m.plot(x,
                                   y,
                                   marker=marker,
                                   color=color,
                                   markersize=0,
                                   label=legend,
                                   alpha=.4,
                                   zorder=zord,
                                   linewidth=2)

            client_plot = m.plot(px,
                                 py,
                                 marker=marker,
                                 color=color,
                                 markersize=markersize,
                                 label=legend,
                                 alpha=alph,
                                 zorder=zord)

    handles, labels = plt.gca().get_legend_handles_labels()
    idx = labels.index(
        'Location: {}, {},  User: {}\nPlatform: {}, IP: {}, Play Count: {}'.
        format(SERVER_CITY, SERVER_STATE, SERVER_FRIENDLY, SERVER_PLATFORM,
               REPLACEMENT_WAN_IP, 0))
    labels = labels[idx:] + labels[:idx]
    handles = handles[idx:] + handles[:idx]
    by_label = OrderedDict(zip(labels, handles))

    leg = plt.legend(by_label.values(),
                     by_label.keys(),
                     fancybox=True,
                     fontsize='x-small',
                     numpoints=1,
                     title="Legend",
                     labelspacing=1.,
                     borderpad=1.5,
                     handletextpad=2.)
    if leg:
        lleng = len(leg.legendHandles)
        for i in range(1, lleng):
            leg.legendHandles[i]._legmarker.set_markersize(10)
            leg.legendHandles[i]._legmarker.set_alpha(1)
        leg.get_title().set_color('#7B777C')
        leg.draggable()
        leg.get_frame().set_facecolor('#2C2C2C')
        for text in leg.get_texts():
            plt.setp(text, color='#A5A5A7')

    plt.title(title_string)
    if filename:
        plt.savefig('{}.png'.format(filename))
        print('Image saved as: {}.png'.format(filename))
    if not headless:
        mng = plt.get_current_fig_manager()
        mng.window.state('zoomed')
        plt.show()
Beispiel #13
0
###############################################################################
import os
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
para = {
    'projection': 'merc',
    'lat_0': 0,
    'lon_0': 120,
    'resolution': 'l',
    'area_thresh': 1000.0,
    'llcrnrlon': 116,
    'llcrnrlat': 36.6,
    'urcrnrlon': 124,
    'urcrnrlat': 40.2
}
###############################################################################
my_map = Basemap(**para)
my_map.drawcoastlines()
plt.show()
###############################################################################
para['resolution'] = 'h'
my_map = Basemap(**para)
my_map.drawcoastlines()
plt.show()
###############################################################################
para['area_thresh'] = .1
my_map = Basemap(**para)
my_map.drawcoastlines()
plt.show()
Beispiel #14
0
# Suppose you'd like to make a map of the world using an orthographic, or
# satellite projection and plot some data on it. Here's how to make the
# map (using matplotlib \>= 0.98.0 and basemap \>= 0.99):
#
# <codecell>

from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt
import numpy as np
# set up orthographic map projection with
# perspective of satellite looking down at 50N, 100W.
# use low resolution coastlines.
# don't plot features that are smaller than 1000 square km.
map = Basemap(projection='ortho',
              lat_0=50,
              lon_0=-100,
              resolution='l',
              area_thresh=1000.)
# draw coastlines, country boundaries, fill continents.
map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color='coral')
# draw the edge of the map projection region (the projection limb)
map.drawmapboundary()
# draw lat/lon grid lines every 30 degrees.
map.drawmeridians(np.arange(0, 360, 30))
map.drawparallels(np.arange(-90, 90, 30))
plt.show()

# <markdowncell>
Beispiel #15
0
# -*- coding: utf-8 -*-
"""
Spyder Editor

This temporary script file is located here:
/home/fabio/.spyder2/.temp.py
"""
from mpl_toolkits.basemap import Basemap
import matplotlib.pyplot as plt

# make sure the value of resolution is a lowercase L,
#  for 'low', not a numeral 1
map = Basemap(projection='ortho',
              lat_0=12,
              lon_0=41,
              resolution='l',
              area_thresh=1000.0)

map.drawcoastlines()
map.drawcountries()
map.fillcontinents(color='coral')

plt.show()
Beispiel #16
0
from mpl_toolkits.basemap import Basemap
from mpl_toolkits.basemap import maskoceans
from mpl_toolkits.basemap import interp
import matplotlib.pyplot as plt
from osgeo import gdal
import numpy as np

map = Basemap(llcrnrlon=-93.7,
              llcrnrlat=28.,
              urcrnrlon=-66.1,
              urcrnrlat=39.5,
              projection='lcc',
              lat_1=30.,
              lat_2=60.,
              lat_0=34.83158,
              lon_0=-98.,
              resolution="h")

ds = gdal.Open("../sample_files/wrf.tiff")
lons = ds.GetRasterBand(4).ReadAsArray()
lats = ds.GetRasterBand(5).ReadAsArray()
data = ds.GetRasterBand(3).ReadAsArray()

x, y = map(lons, lats)

plt.figure(0)

mdata = maskoceans(lons, lats, data)

map.drawcoastlines(color='0.15')
map.contourf(x, y, mdata)
def mosaic_texture(humfile, sonpath, cs2cs_args = "epsg:26949", res = 99, nn = 5, weight = 1):
         
    '''
    Create mosaics of the spatially referenced sidescan echograms

    Syntax
    ----------
    [] = PyHum.mosaic_texture(humfile, sonpath, cs2cs_args, res, nn, weight)

    Parameters
    ----------
    humfile : str
       path to the .DAT file
    sonpath : str
       path where the *.SON files are
    cs2cs_args : int, *optional* [Default="epsg:26949"]
       arguments to create coordinates in a projected coordinate system
       this argument gets given to pyproj to turn wgs84 (lat/lon) coordinates
       into any projection supported by the proj.4 libraries
    res : float, *optional* [Default=0]
       grid resolution of output gridded texture map
       if res=99, res will be determined automatically from the spatial resolution of 1 pixel
    nn: int, *optional* [Default=5]
       number of nearest neighbours for gridding
    weight: int, *optional* [Default=1]
       specifies the type of pixel weighting in the gridding process
       weight = 1, based on grazing angle and inverse distance weighting
       weight = 2, based on grazing angle only
       weight = 3, inverse distance weighting only
       weight = 4, no weighting
    
    Returns
    -------

    sonpath+'GroundOverlay.kml': kml file
        contains gridded (or point cloud) sidescan intensity map for importing into google earth
        of the pth chunk

    sonpath+'map.png' : 
        image overlay associated with the kml file

    '''

    # prompt user to supply file if no input file given
    if not humfile:
       print('An input file is required!!!!!!')
       Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
       humfile = askopenfilename(filetypes=[("DAT files","*.DAT")]) 

    # prompt user to supply directory if no input sonpath is given
    if not sonpath:
       print('A *.SON directory is required!!!!!!')
       Tk().withdraw() # we don't want a full GUI, so keep the root window from appearing
       sonpath = askdirectory() 

    # print given arguments to screen and convert data type where necessary
    if humfile:
       print('Input file is %s' % (humfile))

    if sonpath:
       print('Sonar file path is %s' % (sonpath))

    if cs2cs_args:
       print('cs2cs arguments are %s' % (cs2cs_args))  

    if res:
       res = np.asarray(res,float)
       print('Gridding resolution: %s' % (str(res)))   
       
    if nn:
       nn = int(nn)
       print('Number of nearest neighbours for gridding: %s' % (str(nn)))
                    
    if weight:
       weight = int(weight)
       print('Weighting for gridding: %s' % (str(weight)))               


    ##nn = 5 #number of nearest neighbours in gridding
    ##noisefloor=10 # noise threshold in dB W

    # start timer
    if os.name=='posix': # true if linux/mac or cygwin on windows
       start = time.time()
    else: # windows
       start = time.clock()

    trans =  pyproj.Proj(init=cs2cs_args)

    # if son path name supplied has no separator at end, put one on
    if sonpath[-1]!=os.sep:
       sonpath = sonpath + os.sep

    base = humfile.split('.DAT') # get base of file name for output
    base = base[0].split(os.sep)[-1]

    # remove underscores, negatives and spaces from basename
    base = humutils.strip_base(base)

    meta = loadmat(os.path.normpath(os.path.join(sonpath,base+'meta.mat')))

    esi = np.squeeze(meta['e'])
    nsi = np.squeeze(meta['n']) 
    
    theta = np.squeeze(meta['heading'])/(180/np.pi)

    # load memory mapped scans
    shape_port = np.squeeze(meta['shape_port'])
    if shape_port!='':
       if os.path.isfile(os.path.normpath(os.path.join(sonpath,base+'_data_port_lar.dat'))):
          port_fp = io.get_mmap_data(sonpath, base, '_data_port_lar.dat', 'float32', tuple(shape_port))
       else:
          port_fp = io.get_mmap_data(sonpath, base, '_data_port_la.dat', 'float32', tuple(shape_port))

    shape_star = np.squeeze(meta['shape_star'])
    if shape_star!='':
       if os.path.isfile(os.path.normpath(os.path.join(sonpath,base+'_data_star_lar.dat'))):
             star_fp = io.get_mmap_data(sonpath, base, '_data_star_lar.dat', 'float32', tuple(shape_star))
       else:
          star_fp = io.get_mmap_data(sonpath, base, '_data_star_la.dat', 'float32', tuple(shape_star))

    # time varying gain
    tvg = ((8.5*10**-5)+(3/76923)+((8.5*10**-5)/4))*meta['c']
        
    # depth correction
    dist_tvg = np.squeeze(((np.tan(np.radians(25)))*np.squeeze(meta['dep_m']))-(tvg))

    # read in range data
    R_fp = io.get_mmap_data(sonpath, base, '_data_range.dat', 'float32', tuple(shape_star))

    dx = np.arcsin(meta['c']/(1000*meta['t']*meta['f']))
    pix_m = meta['pix_m']
    c = meta['c']

    if not os.path.isfile( os.path.normpath(os.path.join(sonpath,base+"S.p")) ):
    #if 2 > 1:
       inputfiles = []
       if len(shape_star)>2:    
          for p in range(len(star_fp)):
             e = esi[shape_port[-1]*p:shape_port[-1]*(p+1)]
             n = nsi[shape_port[-1]*p:shape_port[-1]*(p+1)]
             t = theta[shape_port[-1]*p:shape_port[-1]*(p+1)]
             d = dist_tvg[shape_port[-1]*p:shape_port[-1]*(p+1)]
             dat_port = port_fp[p]
             dat_star = star_fp[p]
             data_R = R_fp[p]
             print("writing chunk %s " % (str(p)))
             write_points(e, n, t, d, dat_port, dat_star, data_R, pix_m, res, cs2cs_args, sonpath, p, c, dx)
             inputfiles.append(os.path.normpath(os.path.join(sonpath,'x_y_class'+str(p)+'.asc')))
       else:
          p=0
          print("writing chunk %s " % (str(p)))
          write_points(esi, nsi, theta, dist_tvg, port_fp, star_fp, R_fp, meta['pix_m'], res, cs2cs_args, sonpath, 0, c, dx)
          inputfiles.append(os.path.normpath(os.path.join(sonpath,'x_y_class'+str(p)+'.asc')))         
          
       #trans =  pyproj.Proj(init=cs2cs_args)

       # D, R, h, t
       print("reading points from %s files" % (str(len(inputfiles))))
       X,Y,S,D,R,h,t,i = getxys(inputfiles)

       print("%s points read from %s files" % (str(len(S)), str(len(inputfiles))))

       # remove values where sidescan intensity is zero
       ind = np.where(np.logical_not(S==0))[0]

       X = X[ind]; Y = Y[ind]
       S = S[ind]; D = D[ind]
       R = R[ind]; h = h[ind]
       t = t[ind]; i = i[ind]
       del ind   
   
       # save to file for temporary storage
       pickle.dump( S, open( os.path.normpath(os.path.join(sonpath,base+"S.p")), "wb" ) ); del S
       pickle.dump( D, open( os.path.normpath(os.path.join(sonpath,base+"D.p")), "wb" ) ); del D
       pickle.dump( t, open( os.path.normpath(os.path.join(sonpath,base+"t.p")), "wb" ) ); del t
       pickle.dump( i, open( os.path.normpath(os.path.join(sonpath,base+"i.p")), "wb" ) ); del i

       pickle.dump( X, open( os.path.normpath(os.path.join(sonpath,base+"X.p")), "wb" ) ); del X
       pickle.dump( Y, open( os.path.normpath(os.path.join(sonpath,base+"Y.p")), "wb" ) ); del Y
       pickle.dump( R, open( os.path.normpath(os.path.join(sonpath,base+"R.p")), "wb" ) ); 
       pickle.dump( h, open( os.path.normpath(os.path.join(sonpath,base+"h.p")), "wb" ) ); 

       #grazing angle
       g = np.arctan(R.flatten(),h.flatten())
       pickle.dump( g, open( os.path.normpath(os.path.join(sonpath,base+"g.p")), "wb" ) ); del g, R, h
   
    print("creating grids ...") 

    if res==0:
       res=99

    if res==99:

       #### prepare grids
       R = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"R.p")), "rb" ) )

       ## actual along-track resolution is this: dx times dy = Af
       tmp = R * dx * (c*0.007 / 2)
       del R

       resg = np.min(tmp[tmp>0])
       del tmp
    else:
       resg = res

    X = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"X.p")), "rb" ) )
    Y = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"Y.p")), "rb" ) )
    
    humlon, humlat = trans(X, Y, inverse=True)

    grid_x, grid_y = np.meshgrid( np.arange(np.min(X), np.max(X), resg), np.arange(np.min(Y), np.max(Y), resg) )    
 
    shape = np.shape(grid_x)

    tree = KDTree(zip(X.flatten(), Y.flatten()))
    del X, Y

    print("mosaicking ...")  
    #k nearest neighbour
    try:
       dist, inds = tree.query(zip(grid_x.flatten(), grid_y.flatten()), k = nn, n_jobs=-1)
    except:
       #print ".... update your scipy installation to use faster kd-tree"   
       dist, inds = tree.query(zip(grid_x.flatten(), grid_y.flatten()), k = nn)    
    
    #del grid_x, grid_y
    
    if weight==1:
       g = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"g.p")), "rb" ) )
       w = g[inds] + 1.0 / dist**2
       del g
    elif weight==2:
       g = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"g.p")), "rb" ) )
       w = g[inds]
       del g
    elif weight==3:
       w = 1.0 / dist**2    
    elif weight==4:
       w = 1.0
    
    #g = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"g.p")), "rb" ) )
    #w = g[inds] + 1.0 / dist**2
    #del g

    if weight < 4:
       w[np.isinf(w)]=1
       w[np.isnan(w)]=1
       w[w>10000]=10000
       w[w<=0]=1
    
    # load in sidescan intensity
    S = pickle.load( open( os.path.normpath(os.path.join(sonpath,base+"S.p")), "rb" ) )
    # filter out noise pixels
    S[S<noisefloor] = np.nan

    if nn==1:
       Sdat_g = (w * S.flatten()[inds]).reshape(shape)
       del w
       dist = dist.reshape(shape)
    else:
       if weight < 4:
          Sdat_g = (np.nansum(w * S.flatten()[inds], axis=1) / np.nansum(w, axis=1)).reshape(shape)
       else:
          Sdat_g = (np.nansum(S.flatten()[inds], axis=1)).reshape(shape)
       del w
       dist = np.nanmean(dist,axis=1).reshape(shape)

    del S

    Sdat_g[dist>1] = np.nan
    Sdat_g[Sdat_g<noisefloor] = np.nan

    dat = Sdat_g.copy()
    dat[dist>1] = 0
    dat2 = replace_nans.RN(dat.astype('float64'),1000,0.01,2,'localmean').getdata()
    dat2[dat==0] = np.nan
    del dat

    dat2[dat2<noisefloor] = np.nan

    Sdat_g = dat2.copy()
    del dat2
   
    Sdat_g[Sdat_g==0] = np.nan
    Sdat_g[np.isinf(Sdat_g)] = np.nan
    Sdat_gm = np.ma.masked_invalid(Sdat_g)
    del Sdat_g

    glon, glat = trans(grid_x, grid_y, inverse=True)
    del grid_x, grid_y
    
    # =========================================================
    print("creating kmz file ...")
    ## new way to create kml file  
    pixels = 1024 * 10
 
    fig, ax = humutils.gearth_fig(llcrnrlon=glon.min(),
                     llcrnrlat=glat.min(),
                     urcrnrlon=glon.max(),
                     urcrnrlat=glat.max(),
                     pixels=pixels)
    cs = ax.pcolormesh(glon, glat, Sdat_gm)
    ax.set_axis_off()
    fig.savefig(os.path.normpath(os.path.join(sonpath,'class_overlay1.png')), transparent=True, format='png')    
    

    fig = plt.figure(figsize=(1.0, 4.0), facecolor=None, frameon=False)
    ax = fig.add_axes([0.0, 0.05, 0.2, 0.9])
    cb = fig.colorbar(cs, cax=ax)
    cb.set_label('Texture lengthscale [m]', rotation=-90, color='k', labelpad=20)
    fig.savefig(os.path.normpath(os.path.join(sonpath,'class_legend.png')), transparent=False, format='png')  


    humutils.make_kml(llcrnrlon=glon.min(), llcrnrlat=glat.min(),
         urcrnrlon=glon.max(), urcrnrlat=glat.max(),
         figs=[os.path.normpath(os.path.join(sonpath,'class_overlay1.png'))], 
         colorbar=os.path.normpath(os.path.join(sonpath,'class_legend.png')),
         kmzfile=os.path.normpath(os.path.join(sonpath,'class_GroundOverlay.kmz')), 
         name='Sidescan Intensity')


    # =========================================================
    print("drawing and printing map ...")
    fig = plt.figure(frameon=False)
    map = Basemap(projection='merc', epsg=cs2cs_args.split(':')[1], 
     resolution = 'i', #h #f
     llcrnrlon=np.min(humlon)-0.001, llcrnrlat=np.min(humlat)-0.001,
     urcrnrlon=np.max(humlon)+0.001, urcrnrlat=np.max(humlat)+0.001)

    gx,gy = map.projtran(glon, glat)
       
    try:
       map.arcgisimage(server='http://server.arcgisonline.com/ArcGIS', service='ESRI_Imagery_World_2D', xpixels=1000, ypixels=None, dpi=300)
    except:
       map.arcgisimage(server='http://server.arcgisonline.com/ArcGIS', service='World_Imagery', xpixels=1000, ypixels=None, dpi=300)
    #finally:
    #   print "error: map could not be created..."
      
    ax = plt.Axes(fig, [0., 0., 1., 1.], )
    ax.set_axis_off()
    fig.add_axes(ax)

    if Sdat_gm.size > 25000000:
       print("matrix size > 25,000,000 - decimating by factor of 5 for display")
       map.pcolormesh(gx[::5,::5], gy[::5,::5], Sdat_gm[::5,::5], vmin=np.nanmin(Sdat_gm), vmax=np.nanmax(Sdat_gm))
    else:
       map.pcolormesh(gx, gy, Sdat_gm, vmin=np.nanmin(Sdat_gm), vmax=np.nanmax(Sdat_gm))

    custom_save2(sonpath,'class_map_imagery')
    del fig 

   
    if os.name=='posix': # true if linux/mac
       elapsed = (time.time() - start)
    else: # windows
       elapsed = (time.clock() - start)
    print("Processing took "+str(elapsed)+"seconds to analyse")

    print("Done!")
Beispiel #18
0
# -*- coding: utf-8 -*-

import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np

map = Basemap(projection='cea',
              llcrnrlat=0,
              urcrnrlat=50,
              llcrnrlon=-120,
              urcrnrlon=-80)

map.drawmapboundary(fill_color="blue")

map.fillcontinents(color="coral", lake_color="yellow")

import re


def latlon(coord):
    #22°21′00″N
    r = re.search("(\d+).(\d+).(\d+)..(\w)", coord)

    g = int(r.group(1))
    m = int(r.group(2))
    s = int(r.group(3))

    return g + m / 60.0 + s / 3600.0


import sci
Beispiel #19
0
mSeis = mSeis[sel].T
mWells = np.loadtxt(file_well).T

#--------------------------2---------------------------------------------
#                       map view, select boundaries of seismicity
#------------------------------------------------------------------------
plt.figure(1)
ax1 = plt.subplot(111)
lon_0, lat_0 = .5 * (dPar['xmin'] + dPar['xmax']), .5 * (dPar['ymin'] +
                                                         dPar['ymax'])

m = Basemap(
    llcrnrlon=dPar['xmin'],
    urcrnrlon=dPar['xmax'],
    llcrnrlat=dPar['ymin'],
    urcrnrlat=dPar['ymax'],
    lon_0=lon_0,
    lat_0=lat_0,
    resolution='l',
    projection=dPar['projection'],
)
m.drawstates()
xpt, ypt = m(mSeis[1], mSeis[2])
xpt2, ypt2 = m(mWells[2], mWells[3])
# plot wells
for k in range(0, len(mWells[1])):
    if (mWells[k].all):
        ax2.plot(xpt2[k], ypt2[k], 'bo')
# plot seismicity
for j in range(0, len(sel)):
    if (sel[j]):
        ax2.plot(xpt[j], ypt[j], 'ro')
Beispiel #20
0
    def event_plot(self,
                   assoc_id,
                   west=-104.5,
                   east=-94,
                   south=33.5,
                   north=37.5,
                   deltalon=1.0,
                   deltalat=1.0):
        """ Plot all the circles, stations, location and residual distribution on one map by calling the event number after the event been associated.
        """
        plot_colors = itertools.cycle(['r', 'g', 'b', 'c', 'm', 'y'])
        fig = plt.figure(figsize=(15, 8))
        ax = fig.add_subplot(111)
        # =============================================================
        ### Map bound
        #
        #                 North
        #
        #       West                East
        #
        #                 South
        #
        # =============================================================
        ### Basemap Module
        m = Basemap(projection='merc',
                    llcrnrlat=south,
                    urcrnrlat=north,
                    llcrnrlon=west,
                    urcrnrlon=east,
                    lat_ts=0,
                    resolution='c')
        m.drawcountries()
        m.drawstates()
        m.fillcontinents(color='white', lake_color='aqua', zorder=1)
        # =============================================================
        # draw parallels, meridians and structures.

        # m.drawparallels(np.arange(South,North,deltalat),labels=[1,0,0,0],color='gray',dashes=[1,1e-5],labelstyle='+/-',linewidth=0.1)
        # m.drawmeridians(np.arange(West,East,deltalon),labels=[0,0,0,1],color='gray',dashes=[1,1e-5],labelstyle='+/-',linewidth=0.1)
        m.drawmapboundary(fill_color='blue')

        # =============================================================
        # plot matches and mismatches circles
        matches = self.assoc_db.query(Candidate).filter(
            Candidate.assoc_id == assoc_id).filter(
                Candidate.locate_flag == True).all()
        mismatches = self.assoc_db.query(Candidate).filter(
            Candidate.assoc_id == assoc_id).filter(
                Candidate.locate_flag == False).all()

        lon_eve, lat_eve = self.assoc_db.query(
            Associated.longitude,
            Associated.latitude).filter(Associated.id == assoc_id).first()
        radius_rainbow = []
        s_p_rainbow = []
        rainbow = []
        sta_rainbow = []
        for match in matches:
            lon, lat = self.tt_stations_db_1D.query(
                Station1D.longitude,
                Station1D.latitude).filter(Station1D.sta == match.sta).first()
            s_p_rainbow.append((match.ts - match.tp).total_seconds())
            radius_rainbow.append(match.d_km)
            #            Color = plot_colors.next()
            Color = next(plot_colors)
            rainbow.append(Color)
            sta_rainbow.append(match.sta)
            LocPair, = equi(m, lon, lat, match.d_km, lw=2., color=Color)
        legend_list = {"Pair for locating": LocPair}

        for mismatch in mismatches:
            lon, lat = self.tt_stations_db_1D.query(
                Station1D.longitude, Station1D.latitude).filter(
                    Station1D.sta == mismatch.sta).first()
            s_p_rainbow.append((mismatch.ts - mismatch.tp).total_seconds())
            radius_rainbow.append(mismatch.d_km)
            #            Color = plot_colors.next()
            Color = next(plot_colors)
            rainbow.append(Color)
            sta_rainbow.append(mismatch.sta)
            UnlocPair, = equi(m,
                              lon,
                              lat,
                              mismatch.d_km,
                              ls='--',
                              lw=1.,
                              color=Color)
        try:
            mismatch
        except NameError:
            pass
        else:
            legend_list["Pair not for locating"] = UnlocPair

            # =============================================================
            # plot stations
        #     stations = self.assoc_db.query(Pick.sta).filter(Pick.assoc_id==assoc_id).distinct().all()
        stations = sta_rainbow
        lon_STA = []
        lat_STA = []
        sta_STA = []
        for index, sta in enumerate(stations):  # the comma is needed
            lon, lat = self.tt_stations_db_1D.query(
                Station1D.longitude,
                Station1D.latitude).filter(Station1D.sta == sta).first()
            lon_STA.append(lon)
            lat_STA.append(lat)
            sta_STA.append(sta)
            x, y = m(lon_STA, lat_STA)
            m.scatter(x, y, marker='^', s=100, c=rainbow, zorder=3)
        for xi, yi, stai in zip(x, y, sta_STA):
            plt.text(xi,
                     yi + 1,
                     stai,
                     fontweight='bold',
                     ha='center',
                     color='k')

            # =============================================================
        # plot event location and uncertainty
        event = self.assoc_db.query(Associated).filter(
            Associated.id == assoc_id).first()
        t_create = event.t_create
        t_update = event.t_update
        ot = event.ot
        uncert = event.loc_uncert * 6371 * np.pi / 180.
        lon = event.longitude
        lat = event.latitude
        location = (lon, lat)
        x, y = m(lon, lat)
        m.scatter(x, y, marker='*', s=100, c='k', zorder=3)
        equi(m, lon, lat, uncert, color='k', lw=2.)
        # plt.title('Event %d at Origin Time: %s'%(event.id,ot), fontsize=18)
        plt.title('Event at Origin Time: %s' % (ot), fontsize=18)

        # add in the create and update time text
        # x_text,y_text=m(West+(East-West)*0.2,South+(North-South)*0.05)
        # plt.text(x_text,y_text,'Create Time: %s\nUpdate Time:%s'%(t_create,t_update),horizontalalignment='center',fontsize=12,fontweight='bold')

        # =============================================================
        # plot single phases circles
        single_phases = self.assoc_db.query(PickModified).filter(
            PickModified.assoc_id == assoc_id).filter(
                PickModified.locate_flag == None).all()

        for single_phase in single_phases:
            lon, lat = self.tt_stations_db_1D.query(
                Station1D.longitude, Station1D.latitude).filter(
                    Station1D.sta == single_phase.sta).first()
            x, y = m(lon, lat)
            pick_time = single_phase.time
            travel_time = (pick_time - ot).total_seconds()
            if single_phase.phase == 'P':
                tt, tt_uncert = self.distance_singlephase(
                    single_phase.phase, travel_time)
                d_km = tt.d_km
                UnlocPhase, = equi(m,
                                   lon,
                                   lat,
                                   d_km,
                                   ls=':',
                                   lw=2.,
                                   c='gray',
                                   zorder=4)
                m.scatter(x, y, marker='^', s=100, c='gray', zorder=5)
                plt.text(x,
                         y + 1,
                         single_phase.sta,
                         fontweight='bold',
                         ha='center')
            if single_phase.phase == 'S':
                tt, tt_uncert = self.distance_singlephase(
                    single_phase.phase, travel_time)
                d_km = tt.d_km
                UnlocPhase, = equi(m,
                                   lon,
                                   lat,
                                   d_km,
                                   ls=':',
                                   lw=2.,
                                   c='gray',
                                   zorder=4)
                m.scatter(x, y, marker='^', s=100, c='gray', zorder=5)
                plt.text(x,
                         y + 1,
                         single_phase.sta,
                         fontweight='bold',
                         ha='center')
        try:
            single_phase
        except NameError:
            pass
        else:
            legend_list["Single Phase"] = UnlocPhase

        # add on the legend
        # legend = plt.legend(legend_list.values(),legend_list.keys(),'upper left')

        # =============================================================
        # plot residual distribution

        subpos = [0.05, 0.28, 0.35, 0.6]
        subax = add_subplot_axes(ax, subpos)
        Dist = self.tt_stations_db_1D.query(TTtable1D.d_km).all()
        SP_intv = self.tt_stations_db_1D.query(TTtable1D.s_p).all()
        S_P = []
        D_S_P = []
        for dist, in Dist:
            D_S_P.append(dist)
        for s_p, in SP_intv:
            S_P.append(s_p)

        subax.plot(D_S_P, S_P, 'k-', linewidth=2, zorder=1)

        for i in range(len(radius_rainbow)):
            subax.scatter(radius_rainbow[i],
                          s_p_rainbow[i],
                          s=50,
                          color=rainbow[i],
                          zorder=2)

        plt.xlim([0, 350])
        plt.ylim([0, 40])
        plt.xlabel('Distance (km)')
        plt.ylabel('S-P (s)')
        plt.show()
Beispiel #21
0
tcwvg, tcwvc = grid_field(eralat.ravel(),
                          eralon.ravel(),
                          tcwv.ravel(),
                          gsize=2.5,
                          startlat=65.0)
#%%

lats = np.arange(-65, 65, 2.5)
lons = np.arange(-180, 180, 2.5)

fig, (ax1, ax2) = plt.subplots(2, 1, figsize=[25, 10])
plt.tight_layout()
m = Basemap(projection="cyl",
            llcrnrlon=-180,
            llcrnrlat=-65,
            urcrnrlon=177.5,
            urcrnrlat=65,
            ax=ax1)
m.drawcoastlines()
m.pcolormesh(lons, lats, y_t0, vmin=0, vmax=25, cmap=cm.rainbow)
ax1.set_title("retrieved WVP")

parallels = np.arange(-80., 80, 20.)
# labels = [left,right,top,bottom]
m.drawparallels(parallels, labels=[True, False, True, False])
meridians = np.arange(0., 360., 40.)
m.drawmeridians(meridians, labels=[True, False, False, True])

latmask = np.abs(lats) <= 45
tcwvg[latmask] = np.nan
m = Basemap(projection="cyl",

###########################################################################
### Plot absolute differences
limit = np.arange(-1, 1.1, 0.1)
barlim = np.arange(-1, 2, 1)

fig = plt.figure()
for i in xrange(years.shape[0]):
    diffsit = sitc[i] - sitp[i]
    diffsit[np.isnan(diffsit)] = 0.0

    ax = plt.subplot(2, 4, i + 1)
    m = Basemap(projection='npstere',
                boundinglat=59,
                lon_0=270,
                resolution='l',
                round=True,
                area_thresh=1000.)
    m.drawmapboundary(fill_color='white', color='dimgray', linewidth=0.7)
    m.drawcoastlines(color='k', linewidth=0.2)
    m.drawlsmask(land_color='dimgrey', ocean_color='mintcream')

    x, y = m(lonvals[i], latvals[i])
    cs = m.hexbin(x, y, C=diffsit, vmin=-1, vmax=1)

    cmap = ncm.cmap('NCV_blu_red')
    cs.set_cmap(cmap)

    ax.annotate(r'\textbf{%s}' % years[i],
                xy=(0, 0),
                xytext=(0.7, 0.97),
def netcdf2png(url,
               colormapPath,
               colormapName,
               dirDest,
               lat_name,
               lon_name,
               data_name,
               geos=False):

    # Dataset is the class behavior to open the file
    # and create an instance of the ncCDF4 class
    nc_fid = netCDF4.Dataset(url, 'r')

    if data_name == 'Band1':
        name = basename(url)  # obtengo el nombre base del archivo
    else:
        t_coverage = repr(nc_fid.getncattr('time_coverage_end'))
        # print t_coverage

        ds_name = repr(nc_fid.getncattr('dataset_name'))
        # print ds_name

        date = re.search('\'(.*?)\'', t_coverage).group(1)
        print date

        channel = re.search('-M\d(.*?)_', ds_name).group(1)
        print channel

        channelInfo(channel)

        yyyy = date[0:4]
        mm = date[5:7]
        dd = date[8:10]
        hhmm = date[11:16]

        name = channel + " " + dd + "-" + mm + "-" + yyyy + " " + hhmm + " UTC"
        print "name: " + name
    # if name

    # extract/copy the data
    lats = nc_fid.variables[lat_name][:]
    lons = nc_fid.variables[lon_name][:]
    data = nc_fid.variables[data_name][:]

    if data_name == 'CMI' or data_name == 'Rad':
        # Satellite height
        sat_h = nc_fid.variables[
            'goes_imager_projection'].perspective_point_height
        sat_h -= 10000
        # Satellite longitude
        sat_lon = nc_fid.variables[
            'goes_imager_projection'].longitude_of_projection_origin
        # Satellite sweep
        sat_sweep = nc_fid.variables['goes_imager_projection'].sweep_angle_axis
        X = nc_fid.variables[lon_name][:] * sat_h  # longitud, eje X
        Y = nc_fid.variables[lat_name][:] * sat_h  # latitud, eje Y

        # si el canal es el 2 divido las dimensiones de los elementos
        if not geos and channel == 'C02':
            X = X[7000:9500]
            Y = Y[7000:9500]
            data = data[7000:9500, 7000:9500]
        elif not geos:
            X = X[3500:4800]
            Y = Y[3500:4800]
            data = data[3500:4800, 3500:4800]
        elif geos:
            X = X[::4]
            Y = Y[::4]
            data = data[::4, ::4]

        print "sat_h: " + str(sat_h)
        print "Sat_lon: " + str(sat_lon)

    # end if data_name == 'CMI'

    nc_fid.close()

    min_lon = numpy.amin(lons)
    max_lon = numpy.amax(lons)
    min_lat = numpy.amin(lats)
    max_lat = numpy.amax(lats)

    print "min_lat: " + str(min_lon)
    print "max_lat: " + str(max_lon)
    print "min_lon: " + str(min_lat)
    print "max_lon: " + str(max_lat)

    # for i in data:
    #   print i

    print "Data min: " + str(numpy.amin(data))
    print "Data max: " + str(numpy.amax(data))

    # seteo los minimos y maximos de la imagen en funcion de los min y max de lat y long
    # axes = plt.gca()
    # axes.set_xlim([min_lon, max_lon])
    # axes.set_ylim([min_lat, max_lat])

    zona = 'plata'

    if data_name == 'Band1':  # para archivos nc ya proyectados a mercator

        X = map(lambda x: x + 0.11, lons)  # incremento X
        Y = map(lambda y: y + 0.11, lats)  # incremento Y

        ax = Basemap(projection='merc',\
                      llcrnrlat=-42.94,urcrnrlat=-22.0,\
                      llcrnrlon=-67.0,urcrnrlon=-45.04,\
                      resolution='f')
        # resolution: c, l, i, h, f

        lons2d, lats2d = numpy.meshgrid(X, Y)
        # dadas las lat y lon del archivo, obtengo las coordenadas x y para
        # la ventana seleccionada como proyeccion
        x, y = ax(lons2d, lats2d)

    elif geos:  # proyecto toda la foto completa de geo estacionario
        print "Ventana Globo geoestacionario"

        min_Y = numpy.amin(Y)
        max_Y = numpy.amax(Y)
        min_X = numpy.amin(X)
        max_X = numpy.amax(X)

        XX = map(lambda x: x + max_X, X)  # incremento X
        YY = map(lambda y: y + max_Y, Y)  # incremento Y

        print "min_Y: " + str(min_Y)
        print "max_Y: " + str(max_Y)
        print "min_X: " + str(min_X)
        print "max_X: " + str(max_X)

        print numpy.amin(XX)
        print numpy.amin(YY)

        x, y = numpy.meshgrid(XX, YY)

        ax = Basemap(projection='geos', lon_0=sat_lon, satellite_height=sat_h,\
                      llcrnrx=-x.max()/2,llcrnry=-y.max()/2,\
                      urcrnrx=x.max()/2,urcrnry=y.max()/2,\
                      resolution='l')

    elif zona == 'plata':  # proyecto con mercator en la región del río de la plata
        print "Ventana Ŕío de la Plata"

        # https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_goes16/mapping_GOES16_data.ipynb

        min_Y = numpy.amin(Y)
        max_Y = numpy.amax(Y)
        min_X = numpy.amin(X)
        max_X = numpy.amax(X)

        # parche para alinear la fotografía con las coordenadas geográficas
        # supongo que una vez esté calibrado el satélite hay que eliminar estas líneas
        X = map(lambda x: x + 10000, X)  # incremento X
        Y = map(lambda y: y + 10000, Y)  # incremento Y

        print "min_Y: " + str(min_Y)
        print "max_Y: " + str(max_Y)
        print "min_X: " + str(min_X)
        print "max_X: " + str(max_X)

        print numpy.amin(X)
        print numpy.amin(Y)

        # Región
        ax = Basemap(projection='merc',\
                llcrnrlat=-42.94,urcrnrlat=-22.0,\
                llcrnrlon=-67.0,urcrnrlon=-45.04,\
                resolution='f')

        projection = Proj(proj='geos', h=sat_h, lon_0=sat_lon, sweep=sat_sweep)
        x_mesh, y_mesh = numpy.meshgrid(X, Y)
        lons, lats = projection(x_mesh, y_mesh, inverse=True)
        x, y = ax(lons, lats)

    elif zona == 'sur':  # proyecto con mercator en la región del río de la plata
        print "Ventana Sur"

        # https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_goes16/mapping_GOES16_data.ipynb

        min_Y = numpy.amin(Y)
        max_Y = numpy.amax(Y)
        min_X = numpy.amin(X)
        max_X = numpy.amax(X)

        # parche para alinear la fotografía con las coordenadas geográficas
        # supongo que una vez esté calibrado el satélite hay que eliminar estas líneas
        X = map(lambda x: x + 10000, X)  # incremento X
        Y = map(lambda y: y + 3000, Y)  # incremento Y
        # X = map(lambda x: x+10000, X) # incremento X
        # Y = map(lambda y: y+10000, Y) # incremento Y

        print "min_Y: " + str(min_Y)
        print "max_Y: " + str(max_Y)
        print "min_X: " + str(min_X)
        print "max_X: " + str(max_X)

        print numpy.amin(X)
        print numpy.amin(Y)

        # Región
        ax = Basemap(projection='merc',\
                llcrnrlat=-49.4947,urcrnrlat=-13.6169,\
                llcrnrlon=-73.4699,urcrnrlon=-39.2205,\
                resolution='f')

        projection = Proj(proj='geos', h=sat_h, lon_0=sat_lon, sweep=sat_sweep)
        x_mesh, y_mesh = numpy.meshgrid(X, Y)
        lons, lats = projection(x_mesh, y_mesh, inverse=True)
        x, y = ax(lons, lats)

    elif zona == 'uy':  # proyecto con mercator en la región del río de la plata
        print "Ventana Uruguay"

        # https://github.com/blaylockbk/pyBKB_v2/blob/master/BB_goes16/mapping_GOES16_data.ipynb

        min_Y = numpy.amin(Y)
        max_Y = numpy.amax(Y)
        min_X = numpy.amin(X)
        max_X = numpy.amax(X)

        # parche para alinear la fotografía con las coordenadas geográficas
        # supongo que una vez esté calibrado el satélite hay que eliminar estas líneas
        X = map(lambda x: x + 10000, X)  # incremento X
        Y = map(lambda y: y + 10000, Y)  # incremento Y

        print "min_Y: " + str(min_Y)
        print "max_Y: " + str(max_Y)
        print "min_X: " + str(min_X)
        print "max_X: " + str(max_X)

        print numpy.amin(X)
        print numpy.amin(Y)

        # Región
        ax = Basemap(projection='merc',\
                llcrnrlat=-35.2138,urcrnrlat=-29.7466,\
                llcrnrlon=-58.9073,urcrnrlon=-52.7591,\
            # llcrnrx=-x.max()/2,llcrnry=-y.max()/2,\
            # urcrnrx=x.max()/2,urcrnry=y.max()/2,\
                resolution='f')

        projection = Proj(proj='geos', h=sat_h, lon_0=sat_lon, sweep=sat_sweep)
        x_mesh, y_mesh = numpy.meshgrid(X, Y)
        lons, lats = projection(x_mesh, y_mesh, inverse=True)
        x, y = ax(lons, lats)

    # end if

    # agrego los vectores de las costas, departamentos/estados/provincias y paises
    ax.drawcoastlines(linewidth=0.25)
    ax.drawcountries(linewidth=0.50)
    ax.drawstates(linewidth=0.25)

    if not geos:
        # dibujo los valores de latitudes y longitudes al margen de la imagen
        par = ax.drawparallels(numpy.arange(-45, -20, 5),
                               labels=[1, 0, 0, 0],
                               linewidth=0.0,
                               fontsize=10,
                               color='white')
        mer = ax.drawmeridians(numpy.arange(-70, -45, 5),
                               labels=[0, 0, 1, 0],
                               linewidth=0.0,
                               fontsize=10,
                               color='white')
        setcolor(par, 'white')
        setcolor(mer, 'white')

    # llamo al garbage collector para que borre los elementos que ya no se van a usar
    gc.collect()

    if channel == 'C02':
        data *= 100
    else:
        # Los datos de estan en kelvin, asi que los paso a Celsius
        data -= 273.15

    # defino el min y max en funcion de la banda
    if data_name == 'Band1':
        vmin = numpy.amin(data)
        vmax = numpy.amax(data)
    else:
        vmin, vmax = rangoColorbar(channel)

    print numpy.amin(data)
    print numpy.amax(data)

    data = numpy.ma.masked_where(numpy.isnan(data), data)

    # dibujo img en las coordenadas x e y calculadas

    # cmap = gmtColormap(colormapName, colormapPath, 2048)

    # defino el colormap  y la disposicion de los ticks segun la banda
    if channel == 'C02':
        ticks = [0, 20, 40, 60, 80, 100]
        ticksLabels = ticks
    elif channel == 'C08' or channel == 'C09':
        ticks = [-60, -50, -40, -30, -20, -10, 0]
        ticksLabels = ticks
    else:
        ticks = [
            -80, -75.2, -70.2, -65.2, -60.2, -55.2, -50.2, -45.2, -40.2, -35.2,
            -30.2, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70
        ]
        # defino las etiquetas del colorbar
        ticksLabels = [
            -80, -75, -70, -65, -60, -55, -50, -45, -40, -35, -30, -20, -10, 0,
            10, 20, 30, 40, 50, 60, 70
        ]
    # if FR o RP

    cmap = gmtColormap(colormapName, colormapPath, 2048)
    cs = ax.pcolormesh(x, y, data, vmin=vmin, vmax=vmax, cmap=cmap)

    # seteo los limites del colorbar
    plt.clim(vmin, vmax)

    # agrego el colorbar
    cbar = ax.colorbar(cs, location='bottom', pad='3%', ticks=ticks)

    if channel == 'C02':
        cbar.ax.set_xticklabels(ticksLabels, fontsize=7, color='white')
    else:
        cbar.ax.set_xticklabels(ticksLabels,
                                rotation=45,
                                fontsize=7,
                                color='white')

    cbar.ax.set_xlabel("Temperatura de brillo ($^\circ$C)",
                       fontsize=7,
                       color='white')

    if channel != 'C02':
        cbar.ax.xaxis.labelpad = 0

    # agrego el logo en el documento
    logo = plt.imread('./logo_300_bw.png')
    plt.figimage(logo, 5, 5)

    # si estoy dibujando toda la proyección geos adjunto el string al nombre del archivo
    if geos:
        destFile = dirDest + name + '_geos.png'  # determino el nombre del archivo a escribir
    else:
        destFile = dirDest + name + '.png'  # determino el nombre del archivo a escribir

    # llamo al garbage collector para que borre los elementos que ya no se van a usar
    gc.collect()

    print destFile

    # genero el pie de la imagen, con el logo y la info del archivo
    plt.annotate(name, (0, 0), (106, -60),
                 xycoords='axes fraction',
                 textcoords='offset points',
                 va='top',
                 fontsize=14,
                 family='monospace',
                 color='white')

    plt.savefig(destFile, bbox_inches='tight', dpi=300,
                transparent=True)  # , facecolor='#4F7293'
    plt.close()
#---------------------------------------------------------
# Visualize stations on map
#---------------------------------------------------------
#plotstations = 'yes'
plotstations = 'no'

if plotstations == 'yes':

    # create figure
    plt.close('all')
    fig = plt.figure(figsize=(22, 30))

    # define map projection and add basic geographical features
    #map = Basemap(width=0.4e6,height=0.3e6,projection='stere',lat_ts=46.8,lat_0=46.8,lon_0=8.21,resolution='h')
    map = Basemap(projection='merc',llcrnrlat=45.7,urcrnrlat=47.95,\
            llcrnrlon=5.7,urcrnrlon=10.7,lat_ts=46.8,resolution='h',epsg=3395)
    map.drawcountries(linewidth=1.5)
    map.drawcoastlines()
    #map.drawrivers(color='blue')
    map.arcgisimage(service='World_Shaded_Relief', xpixels=2000)

    # plot meteoswiss automatic measurement network
    x, y = map(stationcoords_lon, stationcoords_lat)
    map.plot(x, y, 'vk', markersize=10)

    # plot TreeNet station network
    i, j = map(treenetcoords_lon, treenetcoords_lat)
    map.plot(i, j, 'ro', markersize=10)

    # export figure
    saveas = '\stationmap.png'
    'lat': 37.7267,
    'lon': -84.3001,
    'color': 'r',
    'tz': 'US/Eastern'
}

cloud_temp = -25.0
local = pytz.timezone('US/Central')
utc = pytz.timezone('UTC')

plt.figure(num=None, figsize=(8, 6), dpi=80, facecolor='w', edgecolor='k')

# setup Lambert Conformal basemap.
m = Basemap(llcrnrlon=-95.,
            llcrnrlat=30.,
            urcrnrlon=-75.,
            urcrnrlat=45.,
            projection='mill',
            resolution='i')
#            projection='merc', area_thresh=1000,
#            resolution='i',lat_1=45.,lat_2=55,lat_0=40,lon_0=-85.)

# draw coastlines and fill the continents (alpha value is set to partial transparancy because for some
# reason the fill is over top the quivers used to denote the wind vectors
m.drawcoastlines()
m.drawstates()
m.fillcontinents(color='0.8')
m.drawparallels(np.arange(30, 45, 5), labels=[1, 1, 0, 0])
m.drawmeridians(np.arange(-95, -75, 5), labels=[0, 0, 0, 1])

# draw coastlines and fill the continents (alpha value is set to partial transparancy because for some
# reason the fill is over top the quivers used to denote the wind vectors
Beispiel #26
0
import os
import numpy as np
from netCDF4 import Dataset
import matplotlib.pyplot as pl
from mpl_toolkits.basemap import Basemap
from shapely.geometry import Polygon, Point, LineString
from geopy.distance import vincenty
import functions as funct

m = Basemap(projection='spstere', boundinglat=-60, lon_0=180, resolution='l')

length = 200
dot_array = np.full((6, 12, length, 11), fill_value=np.NaN)
dist_2 = np.full((6, 12, length, 11), fill_value=np.NaN)
coast_distance_array = np.full((6, 12, length), fill_value=np.NaN)

for year in ['2011', '2012', '2013', '2014', '2015', '2016']:
    for month in [
            '01', '02', '03', '04', '05', '06', '07', '08', '09', '10', '11',
            '12'
    ]:
        file = '/Users/jmh2g09/Documents/PhD/Data/Gridded/' + year + month + '_grid.nc'
        nc = Dataset(file, 'r')
        latitude = nc.variables['lat'][:]
        longitude = nc.variables['lon'][:]
        dot = nc.variables[
            'filtered_dynamic_ocean_topography_seasonal_offset'][:]
        nc.close()

        nc_grid = Dataset(
            '/Users/jmh2g09/Documents/PhD/Data/CoastalCurrent/grid.nc', 'w')
Beispiel #27
0
    def plot_global_map_weights(self):
        """
        Plot global map of event and stations
        """

        # import basemap here due to error
        from mpl_toolkits.basemap import Basemap

        # ax = plt.subplot(211)
        plt.title(self.cmtsource.eventname + "_Weights")
        m = Basemap(projection='cyl', lon_0=0.0, lat_0=0.0, resolution='c')
        m.drawcoastlines()
        m.fillcontinents()
        m.drawparallels(np.arange(-90., 120., 30.))
        m.drawmeridians(np.arange(0., 420., 60.))
        m.drawmapboundary()

        #x, y = m(self.sta_lon, self.sta_lat)
        x, y = self.sta_lon, self.sta_lat
        w = [meta.weights for meta in self.metas]
        print(w)
        w /= max(w)
        w = map(float, w)
        #w = map(str, w)
        w = list(w)
        s = [np.sqrt(x) * 100 for x in w]
        w = [x**0.5 for x in w]
        #print(self.sta_lon,self.sta_lat)
        #print(self.metas)
        #print(len(self.metas),len(self.sta_lon))
        #print(w)

        m.scatter(x, y, s=s, c=w, marker="^", cmap='hsv', zorder=3)
        cmt_lat = self.cmtsource.latitude
        cmt_lon = self.cmtsource.longitude
        focmecs = get_cmt_par(self.cmtsource)[:6]
        ax = plt.gca()
        if self.mode == 'regional':
            minlon = min(self.sta_lon)
            maxlon = max(self.sta_lon)
            minlat = min(self.sta_lat)
            maxlat = max(self.sta_lat)
            padding = 0.2
            m.drawparallels(np.arange(-90., 120., padding),
                            labels=[1, 1, 0, 0],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.drawmeridians(np.arange(0., 420., padding),
                            labels=[0, 0, 1, 1],
                            fmt="%.2f",
                            dashes=[2, 2])
            m.etopo()
            ax.set_xlim(minlon - padding, maxlon + padding)
            ax.set_ylim(minlat - padding, maxlat + padding)
            width_beach = min((maxlon + 2 * padding - minlon) / (40 * padding),
                              (maxlat + 2 * padding - minlat) / (40 * padding))

        bb = beach(focmecs,
                   xy=(cmt_lon, cmt_lat),
                   width=width_beach,
                   linewidth=1,
                   alpha=1.0)
        bb.set_zorder(10)
        ax.add_collection(bb)
def plotConc(concData, lonData, latData, saveLoc, modelRun, prtype, ip1, spc, cmapType, bins, minVal, maxVal, extension, name, removed,buff):
    """ Plots and saves concentration data.

    Will plot difference data if difference data was passed.
    """

    # useful things for determining projection details
    lowLon = np.amin(lonData)
    lowLat = np.amin(latData)
    highLon = np.amax(lonData)
    highLat = np.amax(latData)
    maxDim = maxDimensions(lowLon,highLon,lowLat,highLat,buff)
    midLon = (highLon+lowLon)/2
    midLat = (highLat + lowLat)/2
    # Uncomment the following lines for an alternative midLatLon calculation
    #mids = midLatLon(lonData,latData)
    #midLon = mids['midLon']
    #midLat = mids['midLat']
    max_width = abs(maxDim['xDist'])
    max_height = abs(maxDim['yDist'])
    # Initialize the figure
    fig = plt.figure(figsize=(8,8))

    # Create the map based on projection type
    if (prtype=='ortho') or (prtype == 'nsper') or (prtype == 'laea') or (prtype == 'aeqd') or (prtype == 'gnom') or (prtype == 'lcc'):
        concMap = Basemap(projection=prtype, resolution = 'c', lon_0=midLon, lat_0=midLat, width=max_width, height=max_height)
    elif prtype == 'stere':
        concMap = Basemap(projection=prtype, lon_0=midLon,lat_0=midLat,width=max_width,height=max_height)
    elif (prtype == 'cyl') or (prtype == 'merc'):
        concMap = Basemap(projection=prtype, resolution='c', llcrnrlat=lowLat,  urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon)
    elif (prtype == 'aea') or (prtype == 'eqdc'):
        concMap = Basemap(projection = prtype, lon_0=midLon,  lat_0=midLat, llcrnrlat=lowLat, urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon)
    elif(prtype == 'global'):
        concMap = Basemap(projection = 'cyl', resolution='c', llcrnrlat=lowLat,  urcrnrlat=highLat, llcrnrlon=lowLon, urcrnrlon=highLon)
        mapColor = cmapType
        mapBins = bins
        midPoint = (len(lonData))/2
        xFirst, yFirst = concMap(lonData[:midPoint], latData[:midPoint])
        xLast, yLast = concMap(lonData[midPoint:], latData[midPoint:])
        concFirst = concData[:midPoint]
        concLast = concData[midPoint:]
        concMap.pcolormesh(xFirst, yFirst, concFirst, cmap=plt.cm.get_cmap(mapColor, mapBins))
        concMap.pcolormesh(xLast, yLast, concLast, cmap=plt.cm.get_cmap(mapColor, mapBins))
        concMap.drawcoastlines(color='lightgray')
        concMap.drawcountries(color='gray')
        concMap.drawstates(color='gray')
        concMap.drawmeridians(np.arange(-180, 180,10), labels=[0,0,0,1], fontsize=6)
        concMap.drawparallels(np.arange(-90,90,10), labels=[1,0,0,0],fontsize=6)
        cbar = plt.colorbar(extend = extension, shrink=0.5)
        cbar.set_label=('Concentration: '+spc)
        plt.clim(minVal, maxVal)
        hy = ((os.popen('r.ip1 {}'.format(ip1))).read()).lstrip()
        plt.title('{}, {} \n  hy: {}, Spc: {}'.format(name,modelRun, hy,spc))
        fig.savefig(os.path.join(saveLoc, modelRun) + '_' + spc + '_' + name + '.png', dpi=300, bbox_inches='tight', pad_inches=0.3)

        plt.close('all')

    else:
        print('Error: Could not generate map. Try a different projection.')
        # Can check the available basemap types and add to existing if statements

    # Add in other map details
    mapColor = cmapType
    mapBins = bins
    # if stripping the borders of the data....
    if removed != 0:
        ni = len(lonData)
        nj = len(lonData[0])
        n_pil = removed
        x, y = concMap(lonData[n_pil:ni-n_pil,n_pil:nj-n_pil], latData[n_pil:ni-n_pil,n_pil:nj-n_pil])
        concMap.pcolormesh(x,y,concData[n_pil:ni-n_pil,n_pil:nj-n_pil],cmap=plt.cm.get_cmap(mapColor,mapBins))
    else:
        x, y = concMap(lonData, latData)
        concMap.pcolormesh(x, y, concData, cmap=plt.cm.get_cmap(mapColor, mapBins))
    concMap.drawcoastlines(color='lightgray')
    concMap.drawcountries(color='gray')
    concMap.drawstates(color='gray')
    # Comment out the following to remove lonlat lines
    concMap.drawmeridians(np.arange(-180, 180,10), labels=[0,0,0,1], fontsize=6)
    concMap.drawparallels(np.arange(-90,90,10), labels=[1,0,0,0],fontsize=6)

    # Add colorbar and details
    #TODO: Fix the set label option for the colorbar, right now the colorbar doesn't have a title
    cbar = plt.colorbar(extend = extension, shrink=0.5)
    cbar.set_label=('Concentration: '+spc)
    plt.clim(minVal, maxVal)

    # Name and save the figure
    hy = ((os.popen('r.ip1 {}'.format(ip1))).read()).lstrip()
    plt.title('{}, {} \n  hy: {}, Spc: {}'.format(name,modelRun, hy,spc))
    fig.savefig(os.path.join(saveLoc, modelRun) + '_' + spc + '_' + name + '.png', dpi=300, bbox_inches='tight', pad_inches=0.3)

    plt.close('all')
Beispiel #29
0
    lats_sl = lats[620:720]
    rain_sl_raw = precip_raw[620:720,785:830].T #30 x 35
    Total_rain.append(rain_sl_raw)
    rain_sl_sw_raw = precip_raw[649:691,780:806]
    Total_rain_sw.append(rain_sl_sw_raw)
rain_sl=sum(Total_rain)
rain_sl_sw=sum(Total_rain_sw)
#SW SL
lons_sl_sw=lons[780:806] #77.9E to 80.4E
lats_sl_sw=lats[649:691]#5N to 9N
cmap=cm.rainbow
#cmap.set_under("w",alpha=0)
lon_0 = lons_sl.mean()
lat_0 = lats_sl.mean()
levels=[0, 1, 2, 4, 8, 16, 32, 64, 128, 256]
m = Basemap(llcrnrlon=77, llcrnrlat=5, urcrnrlon=82,urcrnrlat=10, projection='lcc',lat_0=lat_0,lon_0=lon_0, resolution='f')
#lats_sl=lats_sl[::-1]
#rain_sl=rain_sl[::-1]
#precip_T=np.flipud(precip_T)
lon, lat = np.meshgrid(lons_sl, lats_sl)
xi, yi = m(lon, lat)
fig = plt.figure(figsize=(15.,15.))
precip_T=rain_sl
# Plot Data
cs = m.contourf(xi,yi,precip_T,cmap=plt.cm.rainbow, levels=levels)
# Add Grid Lines
m.drawparallels(np.arange(-80., 81., 1.), labels=[1,0,0,0], fontsize=1)
m.drawmeridians(np.arange(-180., 181., 1.), labels=[0,0,0,1], fontsize=1)
# Add Coastlines, States, and Country Boundaries
m.drawcoastlines()
m.drawstates()
Beispiel #30
0
from mpl_toolkits.basemap import Basemap
import numpy as np
import matplotlib.pyplot as plt
# llcrnrlat,llcrnrlon,urcrnrlat,urcrnrlon
# are the lat/lon values of the lower left and upper right corners
# of the map.
# resolution = 'c' means use crude resolution coastlines.
m = Basemap(projection='cyl',llcrnrlat=-90,urcrnrlat=90,\
            llcrnrlon=-180,urcrnrlon=180,resolution='c')
m.drawcoastlines()
m.fillcontinents(color='coral', lake_color='aqua')
# draw parallels and meridians.
m.drawparallels(np.arange(-90., 91., 30.))
m.drawmeridians(np.arange(-180., 181., 60.))
m.drawmapboundary(fill_color='aqua')
plt.title("Equidistant Cylindrical Projection")
plt.show()