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

Bound prior sampling (#69) #70

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
3 changes: 1 addition & 2 deletions pybop/optimisation.py
Original file line number Diff line number Diff line change
Expand Up @@ -44,8 +44,7 @@ def __init__(
if x0 is None:
self.x0 = np.zeros(self.n_parameters)
for i, param in enumerate(self.parameters):
self.x0[i] = param.prior.rvs(1)[0]
# Update to capture dimensions per parameter
self.x0[i] = param.rvs(1)

# Add the initial values to the parameter definitions
for i, param in enumerate(self.parameters):
Expand Down
19 changes: 14 additions & 5 deletions pybop/parameters/base_parameter.py
Original file line number Diff line number Diff line change
Expand Up @@ -8,12 +8,21 @@ def __init__(self, name, value=None, prior=None, bounds=None):
self.prior = prior
self.value = value
self.bounds = bounds
self.lower_bound = self.bounds[0]
self.upper_bound = self.bounds[1]

# To Do:
# priors implementation
# parameter check
# bounds checks and set defaults
# implement methods to assign and retrieve parameters
if self.lower_bound > self.upper_bound:
raise ValueError("Lower bound must be less than upper bound")

def rvs(self, n_samples):
sample = self.prior.rvs(n_samples)

if sample < self.lower_bound:
return self.lower_bound
elif sample > self.upper_bound:
return self.upper_bound
else:
return sample

def update(self, value):
self.value = value
Expand Down
42 changes: 42 additions & 0 deletions tests/unit/test_optimisation.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,42 @@
import pybop
import numpy as np
import pytest


class TestOptimisation:
"""
A class to test the optimisation class.
"""

@pytest.mark.unit
def test_prior_sampling(self):
# Tests prior sampling
model = pybop.lithium_ion.SPM()

Dataset = [
pybop.Dataset("Time [s]", np.linspace(0, 3600, 100)),
pybop.Dataset("Current function [A]", np.zeros(100)),
pybop.Dataset("Terminal voltage [V]", np.ones(100)),
]

param = [
pybop.Parameter(
"Negative electrode active material volume fraction",
prior=pybop.Gaussian(0.75, 0.2),
bounds=[0.73, 0.77],
)
]

signal = "Terminal voltage [V]"
cost = pybop.RMSE()

for i in range(50):
opt = pybop.Optimisation(
cost,
model,
optimiser=pybop.NLoptOptimize(n_param=len(param)),
parameters=param,
dataset=Dataset,
signal=signal,
)
assert opt.x0 <= 0.77 and opt.x0 >= 0.73