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

Enable linting with ruff #8

Merged
merged 9 commits into from
Jan 7, 2025
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
20 changes: 20 additions & 0 deletions .editorconfig
Original file line number Diff line number Diff line change
@@ -0,0 +1,20 @@
# EditorConfig - http://EditorConfig.org

# top-most EditorConfig file
root = true

# Unix-style newlines with a newline ending every file
[*]
end_of_line = lf
insert_final_newline = true
trim_trailing_whitespace = false

# Matches multiple files with brace expansion notation
# Set default charset
[*.{c,py}]
charset = utf-8

# tab indentation
[*.py]
indent_style = tab
indent_size = 4
14 changes: 14 additions & 0 deletions .github/workflows/ci.yml
Original file line number Diff line number Diff line change
Expand Up @@ -14,6 +14,20 @@ concurrency:
cancel-in-progress: true

jobs:
typos:
name: Spelling (typos)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: crate-ci/typos@master

ruff:
name: Linting (ruff)
runs-on: ubuntu-latest
steps:
- uses: actions/checkout@v4
- uses: chartboost/ruff-action@v1

test:
name: Unittest (${{ matrix.os }}/py${{ matrix.python-version }})
runs-on: ${{ matrix.os }}
Expand Down
13 changes: 4 additions & 9 deletions chspy/__init__.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,8 @@
from ._chspy import (
Anchor, CubicHermiteSpline, Extrema,
interpolate, interpolate_vec, interpolate_diff, interpolate_diff_vec,
extrema_from_anchors,
norm_sq_interval, norm_sq_partial, scalar_product_interval, scalar_product_partial,
match_anchors, join,
)
from ._chspy import Anchor, CubicHermiteSpline, Extrema, extrema_from_anchors, interpolate, interpolate_diff, interpolate_diff_vec, interpolate_vec, join, match_anchors, norm_sq_interval, norm_sq_partial, scalar_product_interval, scalar_product_partial # noqa: F401


try:
from .version import version as __version__
from .version import version as __version__ # noqa: F401
except ImportError:
from warnings import warn
warn('Failed to find (autogenerated) version.py. Do not worry about this unless you really need to know the version.')
warn("Failed to find (autogenerated) version.py. Do not worry about this unless you really need to know the version.", stacklevel=1)
37 changes: 18 additions & 19 deletions chspy/_chspy.py
Original file line number Diff line number Diff line change
@@ -1,10 +1,11 @@
#!/usr/bin/python3
# -*- coding: utf-8 -*-

import numpy as np
from bisect import insort, bisect_left, bisect_right
from bisect import bisect_left, bisect_right, insort
from warnings import warn

import numpy as np


def rel_dist(x,y):
x = np.asarray(x)
y = np.asarray(y)
Expand Down Expand Up @@ -131,7 +132,7 @@ def norm_sq_interval(anchors, indices):

def norm_sq_partial(anchors, indices, start):
"""
Returns the sqared norm of the interpolant of `anchors` for the `indices`, but only taking into account the time after `start`.
Returns the squared norm of the interpolant of `anchors` for the `indices`, but only taking into account the time after `start`.
"""
q = (anchors[1].time-anchors[0].time)
z = (start-anchors[1].time) / q
Expand Down Expand Up @@ -201,7 +202,7 @@ def scalar_product_partial(anchors, indices_1, indices_2, start):
vector_2, [1,2]
)*q

