<jupyter_start><jupyter_text>Extract data within a shapefile using ERDDAP This tutorial will teach you how to extract and display SST values for a particular time period or average SST over the whole time-series available within a shapefile.The shapefile for the NOAA Marine National Monument and sanctuaries boundaries can be downloaded here: http://sanctuaries.noaa.gov/library/imast_gis.html. We are going to extract SST data for the Papahanaumokuakea Marine National Monument (PMNM) in Hawaii. However, because the Monument boundaries cross the dateline, the shapefile provided on the website is tricky to work with. We'll work with a cleaned up version, available here:https://oceanwatch.pifsc.noaa.gov/files/PMNM_bounds.csv  Load packages<jupyter_code>import pandas as pd
import numpy as np
import time
import urllib.request 
import xarray as xr 
import netCDF4 as nc
from matplotlib import pyplot as plt 
from matplotlib.colors import LinearSegmentedColormap
from shapely.geometry import Point, Polygon
import geopandas as gpd

np.warnings.filterwarnings('ignore')<jupyter_output><empty_output><jupyter_text>Load the Monument boundary<jupyter_code>df=pd.read_csv('PMNM_bounds.csv')<jupyter_output><empty_output><jupyter_text>Transform the boundary to a Polygon<jupyter_code>geometry = [Point(xy) for xy in zip(df.lon, df.lat)]
poly = Polygon([(p.x, p.y)  for p in  geometry])
poly<jupyter_output><empty_output><jupyter_text>Data extraction The example below extracts monthly 5km CoralTemp SST data within the monument boundary. - We are going to download data from ERDDAP for the smallest bounding box that contains our polygon<jupyter_code>xcoord1 = (np.min(df.lon), np.max(df.lon))
ycoord1 = (np.min(df.lat), np.max(df.lat))<jupyter_output><empty_output><jupyter_text>- let's select a date range:<jupyter_code>tcoord = ("2019-01-15", "2019-12-15")<jupyter_output><empty_output><jupyter_text>- and let's build our ERDDAP URL:<jupyter_code>url='https://oceanwatch.pifsc.noaa.gov/erddap/griddap/CRW_sst_v1_0_monthly.nc?analysed_sst[('+ tcoord[0] +'):1:('+ tcoord[1] +')][('+ str(ycoord1[0]) +'):1:('+ str(ycoord1[1]) +')][(' + str(xcoord1[0]) +'):1:('+ str(xcoord1[1]) +')]'
url<jupyter_output><empty_output><jupyter_text>- now we can download the data:<jupyter_code>urllib.request.urlretrieve(url, "sst.nc")<jupyter_output><empty_output><jupyter_text>- and load it as an xarray dataset:<jupyter_code>ds = xr.open_dataset('sst.nc',decode_cf=False)
ds.analysed_sst.shape<jupyter_output><empty_output><jupyter_text>We now have data for a box around our polygon, for 12 monthly time steps (= 1 year).  Masking the data outside the Monument boundary The .within() function from the shapelypackage checks if a point is within a polygon. We are using it to create a mask which will take the value 1 within the polygon boundary, and NaN outside.(This takes about 1min or less to run).<jupyter_code>start_time=time.time()
mask=np.empty((len(ds.latitude.values),len(ds.longitude.values)))
mask[:]=np.NaN

for i in range(len(ds.latitude.values)):
    for j in range(len(ds.longitude.values)):
        p=Point(ds.longitude.values[j],ds.latitude.values[i],)     
        if int(p.within(poly))==1:
            mask[i,j]=int(p.within(poly))
            
end_time=time.time()
print("total time = %g mins" % ((end_time-start_time)/60.))
plt.contourf(ds.longitude,ds.latitude,mask)<jupyter_output><empty_output><jupyter_text>We now multiply the SST data we downloaded by the mask values:<jupyter_code>SST=ds.analysed_sst*mask<jupyter_output><empty_output><jupyter_text>Plotting the data The extracted data contains several time steps (months) of sst data in the monument boundaries. Let's make a plot of the 4th time step for example.- setting up the colormap<jupyter_code>np.min(SST),np.max(SST)
levs = np.arange(16, 29, 0.05)
jet=["blue", "#007FFF", "cyan","#7FFF7F", "yellow", "#FF7F00", "red", "#7F0000"] 
cm = LinearSegmentedColormap.from_list('my_jet', jet, N=len(levs))<jupyter_output><empty_output><jupyter_text>- loading data to plot the coastline. The file can be downloaded [here](https://oceanwatch.pifsc.noaa.gov/files/gz_2010_us_outline_20m.json), and was provided by https://eric.clst.org/tech/usgeojson/.Download the file and save it to your computer.<jupyter_code># GeoJSON file downloaded from :
# https://eric.clst.org/tech/usgeojson/
country = gpd.read_file("gz_2010_us_outline_20m.json")
country.head()<jupyter_output><empty_output><jupyter_text>- plot:<jupyter_code>country.plot(figsize=(12,8),color='black')
plt.xlim(-183,-153)
plt.ylim(18,32)
cs=plt.contourf(ds.longitude-360,ds.latitude,SST[4,:,:],levs,cmap=cm)
cbar=plt.colorbar(fraction=0.022)
cbar.ax.tick_params(labelsize=12) 
cs.ax.tick_params(labelsize=12)
plt.title('SST - April 2019', fontsize=20)<jupyter_output><empty_output><jupyter_text>Example of loading and working which an ESRI shapefile instead of .csv file<jupyter_code>from shapely.geometry import Point, Polygon
import geopandas as gpd
import descartes
from matplotlib import pyplot as plt 
fp='C:\VM_Shared_Directory\OceanWatch\indicators\Monument\pmnm_Expanded_py_Albers\PMNM_py_files\hihwnms_py.shp'
data = gpd.read_file(fp)

data.plot(figsize=(14, 10))
plt.show()
data
data.geometry[0]
p1=Point(-122.25,36.5)  #27.425 190.025
int(p1.within(data.geometry[0]))<jupyter_output><empty_output>
{'fraction_non_alphanumeric': 0.12464801952318379, 'fraction_numerical': 0.025154871409799138, 'mean_word_length': 6.441340782122905, 'pattern_counts': {'":': 0, '<': 57, '<?xml version=': 0, '>': 57, 'https://': 5, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 7, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'chain_length': '14', 'dir': 'jupyter-structured-clean-dedup', 'id': '570464', 'license': 'MIT', 'n_tokens_mistral': 2041, 'n_tokens_neox': 1911, 'n_words': 460, 'path': 'OW_tutorial3.ipynb', 'repo_name': 'melhawaii/python-satellite-course', 'size': '5327'}