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

Reformat signal into a list #147

Merged
merged 18 commits into from
Dec 14, 2023
Merged
Show file tree
Hide file tree
Changes from 14 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
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@
- [#116](https://github.com/pybop-team/PyBOP/issues/116) - Adds PSO, SNES, XNES, ADAM, and IPropMin optimisers to PintsOptimisers() class
- [#38](https://github.com/pybop-team/PyBOP/issues/38) - Restructures the Problem classes ahead of adding a design optimisation example
- [#120](https://github.com/pybop-team/PyBOP/issues/120) - Updates the parameterisation test settings including the number of iterations
- [#145](https://github.com/pybop-team/PyBOP/issues/145) - Reformats Dataset to contain a dictionary and signal into a list of strings

## Bug Fixes

Expand Down
12 changes: 7 additions & 5 deletions examples/notebooks/spm_nlopt.ipynb
Original file line number Diff line number Diff line change
Expand Up @@ -277,11 +277,13 @@
"outputs": [],
"source": [
"pyb_model = pybop.lithium_ion.SPM()\n",
"dataset = [\n",
" pybop.Dataset(\"Time [s]\", synthetic_sol[\"Time [s]\"].data),\n",
" pybop.Dataset(\"Current function [A]\", synthetic_sol[\"Current [A]\"].data),\n",
" pybop.Dataset(\"Terminal voltage [V]\", corrupt_V),\n",
"]"
"dataset = pybop.Dataset(\n",
" {\n",
" \"Time [s]\": synthetic_sol[\"Time [s]\"].data,\n",
" \"Current function [A]\": synthetic_sol[\"Current [A]\"].data,\n",
" \"Terminal voltage [V]\": corrupt_V,\n",
" }\n",
")"
]
},
{
Expand Down
13 changes: 8 additions & 5 deletions examples/scripts/ecm_CMAES.py
Original file line number Diff line number Diff line change
Expand Up @@ -61,11 +61,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
14 changes: 8 additions & 6 deletions examples/scripts/spm_CMAES.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

# Form dataset for optimisation
dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
13 changes: 8 additions & 5 deletions examples/scripts/spm_IRPropMin.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
12 changes: 7 additions & 5 deletions examples/scripts/spm_SNES.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,13 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
13 changes: 8 additions & 5 deletions examples/scripts/spm_XNES.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
14 changes: 8 additions & 6 deletions examples/scripts/spm_adam.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

# Dataset definition
dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
14 changes: 8 additions & 6 deletions examples/scripts/spm_descent.py
Original file line number Diff line number Diff line change
Expand Up @@ -25,12 +25,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

# Dataset definition
dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
14 changes: 8 additions & 6 deletions examples/scripts/spm_nlopt.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

# Form dataset
Measurements = pd.read_csv("examples/scripts/Chen_example.csv", comment="#").to_numpy()
dataset = [
pybop.Dataset("Time [s]", Measurements[:, 0]),
pybop.Dataset("Current function [A]", Measurements[:, 1]),
pybop.Dataset("Voltage [V]", Measurements[:, 2]),
]
dataset = pybop.Dataset(
{
"Time [s]": Measurements[:, 0],
"Current function [A]": Measurements[:, 1],
"Voltage [V]": Measurements[:, 2],
}
)

# Define model
parameter_set = pybop.ParameterSet.pybamm("Chen2020")
Expand All @@ -30,7 +32,7 @@
]

# Define the cost to optimise
signal = "Voltage [V]"
signal = ["Voltage [V]"]
problem = pybop.FittingProblem(model, parameters, dataset, signal=signal, init_soc=0.98)
cost = pybop.RootMeanSquaredError(problem)

Expand Down
13 changes: 8 additions & 5 deletions examples/scripts/spm_pso.py
Original file line number Diff line number Diff line change
Expand Up @@ -24,11 +24,14 @@
values = model.predict(t_eval=t_eval)
corrupt_values = values["Voltage [V]"].data + np.random.normal(0, sigma, len(t_eval))

dataset = [
pybop.Dataset("Time [s]", t_eval),
pybop.Dataset("Current function [A]", values["Current [A]"].data),
pybop.Dataset("Voltage [V]", corrupt_values),
]
# Form dataset
dataset = pybop.Dataset(
{
"Time [s]": t_eval,
"Current function [A]": values["Current [A]"].data,
"Voltage [V]": corrupt_values,
}
)

# Generate problem, cost function, and optimisation class
problem = pybop.FittingProblem(model, parameters, dataset)
Expand Down
14 changes: 8 additions & 6 deletions examples/scripts/spm_scipymin.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,13 @@

# Form dataset
Measurements = pd.read_csv("examples/scripts/Chen_example.csv", comment="#").to_numpy()
dataset = [
pybop.Dataset("Time [s]", Measurements[:, 0]),
pybop.Dataset("Current function [A]", Measurements[:, 1]),
pybop.Dataset("Voltage [V]", Measurements[:, 2]),
]
dataset = pybop.Dataset(
{
"Time [s]": Measurements[:, 0],
"Current function [A]": Measurements[:, 1],
"Voltage [V]": Measurements[:, 2],
}
)

# Define model
parameter_set = pybop.ParameterSet.pybamm("Chen2020")
Expand All @@ -30,7 +32,7 @@
]

# Define the cost to optimise
signal = "Voltage [V]"
signal = ["Voltage [V]"]
problem = pybop.FittingProblem(model, parameters, dataset, signal=signal, init_soc=0.98)
cost = pybop.RootMeanSquaredError(problem)

Expand Down
18 changes: 10 additions & 8 deletions pybop/_dataset.py
Original file line number Diff line number Diff line change
Expand Up @@ -18,20 +18,22 @@ class Dataset:

"""

def __init__(self, name, data):
def __init__(self, data_dictionary):
"""
Initialize a Dataset instance with a name and data.

Parameters
----------
name : str
The name for the dataset.
data : array-like
data_dictionary : dict or instance of pybamm.solvers.solution.Solution
The experimental data to store within the dataset.
"""

self.name = name
self.data = data
if isinstance(data_dictionary, pybamm.solvers.solution.Solution):
data_dictionary = data_dictionary.get_data_dict()
if not isinstance(data_dictionary, dict):
raise ValueError("The input to pybop.Dataset must be a dictionary.")
self.data = data_dictionary
self.names = self.data.keys()

def __repr__(self):
"""
Expand All @@ -40,9 +42,9 @@ def __repr__(self):
Returns
-------
str
A string that includes the name and data of the dataset.
A string that includes the type and contents of the dataset.
"""
return f"Dataset: {self.name} \n Data: {self.data}"
return f"Dataset: {type(self.data)} \n Contains: {self.names}"

def Interpolant(self):
"""
Expand Down
32 changes: 21 additions & 11 deletions pybop/_problem.py
Original file line number Diff line number Diff line change
Expand Up @@ -108,34 +108,44 @@ def __init__(
model,
parameters,
dataset,
signal="Voltage [V]",
signal=["Voltage [V]"],
check_model=True,
init_soc=None,
x0=None,
):
super().__init__(parameters, model, check_model, init_soc, x0)
if model is not None:
self._model.signal = signal
if isinstance(signal, str):
signal = [signal]
self.signal = signal
self._dataset = {o.name: o for o in dataset}
self.n_outputs = len([self.signal])
self.n_outputs = len(self.signal)
self._dataset = dataset.data

# Check that the dataset contains time and current
for name in ["Time [s]", "Current function [A]", signal]:
for name in ["Time [s]", "Current function [A]"] + signal:
if name not in self._dataset:
raise ValueError(f"expected {name} in list of dataset")

self._time_data = self._dataset["Time [s]"].data
self._time_data = self._dataset["Time [s]"]
self.n_time_data = len(self._time_data)
self._target = self._dataset[signal].data

if np.any(self._time_data < 0):
raise ValueError("Times can not be negative.")
if np.any(self._time_data[:-1] >= self._time_data[1:]):
raise ValueError("Times must be increasing.")

if len(self._target) != len(self._time_data):
raise ValueError("Time data and signal data must be the same length.")
target = [self._dataset[signal] for signal in self.signal]
self._target = np.vstack(target).T
if self.n_outputs == 1:
if len(self._target) != self.n_time_data:
raise ValueError("Time data and target data must be the same length.")
else:
if self._target.shape != (self.n_time_data, self.n_outputs):
raise ValueError("Time data and target data must be the same shape.")

# Add useful parameters to model
if model is not None:
self._model.signal = self.signal
self._model.n_outputs = self.n_outputs
self._model.n_time_data = self.n_time_data

# Build the model
if self._model._built_model is None:
Expand Down
31 changes: 17 additions & 14 deletions pybop/models/base_model.py
Original file line number Diff line number Diff line change
Expand Up @@ -121,8 +121,8 @@ def set_params(self):
if self.dataset is not None and self.parameters is not None:
if "Current function [A]" not in self.fit_keys:
self.parameter_set["Current function [A]"] = pybamm.Interpolant(
self.dataset["Time [s]"].data,
self.dataset["Current function [A]"].data,
self.dataset["Time [s]"],
self.dataset["Current function [A]"],
pybamm.t,
)
# Set t_eval
Expand Down Expand Up @@ -163,9 +163,11 @@ def simulate(self, inputs, t_eval):
if not isinstance(inputs, dict):
inputs = {key: inputs[i] for i, key in enumerate(self.fit_keys)}

return self.solver.solve(self.built_model, inputs=inputs, t_eval=t_eval)[
self.signal
].data
sol = self.solver.solve(self.built_model, inputs=inputs, t_eval=t_eval)

predictions = [sol[signal].data for signal in self.signal]

return np.vstack(predictions).T

def simulateS1(self, inputs, t_eval):
"""
Expand Down Expand Up @@ -204,15 +206,16 @@ def simulateS1(self, inputs, t_eval):
calculate_sensitivities=True,
)

return (
sol[self.signal].data,
np.asarray(
[
sol[self.signal].sensitivities[key].toarray()
for key in self.fit_keys
]
).T,
)
predictions = [sol[signal].data for signal in self.signal]

sensitivities = [
np.array(
[[sol[signal].sensitivities[key]] for signal in self.signal]
).reshape(len(sol[self.signal[0]].data), self.n_outputs)
for key in self.fit_keys
]

return (np.vstack(predictions).T, np.dstack(sensitivities))

def predict(
self,
Expand Down
Loading