<jupyter_start><jupyter_text>Here is a quick example on how to create a `kmzfile` with image overlays using[matplotlib](http://matplotlib.org/) and[simplekml](https://code.google.com/p/simplekml/).The `make_kml()` function below is just a wrapper around `simplekml`.  It takes asarguments:- A list of matplotlib figures;- The figure(s) LatLon box (all overlays must have the **same bbox**);- An optional keyword for the colorbar for one of the overlays;- Some keyword options to tweak the kml/kmz file.All keywords (`kw`) can be modified during the `make_kml()` call.  You can readmore about them [here](http://simplekml.readthedocs.org/en/latest/).<jupyter_code>from simplekml import (Kml, OverlayXY, ScreenXY, Units, RotationXY,
                       AltitudeMode, Camera)


def make_kml(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat,
             figs, colorbar=None, **kw):
    """TODO: LatLon bbox, list of figs, optional colorbar figure,
    and several simplekml kw..."""

    kml = Kml()
    altitude = kw.pop('altitude', 2e7)
    roll = kw.pop('roll', 0)
    tilt = kw.pop('tilt', 0)
    altitudemode = kw.pop('altitudemode', AltitudeMode.relativetoground)
    camera = Camera(latitude=np.mean([urcrnrlat, llcrnrlat]),
                    longitude=np.mean([urcrnrlon, llcrnrlon]),
                    altitude=altitude, roll=roll, tilt=tilt,
                    altitudemode=altitudemode)

    kml.document.camera = camera
    draworder = 0
    for fig in figs:  # NOTE: Overlays are limited to the same bbox.
        draworder += 1
        ground = kml.newgroundoverlay(name='GroundOverlay')
        ground.draworder = draworder
        ground.visibility = kw.pop('visibility', 1)
        ground.name = kw.pop('name', 'overlay')
        ground.color = kw.pop('color', '9effffff')
        ground.atomauthor = kw.pop('author', 'ocefpaf')
        ground.latlonbox.rotation = kw.pop('rotation', 0)
        ground.description = kw.pop('description', 'Matplotlib figure')
        ground.gxaltitudemode = kw.pop('gxaltitudemode',
                                       'clampToSeaFloor')
        ground.icon.href = fig
        ground.latlonbox.east = llcrnrlon
        ground.latlonbox.south = llcrnrlat
        ground.latlonbox.north = urcrnrlat
        ground.latlonbox.west = urcrnrlon

    if colorbar:  # Options for colorbar are hard-coded (to avoid a big mess).
        screen = kml.newscreenoverlay(name='ScreenOverlay')
        screen.icon.href = colorbar
        screen.overlayxy = OverlayXY(x=0, y=0,
                                     xunits=Units.fraction,
                                     yunits=Units.fraction)
        screen.screenxy = ScreenXY(x=0.015, y=0.075,
                                   xunits=Units.fraction,
                                   yunits=Units.fraction)
        screen.rotationXY = RotationXY(x=0.5, y=0.5,
                                       xunits=Units.fraction,
                                       yunits=Units.fraction)
        screen.size.x = 0
        screen.size.y = 0
        screen.size.xunits = Units.fraction
        screen.size.yunits = Units.fraction
        screen.visibility = 1

    kmzfile = kw.pop('kmzfile', 'overlay.kmz')
    kml.savekmz(kmzfile)<jupyter_output><empty_output><jupyter_text>We will also need a `gearth_fig()` function.  It is actually is a wrapperaround matplotlib's `Figure` and `Axes` to create a figure that is"Google-Earth KML" friendly.  The ideas for this function are originally fromthe [octant](https://github.com/hetland/octant/blob/master/octant/sandbox/googleearth.py) library.<jupyter_code>import numpy as np
import matplotlib.pyplot as plt


