Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Move to ruff #35

Merged
merged 1 commit into from
Feb 14, 2024
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
4 changes: 0 additions & 4 deletions .flake8

This file was deleted.

12 changes: 4 additions & 8 deletions .github/workflows/linting.yml
Original file line number Diff line number Diff line change
Expand Up @@ -36,14 +36,10 @@ jobs:
pip install -U pip
pip install ".[tests]"

- name: Lint with isort
- name: Ruff check
if: ${{ always() }}
run: isort --check-only --profile black src tests
run: ruff check .

- name: Lint with black
- name: Ruff format
if: ${{ always() }}
run: black --check src tests

- name: Lint with flake8
if: ${{ always() }}
run: flake8 src tests
run: ruff format . --check
7 changes: 3 additions & 4 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,16 +1,15 @@
#!/usr/bin/env python3

# noqa # pylint: skip-file
import os
import sys
from datetime import date

import xtgeoviz

cwd = os.getcwd()
project_root = os.path.dirname(cwd) + "/src"
sys.path.insert(0, project_root)

from datetime import date

import xtgeoviz

# -- General configuration ---------------------------------------------

Expand Down
37 changes: 27 additions & 10 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,39 +46,37 @@ classifiers = [
]
dynamic = ["version"]
dependencies = [
"xtgeo",
"PyYAML",
"scipy>=1.5.3",
"matplotlib>=3.3.2",
"numpy<2",
"scipy>=1.5.3",
"xtgeo",
]

[project.optional-dependencies]
tests = [
"black",
"coverage>=4.1",
"flake8",
"isort",
"mypy",
"pylint",
"pytest",
"pytest-cov",
"pytest-runner",
"pytest-mock",
"pytest-runner",
"pytest-xdist",
"rstcheck",
"ruff",
"types-PyYAML",
]
docs = [
"autoapi",
"myst-parser",
"sphinx",
"sphinxcontrib-apidoc",
"sphinx-argparse",
"sphinx-autodoc-typehints",
"sphinx-copybutton",
"sphinx-togglebutton",
"sphinx_rtd_theme",
"sphinxcontrib-apidoc",
]

[project.urls]
Expand All @@ -87,11 +85,30 @@ Repository = "https://github.com/equinor/xtgeoviz"
Documentation = "https://github.com/equinor/xtgeoviz"
Issues = "https://github.com/equinor/xtgeoviz/issues"

[tool.black]
[tool.ruff]
line-length = 88

[tool.isort]
profile = "black"
[tool.ruff.lint]
ignore = [
"C901",
]
select = [
"C",
"E",
"F",
"I",
"PIE",
"Q",
"RET",
"RSE",
"SIM",
"TCH",
"TID",
"W",
]

[tool.ruff.lint.isort]
combine-as-imports = true

[tool.mypy]
ignore_missing_imports = true
Expand Down
2 changes: 0 additions & 2 deletions src/xtgeoviz/frontends/_xsectplotting_config.py
Original file line number Diff line number Diff line change
Expand Up @@ -134,8 +134,6 @@
class ConfigError(Exception):
"""Exception for config reading error."""

...


def config_defaults(as_yaml: Optional[bool] = True) -> Union[str, dict]:
"""The YAML file full spec with defaults!
Expand Down
2 changes: 1 addition & 1 deletion src/xtgeoviz/frontends/_xsectplotting_load.py
Original file line number Diff line number Diff line change
Expand Up @@ -58,7 +58,7 @@ def _load_surfaces_generic(self, case="primary"):
Note the surface.name attribute is used to store the display surface name.
"""
config = self.config
sdict = dict()
sdict = {}
names = config["input"]["surfaces"][case]["names"]

if config["input"]["surfaces"][case]["objects"]:
Expand Down
7 changes: 3 additions & 4 deletions src/xtgeoviz/frontends/_xsectplotting_plotting.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
"""Private routines for plotting of xsections."""
from __future__ import annotations

import contextlib
import logging
import os
import os.path
Expand Down Expand Up @@ -182,7 +183,7 @@ def _save_fig(well, pset, xplot):


def _collect_pdf(pset, plotfiles):
if not pset.output_format == "pdf":
if pset.output_format != "pdf":
return

if pset.output_pdfjoin:
Expand Down Expand Up @@ -215,10 +216,8 @@ def _folder_work(pset):

