forked from Adityaparmar2903/pysb_optimize
/
example_fitting_sens.py
169 lines (139 loc) · 4.9 KB
/
example_fitting_sens.py
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
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
from pysb.examples.robertson import model
import numpy as np
from matplotlib import pyplot as plt
from pysb.integrate import Solver
from pysb.sensitivity import Sensitivity
import scipy.optimize
from pyDOE import *
from scipy.stats.distributions import norm
import numdifftools as nd
# Simulate the model
# Create time vector using np.linspace function
num_timepoints = 101
num_dim = 3
t = np.linspace(0, 200, num_timepoints)
# Get instance of the Solver
sol = Solver(model, t, use_analytic_jacobian=False)
# Perform the integration
sol.run()
# Get instance of Sensitivity object
sens = Sensitivity(model, t)
# sol.y contains timecourses for all of the species
# (model.species gives matched list of species)
# sol.yobs contains timecourse only for the observables
# Indexed by the name of the observable
# Plot the timecourses for A, B, and C
plt.ion()
plt.figure()
# Iterate over the observables
colors = ['red', 'green', 'blue']
data = np.zeros((num_timepoints, len(model.observables)))
for obs_ix, obs in enumerate(model.observables):
obs_max = np.max(sol.yobs[obs.name])
# Plot the observable
plt.plot(t, sol.yobs[obs.name] / obs_max, label=obs.name,
color=colors[obs_ix])
# Make noisy data
# Get random numbers
rand_norm = np.random.randn(num_timepoints)
# Multiply by the values of the observable
sigma = 0.1
noise = rand_norm * sigma * sol.yobs[obs.name]
# Add the noise vector to the timecourse
noisy_obs = noise + sol.yobs[obs.name]
norm_noisy_data = noisy_obs / obs_max
plt.plot(t, norm_noisy_data, linestyle='', marker='.',
color=colors[obs_ix])
data[:, obs_ix] = noisy_obs
p_to_fit = [p for p in model.parameters
if p.name in ['k1', 'k2', 'k3']]
p_to_fit_indices = [model.parameters.index(p) for p in p_to_fit]
num_obj_calls = 0
# First define the objective function
def obj_func(x):
global num_obj_calls
num_obj_calls += 1
lin_x = 10 ** x
#print x
# Run a simulation using these parameters
# Initialize the model to have the values in the parameter array
for p_ix, p in enumerate(p_to_fit):
p.value = lin_x[p_ix]
# Run the solver
sol.run()
# Calculate our error
total_err = 0
for obs_ix, obs in enumerate(model.observables):
y = sol.yobs[obs.name]
# Calculate the square difference with the data
total_err += np.sum((y - data[:, obs_ix])**2)
return total_err
num_jac_calls = 0
def jac_func(x):
global num_jac_calls
num_jac_calls += 1
lin_x = 10 ** x
# Initialize the model to have the values in the parameter array
for p_ix, p in enumerate(p_to_fit):
p.value = lin_x[p_ix]
sens.run()
ysens_view = sens.ysens[:, :, p_to_fit_indices]
dgdp = np.zeros(len(p_to_fit))
for y_ix in range(sens.yodes.shape[1]):
dgdy = np.dot(2 * (sens.yodes[:, y_ix] - data[:, y_ix]),
ysens_view[:, y_ix, :])
dgdp += dgdy
return dgdp
# for obs_ix, obs in enumerate(model.observables):
# y = sens.yobs[obs.name]
# # Calculate the square difference with the data
# dgdy[obs_ix] = 2 * np.sum(y - data[:, obs_ix])
# Hang on to the original values for comparison
nominal_values = np.array([p.value for p in p_to_fit])
x_test = np.log10(nominal_values)
#print "True values (in log10 space):", x_test
#print "Nominal error:", obj_func(x_test)
# Pick a starting point; in practice this would be random selected by
# a sampling strategy (e.g., latin hypercube sampling) or from a prior
# distributionmeans
x0 = np.array([np.log10(p.value * 0.1) for p in p_to_fit])
# Run the minimization algorithm!
def hess_func(x):
jaco = nd.Jacobian(jac_func)(x)
return jaco
def Jacob(x):
#x = np.asarray(x)
jaco = nd.Jacobian(obj_func)(x)
#print jaco,'aaa'
return jaco[0]
def Hessi(x):
#x = np.asarray(x)
hes = nd.Hessian(obj_func)(x)
#print hes
return hes
#Jacob = nda.Jacobian(obj_func, method = 'reverse')
#Hessi = nda.Hessian(obj_func)
#result = scipy.optimize.minimize(obj_func, x0, method='trust-ncg',jac = Jacob,
# hess=Hessi)
#result = scipy.optimize.minimize(obj_func, x0, method='trust-ncg',jac=jac_func,
# hess=None)
#result = scipy.optimize.minimize(obj_func, x0, method='Newton-CG',jac=jac_func,
# hess=None)
result = scipy.optimize.minimize(obj_func, x0, method='nelder-mead')
plt.figure()
# Plot the original data
plt.plot(t, data, linestyle='', marker='.', color='k')
# Plot BEFORE
# Set parameter values to start position
for p_ix, p in enumerate(p_to_fit):
p.value = 10 ** x0[p_ix]
sol.run()
plt.plot(t, sol.y, color='red')
# Plot AFTER
# Set parameter values to final position
for p_ix, p in enumerate(p_to_fit):
p.value = 10 ** result.x[p_ix]
sol.run()
plt.plot(t, sol.y, color='yellow')
print "Num obj calls:", num_obj_calls
print "Num jac calls:", num_jac_calls