class Extrema(object):
class Extrema:
"""
Class for containing the extrema and their positions in `n` dimensions. These can be accessed via the attributes `minima`, `maxima`, `arg_min`, and `arg_max`.
"""
Expand Down Expand Up @@ -269,7 +270,7 @@ def extrema_from_anchors(anchors,beginning=None,end=None,target=None):
A = 1/(2*a + b - 2*c + d)
B = a + 2*b/3 - c + d/3
for sign in (-1,1):
with np.errstate(invalid='ignore'):
with np.errstate(invalid="ignore"):
x = (B+sign*np.sqrt(radicant)/3)*A
extrema.update(
retransform(x),
Expand Down Expand Up @@ -479,7 +480,7 @@ def constant(self,state,time=0):
"""

if self:
warn("The spline already contains points. This will remove them. Be sure that you really want this.")
warn("The spline already contains points. This will remove them. Be sure that you really want this.", stacklevel=2)
self.clear()

self.append(( time-1., state, np.zeros_like(state) ))
Expand All @@ -495,7 +496,7 @@ def from_function(self,function,times_of_interest=None,max_anchors=100,tol=5):
assert len(times_of_interest)>=2, "I need at least two time points of interest."

if self:
warn("The spline already contains points. This will remove them. Be sure that you really want this. If not, consider using `from_func`.")
warn("The spline already contains points. This will remove them. Be sure that you really want this. If not, consider using `from_func`.", stacklevel=2)
self.clear()

# A happy anchor is sufficiently interpolated by its neighbours, temporally close to them, or at the border of the interval.
Expand Down Expand Up @@ -623,7 +624,7 @@ def from_data(cls,times,states):
t_2 = times [1:-1]
t_3 = times [2: ]
diffs[1:-1] = (
y_1 * ((t_2-t_3)/(t_2-t_1)/(t_3-t_1))[:,None]
y_1 * ((t_2-t_3)/(t_2-t_1)/(t_3-t_1))[:,None]
+ y_2 / (t_2-t_3)[:,None]
+ y_2 / (t_2-t_1)[:,None]
+ y_3 * ((t_2-t_1)/(t_3-t_1)/(t_3-t_2))[:,None]
Expand Down Expand Up @@ -663,7 +664,7 @@ def get_recent_state(self,t):
"""
anchors = self[-2], self[-1]
output = interpolate_vec(t,anchors)
assert type(output) == np.ndarray
assert type(output) is np.ndarray
return output

def get_current_state(self):
Expand Down Expand Up @@ -744,8 +745,6 @@ def solve(self,i,value,beginning=None,end=None,solve_derivative=False):
if not self[0].time <= beginning < end <= self[-1].time:
raise ValueError("Beginning and end must in the time interval spanned by the anchors.")

extrema = Extrema(self.n)

sols = []

for j in range(self.last_index_before(beginning),len(self)-1):
Expand Down Expand Up @@ -779,8 +778,8 @@ def norm(self, delay, indices):
norm_sq = norm_sq_partial(anchors, indices, threshold)

# full norms of all others
for i in range(i+1, len(self)-1):
anchors = (self[i],self[i+1])
for j in range(i+1, len(self)-1):
anchors = (self[j],self[j+1])
norm_sq += norm_sq_interval(anchors, indices)

return np.sqrt(norm_sq)
Expand All @@ -797,8 +796,8 @@ def scalar_product(self, delay, indices_1, indices_2):
sp = scalar_product_partial(anchors, indices_1, indices_2, threshold)

# full scalar product of all others
for i in range(i+1, len(self)-1):
anchors = (self[i],self[i+1])
for j in range(i+1, len(self)-1):
anchors = (self[j],self[j+1])
sp += scalar_product_interval(anchors, indices_1, indices_2)

return sp
Expand All @@ -813,7 +812,7 @@ def scale(self, indices, factor):

def subtract(self, indices_1, indices_2, factor):
"""
Substract the spline for `indices_2` multiplied by `factor` from the spline for `indices_1`.
Subtract the spline for `indices_2` multiplied by `factor` from the spline for `indices_1`.
"""
for anchor in self:
anchor.state[indices_1] -= factor*anchor.state[indices_2]
Expand Down Expand Up @@ -853,7 +852,7 @@ def plus(self,other):
match_anchors(self,other)
assert self.times == other.times

for i,anchor in enumerate(other):
for i,_anchor in enumerate(other):
self[i].state += other[i].state
self[i].diff += other[i].diff

Expand Down Expand Up @@ -892,7 +891,7 @@ def plot(self,axes,components="all",resolution=20,*args,**kwargs):
kwargs.setdefault("markevery",resolution)
values = self.get_state(plot_times)
return [
axes.plot( plot_times, values[:,c], label=f"Component {c}", *args, **kwargs )
axes.plot( plot_times, values[:,c], *args, label=f"Component {c}", **kwargs )
for c in (components)
]

Expand Down
43 changes: 22 additions & 21 deletions docs/conf.py
Original file line number Diff line number Diff line change
@@ -1,56 +1,57 @@
import sys
import os
import sys

from setuptools_scm import get_version
from unittest.mock import MagicMock as Mock


# Mocking to make RTD autobuild the documentation.
autodoc_mock_imports = ['numpy']
autodoc_mock_imports = ["numpy"]
#sys.modules.update([("numpy", Mock())])
sys.path.insert(0,os.path.abspath("../chspy"))
sys.path.insert(0,os.path.abspath("../examples"))

needs_sphinx = '1.6'
needs_sphinx = "1.6"

extensions = [
'sphinx.ext.autodoc',
'sphinx.ext.autosummary',
'sphinx.ext.mathjax',
'matplotlib.sphinxext.plot_directive',
'numpydoc',
"sphinx.ext.autodoc",
"sphinx.ext.autosummary",
"sphinx.ext.mathjax",
"matplotlib.sphinxext.plot_directive",
"numpydoc",
]

source_suffix = '.rst'
source_suffix = ".rst"

master_doc = 'index'
master_doc = "index"

project = 'CHSPy'
copyright = '2019, Gerrit Ansmann'
project = "CHSPy"
copyright = "2019, Gerrit Ansmann"

release = version = get_version(root='..', relative_to=__file__)
release = version = get_version(root="..", relative_to=__file__)

default_role = "any"

add_function_parentheses = True

add_module_names = False

html_theme = 'nature'
pygments_style = 'colorful'
htmlhelp_basename = 'CHSPydoc'
html_theme = "nature"
pygments_style = "colorful"
htmlhelp_basename = "CHSPydoc"

plot_html_show_formats = False
plot_html_show_source_link = False

numpydoc_show_class_members = False
autodoc_member_order = 'bysource'
autodoc_member_order = "bysource"

toc_object_entries_show_parents = 'hide'
toc_object_entries_show_parents = "hide"

def on_missing_reference(app, env, node, contnode):
if node['reftype'] == 'any':
if node["reftype"] == "any":
return contnode
else:
return None

def setup(app):
app.connect('missing-reference', on_missing_reference)
app.connect("missing-reference", on_missing_reference)
4 changes: 3 additions & 1 deletion examples/simple_example.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
from chspy import CubicHermiteSpline
from matplotlib.pyplot import subplots

from chspy import CubicHermiteSpline


spline = CubicHermiteSpline(n=3)

# time state slope
Expand Down
42 changes: 42 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -43,3 +43,45 @@ include = [

[tool.setuptools_scm]
write_to = "chspy/version.py"

[tool.ruff]
target-version = "py37"
line-length = 320

[tool.ruff.lint]
select = [
"A", # flake8-builtins
"B", # flake8-bugbear
"C4", # flake8-comprehensions
"E", # flake8
"F", # flake8
"I", # flake8-isort
"NPY", # numpy
"Q", # flake8-quotes
"RUF", # ruff
"UP", # pyupgrade
"W", # flake8
]
ignore = [
"A001", # shadowing-builtin-variable
"A005", # shadowing-builtin-module
"C409", # incorrectly-parenthesized-tuple-in-subscript
"E203", # whitespace-before-punctuation
"E402", # module-import-not-at-top-of-file
"E501", # line-too-long
"E731", # assign-to-lambda
"RUF001", # ambiguous-unicode-character-string
"RUF002", # ambiguous-unicode-character-docstring
"W191", # indentation-contains-tabs
"W293", # blank-line-with-whitespace
]

[tool.ruff.lint.flake8-quotes]
docstring-quotes = "double"
inline-quotes = "double"
multiline-quotes = "double"

[tool.ruff.lint.isort]
combine-as-imports = true
known-local-folder = [ "CHSPy" ]
lines-after-imports = 2
Loading
Loading