Skip to content

Commit

Permalink
Add arg parsing and some doc
Browse files Browse the repository at this point in the history
  • Loading branch information
garyo committed Feb 8, 2024
1 parent 2133528 commit 9daf45b
Show file tree
Hide file tree
Showing 8 changed files with 170 additions and 32 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
sst-data-cache.json
21 changes: 21 additions & 0 deletions LICENSE
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
MIT License

Copyright (c) 2024 Dark Star Systems, Inc.

Permission is hereby granted, free of charge, to any person obtaining a copy
of this software and associated documentation files (the "Software"), to deal
in the Software without restriction, including without limitation the rights
to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
copies of the Software, and to permit persons to whom the Software is
furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all
copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
SOFTWARE.
11 changes: 11 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
# Sea Surface Temp Visualization

This python code downloads daily worldwide sea surface temp datasets
and visualizes them either as a world map on a given day, or as a time
series per year.

Examples:
![SST temp map](doc/sst-temp-map.png "SST temp map")
![SST anomaly map](doc/sst-anomalies-map.png "SST anomaly map")
![SST anomaly graph](doc/sst-anomalies.png "SST anomalies")

Binary file added doc/sst-anomalies.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/sst-temp-map.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
Binary file added doc/sst-var-map.png
Loading
Sorry, something went wrong. Reload?
Sorry, we cannot display this file.
Sorry, this file is invalid so it cannot be displayed.
39 changes: 39 additions & 0 deletions requirements.txt
Original file line number Diff line number Diff line change
@@ -0,0 +1,39 @@
Bottleneck==1.3.5
Brotli==1.0.9
Cartopy==0.22.0
certifi==2024.2.2
cffi==1.16.0
charset-normalizer==2.0.4
contourpy==1.2.0
cryptography==41.0.7
cycler==0.11.0
fonttools==4.25.0
h5py==3.9.0
idna==3.4
kiwisolver==1.4.4
matplotlib==3.8.0
munkres==1.1.4
numexpr==2.8.7
numpy==1.26.3
packaging==23.1
pandas==2.1.4
pillow==10.2.0
pip==23.3.1
py-cpuinfo==9.0.0
pycparser==2.21
pyOpenSSL==23.2.0
pyparsing==3.0.9
pyproj==3.6.1
pyshp==2.3.1
PySocks==1.7.1
python-dateutil==2.8.2
pytz==2023.3.post1
requests==2.31.0
setuptools==68.2.2
shapely==2.0.1
six==1.16.0
tables==3.9.2
tornado==6.3.3
tzdata==2023.3
urllib3==1.26.18
wheel==0.41.2
130 changes: 98 additions & 32 deletions sea-surface-temps.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,15 @@
import requests, io, h5py, urllib3
# SPDX-License-Identifier: MIT

import sys, requests, io, h5py, urllib3
import datetime
import calendar
import pandas as pd
import numpy as np
import matplotlib.pyplot as plt
import json
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
import json
import argparse
import pathlib

urllib3.disable_warnings(urllib3.exceptions.InsecureRequestWarning)

Expand Down Expand Up @@ -98,18 +102,26 @@ def get_average_temp(hdf, dataset_name):
return average

# Disk cache: entries are yyyy-mm-dd-DATASETNAME
temps_cache_file='/tmp/sst-data-cache.json'
try:
with open(temps_cache_file, 'r') as f:
temps_cache = json.load(f)
except IOError:
temps_cache = {}
temps_cache_file='./sst-data-cache.json'
temps_cache = {}

def save_cache():
global temps_cache
global temps_cache_file
json_data = json.dumps(temps_cache, cls=NumpyArrayEncoder)
with open(temps_cache_file, 'w') as f:
f.write(json_data)

def load_cache(path):
global temps_cache_file
global temps_cache
temps_cache_file = path
try:
with open(temps_cache_file, 'r') as f:
temps_cache = json.load(f)
except IOError:
temps_cache = {}

def get_temp_for_date(year, mo, day, dataset_name):
cache_key = f'{year}-{mo:02}-{day:02}-{dataset_name}'
cached = temps_cache.get(cache_key)
Expand Down Expand Up @@ -156,34 +168,41 @@ def plot_globe_dataset(data, hdf, vmin, vmax, cmap, title):
plt.colorbar(c, orientation='horizontal', pad=0.05)

plt.title(title)
plt.savefig('/tmp/sst-map.png', dpi=300)
plt.show()

plot_map = False
if plot_map:
year = 2024
mo = 2
day = 6
def process_date(args):
if args.days_ago:
date = datetime.date.today() - datetime.timedelta(days=args.days_ago)
year = date.year
mo = date.month
day = date.day
else:
year = args.year
mo = args.month
day = args.day
date=f'{year}-{mo:02}-{day:02}'
hdf = get_sst_dataset(year, mo, day)

