Full text
Study of Automatic Differentiation in Topology Optimisation Document: Project Report Author: Mascarilla Guiu, Valeri Director/Co-director: Ferrer Ferre, Alex Degree: Bachelor in Aerospace Vehicles Engineering Examination session: Spring 2023
Study of Automatic Differentiation in Topology Optimisation Abstract This bachelor final thesis presents a study on the integration of automatic differentiation functions into basic topology optimisation algorithms to improve not only computation speed, but also efficiency and accuracy. The main goal is to develop a fully functional automatic differentiation script capable of deriving topological expression, linear or non linear ones, aiming to find the optimal distribution. Moreover, the objectives of this research are to explore the application of automatic differentiation in fields related to topology optimisation, analyse the benefits of applying this methods and its disadvantages and review its computational efficiency. The thesis begins by introducing the fundamentals of automatic differentiation. Beforehand, during the initial stages of the project extensive practice of Matlab programming and object oriented programming was taught but it is not included in this report. A literature review is conducted to examine existing studies and approaches that utilize AD techniques. Furthermore, we dig into different AD methods, including forward mode and reverse mode, highlighting its approach with Matlab language and their advantages and limitations. Additionally, specific topologic optimisation tools and software packages commonly used are reviewed but are not included in this report. The report continues by presenting the different discretisation cases in finite element method and developing an AD based case to solve the discretisation of different 2 dimension problems. Deriving its shape functions and testing AD for a future, more sophisticated, topological problem. To achieve the main objective of performing, at least, one topology case using automatic differentiation, an AD based algorithm using different iterative methods is developed and implemented. The algorithm is tested with basic shapes and problems to be improved and more efficient, including all the possible casuistry of a mathematical expression. Ending with the research, we test different topological cases using different iterative methods. One of these methods, newton iteration method, will need an improvement to higher order gradients of the automatic differentiation algorithm. With this improvement we will test and compare both methods for several cases to conclude about the efficiency, accuracy and computing time of both iterative methods and automatic differentiation algorithm applied to topological problems. I
The results of the study demonstrate that automatic differentiation significantly enhances the efficiency and accuracy of topological optimisation for a certain type of problems. For these cases, AD exhibits faster convergence, improved accuracy in gradient computation, and reduced computational time. Moreover, the AD-based approach proves to be robust and applicable to not only deriving structural function, but also different problem domains, highlighting its versatility and practicality. Overall, The research highlights the potential of AD in many fields. II
Study of Automatic Differentiation in Topology Optimisation Contents 1 Introduction 1 1.1 Object................................................. 1 1.2 Scope ................................................. 1 1.3 Requirements............................................. 3 1.4 Justification.............................................. 4 2 Basics of AD. 6 2.1 FunctionComputation. ....................................... 7 2.2 Forward Accumulation Derivative. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 8 2.3 Reverse Accumulation Derivative. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 9 2.4 Comparisonofmethods........................................ 10 3 Programming AD in MATLAB 12 3.1 Analysisofthegivenresults. .................................... 15 4 AD in FEM 17 4.1 ShapeFunctionsandAD. ...................................... 19 4.1.1 2D triangular shape function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 19 4.1.2 2D quadrilateral shape function. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 23 4.1.3 Conclusion of using AD in Jacobian assembly. . . . . . . . . . . . . . . . . . . . . . . . 25 4.2 ADinOptimisationProblems. ................................... 27 4.2.1 The gradient descent method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 28 4.2.2 The Newton iteration method. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 30 4.2.3 Second order gradient in Automatic Differentiation. . . . . . . . . . . . . . . . . . . . 43 4.2.4 Newton Iteration method test. . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . . 45 5 Conclusions 53 III
Study of Automatic Differentiation in Topology Optimisation List of Figures 2.1 The graph encodes the calculation of the function f(x). . . . . . . . . . . . . . . . . . . . . . . 7 2.2 The graph encodes the derivative respect to x of the function f(x) through the forward mode. 8 2.3 The graph encodes the derivative of the function f(x) through the reverse mode. . . . . . . . . 10 4.1 Discretization of a 1D topological problem. Source: [5]. . . . . . . . . . . . . . . . . . . . . . 17 4.2 Transformation of the coordinate system of a triangle element. Source: [7]. . . . . . . . . . . 21 4.3 Transformation of the coordinate system of a quadrilateral element. Source: [8]. . . . . . . . . 23 4.4 Example of the gradient descent method for a quadratic function. Source: [9]. . . . . . . . . . 28 4.5 A comparison of gradient descent (green) and Newton’s method (red) for minimising a function. Newton’s method uses curvature information to take a more direct route. Source: [10] . . . . 30 4.6 Cost function output of the circumference test to validate the Matlab AD script and the gradientdescentmethod. ...................................... 34 4.7 Example of problem described. 1 dimension and 3 node FEM test using AD. Source: [11]. . . 35 4.8 Cost function output of the 1 dimension 3 nodes test to validate the Matlab AD script and thegradientdescentmethod. .................................... 38 4.9 The straight tendency proves the feasibility of the script. . . . . . . . . . . . . . . . . . . . . . 39 4.10 Cost function output of the 1 dimension 3 nodes neohookean test to validate the Matlab AD script and the gradient descent method for non linear functions. . . . . . . . . . . . . . . . . . 42 4.11 The non linear tendency is an indicator that the script works properly. . . . . . . . . . . . . . 43 4.12 Cost function output of the test to prove the feasibility of the second order gradient script. . 44 4.13 Cost function output of the test of the newton method for a non linear function with 1 variable. 46 4.14 Cost function output of the test of the gradient descent for a non linear function with 1 variable. 46 4.15 Cost function output of the test of the newton method for a non linear function with 1 variable. 48 4.16 Results of the node 25 and node 50 after computing 50 nodes at once. . . . . . . . . . . . . . 51 4.17 Evolution of the AD script iterations as the variables increase. . . . . . . . . . . . . . . . . . 52 IV
Study of Automatic Differentiation in Topology Optimisation List of Tables 2.1 Derivative of an example function respect to x using forward accumulation. . . . . . . . . . . 9 2.2 Derivative of an example function respect to y using forward accumulation. . . . . . . . . . . 9 2.3 Derivative of an example function using reverse accumulation. . . . . . . . . . . . . . . . . . . 10 V
Study of Automatic Differentiation in Topology Optimisation List of abbreviations / Glossary AD - Automatic Differentiation. Automatic Differentiation, commonly AD, is a computational technique to evaluate the derivative of a function. A computational programme works by applying the elementary operations, such as the multiplication. By applying the chain rule to a derivative function we can obtain the desired results automatically. [1] OOP - Objected Oriented Programming. Object Oriented Programming is a model used in computer programming that organises the scripts different from traditional computing languages that use functions and logic. OOP organises with objects that have different data inside named properties, it also have different attributes that result in different approaches or behaviours. This can be useful, for example in AD, in the definition of a value and the derivative of this value. FEM - Finite Element Method. The finite element method, commonly FEM, is a popular method for numerically solving differential equations. Typical problem areas of interest include the traditional fields of structural analysis, which is what we will use FEM for, heat transfer, fluid flow, etc. [2] AI - Artificial Intelligence. Artificial intelligence, commonly AI, is a set of technologies that enable computers to perform a variety of advanced functions, including the ability to see or understand, analyse data, make recommendations, and much more. [3] VI
Study of Automatic Differentiation in Topology Optimisation Chapter 1 Introduction 1.1 Object The aim of this project is to develop an automatic differentiation algorithm in Matlab language capable of solving derivatives. Therefore, compare different approaches of solving a derivative to improve its solution and its computing time to achieve the desired and most optimised result. The different approaches are types of expressions and numerical iterations, all of them, using automatic differentiation. The AD used in this thesis will be initially developed using 2 different approaches, forward accumulation and reverse accumulation, the aim is to compute large derivatives and find the best way and the less computing time possible to improve a case. Despite similar studies in the past were focused on numerical methods to achieve a great and faster results, the difference between these studies will be the introduction of the automatic differentiation in topology optimisation, as the title describes. AD is used in machine learning, a branch of AI and computer science. As AI is growing so fast nowadays I think that the object and the final result of the project will be justified by using these methods described. 1.2 Scope 1. Matlab key features. First, I aimed to practise and improve software development in Matlab, which would be the language used for the thesis, by focusing on 3 key areas of software developing: Object oriented programming, clean code practises and GitHub integration. Combining these 3 aspects would make my code more understandable, more efficient and easier for me to code it. The initial package was focusing on clean code practices. It refers to code that is easy to read and understand, it is achieved by a sort of guidelines such as naming conventions, code order and the proper use of explanation comments. Moreover, OOP provides a structured approach to software development, i got into the fundamental concepts of OOP and explored how they could be effectively applied in MATLAB and precisely, automatic differentiation 1
1.2. SCOPE CHAPTER 1. INTRODUCTION code. Finally, I focused on integrating software or coding projects with GitHub. I explored code versioning, branching, and merging. Although this part of the thesis was a significant step toward enhancing software development, it will not be included in the report. 2. Automatic Differentiation. The aim of this package of work was the development and implementation of an automatic differentiation algorithm through the Matlab environment, using all practises described in Matlab key features. First, I made a research of information, existing techniques and algorithms in the field of automatic differentiation, even if they were not made in Matlab language, to understand the basis of its development. Based on this knowledge, I designed and implemented an algorithm that could handle a reduced range of mathematical expressions, such as addition and multiplication, useful to test the code with polynomials. Furthermore, I started to include improvements to enhance the versatility of the software by adding multiple mathematical expressions. Then, I focused in efficiency and performance of the software. Overall, the development of an automatic differentiation script represents the major step of work in this report. The implementation of a tool capable of calculate a wide range of mathematical expressions is a significant contribution. As we progress in the report, we will upgrade the code to work with multiple variables and higher order gradients. 3. Finite Element Method. This research section aimed to test the benefits of utilising the automatic differentiation script in solving partial differential equation. After the development of the automatic differentiation script, I focused on the application of it into Finite Element Method. I started with some element analysis. The script allowed to calculate, fast and efficient, the derivatives of the shape functions of different elements such as the 2 dimension triangular and quadrilateral elements. This package of work prove the viability of the automatic differentiation script as we get into more specific problems. Then I implemented the automatic differentiation script into some basic 1 dimensional beam. This involved integrating the script with the appropriate iterative solvers and algorithms such as the gradient descent method and the newton method. As I conducted these cases, I started to introduce non linear functions to the code, to prove the convergence and the viability of the code even for non linear expressions. These cases were designed to evaluate the effectiveness of the automatic differentiation script in terms of accuracy, efficiency, and optimisation performance. I compared the results obtained using the automatic differentiation with the different methods and number of nodes to assess the improvements achieved. 4. Conclusions. Finally, during the conclusion package I aimed to demonstrate the practical utility and effectiveness of the script in solving diverse engineering problems, not only derivatives, but also any case related to differentiation of an expression showing the applicability of the automatic differentiation script across a range of engineering cases. The AD algorithm demonstrated its effectiveness and versatility, which underscores the script’s potential for widespread adoption across various fields of engineering. 2
2.3. REVERSE ACCUMULATION DERIVATIVE. CHAPTER 2. BASICS OF AD. Value Derivative Evaluation z1= x = 2 ˙z1= 1 ˙z1= 1 z2= y = 0.5 ˙z2= 0 ˙z2= 0 z3= cos z1˙z3=−sinz1·˙z1˙z3=−sinx ·1 = -sin x z4=z12˙z4= ˙z1·z1+z1·˙z1˙z4= 1 ·x+x·1 = 2x z5=z22˙z5= ˙z2·z2+z2·˙z2˙z5= 0 ·y+y·0 = 0 z6=z1·z5˙z6= ˙z1·z5+z1·˙z5˙z6= 1 ·y2+x·0 = y2 z7=z3+z6+z4˙z7= ˙z3+ ˙z6+ ˙z4˙z7= - sin x + y2+ 2x = 3.3407 Table 2.1: Derivative of an example function respect to x using forward accumulation. Now, we will derive respect to the other variable, y. ∂f ∂y =∂f ∂(cosx +xy2+x2)· ∂cosx +xy2+x2 ∂y ∂f ∂y =∂f ∂(cosx +xy2+x2)· ∂(cosx) ∂y +∂xy2 ∂y +∂x2 ∂y ! ∂f ∂y = 1 · 0 + ∂xy2 ∂y2· ∂y2 ∂y !+ 0!=x·2y= 2xy Value Derivative Evaluation z1= x = 2 ˙z1= 0 ˙z1= 0 z2= y = 0.5 ˙z2= 1 ˙z2= 1 z3= cos z1˙z3=−sinz1·˙z1˙z3=−sinx ·0 = 0 z4=z12˙z4= ˙z1·z1+z1·˙z1˙z4= 0 ·x+x·0 = 0 z5=z22˙z5= ˙z2·z2+z2·˙z2˙z5= 1 ·y+y·1 = 2y z6=z1·z5˙z6= ˙z1·z5+z1·˙z5˙z6= 0 ·y2+x·2y= 2xy z7=z3+z6+z4˙z7= ˙z3+ ˙z6+ ˙z4˙z7= 2xy = 2 Table 2.2: Derivative of an example function respect to y using forward accumulation. 2.3 Reverse Accumulation Derivative. For the same function, using reverse accumulation, the procedure will be the following: f(x, y) = cosx +x·y2+x2 9
2.4. COMPARISON OF METHODS. CHAPTER 2. BASICS OF AD. ∂s ∂z = 1(seed) ∂s ∂a =∂s ∂z = 1 ∂s ∂b =∂s ∂z = 1 ∂s ∂c =∂s ∂z = 1 ∂s ∂x =−sinx · ∂s ∂a +y2 · ∂s ∂b + 2x· ∂s ∂c ∂s ∂y = 2yx · ∂s ∂b ∂f ∂x =−sinx +y2+ 2x∂f ∂y = 2yx Figure 2.3: The graph encodes the derivative of the function f(x) through the reverse mode. Value Derivative Evaluation z1= x = 2 ¯z1=−sinz1·¯z3+ ¯z4·2x+ ¯z6·y2¯z1= 3.3407 z2= y = 0.5 ¯z2= ¯z5¯z2= 2 z3= cos z1¯z3= ¯z7¯z3= 1 z4=z12¯z4= ¯z7¯z4= 1 z5=z22¯z5= 2 ·z1·z2·¯z6¯z5= 2 z6=z1·z5¯z6= ¯z7¯z6= 1 z7=z3+z6+z4¯z7= 1 ¯z7= 1 Table 2.3: Derivative of an example function using reverse accumulation. 2.4 Comparison of methods. Forward accumulation calculates the function and its derivatives in the order of the operations of the function as seen on figure 2.2. On the other hand, reverse accumulation calculates the derivatives of the function in the reverse order of the operations of the function as seen on figure 2.3. In terms of efficiency, forward 10
2.4. COMPARISON OF METHODS. CHAPTER 2. BASICS OF AD. accumulation is efficient when the number of independent variables is small and the number of dependent variables is large. On the other hand, reverse accumulation is efficient when the number of independent variables is large and the number of dependent variables is small, later in the report we will evaluate these characteristic with engineering tests. Moreover and in the same direction, forward accumulation requires storing intermediate values for every step of the calculation, which can require a lot of memory for large functions with many intermediate variables, the variables in memory can be huge and slow every iteration. Reverse accumulation does not have this issue, but requires storing the values of the dependent variables and their derivatives. Forward accumulation is relatively easy to implement, as it involves simply computing the function and its derivatives in the order of the operations of the function, while reverse accumulation is hard to understand and difficult to programme, it is helpful and in some cases also requires the use of a graph as the one on figure 2.3 to understand the algorithm which makes it more complex to implement. At the end, both forward accumulation and reverse accumulation can suffer from issues such as memory overload, numerical errors, efficiency issues, etc. In summary, forward accumulation and reverse accumulation are two different methods for computing the derivatives of a function in automatic differentiation. They differ in terms of the path to achieve the result, its efficiency, memory usage, coding complexity, etc. The choice between the two methods depends on the specific requirements, such as the number of variables, the memory constraints, and the desired precision. 11
Study of Automatic Differentiation in Topology Optimisation Chapter 3 Programming AD in MATLAB The first goal of this thesis is to develop a code that performs any kind of function using automatic differentiation in Matlab code. Furthermore, it is important to code it using object oriented method. This type of programming will guide us into a cleaner and more understandable coding experience and will empower our coding skills. First of all, to code automatic differentiation in Matlab, we will develop a class to perform forward accumulation because it is, a beforehand, easier and more understandable to programme. Moreover, the main disadvantage of forward accumulation is that the code has to run as many times as variables we have to differentiate over these variables. Nevertheless, Matlab can use a gradient vector to solve this issue. By substituting the derivative of a variable (normally the derivative value is equal to 1) for a matrix we can overcome this weakness. Leaving this feature aside, the first steps that we have followed to develop the code will be the following: [4] 1. The first step we followed to achieve the code was to define a class that represents every mathematical expression or operator that we can find, such as the sum of variables, multiplication, exponential and many more expressions. To do so we will first define a class constructor method. This method will store the variable value and gradient and during the analysis of the function it will store intermediate values and gradients. Then, the first part of the class script will look as the following: Listing 3.1: AD Forward Accumulation Class Constructor Method. 1classdef ValGradForward 2 3properties 4 5val % f u n c t i o n v alue 6 7grad % g r a d i e n t v a lu e o r g r a d i e n t v e c t o r 8 9end 10 11 methods ( Acc ess = p u b l i c ) 12 12
CHAPTER 3. PROGRAMMING AD IN MATLAB 13 function o bj = ValGradForward ( a , b ) %ValGrad c l a s s c o n s t r u c t o r ; 14 15 o bj . v a l = a ; %g i v e n f u n c t i o n v a l u e 16 obj . grad = b ; %g iv e n g r a d i e n t v a l ue o r g r a d i e n t v e c t o r 17 18 end This method will be useful to define a variable of the function, for example, if the variable to define is x, the call will be x = ValGradForward(2,1). This call means that the value of the variable x is 2 and the derivative will be over x, then the second number will be 1. If we have another variable and we want to derivative the function over the other variable, for example y with a value of 3, then, the call for both variables will be x = ValGradForward(2,0) and y = ValGradForward(3,1). For an example function, the same as the one in the previous section the call to perform the automatic differentiation will be the following: Listing 3.2: AD Forward Accumulation Class Constructor Method Call. 1x = ValGradForward ( 2 , 0 ) 2y = ValGradForward ( 3 , 1 ) 3f = c o s x + x ∗y ˆ2 + xˆ2 First, we will store the variables values in an object and then we will analyse the operation of the mathematical function using other Matlab functions that we will describe in the second point. 2. The next major step to achieve the script will be the definitions of all the function that evaluate each mathematical operations such as addition, multiplication, sin, exp, etc. These sub functions should override the evaluation and derivatives to compute the function and its gradient using the appropriate rules of differentiation. This script, with the amount of mathematical operation that can contain a function would be larger than 100 lines, which is the maximum desired length of an script. Therefore, we will create another sub sub function of every possible operation. At this point, with the function I have tested and evaluated the operations that I have included in my script are the following. Listing 3.3: AD Forward Accumulation Class Functions for some Math Operators. 1function h = p l u s ( u , v ) 2 3h = pl usFu n ( u , v ) ; 4 5end 6 7function h = minus ( u , v ) 8 9h = minusFun ( u , v ) ; 10 11 end 12 13 function h = uminus ( u , v ) 14 15 h = uminusFun ( u , v ) ; 16 17 end 18 19 function h = mtimes ( u , v ) 20 21 h = mtimesFun ( u , v ) ; 22 23 end 13
CHAPTER 3. PROGRAMMING AD IN MATLAB 24 25 function h = m rd i vi d e ( u , v ) 26 27 h = mr divi deFu n ( u , v ) ; 28 29 end 30 31 function h = mpower ( u , v ) 32 33 h = mpowerFun ( u , v ) ; 34 35 end 36 37 function h = s i n ( u ) 38 39 h = sinF un ( u ) ; 40 41 end 42 43 function h = c o s ( u ) 44 45 h = cosFun ( u ) ; 46 47 end 48 49 function h = exp ( u ) 50 51 h = expFun ( u ) ; 52 53 end 54 55 function h = l o g ( u ) 56 57 h = logFun ( u ) ; 58 59 end 60 61 function h = s q r t ( u ) 62 63 h = s qrtFu n ( u ) ; 64 65 end There are many more operations to add such as logarithm, square root, arc cosine, arc tangent, etc. The next step will be the development and the evaluation of every operation in each function. 3. For every operation we will define the evaluation of its value and derivative and we will give some examples for each case. Every function will be detailed in an appendix at the end. First we will describe the function to evaluate the operation of multiplication. For this case the function is the following. Listing 3.4: Automatic Differentiation Function of the operator multiplication. 1function h = mtimesFun ( u , v ) 2 3i f ˜ i s a ( u , 'ValGradForward ') && ˜ i s a ( v , 'ValGradForward ')%u and v a r e s c a l a r s 4h = ValGradForward (u ∗v , 0 ) ; 5 6e l s e i f ˜ i s a ( u , 'ValGradForward ')%u i s a s c a l a r 7h = ValGradForward (u ∗v . val , u ∗v . gra d ) ; 8 9e l s e i f ˜ i s a ( v , 'ValGradForward ')%v i s a s c a l a r 10 h = ValGradForward (v ∗u . val , v ∗u . grad ) ; 11 12 e l s e 13 h = ValGradForward ( u . v a l ∗v . val , u . grad ∗v . v a l + u . v a l ∗v . grad ) ; 14 15 end 16 end 14
3.1. ANALYSIS OF THE GIVEN RESULTS. CHAPTER 3. PROGRAMMING AD IN MATLAB For this case, the first thing we have to take into account is the characteristics of the variables u and v. We have to evaluate each variable and know if it is a scalar or an object with value and gradient. This is the main reason of the if statement. Therefore, we have a case for every case and for the evaluation of the derivative. If the variable is a scalar, then the value is simply the letter u or v, but if it is variable we have to add the object property, u.val or u.grad for example. For the value of the function it is really easy, following the rules that i mentioned for scalars or variables. Then, for the evaluation of the gradient, the most complicated case for this operator is when both are variables, the gradient will be u.grad * v.val + u.val * v.grad as we can see on the else statement of the previous listing. 4. At the end, it will be the same for each case and each mathematical operator. All of the function will be displayed and described in an appendix at the end of the thesis. 3.1 Analysis of the given results. Furthermore, we have much more things to add to understand the values given by the automatic differentiation class. What does the final returns mean? What will be the value and the gradient of each function for the determined point? When we run the script which calls the automatic differentiation class with the same function and variables of the first section example we will get 3 object outputs. The first 2 will be the variables x and y with each values and gradients, these outputs are not significant because they were our inputs. However, the function f will have an object output named f with a value and a gradient. The value, as we have described is the output or the result of the function for the given point, without the need of any derivative. Then the grad will be, as it is named, the gradient of the function respect the derivative that we desire. In the example we wanted to take derivatives over y. Then, the gradient given will symbolise the derivative ∂f ∂y for the given point. As we explained in the beginning of this section, one of the weakness of forward accumulation is that we have to compute automatic differentiation twice or as many times as variables we have in the function to obtain the gradient over every variable, but we found the perfect solution to avoid running the script twice and it is using vectors instead of single values for the gradient input. The first input was the one shown in the listing below. Listing 3.5: AD Forward Accumulation Class Constructor Method Call. 1x = ValGradForward ( 2 , 0 ) 2y = ValGradForward ( 3 , 1 ) 3f = c o s x + x ∗y ˆ2 + xˆ2 The difference with this second input is that the derivatives of the variables will be a vector of gradients as we can see in the next listing. Listing 3.6: AD Forward Accumulation Class Constructor Method Call with Gradient Vector. 1x = ValGradForward ( 2 , [ 1 0 ] ) 2y = ValGradForward ( 3 , [ 0 1 ] ) 3f = c o s x + x ∗y ˆ2 + xˆ2 15
3.1. ANALYSIS OF THE GIVEN RESULTS. CHAPTER 3. PROGRAMMING AD IN MATLAB The computing time is almost the same using this vector structure for the derivative of the variable and we mitigate the weakness of the forward accumulation method. For functions of more than 2 variables, which will be the ones that we will evaluate for the 3 different axis in 3 dimensions then the vectors of the derivative will be the following. Listing 3.7: AD Forward Accumulation Class Constructor Method Call with Gradient Vector. 1x = ValGradForward ( 2 , [ 1 0 0 ] ) 2y = ValGradForward ( 3 , [ 0 1 0 ] ) 3z = ValGradForward ( 4 , [ 0 0 1 ] ) If the inputs are these variables with a vector of gradients the output will be an object with a single value and 3 different gradients which will be the gradients over each variable. Finally, to transform the object to a vector of elements we will use another function named double which is as simple as transform the properties of the object into a vector. The first column of this new vector will be the value and the second column until last columns will be the gradients of each variable. And finally, to obtain a variable with the value and a vector with the gradients we will operate with the vector given. To obtain the value we will create a variable named val and we will get the first column of the vector, and for the gradient we will get from the second column until the end of the vector. The next listing shows these operation, where the vecot is named as AD. Listing 3.8: AD final variables. 1v a l = AD( : , 1 ) ; 2grad = AD( : , 2 : end ) ; In the appendix ?? at the end we will see the whole code together and the different functions of each casuistry. 16
Study of Automatic Differentiation in Topology Optimisation Chapter 4 AD in FEM The first idea that we have when building and automatic differentiation script was to optimise partial differential equations. The word optimise can be understand in different ways but, the essence of the word is, to improve. One of the main tools to perform these type of problems is Finite Element Method, mostly known as FEM, the most extended method and the most precise to solve real word problems in a lot of fields. The finite element method is a numerical method used to solve partial differential equation, named as PDE and evaluate physical phenomena in various fields as we have said, including topology but also heat transfer, fluid flow, electromagnetic, computational fluid dynamics and many more fields. This method works by dividing a continuous problem into smaller entities called nodes or elements. The idea behind this method is to represent the variables of a problem, such as the stress or displacement in a topology case as discrete values at specific locations within each element. This method gives an approximate solution to each element which is represented using shape functions (this are the functions that we will evaluate via AD). These function describe how the solution varies over one element. To perform a FEM problem, the first step to achieve a valid solution is discretization. This means to divide the object we are studying in small fields called elements. The easiest example that we will perform is a 1 dimension problem with multiple nodes such as the one in the picture 4.1 below. Figure 4.1: Discretization of a 1D topological problem. Source: [5]. In this figure we can see a 1 dimension object divided into elements, each element is between nodes which are the points where we will evaluate and derive our functions. The second step is to set the boundary conditions such as external forces and locked displacements or locked rotations. These conditions define the behaviour 17
CHAPTER 4. AD IN FEM of the problem at its boundaries and are imposed by modifying the global equations. These conditions can include prescribed values, forces, or constraints at specific nodes or elements. And finally, we would solve the system of equations using our automatic differentiation script. After that, it is time to evaluate the solution at specific points or regions of interest within each element and obtain the solution of the problem. In the evaluation of the functions is the point where automatic differentiation takes place, in these cases AD plays a crucial role in the implementation and optimisation of numerical methods like the finite element method. As we have seen, the FEM is a numerical technique used to solve partial differential equations. Also, FEM involves the minimisation of an objective functional. To find the optimal solution, the derivatives of the objective functional with respect to the unknowns need to be computed. This is where automatic differentiation comes into play. In the final section we will develop and explore this field with some examples. The benefits of using AD for these cases are more accurate and efficient solving of a FEM problem through the automatic evaluation of elementary operations such as the addition, subtraction, multiplication, division and many more used in the FEM functions and evaluated by our AD script described in section 3. This process involves analysing each part of a function and its mathematical expressions and divide these parts into a sequence of elementary operations, each with a known derivative. The derivatives are then evaluated using the chain rule. This allows for the exact computation of derivatives without the need for numerical approximations or symbolic variables, which involves a lot of computing time in Matlab. In the context of the FEM, automatic differentiation is employed in multiple stages of the computation. It can be used during the assembly of the global stiffness matrix, which involves the integration of element-level contributions. It also can help to compute the derivatives of the element stiffness matrix with respect to the nodal values, but none of these operations are a problem or require less computing time because all of these steps are well optimised because in most of the cases the functions evaluated are linear and the derivative of these functions are simply the coefficients of the variables. Nevertheless, we have also used these methods and we will describe them in the next section. The real usage of AD in FEM is using the gradient to optimise a case. AD is utilised in the computation of the gradient of the objective functional with respect to the unknowns. This gradient is often needed for optimisation purposes, such as finding the minimum of the objective functional using iterative algorithms like the gradient descent method or the newton iteration. The function is a mathematical representation of the problem we are trying to solve, and the minimum of this function represents the optimal solution. Overall, AD simplifies the FEM method by ”automating” the computation of the derivatives for solving the underlying partial differentiation equations accurately and efficiently. 18
4.1. SHAPE FUNCTIONS AND AD. CHAPTER 4. AD IN FEM 27 c o e f ( i , 3 ) = 0 . 2 5 ∗(−o b j . coor dE le m ( 1 , i ) −obj . coordElem ( 2 , i ) + obj . coordElem ( 3 , i ) + ob j . coordElem (4 , i ) ) ; 28 c o e f ( i , 4 ) = 0 . 2 5 ∗( o bj . coordElem ( 1 , i ) + obj . coordElem ( 2 , i ) + ob j . coordElem (3 , i ) + o b j . coordElem ( 4 , i ) ) ; 29 30 end 31 32 %AD u s i n g my c od e 33 x i = ValGradForward ( 1 , [ 1 0 ] ) ; 34 e ta = ValGradForward ( 1 , [ 0 1 ] ) ; 35 36 coo rd ( 1 ) = c o e f ( 1 , 1 ) ∗x i ∗e t a + c o e f ( 1 , 2 ) ∗x i + c o e f ( 1 , 3 ) ∗e t a + c o e f ( 1 , 4 ) ; 37 coo rd ( 2 ) = c o e f ( 2 , 1 ) ∗x i ∗e t a + c o e f ( 2 , 2 ) ∗x i + c o e f ( 2 , 3 ) ∗e t a + c o e f ( 2 , 4 ) ; 38 39 N = [ c oo rd ( 1 ) . d ou bl e ; c oo rd ( 2 ) . d ou bl e ] ; 40 41 %Jacobian 42 J = N( : , 2 : end ) ; 43 44 end 45 end 46 end For both cases, the triangle and quadrilateral elements, the inputs are the coordinates in the physical coordinate system, meaning the points of the first element, before the transformation, of both figure 4.2 and 4.3 and the desired points of the ξ and η coordinate system. Given example, if we choose the point -1,-1 in the reference coordinate system we will get the first point of the quadrilateral element in the physical coordinate system, for our example in the listing, the point 1,1. Despite this transformation, the important output is the Jacobian matrix, as we have explained, this matrix captures the local deformation of the element. It is also used to perform coordinate transformations, compute element stiffness matrices, and evaluate integrals over the element, among other calculations. Additionally, the determinant of the Jacobian matrix is used to account for the element’s local deformation when integrating quantities over the element. 4.1.3 Conclusion of using AD in Jacobian assembly. In both cases we have evaluated linear shape functions for 2 dimension problems. Automatic differentiation can be very useful to obtain the gradients of any function but for linear functions AD is practically not useful in practise. When the shape functions are linear, as in the case of the bilinear shape function mentioned earlier, the derivatives are constant coefficients and can be easily computed analytically. In such cases, using automatic differentiation may not provide significant advantages over analytical computation, as the derivatives can be readily determined. The coefficients of the variables are, on its own, the gradient of the function. However, when dealing with non-linear shape functions, such as the ones explained in the previous sections, the derivatives become not obvious and their evaluation becomes more complex. In this situation, AD can be particularly useful. Non-linear shape functions often arise in advanced numerical methods or when dealing with complex material models. Later in this thesis, we will evaluate a non-linear function used to compute a problem of neohookean materials. 25
4.1. SHAPE FUNCTIONS AND AD. CHAPTER 4. AD IN FEM Conclusively, while linear shape functions may not benefit significantly from automatic differentiation due to the simplicity of their derivatives, non-linear shape functions can greatly benefit from its use. AD provides accuracy, flexibility, and efficiency in evaluating derivatives, enabling more robust and accurate simulations in the presence of complex non-linear behaviour. Although the usage of AD for this case is nonsense, we have learned the basis of applying AD and our code to a FEM case and it will be useful for the upcoming AD and FEM analysis. 26
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM 4.2 AD in Optimisation Problems. We began our thesis claiming that we would optimise partial differential equations, therefore we will use Automatic differentiation to solve topological problems faster and more efficient. In the context of AD, the term optimise refers to the process of finding the optimal values or parameters of a mathematical model or function. The goal is to minimise or maximise an objective function based on certain criteria or constraints. In our case we will use the energy method to solve and optimisation problems. In our case we will derive the energy equation of a problem to find the minimum of the function. For these cases, AD can play a crucial role in optimisation because it enables the efficient computation of gradients or derivatives of the objective function with respect to the variables or parameters being optimised which is the goal of the energy method. These derivatives provide valuable information about how the objective function changes as the variables or parameters are adjusted. AD is powerful for these cases because we can compute gradients accurately and efficiently without relying on numerical approximations or manual derivations. This is particularly useful when dealing with complex models or high-dimensional optimisation problems such as neohookean materials which are not elastic and therefore the deformation is not lineal for this cases. The gradients of these functions will be challenging to compute them manually or by traditional methods. As we have explained, the goal of AD is to find the gradients which are then used in optimisation algorithms to guide the search for the optimal values of the function and problem. After finding the gradient for a point and direction of a function we will apply and compare different methods. The ones we will be studying are the gradient method and the newton method which will be more efficient but more challenging to programme. All of these methods utilise the gradients to update the variables iteratively, for our case, it will be all the time for displacements, moving in the direction that leads to a decrease or increase in the mathematical function based on the optimisation problem. As we progress in the project and in the investigation, we will see different examples of optimisation and different methods that will use an iterative process to find the ideal value. The optimisation process typically requires repeated evaluations of the objective function for different points and derivatives in each direction and for each gradient using AD. The variables or parameters are adjusted iteratively, moving towards the optimal values that minimise or maximise the objective function based on the specific problem and requirements. Summarising, AD will facilitate the finding of an optimal value of a model or function by efficiently computing and utilising gradients. AD is more efficient because it automates every function, by ”teaching” the script to solve every casuistry in every function to find the gradient for a determined point. This allows accurate and faster exploration of the solution and therefore, enabling the search for optimal solutions to difficult problems such as non lineal or complex materials. 27
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM 4.2.1 The gradient descent method. The gradient of a function is a vector that points in the direction of the increase or decrease of a function at a particular point for a particular direction. For example, in the figure 4.4 we can obtain the zero gradient if we derive over the ”weight” axis but we will not find a gradient equal to zero if we derive over the cost (it would be in the infinite). In some other cases, such as the function of a circumference, we can find the gradient equal to zero in 2 direction. We will get into this example later in the thesis. In other words, the gradient descent method tells us which way to move from a given point in order to increase or decrease the value of the function. In optimisation problems, such as the structural ones, that we want to study, we are interested in finding the minimum of the energy function. The gradient provides valuable information about the local behaviour of the function around a particular given point. By following the direction opposite to the gradient, we can iteratively update our current point to move towards the minimum (for our case, it is useful to find the minimum, but changing the sign of the iteration will lead to a local maximum). Below, we can observe figure 4.4 which describes, using an example, the process of the gradient descent algorithm to find the minimum of a quadratic function. Figure 4.4: Example of the gradient descent method for a quadratic function. Source: [9]. The gradient descent method, as we have introduced it before, is an iterative optimisation algorithm. It starts with an initial guess, for our case, it will be the displacement of the nodes and the initial guess will be a vector of zeros or ones. With this initial data, it updates the function and finds the gradient for each point and updated the initial values by taking steps proportional to the negative gradient at that point (to find a local minimum). This process is repeated until convergence is reached, meaning that the algorithm has found a point where the gradient is close to zero, indicating a minimum. Below you will find the gradient descent iteration that we have used to find the minimum and optimise the functions. For each case we have an initial value, named as u, then a succession of iterations until find 28
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM the convergence. The method that delimits convergence is the sum of the gradient vector starting from the second column (normally, the first node is fixed meaning the displacement will be zero). The problem that we have in this method is to choose the alpha value, for most of the cases, we will reach convergence by choosing an alpha equal to 0,1 but for some particular cases we will need an alpha much smaller to reach convergence harming the calculation time, in these cases we will have much more iterations. x = 1 % initial guess while abs(grad) >0 % absolute of the gradient must be 0, then convergence is reached. xk+1 =xkalpha ·gradient; end Listing 4.5: Gradient descent iteration method. 1u = [ 1 1 1 ] ; 2 3iterations = 0; 4 5[ ˜ , numElem ] = s i z e ( u ) ; 6 7gr ad = 1 + z e r o s ( 1 , numElem) ; 8 9while ab s ( sum ( gr ad ( 1 , 2 : end ) ) ) >10ˆ( −6) && iterations <10ˆ5 10 iterations = iterations + 1; 11 [ val , grad ] = iterativeADNewtonNVariables(u) ; 12 u = u −a lph a ∗grad ; 13 end Evaluation of gradient descent method. As we have seen throughout these examples, AD is a powerful technique to solve topological cases, it is efficient and accurate to compute derivatives of functions. Also, the gradient descent method is a widely used optimisation algorithm, and it has worked for our topological cases giving accuracy, precision and it reaches convergence fast. However, it may not always be the best choice for optimising functions, especially in complex scenarios. Gradient descent relies on the gradient information to update the parameters iteratively, seeking to minimise or maximise the objective function. Overall, gradient descent method is a good optimising tool, it is relatively easy to understand and implement and it has helped us throughout the experimentation with automatic differentiation. It only requires the calculation of the first gradient of a function, making it suitable for a wide range of optimisation problems. Moreover, its easy to add more variables into the iteration by making the vectors larger, that is the reason why it is particularly useful in machine learning applications, such as our automatic differentiation code, where the number of parameters can be massive. Although the convergence time has not been bad, we are looking for a even greater convergence speed, functions will be difficult and with multiple variables that require much greater speeds. Gradient descent 29
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM might converge slowly, especially in scenarios where the objective function has a complex landscape or when the learning rate is not appropriately tuned. It may require a large number of iterations to reach an optimal solution. These are the reasons why we have moved onto a new method, a priori faster and with some advantages over gradient descent method, it is not a better method for any case but it will guide us to an improvement in convergence speeds and a great improvement in our AD script. 4.2.2 The Newton iteration method. The Newton iteration [10] is another optimisation algorithm that uses the gradient. It approximates the objective function with a quadratic function and finds the minimum of the quadratic approximation. The gradient provides information about the slope of the objective function, and the second derivative provides information about the curvature. By using these derivatives, the Newton iteration can converge to the minimum more quickly than gradient descent in many cases. In figure 4.5 we can observe a visual example of this explanation. Figure 4.5: A comparison of gradient descent (green) and Newton’s method (red) for minimising a function. Newton’s method uses curvature information to take a more direct route. Source: [10] In both cases, the gradient plays a crucial role in determining the direction of movement towards the minimum. It guides the iterative updates and helps to refine the estimation of the optimal solution. Moving onto the coding, to perform a Newton iteration in Matlab, we need to define the function and run it with an initial guess. For our case, most of the time it will be a vector of 1s. This is not new, gradient descent method uses the same operation. Then we will store the value of the function and its gradient using our AD script. From now on, it is the same performance as for the gradient descent method. The main difference is that from the AD script we need the 30
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM second order gradient. To obtain this gradient we need to modify and improve our AD script. This operation will be done in next section 4.2.3. After the AD script computation we will have a matrix containing the value of the function, its gradient and its second order gradient. With these data we can perform the newton iteration. The iteration operation divides the first gradient by the second order gradient and multiplies it by the initial guess. Mathematically the operation is the following one. uk+1 =uk− f′(uk) f′′(uk) Another expression of the second order gradient is named Hessian matrix, this matrix represents the curvature of the objective function and it is obtained by dividing 1 by the second order gradient. h=1 f′′(u) Then, the newton iteration expression is as follows. uk+1 =uk−h·f′(uk) In the Matlab field this iteration will look as the listing below. Listing 4.6: Newton iteration method in Matlab. 1u = [ 1 1 1 ] ; 2 3iterations = 0; 4 5[ ˜ , numElem ] = s i z e ( u ) ; 6 7gr ad = 1 + z e r o s ( 1 , numElem) ; 8 9while ab s ( sum ( gr ad ( 1 , 2 : end ) ) ) >10ˆ( −6) && iterations <10ˆ5 10 11 iterations = iterations + 1; 12 13 [ v al , grad , g rad2 ] = i t er at ive AD N ew to n NV ar i ab le s ( u ) ; 14 15 h = g rad 2 ˆ( −1) ; 16 17 u = u −h∗grad ; 18 19 end The main reasons why the Newton method can be advantageous over gradient descent are a faster convergence thanks to the second-order gradient information about the function. By considering this additional information, the Newton method can take more direct steps towards the minimum or maximum, leading to faster convergence in many cases as we have seen in figure 4.5. Many more advantages of the newton method are the adaptive step sizes, different from the gradient descent method which had an alpha initially set, the Newton method can adaptively adjust step sizes during optimi- 31
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM sation. It uses the curvature of the function to determine step directions, which allows it to take larger steps in flat regions and smaller steps in steep regions. This adaptive behaviour helps to converge efficiently. Despite these advantages, it’s important to note that the Newton method also has its limitations. It can be computationally expensive, especially for high variables problems, as it requires calculating and inverting the Hessian matrix. Additionally, the Newton method assumes that the Hessian is positive definite and that the objective function is twice differentiable. These assumptions may not hold in all cases, limiting the applicability of the method. Advancing into our investigation we will find cases where newton method will struggle to reach convergence due to the non positiveness of the hessian matrix or the computational time with many variables. Minimum of a circumference. First, to prove the feasibility of the gradient descent method and the automatic differentiation script we chose an easy example such as the circumference function, a priori, we knew that the minimum of this function will be on the point [1,1], so when the programme reaches convergence and the gradient is zero, the value has to be the point 1,1. The function and its derivative is the following and the script used to compute this test is next. f(x, y)=(x−1)2+ (y−1)2 f′(x, y) = 2x+ 2y−4 f′(1,1) = 2 ·1+2·1−4=0 This is the analytic proof that the desired output is the value 1,1. Listing 4.7: Circumference function. Gradient descent iteration method test. 1clear ; 2 3%% DEFINE INITIAL VARIABLES AND MATRIX 4 5x = [ 0 0 ] ; 6 7plotX = z e r o s ( 5 0 , 1 ) ; 8plotY = z e r o s ( 5 0 , 1 ) ; 9pl otV alX = z e r o s ( 5 0 , 1 ) ; 10 pl otV alY = z e r o s ( 5 0 , 1 ) ; 11 12 iterations = 0; 13 14 %% ITERATE STARTING WITH A FOR WITH THE 2 VARIABLES 15 16 [ ˜ , numElem ] = s i z e ( x ) ; 17 18 gr ad = 1 + z e r o s ( 1 , numElem) ; 19 20 alp ha = 0 . 1 ; 21 32
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM 22 while ab s ( sum ( gr ad ( 1 , 1 : end ) ) ) >10ˆ(−10) && iterations <10ˆ5 23 24 iterations = iterations + 1; %i t e r a t i o n s c o unter 25 26 [ v al , g ra d ] = i t e r a t i v e A D 2 v a r ( x ) ; 27 28 x=x−a lpha ∗grad ; 29 30 %% PLOT 31 32 plotX ( i t e r a t i o n s ) = grad ( 1 ) ; 33 plotY ( i t e r a t i o n s ) = grad ( 2 ) ; 34 35 pl otValX ( i t e r a t i o n s ) = x ( 1 ) ; 36 pl otValY ( i t e r a t i o n s ) = x ( 2 ) ; 37 38 39 end 40 41 function [ v al , g ra d ] = i t e r a t i v e A D 2 v a r ( c oo rd ) 42 43 x = ValGradForward ( c oor d ( 1 ) , [ 1 0 ] ) ; 44 y = ValGradForward ( c oor d ( 2 ) , [ 0 1 ] ) ; 45 46 f = ( x −1) ˆ2 + ( y −1) ˆ 2 ; 47 48 AD = f . dou ble ; 49 v a l = AD( : , 1 ) ; 50 grad = AD( : , 2 : end ) ; As we can see in the Matlab script above, we start by setting up the initial variables and the iterations counter to 0. Normally, we would set the initial values at 1,1. but this is the point where the gradient is zero so it would run only 1 iteration. Then, the while statement began with the condition of the sum of gradients under 10 −10 , this statement will run until the gradients is very low, in terms of optimisation, we can set up this error as high or low as we want, depending on the accuracy or precision of the problem. After that, inside the while statement we iterate using the gradient descent method and the calculation of the gradients using AD is explained in the function below, on line 41. First we set the variables for its value and gradient, remember we are using forward accumulation but using a vector with all the possible gradients turning it into reverse accumulation. After setting up the main variables, the function starts to run. The output of the function will be a ValGradForward object with a value and gradient properties. To transform it to double we had created a function called double that transforms the object into an array of values. The first column will be the value and from the second column until the end will be the gradients. On the lines 48, 49 and 50 we can observe this transformation of the object to the number and more precisely from the array of numbers into value and gradient which are the variables that will go back to the iteration script. With the variables from the AD we update the point values, named as x in the script, using gradient descent method and an alpha of 0.1 and we store the variables to plot them afterwards. Finally, When the sum of the gradients reach the statement in the beginning of the iteration, we can plot the results. These results were reached within 111 iterations with the sum of the gradients being 10 −10 and with the function described 33
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM on line 46 from script above. The results are displayed in figure 4.6 below. Figure 4.6: Cost function output of the circumference test to validate the Matlab AD script and the gradient descent method. After 111 iterations, we have the desired results. The gradients tend to zero and the variables tend to 1. As we can see, from 20 to 30 iterations the graph converges, but as much precision we want to have, more iterations are needed. Therefore, we can proof that our automatic differentiation script and the gradient descent method work for these cases, then we will move onto more complex problems applied to topological optimisation and with more values meaning more variables and more difficulty. 3 node axial test. The second case we tried, more into structures field, is a simple 1 dimension FEM case, with 3 nodes. We’ll assume that the structure is a beam or a bar and the first node is fixed, meaning it will not have any displacement, and the last node is free and with a tension force applied. The node in the middle is free and without any force. This problem is represented in figure 4.7 below. 34
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM we will apply an axial force in the last node with the first node being fixed. A priori, the neohookean material will exhibit nonlinear stress-strain behaviour. Therefore, the displacement between the second node and the last node will not be proportional and the force - strain relation will not be proportional neither. The script used to test this example will use the gradient descent method, previously described, the diference between this script and the three node test will be the energy equation. The script is shown next. Listing 4.10: Three Node test of a neohookean material. Main script. 1clear ; 2 3%% DEFINE INITIAL VARIABLES AND MATRIX 4u = [ 1 1 1 ] ; 5 6iterations = 0; 7 8[ ˜ , numElem ] = s i z e ( u ) ; 9 10 gr ad = 1 + z e r o s ( 1 , numElem) ; 11 12 alp ha = 1 ∗10ˆ(−2) ; 13 14 while ab s ( sum ( gr ad ( 1 , 2 : end ) ) ) >10ˆ( −6) && iterations <10ˆ3 %w h i l e grad == 0 or i t e r a t i o n s above 10ˆ3 15 16 iterations = iterations + 1; %i t e r a t i o n s c o unter 17 18 [ val , grad ] = iterativeADThreeNodeNeoHookean(u) ; 19 20 u = u −a lph a ∗grad ; 21 22 end Listing 4.11: Three Node test of a neohookean material. Iterative AD script. 1function [ val , grad ] = iterativeADThreeNodeNeoHookean(u0) 2 3C1 = 1 ; %m a t e r i a l c o n st a n t 4D1 = 1 ; %m a t e r i a l c o n sta n t 5D = [ 1 , −1 , 0 ; −1 ,2 , −1; 0 , −1 , 1 ] ; 6 7[ ˜ , numElem ] = s i z e ( u0 ) ; 8 9G = z e r o s ( 1 , numElem ) ; 10 G( 1 , numElem ) = 1 ∗1 0 ˆ ( 0 ) ; 11 12 u1 = ValGradForward ( u0 ( 1 ) , [ 1 0 0 ] ) ; 13 u2 = ValGradForward ( u0 ( 2 ) , [ 0 1 0 ] ) ; 14 u3 = ValGradForward ( u0 ( 3 ) , [ 0 0 1 ] ) ; 15 16 F ( 1 , 1 ) = D( 1 , 1 ) ∗u1 ; F( 1 , 2 ) = D( 1 , 2 ) ∗u2 ; F ( 1 , 3 ) = D( 1 , 3 ) ∗u3 ; 17 F ( 2 , 1 ) = D( 1 , 2 ) ∗u1 ; F( 2 , 2 ) = D( 2 , 2 ) ∗u2 ; F ( 2 , 3 ) = D( 2 , 3 ) ∗u3 ; 18 F ( 3 , 1 ) = D( 1 , 3 ) ∗u1 ; F( 3 , 2 ) = D( 2 , 3 ) ∗u2 ; F ( 3 , 3 ) = D( 3 , 3 ) ∗u3 ; 19 20 I 1 = F ( 1 , 1 ) ˆ2 + F ( 2 , 2 ) ˆ2+ F ( 3 , 3 ) ˆ 2 ; 21 22 J = F ( 1 , 1 ) ∗( F ( 2 , 2 ) ∗F ( 3 , 3 ) −F( 2 , 3 ) ∗F ( 3 , 2 ) ) −F ( 1 , 2 ) ∗( F ( 2 , 1 ) ∗F ( 3 , 3 ) −F ( 2 , 3 ) ∗F ( 3 , 1 ) ) + F ( 1 , 3 ) ∗( F ( 2 , 1 ) ∗F ( 3 , 2 ) −F ( 2 , 2 ) ∗F ( 3 , 1 ) ) ; 23 24 J = F ( 1 , 1 ) ∗F ( 2 , 2 ) ∗F ( 3 , 3 ) ; 25 26 fu n1 = C1 ∗( I 1 −3 ) ; 27 28 fu n2 = 2 ∗C1 ∗l o g ( J ) ; 29 30 fu n3 = D1 ∗( J −1 ) ˆ 2 ; 41
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM 31 32 fu n4 = G( 1 ) ∗u1 + G( 2 ) ∗u2 + G( 3 ) ∗u3 ; 33 34 fu n = f un 1 −fun2 + fun3 −fun4 ; 35 36 AD = fun . dou ble ; 37 v a l = AD( : , 1 ) ; 38 grad = AD( : , 2 : end ) ; After 386 iterations and a computing time of less than 0,5 seconds the results are the expected ones. The first indicator that the iteration has been successful is the gradient which converges to 0. Then the displacements will converge to a number too. In the figure 4.10 we can see these results and the displacement for this case is 0,47 for the second node and 1,23 for the third node. It is obvious that the number is not significant because we have computed the test with random material properties but the important data is the non proportionality of these displacements and the proof that the AD works well for these cases too. Figure 4.10: Cost function output of the 1 dimension 3 nodes neohookean test to validate the Matlab AD script and the gradient descent method for non linear functions. For the same reason as for the elastic material, it is time to validate the correctness of the script. At the moment, the script accurately computes the gradients and matches the expected results, but to prove that the script works correctly, the energy function is the correct one and performs AD effectively we will evaluate the displacements over the change of the force. A priori the result is not a straight line, the force is not proportional to the displacement in a neohookean material. 42
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM Figure 4.11: The non linear tendency is an indicator that the script works properly. 4.2.3 Second order gradient in Automatic Differentiation. When it comes to write a higher order script to perform automatic differentiation it might sound challenging at the start, and it is true, there are a few challenges that you may encounter. Computing second-order or higher gradients involves differentiating the first-order gradients but for my case, the script does not return an expression with the derivative of the objective expression, it returns a number. This introduces additional complexity to the script, as you need to correctly handle the chain rule for the second order. As I stated, it may sound challenging, but at the end is as easy as it gets. The first consideration we should take into account is that manipulating double expressions would be computationally expensive, especially for large systems or high-dimensional problems. The number of operations and memory requirements increase significantly compared to first-order gradients. Remember that we managed to programme reverse accumulation by programming forward accumulation with a vector of gradients. Review section 3. Then for a second gradient will it be a matrix of gradients? After trying to code second order gradient for a long time I started to review some literature related to AD in many programming languages [4] and I realised that programming higher order automatic differentiation was relatively easy when you think about the functions of the script i programmed. The basis of my script, explained in section 3, identifies an operation, for example a multiplication, and it stores both parts of the multiplication, let’s say for u·v , it stores the u and v variables and then a function computes the value and the gradient of this operation. For the multiplication example: value = u.val ·v.val gradient = u.grad ·v.val + u.val ·v.grad Now, if we change the value of the ValGradForward for another ValGradForward call the first gradient will 43
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM be recomputed and it will be reevaluated as a new function. In the previous example the multiplication of the gradient will be the following. value of second gradient = first gradient = u.grad.val ·v.val.val + u.val.val ·v.grad.val second gradient = u.grad.grad·v.val.val+u.grad.val·v.val.grad+u.val.grad·v.grad.val+u.val.val·v.grad.grad Then, as we have explained, the call for a function and for a second order gradient is the following. Listing 4.12: Call to perform a second order gradient with automatic differentiation. 1x = ValGradForward ( ValGradForward ( u , 1 ) , 1 ) ; 2f = exp(−s q r t ( x ) ) ∗s i n ( x∗l o g (1+x ˆ 2) ) ; 3 4f i r s t G r a d = f . v al . do uble ; 5secondGrad = f . grad . do ubl e ; 6 7v al = f i r s t G r a d ( : , 1 ) ; 8grad = f i r s t G r a d ( : , 2 ) ; 9gr ad2 = secondGrad ( : , 2 ) ; The variable val is the output of the function for the given point and the grad is a vector of the gradients, then the second gradient named as grad2 is a matrix of the second gradients. To prove the second-order gradient script I will use a simple polynomial function. This test is an essential step to verify its correctness and ensure that it produces accurate results. By using a known function with known second-order derivatives, you can compare the computed gradients against the expected values. The function for testing will be as simple as x3 . Then I will run the code for many points, from -50 to 50, the expected result is a parabola for the first gradient and a straight line for the second gradient. The output of this test proves the functionality of the script and is the following figure 4.12. Figure 4.12: Cost function output of the test to prove the feasibility of the second order gradient script. 44
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM 4.2.4 Newton Iteration method test. After explaining and developing the automatic differentiation script with higher order gradients it is important to test the Newton method. As we have explained in the previous section 4.2.2, newton method is an iterative algorithm. The newton method test will be done with a non linear one variable function. This type of function will prove the feasibility of the method for non linear function but starting with only one variable. Then we will move onto functions with more variables which will be challenging for our AD script. The first function to test will be the following. f(x) = exp −√x·sin x·log(1 + x2) To test this function we had to add the operation exponential, square root and logarithm to the AD script. All of these functions will be available at the end of the report in the appendix part. The aim of these test is to find the minimum of these function using newton method. The test will prove the speed of convergence of the method, moreover, it will test accuracy and the efficiency of this test with the second order gradient. The script used to perform this iteration is the following. Listing 4.13: Test script of the newton method. 1u = 4 ; 2 3iterations = 0; 4 5grad = 1 ; 6 7while abs ( gra d ) >10ˆ(−6) 8 9iterations = iterations + 1; 10 11 [ v al , gra d , g ra d2 ] = i t e r a t i v e A D H i g h e r O r d e r ( u ) ; 12 13 u = u −grad2ˆ(−1) ∗grad ; 14 15 end Listing 4.14: Iterative script of the newton method test. 1function [ v al , gra d , g ra d2 ] = i t e r a t i v e A D H i g h e r O r d e r ( u ) 2x = ValGradForward ( ValGradForward ( u , 1 ) , 1 ) ; 3f = exp(−s q r t ( x ) ) ∗s i n ( x∗l o g (1+x ˆ 2) ) ; 4 5f i r s t G r a d = f . v al . do uble ; 6secondGrad = f . grad . do ubl e ; 7 8v al = f i r s t G r a d ( : , 1 ) ; 9grad = f i r s t G r a d ( : , 2 ) ; 10 gr ad2 = secondGrad ( : , 2 ) ; After only 7 iteration the results are shown in figure 4.13. 45
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM Figure 4.13: Cost function output of the test of the newton method for a non linear function with 1 variable. Figure 4.14: Cost function output of the test of the gradient descent for a non linear function with 1 variable. As we can see in figure 4.13 the newton method reaches convergence after 4 iterations. The same test carried out with gradient descent method converges to the same error after 75 iterations as shown in figure 4.14. This demonstrates the feasibility of the method and ensures the faster convergence attribute than the gradient descent method. As we have explained in section 4.2.2, this is because the Newton method utilises second order information about the function, which helps it converge more quickly towards the minimum. The second step on Newton method is to test similar exercises as with the gradient descent method, then, you gain valuable insights into their performance and suitability. This comparison will help make informed decisions about which method to choose based on the specific requirements and constraints of your optimisation problem. Therefore, we will try the first topological case we have tried, a 1 dimensional beam fixed at one end and with a tension force at the other end. Figure 4.7 summarises the geometry of the problem. The script used to perform this test is the following. 46
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM Listing 4.15: Test script of the newton method. 1clear ; 2 3u = [ 1 1 1 ] ; 4 5iterations = 0; 6 7grad = 1 ; 8 9while abs ( gra d ) >10ˆ(−6) 10 11 iterations = iterations + 1; 12 13 [ v al , grad , g rad2 ] = i tera tiveADNe wton ( u ) ; 14 15 h = g rad2 .ˆ( −1) ; 16 17 h = t r a n s p o s e ( d i ag ( h ) ) ; 18 19 u = u −h . ∗g rad ; 20 21 end Listing 4.16: Iterative script of the newton method test. 1function [ v al , grad , g rad2 ] = i tera tiveADNe wton ( u ) 2 3G = [ 0 ; 0 ; 1 ] ; 4G = t r a n s p o s e (G) ; 5 6u1 = ValGradForward ( ValGradForward ( 0 , [ 1 0 0 ] ) , [ 1 1 1 ; 0 0 0 ; 0 0 0 ] ) ; 7u2 = ValGradForward ( ValGradForward ( u ( 2 ) , [ 0 1 0 ] ) , [ 0 0 0 ; 1 1 1 ; 0 0 0 ] ) ; 8u3 = ValGradForward ( ValGradForward ( u ( 3 ) , [ 0 0 1 ] ) , [ 0 0 0 ; 0 0 0 ; 1 1 1 ] ) ; 9 10 W = 0 . 5 ∗( u1 ˆ2 + 2∗u2 ˆ2 + u3 ˆ2 −2∗u1∗u2 −2∗u2∗u3 ) −(G( 1 ) ∗u1 + G( 2 ) ∗u2 + G( 3 ) ∗u3 ) ; 11 12 f i r s t G r a d = W. v a l . do uble ; 13 secondGrad = W. grad . dou ble ; 14 15 v al = f i r s t G r a d ( : , 1 ) ; 16 grad = f i r s t G r a d ( : , 2 : end ) ; 17 gr ad2 = secondGrad ( 1 : end , 4 : end ) ; With a computing time of less than tenth of a second and 40 iterations, we find out that the newton method overcomes in terms of computation speed the gradient descent method. We set the same error (10 −6 ) and we got less than half of the time with 10% of the iterations done with gradient descent method. Then we can assume that, for this cases, newton method is as accurate as gradient descent method but it is much faster. The results of the test are the following in figure 4.15. 47
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM Figure 4.15: Cost function output of the test of the newton method for a non linear function with 1 variable. Starting with a 3 node test allowed us to work with a relatively small and simple problem. The simplicity of this test facilitate the understanding and the debugging of the automatic differentiation script. We had many problems with the script because, as seen in the previous code, the matrix of the second gradient is a 3x3 and the operation through the automatic differentiation script did not allowed matrix to multiply for vectors and vice versa. I encountered many problems such as incorrect dimensions for matrix multiplication. Therefore, it was necessary to check that all the automatic differentiation function scripts had the right order to multiply the matrices. This is the reason why was easier with a 3 node test, otherwise, with a 50 node test the matrix would have been 50x50 and the debugging much more difficult. Now that we have tested the script for a 3 node and it is proven that it works properly we will move on into a more challenging problem. The first test, allowed us to gain confidence in the feasibility and correctness of the script and serves as a proof. The next step is to build an even more challenging script to compute any number of nodes, starting by 4 nodes, this is a progression towards increasing the versatility and applicability of the automatic differentiation script through more fields. The benefits of this test will be several, starting with the flexibility because it will be capable of compute any number of nodes, the script will be able to accommodate the requirements, providing an accurate solution. Then, as we have explained in the previous sections, it is 48
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM important to build an scalable code, capable of handling any number of nodes, ensuring accuracy and effectiveness. With this test we will evaluate the effectiveness of computing large number of nodes independently. Independently means that every node will be computed at once, we will not wait for a node to finish its iteration and then move on to the next one. Depending on the efficiency, we will move on to more nodes but it will require an efficient script. By building a script capable of accommodating any number of nodes, we will proof the implementation of the code in any field of engineering. We anticipate the potential growth to more challenging problems by trying to compute the 50 nodes with 50 variables at once. This test means that we will minimise an expression of 50 variables with 50 different gradients at once. This will demonstrate the scalability and the efficiency of the script. The first step will be to build an script dependent on the number of nodes. The expression and the iterative script will be dependant of the number of nodes. The next script can perform a one dimension test for n variables. Listing 4.17: Call of the n variables script. 1clear ; 2no des = 5 0 ; 3u0 = 1 + z e r o s ( 1 , no des ) ; 4 5[ ˜ , numElem ] = s i z e ( u0 ) ; 6 7G = z e r o s ( 1 , numElem ) ; 8G( 1 , numElem ) = 1 ∗1 0 ˆ ( 0 ) ; %f o r c e 9 10 [ plotU , pl o tVa l , plotGrad , plotGrad2 , i t e r a t i o n s ] = newtonMethodFindMinNVariables ( u0 ,G) ; Listing 4.18: Newton method script for computing a 1 dimension test with n variables 1function [ plotU , pl o tVa l , plotGrad , plotGrad2 , i t e r a t i o n s ] = newtonMethodFindMinNVariables ( u ,G) 2 3iterations = 41; 4 5[ ˜ , numElem ] = s i z e ( u ) ; 6 7iterations = 0; 8 9gr ad = 1 + z e r o s ( 1 , numElem) ; 10 11 while abs ( sum( abs ( grad ( 1 , 2 : end ) ) ) ) >10ˆ( −6) && iterations <10ˆ5 12 13 iterations = iterations + 1; 14 15 [ v al , grad , g ra d2 ] = i t e ra t iv e AD N ew t on N Va r i ab l es ( u ,G) ; 16 17 h = g rad2 .ˆ( −1) ; 18 19 h ( i s i n f ( h ) ) = 0 ; 20 21 h = t r a n s p o s e ( d i ag ( h ) ) ; 22 23 u = u −h . ∗g rad ; 24 25 end Listing 4.19: Iterative script of the newton method for n variables. 49
4.2. AD IN OPTIMISATION PROBLEMS. CHAPTER 4. AD IN FEM 1function [ val , grad , grad2 ] = i te ra ti ve ADN ew ton NVa ri abl es ( u0 ,G) 2 3[ ˜ , numElem ] = s i z e ( u0 ) ; 4 5A = 1 ∗10ˆ(−6) ; %beam a r e a 6E = 1 ∗1 0 ˆ ( 9 ) ; %young modulus 7L = 1 ∗1 0 ˆ ( 3 ) ; %beam l e n g t h 8 9k = ( (A∗E) /L) ; 10 11 f i r s t G r a d = z e r o s ( 1 , numElem) ; 12 f i r s t G r a d ( 1 , 1 ) = 1 ; 13 14 secondGrad = z e r o s ( numElem ) ; 15 secondGrad ( 1 , : ) = 1 ; 16 17 u ( 1 ) = ValGradForward ( ValGradForward ( u0 (1 ) , f i r s t G r a d ) , secondGrad ) ; 18 19 f o r i = 2 : numElem 20 21 f i r s t G r a d = z e r o s ( 1 , numElem) ; 22 f i r s t G r a d ( 1 , i ) = 1 ; 23 24 se co ndG rad = z e r o s ( numElem ) ; 25 secondGrad ( i , : ) = 1 ; 26 27 u ( i ) = ValGradForward ( ValGradForward ( u0 ( i ) , f i r s t G r a d ) , secondGrad ) ; 28 end 29 30 d i s p = ( u ( 1 )−u ( 2 ) ) ˆ 2 ; 31 32 f o r i = 2 : ( numElem−1) 33 34 d i s p = d i s p + ( u ( i )−u ( i +1) ) ˆ 2 ; 35 36 end 37 38 % f o r i = 2 : ( numElem−1) 39 % 40 % d i s p = d i s p + (−u ( i −1)+2∗u ( i )−u ( i +1) ) ˆ 2 ; 41 % 42 % end 43 % 44 % d i s p = d i s p + (−u ( numElem−1)+u ( numElem ) ) ˆ 2 ; 45 46 d i s p = k ˆ2 ∗disp ; 47 48 f o r c e = G( 1 ) ∗u ( 1 ) ; 49 50 f o r i = 2 : numElem 51 52 f o r c e = f o r c e + G( i ) ∗u ( i ) ; 53 54 end 55 56 W = 0 . 5 ∗disp −f o r c e ; 57 58 f i r s t G r a d = W. v a l . do uble ; 59 secondGrad = W. grad . dou ble ; 60 61 v al = f i r s t G r a d ( : , 1 ) ; 62 grad = f i r s t G r a d ( : , 2 : end ) ; 63 gr ad2 = secondGrad ( 1 : end , (1+numElem ) : end ) ; After some tries the script work properly for any number of nodes, having said that the 50 node test lasted for almost 500 seconds of computing time and after 27416 iterations the result converges to the right solution. Despite proving that the software is scalable and can perform many numbers of nodes at once, we can conclude that this is not the right way to compute these type of problems. Computing all 50 nodes simultaneously requires storing the intermediate results for each node in memory, adding all the gradients and the matrices of 50x50 for every computation makes the script slower and time consuming. On the other hand, as we 50