Skip to content

Commit

Permalink
format with ruff, add GHA
Browse files Browse the repository at this point in the history
  • Loading branch information
phobson committed Oct 25, 2024
1 parent 3849b9e commit 19b9cc7
Show file tree
Hide file tree
Showing 14 changed files with 99 additions and 69 deletions.
19 changes: 19 additions & 0 deletions .github/workflows/python-ruff.yml
Original file line number Diff line number Diff line change
@@ -0,0 +1,19 @@
name: ruff 'n' stuff
on: [pull_request]

jobs:
build:
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v3
- name: Install Python
uses: actions/setup-python@v4
with:
python-version: "3.12"
- name: Install dependencies
run: |
python -m pip install --upgrade pip
pip install ruff
# Update output format to enable automatic inline annotations.
- name: Run Ruff
run: ruff check --output-format=github .
4 changes: 1 addition & 3 deletions .github/workflows/python-run-tests.yml
Original file line number Diff line number Diff line change
Expand Up @@ -38,7 +38,5 @@ jobs:
cache-environment: true
post-cleanup: 'all'
- name: Run Python tests
run: python check_pygridgen.py --verbose --durations=10
run: python check_pygridgen.py --verbose --durations=10 --strict
shell: bash -el {0}


2 changes: 1 addition & 1 deletion check_pygridgen.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,7 @@
matplotlib.use('agg')
style.use('classic')

import pygridgen
import pygridgen # noqa: E402

if '--strict' in sys.argv:
sys.argv.remove('--strict')
Expand Down
5 changes: 0 additions & 5 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,4 @@
#!/usr/bin/env python3
# -*- coding: utf-8 -*-
#
# pygridgen documentation build configuration file, created by
# sphinx-quickstart on Sat Jan 16 18:37:00 2016.
Expand All @@ -13,10 +12,6 @@
# All configuration values have a default; values that are commented out
# serve to show the default.

import sys
import os
import shlex
import sphinx

numpydoc_show_class_members = False
autodoc_member_order = 'bysource'
Expand Down
2 changes: 1 addition & 1 deletion docs/tutorial/dochelpers.py
Original file line number Diff line number Diff line change
Expand Up @@ -62,7 +62,7 @@ def plot_grid(grid, data_ax, cell_ax, leg_loc='lower left'):


def read_boundary(example):
df = pandas.read_table("gg_examples/xy.{}".format(example), sep='\s+').fillna(0)
df = pandas.read_table(f"gg_examples/xy.{example}", sep='\s+').fillna(0)
x, y, beta = df['x'].values, df['y'].values, df['b'].values
ul_idx = numpy.nonzero(df['ul'])[0][0] + 1
return x, y, beta, ul_idx
9 changes: 4 additions & 5 deletions pygridgen/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# encoding: utf-8
"""
PYGRIDGEN is a tool for building curvilinear grids.
Expand All @@ -13,10 +12,10 @@
"""


from .grid import *
from . import csa
from . import utils
from .tests import test, teststrict
from .grid import * # noqa: F403
from . import csa # noqa: F401
from . import utils # noqa: F401
from .tests import test, teststrict # noqa: F401

