{"data":{"site":{"siteMetadata":{"testTemplate":"from wasabi import msg\nfrom black import format_str, FileMode\n\nfile_mode = FileMode()\n\ndef blacken(code):\n    try:\n        return format_str(code, mode=file_mode)\n    except:\n        return code\n\n__msg__ = msg\n__solution__ = blacken(\"\"\"${solution}\"\"\")\n\n${solution}\n\n${test}\n\ntry:\n    test()\nexcept AssertionError as e:\n    __msg__.fail(e)","juniper":{"repo":"amgeo-collaboration/earthcube_workshop_2022","branch":"main","kernelType":"python3","lang":"python","debug":false}}},"allCode":{"edges":[{"node":{"name":"exc_01_01","code":"------------\n"}},{"node":{"name":"exc_01_04","code":"# Create the dictionary\n\nmydict = {'archiveType':'coral',\n        'Publication':{'author':'J. Doe','title':'The most important record'}}\n\n#print the keys\n\nmydict.keys()\n"}},{"node":{"name":"exc_01_02","code":"mylist =[___]\n\nfor item in ___:\n    print(___)\n"}},{"node":{"name":"exc_01_03","code":"# Create the dictionary\n\ndataset1 = {\n            \"archiveType\":_____,\n            _____________,\n            }\n\nprint(dataset1)\n# return latitude into a variable\n\nlatitude = _________\n\nprint(latitude)\n"}},{"node":{"name":"exc_01_05","code":"import ________ as np\n\ntime = np._______(__,__,__)\ntime_index = _______\n"}},{"node":{"name":"exc_03_02","code":"import ______ as np\nfrom numpy.random import default_rng\n\nrng = default_rng(10) #seed to obtain same value for the distribution\n\n\ntime = np.arange(___,___,___)\nvalue = _________\n\nwhite_noise = rng.normal(___,____,______)\n\nvalue2 = _________\n\nprint(time)\nprint(value2)\n"}},{"node":{"name":"exc_03_01","code":"import ________ as np\n\ntime = np._______(__,__,__)\nvalue = ____\n\nprint(time)\nprint(value)\n"}},{"node":{"name":"exc_03_03","code":"import numpy as np\n\n\ntime = np.arange(__,___,___)\nvalue = ____________\n\nidx_min = np.where(time==200)[0][0]\nidx_max = ______(time==____)[0][0]\n\nvalue2 = value[______]\n\nprint(value2)\n"}},{"node":{"name":"exc_03_04","code":"import ______ as np\nfrom ______ import default_rng\n\nrng = default_rng(______) #seed to obtain same value for the distribution\n\n\ntime = np.arange(_,_,__)\ntime_ens=np.reshape(np.repeat(time,1000),[__,___])\nnoise = rng.normal(___,___, size=___)\n\ntime_ens = ______\n\ntime_mean = ______\n\nprint(np.shape(time))\nprint(np.shape(time_ens))\nprint(np.shape(time_mean))\n"}},{"node":{"name":"exc_04_01","code":"from AMGeO.api import AMGeOApi\n\napi = ___"}},{"node":{"name":"exc_04_02","code":"from AMGeO.api import AMGeOApi\n\napi = AMGeOApi()\n\ncontroller = api.___"}},{"node":{"name":"exc_04_03","code":"from AMGeO.api import AMGeOApi\nfrom datetime import date\n\napi = AMGeOApi()\n\ncontroller = api.get_controller()\n\nd = ___ \n\nh = ___\n\ncontroller.___"}},{"node":{"name":"exc_05_01","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward.\nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0)\nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\n\n\nfig, ax = plt.subplots()\nfig.patch.set_facecolor('white')\nax.____(___,___)\nax.___('NINO3 SST')\nax.___('NINO3 (K)')\nax.___('Year AD')\nplt.show()\n"}},{"node":{"name":"exc_04_04","code":"from AMGeO.api import AMGeOApi\nfrom datetime import date\n\napi = AMGeOApi()\n\ncontroller = api.get_controller()\n\nd = ___ \n\nh = ___\n\ncontroller.___"}},{"node":{"name":"exc_05_04","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nfig, ax = plt.subplots(figsize=(10, 6))\nax.plot(t,nino3,label='NINO3',color=____)\nax.set_ylabel('NINO3 SST (K)')\nax.set_title('NINO3 and All India Rainfall',fontweight='bold')\nax.legend()\n# twin object for two different y-axis on the sample plot\nax2=ax.twinx()\nax2.plot(t,air,label='AIR',color=____,____=____)\nax2.set_xlabel('Year AD') \nax2.legend()\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_05_02","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\n \n# plot\nfig, ax = plt.subplots()\nax.____(___,___)\nax.___('NINO3 SST')\nax.___('NINO3 (K)')\nax.___('Year AD')\n# remove upper and top spines\nax.spines[['top', 'right']].___(___)\n\nplt.show() # note: this last command is unnecessary in Jupyter notebooks, \n           # where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_05_03","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\n# plot\nfig, ax = plt.subplots(2,1,figsize=(10, 6),sharex = True)\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\ncsfont = {'fontname':_______}\nax[0].plot(t,nino3)\nax[0].set_ylabel('NINO3 SST (K)',**csfont)\nax[0].set_title('NINO3 and All India Rainfall',fontdict={____:__, ___ :___ })\nax[1].plot(t,air)\nax[1].set_ylabel('AIR (mm/month)',**csfont)\nax[1].set_xlabel(______)\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_05_05","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\ndef nino3_air_plot(plot_title):\n    fig, ax = plt.subplots()\n    fig.patch.set_facecolor('white')\n    ax.plot(t,nino3,label='NINO3',color='C0')\n    ax.set_ylabel('NINO3 SST (K)')\n    ax.set_title(plot_title)\n    ax.legend()\n    # twin object for two different y-axis on the sample plot\n    ax2=ax.twinx()\n    ax2.plot(t,air,label='AIR',color='C1')\n    ax2.set_xlabel('Year AD')\n    ax2.legend()\n\navailable = ['default'] + plt.style.available\nfor i, style in enumerate(available):\n    with plt.style.context(style):\n        _______(_____=____)\n    \nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_06_01","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=-75))\nax.set_title(\"A Geo-referenced subplot, Plate Carrée projection\");"}},{"node":{"name":"exc_05_06","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nwith plt.style.context('ggplot'):\n    fig, ax = plt.subplots(figsize=(8,6))\n    fig.patch.set_facecolor('white') # Gatsby shenanigan\n    ax.______(nino3,air,_____=____)\n    ax.set_xlabel('NINO3 SST (K)')\n    ax.set_ylabel('AIR (mm/month)')\n    ax.set_title('NINO3 vs All India Rainfall, monthly data',fontweight = 'bold')\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_06_02","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs\n\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=-75))\nax.set_title(\"A Geo-referenced subplot, Plate Carrée projection\");\nax.coastlines()"}},{"node":{"name":"exc_05_08","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf  = pd.read_csv(url,skiprows=0) \nt   = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nfig = plt.figure(figsize=(10,8))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.axes(projection = ____ )  # syntax for 3-D projection \np = ax.scatter(___, ___ , ___, c=_, cmap='viridis');\nfig.colorbar(p,label='Year', ax=ax) # include colorbar\nax.set_xlabel('NINO3 (K)'); ax.set_ylabel('Year'); ax.set_zlabel('AIR (mm/month)');\nax.set_title('3D representation', fontweight = 'bold')\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_06_03","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=-75))\nax.set_title(\"A Geo-referenced subplot, Plate Carrée projection\");\nax.coastlines()\nax.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor='black')\nax.add_feature(cfeature.STATES, linewidth=0.3, edgecolor='brown')"}},{"node":{"name":"exc_05_07","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nwith plt.style.context(_____):\n    fig = plt.figure(figsize=(12,8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    plt._____(nino3, air, c=t, _____ = _____ , ___ =___)\n    plt.xlabel('NINO3 SST (K)')\n    plt.ylabel('AIR (mm/month)')\n    plt.colorbar(label='year')\n    \nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"exc_06_05","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(10, 5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = fig.add_subplot(1, 1, 1, projection=ccrs.PlateCarree())\nax.stock_img()\nax.coastlines()\nax.tissot(facecolor='orange', alpha=0.8)\nax.set_title(\"Plate Carrée projection with Tissot's indicatrix\");"}},{"node":{"name":"exc_06_04","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=-75))\nax.set_title(\"A Geo-referenced subplot, Plate Carrée projection\");\nax.coastlines()\nax.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor='black')\nax.add_feature(cfeature.STATES, linewidth=0.3, edgecolor='brown')\nax.stock_img()"}},{"node":{"name":"exc_06_06","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nprojMoll = ccrs.Mollweide(central_longitude=0)\nax = plt.subplot(1, 1, 1, projection=projMoll)\nax.set_title(\"Mollweide Projection\")\nax.coastlines()\nax.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor='blue')\nax.stock_img()"}},{"node":{"name":"exc_06_07","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nproj = ccrs.__________\nax = plt.subplot(1, 1, 1, projection=proj)\nax.coastlines()\nax.stock_img()\nax.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor='blue');\nax.tissot(facecolor='orange', alpha=0.8)\nax.set_title(\"____________ Projection with Tissot's indicatrix\");"}},{"node":{"name":"exc_06_08","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nprojPC = ccrs.PlateCarree()\nlonW = -140; lonE = -40\nlatS = 15; latN = 65\ncLat = (latN + latS) / 2\ncLon = (lonW + lonE) / 2\nres = '110m'\n\nprojStr = ccrs.Stereographic(central_longitude=cLon, central_latitude=cLat)\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.subplot(1, 1, 1, projection=projStr)\nax.set_title('Stereographic')\ngl = ax.gridlines(\n    draw_labels=True, linewidth=2, color='gray', alpha=0.5, linestyle='--'\n)\nax.set_extent([lonW, lonE, latS, latN], crs=projPC)\nax.coastlines(resolution=res, color='black')\nax.add_feature(cfeature.STATES, linewidth=0.3, edgecolor='brown')\nax.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor='blue');"}},{"node":{"name":"exc_06_10","code":"from cartopy.io import shapereader\nimport geopandas\nimport matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef map_ukraine(highlight_color='orange'):\n    '''\n        This function plots a regional map of Ukraine with administrative boundaries\n        \n        Inputs:\n        -------\n        highlight_color: the color in which the territory is highlighted\n        \n        Outputs:\n        -------\n        - fig: the resuling Matplotlib Figure object\n        - ax: the resuling Matplotlib Axes object\n    '''\n    \n    latN = 54; latS = 43\n    lonW = 23; lonE = 41\n    cLat = (latN + latS) / 2\n    cLon = (lonW + lonE) / 2\n\n    projLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\n    projPC = ccrs.PlateCarree() # we keep this for transforms\n\n    # get country borders\n    resolution = '10m'\n    category = 'cultural'\n    name = 'admin_0_countries'\n    shpfilename = shapereader.natural_earth(resolution, category, name)\n    # read the shapefile using geopandas\n    df = geopandas.read_file(shpfilename)\n\n    # put into polygon:\n    poly = df.loc[df['ADMIN'] == 'Ukraine']['geometry'].values[0]\n    # plot: \n    fig = plt.figure(figsize=(11.5, 8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    ax = plt.subplot(1, 1, 1, projection=projLccUk)\n    ax.set_extent([lonW, lonE, latS, latN], crs=projPC)\n    ax.set_facecolor(cfeature.COLORS['water'])\n    ax.add_feature(cfeature.LAND)\n    ax.add_feature(cfeature.COASTLINE)\n    ax.add_feature(cfeature.BORDERS, linestyle='--')\n    ax.add_feature(cfeature.LAKES, alpha=0.5)\n    ax.add_feature(cfeature.RIVERS)\n    ax.set_title('Ukraine and neighbors');\n    ax.add_geometries(poly, crs=projPC, facecolor=highlight_color, edgecolor='0.5')\n\n    return fig, ax\n\nmap_ukraine()\nplt.show()"}},{"node":{"name":"exc_06_11","code":"from cartopy.io import shapereader\nimport geopandas\nimport matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef map_ukraine(highlight_color='orange'):\n    '''\n        This function plots a regional map of Ukraine with administrative boundaries\n        \n        Inputs:\n        -------\n        highlight_color: the color in which the territory is highlighted\n        \n        Outputs:\n        -------\n        - fig: the resuling Matplotlib Figure object\n        - ax: the resuling Matplotlib Axes object\n    '''\n    \n    latN = 54; latS = 43\n    lonW = 23; lonE = 41\n    cLat = (latN + latS) / 2\n    cLon = (lonW + lonE) / 2\n\n    projLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\n    projPC = ccrs.PlateCarree() # we keep this for transforms\n\n    # get country borders\n    resolution = '10m'\n    category = 'cultural'\n    name = 'admin_0_countries'\n    shpfilename = shapereader.natural_earth(resolution, category, name)\n    # read the shapefile using geopandas\n    df = geopandas.read_file(shpfilename)\n\n    # put into polygon:\n    poly = df.loc[df['ADMIN'] == 'Ukraine']['geometry'].values[0]\n    # plot: \n    fig = plt.figure(figsize=(11.5, 8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    ax = plt.subplot(1, 1, 1, projection=projLccUk)\n    ax.set_extent([lonW, lonE, latS, latN], crs=projPC)\n    ax.set_facecolor(cfeature.COLORS['water'])\n    ax.add_feature(cfeature.LAND)\n    ax.add_feature(cfeature.COASTLINE)\n    ax.add_feature(cfeature.BORDERS, linestyle='--')\n    ax.add_feature(cfeature.LAKES, alpha=0.5)\n    ax.add_feature(cfeature.RIVERS)\n    ax.set_title('Ukraine and neighbors');\n    ax.add_geometries(poly, crs=projPC, facecolor=highlight_color, edgecolor='0.5')\n    return fig, ax\n\nmap_ukraine(______)\nplt.show()"}},{"node":{"name":"exc_06_12","code":"from cartopy.io import shapereader\nimport geopandas\nimport matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef map_ukraine(highlight_color='orange'):\n    '''\n        This function plots a regional map of Ukraine with administrative boundaries\n        \n        Inputs:\n        -------\n        highlight_color: the color in which the territory is highlighted\n        \n        Outputs:\n        -------\n        - fig: the resuling Matplotlib Figure object\n        - ax: the resuling Matplotlib Axes object\n    '''\n    \n    latN = 54; latS = 43\n    lonW = 23; lonE = 41\n    cLat = (latN + latS) / 2\n    cLon = (lonW + lonE) / 2\n\n    projLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\n    projPC = ccrs.PlateCarree() # we keep this for transforms\n\n    # get country borders\n    resolution = '10m'\n    category = 'cultural'\n    name = 'admin_0_countries'\n    shpfilename = shapereader.natural_earth(resolution, category, name)\n    # read the shapefile using geopandas\n    df = geopandas.read_file(shpfilename)\n\n    # put into polygon:\n    poly = df.loc[df['ADMIN'] == 'Ukraine']['geometry'].values[0]\n    # plot: \n    fig = plt.figure(figsize=(11.5, 8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    ax = plt.subplot(1, 1, 1, projection=projLccUk)\n    ax.set_extent([lonW, lonE, latS, latN], crs=projPC)\n    ax.set_facecolor(cfeature.COLORS['water'])\n    ax.add_feature(cfeature.LAND)\n    ax.add_feature(cfeature.COASTLINE)\n    ax.add_feature(cfeature.BORDERS, linestyle='--')\n    ax.add_feature(cfeature.LAKES, alpha=0.5)\n    ax.add_feature(cfeature.RIVERS)\n    ax.set_title('Ukraine and neighbors');\n    ax.add_geometries(poly, crs=projPC, facecolor=highlight_color, edgecolor='0.5')\n    return fig, ax\n\nfig, ax = map_ukraine()\nlatK, lonK = 50.45, 30.523333 \n# add a dot and a label for the city of Kyiv\nax.plot(lonK,latK,color=\"k\", marker=\"o\", markersize= 10,transform=ccrs.PlateCarree())\nax.text(lonK+0.5,latK+0.5,\"Kyiv\", transform=ccrs.PlateCarree(),\n        va='top', ha='right', fontweight='bold') # ofset the text from the city itself, for clarity\nplt.show()"}},{"node":{"name":"exc_06_13","code":"from cartopy.io import shapereader\nimport geopandas\nimport matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef map_ukraine(highlight_color='orange'):\n    '''\n        This function plots a regional map of Ukraine with administrative boundaries\n        \n        Inputs:\n        -------\n        highlight_color: the color in which the territory is highlighted\n        \n        Outputs:\n        -------\n        - fig: the resuling Matplotlib Figure object\n        - ax: the resuling Matplotlib Axes object\n    '''\n    \n    latN = 54; latS = 43\n    lonW = 23; lonE = 41\n    cLat = (latN + latS) / 2\n    cLon = (lonW + lonE) / 2\n\n    projLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\n    projPC = ccrs.PlateCarree() # we keep this for transforms\n\n    # get country borders\n    resolution = '10m'\n    category = 'cultural'\n    name = 'admin_0_countries'\n    shpfilename = shapereader.natural_earth(resolution, category, name)\n    # read the shapefile using geopandas\n    df = geopandas.read_file(shpfilename)\n\n    # put into polygon:\n    poly = df.loc[df['ADMIN'] == 'Ukraine']['geometry'].values[0]\n    # plot: \n    fig = plt.figure(figsize=(11.5, 8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    ax = plt.subplot(1, 1, 1, projection=projLccUk)\n    ax.set_extent([lonW, lonE, latS, latN], crs=projPC)\n    ax.set_facecolor(cfeature.COLORS['water'])\n    ax.add_feature(cfeature.LAND)\n    ax.add_feature(cfeature.COASTLINE)\n    ax.add_feature(cfeature.BORDERS, linestyle='--')\n    ax.add_feature(cfeature.LAKES, alpha=0.5)\n    ax.add_feature(cfeature.RIVERS)\n    ax.set_title('Ukraine and neighbors');\n    ax.add_geometries(poly, crs=projPC, facecolor=highlight_color, edgecolor='0.5')\n    return fig, ax\n\nfig, ax = map_ukraine()\nlatK, lonK = 50.45, 30.523333 # coordinates obtained from https://geohack.toolforge.org/geohack.php?pagename=Kyiv&params=50_27_00_N_30_31_24_E_region:UA_type:city\n# add a dot and a label for the city of Kyiv\nax.plot(lonK,latK,color=\"k\", marker=\"o\", markersize= 10,transform=ccrs.PlateCarree())\nax.text(lonK+0.5,latK+0.5,\"Kyiv\", transform=ccrs.PlateCarree(),\n        va='top', ha='right', fontweight='bold')\n# same for Mariupol\nlonM = _______ ; latM = _______\nax.plot(__,__,color=\"k\", marker=\"o\", markersize= 10,transform=ccrs.PlateCarree())\nax.text(__+0.5,__+0.5,\"Mariupol\", transform=ccrs.PlateCarree(),\n        va='top', ha='right', fontweight='bold')"}},{"node":{"name":"exc_06_14","code":"import matplotlib.pyplot as plt\nimport numpy as np\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nlon, lat = np.mgrid[-180:181, -90:91]\ndata = np.sin(3 * np.deg2rad(lon)) + np.cos(4 * np.deg2rad(lat))\nplt.contourf(lon, lat, data)\nplt.colorbar();\n\n"}},{"node":{"name":"exc_06_09","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nlatN = 54; latS = 43\nlonW = 23; lonE = 41\ncLat = (latN + latS) / 2\ncLon = (lonW + lonE) / 2\nprojLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\nprojPC = ccrs.PlateCarree() # we keep this for transforms\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.subplot(1, 1, 1, projection=projLccUk)\nax.set_extent([lonW, lonE, latS, latN], crs=projPC)\nax.set_facecolor(cfeature.COLORS['water'])\nax.add_feature(cfeature.LAND)\nax.add_feature(cfeature.COASTLINE)\nax.add_feature(cfeature.BORDERS, linestyle='--')\nax.add_feature(cfeature.LAKES, alpha=0.5)\nax.add_feature(cfeature.RIVERS)\nax.set_title('Ukraine and neighbors');"}},{"node":{"name":"exc_06_16","code":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport cartopy.crs as ccrs\nfrom cartopy.io import shapereader\nimport geopandas\nplt.style.use('seaborn-whitegrid')\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# import data \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0)\nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall\n\nfig = plt.figure(figsize = (12,12))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n# first plot the timeseries as in Module 5\na1 = plt.subplot(2, 1, 1)\na1.plot(t,nino3,label='NINO3',color='red')\na1.set_ylabel('SST (K)')\na1.set_title('Temporal evolution',fontweight='bold')\na1.legend()\n# twin object for two different y-axis on the sample plot\na1b=a1.twinx()\na1b.plot(t,air,label='AIR',color='blue')\na1b.set_ylabel('Rainfall (mm/month)')\na1b.set_xlabel('Year AD') \na1b.legend()\n# then add the map:\nproj = ccrs.Robinson(central_longitude=180, globe=None)\na0 = plt.subplot(2, 1, 2, projection=proj)\na0.set_extent([60, 280, -10, 40], crs=ccrs.PlateCarree())\na0.coastlines()\na0.stock_img()\ngl = a0.gridlines(\n    draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--'\n)\n# add a box for NINO3\na0.add_patch(mpatches.Rectangle(xy=[210, -5], width=60, height=10,\n                                    facecolor='C0', transform=ccrs.PlateCarree()))\na0.text(230,0,\"NINO3\",transform=ccrs.PlateCarree(),fontweight='bold')\n\n# highlight India the same color as the line on the plot (2nd color in the default cycler)\n\n# extract country shape from the NaturalEarth database using geopandas\nresolution = '10m'; category = 'cultural'; name = 'admin_0_countries'\nshpfilename = shapereader.natural_earth(resolution, category, name)\ndf = geopandas.read_file(shpfilename)\n# put into polygon:\npoly = df.loc[df['ADMIN'] == 'India']['geometry'].values[0]\na0.add_geometries(poly, crs=ccrs.PlateCarree(), facecolor='C1')\na0.text(75,22,\"India\",transform=ccrs.PlateCarree(),fontweight='bold')\na0.set_title('Spatial relationships',fontweight='bold')\n\n\n\n\n"}},{"node":{"name":"exc_06_15","code":"import matplotlib.pyplot as plt\nimport numpy as np\nfrom cartopy import crs as ccrs\n\n\nlon, lat = np.mgrid[-180:181, -90:91]\ndata = np.sin(3 * np.deg2rad(lon)) + np.cos(4 * np.deg2rad(lat))\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n\nax = plt.subplot(1, 1, 1, projection=ccrs.Mollweide(central_longitude=0))\nax.coastlines()\ndataplot = ax.contourf(lon, lat, data, transform=ccrs.PlateCarree())\nplt.colorbar(dataplot, orientation='horizontal');"}},{"node":{"name":"exc_06_17","code":"\n# see example above\n\n\n\n"}},{"node":{"name":"exc_08_01","code":"startDate = '2018-05-29T00:00:00Z'\nendDate   = '2018-05-31T00:00:00Z'\n\npolygon = '[[61.096076,25.106205],[51.933279,10.054482],[60.37706,9.236052],[68.777189,8.221804],[77.130969,7.034482],[71.404221,19.816425],[61.096076,25.106205]]'\nprint(startDate, endDate, polygon)\n"}},{"node":{"name":"exc_08_02","code":"import requests\nimport pandas as pd\nimport numpy as np\nfrom utilities import check_error_message\n\n# prefix to use with all API queries\nURL_PREFIX = 'https://argovis-api.colorado.edu'\n# users that have an API key would use it in their code (no need to do so here)\nAPI_KEY   = ''\n\nstartDate = '2018-05-29T00:00:00Z'\nendDate   = '2018-05-31T00:00:00Z'\n\npolygon = '[[61.096076,25.106205],[51.933279,10.054482],[60.37706,9.236052],[68.777189,8.221804],[77.130969,7.034482],[71.404221,19.816425],[61.096076,25.106205]]'\n\n# define url for the API query of profile locations in a region (polygon) and time range of interest\nurl = URL_PREFIX + '/profiles?' + \\\n      '&startDate=' + startDate + \\\n      '&endDate=' + endDate + \\\n      '&polygon=' + polygon + \\\n      '&source=argo_core'\n\n# make the request\nd   = requests.get(url,headers={\"x-argokey\": API_KEY}).json()\n# check what the API request returned\nans = check_error_message(ans=d,writeFlag=True)\n# if there are data, create a panda dataframe from the returned list of dictionaries\n\nif np.isnan(ans):\n    df = pd.DataFrame(d)\n\n# Printing column names as the Data Frame is too wide\ndf.columns"}},{"node":{"name":"exc_08_05","code":"import requests\nimport pandas as pd\nimport numpy as np\nfrom utilities import check_error_message\n\n#data visualization\nimport matplotlib.pylab as plt\nfrom matplotlib import ticker\n\n#used for map projections\nimport cartopy.crs as ccrs\nimport cartopy.feature as cft\nfrom cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\n\n\n# prefix to use with all API queries\nURL_PREFIX = 'https://argovis-api.colorado.edu'\n# users that have an API key would use it in their code (no need to do so here)\nAPI_KEY   = ''\n\nstartDate = '2018-05-29T00:00:00Z'\nendDate   = '2018-05-31T00:00:00Z'\n\npolygon = '[[61.096076,25.106205],[51.933279,10.054482],[60.37706,9.236052],[68.777189,8.221804],[77.130969,7.034482],[71.404221,19.816425],[61.096076,25.106205]]'\n\n# define url for the API query of profile locations in a region (polygon) and time range of interest\nurl = URL_PREFIX + '/profiles?' + \\\n      '&startDate=' + startDate + \\\n      '&endDate=' + endDate + \\\n      '&polygon=' + polygon + \\\n      '&source=argo_core'\n\n# make the request\nd   = requests.get(url,headers={\"x-argokey\": API_KEY}).json()\n# check what the API request returned\nans = check_error_message(ans=d,writeFlag=True)\n# if there are data, create a panda dataframe from the returned list of dictionaries\n\nif np.isnan(ans):\n    df = pd.DataFrame(d)\n\n# Printing column names as the Data Frame is too wide\n# let's store longitude and latitude for the profiles in the dataframe\nlon = [x['coordinates'][0] for x in df['geolocation']]\nlat = [x['coordinates'][1] for x in df['geolocation']]\n\n# Plot Code\n# if there are data, plot profile locations on a map\nif np.isnan(ans):\n    #### set up the map first\n    # this declares a recentered projection for Pacific areas\n    usemap_proj = ccrs.PlateCarree(central_longitude=50)\n    usemap_proj._threshold /= 20.  # to make greatcircle smooth\n\n    ax = plt.axes(projection=usemap_proj)\n    # set appropriate extents: (lon_min, lon_max, lat_min, lat_max)\n    ax.set_extent([min(lon)-10,max(lon)+10,min(lat)-5,max(lat)+5], crs=ccrs.PlateCarree())\n\n    gl = ax.gridlines(draw_labels=True,color='black')\n    gl.xlabels_top = False\n    gl.ylabels_right = False\n    gl.xformatter = LONGITUDE_FORMATTER\n    gl.yformatter = LATITUDE_FORMATTER\n    gl.xlocator = ticker.FixedLocator(np.arange(-180,180,5))\n    gl.ylocator = ticker.FixedLocator(np.arange(-90,90,5))\n\n    gl.xlabel_style = {'size': 16}\n    gl.ylabel_style = {'size': 16}\n\n    ax.coastlines()\n    ax.add_feature(cft.LAND)#, color='lightgray'\n    ax.add_feature(cft.OCEAN)\n    ax.add_feature(cft.COASTLINE)\n    ax.add_feature(cft.BORDERS, linestyle=':')\n\n    geodetic = ccrs.Geodetic()\n    #### plot the profile locations\n    plt.plot(lon,lat,marker='o',markersize=10,color='k',linestyle='none',transform=ccrs.PlateCarree())"}},{"node":{"name":"solution_01_01","code":"print(\"I love doing paleoclimate research with Python\")\n"}},{"node":{"name":"exc_08_04","code":"import requests\nimport pandas as pd\nimport numpy as np\nfrom utilities import check_error_message\n\n# prefix to use with all API queries\nURL_PREFIX = 'https://argovis-api.colorado.edu'\n# users that have an API key would use it in their code (no need to do so here)\nAPI_KEY   = ''\n\nstartDate = '2018-05-29T00:00:00Z'\nendDate   = '2018-05-31T00:00:00Z'\n\npolygon = '[[61.096076,25.106205],[51.933279,10.054482],[60.37706,9.236052],[68.777189,8.221804],[77.130969,7.034482],[71.404221,19.816425],[61.096076,25.106205]]'\n\n# define url for the API query of profile locations in a region (polygon) and time range of interest\nurl = URL_PREFIX + '/profiles?' + \\\n      '&startDate=' + startDate + \\\n      '&endDate=' + endDate + \\\n      '&polygon=' + polygon + \\\n      '&source=argo_core'\n\n# make the request\nd   = requests.get(url,headers={\"x-argokey\": API_KEY}).json()\n# check what the API request returned\nans = check_error_message(ans=d,writeFlag=True)\n# if there are data, create a panda dataframe from the returned list of dictionaries\n\nif np.isnan(ans):\n    df = pd.DataFrame(d)\n\n# Printing column names as the Data Frame is too wide\n# let's store longitude and latitude for the profiles in the dataframe\nlon = [x['coordinates'][0] for x in df['geolocation']]\nlat = [x['coordinates'][1] for x in df['geolocation']]\n\n\nprint(\"lat\", lat)\nprint(\"long\", lon)"}},{"node":{"name":"exc_08_03","code":"import requests\nimport pandas as pd\nimport numpy as np\nfrom utilities import check_error_message\n\n# prefix to use with all API queries\nURL_PREFIX = 'https://argovis-api.colorado.edu'\n# users that have an API key would use it in their code (no need to do so here)\nAPI_KEY   = ''\n\nstartDate = '2018-05-29T00:00:00Z'\nendDate   = '2018-05-31T00:00:00Z'\n\npolygon = '[[61.096076,25.106205],[51.933279,10.054482],[60.37706,9.236052],[68.777189,8.221804],[77.130969,7.034482],[71.404221,19.816425],[61.096076,25.106205]]'\n\n# define url for the API query of profile locations in a region (polygon) and time range of interest\nurl = URL_PREFIX + '/profiles?' + \\\n      '&startDate=' + startDate + \\\n      '&endDate=' + endDate + \\\n      '&polygon=' + polygon + \\\n      '&source=argo_core'\n\n# make the request\nd   = requests.get(url,headers={\"x-argokey\": API_KEY}).json()\n# check what the API request returned\nans = check_error_message(ans=d,writeFlag=True)\n# if there are data, create a panda dataframe from the returned list of dictionaries\n\nif np.isnan(ans):\n    df = pd.DataFrame(d)\n\n# Explore different components of the dataset\n\nprint(df.info())\n\ndf['data_keys_mode']"}},{"node":{"name":"solution_01_02","code":"mylist = ['Marine Sediment', 'Coral', 'Ice', 'Wood']\n\nfor item in mylist:\n    print(\"I study paleoclimate using \"+item)\n"}},{"node":{"name":"solution_01_03 copy","code":"import json\n\n# This code will run relative to the root of the repo, so we can load files\nwith open(\"exercises/bookquotes.json\") as f:\n    DATA = json.loads(f.read())\n\n# Print the first record in the DATA\nprint(DATA[0])\n\n# Assign the length of DATA to some_var\nsome_var = len(DATA)\n"}},{"node":{"name":"solution_01_03","code":"#Create the dictionary\n\ndataset1 = {\n            \"archiveType\":\"marinesediment\",\n            \"geo\":{\"lat\":-5,\"lon\":140},\n            \"data\":{\"values\":[1,2,3],\"units\":\"N/A\"}\n            }\n\nprint(dataset1)\n# return latitude into a variable\n\nlatitude = dataset1[\"geo\"][\"lat\"]\n\nprint(latitude)\n"}},{"node":{"name":"solution_01_05","code":"import numpy as np\n\ntime = np.linspace(0,1000,1001)\ntime_index = time[20]\n"}},{"node":{"name":"solution_03_01","code":"import numpy as np\n\ntime = np.arange(1,2001,1)\nvalue = np.sin(2*np.pi*1/20*time)\n\nprint(time)\nprint(value)\n"}},{"node":{"name":"solution_03_02","code":"import numpy as np\nfrom numpy.random import default_rng\n\nrng = default_rng(10) #seed to obtain same value for the distribution\n\n\ntime = np.arange(1,2001,1)\nvalue = np.sin(2*np.pi*1/20*time)\n\nwhite_noise = rng.normal(0, np.sqrt(np.var(value)/2), size=np.size(value))\n\nvalue2 = value+white_noise\n\nprint(time)\nprint(value2)\n"}},{"node":{"name":"solution_03_03","code":"import numpy as np\n\n\ntime = np.arange(1,2001,1)\nvalue = np.sin(2*np.pi*1/20*time)\n\nidx_min = np.where(time==200)[0][0]\nidx_max = np.where(time==400)[0][0]\n\nvalue2 = value[idx_min:idx_max+1]\n\nprint(value2)\n"}},{"node":{"name":"solution_03_04","code":"import numpy as np\nfrom numpy.random import default_rng\n\nrng = default_rng(30) #seed to obtain same value for the distribution\n\n\ntime = np.arange(0,10001,100)\ntime_ens=np.reshape(np.repeat(time,1000),[np.shape(time)[0],1000])\nnoise = rng.normal(0, 200, size=np.shape(time_ens))\n\ntime_ens = time_ens+noise\n\ntime_mean = np.mean(time_ens,axis=1)\n\nprint(np.shape(time))\nprint(np.shape(time_ens))\nprint(np.shape(time_mean))\n"}},{"node":{"name":"solution_04_02","code":"from AMGeO.api import AMGeOApi\n\napi = AMGeOApi()\n\ncontroller = api.get_controller()"}},{"node":{"name":"solution_04_03","code":"from AMGeO.api import AMGeOApi\nfrom datetime import date\n\napi = AMGeOApi()\n\ncontroller = api.get_controller()\n\nd = date(2016, 1, 2)\n\nh = 'S'\n\ncontroller.browse(d, h)"}},{"node":{"name":"solution_04_04","code":"from AMGeO.api import AMGeOApi\nfrom datetime import date\n\napi = AMGeOApi()\n\ncontroller = api.get_controller()\n\nd = date(2016, 1, 2)\n\nh = 'S'\n\ncontroller.load(d, h)"}},{"node":{"name":"solution_05_01","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\n \n\nfig, ax = plt.subplots()\nfig.patch.set_facecolor('white')\nax.plot(t,nino3)\nax.set_title('NINO3 SST')\nax.set_ylabel('NINO3 (K)')\nax.set_xlabel('Year AD')\nplt.show()\n"}},{"node":{"name":"solution_05_02","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\n \n\n# plot\nfig, ax = plt.subplots()\nfig.patch.set_facecolor('white')\nax.plot(t,nino3)\nax.set_title('NINO3 SST')\nax.set_ylabel('NINO3 (K)')\nax.set_xlabel('Year AD')\n# remove upper and top spines\nax.spines[['top', 'right']].set_visible(False)\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_05_03","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\n# plot\nfig, ax = plt.subplots(2,1,figsize=(10, 6),sharex = True)\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\ncsfont = {'fontname':'Helvetica'}\nax[0].plot(t,nino3)\nax[0].set_ylabel('NINO3 SST (K)',**csfont)\nax[0].set_title('NINO3 and All India Rainfall',fontdict={'fontweight':'bold','fontsize':18})\nax[1].plot(t,air)\nax[1].set_ylabel('AIR (mm/month)',**csfont)\nax[1].set_xlabel('Year AD')\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_05_04","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nfig, ax = plt.subplots(figsize=(10, 6))\nfig.patch.set_facecolor('white') # gatsby adjustment\nax.plot(t,nino3,label='NINO3',color='tab:red')\nax.set_ylabel('NINO3 SST (K)')\nax.set_title('NINO3 and All India Rainfall',fontweight='bold')\nax.legend()\n# twin object for two different y-axis on the sample plot\nax2=ax.twinx()\nax2.plot(t,air,label='AIR',color='tab:green',alpha=0.6)\nax2.set_xlabel('Year AD') \nax2.legend()\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_05_05","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\ndef nino3_air_plot(plot_title):\n    fig, ax = plt.subplots()\n    fig.patch.set_facecolor('white')\n    ax.plot(t,nino3,label='NINO3',color='C0')\n    ax.set_ylabel('NINO3 SST (K)')\n    ax.set_title(plot_title)\n    ax.legend()\n    # twin object for two different y-axis on the sample plot\n    ax2=ax.twinx()\n    ax2.plot(t,air,label='AIR',color='C1')\n    ax2.set_xlabel('Year AD')\n    ax2.legend()\n\navailable = ['default'] + plt.style.available\nfor i, style in enumerate(available):\n    with plt.style.context(style):\n        nino3_air_plot(plot_title=style)\n    \nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_05_07","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nwith plt.style.context('seaborn-whitegrid'):\n    fig = plt.figure(figsize=(12,8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    plt.scatter(nino3,air,c=t,cmap='viridis',alpha=0.7)\n    plt.xlabel('NINO3 SST (K)')\n    plt.ylabel('AIR (mm/month)')\n    plt.colorbar(label='year')\n    \nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_05_06","code":"import pandas as pd\nimport matplotlib.pyplot as plt\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0) \nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nwith plt.style.context('ggplot'):\n    fig, ax = plt.subplots(figsize=(8,6))\n    fig.patch.set_facecolor('white') # Gatsby shenanigan\n    ax.scatter(nino3,air,alpha=0.3)\n    ax.set_xlabel('NINO3 SST (K)')\n    ax.set_ylabel('AIR (mm/month)')\n    ax.set_title('NINO3 vs All India Rainfall, monthly data',fontweight = 'bold')\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_05_08","code":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport numpy as np\n\n# this block loads the data. You will need to reuse it in all exercises going forward. \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf  = pd.read_csv(url,skiprows=0) \nt   = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall \n\nfig = plt.figure(figsize=(10,8))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nax = plt.axes(projection ='3d')  # syntax for 3-D projection \nX, Y = np.meshgrid(nino3, t)\np = ax.scatter3D(nino3, t, air, c=t, cmap='viridis');\nfig.colorbar(p,label='Year', ax=ax)\nax.set_xlabel('NINO3 (K)'); ax.set_ylabel('Year'); ax.set_zlabel('AIR (mm/month)');\nax.set_title('3D representation', fontweight = 'bold')\n\nplt.show() #note: this last command is unnecessary in Jupyter notebooks, where the \"inline plot\" option is on by default.\n"}},{"node":{"name":"solution_06_01","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n\nfig = plt.figure(figsize=(11, 8.5))\nax = plt.subplot(1, 1, 1, projection=ccrs.PlateCarree(central_longitude=-75))\nax.set_title(\"A Geo-referenced subplot, Plate Carrée projection\");"}},{"node":{"name":"solution_06_07","code":"import matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\nfig = plt.figure(figsize=(11, 8.5))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\nproj = ccrs.LambertAzimuthalEqualArea(central_longitude=0.0, central_latitude=0.0)\nax = plt.subplot(1, 1, 1, projection=proj)\nax.coastlines()\nax.stock_img()\nax.add_feature(cfeature.BORDERS, linewidth=0.5, edgecolor='blue');\nax.tissot(facecolor='orange', alpha=0.8)\nax.set_title(\"Lambert Azimuthal Equal Area Projection with Tissot's indicatrix\");"}},{"node":{"name":"solution_06_11","code":"from cartopy.io import shapereader\nimport geopandas\nimport matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef map_ukraine(highlight_color='orange'):\n    '''\n        This function plots a regional map of Ukraine with administrative boundaries\n        \n        Inputs:\n        -------\n        highlight_color: the color in which the territory is highlighted\n        \n        Outputs:\n        -------\n        - fig: the resuling Matplotlib Figure object\n        - ax: the resuling Matplotlib Axes object\n    '''\n    \n    latN = 54; latS = 43\n    lonW = 23; lonE = 41\n    cLat = (latN + latS) / 2\n    cLon = (lonW + lonE) / 2\n\n    projLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\n    projPC = ccrs.PlateCarree() # we keep this for transforms\n\n    # get country borders\n    resolution = '10m'\n    category = 'cultural'\n    name = 'admin_0_countries'\n    shpfilename = shapereader.natural_earth(resolution, category, name)\n    # read the shapefile using geopandas\n    df = geopandas.read_file(shpfilename)\n\n    # put into polygon:\n    poly = df.loc[df['ADMIN'] == 'Ukraine']['geometry'].values[0]\n    # plot: \n    fig = plt.figure(figsize=(11.5, 8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    ax = plt.subplot(1, 1, 1, projection=projLccUk)\n    ax.set_extent([lonW, lonE, latS, latN], crs=projPC)\n    ax.set_facecolor(cfeature.COLORS['water'])\n    ax.add_feature(cfeature.LAND)\n    ax.add_feature(cfeature.COASTLINE)\n    ax.add_feature(cfeature.BORDERS, linestyle='--')\n    ax.add_feature(cfeature.LAKES, alpha=0.5)\n    ax.add_feature(cfeature.RIVERS)\n    ax.set_title('Ukraine and neighbors');\n    ax.add_geometries(poly, crs=projPC, facecolor=highlight_color, edgecolor='0.5')\n    return fig, ax\n\nmap_ukraine(highlight_color='tab:purple')\nplt.show()"}},{"node":{"name":"test_01_01","code":"def test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    #assert \"print(DATA[0])\" in __solution__, \"Are you printing the first record?\"\n    #assert some_var == len(DATA), \"Are you getting the correct length?\"\n    assert df.shape[0] == 828, \"Are you loading the right dataframe? The shape does not match\"\n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"solution_06_13","code":"from cartopy.io import shapereader\nimport geopandas\nimport matplotlib.pyplot as plt\nfrom cartopy import crs as ccrs, feature as cfeature\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\ndef map_ukraine(highlight_color='orange'):\n    '''\n        This function plots a regional map of Ukraine with administrative boundaries\n        \n        Inputs:\n        -------\n        highlight_color: the color in which the territory is highlighted\n        \n        Outputs:\n        -------\n        - fig: the resuling Matplotlib Figure object\n        - ax: the resuling Matplotlib Axes object\n    '''\n    \n    latN = 54; latS = 43\n    lonW = 23; lonE = 41\n    cLat = (latN + latS) / 2\n    cLon = (lonW + lonE) / 2\n\n    projLccUk = ccrs.LambertConformal(central_longitude=cLon, central_latitude=cLat)\n    projPC = ccrs.PlateCarree() # we keep this for transforms\n\n    # get country borders\n    resolution = '10m'\n    category = 'cultural'\n    name = 'admin_0_countries'\n    shpfilename = shapereader.natural_earth(resolution, category, name)\n    # read the shapefile using geopandas\n    df = geopandas.read_file(shpfilename)\n\n    # put into polygon:\n    poly = df.loc[df['ADMIN'] == 'Ukraine']['geometry'].values[0]\n    # plot: \n    fig = plt.figure(figsize=(11.5, 8))\n    fig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n    ax = plt.subplot(1, 1, 1, projection=projLccUk)\n    ax.set_extent([lonW, lonE, latS, latN], crs=projPC)\n    ax.set_facecolor(cfeature.COLORS['water'])\n    ax.add_feature(cfeature.LAND)\n    ax.add_feature(cfeature.COASTLINE)\n    ax.add_feature(cfeature.BORDERS, linestyle='--')\n    ax.add_feature(cfeature.LAKES, alpha=0.5)\n    ax.add_feature(cfeature.RIVERS)\n    ax.set_title('Ukraine and neighbors');\n    ax.add_geometries(poly, crs=projPC, facecolor=highlight_color, edgecolor='0.5')\n    return fig, ax\n\nfig, ax = map_ukraine()\nlatK, lonK = 50.45, 30.523333 # coordinates obtained from https://geohack.toolforge.org/geohack.php?pagename=Kyiv&params=50_27_00_N_30_31_24_E_region:UA_type:city\n# add a dot and a label for the city of Kyiv\nax.plot(lonK,latK,color=\"k\", marker=\"o\", markersize= 10,transform=ccrs.PlateCarree())\nax.text(lonK+0.5,latK+0.5,\"Kyiv\", transform=ccrs.PlateCarree(),\n        va='top', ha='right', fontweight='bold')\n# same for Mariupol\nlonM = 37.549444; latM = 47.095833\nax.plot(lonM,latM,color=\"k\", marker=\"o\", markersize= 10,transform=ccrs.PlateCarree())\nax.text(lonM+0.5,latM+0.5,\"Mariupol\", transform=ccrs.PlateCarree(),\n        va='top', ha='right', fontweight='bold')\nplt.show()"}},{"node":{"name":"solution_06_17","code":"import pandas as pd\nimport matplotlib.pyplot as plt\nimport matplotlib.patches as mpatches\nimport cartopy.crs as ccrs\nfrom cartopy.io import shapereader\nimport geopandas\nplt.style.use('seaborn-whitegrid')\n#  Suppress warnings issued by Cartopy when downloading data files\nimport warnings\nwarnings.filterwarnings('ignore')\n\n# import data \nurl = 'https://raw.githubusercontent.com/LinkedEarth/Pyleoclim_util/master/example_data/wtc_test_data_nino.csv'\ndf = pd.read_csv(url,skiprows=0)\nt = df['t'] # time in fractional years\nnino3 = df['nino'] # NINO3 data\nair  =  df['air'] # All India Rainfall\n\nfig = plt.figure(figsize = (12,12))\nfig.patch.set_facecolor('white') # necessary on Gatsby for some reason; redundant otherwise\n\n# first plot the timeseries as in Module 5\na1 = plt.subplot(2, 1, 2)\na1.plot(t,nino3,label='NINO3',color='C0')\na1.set_ylabel('SST (K)')\na1.set_title('Temporal evolution',fontweight='bold')\na1.legend()\n# twin object for two different y-axis on the sample plot\na1b=a1.twinx()\na1b.plot(t,air,label='AIR',color='C1')\na1b.set_ylabel('Rainfall (mm/month)')\na1b.set_xlabel('Year AD') \na1b.legend()\n# then add the map:\nproj = ccrs.Robinson(central_longitude=180, globe=None)\na0 = plt.subplot(2, 1, 1, projection=proj)\na0.set_extent([60, 280, -10, 40], crs=ccrs.PlateCarree())\na0.coastlines()\n#a0.stock_img()\ngl = a0.gridlines(\n    draw_labels=True, linewidth=1, color='gray', alpha=0.5, linestyle='--'\n)\n# add a box for NINO3\na0.add_patch(mpatches.Rectangle(xy=[210, -5], width=60, height=10,\n                                    facecolor='C0', transform=ccrs.PlateCarree()))\na0.text(230,0,\"NINO3\",transform=ccrs.PlateCarree(),fontweight='bold')\n\n# highlight India the same color as the line on the plot (2nd color in the default cycler)\n\n# extract country shape from the NaturalEarth database using geopandas\nresolution = '10m'; category = 'cultural'; name = 'admin_0_countries'\nshpfilename = shapereader.natural_earth(resolution, category, name)\ndf = geopandas.read_file(shpfilename)\n# put into polygon:\npoly = df.loc[df['ADMIN'] == 'India']['geometry'].values[0]\na0.add_geometries(poly, crs=ccrs.PlateCarree(), facecolor='C1')\na0.text(75,22,\"India\",transform=ccrs.PlateCarree(),fontweight='bold')\na0.set_title('Spatial relationships',fontweight='bold')\n\n\n\n\n\n"}},{"node":{"name":"test_01_03","code":"def test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    assert list(dataset1.keys())==['archiveType', 'geo', 'data'], \"Keys are incorrect\"\n    assert type(dataset1['geo']) == dict, 'geo should be a dictionary'\n    assert list(dataset1['geo'].keys())==['lat', 'lon'], 'The keys of the \"geo\" dictionary are incorrect'\n    assert type(dataset1['data']) == dict, 'data should be a dictionary'\n    assert list(dataset1['data'].keys())==['values', 'units'], 'The keys of the \"data\" dictionary are incorrect'\n    assert dataset1[\"archiveType\"] == \"marinesediment\", \"archiveType is incorrect\"\n    assert dataset1[\"geo\"]['lat'] == -5, \"lat is incorrect\"\n    assert dataset1[\"geo\"]['lon'] == 140, \"lon is incorrect\"\n    assert dataset1[\"data\"]['units'] == 'N/A', \"units is incorrect\"\n    assert type(dataset1[\"data\"]['values']) == list, \"The data values should be a list\"\n    assert dataset1[\"data\"]['values'] == [1,2,3], \"The data values are incorrect\"\n    assert latitude == -5, \"latitude is incorrect\"\n\n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"test_01_05","code":"import numpy as np\n\ndef test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    np.testing.assert_allclose(time, np.linspace(0,1000,1001),err_msg='incorrect time vector')\n    assert time_index == time[20], 'Wrong index'\n\n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"test_03_01","code":"import numpy as np\n\ndef test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    np.testing.assert_allclose(value, np.sin(2*np.pi*1/20*time),err_msg='incorrect value vector')\n    np.testing.assert_allclose(time, np.arange(1,2001,1),err_msg='incorrect time vector')\n\n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"test_03_02","code":"import numpy as np\nfrom numpy.random import default_rng\n\ndef test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    rng = default_rng(10)\n    white_noise_ans = rng.normal(0, np.sqrt(np.var(value)/2), size=np.size(value))\n\n    np.testing.assert_allclose(value2, value+white_noise_ans,err_msg='incorrect value vector')\n    \n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"test_03_03","code":"import numpy as np\n\n\ndef test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    idx_min = np.where(time==200)[0][0]\n    idx_max = np.where(time==400)[0][0]\n\n    np.testing.assert_allclose(value2, value[idx_min:idx_max+1], err_msg='Remember that slice notation is exclusive of the final index')\n\n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"test_03_04","code":"import numpy as np\n\ndef test():\n    # Here we can either check objects created in the solution code, or the\n    # string value of the solution, available as __solution__. A helper for\n    # printing formatted messages is available as __msg__. See the testTemplate\n    # in the meta.json for details.\n\n    # If an assertion fails, the message will be displayed\n    np.testing.assert_allclose(time, np.arange(0,10001,100), err_msg='Time vector is incorrect. Remember that the last value is excluded')\n    assert np.shape(time_ens) == (101,1000), 'The shape of the ensemble array should be (length of time vector, 1000)'\n    assert np.shape(time_mean) == (101,), 'The shape of the mean should be the same as the shape of time'\n\n    __msg__.good(\"Well done!\")\n"}},{"node":{"name":"utils","code":"def import_all():\n    import requests\n    import numpy as np\n    import pandas as pd\n    from datetime import datetime, timedelta, date\n\n    #import xarray as xr\n    import os\n    import time\n\n    #data visualization\n    %matplotlib inline\n    import matplotlib.pylab as plt\n    from matplotlib import ticker\n    %matplotlib inline\n\n    #used for map projections\n    import cartopy.crs as ccrs\n    import cartopy.feature as cft\n    from cartopy.mpl.gridliner import LONGITUDE_FORMATTER, LATITUDE_FORMATTER\n\n    import warnings\n    warnings.filterwarnings('ignore')\n\ndef check_error_message(ans,writeFlag=False):\n    # ans: response JSON from an API query\n    # writeFlag: bool, true == print verbose errors, if found\n    # returns error code if found, or NaN if not.\n    if isinstance(ans,dict) and 'message' in ans.keys() and 'code' in ans.keys():\n        if writeFlag:\n            print(str(ans['code']) + ': ' + ans['message'])\n        ##### NOTE: we should include here below all the codes that do not return data as the user expects\n        if ans['code'] >= 400 and ans['code'] != 404:\n            print('Data were not returned')\n            print(ans)\n            raise Exception('No data')\n        return ans['code']        \n    elif ans:\n        return np.nan"}}]}}}