Skip to content

Commit

Permalink
Merge pull request #223 from xylar/fix-flake8
Browse files Browse the repository at this point in the history
Fix `flake8` lint in `geometric_features`
  • Loading branch information
xylar authored Dec 21, 2024
2 parents c06adaf + e52048c commit 383777e
Show file tree
Hide file tree
Showing 11 changed files with 57 additions and 50 deletions.
8 changes: 8 additions & 0 deletions .github/workflows/build_workflow.yml
Original file line number Diff line number Diff line change
Expand Up @@ -37,12 +37,20 @@ jobs:
with:
python-version: "3.10"

- if: ${{ steps.skip_check.outputs.should_skip != 'true' }}
id: file_changes
uses: trilom/[email protected]
with:
output: ' '

- if: ${{ steps.skip_check.outputs.should_skip != 'true' }}
# Run all pre-commit hooks on all the files.
# Getting only staged files can be tricky in case a new PR is opened
# since the action is run on a branch in detached head state
name: Install and Run Pre-commit
uses: pre-commit/[email protected]
with:
extra_args: --files ${{ steps.file_changes.outputs.files}}

build:
name: test geometric_features - python ${{ matrix.python-version }}
Expand Down
12 changes: 6 additions & 6 deletions geometric_features/aggregation/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,11 +58,11 @@ def get_aggregator_by_name(region_group):
'date': '20201123',
'function': subbasins},
'ISMIP6 Greenland Regions': {'prefix': 'ismip6GreenlandRegions',
'date': '20240510',
'function': ismip6_greenland},
'NASA Greenland Regions': {'prefix':'nasaGreenlandRegions',
'date':'20241017',
'function': nasa_greenland},
'date': '20240510',
'function': ismip6_greenland},
'NASA Greenland Regions': {'prefix': 'nasaGreenlandRegions',
'date': '20241017',
'function': nasa_greenland},
'ISMIP6 Regions': {'prefix': 'ismip6Regions',
'date': '20210201',
'function': ismip6},
Expand All @@ -75,7 +75,7 @@ def get_aggregator_by_name(region_group):
'Transport Transects': {'prefix': 'transportTransects',
'date': '20210323',
'function': transport},
'Arctic Transport Transects': {'prefix': 'arcticTransportTransects',
'Arctic Transport Transects': {'prefix': 'arcticTransportTransects', # noqa: E501
'date': '20220926',
'function': arctic_transport}}

