-
Notifications
You must be signed in to change notification settings - Fork 0
/
nonlinear_least_squares.py
204 lines (183 loc) · 6.3 KB
/
nonlinear_least_squares.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
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
import numpy as np
import keepin_handler as keepin
import matplotlib.pyplot as plt
from scipy.optimize import least_squares
import time
class NLS:
"""
Nonlinear least squares implementation
"""
def __init__(self, times, counts, fissions, efficiency, groups):
"""
Initialize
Parameters
----------
times : list
List of time values
counts : list
List of counts at each time
Returns
-------
None
"""
self.times = times
self.counts = counts
self.groups = groups
self.fissions = fissions
self.efficiency = efficiency
return
def func(self, x, t, y):
result = 0
groups = list()
for each in range(self.groups):
groups.append(2 * each)
for g in groups:
ai = x[g]
lam = x[g+1]
result += self.fissions * self.efficiency * ai * lam * np.exp(-lam * t)
result -= y
return result
def jacobian(self, x, *args, **kwargs):
# First row is alternating e^-x[1]t and -t*x[0] e^(-x[1]t)
# Rest of rows are same with updated time value
J_mat = np.zeros((len(self.times), self.groups*2))
for rowi, t in enumerate(self.times):
# Each row
row_val = list()
for each_pair in range(self.groups):
ai = x[2*each_pair]
lam = x[2*each_pair + 1]
row_val.append(lam * np.exp(-lam * t))
row_val.append(np.exp(-t * lam) * (ai - ai*t*lam))
J_mat[rowi, :] = row_val
return J_mat
def solver(self):
"""
Solves the nonlinear least squares problem
Parameters
----------
None
Returns
-------
soln_vec : 1D numpy array
groups*2x1 list of a_i, lam_i values
"""
x0 = np.ones((1, 2*self.groups))[0]
#x0 = np.random.rand(2*self.groups)
half_life_min = 0.0001
min_ailam = 0
max_ailam = 1
min_lam = 0
max_lam = np.log(2)/half_life_min
boundaries = ([min_ailam, min_lam] * self.groups,
[max_ailam, max_lam] * self.groups)
soln_vec = least_squares(self.func, x0, args=(self.times, self.counts),
bounds = boundaries,
jac = self.jacobian,
method='trf',
ftol=5e-16,
xtol=5e-16,
gtol=5e-16,
max_nfev=1E8)
print(soln_vec)
if not soln_vec['success']:
print('Run failed')
self.data_out(soln_vec['x'])
return soln_vec
def data_out(self, soln_vec):
ai = list()
lami = list()
for ind, each in enumerate(soln_vec):
if ind % 2 == 0:
ai.append(each)
else:
lami.append(np.log(2) / each)
print(f'n/F: {sum(ai)}')
print(f'Half Lives: {lami}')
print(f'Abundances: {ai}')
print(f'Rel abundances: {ai / sum(ai)}')
return
def simulate_nlin_solve(self, times, soln_vec):
"""
Simulate instantaneous irradiation using the groups generated by the
nonlinear least squares method
Parameters
----------
times : list
List of times to generate data points
soln_vec : numpy array
12x1 a_i, lambda_i for n groups
Returns
-------
delnu : list
Delayed neutrons at given times
"""
delnu = list()
groups = list()
normalize = 0
peak = self.counts[0]
for index, g in enumerate(soln_vec):
if index % 2 == 0:
normalize += g * soln_vec[index + 1]
groups.append(index)
for t in times:
detect = 0
for g in groups:
ai = soln_vec[g]
lam = soln_vec[g+1]
detect += self.fissions * self.efficiency * (ai * lam * np.exp(-lam * t))
delnu.append(detect)
return delnu
def debug_run(deb_group):
data_name = 'test_' + str(deb_group)
keepin_response = keepin.KEEPIN(data_name, 'fast')
counts = keepin_response.simulate_instant(times, fissions, efficiency)
nlin_solver = NLS(times, counts, fissions, efficiency, deb_group)
#nlin_solver = NLS(np.array(keepin_response.true_data_time),
# keepin_response.true_data_resp,
# fissions,
# efficiency)
soln_vec = nlin_solver.solver()
new_counts = nlin_solver.simulate_nlin_solve(times, soln_vec['x'])
plt.plot(times, counts, label = 'Keepin')
plt.plot(times, new_counts, label = 'NLS')
plt.yscale('log')
plt.ylabel('Delayed Neutron Count Rate [#/s]')
plt.xlabel('Time [s]')
plt.legend()
plt.show()
return
if __name__ == '__main__':
begin = time.time()
dt = 0.001
end = 300
times = np.arange(0, end+dt, dt)
fissions = 1#1E16
efficiency = 1#5.874643361662476e-08
default = False
debug = True
debug_group = 3
numgroups = 6
if debug:
debug_run(debug_group)
if default:
keepin_response = keepin.KEEPIN('u235', 'fast')
counts = keepin_response.simulate_instant(times, fissions, efficiency)
#nlin_solver = NLS(times, counts, fissions, efficiency)
nlin_solver = NLS(np.array(keepin_response.true_data_time),
keepin_response.true_data_resp,
fissions,
efficiency,
numgroups)
soln_vec = nlin_solver.solver()
new_counts = nlin_solver.simulate_nlin_solve(times, soln_vec['x'])
plt.plot(times, counts, label = 'Keepin')
plt.plot(times, new_counts, label = 'NLS')
plt.plot(keepin_response.true_data_time, keepin_response.true_data_resp,
label='True', linestyle='', marker='.')
plt.yscale('log')
plt.ylabel('Delayed Neutron Count Rate [#/s]')
plt.xlabel('Time [s]')
plt.legend()
plt.show()
print(f'Completed in {time.time() - begin}')