Skip to content

Commit

Permalink
run ruff --fix --unsafe-fixes .
Browse files Browse the repository at this point in the history
  • Loading branch information
paquiteau committed Feb 16, 2024
1 parent 4522e74 commit 476178f
Show file tree
Hide file tree
Showing 40 changed files with 61 additions and 118 deletions.
23 changes: 11 additions & 12 deletions docs/source/conf.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
# Python Template sphinx config

# Import relevant modules
Expand All @@ -19,7 +18,7 @@
mdata = metadata(project)
author = mdata["Author"]
version = mdata["Version"]
copyright = "2020, {}".format(author)
copyright = f"2020, {author}"
gh_user = "sfarrens"

# If your documentation needs a minimal Sphinx version, state it here.
Expand Down Expand Up @@ -117,7 +116,7 @@
)
# The name for this set of Sphinx documents. If None, it defaults to
# "<project> v<release> documentation".
html_title = "{0} v{1}".format(project, version)
html_title = f"{project} v{version}"

# A shorter title for the navigation bar. Default is the same as html_title.
# html_short_title = None
Expand Down Expand Up @@ -174,20 +173,20 @@ def add_notebooks(nb_path="../../notebooks"):
nb_name = nb.rstrip(nb_ext)

nb_link_file_name = nb_name + ".nblink"
print("Writing {0}".format(nb_link_file_name))
print(f"Writing {nb_link_file_name}")
with open(nb_link_file_name, "w") as nb_link_file:
nb_link_file.write(nb_link_format.format(nb_path, nb))

print("Looking for {0} in {1}".format(nb_name, nb_rst_file_name))
with open(nb_rst_file_name, "r") as nb_rst_file:
print(f"Looking for {nb_name} in {nb_rst_file_name}")
with open(nb_rst_file_name) as nb_rst_file:
check_name = nb_name not in nb_rst_file.read()

if check_name:
print("Adding {0} to {1}".format(nb_name, nb_rst_file_name))
print(f"Adding {nb_name} to {nb_rst_file_name}")
with open(nb_rst_file_name, "a") as nb_rst_file:
if list_pos == 0:
nb_rst_file.write("\n")
nb_rst_file.write(" {0}\n".format(nb_name))
nb_rst_file.write(f" {nb_name}\n")

return nbs

Expand Down Expand Up @@ -220,14 +219,14 @@ def add_notebooks(nb_path="../../notebooks"):
"""
nb_header_pt2 = (
r""" <p><div class="inline-block">"""
r"""<a href="{0}/{1}/{2}/""".format(binder, gh_user, project)
rf"""<a href="{binder}/{gh_user}/{project}/"""
+ r"""master?filepath={{ docpath }}">"""
+ r"""<img alt="Binder badge" src="{0}" """.format(binder_badge)
+ rf"""<img alt="Binder badge" src="{binder_badge}" """
+ r"""style="vertical-align:text-bottom"></a></div>"""
r"""<div class="inline-block"><a href="""
+ r""""{0}/{1}/{2}/blob/master/""".format(github, gh_user, project)
+ rf""""{github}/{gh_user}/{project}/blob/master/"""
+ r"""{{ docpath }}"><img alt="GitHub badge" """
+ r"""src="{0}" style="vertical-align:text-bottom">""".format(github_badge)
+ rf"""src="{github_badge}" style="vertical-align:text-bottom">"""
+ r"""</a></div></p>"""
)

Expand Down
1 change: 0 additions & 1 deletion modopt/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""MODOPT PACKAGE.
Expand Down
1 change: 0 additions & 1 deletion modopt/base/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""BASE ROUTINES.
Expand Down
1 change: 0 additions & 1 deletion modopt/base/backend.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""BACKEND MODULE.
Expand Down
1 change: 0 additions & 1 deletion modopt/base/np_adjust.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""NUMPY ADJUSTMENT ROUTINES.
Expand Down
7 changes: 3 additions & 4 deletions modopt/base/observable.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""Observable.
Expand All @@ -13,13 +12,13 @@
import numpy as np


class SignalObject(object):
class SignalObject:
"""Dummy class for signals."""

pass


