dlfeval returns incorrect gradient
4 views (last 30 days)
Show older comments
Hi Everyone,
I am using the Deep Learning toolbox, dlfeval and dlgradient, to evaluate a function's derivatives for an optimization problem. Although the code runs, the gradient it is calculating is incorrect. Are there resouces I can explore to find out what is going wrong with the code, or any sense of what might be causing issues int he calculations? Thank you!
I am including the portion of my code in question below, but can provide more if it helps find a solution. All code until the "CODE ABOVE HAS BEEN VERIFIED" line has already been confirmed to be functional in another code.
x = dlarray(x);
[c,dc,vms] = dlfeval(@stress_objVal_objGrad,x,penal,nelx,nely,KE,H,Hs,beta,E0,Emin,...
F,freedofs,fixeddofs,nu);
function [c,dc,vms] = stress_objVal_objGrad(x,penal,nelx,nely,KE,H,Hs,beta,E0,Emin,...
F,freedofs,fixeddofs,nu)
%% FILTER
x = x(:);
xTilde = (H*x)./Hs;
xPhys = 1-exp(-beta*xTilde)+xTilde*exp(-beta);
xPhys = reshape(xPhys,[nely,nelx]);
%% FEA
[U] = FE(nelx,nely,xPhys,penal,KE,E0,Emin,F,freedofs,fixeddofs);
%% CODE ABOVE HAS BEEN VERIFIED
nele = nelx*nely;
nodenrs = reshape(1:(1+nelx)*(1+nely),1+nely,1+nelx);
edofVec = reshape(2*nodenrs(1:end-1,1:end-1)+1,nelx*nely,1);
edofMat = repmat(edofVec,1,8)+repmat([0 1 2*nely+[2 3 0 1] -2 -1],nelx*nely,1);
%Strain-Displacement matrix for 4-node element
B = [-1/2 0 1/2 0 1/2 0 -1/2 0
0 -1/2 0 -1/2 0 1/2 0 1/2
-1/2 -1/2 -1/2 1/2 1/2 1/2 1/2 -1/2];
% UE = reshape(sum(U(edofMat),2),nely,nelx);
%Constitutive matrix for plane stress
DE = 1/(1-nu^2)*[ 1 nu 0
nu 1 0
0 0 (1-nu)/2];
%% CODE OF CONCERN BEGINS HERE:
q = 1;
xPhys = xPhys(:);
E = Emin+xPhys.^q*(E0-Emin);
% Stress Calculation
s = (U(edofMat)*(DE*B)').*repmat(E,1,3);
vms = sqrt(sum(s.^2,2)-s(:,1).*s(:,2)+2.*s(:,3).^2);
c=max(vms);
%% CALCULATE GRADIENT
dc = -1*dlgradient(c,x);
dc = reshape(dc,[nely,nelx]);
vms = reshape(vms,[nely,nelx]);
end
2 Comments
Torsten
on 27 Nov 2022
We must have executable code that reproduces the computation for what you think gives wrong results.
The code from above does not help in this respect.
Answers (0)
See Also
Community Treasure Hunt
Find the treasures in MATLAB Central and discover how the community can help you!
Start Hunting!