Skip to content
Snippets Groups Projects
Commit b45a84b9 authored by Charles Troupin's avatar Charles Troupin
Browse files

remove python

parent 399091a4
No related branches found
No related tags found
No related merge requests found
Showing
with 0 additions and 7719 deletions
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
source diff could not be displayed: it is too large. Options to address this: view the blob.
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
{
"cells": [],
"metadata": {},
"nbformat": 4,
"nbformat_minor": 2
}
import os
import numpy as np
import netCDF4
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import six
from six.moves import xrange
import matplotlib
import matplotlib.cm as cm
import matplotlib.colors as mcolors
import matplotlib.collections as mcollections
import matplotlib.patches as patches
from matplotlib.path import Path
from matplotlib.offsetbox import AnnotationBbox, OffsetImage
from matplotlib._png import read_png
def add_logo(imagepath, ax, position, zoom, zorder):
"""Add an image on the figure
:param imagepath: path to the image to add
:param ax: axes object
:param position: relative position on the map
:param zoom: zoom level
:param zorder:
:return:
"""
logo2plot = read_png(imagepath)
imagebox = OffsetImage(logo2plot, zoom=zoom)
# coordinates to position this image
ab = AnnotationBbox(imagebox, position,
xybox=(0., 0.),
xycoords='data',
pad=0.0,
boxcoords="offset points")
ab.zorder = zorder
ax.add_artist(ab)
def create_rect_patch(coordinates, m, **kwargs):
"""
Create a rectangular patch to add on the map
:param coordinates:
:param m: Basemap object
:return: patch
"""
xr1, yr1 = m(coordinates[0], coordinates[2])
xr2, yr2 = m(coordinates[0], coordinates[3])
xr3, yr3 = m(coordinates[1], coordinates[3])
xr4, yr4 = m(coordinates[1], coordinates[2])
verts = [(xr1, yr1), (xr2, yr2), (xr3, yr3), (xr4, yr4), (xr1, yr1), ]
codes = [Path.MOVETO, Path.LINETO, Path.LINETO,
Path.LINETO, Path.CLOSEPOLY, ]
path = Path(verts, codes)
patch = patches.PathPatch(path, **kwargs)
return patch
def extract_coastline(coordinates, filename, res='i'):
"""
Extract the coastline in a region delimited by a bounding box
and save the result in a text file
:param coordinates: coordinates delimiting a bounding box (lonmin, lonmax, latmin, latmax)
:param filename: name of the file where the coastline will be saved
:param res: resolution for the extraction
:return:
"""
x, y = gshhs.get_coastline(xlim=[coordinates[0], coordinates[1]],
ylim=[coordinates[2], coordinates[3]],
res=res)
# Save the coastline
np.savetxt(filename, np.ma.vstack((x, y)).T)
def load_coast(coastfile, valex=-999.):
"""
Read coastline coordinates from an existing file
:param coastfile: name of the file containing the coastline
:param valex: exclusion value
:return: lon, lat
"""
lon, lat = np.loadtxt(coastfile, usecols=(0, 1), unpack=True)
lon[lon == valex] = np.nan
lat[lat == valex] = np.nan
return lon, lat
def load_coast_gshhs(coastfile, coordinates, valex=-999.):
"""
Read coastline coordinates from an existing file in a region delimited
by a bounding box
:param coastfile: name of the file containing the coastline
:param coordinates: coordinates delimiting a bounding box (lonmin, lonmax, latmin, latmax)
:param valex: exclusion value
:return: lon, lat
"""
lon, lat = np.loadtxt(coastfile, usecols=(0, 1), unpack=True)
goodcoord = np.where((lon >= coordinates[0]) & (lon <= coordinates[1]) &
(lat >= coordinates[2]) & (lat <= coordinates[3]))[0]
goodcoord2 = np.where(np.logical_or((lon == valex), (lat == valex)))[0]
goodcoord = np.union1d(goodcoord, goodcoord2)
lon, lat = lon[goodcoord], lat[goodcoord]
lon[lon == valex] = np.nan
lat[lat == valex] = np.nan
return lon, lat
def alborex_load_bathy(bathyfile, coordinates):
"""
Load bathymetry from a netCDF file in a select region
delimited by a list of coordinates
:param bathyfile: name of the netCDF file
:param coordinates: coordinates delimiting a bounding box (lonmin, lonmax, latmin, latmax)
:return:
"""
with netCDF4.Dataset( bathyfile, 'r') as nc:
lon = nc.variables['longitude'][:]
lat = nc.variables['latitude'][:]
depth = nc.variables['depth'][:]
# subset
goodlon = np.where(np.logical_and((lon >= coordinates[0]),
(lon <= coordinates[1])))[0]
goodlat = np.where(np.logical_and((lat >= coordinates[2]),
(lat <= coordinates[3])))[0]
lon = lon[goodlon]
lat = lat[goodlat]
depth = depth[goodlat, :]
depth = depth[:, goodlon]
return lon, lat, depth
def load_altimetry(altimetryfile, coordinates):
"""
:param altimetryfile:
:param coordinates: coordinates delimiting a bounding box (lonmin, lonmax, latmin, latmax)
:return:
"""
with netCDF4.Dataset(altimetryfile, 'r') as nc:
lon = nc.variables['lon'][:] - 360.
lat = nc.variables['lat'][:]
u = np.squeeze(nc.variables['u'][:])
v = np.squeeze(nc.variables['v'][:])
# subset
goodlon = np.where(np.logical_and((lon >= coordinates[0]),
(lon <= coordinates[1])))[0]
goodlat = np.where(np.logical_and((lat >= coordinates[2]),
(lat <= coordinates[3])))[0]
lon = lon[goodlon]
lat = lat[goodlat]
u = u[goodlat, :]
u = u[:, goodlon]
v = v[goodlat, :]
v = v[:, goodlon]
return lon, lat, u, v
def load_sst(sstfile, coordinates):
"""Return the coordinates, the SST, the time and the satellite name,
given a data file and a list of coordinates delimiting a bounding box
:param sstfile: name of the netCDF4 file containing the data
:param coordinates: coordinates delimiting a bounding box (lonmin, lonmax, latmin, latmax)
:return:
"""
with netCDF4.Dataset(sstfile, 'r') as nc:
lon = nc.variables['lon'][:]
lat = nc.variables['lat'][:]
timesst = nc.variables['time'][:]
# subset
goodlon = np.where(np.logical_and((lon >= coordinates[0]),
(lon <= coordinates[1])))[0]
goodlat = np.where(np.logical_and((lat >= coordinates[2]),
(lat <= coordinates[3])))[0]
lon = lon[goodlon]
lat = lat[goodlat]
sst = np.squeeze(nc.variables['mcsst'][:, goodlat, goodlon])
mask = nc.variables['lsmask'][:, goodlat, goodlon].squeeze()
sst = np.ma.masked_where(mask == 1, sst)
timesst *= 60.
sat = nc.satellite
sensor = nc.sensor_name
sensorsat = sensor.upper() + ' on ' + sat.upper()
return lon, lat, sst, timesst, sensorsat
def load_sst_l2(filename):
"""
Load the SST from netCDF L2 file obtained from
https://oceancolor.gsfc.nasa.gov
:param filename: name of the netCDF file
:return: lon, lat, sst, sstflag, sstyear, sstday
"""
if os.path.exists(filename):
with netCDF4.Dataset(filename) as nc:
# Read platform
sat = nc.platform
# Read time information
# Assume all the measurements made the same day (and same year)
year = nc.groups['scan_line_attributes'].variables['year'][0]
day = nc.groups['scan_line_attributes'].variables['day'][0]
# Read coordinates
lon = nc.groups['navigation_data'].variables['longitude'][:]
lat = nc.groups['navigation_data'].variables['latitude'][:]
# Read geophysical variables
try:
sst = nc.groups['geophysical_data'].variables['sst'][:]
sstqual = nc.groups['geophysical_data'].variables['qual_sst'][:]
except KeyError:
sst = nc.groups['geophysical_data'].variables['sst4'][:]
sstqual = nc.groups['geophysical_data'].variables['qual_sst4'][:]
else:
lon, lat, sst, sstqual, year, day, sat = [], [], [], [], [], [], []
return lon, lat, sst, sstqual, year, day, sat
def load_sst_l2_old(sstfile):
"""
Load the SST from netCDF L2 file obtained from
https://oceancolor.gsfc.nasa.gov
:param sstfile: name of the netCDF file
:return: lon, lat, sst, sstflag, sstyear, sstday
"""
if 'SST4' in sstfile:
sstname = 'Geophysical_Data_sst4'
sstflagname = 'Geophysical_Data_qual_sst4'
else:
sstname = 'Geophysical_Data_sst'
sstflagname = 'Geophysical_Data_qual_sst'
with netCDF4.Dataset(sstfile, 'r') as nc:
lon = nc.variables['Navigation_Data_longitude'][:]
lat = nc.variables['Navigation_Data_latitude'][:]
sst = nc.variables[sstname][:] * 0.005
sstflag = nc.variables[sstflagname][:]
sst = np.ma.masked_where(sstflag > 1, sst)
sstyear = nc.Start_Year
sstday = nc.Start_Day
return lon, lat, sst, sstflag, sstyear, sstday
def plot_sst_leaflet(lon, lat, sst, figname, **kwargs):
m = Basemap(llcrnrlon=coordinates[0],
llcrnrlat=coordinates[2],
urcrnrlon=coordinates[1],
urcrnrlat=coordinates[3], resolution = 'l', epsg=3857)
llon, llat = m(lon, lat)
fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
m.pcolormesh(llon, llat, sst, **kwargs)
ax.axis('off')
#ax.set_xlim(lon.min(), lon.max())
#ax.set_ylim(lat.min(), lat.max())
f1 = plt.gca()
f1.axes.get_xaxis().set_ticks([])
f1.axes.get_yaxis().set_ticks([])
plt.savefig(figname, transparent=True,
bbox_inches='tight', pad_inches=0)
plt.close()
def load_ctd(ctdfile):
"""
Load the coordinates (lon, lat, depth), the temperature and chlorophyll concentration
from the selected netCDF file
:param ctdfile: name of the netCDF file
:return: lon, lat, depth, temp, chloro
"""
with netCDF4.Dataset(ctdfile, 'r') as nc:
lon = nc.variables['LON'][:]
lat = nc.variables['LAT'][:]
depth = nc.variables['DEPTH'][:]
time = nc.variables['time'][:]
temp = nc.variables['WTR_TEM_01'][:]
chloro = nc.variables['CHLO'][:]
chloro = np.ma.masked_where(np.isnan(chloro), chloro)
return lon, lat, depth, time, temp, chloro
def load_glider_data(gliderfile, NN=1):
"""
Load the coordinates and the temperature from a glider file
:param gliderfile: name of the netCDF file
:param NN: sub-sampling factor (keep 1 out of NN measurements)
"""
with netCDF4.Dataset(gliderfile, 'r') as nc:
lon = nc.variables['longitude'][::NN]
lat = nc.variables['latitude'][::NN]
depth = nc.variables['depth'][::NN]
temperature = nc.variables['temperature'][::NN]
return lon, lat, depth, temperature
def load_glider_coord(gliderfile):
"""
Load the coordinates from a glider file
:param gliderfile: name of the glider netCDF file
:return: lon: longitude
:return: lat: latitude
:return: depth: depth
:return: time: time
"""
with netCDF4.Dataset(gliderfile, 'r') as nc:
lon = nc.variables['longitude'][:]
lat = nc.variables['latitude'][:]
depth = nc.variables['depth'][:]
time = nc.variables['time'][:]
return lon, lat, depth, time
def change_wall_prop(ax, coordinates, depths, angles):
ax.w_xaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.w_yaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.w_zaxis.set_pane_color((1.0, 1.0, 1.0, 1.0))
ax.w_xaxis.gridlines.set_linestyles(':')
ax.w_yaxis.gridlines.set_linestyles(':')
ax.w_zaxis.gridlines.set_linestyles(':')
ax.view_init(angles[0], angles[1])
ax.set_xlim(coordinates[0], coordinates[1])
ax.set_ylim(coordinates[2], coordinates[3])
ax.set_zlim(depths[0], depths[1])
ax.set_zlabel('Depth (m)')
ax.set_zticks(np.arange(depths[0], depths[1] + 10, depths[2]))
ax.set_zticklabels(range(int(-depths[0]), -int(depths[1]) - 10, -int(depths[2])))
def read_l2_wind(windfile, coordinates):
"""
Read the L2 wind from a netCDF file
given a list of coordinates delimiting a bounding box
:param windfile: netCDF file containing the data
:param coordinates: coordinates delimiting a bounding box (lonmin, lonmax, latmin, latmax)
:return: lon, lat, uwind, vwind, windtime
"""
# Open NetCDF file
with netCDF4.Dataset(windfile) as nc:
lon = nc.variables['lon'][:]
lat = nc.variables['lat'][:]
windspeed = nc.variables['wind_speed'][:]
winddirection = nc.variables['wind_dir'][:]
windtime = nc.variables['time'][:]
# Change longitudes
lon[lon > 180] -= 360.0
# Reduce dimensions
lon = lon.flatten()
lat = lat.flatten()
windspeed = windspeed.flatten()
winddirection = winddirection.flatten()
# Select sub-region and check if data inside the area of interest
goodlon = np.nonzero(np.logical_and(lon <= coordinates[1],
lon >= coordinates[0]))
goodlon = goodlon[0]
if goodlon.size != 0:
lat = lat[goodlon]
lon = lon[goodlon]
windspeed = windspeed[goodlon]
winddirection = -winddirection[goodlon] + 90.
goodlat = np.nonzero(np.logical_and(lat <= coordinates[3],
lat >= coordinates[2]))
goodlat = goodlat[0]
if goodlat.size != 0:
lat = lat[goodlat]
lon = lon[goodlat]
windspeed = windspeed[goodlat]
winddirection = winddirection[goodlat]
uwind = windspeed * np.cos(np.deg2rad(winddirection))
vwind = windspeed * np.sin(np.deg2rad(winddirection))
uwind = np.ma.masked_where(uwind == uwind.fill_value, uwind)
vwind = np.ma.masked_where(vwind == vwind.fill_value, vwind)
uwind.data[uwind.data == uwind.data.min()] = 0
vwind.data[vwind.data == vwind.data.min()] = 0
else:
# print 'No value in selected region'
# print ' '
lon, lat, uwind, vwind = [], [], [], []
else:
print("No value in selected region")
lon, lat, uwind, vwind = [], [], [], []
return lon, lat, uwind, vwind, windtime
{
"datafiles":{
"adcp": "/home/ctroupin/Data/Alborex/ADCP/dep0023_socib-rv_scb-rdi001_L1_2014-05.nc",
"ctd": "/home/ctroupin/Data/Alborex/CTD/dep0007_socib-rv_scb-sbe9002_L1_2014-05-25.nc",
"ctdlegs": ["/home/ctroupin/Data/Alborex/CTD/ctd_positions_Leg1.txt",
"/home/ctroupin/Data/Alborex/CTD/ctd_positions_Leg2.txt"],
"gliders": ["/home/ctroupin/Data/Alborex/Gliders/dep0005_icoast00_ime-slcost000_L1_2014-05-25_data_dt.nc",
"/home/ctroupin/Data/Alborex/Gliders/dep0012_ideep00_ime-sldeep000_L1_2014-05-25_data_dt.nc"],
"profilers": ["/home/ctroupin/Data/Alborex/Profilers/dep0001_profiler-drifter-arvora3001_ogs-arvora3001_L1_2014-05-25.nc",
"/home/ctroupin/Data/Alborex/Profilers/dep0001_profiler-drifter-provbioll001_ogs-provbioll001_L1_2014-05-25.nc"],
"coast": "/home/ctroupin/Data/Alborex/Coastline/coastline_cartex_f3.txt",
"rv": "/home/ctroupin/Data/Alborex/RV/dep0015_socib-rv_scb-pos001_L1_2014-05-25.nc",
"altimetry": "/home/ctroupin/Data/Alborex/Altimetry/mean.nc",
"coast": "/home/ctroupin/Data/Alborex/Coastline/coastline_f.dat",
"thermosal": "/home/ctroupin/Data/Alborex/RV/dep0015_socib-rv_scb-tsl001_L1_2014-05-25_HR.nc"
},
"datadirs":{
"sst": "/home/ctroupin/Data/Alborex/SST/",
"drifters": "/home/ctroupin/Data/Alborex/Drifters",
"profilers": "/home/ctroupin/Data/Alborex/Profilers",
"adcp": "/home/ctroupin/Data/Alborex/ADCP"
},
"figdir": "/home/ctroupin/Publis/201703_AlborexData/figures",
"figdirleaflet": "/home/ctroupin/Publis/201703_AlborexData/leaflet/images/",
"domain":{
"coordinates1": [-6.75, 3.001, 34.75, 40.0],
"coordinates2": [-1.0, -0.25, 36.65, 37.25],
"coordinates3": [-6.0, -5.25, 35.8, 36.2],
"resolution1": [1.0, 1.0],
"resolution2": [0.25, 0.25]
}
}
This diff is collapsed.
source diff could not be displayed: it is too large. Options to address this: view the blob.
%% Cell type:code id: tags:
``` python
import os
import glob
import netCDF4
import matplotlib.pyplot as plt
```
%% Cell type:code id: tags:
``` python
datadir = "/home/ctroupin/Data/Alborex/Glider/"
datafilelist = sorted(glob.glob(os.path.join(datadir, "*nc")))
nfiles = len(datafilelist)
print(nfiles)
```
%% Output
3
%% Cell type:code id: tags:
``` python
for datafile in datafilelist:
with netCDF4.Dataset(datafile) as nc:
profiles = nc.variables["profile_index"][:]
print("Working on {}".format(os.path.basename(datafile)))
print("Number of profiles: {0}".format(profiles.max()))
print("Number of profiles: {0}".format(profiles.min()))
```
%% Output
Working on dep0005_icoast00_ime-slcost000_L1_2014-05-25_data_dt.nc
Number of profiles: 392.5
Number of profiles: 0.5
Working on dep0012_ideep00_ime-sldeep000_L1_2014-05-25_data_dt.nc
Number of profiles: 160.5
Number of profiles: 0.5
Working on dep0012_ideep00_ime-sldeep000_L2_2014-05-25_data_dt.nc
Number of profiles: 160.0
Number of profiles: 1.0
%% Cell type:code id: tags:
``` python
profiles.max()
```
%% Output
392.5
%% Cell type:code id: tags:
``` python
datadir2 = "/home/ctroupin/Data/Alborex/Profilers/"
datafilelist = sorted(glob.glob(os.path.join(datadir2, "*nc")))
nfiles = len(datafilelist)
print(nfiles)
```
%% Output
2
%% Cell type:code id: tags:
``` python
for datafile in datafilelist:
with netCDF4.Dataset(datafile) as nc:
time = nc.variables["time"][:]
print("Working on {}".format(os.path.basename(datafile)))
print("Number of profiles: {0}".format(len(time)))
```
%% Output
Working on dep0001_profiler-drifter-arvora3001_ogs-arvora3001_L1_2014-05-25.nc
Number of profiles: 12
Working on dep0001_profiler-drifter-provbioll001_ogs-provbioll001_L1_2014-05-25.nc
Number of profiles: 71
%% Cell type:code id: tags:
``` python
393+161
```
%% Output
554
%% Cell type:code id: tags:
``` python
```
This diff is collapsed.
This diff is collapsed.
%% Cell type:code id: tags:
``` python
import alborex_functions
import alborexdata
import netCDF4
import glob
import os
import json
import matplotlib.pyplot as plt
from mpl_toolkits.basemap import Basemap
import numpy as np
import datetime
import cmocean
from importlib import reload
```
%% Cell type:code id: tags:
``` python
reload(alborexdata)
```
%% Output
<module 'alborexdata' from '/home/ctroupin/Publis/201703_AlborexData/python/alborexdata.py'>
%% Cell type:code id: tags:
``` python
import warnings
import matplotlib.cbook
warnings.filterwarnings("ignore",category=matplotlib.cbook.mplDeprecation)
```
%% Cell type:markdown id: tags:
# Configuration
%% Cell type:code id: tags:
``` python
with open('alborexconfig.json') as json_data_file:
config = json.load(json_data_file)
```
%% Cell type:code id: tags:
``` python
makeFigs, makeFigsLeaflet = 1, 0
```
%% Cell type:markdown id: tags:
Create a logger
%% Cell type:code id: tags:
``` python
logger = alborexdata.configure_logging("./logs/alborexFigure2.log")
```
%% Cell type:markdown id: tags:
Domain
%% Cell type:code id: tags:
``` python
coordinates = config["domain"]["coordinates1"]
coordinates2 = config["domain"]["coordinates2"]
```
%% Cell type:markdown id: tags:
Create a list of netCDF files containing SST
%% Cell type:code id: tags:
``` python
coastfile = config["datafiles"]["coast"]
sstfilelist = sorted(glob.glob(os.path.join(config["datadirs"]["sst"], '*SST*.nc')))
nfiles = len(sstfilelist)
if nfiles == 0:
logger.warning("No SST files in directory {0}".format(sstdir))
else:
logger.info("Working on {0} SST files".format(nfiles))
```
%% Output
2018-08-28 10:30:04,652 - alborex_logger - INFO - Working on 2 SST files
%% Cell type:code id: tags:
``` python
cmap = plt.cm.RdYlBu_r
```
%% Cell type:markdown id: tags:
# Data reading and plotting
Make figure directory if necessary.
%% Cell type:code id: tags:
``` python
if os.path.isdir(config["figdir"]):
logger.debug("Figure directory {0} already exists".format(config["figdir"]))
else:
os.makedirs(config["figdir"])
logger.debug("Creating figure directory {0}".format(config["figdir"]))
if os.path.isdir(config["figdirleaflet"]):
logger.debug("Figure directory {0} already exists".format(config["figdirleaflet"]))
else:
os.makedirs(config["figdirleaflet"])
logger.debug("Creating figure directory {0}".format(config["figdirleaflet"]))
```
%% Output
2018-08-28 10:30:13,926 - alborex_logger - DEBUG - Figure directory /home/ctroupin/Publis/201703_AlborexData/figures already exists
2018-08-28 10:30:13,932 - alborex_logger - DEBUG - Figure directory /home/ctroupin/Publis/201703_AlborexData/leaflet/images/ already exists
%% Cell type:markdown id: tags:
## Coastline
%% Cell type:code id: tags:
``` python
loncoast, latcoast = alborexdata.read_lonlat_coast(config["datafiles"]["coast"])
```
%% Cell type:markdown id: tags:
Create the projection (only once)
%% Cell type:code id: tags:
``` python
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')
```
%% Cell type:markdown id: tags:
Projection for overlay in leaflet
%% Cell type:code id: tags:
``` python
m2 = Basemap(llcrnrlon=coordinates[0],
llcrnrlat=coordinates[2],
urcrnrlon=coordinates[1],
urcrnrlat=coordinates[3], resolution = 'l', epsg=3857)
```
%% Cell type:markdown id: tags:
## Front position
%% Cell type:code id: tags:
``` python
frontcoords = "../data/front_coordinates.dat"
f = alborexdata.Front()
f.get_from_file(frontcoords)
f.smooth()
```
%% Cell type:markdown id: tags:
## Two plots on the same figure
Required by the journal
%% Cell type:code id: tags:
``` python
# Rectangle for the region of interest
xrect = (coordinates2[0], coordinates2[1], coordinates2[1], coordinates2[0], coordinates2[0])
yrect = (coordinates2[2], coordinates2[2], coordinates2[3], coordinates2[3], coordinates2[2])
figname = "fig02.png"
fig = plt.figure(figsize=(10, 10))
for ii, sstfiles in enumerate(sstfilelist):
logger.info("Working on file: {0}".format(os.path.basename(sstfiles)))
# Read data from file
lon, lat, sst, sstqual, year, day, platform = alborex_functions.load_sst_l2(sstfiles)
# Create date from year and day
titledate = (datetime.datetime(int(year), 1, 1) + datetime.timedelta(int(day) - 1)).strftime('%Y-%m-%d')
figtitle = ' '.join(('MODIS', platform, '$-$', titledate))
# Make the SST when flag > 1
sst = np.ma.masked_where(sstqual > 1, sst)
ax = plt.subplot(2,1,ii+1)
m.ax = ax
pcm = m.pcolormesh(lon, lat, sst, latlon=True,
vmin=18., vmax=20.5, cmap=cmap)
# Add the coastline
for i in range(0, len(loncoast)):
m.plot(np.array(loncoast[i]), np.array(latcoast[i]),
color='k', linewidth=.25, latlon=True)
alborexdata.add_map_grid(m, coordinates, dlon=2., dlat=2.,
fontname='Times New Roman', fontsize=14,
linewidth=0.2, zorder=1, color=".6")
m.drawmapscale(-.75, 35.25, -1, 35.25, 75, fontsize=12)
m.plot(xrect, yrect, ":", color='k', latlon=True)
xtext1, ytext1 = m(-3.2, 37.)
xfig1, yfig1 = m(coordinates2[0], coordinates2[2])
# Plot front
m.plot(f.lon, f.lat, "k--", linewidth=2, latlon=True)
ax.set_title(figtitle, fontsize=20)
fig.subplots_adjust(right=0.95)
cbar_ax = fig.add_axes([0.85, 0.15, 0.035, 0.7])
cb = plt.colorbar(pcm, cax=cbar_ax, extend='both')
cb.set_label('$^{\circ}$C', rotation=0, ha='left', fontsize=16)
cb.ax.tick_params(labelsize=14)
# plt.show()
plt.savefig(os.path.join(config["figdir"], figname), dpi=300, bbox_inches='tight')
plt.close()
```
%% Output
2018-08-28 10:53:21,350 - alborex_logger - INFO - Working on file: A2014145125000.L2_LAC_SST.nc
2018-08-28 10:53:21,985 - alborex_logger - INFO - Working on file: A2014150020500.L2_LAC_SST.nc
%% Cell type:markdown id: tags:
## Loop on the files
%% Cell type:code id: tags:
``` python
for sstfiles in sstfilelist:
logger.info("Working on file: {0}".format(os.path.basename(sstfiles)))
# Read data from file
lon, lat, sst, sstqual, year, day, platform = alborex_functions.load_sst_l2(sstfiles)
# Create date from year and day
titledate = (datetime.datetime(int(year), 1, 1) + datetime.timedelta(int(day) - 1)).strftime('%Y-%m-%d')
figtitle = ' '.join(('MODIS', platform, '$-$', titledate))
# logger.debug(title)
# Make the SST when flag > 1
sst = np.ma.masked_where(sstqual > 1, sst)
# Create figure name (remove .nc extension and substitute . by _)
figname = ''.join(('_'.join(os.path.basename(sstfiles).split('.')[:-1]), '_cm.png'))
logger.info("Making figure {0}".format(figname))
# Rectangle for the region of interest
xrect = (coordinates2[0], coordinates2[1], coordinates2[1], coordinates2[0], coordinates2[0])
yrect = (coordinates2[2], coordinates2[2], coordinates2[3], coordinates2[3], coordinates2[2])
if makeFigs:
# Normal figures
fig = plt.figure(figsize=(10, 10))
ax = plt.subplot(111)
m.ax = ax
pcm = m.pcolormesh(lon, lat, sst, latlon=True,
vmin=18., vmax=20.5, cmap=cmocean.cm.thermal)
# Add the contours
for i in range(0, len(loncoast)):
m.plot(np.array(loncoast[i]), np.array(latcoast[i]),
color='k', linewidth=.25, latlon=True)
alborexdata.add_map_grid(m, coordinates, dlon=2., dlat=2.,
fontname='Times New Roman', fontsize=14,
linewidth=0.2, zorder=1, color=".6")
#m.fillcontinents(color='w', zorder=2)
#ax.set_xlim(coordinates[0], coordinates[1])
#ax.set_ylim(coordinates[2], coordinates[3])
cb = plt.colorbar(pcm, extend='both', shrink=0.6)
cb.set_label('$^{\circ}$C', rotation=0, ha='left', fontsize=16)
m.drawmapscale(-.75, 35.25, -1, 35.25, 75, fontsize=12)
m.plot(xrect, yrect, ":", color='.25', latlon=True)
xtext1, ytext1 = m(-3.2, 37.)
xfig1, yfig1 = m(coordinates2[0], coordinates2[2])
# Plot front
m.plot(f.lon, f.lat, "k--", linewidth=2, latlon=True)
"""
ax.annotate("Region of interest", xy=(xfig1, yfig1),
xytext=(xtext1, ytext1),
xycoords='data', textcoords='data', fontsize=16,
horizontalalignment="center"
)
"""
plt.title(figtitle, fontsize=20)
plt.savefig(os.path.join(config["figdir"], figname), dpi=300, bbox_inches='tight')
plt.close()
if makeFigsLeaflet:
# Figures without border and axes
llon, llat = m2(lon, lat)
fig = plt.figure(frameon=False)
ax = fig.add_axes([0, 0, 1, 1])
m2.pcolormesh(llon, llat, sst, vmin=17., vmax=20., cmap=cmap)
ax.axis('off')
#ax.set_xlim(lon.min(), lon.max())
#ax.set_ylim(lat.min(), lat.max())
f1 = plt.gca()
f1.axes.get_xaxis().set_ticks([])
f1.axes.get_yaxis().set_ticks([])
plt.savefig(os.path.join(config["figdirleaflet"], figname), transparent=True,
bbox_inches='tight', pad_inches=0)
plt.close()
```
%% Output
2018-07-30 10:07:59,791 - alborex_logger - INFO - Working on file: A2014145125000.L2_LAC_SST.nc
2018-07-30 10:08:00,293 - alborex_logger - INFO - Making figure A2014145125000_L2_LAC_SST_cm.png
2018-07-30 10:08:04,481 - alborex_logger - INFO - Working on file: A2014146023000.L2_LAC_SST4.nc
2018-07-30 10:08:04,928 - alborex_logger - INFO - Making figure A2014146023000_L2_LAC_SST4_cm.png
2018-07-30 10:08:08,735 - alborex_logger - INFO - Working on file: A2014147013500.L2_LAC_SST4.nc
2018-07-30 10:08:09,137 - alborex_logger - INFO - Making figure A2014147013500_L2_LAC_SST4_cm.png
2018-07-30 10:08:12,756 - alborex_logger - INFO - Working on file: A2014148132000.L2_LAC_SST.nc
2018-07-30 10:08:13,172 - alborex_logger - INFO - Making figure A2014148132000_L2_LAC_SST_cm.png
2018-07-30 10:08:18,754 - alborex_logger - INFO - Working on file: A2014149012000.L2_LAC_SST4.nc
2018-07-30 10:08:19,226 - alborex_logger - INFO - Making figure A2014149012000_L2_LAC_SST4_cm.png
2018-07-30 10:08:23,703 - alborex_logger - INFO - Working on file: A2014149122500.L2_LAC_SST.nc
2018-07-30 10:08:24,116 - alborex_logger - INFO - Making figure A2014149122500_L2_LAC_SST_cm.png
2018-07-30 10:08:27,975 - alborex_logger - INFO - Working on file: A2014150020500.L2_LAC_SST.nc
2018-07-30 10:08:28,396 - alborex_logger - INFO - Making figure A2014150020500_L2_LAC_SST_cm.png
2018-07-30 10:08:32,622 - alborex_logger - INFO - Working on file: A2014150020500.L2_LAC_SST4.nc
2018-07-30 10:08:32,906 - alborex_logger - INFO - Making figure A2014150020500_L2_LAC_SST4_cm.png
2018-07-30 10:08:36,894 - alborex_logger - INFO - Working on file: T2014145111000.L2_LAC_SST.nc
2018-07-30 10:08:37,360 - alborex_logger - INFO - Making figure T2014145111000_L2_LAC_SST_cm.png
2018-07-30 10:08:41,215 - alborex_logger - INFO - Working on file: T2014145221500.L2_LAC_SST4.nc
2018-07-30 10:08:41,734 - alborex_logger - INFO - Making figure T2014145221500_L2_LAC_SST4_cm.png
2018-07-30 10:08:45,844 - alborex_logger - INFO - Working on file: T2014146212000.L2_LAC_SST4.nc
2018-07-30 10:08:46,258 - alborex_logger - INFO - Making figure T2014146212000_L2_LAC_SST4_cm.png
2018-07-30 10:08:50,637 - alborex_logger - INFO - Working on file: T2014149215000.L2_LAC_SST.nc
2018-07-30 10:08:51,090 - alborex_logger - INFO - Making figure T2014149215000_L2_LAC_SST_cm.png
2018-07-30 10:08:55,240 - alborex_logger - INFO - Working on file: T2014149215000.L2_LAC_SST4.nc
2018-07-30 10:08:55,661 - alborex_logger - INFO - Making figure T2014149215000_L2_LAC_SST4_cm.png
2018-07-30 10:08:59,812 - alborex_logger - INFO - Working on file: T2014150113000.L2_LAC_SST.nc
2018-07-30 10:09:00,331 - alborex_logger - INFO - Making figure T2014150113000_L2_LAC_SST_cm.png
2018-07-30 10:09:04,373 - alborex_logger - INFO - Working on file: T2014150223500.L2_LAC_SST4.nc
2018-07-30 10:09:04,863 - alborex_logger - INFO - Making figure T2014150223500_L2_LAC_SST4_cm.png
%% Cell type:code id: tags:
``` python
```
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
This diff is collapsed.
0% Loading or .
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment