-
Notifications
You must be signed in to change notification settings - Fork 44
Expand file tree
/
Copy pathspecification_oscillator2_numpy.txt
More file actions
55 lines (40 loc) · 1.66 KB
/
specification_oscillator2_numpy.txt
File metadata and controls
55 lines (40 loc) · 1.66 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
"""
Find the mathematical function skeleton that represents acceleration in a damped nonlinear oscillator system with driving force, given data on time, position, and velocity.
"""
import numpy as np
#Initialize parameters
MAX_NPARAMS = 10
PRAMS_INIT = [1.0]*MAX_NPARAMS
@evaluate.run
def evaluate(data: dict) -> float:
""" Evaluate the equation on data observations."""
# Load data observations
inputs, outputs = data['inputs'], data['outputs']
t, x, v = inputs[:,0], inputs[:,1], inputs[:,2]
# Optimize parameters based on data
from scipy.optimize import minimize
def loss(params):
y_pred = equation(t, x, v, params)
return np.mean((y_pred - outputs) ** 2)
loss_partial = lambda params: loss(params)
result = minimize(loss_partial, [1.0]*MAX_NPARAMS, method='BFGS')
# Return evaluation score
optimized_params = result.x
loss = result.fun
if np.isnan(loss) or np.isinf(loss):
return None
else:
return -loss
@equation.evolve
def equation(t: np.ndarray, x: np.ndarray, v: np.ndarray, params: np.ndarray) -> np.ndarray:
""" Mathematical function for acceleration in a damped nonlinear oscillator
Args:
t: A numpy array representing time.
x: A numpy array representing observations of current position.
v: A numpy array representing observations of velocity.
params: Array of numeric constants or parameters to be optimized
Return:
A numpy array representing acceleration as the result of applying the mathematical function to the inputs.
"""
dv = params[0] * t + params[1] * x + params[2] * v + params[3]
return dv