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

Add search infrastructure #29

Merged
merged 1 commit into from
Jan 5, 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
25 changes: 25 additions & 0 deletions cleedpy/cli/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,25 @@
import click
import numpy as np
import yaml

from .. import search


@click.command("cli")
@click.option("--config", "-c", help="Config file", required=True)
def cli(config):
"""Command line interface for the search tool"""
with open(config) as fobj:
data = yaml.safe_load(fobj)

x_init = np.array(data["x_init"])

def f(x):
return (x[0] - 2) ** 2 + (x[1] - 3) ** 2

res = search.simplex(f, x_init)
print(f"Solution: {res}")


if __name__ == "__main__":
cli()
12 changes: 12 additions & 0 deletions cleedpy/search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,12 @@
from scipy import optimize


def simplex(f, x0):
"""Minimize a function using the Nelder-Mead simplex algorithm.

:param f: Function to minimize.
:param x0: Initial guess.
:return: Optimal value.
"""
res = optimize.minimize(f, x0, method="Nelder-Mead", tol=1e-7)
return res.x
1 change: 1 addition & 0 deletions examples/search/input.yaml
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
x_init: [0, 1]
2 changes: 2 additions & 0 deletions pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -25,6 +25,7 @@ dependencies = [
"click",
"numpy",
"pyyaml",
"scipy",
]

[project.optional-dependencies]
Expand All @@ -37,6 +38,7 @@ dev = [

[project.scripts]
cleedpy-rfactor = "cleedpy.cli.rfactor:cli"
cleedpy-search = "cleedpy.cli.search:cli"

[tool.setuptools]
include-package-data = true
Expand Down
16 changes: 16 additions & 0 deletions tests/test_search.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,16 @@
import numpy as np
import pytest

from cleedpy import search


@pytest.mark.parametrize(
"f, x0, expected",
[
(lambda x: x[0] ** 2, [2], [0]),
(lambda x: (x[0] - 2) ** 2 + (x[1] - 3) ** 2, [0, 0], [2, 3]),
],
)
def test_simplex(f, x0, expected):
res = search.simplex(f, x0)
assert np.isclose(res, np.array(expected), atol=1e-5).all()