- #1
Falgata
- 6
- 0
Homework Statement
Okey her we go
I was given a base code called heat_equation_primer. The goal is to implement a optimizer into the program. The two methods that are going to be used is the Quasi-Newton and Steepest descent with search line. So I need gradients. So I tried to differentiate as best I could. Then using forward AD I was trying to verify what weighting the different values of a had on the system. The target values was given by the professor. The problems is that mine are to high and by a gargantuan size as well being 1 order of magnitude higher. He gave a suggestion where to start. I started in the set_bc and followed where the variables designed there headed. The differential will be makred with a d after the variable.
Homework Equations
The problem I think might be in the cost function L
L=sqrt(1/(4N) sum from 1 to 4N (fi-f(T,i))
noted in the code as L=sqrt(L/MX)
The Attempt at a Solution
Here is the parts modified code. I am not looking for someone to solve this for me Just to point me into the right direction. Thanks
Matlab:
function Tbot = T_bottom ( x, a )
[nr, MDVAR] = size(a) ;
Tbot = 0.0 ;
phi = x*pi ;
for n = 1:MDVAR/2
arg = n*phi ;
Tbot = Tbot + a(2*n-1)*cos(arg);
Tbot = Tbot + a(2*n) *sin(arg) ;
end
end
function [T, Td] = set_bc ( T, Td, a, ad )
for k = LEFT+1:RIGHT-1
x = get_x ( k ) ;
T(k,BOT) = T_bottom( x, a );
Td(k,BOT) = T_bottom(x, ad);
T(k,TOP) = 0.0 ;
Td(k, TOP) = 0.0;
end
for l=BOT+1:TOP-1
T(LEFT,l) = T(LEFT+1,l) ;
Td(LEFT,1) = Td(LEFT+1,1);
T(RIGHT,l) = T(RIGHT-1,l) ;
Td(RIGHT,l) = Td(RIGHT-1,l) ;
end
end
function [res, resd, resNorm, resNormd] = residual ( T, Td )
resNorm = 0.0 ;
res = 0.0 ;
resd = 0.0;
resNormd = 0.0;
for k=LEFT+1:RIGHT-1
for l = BOT+1:TOP-1
r = T(k-1,l) - 2*T(k,l) + T(k+1,l) + T(k,l-1) - 2*T(k,l) + T(k,l+1) ;
rd = Td(k-1,l) - 2*Td(k,l) + Td(k+1,l) + Td(k,l-1) - 2*Td(k,l) + Td(k,l+1);
res(k,l) = r ;
resd(k,l)= rd;
resNorm =resNorm+ r^2 ;
resNormd=resNormd+ 2*r*rd;
end
end
end
function [T, Td] = update_explicit ( T, Td, res, resd, cfl )
for k=LEFT+1:RIGHT-1
for l = BOT+1:TOP-1
T(k,l) = T(k,l) + cfl*res(k,l) ;
Td(k,l) = Td(k,l)+cfl*resd(k,l);
end
end
end
function [L, Ld] = cost ( T, Td )
L = 0 ;
Ld = 0;
for k = LEFT+1:RIGHT-1
x = get_x ( k ) ;
if ( x < -0.5 )
fTarget = 0 ;
elseif ( x < 0.0 )
fTarget = 1 ;
else
fTarget = 0 ;
end
f = ( T(k,TOP)-T(k,TOP-1) )/DY ;%% actual flux between internal node and ghost node at i.
fd = (Td(k,TOP)-Td(k,TOP-1))/DY;
df = fTarget-f ;%% difference to target.
dfd =-fd;
L = L + df^2 ;%% norm.
Ld = Ld + 2*df*dfd;
end
L = sqrt(L/MX) ;
Ld = (0.5*Ld*sqrt(1/MX))/sqrt(L);
end
for i=1:MDVAR
ad = zeros(1,MDVAR) ;
ad(i) = 1 ;
fprintf ( 'variable %d\n', i ) ;
[T, Td] = init () ;
[L,Ld, T, Td] = heatEq_solve_explicit ( T, Td, cfl, a, ad, tol, maxIter, fprintfreq );
v(i)=Ld;
fprintf ( ' a = %g\n', v(i)) ;
end
end
Last edited by a moderator: