0

I have a simple algorithm for computing the residuals of a mathematical model and some experimental data with noise. The objective is to find the phase if the amplitude and frequency are known. The algorithm loops over all phase values (to a precision of 3 decimal places) from 0 to 2*pi. The residuals from each calculation of the model for each phase are then calculated. The program then appends each phase and residual to their respective lists. I know I can use scipy.optimize to attack this problem, but I have reasons for wanting to use this algorithm. My question is, how can I retrieve the phase value associated with the smallest residual value? The program looks like this:

import numpy as np
from numpy import loadtxt

data = loadtxt('foo.txt', float)

x = data[:,0]
y = data[:,1]

a = 1.5
f = 0.01
p = []
phase = 0.000
residuals = []


for i in range(0, 6284):
    p.append(phase)
    model = a*np.sin(2*np.pi*f*x+phase)
    res = sum((y-model)**2)
    residuals.append(res)
    phase += 0.001

print min(residuals)

Any help on how to retrieve the phase value associated with the minimum residual would be helpful. Thanks.

Gary
  • 55
  • 1
  • 6

2 Answers2

1

Use following code

p[residuals.index(min(residuals))]
Sarit Adhikari
  • 1,344
  • 2
  • 16
  • 28
0

You could do something like this:

min_index, min_value = min(enumerate(residuals), key=lambda p: p[1])
phase_at_min = p[min_index]

But depending on your use case a better approach might be to store tuples for the results (or even use a dictionary):

results = []

for phase in range(0, 6.284, 0.001):
    model = a*np.sin(2*np.pi*f*x+phase)
    res = sum((y-model)**2)
    results.append((phase, res))

print(min(results, key=lambda x: x[1]))

as this way you have easier lookup of results for various phase amounts.

shuttle87
  • 15,466
  • 11
  • 77
  • 106
  • Thanks. That is useful as well. Both approaches will do what I need it to do for now. This may be the way to go going down the road, however. – Gary Jun 03 '15 at 18:02