Skip to content

Commit

Permalink
STY, LINT: resolve numerous style/lint flags
Browse files Browse the repository at this point in the history
- resolved only simple ones, more severe ones remaining
  • Loading branch information
fkuehlein committed Jul 27, 2023
1 parent 6b96ced commit b9a31aa
Show file tree
Hide file tree
Showing 32 changed files with 428 additions and 436 deletions.
4 changes: 0 additions & 4 deletions examples/tutorials/climate_network_cartopy_plotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -176,7 +176,3 @@
# Plot with cartopy and matplotlib
cn_plot.generate_plots(file_name="climate_network_measures",
title_on=False, labels_on=True)




59 changes: 24 additions & 35 deletions src/pyunicorn/climate/cartopy_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -20,24 +20,15 @@
multivariate data and generating time series surrogates.
"""

import os
import glob
# time handling
# import datetime

import numpy as np
import matplotlib.pyplot as plt

# Import Ngl support functions for plotting, map projections etc.
try:
import cartopy
import cartopy.crs as ccrs
import cartopy.feature as cf
except ImportError:
print("climate: Package cartopy could not be loaded. Some functionality "
"in class MapPlots might not be available!")

import cartopy.crs as ccrs
import cartopy.feature as cf

#
# Define class CartopyPlots
#
Expand Down Expand Up @@ -84,18 +75,18 @@ def __init__(self, grid, title):

# get spatial dims
self.lon = self.grid.convert_lon_coordinates(self.grid.lon_sequence())
# self.lon = self.grid.lon_sequence()
self.lat = self.grid.lat_sequence()
self.gridsize_lon = len(self.lon)
self.gridsize_lat = len(self.lat)
self.lon_min = self.grid.boundaries()["lon_min"]
self.lon_max = self.grid.boundaries()["lon_max"]
self.lat_min = self.grid.boundaries()["lat_min"]
self.lat_max = self.grid.boundaries()["lat_max"]

# extent of data will also give extent of world map
self.data_extent = [self.lon_min, self.lon_max, self.lat_min, self.lat_max]

self.data_extent = [self.lon_min, self.lon_max,
self.lat_min, self.lat_max]

print("Created plot class.")

def add_dataset(self, title, data):
Expand Down Expand Up @@ -126,52 +117,50 @@ def generate_plots(self, file_name, title_on=True, labels_on=True):
plotted.
"""

for dataset in self.map_data:
for dataset in self.map_data:

# Generate figue
fig = plt.figure()

# create map plot
ax = plt.axes(projection=self.projection)

# make it a class feature, as to work with it from outside
# self.ax = ax

# create some standards of plotting that can be adjusted
# before calling generate_cartopy_plot
# before calling generate_cartopy_plot
# adjust size and plot coastlines and borders
ax.set_extent(self.data_extent, crs=self.crs)
# ax.set_global()
ax.add_feature(cf.COASTLINE.with_scale("50m"), lw=0.5)
ax.add_feature(cf.BORDERS.with_scale("50m"), lw=0.2)
ax.add_feature(cf.BORDERS.with_scale("50m"), lw=0.2)

# Draw gridlines in degrees over map
gl = ax.gridlines(crs=self.crs, draw_labels=True,
linewidth=.6, color='gray', alpha=0.5, linestyle='-.')
linewidth=.6, color='gray',
alpha=0.5, linestyle='-.')
gl.xlabel_style = {"size": 7}
gl.ylabel_style = {"size": 7}
gl.ylabel_style = {"size": 7}
# plot data upon map
ax = plt.tricontourf(self.lon, self.lat, dataset["data"], extent = self.data_extent, transform = self.crs)

ax = plt.tricontourf(self.lon, self.lat, dataset["data"],
extent=self.data_extent, transform=self.crs)
ax = plt.colorbar(shrink=0.5)

# plot main title
if title_on:
plt.suptitle(self.title)

# plot subtitles
if labels_on:
plt.title(dataset["title"])

# save figures at current dir
file_extension = dataset["title"] + ".png"
file_extension = file_extension.replace(" ", "")