Expand Down
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
def nasa_greenland(gf):
"""
Aggregate NASA Greenland ice sheet basin regions extended to continental shelf.
Aggregate NASA Greenland ice sheet basin regions extended to continental
shelf.
Parameters
----------
Expand Down
4 changes: 2 additions & 2 deletions geometric_features/aggregation/seaice/historical_sea_ice.py
Original file line number Diff line number Diff line change
Expand Up @@ -27,8 +27,8 @@ def qgreenland(gf):
'May Historical Median Sea Ice Extent',
'November Historical Median Sea Ice Extent',
'October Historical Median Sea Ice Extent',
'September Historical Median Sea Ice Extent'
]
'September Historical Median Sea Ice Extent']

fc = gf.read(componentName='seaice', objectType='region',
featureNames=regions)

Expand Down
33 changes: 17 additions & 16 deletions geometric_features/feature_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -261,7 +261,7 @@ def difference(self, maskingFC, show_progress=False):
featureCount = len(self.features)
maskCount = len(maskingFC.features)

totalCount = featureCount*maskCount
totalCount = featureCount * maskCount

if show_progress:
print('Masking features...')
Expand All @@ -285,7 +285,7 @@ def difference(self, maskingFC, show_progress=False):
masked = False
for maskIndex, maskFeature in enumerate(maskingFC.features):
if show_progress:
bar.update(maskIndex + featureIndex*maskCount)
bar.update(maskIndex + featureIndex * maskCount)
maskShape = shapely.geometry.shape(maskFeature['geometry'])
if featureShape.intersects(maskShape):
masked = True
Expand Down Expand Up @@ -613,7 +613,8 @@ def _validate_feature(feature):
raise KeyError(f'Feature {name} missing [{outerKey}] key')
for innerKey in required[outerKey]:
if innerKey not in feature[outerKey]:
raise KeyError(f'Feature {name} missing [{outerKey}][{innerKey}] key')
raise KeyError(
f'Feature {name} missing [{outerKey}][{innerKey}] key')

geomType = feature['geometry']['type']
objectType = feature['properties']['object']
Expand Down Expand Up @@ -666,18 +667,18 @@ def _validate_feature(feature):

def _split_geometry_crossing_antimeridian(geometry):
def _to_polar(lon, lat):
phi = np.pi/180.*(np.mod(lon + 180., 360.) - 180.)
radius = np.pi/180.*(90. - sign*lat)
phi = np.pi / 180. * (np.mod(lon + 180., 360.) - 180.)
radius = np.pi / 180. * (90. - sign * lat)

# nudge points at +/- 180 out of the way so they don't intersect the
# testing wedge
phi = np.sign(phi) * \
np.where(np.abs(phi) > np.pi - 1.5*epsilon,
np.pi - 1.5*epsilon, np.abs(phi))
np.where(np.abs(phi) > np.pi - 1.5 * epsilon,
np.pi - 1.5 * epsilon, np.abs(phi))
# radius = np.where(radius < 1.5*epsilon, 1.5*epsilon, radius)

x = radius*np.sin(phi)
y = radius*np.cos(phi)
x = radius * np.sin(phi)
y = radius * np.cos(phi)
if isinstance(lon, list):
x = x.tolist()
y = y.tolist()
Expand All @@ -688,17 +689,17 @@ def _to_polar(lon, lat):
return x, y

def _from_polar(x, y):
radius = np.sqrt(np.array(x)**2+np.array(y)**2)
radius = np.sqrt(np.array(x)**2 + np.array(y)**2)
phi = np.arctan2(x, y)

# close up the tiny gap
radius = np.where(radius < 2*epsilon, 0., radius)
radius = np.where(radius < 2 * epsilon, 0., radius)
phi = np.sign(phi) * \
np.where(np.abs(phi) > np.pi - 2*epsilon,
np.where(np.abs(phi) > np.pi - 2 * epsilon,
np.pi, np.abs(phi))

lon = 180./np.pi*phi
lat = sign*(90. - 180./np.pi*radius)
lon = 180. / np.pi * phi
lat = sign * (90. - 180. / np.pi * radius)

if isinstance(x, list):
lon = lon.tolist()
Expand All @@ -717,8 +718,8 @@ def _from_polar(x, y):
(epsilon, -np.pi)])

featureShape = shapely.geometry.shape(geometry)
sign = (2.*(0.5*(featureShape.bounds[1] + featureShape.bounds[3]) >= 0.) -
1.)
sign_mask = featureShape.bounds[1] + featureShape.bounds[3] >= 0.
sign = 2. * sign_mask - 1.
polarShape = shapely.ops.transform(_to_polar, featureShape)

if not polarShape.intersects(antimeridianWedge):
Expand Down
13 changes: 7 additions & 6 deletions geometric_features/plot.py
Original file line number Diff line number Diff line change
Expand Up @@ -83,17 +83,17 @@ def subdivide_line_string(lineString, periodic=False):
coords.append(coords[0])

outCoords = [coords[0]]
for iVert in range(len(coords)-1):
for iVert in range(len(coords) - 1):
segment = shapely.geometry.LineString([coords[iVert],
coords[iVert+1]])
coords[iVert + 1]])
if segment.length < maxLength:
outCoords.append(coords[iVert+1])
outCoords.append(coords[iVert + 1])
else:
# we need to subdivide this segment
subsegment_count = int(np.ceil(segment.length/maxLength))
subsegment_count = int(np.ceil(segment.length / maxLength))
for index in range(subsegment_count):
point = segment.interpolate(
float(index+1)/float(subsegment_count),
float(index + 1) / float(subsegment_count),
normalized=True)
outCoords.append(point.coords[0])

Expand Down Expand Up @@ -126,7 +126,8 @@ def subdivide_line_string(lineString, periodic=False):
elif geomtype == 'Point':
newGeometry = geometry
else:
print(f"Warning: subdividing geometry type {geomtype} is not supported.")
print(
f"Warning: subdividing geometry type {geomtype} is not supported.")
newGeometry = geometry

return newGeometry
15 changes: 7 additions & 8 deletions geometric_features/test/test_aggregation.py
Original file line number Diff line number Diff line change
@@ -1,5 +1,3 @@
import pytest

from geometric_features import GeometricFeatures
from geometric_features.aggregation import (antarctic, arctic_ocean,
arctic_seaice, arctic_transport,
Expand All @@ -8,18 +6,19 @@
ismip6_greenland, moc,
nasa_greenland, qgreenland_seaice,
subbasins, transport)
from geometric_features.test import TestCase, loaddatadir
from geometric_features.test import TestCase


@pytest.mark.usefixtures('loaddatadir')
class TestAggregation(TestCase):

def test_get_aggregator_by_name(self):
gf = GeometricFeatures()
names = ['Antarctic Regions', 'Arctic Ocean Regions', 'ISMIP6 Greenland Regions',
'NASA Greenland Regions', 'Arctic Sea Ice Regions', 'Ocean Basins',
'Ice Shelves', 'Ocean Subbasins', 'ISMIP6 Regions', 'MOC Basins', 'Historical Sea Ice',
'Transport Transects', 'Arctic Transport Transects']
names = ['Antarctic Regions', 'Arctic Ocean Regions',
'ISMIP6 Greenland Regions', 'NASA Greenland Regions',
'Arctic Sea Ice Regions', 'Ocean Basins', 'Ice Shelves',
'Ocean Subbasins', 'ISMIP6 Regions', 'MOC Basins',
'Historical Sea Ice', 'Transport Transects',
'Arctic Transport Transects']

for name in names:
function, prefix, date = get_aggregator_by_name(name)
Expand Down
4 changes: 2 additions & 2 deletions geometric_features/test/test_feature_collection.py
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@

from geometric_features import (FeatureCollection, GeometricFeatures,
read_feature_collection)
from geometric_features.test import TestCase, loaddatadir
from geometric_features.test import TestCase, loaddatadir # noqa: F401


@pytest.mark.usefixtures('loaddatadir')
Expand Down Expand Up @@ -393,7 +393,7 @@ def test_plot(self):

projection = 'cyl'

fig = fc.plot(projection, maxLength=4.0, figsize=(12,12),
fig = fc.plot(projection, maxLength=4.0, figsize=(12, 12),
colors=colors, dpi=200)

dest_filename = str(self.datadir.join('plot.png'))
Expand Down
9 changes: 3 additions & 6 deletions geometric_features/test/test_features_and_tags.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,10 @@
import difflib
import os

import pytest

from geometric_features.test import TestCase, loaddatadir
from geometric_features.test import TestCase
from geometric_features.utils import write_feature_names_and_tags


@pytest.mark.usefixtures('loaddatadir')
class TestFeaturesAndTags(TestCase):

def test_features_and_tags(self):
Expand Down Expand Up @@ -36,5 +33,5 @@ def test_features_and_tags(self):

if count != 0:
raise ValueError(
'Unexpected differences in geometric_features/features_and_tags.json '
'compared with the results of geometric_features.utils.write_feature_names_and_tags()')
'Unexpected differences in geometric_features/features_and_tags.json ' # noqa: E501
'compared with the results of geometric_features.utils.write_feature_names_and_tags()') # noqa: E501
4 changes: 2 additions & 2 deletions geometric_features/test/test_geometric_features.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,7 +3,7 @@
import pytest

from geometric_features import GeometricFeatures
from geometric_features.test import TestCase, loaddatadir
from geometric_features.test import TestCase, loaddatadir # noqa: F401


@pytest.mark.usefixtures('loaddatadir')
Expand Down Expand Up @@ -138,5 +138,5 @@ def test_split(self, component='ocean', object_type='region',
for feature in fc.features:
name = feature['properties']['name']
subdir = name.replace(' ', '_')
path = f'{self.datadir}/{component}/{object_type}/{subdir}/{object_type}.geojson'
path = f'{self.datadir}/{component}/{object_type}/{subdir}/{object_type}.geojson' # noqa: E501
assert os.path.exists(path)
2 changes: 1 addition & 1 deletion geometric_features/utils.py
Original file line number Diff line number Diff line change
Expand Up @@ -64,5 +64,5 @@ def provenance_command():
call = ' '.join(sys.argv)
host = socket.gethostname()
sep = ' : '
provstr = sep.join([curtime, host, user, cwd, call]) + ';'
provstr = sep.join([curtime, host, user, cwd, call]) + ';'
return provstr

0 comments on commit 383777e

Please sign in to comment.