From 1f510ed26b86a4402ac6d4e43331c10273ed2798 Mon Sep 17 00:00:00 2001 From: Davide Madrisan Date: Mon, 28 Aug 2023 12:40:22 +0200 Subject: [PATCH] ci: make code format compliant to black linter Signed-off-by: Davide Madrisan --- hadcrut5-bars.py | 115 ++++++++++++++----------- hadcrut5-plot.py | 209 ++++++++++++++++++++++++++------------------- hadcrut5-stripe.py | 134 ++++++++++++++++++----------- hadcrut5lib.py | 135 +++++++++++++++++------------ 4 files changed, 354 insertions(+), 239 deletions(-) diff --git a/hadcrut5-bars.py b/hadcrut5-bars.py index 645a9aa..eb2189c 100755 --- a/hadcrut5-bars.py +++ b/hadcrut5-bars.py @@ -11,40 +11,54 @@ from hadcrut5lib import argparser, HadCRUT5 + def parse_args(): """This function parses and return arguments passed in""" descr = "Parse and plot the HadCRUT5 temperature datasets" examples = [ - "%(prog)s", - "%(prog)s --period \"1850-1900\"", - "%(prog)s --period \"1880-1920\"", - "%(prog)s --outfile HadCRUT5-global.png"] + "%(prog)s", + '%(prog)s --period "1850-1900"', + '%(prog)s --period "1880-1920"', + "%(prog)s --outfile HadCRUT5-global.png", + ] parser = argparser(descr, examples) parser.add_argument( - "-f", "--outfile", - action="store", dest="outfile", - help="name of the output PNG file") + "-f", + "--outfile", + action="store", + dest="outfile", + help="name of the output PNG file", + ) parser.add_argument( - "-p", "--period", - action="store", dest="period", default="1961-1990", - help="show anomalies related to 1961-1990 (default), 1850-1900, or 1880-1920") + "-p", + "--period", + action="store", + dest="period", + default="1961-1990", + help="show anomalies related to 1961-1990 (default), 1850-1900, or 1880-1920", + ) parser.add_argument( - "-v", "--verbose", + "-v", + "--verbose", action="store_true", dest="verbose", - help="make the operation more talkative") + help="make the operation more talkative", + ) return parser.parse_args() + def plotbar(period, outfile, verbose): """ Create a bar plot for the specified period and diplay it or save it to file if outfile is set """ + # pylint: disable=W0613 def major_formatter(x, pos): - return f'{x:.1f}' if x >= 0 else '' + return f"{x:.1f}" if x >= 0 else "" + # pylint: enable=W0613 hc5 = HadCRUT5(period=period, verbose=verbose) @@ -57,67 +71,72 @@ def major_formatter(x, pos): bar_width = 0.7 basefont = { - 'family': 'DejaVu Sans', - 'color' : 'white', - 'weight': 'bold', + "family": "DejaVu Sans", + "color": "white", + "weight": "bold", } - fontxl = { **basefont, "size": 20 } - fontxs = { **basefont, "size": 12 } + fontxl = {**basefont, "size": 20} + fontxs = {**basefont, "size": 12} plt.style.use("dark_background") _, ax = plt.subplots() - cmap = plt.cm.jet # or plt.cm.bwr + cmap = plt.cm.jet # or plt.cm.bwr norm = matplotlib.colors.Normalize(vmin=-1, vmax=max(mean)) colors = cmap(norm(mean)) - ax.bar(years, - mean, - width=bar_width, - color=colors, - align="center") + ax.bar(years, mean, width=bar_width, color=colors, align="center") ax.set_frame_on(False) ax.yaxis.tick_right() ax.yaxis.set_major_formatter(major_formatter) - ax.tick_params(axis=u'both', which=u'both',length=0) + ax.tick_params(axis="both", which="both", length=0) - upper, left = .95, .025 + upper, left = 0.95, 0.025 last_year = years[-1] - text_props = dict(horizontalalignment="left", - verticalalignment="top", - transform=ax.transAxes) - plt.text(left, upper, - '\n'.join(( - r"Global average temperature difference *", - r"1850-{}".format(last_year))), - fontdict=fontxl, - linespacing=1.2, - **text_props) - plt.text(left, upper - .125, - '\n'.join(( - r"(*) Compared to {} pre-industrial levels".format(period), - r"Data source - HadCRUT5")), - fontdict=fontxs, - linespacing=1.5, - **text_props) + text_props = dict( + horizontalalignment="left", verticalalignment="top", transform=ax.transAxes + ) + plt.text( + left, + upper, + "\n".join( + (r"Global average temperature difference *", r"1850-{}".format(last_year)) + ), + fontdict=fontxl, + linespacing=1.2, + **text_props, + ) + plt.text( + left, + upper - 0.125, + "\n".join( + ( + r"(*) Compared to {} pre-industrial levels".format(period), + r"Data source - HadCRUT5", + ) + ), + fontdict=fontxs, + linespacing=1.5, + **text_props, + ) fig = plt.gcf() - fig.set_size_inches(10, 8) # 1 inch equal to 80pt + fig.set_size_inches(10, 8) # 1 inch equal to 80pt if outfile: - fig.savefig(outfile, dpi=80, bbox_inches='tight') + fig.savefig(outfile, dpi=80, bbox_inches="tight") plt.close(fig) else: plt.show() + # pylint: disable=C0116 def main(): args = parse_args() - plotbar(args.period, - args.outfile, - args.verbose) + plotbar(args.period, args.outfile, args.verbose) + main() diff --git a/hadcrut5-plot.py b/hadcrut5-plot.py index 4a07aad..b89e330 100755 --- a/hadcrut5-plot.py +++ b/hadcrut5-plot.py @@ -13,86 +13,112 @@ from math import trunc from hadcrut5lib import argparser, dprint, HadCRUT5 + def parse_args(): """This function parses and return arguments passed in""" descr = "Parse and plot the HadCRUT5 temperature datasets" examples = [ - "%(prog)s", - "%(prog)s --global --annotate=2", - "%(prog)s --period \"1850-1900\"", - "%(prog)s --period \"1850-1900\" --smoother 5", - "%(prog)s --period \"1880-1920\" --outfile HadCRUT5-1880-1920.png", - "%(prog)s --period \"1880-1920\" --time-series monthly --global"] + "%(prog)s", + "%(prog)s --global --annotate=2", + '%(prog)s --period "1850-1900"', + '%(prog)s --period "1850-1900" --smoother 5', + '%(prog)s --period "1880-1920" --outfile HadCRUT5-1880-1920.png', + '%(prog)s --period "1880-1920" --time-series monthly --global', + ] parser = argparser(descr, examples) parser.add_argument( - "-a", "--annotate", - action="store", dest="annotate", default="1", + "-a", + "--annotate", + action="store", + dest="annotate", + default="1", help="add temperature annotations (0: no annotations, 1 (default): " - "bottom only, 2: all ones") + "bottom only, 2: all ones", + ) parser.add_argument( - "-f", "--outfile", + "-f", + "--outfile", action="store", dest="outfile", - help="name of the output PNG file") + help="name of the output PNG file", + ) parser.add_argument( - "-g", "--global", + "-g", + "--global", action="store_true", dest="plot_global", - help="plot the Global Temperatures") + help="plot the Global Temperatures", + ) parser.add_argument( - "-m", "--smoother", + "-m", + "--smoother", action="store", dest="smoother", - help="make the lines smoother by using N-year means") + help="make the lines smoother by using N-year means", + ) parser.add_argument( - "-n", "--northern", + "-n", + "--northern", action="store_true", dest="plot_northern", - help="Northern Hemisphere Temperatures") + help="Northern Hemisphere Temperatures", + ) parser.add_argument( - "-p", "--period", + "-p", + "--period", action="store", dest="period", default="1961-1990", - help="show anomalies related to 1961-1990 (default), 1850-1900, or 1880-1920") + help="show anomalies related to 1961-1990 (default), 1850-1900, or 1880-1920", + ) parser.add_argument( - "-s", "--southern", - action='store_true', + "-s", + "--southern", + action="store_true", dest="plot_southern", - help="Southern Hemisphere Temperatures") + help="Southern Hemisphere Temperatures", + ) parser.add_argument( - "-t", "--time-series", - action='store', + "-t", + "--time-series", + action="store", default="annual", dest="time_series", - help="do plot the \"annual\" time series (default) or the \"monthly\" one") + help='do plot the "annual" time series (default) or the "monthly" one', + ) parser.add_argument( - "-v", "--verbose", + "-v", + "--verbose", action="store_true", dest="verbose", - help="make the operation more talkative") + help="make the operation more talkative", + ) return parser.parse_args() + def dataset_current_anomaly(temperatures): """Return the current anomaly""" return temperatures[-1] + def dataset_max_anomaly(temperatures): """Return the maximum anomaly with respect to 'temperatures'""" return np.max(temperatures) + def dataset_smoother(years, temperatures, chunksize): """Make the lines smoother by using {chunksize}-year means""" data_range = range((len(years) + chunksize - 1) // chunksize) - subset_years = [years[i*chunksize] for i in data_range] + subset_years = [years[i * chunksize] for i in data_range] subset_temperatures = [ - np.mean(temperatures[i*chunksize:(i+1)*chunksize]) for i in data_range + np.mean(temperatures[i * chunksize : (i + 1) * chunksize]) for i in data_range ] return subset_years, subset_temperatures + def plotline(hc5, chunksize, annotate, outfile, verbose): """ Create a plot for the specified period and arguments and diplay it or save @@ -122,39 +148,39 @@ def plotline(hc5, chunksize, annotate, outfile, verbose): anomaly_current[region] = dataset_current_anomaly(mean) anomaly_max[region] = dataset_max_anomaly(mean) - dprint(verbose, ("Current anomalies: {}" - .format(anomaly_current[region]))) + dprint(verbose, ("Current anomalies: {}".format(anomaly_current[region]))) dprint(verbose, "Max anomalies: {}".format(anomaly_max[region])) if annotate > 1: - plt.annotate("{0:.2f}°C".format(anomaly_current[region]), - xy=(years[-1]-5, anomaly_current[region]+.05), - fontsize=6, - horizontalalignment='left', - bbox={ - "facecolor": "lightgray", - "alpha": 0.6, - "pad": 3 - } + plt.annotate( + "{0:.2f}°C".format(anomaly_current[region]), + xy=(years[-1] - 5, anomaly_current[region] + 0.05), + fontsize=6, + horizontalalignment="left", + bbox={"facecolor": "lightgray", "alpha": 0.6, "pad": 3}, ) linewidth = 1 if hc5.is_monthly_dataset and chunksize < 2 else 2 - plt.plot(years, - mean, - linewidth=linewidth, - markersize=12, - label=region) - - plt.hlines(0, np.min(dataset_years), np.max(dataset_years), - colors='gray', linestyles='dotted') - - plt.title(( - "HadCRUT5: land and sea temperature anomalies relative to {}" - .format(hc5.dataset_period))) + plt.plot(years, mean, linewidth=linewidth, markersize=12, label=region) + + plt.hlines( + 0, + np.min(dataset_years), + np.max(dataset_years), + colors="gray", + linestyles="dotted", + ) + + plt.title( + ( + "HadCRUT5: land and sea temperature anomalies relative to {}".format( + hc5.dataset_period + ) + ) + ) plt.xlabel("year", fontsize=10) - ylabel = ("{} Temperature Anomalies in °C" - .format(hc5.dataset_datatype.capitalize())) + ylabel = "{} Temperature Anomalies in °C".format(hc5.dataset_datatype.capitalize()) if chunksize > 1: ylabel += " ({}-year averages)".format(chunksize) @@ -164,27 +190,32 @@ def plotline(hc5, chunksize, annotate, outfile, verbose): if annotate > 0 and current and maximum: current_year = trunc(hc5.dataset_years()[-1]) - plt.annotate(("current global anomaly ({0}): {1:+.2f}°C, max: {2:+.2f}°C" - .format(current_year, current, maximum)), - xy=(0.98, 0.03), - xycoords="axes fraction", - fontsize=8, - horizontalalignment="right", - verticalalignment="bottom", - bbox={ - "facecolor": "{}".format( - "blue" if current <= 0 else "red" - ), - "alpha": 0.3, - "pad": 5, - }) - - plt.annotate(hc5.dataset_history, - xy=(0.01, 0.8), - xycoords="axes fraction", - fontsize=8, - horizontalalignment="left", - verticalalignment="top") + plt.annotate( + ( + "current global anomaly ({0}): {1:+.2f}°C, max: {2:+.2f}°C".format( + current_year, current, maximum + ) + ), + xy=(0.98, 0.03), + xycoords="axes fraction", + fontsize=8, + horizontalalignment="right", + verticalalignment="bottom", + bbox={ + "facecolor": "{}".format("blue" if current <= 0 else "red"), + "alpha": 0.3, + "pad": 5, + }, + ) + + plt.annotate( + hc5.dataset_history, + xy=(0.01, 0.8), + xycoords="axes fraction", + fontsize=8, + horizontalalignment="left", + verticalalignment="top", + ) plt.ylabel(ylabel, fontsize=10) plt.legend() @@ -194,6 +225,7 @@ def plotline(hc5, chunksize, annotate, outfile, verbose): else: plt.show() + # pylint: disable=C0116 def main(): args = parse_args() @@ -208,16 +240,21 @@ def main(): regions = (plot_global, plot_northern, plot_southern) smoother = int(args.smoother) if args.smoother else 1 - hc5 = HadCRUT5(period=args.period, - datatype=args.time_series, - regions=regions, - smoother=smoother, - verbose=args.verbose) - - plotline(hc5, - smoother, - int(args.annotate) if args.annotate else 1, - args.outfile, - args.verbose) + hc5 = HadCRUT5( + period=args.period, + datatype=args.time_series, + regions=regions, + smoother=smoother, + verbose=args.verbose, + ) + + plotline( + hc5, + smoother, + int(args.annotate) if args.annotate else 1, + args.outfile, + args.verbose, + ) + main() diff --git a/hadcrut5-stripe.py b/hadcrut5-stripe.py index c95f583..f6800bf 100755 --- a/hadcrut5-stripe.py +++ b/hadcrut5-stripe.py @@ -13,44 +13,61 @@ from hadcrut5lib import argparser, HadCRUT5 + def parse_args(): """This function parses and return arguments passed in""" descr = "Parse and plot a stripe image of the HadCRUT5 temperature datasets" examples = [ - "%(prog)s", - "%(prog)s --no-labels --region northern", - "%(prog)s --region global --outfile HadCRUT5-stripe-global.png"] + "%(prog)s", + "%(prog)s --no-labels --region northern", + "%(prog)s --region global --outfile HadCRUT5-stripe-global.png", + ] parser = argparser(descr, examples) parser.add_argument( - "-f", "--outfile", - action="store", dest="outfile", - help="name of the output PNG file") + "-f", + "--outfile", + action="store", + dest="outfile", + help="name of the output PNG file", + ) parser.add_argument( - "-r", "--region", choices=["global", "northern", "southern"], - action="store", dest="region", default="global", - help="select between Global (default), Northern, or Southern Temperatures") + "-r", + "--region", + choices=["global", "northern", "southern"], + action="store", + dest="region", + default="global", + help="select between Global (default), Northern, or Southern Temperatures", + ) parser.add_argument( - "-v", "--verbose", - action="store_true", dest="verbose", - help="make the operation more talkative") + "-v", + "--verbose", + action="store_true", + dest="verbose", + help="make the operation more talkative", + ) parser.add_argument( - "-l", "--no-labels", - action="store_false", dest="labels", - help="do not disply the header and footer labels") + "-l", + "--no-labels", + action="store_false", + dest="labels", + help="do not disply the header and footer labels", + ) parser.set_defaults(labels=True) return parser.parse_args() + def plotstripe(region, outfile, labels, verbose): """ Create a stripe plot for the specified period and diplay it or save it to file if outfile is set """ - hc5 = HadCRUT5(regions=(region == "global", - region == "northern", - region == "southern"), - verbose=verbose) + hc5 = HadCRUT5( + regions=(region == "global", region == "northern", region == "southern"), + verbose=verbose, + ) hc5.datasets_download() hc5.datasets_load() hc5.datasets_normalize() @@ -60,9 +77,9 @@ def plotstripe(region, outfile, labels, verbose): yrange = ylast - yfirst regions_switch = { - "global": hc5.GLOBAL_REGION, - "northern": hc5.NORTHERN_REGION, - "southern": hc5.SOUTHERN_REGION + "global": hc5.GLOBAL_REGION, + "northern": hc5.NORTHERN_REGION, + "southern": hc5.SOUTHERN_REGION, } _, mean, _ = hc5.dataset_normalized_data(regions_switch[region]) @@ -71,60 +88,75 @@ def plotstripe(region, outfile, labels, verbose): # the colors in this colormap come from http://colorbrewer2.org # (the 8 more saturated colors from the 9 blues / 9 reds) - cmap = ListedColormap([ - '#08306b', '#08519c', '#2171b5', '#4292c6', - '#6baed6', '#9ecae1', '#c6dbef', '#deebf7', - '#fee0d2', '#fcbba1', '#fc9272', '#fb6a4a', - '#ef3b2c', '#cb181d', '#a50f15', '#67000d', - ]) + cmap = ListedColormap( + [ + "#08306b", + "#08519c", + "#2171b5", + "#4292c6", + "#6baed6", + "#9ecae1", + "#c6dbef", + "#deebf7", + "#fee0d2", + "#fcbba1", + "#fc9272", + "#fb6a4a", + "#ef3b2c", + "#cb181d", + "#a50f15", + "#67000d", + ] + ) # create a collection with a rectangle for each year - collection = PatchCollection([ - Rectangle((x/yrange, 0), x + 1/yrange, 1) - for x in range(1 + yrange) - ]) + collection = PatchCollection( + [Rectangle((x / yrange, 0), x + 1 / yrange, 1) for x in range(1 + yrange)] + ) # set data and colormap collection.set_array(mean) collection.set_cmap(cmap) - #collection.set_clim(,) + # collection.set_clim(,) ax.add_collection(collection) ax.get_yaxis().set_visible(False) ax.set_frame_on(False) if labels: - ax.tick_params(axis='both', which='both', length=0) - #pylint: disable=consider-using-f-string - plt.title(("{} Temperature Change ({}-{})" - .format(regions_switch[region], - yfirst, - ylast)), - fontsize=16, - loc='left', - fontweight='bold', - family='DejaVu Sans') + ax.tick_params(axis="both", which="both", length=0) + # pylint: disable=consider-using-f-string + plt.title( + ( + "{} Temperature Change ({}-{})".format( + regions_switch[region], yfirst, ylast + ) + ), + fontsize=16, + loc="left", + fontweight="bold", + family="DejaVu Sans", + ) ticks = [0, 0.2, 0.4, 0.6, 0.8, 1] - xlabels = [round(yfirst + x*yrange) for x in ticks] - plt.xticks(ticks, xlabels, fontweight='bold', fontsize=12) + xlabels = [round(yfirst + x * yrange) for x in ticks] + plt.xticks(ticks, xlabels, fontweight="bold", fontsize=12) else: ax.get_xaxis().set_visible(False) fig = plt.gcf() - fig.set_size_inches(10, 4) # 1 inch equal to 80pt + fig.set_size_inches(10, 4) # 1 inch equal to 80pt if outfile: - fig.savefig(outfile, dpi=80, bbox_inches='tight') + fig.savefig(outfile, dpi=80, bbox_inches="tight") plt.close(fig) else: plt.show() + # pylint: disable=C0116 def main(): args = parse_args() - plotstripe(args.region, - args.outfile, - args.labels, - args.verbose) + plotstripe(args.region, args.outfile, args.labels, args.verbose) + main() diff --git a/hadcrut5lib.py b/hadcrut5lib.py index 73953d2..8d66ae7 100755 --- a/hadcrut5lib.py +++ b/hadcrut5lib.py @@ -14,6 +14,7 @@ # pylint: disable=E0611 from netCDF4 import Dataset as nc_Dataset + # pylint: enable=E0611 __author__ = "Davide Madrisan" @@ -23,25 +24,29 @@ __email__ = "davide.madrisan@gmail.com" __status__ = "stable" + def copyleft(descr): - """Print the Copyright message and License """ - return ("{} v{} ({})\n{} <{}>\nLicense: {}" - .format(descr, __version__, __status__, - __copyright__, __email__, - __license__)) + """Print the Copyright message and License""" + return "{} v{} ({})\n{} <{}>\nLicense: {}".format( + descr, __version__, __status__, __copyright__, __email__, __license__ + ) + def argparser(descr, examples): - """Return a new ArgumentParser object """ + """Return a new ArgumentParser object""" return argparse.ArgumentParser( - formatter_class = argparse.RawDescriptionHelpFormatter, - description = copyleft(descr), - epilog = "examples:\n " + "\n ".join(examples)) + formatter_class=argparse.RawDescriptionHelpFormatter, + description=copyleft(descr), + epilog="examples:\n " + "\n ".join(examples), + ) + def dprint(verbose, message): """Print a message when in verbose mode only""" if verbose: print(message) + # pylint: disable=R0902 class HadCRUT5: """Class for parsing and plotting HadCRUT5 datasets""" @@ -61,19 +66,18 @@ class HadCRUT5: NORTHERN_REGION = "Northern Hemisphere" SOUTHERN_REGION = "Southern Hemisphere" - def __init__(self, - period=_DEFAULT_PERIOD, - datatype=_DEFAULT_DATATYPE, - regions=(True, False, False), - smoother=1, - verbose=False): - + def __init__( + self, + period=_DEFAULT_PERIOD, + datatype=_DEFAULT_DATATYPE, + regions=(True, False, False), + smoother=1, + verbose=False, + ): if datatype not in self._VALID_DATATYPES: - raise Exception(("Unsupported time series type \"{}\"" - .format(datatype))) + raise Exception(('Unsupported time series type "{}"'.format(datatype))) if period not in self._VALID_PERIODS: - raise Exception(("Unsupported reference period: \"{}\"" - .format(period))) + raise Exception(('Unsupported reference period: "{}"'.format(period))) # will be populated by datasets_load() self._datasets = {} @@ -82,23 +86,27 @@ def __init__(self, self._datatype = datatype - (self._enable_global, - self._enable_northern, - self._enable_southern) = regions + (self._enable_global, self._enable_northern, self._enable_southern) = regions self._period = period self._smoother = smoother self._verbose = verbose self._global_filename = ( - "HadCRUT.{}.analysis.summary_series.global.{}.nc" - .format(self._DATASET_VERSION, datatype)) + "HadCRUT.{}.analysis.summary_series.global.{}.nc".format( + self._DATASET_VERSION, datatype + ) + ) self._northern_hemisphere_filename = ( - "HadCRUT.{}.analysis.summary_series.northern_hemisphere.{}.nc" - .format(self._DATASET_VERSION, datatype)) + "HadCRUT.{}.analysis.summary_series.northern_hemisphere.{}.nc".format( + self._DATASET_VERSION, datatype + ) + ) self._southern_hemisphere_filename = ( - "HadCRUT.{}.analysis.summary_series.southern_hemisphere.{}.nc" - .format(self._DATASET_VERSION, datatype)) + "HadCRUT.{}.analysis.summary_series.southern_hemisphere.{}.nc".format( + self._DATASET_VERSION, datatype + ) + ) def datasets_download(self): """Download the required HadCRUT5 datasets""" @@ -117,16 +125,20 @@ def dataset_load(dataset_filename): dataset = nc_Dataset(dataset_filename) return { "dimensions": dataset.dimensions, - "metadata" : dataset.__dict__, - "variables" : dataset.variables, + "metadata": dataset.__dict__, + "variables": dataset.variables, } def dataset_metadata_dump(dataset_name, dataset): metadata = dataset["metadata"] - dprint(self._verbose, - ("Metadata for \"{}\" dataset:\n{}" - .format(dataset_name, - json.dumps(metadata, indent=2)))) + dprint( + self._verbose, + ( + 'Metadata for "{}" dataset:\n{}'.format( + dataset_name, json.dumps(metadata, indent=2) + ) + ), + ) if self._enable_global: region = self.GLOBAL_REGION @@ -134,13 +146,11 @@ def dataset_metadata_dump(dataset_name, dataset): dataset_metadata_dump(region, self._datasets[region]) if self._enable_northern: region = self.NORTHERN_REGION - self._datasets[region] = \ - dataset_load(self._northern_hemisphere_filename) + self._datasets[region] = dataset_load(self._northern_hemisphere_filename) dataset_metadata_dump(region, self._datasets[region]) if self._enable_southern: region = self.SOUTHERN_REGION - self._datasets[region] = \ - dataset_load(self._southern_hemisphere_filename) + self._datasets[region] = dataset_load(self._southern_hemisphere_filename) dataset_metadata_dump(region, self._datasets[region]) def datasets_normalize(self): @@ -149,6 +159,7 @@ def datasets_normalize(self): Set _datasets_normalized with a tuple containing lower, mean, and upper temperatures for every enabled region """ + def normalization_value(temperatures): """ Return the value to be substracted to temperatures in order to @@ -164,23 +175,34 @@ def normalization_value(temperatures): if self._period == "1850-1900": # The dataset starts from 1850-01-01 00:00:00 # so we calculate the mean of the first 50 years - norm_temp = np.mean(temperatures[:50*factor]) + norm_temp = np.mean(temperatures[: 50 * factor]) elif self._period == "1880-1920": # We have to skip the first 30 years here - norm_temp = np.mean(temperatures[30*factor:70*factor+1]) + norm_temp = np.mean(temperatures[30 * factor : 70 * factor + 1]) else: # this should never happen... - raise Exception(("Unsupported period \"{}\"".format(self._period))) - - dprint(self._verbose, ("The mean anomaly in {0} is about {1:.8f}°C" - .format(self._period, norm_temp))) + raise Exception(('Unsupported period "{}"'.format(self._period))) + + dprint( + self._verbose, + ( + "The mean anomaly in {0} is about {1:.8f}°C".format( + self._period, norm_temp + ) + ), + ) return norm_temp for region in self._datasets: mean = self._datasets[region]["variables"]["tas_mean"] - dprint(self._verbose, - ("dataset ({}): mean ({} entries) \\\n{}" - .format(region, len(mean), mean[:]))) + dprint( + self._verbose, + ( + "dataset ({}): mean ({} entries) \\\n{}".format( + region, len(mean), mean[:] + ) + ), + ) lower = self._datasets[region]["variables"]["tas_lower"] upper = self._datasets[region]["variables"]["tas_upper"] @@ -192,9 +214,14 @@ def normalization_value(temperatures): "mean": np.array(mean) - norm_temp, "upper": np.array(upper) - norm_temp, } - dprint(self._verbose, - ("normalized dataset ({}): mean \\\n{}" - .format(region, np.array(mean) - norm_temp))) + dprint( + self._verbose, + ( + "normalized dataset ({}): mean \\\n{}".format( + region, np.array(mean) - norm_temp + ) + ), + ) def datasets_regions(self): """Return the dataset regions set by the user at command-line""" @@ -215,14 +242,14 @@ def _wget_dataset_file(self, filename): print("Using the local dataset file: {}".format(filename)) except IOError: if self._verbose: - print ("Downloading {} ...".format(filename)) + print("Downloading {} ...".format(filename)) url_dataset = self._hadcrut5_data_url(filename) response = requests.get(url_dataset, stream=True) # Throw an error for bad status codes response.raise_for_status() - with open(filename, 'wb') as handle: + with open(filename, "wb") as handle: for block in response.iter_content(1024): handle.write(block) @@ -260,7 +287,7 @@ def dataset_years(self): # The datasets have all the same length so choose the first one region = list(self._datasets.keys())[0] mean = self._datasets[region]["variables"]["tas_mean"][:] - factor = 1/12 if self.is_monthly_dataset else 1 + factor = 1 / 12 if self.is_monthly_dataset else 1 years = [1850 + (y * factor) for y in range(len(mean))] dprint(self._verbose, "years: \\\n{}".format(np.array(years))) return years