class Observable(object):
class Observable:
"""Base class for observable classes.
This class defines a simple interface to add or remove observers
Expand Down Expand Up @@ -177,7 +176,7 @@ def _remove_observer(self, signal, observer):
self._observers[signal].remove(observer)


class MetricObserver(object):
class MetricObserver:
"""Metric observer.
Wrapper of the metric to the observer object notify by the Observable
Expand Down
5 changes: 2 additions & 3 deletions modopt/base/transform.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""DATA TRANSFORM ROUTINES.
Expand Down Expand Up @@ -288,7 +287,7 @@ def cube2matrix(data_cube):
"""
return data_cube.reshape(
[data_cube.shape[0]] + [np.prod(data_cube.shape[1:])],
[data_cube.shape[0], np.prod(data_cube.shape[1:])],
).T


Expand Down Expand Up @@ -333,4 +332,4 @@ def matrix2cube(data_matrix, im_shape):
cube2matrix : complimentary function
"""
return data_matrix.T.reshape([data_matrix.shape[1]] + list(im_shape))
return data_matrix.T.reshape([data_matrix.shape[1], *list(im_shape)])
3 changes: 1 addition & 2 deletions modopt/base/types.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""TYPE HANDLING ROUTINES.
Expand Down Expand Up @@ -183,7 +182,7 @@ def check_npndarray(input_obj, dtype=None, writeable=True, verbose=True):
):
raise (
TypeError(
"The numpy array elements are not of type: {0}".format(dtype),
f"The numpy array elements are not of type: {dtype}",
),
)

Expand Down
1 change: 0 additions & 1 deletion modopt/base/wrappers.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""WRAPPERS.
Expand Down
1 change: 0 additions & 1 deletion modopt/examples/example_lasso_forward_backward.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# noqa: D205
"""
Solving the LASSO Problem with the Forward Backward Algorithm.
==============================================================
Expand Down
1 change: 0 additions & 1 deletion modopt/interface/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""INTERFACE ROUTINES.
Expand Down
13 changes: 6 additions & 7 deletions modopt/interface/errors.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""ERROR HANDLING ROUTINES.
Expand Down Expand Up @@ -39,7 +38,7 @@ def warn(warn_string, log=None):
warn_txt = colored("WARNING", "yellow")

# Print warning to stdout.
sys.stderr.write("{0}: {1}\n".format(warn_txt, warn_string))
sys.stderr.write(f"{warn_txt}: {warn_string}\n")

# Check if a logging structure is provided.
if not isinstance(log, type(None)):
Expand All @@ -66,12 +65,12 @@ def catch_error(exception, log=None):
err_txt = colored("ERROR", "red")

# Print exception to stdout.
stream_txt = "{0}: {1}\n".format(err_txt, exception)
stream_txt = f"{err_txt}: {exception}\n"
sys.stderr.write(stream_txt)

# Check if a logging structure is provided.
if not isinstance(log, type(None)):
log_txt = "ERROR: {0}\n".format(exception)
log_txt = f"ERROR: {exception}\n"
log.exception(log_txt)


Expand All @@ -92,10 +91,10 @@ def file_name_error(file_name):
"""
if file_name == "" or file_name[0][0] == "-":
raise IOError("Input file name not specified.")
raise OSError("Input file name not specified.")

elif not os.path.isfile(file_name):
raise IOError("Input file name {0} not found!".format(file_name))
raise OSError(f"Input file name {file_name} not found!")


def is_exe(fpath):
Expand Down Expand Up @@ -151,4 +150,4 @@ def is_executable(exe_name):

if not res:
message = "{0} does not appear to be a valid executable on this system."
raise IOError(message.format(exe_name))
raise OSError(message.format(exe_name))
3 changes: 1 addition & 2 deletions modopt/interface/log.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""LOGGING ROUTINES.
Expand Down Expand Up @@ -30,7 +29,7 @@ def set_up_log(filename, verbose=True):
"""
# Add file extension.
filename = "{0}.log".format(filename)
filename = f"{filename}.log"

if verbose:
print("Preparing log file:", filename)
Expand Down
1 change: 0 additions & 1 deletion modopt/math/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""MATHEMATICS ROUTINES.
Expand Down
1 change: 0 additions & 1 deletion modopt/math/convolve.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""CONVOLUTION ROUTINES.
Expand Down
3 changes: 1 addition & 2 deletions modopt/math/matrix.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""MATRIX ROUTINES.
Expand Down Expand Up @@ -257,7 +256,7 @@ def rotate(matrix, angle):
return matrix[tuple(zip(new_index.T))].reshape(shape.T)


class PowerMethod(object):
class PowerMethod:
"""Power method class.
This method performs implements power method to calculate the spectral
Expand Down
3 changes: 1 addition & 2 deletions modopt/math/metrics.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""METRICS.
Expand Down Expand Up @@ -268,6 +267,6 @@ def nrmse(test, ref, mask=None):
ref = mask * ref