data = get_processed_hdf_data_array(hdf, 'anom', -90, 90)
# Blue below zero (midpoint=0.5), yellow to red above. Midpoint should map to 0 temp diff.
variance_cmap = LinearSegmentedColormap.from_list("sst_cmap",
[[0, "white"], [0.2, "darkblue"],
[0.45, "lightblue"], [0.5, "white"],
[0.6, "yellow"], [0.9, "red"],
[1.0, "darkred"]])
plot_globe_dataset(data, hdf, -3, 3, variance_cmap, f'{date}\nSea Surface Temp Variance from 1971–2000 Mean, °C')
data = get_processed_hdf_data_array(hdf, 'sst', -90, 90)
# white at 20°C or 0.666
sst_cmap = LinearSegmentedColormap.from_list("sst_cmap",
[[0, "darkblue"], [0.666, "white"],
[0.8, "yellow"], [0.9, "red"],
[1.0, "darkred"]])
plot_globe_dataset(data, hdf, 0, 30, sst_cmap, f'{date}\nSea Surface Temp, °C')

plot_all_data = True
if plot_all_data:
if args.dataset == 'anom':
data = get_processed_hdf_data_array(hdf, 'anom', -90, 90)
# Blue below zero (midpoint=0.5), yellow to red above. Midpoint should map to 0 temp diff.
variance_cmap = LinearSegmentedColormap.from_list("sst_cmap",
[[0, "white"], [0.2, "darkblue"],
[0.45, "lightblue"], [0.5, "white"],
[0.6, "yellow"], [0.9, "red"],
[1.0, "darkred"]])
plot_globe_dataset(data, hdf, -3, 3, variance_cmap, f'{date}\nSea Surface Temp Variance from 1971–2000 Mean, °C')
else:
data = get_processed_hdf_data_array(hdf, 'sst', -90, 90)
# white at 20°C or 0.666
sst_cmap = LinearSegmentedColormap.from_list("sst_cmap",
[[0, "darkblue"], [0.666, "white"],
[0.8, "yellow"], [0.9, "red"],
[1.0, "darkred"]])
plot_globe_dataset(data, hdf, 0, 30, sst_cmap, f'{date}\nSea Surface Temp, °C')

def process_all(args):
def get_data(temp_data, dataset_name):
start_year = 2000
end_year = 2024
Expand Down Expand Up @@ -239,7 +258,7 @@ def plot_fig(temps, title):
plt.text(0, 0,
msg,
ha="left", va="top", transform=plt.gca().transAxes, fontsize=9)
plt.savefig('/tmp/sst-anomalies.png', dpi=300)
plt.savefig('/tmp/sst.png', dpi=300)
plt.show()

temp_data = {} # indexed by year and then day of year (0-based)
Expand All @@ -248,3 +267,50 @@ def plot_fig(temps, title):
plot_fig(temp_data, "Sea Surface Temp anomalies (°C) by year, vs. 1971-2000 mean"
if type == 'anom'
else "Sea Surface Temps by year")


def main(argv=None):
class CustomFormatter(argparse.ArgumentDefaultsHelpFormatter,
argparse.RawDescriptionHelpFormatter):
pass

try:
parser = argparse.ArgumentParser(description="""Sea Surface Temperature Visualizer""",
formatter_class=CustomFormatter)
parser.add_argument('--verbose', '-v', action='store_true',
help="""Process verbosely""")
parser.add_argument('--dataset', '-d', choices=('anom', 'sst'),
default='anom',
help="""Dataset: sst=temperatures, anom=anomalies vs. mean""")
parser.add_argument('--mode', '-m', choices=('all', 'map'),
default='all',
help="""Mode: all=all time, map=map of today""")
parser.add_argument('--year', '-Y', type=int,
default=datetime.date.today().year,
help="""Year for map mode""")
parser.add_argument('--month', '-M', type=int,
default=datetime.date.today().month,
help="""Month for map mode""")
parser.add_argument('--day', '-D', type=int,
default=datetime.date.today().day,
help="""Day of month for map mode""")
parser.add_argument('--days-ago', type=int,
default=0,
help="""Days ago (before today), for map mode""")
parser.add_argument('--cache-file', type=pathlib.Path,
default='./sst-data-cache.json',
help="""Cache file to speed up future runs""")
args = parser.parse_args(argv)

load_cache(args.cache_file)
if args.mode == 'all':
process_all(args)
else:
process_date(args)
except RuntimeError as e:
print(e)
return 1


if __name__ == "__main__":
sys.exit(main(sys.argv[1:]))

0 comments on commit 9daf45b

Please sign in to comment.