示例#1
0
# Import lsqpy
from lsqpy import Variable,sum_squares,minimize

# Import the test data
from data import x_data,y_data

# Create variables that holds the coefficients
quadratic = Variable()
slope = Variable()
offset = Variable()

# We copy x_data but square the entries
import numpy as np
x_squared = np.power(x_data,2)

# Solve the problem
minimize(sum_squares(offset + x_data*slope + x_squared*quadratic - y_data))

# Create some evenly spaced points for plotting, again replicate powers
t = np.arange(0,5,0.1).reshape(-1,1)
t_squared = np.power(t,2)

# Plot our regressed function
import matplotlib.pyplot as plt
plt.figure(0,(4,4))
plt.plot(x_data,y_data,'ro')
plt.plot(t,offset.value[0,0] + t*slope.value[0,0] + t_squared*quadratic.value[0,0],'b')
plt.xlabel('x')
plt.ylabel('y')
plt.show()
示例#2
0
velocity = Variable(2,T)
force = Variable(2,T-1)

# Create the list of constraints on our variables
constraints = []
for i in range(T-1):
	constraints.append(position[:,i+1] == position[:,i] + h * velocity[:,i])
for i in range(T-1):
	constraints.append(velocity[:,i+1] == velocity[:,i] + h/mass * force[:,i] - drag*velocity[:,i])
	
# Add position constraints
constraints.append(position[:,0] == 0)
constraints.append(position[:,T-1] == final_position)

# Add velocity constraints
constraints.append(velocity[:,0] == initial_velocity)
constraints.append(velocity[:,T-1] == 0)

# Solve the problem
mu = 1
minimize(mu*sum_squares(velocity)+sum_squares(force),constraints)

# Plot the points
plt.figure(0,(4,4))
plt.quiver(position.value[0,0:T-1:2],position.value[1,0:T-1:2],
	force.value[0,::2],force.value[1,::2])
plt.plot(position.value[0,:],position.value[1,:],'r')
plt.plot(0,0,'bo')
plt.plot(final_position[0],final_position[1],'bo')
plt.xlim([-2,12]), plt.ylim([-1,4])
plt.show()
示例#3
0
文件: data.py 项目: keegango/lsqpy
	constraints.append(positions[ship][:,0] == 0)
	constraints.append(velocities[ship][:,0] == speeds0[:,ship:ship+1])
	constraints.append(positions[ship][:,300] == speeds0[:,ship:ship+1])
	if ship == 0:
		constraints.append(positions[ship][:,formation1_end] == np.array([[20,-20]]).T)
		constraints.append(positions[ship][:,400] == np.array([[-20,20]]).T)
		constraints.append(positions[ship][:,499] == np.array([[10,-20]]).T)
	else:
		for t in range(formation1_start,formation1_end):
			constraints.append(positions[ship][:,t] - positions[0][:,t] == formation1[:,ship-1:ship])
		for t in range(400,500):
			constraints.append(positions[ship][:,t] - positions[0][:,t] == formation2[:,ship-1:ship])

objective = sum_squares(forces[0])
for i in range(1,n): objective += sum_squares(forces[i])
minimize(objective,constraints)

# Plot paths
fig = plt.figure(0)
ax = fig.add_subplot(111, autoscale_on=False, xlim=(-25, 25), ylim=(-25, 25))

line, = ax.plot([], [], 'o-', lw=2)
time_template = 'time = %.1fs'
time_text = ax.text(0.05, 0.9, '', transform=ax.transAxes)

def init():
	line.set_data([], [])
	time_text.set_text('')
	return line, time_text
	
def animate(i):
示例#4
0
# Import the test data
from data import x_data, y_data

# Fit a polynomial of this degree to data
num_powers = 20

# Import matplotlib and create the extra variables we need for plotting
# NumPy imported for matrix manipulation
import numpy as np
import matplotlib.pyplot as plt

plt.plot(x_data, y_data, "bo")
t = np.arange(0, 18, 0.1).reshape(-1, 1)
T = np.hstack([np.power(t, i) for i in range(num_powers)])

# We will regress using different powers of x
X = np.hstack([np.power(x_data, i) for i in range(num_powers)])

# Solve the problem
mu = 0
a = Variable(num_powers)
minimize(sum_sq(X * a - y_data) + mu * sum_sq(a))

