using ForwardDiff
using Plots
using Calculus
plotly()
#number of degrees of freedom
n = 10
left = 0 #x_L default. never changed
right = 11 #x_R default. to be changed later
#number of springs
num_springs = n+1
#lengths of each spring
L = ones(num_springs,1);
#spring constants:
k_spring = ones(num_springs,1)
for i in 1:num_springs
if(i %2 == 0)
k_spring[i] = 0.5
end
end
#Construct spring system matrix:
cols = n+2
rows = num_springs
A = eye(rows,cols)
for i = 1:rows
A[i,i+1] = -1
end
#define PE
PE(x) = sum(1/2*k_spring.*(abs.(A*[left;x;right])-L).^2)
K = 10000 #maximum number of iterations
epsilon = 1e-8
#f is a function (PE or rosenbrock). x0 is the initial condition.
function myGradientDescent(f, x0)
#YOUR CODE HERE
#Return optimal x vector
end
#f is a function (PE or rosenbrock). x0 is the initial condition.
function myNewtonMethod(f, x0)
#YOUR CODE HERE
#Return optimal x vector
end
#rosenbrock function and initial condition.
rosenbrock(x) = (1.0 - x[1])^2 + 100.0 * (x[2] - x[1]^2)^2
rosenbrockx0 = [0; 0];
#Part 1
println("Gradient Descent")
res = myGradientDescent(rosenbrock, [0;0])
println(res)
println("Newton's Method")
res = myNewtonMethod(rosenbrock, [0,0])
println(res)
#Problem 2, try to solve on large boundary.
left = 0
right = 11
x0 = linspace(1, right-1, n)*0.9
#Part 3, try to solve on smaller boundary.
left = 0
right = 5
x0 = linspace(1, right-1, n)
#Part 4, Compress the system to get to a smaller boundary.
left = 0
right = 11
x0 = linspace(1, right-1, n)
while right > 1
right = right-0.1
res = myNewtonMethod(PE,x0)
dres = diff([left;res;right])
#println(dres)
if(any(x->x<0, dres))
println("FAILURE when right= ", right)
println(res)
break;
end
x0 = res
end
println(left, " ", right, " ", x0)