__authors__ = [
'Robert Hetland <hetland@tamu.edu>',
Expand Down
62 changes: 30 additions & 32 deletions pygridgen/boundary_interactor.py
Original file line number Diff line number Diff line change
@@ -1,15 +1,15 @@
import os
try:
import cPickle as pickle
except ImportError:
import pickle

from copy import deepcopy

import numpy
import numpy as np
from numpy import dist
from matplotlib import pyplot
from matplotlib.artist import Artist
from matplotlib.patches import Polygon, CirclePolygon
from matplotlib.patches import Polygon
from matplotlib.lines import Line2D

from .grid import Gridgen
Expand Down Expand Up @@ -37,14 +37,14 @@ def dist_point_to_segment(p, s0, s1):

c2 = np.dot(v, v)
if c2 <= c1:
return numpy.hypot(p, s1)
return np.hypot(p, s1)

b = c1 / c2
pb = s0 + b * v
return numpy.hypot(p, pb)
return np.hypot(p, pb)


class BoundaryInteractor(object): # pragma: no cover
class BoundaryInteractor: # pragma: no cover
"""
Interactive grid creation
Expand Down Expand Up @@ -148,21 +148,21 @@ def _get_ind_under_point(self, event):

# display coords
xt, yt = self._poly.get_transform().numerix_x_y(x, y)
d = numpy.sqrt((xt - event.x)**2 + (yt - event.y)**2)
indseq = numpy.nonzero(numpy.equal(d, numpy.amin(d)))
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
indseq = np.nonzero(np.equal(d, np.amin(d)))
ind = indseq[0]

if d[ind] >= self._epsilon:
ind = None

return ind
except:
except Exception:
# display coords
xy = numpy.asarray(self._poly.xy)
xy = np.asarray(self._poly.xy)
xyt = self._poly.get_transform().transform(xy)
xt, yt = xyt[:, 0], xyt[:, 1]
d = numpy.sqrt((xt - event.x)**2 + (yt - event.y)**2)
indseq = numpy.nonzero(numpy.equal(d, numpy.amin(d)))[0]
d = np.sqrt((xt - event.x)**2 + (yt - event.y)**2)
indseq = np.nonzero(np.equal(d, np.amin(d)))[0]
ind = indseq[0]

if d[ind] >= self._epsilon:
Expand Down Expand Up @@ -232,7 +232,7 @@ def _key_press_callback(self, event):
s1 = xys[i + 1]
d = dist_point_to_segment(p, s0, s1)
if d <= self._epsilon:
self._poly.xy = numpy.array(
self._poly.xy = np.array(
list(self._poly.xy[:i + 1]) +
[(event.xdata, event.ydata)] +
list(self._poly.xy[i + 1:]))
Expand All @@ -243,7 +243,7 @@ def _key_press_callback(self, event):
s1 = xys[0]
d = dist_point_to_segment(p, s0, s1)
if d <= self._epsilon:
self._poly.xy = numpy.array(
self._poly.xy = np.array(
list(self._poly.xy) +
[(event.xdata, event.ydata)])
self._line.set_data(zip(*self._poly.xy))
Expand Down Expand Up @@ -316,7 +316,7 @@ def __init__(self, x, y=None, beta=None, ax=None, proj=None,
**gridgen_options):

if isinstance(x, str):
bry_dict = numpy.load(x)
bry_dict = np.load(x)
x = bry_dict['x']
y = bry_dict['y']
beta = bry_dict['beta']
Expand Down Expand Up @@ -375,7 +375,7 @@ def __init__(self, x, y=None, beta=None, ax=None, proj=None,
self._ax.add_artist(self._sline)

# get the canvas and connect the callback events
cid = self._poly.add_callback(self._poly_changed)
cid = self._poly.add_callback(self._poly_changed) # noqa
self._ind = None # the active vert

self._canvas.mpl_connect('draw_event', self._draw_callback)
Expand All @@ -388,13 +388,12 @@ def __init__(self, x, y=None, beta=None, ax=None, proj=None,
self._motion_notify_callback)

def save_bry(self, bry_file='bry.pickle'):
f = open(bry_file, 'wb')
bry_dict = {'x': self.x, 'y': self.y, 'beta': self.beta}
pickle.dump(bry_dict, f, protocol=-1)
f.close()
with open(bry_file, 'wb') as f:
bry_dict = {'x': self.x, 'y': self.y, 'beta': self.beta}
pickle.dump(bry_dict, f, protocol=-1)

def load_bry(self, bry_file='bry.pickle'):
bry_dict = numpy.load(bry_file)
bry_dict = np.load(bry_file)
x = bry_dict['x']
y = bry_dict['y']
self._line.set_data(x, y)
Expand All @@ -406,9 +405,8 @@ def load_bry(self, bry_file='bry.pickle'):
self._canvas.draw()

def save_grid(self, grid_file='grid.pickle'):
f = open(grid_file, 'wb')
pickle.dump(self.grd, f, protocol=-1)
f.close()
with open(grid_file, 'wb') as f:
pickle.dump(self.grd, f, protocol=-1)

def _get_verts(self):
return zip(self.x, self.y)
Expand All @@ -426,24 +424,24 @@ def get_ydata(self):
y = property(get_ydata)


class edit_mask_mesh(object): # pragma: no cover
class edit_mask_mesh: # pragma: no cover

def _on_key(self, event):
if event.key == 'e':
self._clicking = not self._clicking
pyplot.title('Editing %s -- click "e" to toggle' % self._clicking)
pyplot.title(f'Editing {self._clicking} -- click "e" to toggle')
pyplot.draw()

def _on_click(self, event):
x, y = event.xdata, event.ydata
if event.button == 1 and event.inaxes is not None and self._clicking:
d = (x - self._xc)**2 + (y - self._yc)**2
if isinstance(self.xv, numpy.ma.MaskedArray):
idx = numpy.argwhere(d[~self._xc.mask] == d.min())
if isinstance(self.xv, np.ma.MaskedArray):
idx = np.argwhere(d[~self._xc.mask] == d.min())
else:
idx = numpy.argwhere(d.flatten() == d.min())
idx = np.argwhere(d.flatten() == d.min())
self._mask[idx] = float(not self._mask[idx])
i, j = numpy.argwhere(d == d.min())[0]
i, j = np.argwhere(d == d.min())[0]
self.mask[i, j] = float(not self.mask[i, j])
self._pc.set_array(self._mask)
self._pc.changed()
Expand Down Expand Up @@ -471,13 +469,13 @@ def __init__(self, xv, yv, mask, **kwargs):
self._xc = 0.25 * (xv[1:, 1:] + xv[1:, :-1] + xv[:-1, 1:] + xv[:-1, :-1])
self._yc = 0.25 * (yv[1:, 1:] + yv[1:, :-1] + yv[:-1, 1:] + yv[:-1, :-1])

if isinstance(self.xv, numpy.ma.MaskedArray):
if isinstance(self.xv, np.ma.MaskedArray):
self._mask = mask[~self._xc.mask]
else:
self._mask = mask.flatten()

pyplot.connect('button_press_event', self._on_click)
pyplot.connect('key_press_event', self._on_key)
self._clicking = False
pyplot.title('Editing %s -- click "e" to toggle' % self._clicking)
pyplot.title(f'Editing {self._clicking} -- click "e" to toggle')
pyplot.draw()
3 changes: 1 addition & 2 deletions pygridgen/csa.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,12 @@
import sys
import os
import ctypes
from pkg_resources import resource_filename

import numpy
from matplotlib import pyplot


class CSA(object):
class CSA:
"""
Cubic spline approximation for re-gridding 2D data sets
Expand Down
22 changes: 13 additions & 9 deletions pygridgen/grid.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# encoding: utf-8
import os
import sys
import ctypes
Expand Down Expand Up @@ -42,7 +41,7 @@ def _approximate_erf(x):
return numpy.sign(x) * numpy.sqrt(1.0 - numpy.exp(guts))


class _FocusPoint(object):
class _FocusPoint:
"""
Return a transformed, uniform grid, focused in the x- or
y-direction.
Expand Down Expand Up @@ -114,11 +113,16 @@ def __call__(self, x, y):
return self._do_focus(x), y

def to_dict(self):
output_dict = {'pos': self.pos, 'axis': self.axis, 'factor': self.factor, 'extent': self.extent}
output_dict = {
'pos': self.pos,
'axis': self.axis,
'factor': self.factor,
'extent': self.extent
}
return output_dict


class Focus(object):
class Focus:
"""
Return a container for a sequence of Focus objects.
Expand Down Expand Up @@ -215,7 +219,7 @@ def from_spec(cls, foci):
return f


class CGrid(object):
class CGrid:
"""
Curvilinear Arakawa C-Grid.
Expand Down Expand Up @@ -632,10 +636,10 @@ class CGrid_geo(CGrid):

def __init__(self, lon, lat, proj, use_gcdist=True, ellipse='WGS84'):
try:
import pyproj
import pyproj # noqa
except ImportError:
try:
from mpl_toolkits.basemap import pyproj
from mpl_toolkits.basemap import pyproj # noqa
except ImportError:
raise ImportError('pyproj or mpltoolkits-basemap required')

Expand All @@ -649,7 +653,7 @@ def __init__(self, lon, lat, proj, use_gcdist=True, ellipse='WGS84'):
self.proj = proj
self.geod = pyproj.Geod(ellps=self.ellipse)

super(CGrid_geo, self).__init__(x, y)
super().__init__(x, y)

self.lon_rho, self.lat_rho = self.proj(self.x_rho, self.y_rho,
inverse=True)
Expand Down Expand Up @@ -993,7 +997,7 @@ def generate_grid(self):
x = numpy.ma.masked_where(numpy.isnan(x), x)
y = numpy.ma.masked_where(numpy.isnan(y), y)

super(Gridgen, self).__init__(x, y)
super().__init__(x, y)

def to_spec(self):
""" Export the grid-defining parameters into a JSON-like structure """
Expand Down
2 changes: 0 additions & 2 deletions pygridgen/tests/__init__.py
Original file line number Diff line number Diff line change
@@ -1,8 +1,6 @@
from pkg_resources import resource_filename
from contextlib import contextmanager
from functools import wraps

import pygridgen
from pygridgen.utils import requires

try:
Expand Down
1 change: 0 additions & 1 deletion pygridgen/tests/test_csa.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,7 +9,6 @@
import numpy.testing as nptest

from pygridgen import utils
from pygridgen.tests import raises

from pygridgen import csa

Expand Down
Loading

0 comments on commit 19b9cc7

Please sign in to comment.