# Plot our regressed function
plt.plot(t, T.dot(a.value), "r")
plt.xlabel("x")
plt.ylabel("y")
plt.ylim([-5, 5])
plt.show()
示例#5
0
"""
A simple linear regression problem
"""

# Import lsqpy
from lsqpy import Variable,sum_squares,minimize

# Import the test data
from data import x_data,y_data

# Solve the problem, and print the result
slope = Variable()
offset = Variable()
minimize(sum_squares(offset + x_data*slope - y_data))
print('slope = '+str(slope.value[0,0])+', offset = '+ str(offset.value[0,0]))

# Print results and plot
import numpy as np
import matplotlib.pyplot as plt
t = np.arange(0, 5.0, 0.1)
plt.figure(0,(4,4))
plt.plot(x_data,y_data,'ro')
plt.plot(t,(slope.value[0,0]*t + offset.value[0,0]))
plt.xlabel('x'), plt.ylabel('y')
plt.show()
示例#6
0
from lsqpy import Variable, sum_squares, minimize
import matplotlib.pyplot as plt
import numpy as np

# Import data for the problem
from data import temps, n

seasonal = Variable(n)

eq_constraints = []
for i in range(365,n): eq_constraints.append(seasonal[i] == seasonal[i-365])

smoothing = 0
smooth_objective = sum_squares(seasonal[0:n-1] - seasonal[1:n])
minimize(sum_squares(temps - seasonal) + smoothing*smooth_objective,eq_constraints)

residuals = temps - seasonal.value

# Generate the residuals matrix
matlist = []
ar_len = 5
for i in range(ar_len): matlist.append(residuals[ar_len-i-1:n-i-1])
residuals_mat = np.hstack(matlist)

# Solve autoregressive problem
ar_coef = Variable(ar_len)
minimize(sum_squares(residuals_mat*ar_coef - residuals[ar_len:]))
print(ar_coef.value)

# Do all plotting
plt.figure(0)
示例#7
0
from lsqpy import Variable,sum_squares,minimize

import numpy as np

import sys

test_num = int(sys.argv[1])

if test_num == 1:
	print('basic problem')
	x = Variable(4)
	A = np.array([[1,2,3,10],[5,4,6,11],[9,7,8,12]]);
	b = np.array([[16,26,36]]).T
	minimize(sum_squares(x),[A*x == b])
	print(x.value)

elif test_num == 2:
	print('another basic problem')
	x = Variable(4)
	A = np.array([[1,2,3,10],[5,4,6,11],[9,7,8,12]]);
	b = np.array([[16,26,36]]).T
	objective = sum_squares(A*x+b)+100*sum_squares(x)
	const_val = np.array([[100,100]]).T
	constraint = const_val == x[2:4]
	minimize(objective,[constraint])
	print(x.value)

elif test_num == 3:
	print('really concise test')
	# Generate some data for a small example
	A = np.array(range(12)).reshape(4,3)
示例#8
0
from lsqpy import Variable, sum_squares, minimize
from data import temperatures, num_samples
import matplotlib.pyplot as plt
import numpy as np

yearly_tread = Variable(num_samples)
a = Variable()
b = Variable()

equality_constraints = []
for i in range(12,num_samples):
	equality_constraints.append(yearly_tread[i] == yearly_tread[i-12])
	
t = np.array([list(range(0,num_samples))]).T
t2 = np.power(t,2)

smoothing = 0.0001
objective = sum_squares(yearly_tread + t*b + t2*a - temperatures)
objective += smoothing*sum_squares(yearly_tread[0:num_samples-1] - yearly_tread[1:num_samples])

minimize(objective,equality_constraints)

plt.figure(0)
plt.plot(temperatures)
plt.plot(yearly_tread.value + t*b.value + t2*a.value,'r')
plt.show()

plt.figure(1)
plt.plot(yearly_tread.value + t*b.value + t2*a.value - temperatures)
plt.show()
示例#9
0
"""
An example of tomography
"""

from lsqpy import Variable, sum_squares, minimize

from data import img_size, num_pixels, line_mat, line_vals

x = Variable(num_pixels)

objective = sum_squares(x.__rmul__(line_mat) - line_vals)

minimize(objective,method='iterative')

import matplotlib.pyplot as plt
import matplotlib.cm as cm
plt.figure(0)
plt.imshow(x.value.reshape(img_size,img_size).T,cmap = cm.Greys_r)
plt.show()