if pset.output_cleanup:
logger.info("Removing previous files in %s", pset.output_plotfolder)
try:
with contextlib.suppress(Exception):
shutil.rmtree(pset.output_plotfolder + "/*")
except Exception: # pylint: disable=broad-except
pass


def _compute_wellcrossings(pset):
Expand Down
8 changes: 5 additions & 3 deletions src/xtgeoviz/frontends/xsectplotting.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,9 +11,11 @@

import yaml

from . import _xsectplotting_config as _cfg
from . import _xsectplotting_load as _load
from . import _xsectplotting_plotting as _plt
from . import (
_xsectplotting_config as _cfg,
_xsectplotting_load as _load,
_xsectplotting_plotting as _plt,
)

APPNAME = "xtgeoviz.xsectplot"

Expand Down
8 changes: 2 additions & 6 deletions src/xtgeoviz/plot/_colortables.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,7 +11,7 @@
def random40():
"""Random but fixed color table with 40 entries, mostly for testing."""

ctable = [
return [
(0.83345071168299956, 0.2382011018575051, 0.6457693086399422),
(0.541018453798349, 0.48038587236806063, 0.9151873938263322),
(0.10882072036344093, 0.8838633180878654, 0.5133890790690832),
Expand Down Expand Up @@ -54,8 +54,6 @@ def random40():
(0.18715791502874501, 0.8748052205404021, 0.43694647042971213),
]

return ctable


def randomc(nlen):
"""Get a truly random color table with nlen entries."""
Expand All @@ -73,7 +71,7 @@ def randomc(nlen):
def xtgeocolors():
"""Get the XTGeo color table which is basic inherited from old IRAP."""

ctable = [
return [
(0.500, 0.500, 0.500), # CGM colour 0 is "dummy" grey
(0.000, 0.000, 0.000),
(1.000, 0.000, 0.000),
Expand Down Expand Up @@ -332,8 +330,6 @@ def xtgeocolors():
(1.000, 1.000, 1.000),
]

return ctable


def colorsfromfile(fname, fformat="rms"):
"""Read a color table from a file."""
Expand Down
18 changes: 10 additions & 8 deletions src/xtgeoviz/plot/_libwrapper.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,15 +24,17 @@ def _version_ge_than(proposed, comparewith):

def matplotlib_colormap(name):
"""Compatibility wrapper for matplotlib colormaps syntax that change across 3.6."""
if _version_ge_than(matplotlib.__version__, "3.6.0"):
return matplotlib.colormaps[name]
else:
return matplotlib.pyplot.cm.get_cmap(name)
return (
matplotlib.colormaps[name]
if _version_ge_than(matplotlib.__version__, "3.6.0")
else matplotlib.pyplot.cm.get_cmap(name)
)


def scipy_gaussianfilter(inputv, sigma):
"""Compatibility wrapper for scipy gaussian_filter syntax that change across 1.8."""
if _version_ge_than(scipy.__version__, "1.8.0"):
return scipy.ndimage.gaussian_filter(inputv, sigma)
else:
return scipy.ndimage.filters.gaussian_filter(inputv, sigma)
return (
scipy.ndimage.gaussian_filter(inputv, sigma)
if _version_ge_than(scipy.__version__, "1.8.0")
else scipy.ndimage.filters.gaussian_filter(inputv, sigma)
)
3 changes: 1 addition & 2 deletions src/xtgeoviz/plot/baseplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -153,8 +153,7 @@ def define_any_colormap(cfile, colorlist=None):
@staticmethod
def get_any_colormap_as_table(cmap):
"""Returns the given color map cmap as a list of RGB tuples."""
cmaplist = [cmap(i) for i in range(cmap.N)]
return cmaplist
return [cmap(i) for i in range(cmap.N)]

def get_colormap_as_table(self):
"""Get the current color map as a list of RGB tuples."""
Expand Down
4 changes: 1 addition & 3 deletions src/xtgeoviz/plot/grid3d_slice.py
Original file line number Diff line number Diff line change
Expand Up @@ -94,9 +94,7 @@ def plot_gridslice(
self._minvalue = minvalue
self._maxvalue = maxvalue

if mode == "column":
pass # self._plot_row()
elif mode == "row":
if mode in ("column", "row"):
pass # self._plot_row()
else:
self._plot_layer()
Expand Down
6 changes: 4 additions & 2 deletions src/xtgeoviz/plot/quickplot.py
Original file line number Diff line number Diff line change
Expand Up @@ -12,14 +12,16 @@
"""
from __future__ import annotations

import pathlib
import warnings
from typing import Optional, Union
from typing import TYPE_CHECKING, Optional, Union

import xtgeo

from .xtmap import Map

if TYPE_CHECKING:
import pathlib


def quickplot(xobj, **kwargs):
"""A common entry point for quickplot."""
Expand Down
43 changes: 19 additions & 24 deletions src/xtgeoviz/plot/xsection.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,20 +4,23 @@
import logging
import math
import warnings
from typing import Optional, Union
from typing import TYPE_CHECKING, Optional, Union

import matplotlib.pyplot as plt
import numpy as np
import numpy.ma as ma
import pandas as pd
import xtgeo
from matplotlib import collections as mc
from matplotlib.colors import LinearSegmentedColormap, ListedColormap
from matplotlib.lines import Line2D

from ._libwrapper import matplotlib_colormap, scipy_gaussianfilter
from .baseplot import BasePlot

if TYPE_CHECKING:
from matplotlib.colors import LinearSegmentedColormap, ListedColormap


logger = logging.getLogger(__name__)


Expand Down Expand Up @@ -535,7 +538,7 @@ def _plot_well_zlog(self, df, ax, bba, zonelogname, logwidth=4, legend=False):
idx = self.colormap_zonelog_dict

# adjust for zoneshift.
idx_zshift = dict()
idx_zshift = {}
for key in idx:
idx_zshift[key - zshift + 1] = idx[key]

Expand All @@ -554,14 +557,11 @@ def _plot_well_zlog(self, df, ax, bba, zonelogname, logwidth=4, legend=False):
zrecord = self._well.get_logrecord(zonelogname)
zrecord = {val: zname for val, zname in zrecord.items() if val >= 0}

zcolors = dict()
zcolors = {}
for zone in zrecord:
if isinstance(idx[zone], str):
color = idx[zone]
else:
color = ctable[idx[zone]]

zcolors[zrecord[zone]] = color
zcolors[zrecord[zone]] = (
idx[zone] if isinstance(idx[zone], str) else ctable[idx[zone]]
)

self._drawproxylegend(ax, bba, items=zcolors, title="Zonelog")

Expand Down Expand Up @@ -646,12 +646,9 @@ def _plot_well_perflog(self, df, ax, bba, perflogname, logwidth=12, legend=True)

pcolors = {}
for perf in precord:
if isinstance(idx[perf], str):
color = idx[perf]
else:
color = ctable[idx[perf]]

pcolors[precord[perf]] = color
pcolors[precord[perf]] = (
idx[perf] if isinstance(idx[perf], str) else ctable[idx[perf]]
)

self._drawproxylegend(ax, bba, items=pcolors, title="Perforations")

Expand Down Expand Up @@ -725,10 +722,7 @@ def _plot_well_crossings(dfr, ax, wcross, names=True, years=False):
text = xtgeo.Well.get_short_wellname(row.CWELL)

if years:
if names:
text = text + "\n" + row.CYEAR
else:
text = row.CYEAR
text = text + "\n" + row.CYEAR if names else row.CYEAR

if names or years:
ax.annotate(
Expand All @@ -737,9 +731,10 @@ def _plot_well_crossings(dfr, ax, wcross, names=True, years=False):
xy=(dfrc.R_HLEN[minindx], row.Z_TVDSS),
xytext=placings[modulo],
textcoords="offset points",
arrowprops=dict(
arrowstyle="->", connectionstyle="angle3,angleA=0,angleB=90"
),
arrowprops={
"arrowstyle": "->",
"connectionstyle": "angle3,angleA=0,angleB=90",
},
color="black",
)

Expand Down Expand Up @@ -1002,7 +997,7 @@ def plot_surfaces(

slegend = surfacenames

if self._colormap.N < nlen:
if nlen > self._colormap.N:
raise ValueError(
f"Too few colors in color table ({self._colormap.N}) "
f"vs number of surfaces ({nlen})"
Expand Down
Loading
Loading