num = np.sqrt(mse(test, ref))
deno = np.sqrt(np.mean((np.square(test))))
deno = np.sqrt(np.mean(np.square(test)))

return num / deno
1 change: 0 additions & 1 deletion modopt/math/stats.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""STATISTICS ROUTINES.
Expand Down
1 change: 0 additions & 1 deletion modopt/opt/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""OPTIMISATION PROBLEM MODULES.
Expand Down
19 changes: 0 additions & 19 deletions modopt/opt/algorithms/__init__.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
r"""OPTIMISATION ALGORITHMS.
This module contains class implementations of various optimisation algoritms.
Expand Down Expand Up @@ -45,21 +44,3 @@
"""

from modopt.opt.algorithms.base import SetUp
from modopt.opt.algorithms.forward_backward import (
FISTA,
POGM,
ForwardBackward,
GenForwardBackward,
)
from modopt.opt.algorithms.gradient_descent import (
AdaGenericGradOpt,
ADAMGradOpt,
GenericGradOpt,
MomentumGradOpt,
RMSpropGradOpt,
SAGAOptGradOpt,
VanillaGenericGradOpt,
)
from modopt.opt.algorithms.primal_dual import Condat
from modopt.opt.algorithms.admm import ADMM, FastADMM
3 changes: 1 addition & 2 deletions modopt/opt/algorithms/base.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Base SetUp for optimisation algorithms."""

from inspect import getmro
Expand Down Expand Up @@ -118,7 +117,7 @@ def metrics(self, metrics):
self._metrics = metrics
else:
raise TypeError(
"Metrics must be a dictionary, not {0}.".format(type(metrics)),
f"Metrics must be a dictionary, not {type(metrics)}.",
)

def any_convergence_flag(self):
Expand Down
9 changes: 4 additions & 5 deletions modopt/opt/algorithms/forward_backward.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Forward-Backward Algorithms."""

import numpy as np
Expand All @@ -9,7 +8,7 @@
from modopt.opt.linear import Identity


class FISTA(object):
class FISTA:
r"""FISTA.
This class is inherited by optimisation classes to speed up convergence
Expand Down Expand Up @@ -602,15 +601,15 @@ def __init__(
self._x_old = self.xp.copy(x)

# Set the algorithm operators
for operator in [grad, cost] + prox_list:
for operator in [grad, cost, *prox_list]:
self._check_operator(operator)

self._grad = grad
self._prox_list = self.xp.array(prox_list)
self._linear = linear

if cost == "auto":
self._cost_func = costObj([self._grad] + prox_list)
self._cost_func = costObj([self._grad, *prox_list])
else:
self._cost_func = cost

Expand Down Expand Up @@ -689,7 +688,7 @@ def _set_weights(self, weights):
if self.xp.sum(weights) != expected_weight_sum:
raise ValueError(
"Proximity operator weights must sum to 1.0. Current sum of "
+ "weights = {0}".format(self.xp.sum(weights)),
+ f"weights = {self.xp.sum(weights)}",
)

self._weights = weights
Expand Down
1 change: 0 additions & 1 deletion modopt/opt/algorithms/gradient_descent.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Gradient Descent Algorithms."""

import numpy as np
Expand Down
1 change: 0 additions & 1 deletion modopt/opt/algorithms/primal_dual.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-
"""Primal-Dual Algorithms."""

from modopt.opt.algorithms.base import SetUp
Expand Down
5 changes: 2 additions & 3 deletions modopt/opt/gradient.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,3 @@
# -*- coding: utf-8 -*-

"""GRADIENT CLASSES.
Expand All @@ -14,7 +13,7 @@
from modopt.base.types import check_callable, check_float, check_npndarray


class GradParent(object):
class GradParent:
"""Gradient Parent Class.
This class defines the basic methods that will be inherited by specific
Expand Down Expand Up @@ -289,7 +288,7 @@ def _cost_method(self, *args, **kwargs):
"""
cost_val = 0.5 * np.linalg.norm(self.obs_data - self.op(args[0])) ** 2

if "verbose" in kwargs and kwargs["verbose"]:
if kwargs.get("verbose"):
print(" - DATA FIDELITY (X):", cost_val)

return cost_val
2 changes: 1 addition & 1 deletion modopt/opt/linear/base.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,7 @@
from modopt.base.backend import get_array_module


class LinearParent(object):
class LinearParent:
"""Linear Operator Parent Class.
This class sets the structure for defining linear operator instances.
Expand Down
Loading

0 comments on commit 476178f

Please sign in to comment.