fig.savefig(file_name + "_" + file_extension)

plt.close()

print("Created and saved plots @ current directory.")


plt.close()

print("Created and saved plots @ current directory.")
13 changes: 6 additions & 7 deletions src/pyunicorn/climate/climate_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -126,8 +126,8 @@ def __str__(self):
Local connections filtered out: False
"""
return (f'ClimateNetwork:\n{GeoNetwork.__str__(self)}\n' +
f'Threshold: {self.threshold()}\n' +
f'Local connections filtered out: {self.non_local()}')
f'Threshold: {self.threshold()}\n' +
f'Local connections filtered out: {self.non_local()}')

def clear_cache(self, irreversible=False):
"""
Expand Down Expand Up @@ -164,9 +164,8 @@ def _regenerate_network(self):
# Load and save ClimateNetwork object
#

def save(self, filename_network, filename_grid=None,
filename_similarity_measure=None, fileformat=None, *args,
**kwds):
def save(self, filename_network, filename_grid=None, fileformat=None,
filename_similarity_measure=None, *args, **kwds):
"""
Save the ClimateNetwork object to files.
Expand All @@ -193,8 +192,6 @@ def save(self, filename_network, filename_grid=None,
object is to be stored.
:arg str filename_grid: The name of the file where the GeoGrid object
is to be stored (including ending).
:arg str filename_similarity_measure: The name of the file where the
similarity measure matrix is to be stored.
:arg str fileformat: the format of the file (if one wants to override
the format determined from the filename extension, or the filename
itself is a stream). ``None`` means auto-detection. Possible
Expand All @@ -205,6 +202,8 @@ def save(self, filename_network, filename_grid=None,
(DIMACS format), ``"edgelist"``, ``"edges"`` or ``"edge"`` (edge
list), ``"adjacency"`` (adjacency matrix), ``"pickle"`` (Python
pickled format), ``"svg"`` (Scalable Vector Graphics).
:arg str filename_similarity_measure: The name of the file where the
similarity measure matrix is to be stored.
"""
# Store GeoNetwork
GeoNetwork.save(self, filename_network=filename_network,
Expand Down
4 changes: 2 additions & 2 deletions src/pyunicorn/climate/coupled_climate_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -146,8 +146,8 @@ def __str__(self):
"""
Return a string representation of CoupledClimateNetwork object.
"""
return f'CoupledClimateNetwork:\n{ClimateNetwork.__str__(self)}\
\nN1: {self.N_1}\nN2: self.N_2'
return f'CoupledClimateNetwork:\n{ClimateNetwork.__str__(self)} \
\nN1: {self.N_1}\nN2: self.N_2'

#
# Define methods for handling the coupled network
Expand Down
8 changes: 4 additions & 4 deletions src/pyunicorn/climate/eventseries_climatenetwork.py
Original file line number Diff line number Diff line change
Expand Up @@ -112,9 +112,9 @@ def __init__(self, data, method='ES', taumax=np.inf, lag=0.0,

method_types = ['ES', 'ECA', 'ES_pval', 'ECA_pval']
if method not in method_types:
raise IOError(f"Method input must be: {method_types[0]},\
{method_types[1]},\
{method_types[2]}, or {method_types[3]}!")
raise IOError(f"Method input must be:"
f"{method_types[0]}, {method_types[1]},"
f"{method_types[2]}, or {method_types[3]}!")

etypes = ["directed", "symmetric", "antisym", "mean", "max", "min"]
if symmetrization not in etypes:
Expand All @@ -125,7 +125,7 @@ def __init__(self, data, method='ES', taumax=np.inf, lag=0.0,

self.__method = method
self.__symmetry = symmetrization
self.directed = (self.__symmetry == "directed")
self.directed = self.__symmetry == "directed"
self.__es_type = method
self.__window_type = window_type
self.__p_value = p_value
Expand Down
6 changes: 2 additions & 4 deletions src/pyunicorn/climate/map_plots.py
Original file line number Diff line number Diff line change
Expand Up @@ -22,8 +22,6 @@

import os
import glob
# time handling
# import datetime

import numpy as np

Expand Down Expand Up @@ -203,7 +201,7 @@ def generate_multiple_map_plots(self, map_names, map_scales, title_on=True,
list of dictionaries. Stores the plots in the file indicated by
filename in the current directory.
"""
for k in range(len(self.map_mult_data)):
for k, map_data in enumerate(self.map_mult_data):
# Set resources
resources = self.resources

Expand All @@ -225,7 +223,7 @@ def generate_multiple_map_plots(self, map_names, map_scales, title_on=True,
# Generate map plots
#

for dataset in self.map_mult_data[k]:
for dataset in map_data:
# Set title
if labels_on:
resources.lbTitleString = dataset["title"]
Expand Down
2 changes: 1 addition & 1 deletion src/pyunicorn/climate/rainfall.py
Original file line number Diff line number Diff line change
Expand Up @@ -242,7 +242,7 @@ def calculate_top_events(rainfall, event_threshold):

up_mask = rainfall <= onelist[uplimit-1]

no_rain_mask = (rainfall != 0)
no_rain_mask = rainfall != 0

final_mask = down_mask & up_mask & no_rain_mask

Expand Down
5 changes: 3 additions & 2 deletions src/pyunicorn/climate/tsonis.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,9 @@ def __str__(self):
Local connections filtered out: False
Use only data points from winter months: False
"""
return (f'TsonisClimateNetwork:\n{ClimateNetwork.__str__(self)}\n' +
f'Use only data points from winter months: {self.winter_only()}')
return (f'TsonisClimateNetwork:\n{ClimateNetwork.__str__(self)}\n'
f'Use only data points from winter months: '
f'{self.winter_only()}')

#
# Methods for testing purposes
Expand Down
12 changes: 5 additions & 7 deletions src/pyunicorn/core/data.py
Original file line number Diff line number Diff line change
Expand Up @@ -115,10 +115,9 @@ def __str__(self):
if self.file_name:
self.print_data_info()

return ('Data: %i grid points, %i measurements.\n'
'Geographical boundaries:\n%s') % (
self.grid.N, self.grid.n_grid_points,
self.grid.print_boundaries())
return (f"Data: {self.grid.N} grid points, "
f"{self.grid.n_grid_points} measurements.\n"
f"Geographical boundaries:\n{self.grid.print_boundaries()}")

def set_silence_level(self, silence_level):
"""
Expand Down Expand Up @@ -397,7 +396,7 @@ def print_data_info(self):
print(name + ":", getattr(f, name))
print("Variables (size):")
for name, obj in f.variables.items():
print("%s (%i)" % (name, len(obj)))
print(f"{name} ({len(obj)})")
f.close()

def observable(self):
Expand Down Expand Up @@ -592,8 +591,7 @@ def rescale(array, var_type):
array /= scale_factor
scaled_array = array.astype('uint8')
else:
print("Data type %s variable %s for rescaling array "
"not supported!" % var_type)
print(f"Data type {var_type} not supported!")
scale_factor = 1.
add_offset = 0.

Expand Down
4 changes: 2 additions & 2 deletions src/pyunicorn/core/geo_grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -88,8 +88,8 @@ def __str__(self):
"""
Return a string representation of the GeoGrid object.
"""
return 'GeoGrid: %i grid points, %i timesteps.' % (
self._grid_size['space'], self._grid_size['time'])
return (f"GeoGrid: {self._grid_size['space']} grid points, "
f"{self._grid_size['time']} timesteps.")

def clear_cache(self):
"""
Expand Down
9 changes: 4 additions & 5 deletions src/pyunicorn/core/geo_network.py
Original file line number Diff line number Diff line change
Expand Up @@ -1044,9 +1044,9 @@ def boundary(self, nodes, geodesic=True, gap=0.0):
import stripack # @UnresolvedImport
# tries to import stripack.so which must have been compiled with
# f2py -c -m stripack stripack.f90
except ImportError:
raise RuntimeError("NOTE: stripack.so not available, boundary() \
won't work.")
except ImportError as err:
raise RuntimeError("NOTE: stripack.so not available, "
"boundary() won't work.") from err

N = self.N
nodes_set = set(nodes)
Expand Down Expand Up @@ -1174,8 +1174,7 @@ def boundary(self, nodes, geodesic=True, gap=0.0):
rep = self.cartesian2latlon((pos1+pos2)/2)
mind2 = d2
latlon_shape.append(self.cartesian2latlon(partial_shape[-1]))
for it, _ in enumerate(partial_fullshape):
pos1 = partial_fullshape[it]
for pos1 in partial_fullshape:
latlon_fullshape.append(self.cartesian2latlon(pos1))

boundary.append(partial_boundary)
Expand Down
15 changes: 6 additions & 9 deletions src/pyunicorn/core/grid.py
Original file line number Diff line number Diff line change
Expand Up @@ -99,8 +99,8 @@ def __str__(self):
"""
Return a string representation of the Grid object.
"""
return 'Grid: %i grid points, %i timesteps.' % (
self._grid_size['space'], self._grid_size['time'])
return (f"Grid: {self._grid_size['space']} grid points, "
f"{self._grid_size['time']} timesteps.")

#
# Functions for loading and saving the Grid object
Expand All @@ -114,9 +114,8 @@ def save(self, filename):
(including ending).
"""
try:
f = open(filename, 'wb')
pickle.dump(self, f)
f.close()
with open(filename, 'wb') as f:
pickle.dump(self, f)
except IOError:
print("An error occurred while saving Grid instance to "
f"pickle file {filename}")
Expand All @@ -132,10 +131,8 @@ def Load(filename):
:return: :class:`Grid` instance.
"""
try:
f = open(filename, 'rb')
grid = pickle.load(f)
f.close()

with open(filename, 'rb') as f:
grid = pickle.load(f)
return grid
except IOError:
print("An error occurred while loading Grid instance from "
Expand Down
13 changes: 7 additions & 6 deletions src/pyunicorn/core/interacting_networks.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@
import numpy as np
from numpy import random

from ._ext.types import to_cy, ADJ, NODE, WEIGHT, DWEIGHT, FIELD, DFIELD
from ._ext.types import to_cy, ADJ, NODE, DWEIGHT, DFIELD
from ._ext.numerics import _randomlySetCrossLinks, _randomlyRewireCrossLinks, \
_cross_transitivity, _nsi_cross_transitivity, _cross_local_clustering, \
_nsi_cross_local_clustering
Expand Down Expand Up @@ -805,8 +805,8 @@ def cross_global_clustering(self, node_list1, node_list2):
subnetworks.
"""
# Get cross local clustering sequences
cc = InteractingNetworks.cross_local_clustering(self, node_list1,
node_list2)
cc = InteractingNetworks.cross_local_clustering(self,
node_list1, node_list2)
return cc.mean()

def cross_global_clustering_sparse(self, node_list1, node_list2):
Expand Down Expand Up @@ -995,7 +995,7 @@ def cross_average_path_length(self, node_list1, node_list2,
subnetworks.
"""
path_lengths = InteractingNetworks.cross_path_lengths(
self, node_list1, node_list2, link_attribute)
self, node_list1, node_list2, link_attribute)

return self._calculate_general_average_path_length(
path_lengths, internal=False)
Expand Down Expand Up @@ -1427,8 +1427,9 @@ def cross_closeness(self, node_list1, node_list2, link_attribute=None):
:rtype: 1D arrays [index]
:return: the cross closeness sequence.
"""
path_lengths = InteractingNetworks.cross_path_lengths(self, node_list1,
node_list2, link_attribute)
path_lengths = InteractingNetworks.cross_path_lengths(
self, node_list1, node_list2, link_attribute)

return self._calculate_general_closeness(path_lengths, internal=False)

def internal_closeness(self, node_list, link_attribute=None):
Expand Down
Loading

0 comments on commit b9a31aa

Please sign in to comment.