def gearth_fig(llcrnrlon, llcrnrlat, urcrnrlon, urcrnrlat, pixels=1024):
    """Return a Matplotlib `fig` and `ax` handles for a Google-Earth Image."""
    aspect = np.cos(np.mean([llcrnrlat, urcrnrlat]) * np.pi/180.0)
    xsize = np.ptp([urcrnrlon, llcrnrlon]) * aspect
    ysize = np.ptp([urcrnrlat, llcrnrlat])
    aspect = ysize / xsize

    if aspect > 1.0:
        figsize = (10.0 / aspect, 10.0)
    else:
        figsize = (10.0, 10.0 * aspect)

    if False:
        plt.ioff()  # Make `True` to prevent the KML components from poping-up.
    fig = plt.figure(figsize=figsize,
                     frameon=False,
                     dpi=pixels//10)
    # KML friendly image.  If using basemap try: `fix_aspect=False`.
    ax = fig.add_axes([0, 0, 1, 1])
    ax.set_xlim(llcrnrlon, urcrnrlon)
    ax.set_ylim(llcrnrlat, urcrnrlat)
    return fig, ax
We will test it with the Mean Dynamic Topography from
[AVISO](http://www.aviso.altimetry.fr/en/).  Below are examples for two
overlays, the Mean Dynamic Topography and the velocity vectors derived from it.
import numpy.ma as ma
from netCDF4 import Dataset, date2index, num2date

nc = Dataset('F:/data/sst/jpl_mur/v4.1/2017/007/20170107090000-JPL-L4_GHRSST-SSTfnd-MUR-GLOB-v02.0-fv04.1.nc')

sst = nc.variables['analysed_sst'][:,11500:13000,5500:7000]
#u = nc.variables['Grid_0002'][:]
#v = nc.variables['Grid_0003'][:]

lat = nc.variables['lat'][11500:13000]
lon = nc.variables['lon'][5500:7000]
nc.close()
lat, lon = np.meshgrid(lat, lon)

#mdt = nc.variables['Grid_0001'][:]
sst = ma.masked_equal(sst, 9999.0)

#here i squeeze array and flip coordinates
print(sst.shape,lon.shape,lat.shape,type(sst))
sst2 = sst[0,:,:]
print(sst2.shape)
sst3 = ma.swapaxes(sst2,0,1)
print(sst3.shape)<jupyter_output><empty_output><jupyter_text>Overlay 1:<jupyter_code>from palettable import colorbrewer

pixels = 1024 * 10
cmap = colorbrewer.get_map('Spectral', 'diverging', 11, reverse=True).mpl_colormap

fig, ax = gearth_fig(llcrnrlon=lon.min(),
                     llcrnrlat=lat.min(),
                     urcrnrlon=lon.max(),
                     urcrnrlat=lat.max(),
                     pixels=pixels)
cs = ax.pcolormesh(lon, lat, sst3 - 273.15, cmap=cmap, vmin = 11, vmax = 20)
ax.set_axis_off()
fig.savefig('overlay1.png', transparent=False, format='png')
print('done')<jupyter_output><empty_output><jupyter_text>the colorbar for overlay 1,<jupyter_code>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('SST [C]', rotation=-90, color='k', labelpad=20)
fig.savefig('legend.png', transparent=False, format='png')  # Change transparent to True if your colorbar is not on space :)<jupyter_output><empty_output><jupyter_text>... and overlay 2<jupyter_code>make_kml(llcrnrlon=lon.min(), llcrnrlat=lat.min(),
         urcrnrlon=lon.max(), urcrnrlat=lat.max(),
         figs=['overlay1.png'], colorbar='legend.png',
         kmzfile='sst_mur.kmz', name='Sea Surface Temperature')
from datetime import datetime, timedelta
from bs4 import BeautifulSoup
import requests
def listFD(url, ext=''):
    page = requests.get(url).text
    #print(page)
    soup = BeautifulSoup(page, 'html.parser')
    return [url + node.get('href') for node in soup.find_all('a') if (node.get('href').endswith(ext) and node.get('href').startswith('2'))]

from os.path import exists

filename_pmw_sst = 'F:/data/cruise_data/saildrone/baja-2018/pmw_sst_data.npy'
filename_png = 'F:/data/cruise_data/saildrone/baja-2018/recent_pmw_sst.png'
filename_kmz = 'F:/data/cruise_data/saildrone/baja-2018/recent_pmw_sst.kmz'

inew_data=0 #initialize for new data
if exists(filename_pmw_sst):
    print('reading:',filename_pmw_sst)
    sst_new = np.load(filename_pmw_sst)
else:
    inew_data=1  
    
for incr_day in range(-1,1):
    d = datetime.today() + timedelta(days=incr_day)
    day_of_year = d.timetuple().tm_yday
    adir = 'https://opendap.jpl.nasa.gov/opendap/OceanTemperature/ghrsst/data/GDS2/L3U/AMSR2/REMSS/v8a/'
    dstr = str(d.year).zfill(4) + str(d.month).zfill(2) + str(d.day).zfill(2)
    file = adir +  str(d.year) + '/' + str(day_of_year).zfill(3) + '/' \
            + dstr + '000000-REMSS-L3U_GHRSST-SSTsubskin-AMSR2-f34_' \
            + dstr + 'v8_rt-v02.0-fv01.0.nc'       
    nc = Dataset(file)
    sst = nc.variables['sea_surface_temperature'][:]
    #sst = np.flip(sst, 2)
    cnt = ma.count(sst)
    lat = nc.variables['lat'][:]
    lat = np.flip(lat, 0)
    lon = nc.variables['lon'][:]
    nc.close()
    if inew_data==1:
        sst_new = ma.copy(sst)
        inew_data = 0
    if cnt<5:
        continue
    print(file)
    mask = sst_new < -10
    sst_new[mask] = sst[mask]
    
    adir = 'https://opendap.jpl.nasa.gov/opendap/OceanTemperature/ghrsst/data/GDS2/L3U/GMI/REMSS/v8.2a/'
    dstr = str(d.year).zfill(4) + str(d.month).zfill(2) + str(d.day).zfill(2)
    file = adir +  str(d.year) + '/' + str(day_of_year).zfill(3) + '/' \
            + dstr + '000000-REMSS-L3U_GHRSST-SSTsubskin-GMI-f35_' \
            + dstr + 'v8.2-v02.0-fv01.0.nc'       
    nc = Dataset(file)
    sst = nc.variables['sea_surface_temperature'][:]
    #sst = np.flip(sst, 2)
    cnt = ma.count(sst)
    lat = nc.variables['lat'][:]
    lat = np.flip(lat, 0)
    lon = nc.variables['lon'][:]
    nc.close()
    if inew_data==1:
        sst_new = ma.copy(sst)
        inew_data = 0
    if cnt<5:
        continue
    print(file)
    mask = sst_new < -10
    sst_new[mask] = sst[mask]
    
lat, lon = np.meshgrid(lat, lon)

mask = (sst_new < -10)
sst_new[mask]=-9999.
sst_new2 = sst_new[0,:,:]
sstx = ma.masked_values (sst_new2, -9999.)
#print(lon.shape,lat.shape,sstx.shape)
#sst3x = np.flip(sstx, 1)
sst4x = np.flip(sstx, 0)
sst5x = ma.swapaxes(sst4x,0,1)
#print(lon.shape,lat.shape,sst3x.shape)
#print(lon.shape,lat.shape,sst4x.shape)
#print(lon.shape,lat.shape,sst5x.shape)

pixels = 1024 * 10
cmap = colorbrewer.get_map('Spectral', 'diverging', 11, reverse=True).mpl_colormap

fig, ax = gearth_fig(llcrnrlon=lon.min(),
                                     llcrnrlat=lat.min(),
                                     urcrnrlon=lon.max(),
                                     urcrnrlat=lat.max(),
                                     pixels=pixels)
cs = ax.pcolormesh(lon, lat, sst5x - 273.15, cmap=cmap, vmin = 13, vmax = 19)
ax.set_axis_off()

fig.savefig(filename_png, transparent=False, format='png')
print('done')        
#print(lat[1,1],lat[1,-1],lon[1,1],lon[-1,1])
make_kml(llcrnrlon=lon[1,1], llcrnrlat=lat[1,1],
        urcrnrlon=lon[-1,1], urcrnrlat=lat[1,-1],
        figs= [filename_png], colorbar='legend.png',
        kmzfile=filename_kmz, name='AMSR2 Sea Surface Temperature')

sst_new.dump(filename_pmw_sst)

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('SST [C]', rotation=-90, color='k', labelpad=20)
fig.savefig('legend.png', transparent=False, format='png')  # Change transparent to True if your colorbar is not on space :)<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.14556609035136642, 'fraction_numerical': 0.03216211191671314, 'mean_word_length': 3.005584512285927, 'pattern_counts': {'":': 0, '<': 26, '<?xml version=': 0, '>': 22, 'https://': 4, 'lorem ipsum': 0, 'www.': 1, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 11, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '5', 'dir': 'jupyter-structured-clean-dedup', 'id': '482886', 'license': 'Apache-2.0', 'n_tokens_mistral': 4367, 'n_tokens_neox': 4095, 'n_words': 763, 'path': 'sat_collocation/pmw_google_earth_image.ipynb', 'repo_name': 'riddhimap/Saildrone', 'size': '10758'}