## Welcome to the World of Modelling and Simulation

### What is Modelling?

This blog is all about system dynamics modelling and simulation applied in the engineering field, especially mechanical, electrical, and ... ### A Python Program for Application of the Newton-Raphson Method

In this tutorial, we will develop a simple Python program to implement the famous Newton-Raphson algorithm. Let us consider the following function:

f(x) = exp (-0.5x) (4 - x ) - 2

We will find the roots of the above function by the Newton-Raphson approach and code them using Python. We will start with an initial guess for the solution and then change it to check for other initial guesses to see whether the solution converges or diverges. This is a very basic and fundamental application of the Newton-Raphson method to find the roots of an unknown function. In the following, Python codes are written by Anaconda to find the roots of the unknown function by the Newton-Raphson method. We begin with, x = 2 for our first initial guess.

Python Script for Newton-Raphson Method

import sympy as sp  # Importing symbolic mathematics library
import pandas as pd  # Importing pandas to work with arrays
import math # Importing mathematics library
def f(x):
return (math.e**(-0.5*x)*(4-x))-2  # Given function
x = sp.symbols('x')
fp = f(x).diff(x) # Derivative of the function
x_value =  # Initial guess
error = 
tol = 0.0001
MaxIter = 100
i = 0
while i <= MaxIter and abs(error[i]) > tol: # Setting convergence criteria
x_new = x_value[i] - (f(x_value[i])/fp.subs(x,x_value[i])) # Newton-Raphson Algorithm
x_value.append(x_new)
ernew = (x_new - x_value[i])/x_new
error.append(ernew)
i+=1
solution = [[i, x_value[i], error[i]] for i in range(len(x_value))];
solution_new = pd.DataFrame(solution,columns=["No of Iterations", "x_value", "Error"])
print(solution_new)

Results:

When x = 2,

No of Iterations            x_value                Error
0                 0                  2                    1
1                 1  0.281718171540955    -6.09929355660769
2                 2  0.776886845045375    0.637375541447737
3                 3  0.881707878928567    0.118884084386961
4                 4  0.885703241166645  0.00451094909940144
5                 5  0.885708801994023  6.27839236320089e-6

So, the algorithm converges for the initial guess, x = 2.

When x = 6,

The algorithm diverges, relative error is NAN or infinity.

When x = 8,

The algorithm again diverges, relative error is close to infinity.

As we see from the results that the algorithm converges only when x = 2, but it diverges for the other two cases. The reason behind this is the derivative of the given function is zero when x = 6 and close to zero for x = 8. Since the slope of the function reaches to zero, the algorithm fails to provide a converged solution. From this example, it is evident that for any numerical method to work for a solution, the initial condition is a very important parameter, which needs to have an educated guess.

#Python #PythonScripting #NewtonRaphson #NumericalMethod

### Understanding the Role of the Friction Force in Dynamics with an Example

In this blog post, I would like to discuss an example from the web, which may help understand better about the presence and significance of the friction force in dynamics. Friction plays a very vital role in our daily activities, for example walking, driving, etc. are all possible for us because of friction. We mostly know that the friction is a resistive force (opposes the motion), but it is also a driving force (aids the motion). The following example problem enlightens both the facts of the friction force. It is explained below.

Example Problem:

A 0.5 kg wooden block is placed on top of a 1.0 kg wooden block. The coefficient of static friction between the two blocks is 0.35. The coefficient of kinetic friction between the lower and the level table is 0.20. What is the maximum horizontal force that can be applied to the lower block without the upper block slipping? Here, the lower block has twice the weight than the upper block. In order to keep the upper block from sliding while a horizontal force is applied to the lower block, the static friction between two blocks has to be the key factor. The maximum static force is calculated as follows,

Ff = 𝛍ₛ FN

According to the Coulomb’s friction model, this static friction is solely dependent on the weight of the body. The more the weight is the more static friction is generated. Say, if we apply a horizontal force on the lower block to move it to the right on the table as in the figure, the upper block would slide backward to the left on the table. And, this is dependent on the friction force between the block surfaces, which can resist the upper block’s sliding motion to the opposite to the lower block. For this problem, to satisfy the above mentioned condition, the friction force acting between the block surfaces must act to the right, which is acting same direction as the applied horizontal force on the lower block. This friction force will resist the upper block sliding backward and maintain the same acceleration for both of the blocks as well. Again, this friction force might be termed driving force in a sense to keep the upper block in its position while the actual driving force to create acceleration is done by the horizontal force applied on the lower block.

The following free body diagram for the upper block will show the direction of the forces and calculation of the system acceleration. Also, another free body diagram is shown later for the combined blocks where we apply the Newton’s second law to determine the required horizontal force on the lower block to keep preventing the  sliding of the upper block.

From the above calculation, we see that for the upper block, the direction of acceleration and maximum friction force is the same. So, for the upper block, we may imply that the friction works as a driving force. The magnitude of the friction force is 1.7 N. Next, we are going to calculate the acceleration based on this frictional force and consider the free body diagram of the two blocks together as well.

Here, we see from the combined free body diagram of the problem that the friction force acts opposite to the applied horizontal force. The applied horizontal force to the lower block is the driving force and friction is the resistive force in this case. Now, we will calculate the net maximum horizontal force that can be applied to the lower block without the upper block slipping using the Newton’s second law of motion again.

By this example, we see that the friction is a resistive force when we consider the overall system (two blocks together); however, it is a driving force for the upper block as per the fundamental laws of motion. The compliance or stiffness (inverse of compliance) is a tendency to resist tension or compression in a system, which is a conservative force (restores energy). But friction is a non-conservative force (dissipates energy), and due to its obvious presence in physical systems, we have some losses from the system in terms of heat, wear and tear, and so on. This may serve as an intuitive example, in regards to realizing the friction force in a conspicuous manner
.

#FreeBodyDiagram #Friction #CoulombFriction #ResistiveForce #NewtonsLaw #Blog #Blogger

### How to Convert Graphics to Solid Body in CATIA

This tutorial demonstrates how to convert a Stereolithography Mesh (.stl) graphics object to solid editable body in CATIA V5. This is useful when we require to modify an STL object file in any CAD processing tool, such as, AutoCAD, Autodesk Inventor, SolidWorks, CATIA, and so forth. It is also important when we plan to do a Finite Element (FE) analysis of an object that is available only in the STL format. For the demonstration purpose, this tutorial uses an STL image of an anonymous patient having Scoliosis, which is available online. You can download the file from this site.

## Processing an Image in CATIA

At first, open CATIA V5, then go to 'Start' and select ‘Shape’, then choose ‘Digitized Shape Editor’. See the screenshot below for the process.

After that, in the following window, just click ‘ok’ to create a new part file.

We will now import the (.stl) by clicking the ‘Import’ option as highlighted below.

Next, click ‘Apply’ and then select ‘ok’ to import the (.stl) file, which looks like below:

Since, we have imported an STL file from third-party source, we need to check the quality of the image, and clean it up. There is an option ‘Mesh Cleaner’, click it, and the following window will appear.

A pop-up small window will appear. Select the object, and then click ‘Analyze’. Click on the ‘Isolated Triangles’ option, and change the color, so that you can visualize it clearly. In this case, we see it is yellow.

As you notice that we are in the ‘Deletion’ mode of the ‘Mesh Cleaner’ window. So, we need to delete those unwanted or corrupted triangles to make it a valid solid body. Otherwise, the conversion either might fail or proceed, but in that case with lots of corrupt meshes that will hamper your analysis.

As we see, there are 60999 corrupt triangles, which need to be discarded. This may also remove some parts from the image, but if that part is not significant, then it may be alright to proceed depending on our requirement. We just need to make sure that we have our concerned region unaffected for the analysis. Next, click on the ‘Long Edges’ and continue the same process for removing the corrupt regions. The last option is the ‘Small Angles’, which we need to select and click ‘Apply’.

After the process is done, the following window will appear. We see that there are three ‘Non-manifold Vertices’ that need to be removed as well in a similar way.
We need to continue the mesh cleaning process at least twice to make sure that we have removed all the corrupt segments. After doing so, we will have the following image without the unwanted meshes.

Next, we need to click on the ‘Structure’ tab and subsequently, click on the ‘Orientation’, and ‘Split in Connected Zones’ options to check the followings. If the color for the ‘Orientation’ stays same, as in this case, ‘Yellow’, then we are good to go. For the ‘Split in Connected Zones’, there should be nothing specified in the window as highlighted by the following two screenshots below.

After the above process, we need to click Start > Shape > Quick Surface Reconstruction. The steps are depicted below.

Next, click Insert > Surface Creation > Automatic Surface. Just follow the following instructions shown by the image.

The following window will appear. Try to keep the parameters same as shown in the tiny popped-up window. Then, hit ‘ok’.

We are almost done in creating the Solid Body. After the automatic surface creation, we need to close the surface, which is depicted below. Click Start > Mechanical Engineering > Part

Then follow this sequence: Insert > Surface-Based Features > Close Surface.

We are all done. Finally, we need to save it as a 'CATIA part' file and also export it to (.igs) format in case if somebody wants to perform FE analysis.

The following image shows the closed view of the processed solid 3D Scoliosis skeleton that may be used for any analysis that needs geometry manipulation.

#Catia #ReverseEngineering #3Drendering #3Dmodel #ImageProcessing #Blog #Blogger

### How to Solve a System of Partial Differential Equations in MATLAB?

In this tutorial, we are going to discuss a MATLAB solver 'pdepe' that is used to solve partial differential equations (PDEs). Let us consider the following two PDEs that may represent some physical phenomena. Sometimes, it is quite challenging to get even a numerical solution for a system of coupled nonlinear PDEs with mixed boundary conditions. This example demonstrates how we may solve a system of two PDEs simultaneously by formulating it according to the MATLAB solver format and then, plotting the results. This method is relatively easier and saves time while coding.

∂y₁/∂t = 0.375 ∂²y₁/∂x² + A(y₁ - y₂)          (1)

∂y₂/∂t = 0.299 ∂²y₂/∂x² - A(y₁ - y₂)          (2)

Where, A is a function of sinusoidal x, meaning that A = sin (x). The above two equations have two derivative terms. The time derivative, generally represents parabolic equation, and the spatial derivative defines elliptic equation. So, we have both forms of PDEs and the highest order is two in the space. There is one limitation of the 'pdepe' that you need to have the parabolic term in the PDEs in order to solve by the 'pdepe'. Now, let's assume, we have the following initial conditions:

y₁(x,0) = 1

y₂(x,0) = 0

The boundary conditions are,

∂/∂x y₁(0,t) = 0

y₂(0,t) = 0

∂/∂x y₂(1,t) = 0

y₁(1,t) = 1

The initial and boundary conditions are true if 0 ⩽ x ⩽ 1 and t ⩾ 0. Before we move forward with the coding, we need to understand first how the 'pdepe' solver accepts the PDEs in MATLAB, which form it recognizes. The general form of PDEs that the solver understands is of the following form:

Here,

x is the independent spatial variable.

t is the independent time variable.

y is the dependent variable being differentiated with respect to x and t. It is a two-element vector where y(1) is y₁(x,t) and y(2) is y₂(x,t).

m is the symmetry constant. For cartesian coordinate, the value is 0; for cylindrical coordinate, the value is 1; and for spherical coordinate, it is 2. For our problem, it is 0 as our coordinate system is simply cartesian.

The functions c, f, and s refer to the coefficients in the above two PDE equations (1) and (2), which are required in a form that is usually expected by 'pdepe' solver.

So, in the above mentioned form, the coefficients of the PDEs may be arranged in a matrix and the equations become as,

Now, we are ready to begin the coding. In the MATLAB, we may create three functions, for example, the first function is for the equations, the second function is for the initial conditions, and the third function is for the boundary conditions. Also, we may incorporate all these functions inside another global function that is convenient as we would have everything in a single file. As the MATLAB solvers use the finite difference approach, the time integration is done with the MATLAB ‘ode15s’ solver. So, the ‘pdepe’ takes advantage of the capabilities of the stiff ‘ode15s’ solver for solving the differential-algebraic equations (DAE), which may arise when the PDEs contain elliptic equations. It is also used for handling the Jacobians with a certain sparsity pattern. Now, if there is an error during the solution process, you may try to refine the mesh size as the initial conditions are sensitive and sometimes are not consistent with the mesh size and the solver.

## MATLAB Program:

function system_of_PDEs
close all
clear
clc

% Discretization of the simulation domain
x = linspace(0,10,100);
t = linspace(0,10,100);

% Application of the Matlab partial differential equation solver 'pdepe'
m = 0;
sol = pdepe(m,@pde_func,@pde_ics,@pde_bcs,x,t);

% The solution matrices
y1 = sol(:,:,1);
y2 = sol(:,:,2);

figure(1)
surf(x,t,y1)
title('y_1(x,t)')
xlabel('Distance x')
ylabel('Time t')

figure(2)
surf(x,t,y2)
title('y_2(x,t)')
xlabel('Distance x')
ylabel('Time t')

% Equations to solve
function [c,f,s] = pde_func(x,t,y,dydx)
% Equations arranged for the 'pdepe' solver
c = [1; 1];
f = [0.375; 0.299].*dydx;
A = sin(x);
s = [A; -A];
end

% Initial Conditions
function u0 = pde_ics(x)
u0 = [1; 0];
end

% Boundary Conditions
function [pl,ql,pr,qr] = pde_bcs(xl,ul,xr,ur,t)
pl = [0; ul(2)];
ql = [1; 0];
pr = [ur(1)-1; 0];
qr = [0; 1];
end

end

## Results:

The following results show the variations of the two dependent variables, y₁, and y₂, with respect to both space (x) and time (t). We may use the MATLAB 'Surface Plot' feature to do that.

#PDE #Matlab #FiniteDifference #HyperbolicEquation #PDEPE #Blog #Blogger

### Application of the Taylor Series to Determine the Unknown Coefficients of a Polynomial

Let's say, we have a polynomial equation of the following form.

y = ax^b + 5

Where, a, and b are the unknown coefficients of the polynomials. In this tutorial, we will discuss a method to determine the unknown coefficients using the Taylor series expansion assuming the data points are provided.

From the above polynomial equation, y is the dependent variable, and x is the independent variable. Let's assume that we know ten data points for the polynomial so that the following equations may be written based on the data points:

y₁ = ax₁^b + 5

y2 = ax2^b + 5

y3 = ax3^b + 5

.
.
.

y10 = ax10^b + 5

This model seems to have a nonlinear dependence on the parameters a and b. Nonlinear regression can be used here to estimate these parameters. Nonlinear regression is based on determining the values of the parameters that minimize the sum of the squares of the residuals and the solution is preceded in an iterative manner. The Gauss-Newton method is one of the algorithms which minimize the sum of the squares of the residuals between nonlinear equation and data. A Taylor series expansion is used to express the nonlinear equation is an approximate linear form. After that, least square method is applied to estimate the parameters, which move towards the minimization of the residuals.

yi = f(xi; a,b,c) + ei;          i = 1, 2, 3, ... ... ... 10

Where, yi is a measured value of the dependent variable,  f(xi; a,b,c) is the nonlinear function of the independent variable, xi, with two unknown parameters a, b, and one given parameter c, which is 5 according to the given correlation. The last term ei is the random error. The model may be represented in a short form without the parameters for convenience as,

yi = f(xi) + ei                               (1)

For the two parameters case, a Taylor series expansion is written for the first two terms as,

Here, j is the initial guess, j+1 is the prediction, ∆a = aj+1 - aj and ∆b = bj+1 - bjEquation (2) is substituted to equation (1) which yields,

In matrix form, equation (3) may be written as,

Where, Zj is the matrix of the partial derivatives of the function at the initial guess j.

The vector {D} contains the difference between the measurements and function values at 10 points.

And, the vector {A} contains the changes in the parameters’ values as,

Applying least square method to equation (4) results the following normal equation,

Equation (5) is implemented to solve for {∆A} to estimate the improved values of the parameters a and b,

aj+1 = aj + ∆a

bj+1 = bj + ∆b

Thus, this procedure is continued until the solution converges.

#TaylorSeries #Polynomial #NonlinearRegression #LeastSquare #Matlab #Blog #Blogger

### Discussion of the Secant Method to Solve an Equation

Let's consider the following equation:

eˣ = 2x² + 1

We may write the above expression as,

f(x) = eˣ - 2x² - 1

To find the value of x or roots of the equation, we may apply the Secant method. In this method, the derivative may be approximated by a backward finite divided difference approach. So, the function may be expressed as,
This method is convenient when evaluating derivative for some function is difficult in Newton-Raphson method. Now, the above equation may be substituted in Newton-Raphson’s formula to get the following algorithm.
In contrast to Newton-Raphson method, two initial assumptions are made for the two unknowns’ xi-1 and xi.
For the proper initial guess for x, graphical method is applied to visualize the characteristics of the function. The MATLAB commands generate the plot of the function f(x). This function is plotted with respect to the values of x from -10 to +10. The following figure shows the function plot. From the plot, the function changes sign when x is between 2 to 3. So, the root lies in this interval. And, in the program developed for Secant method, two initial guesses for xi-1 and xi are 2 and 3 respectively.

However, more close observation reveals two roots, which are shown in the following figure. In this time, the range of x is decreased significantly for precise investigation between -2 to +2 as this interval seems unclear in the previous figure for the presence of any roots.

So, the above figure shows the existence of other two roots, which lie in between 0.1 to 1 and at the origin. The origin is obvious for this case, and there is no need for any further estimation by numerical methods. But, for the interval 0.1 to 1, the accurate and precise approximation is necessary. For this, the two initial guesses are set to 0.1 and 1 for xi-1 and xi accordingly.
The following Secant formula is implemented to approximate the two roots lie in the intervals 2 to 3 and 0.1 to 1. The results are shown after the program.

Secant Formula Implementation by a MATLAB Program

% Definition of a function "secant" to solve equation by Secant Method

function [x,ea] = secant(X,X0,etol)

format long;

% Input: X,X0, etol=Tolerance definition for error
% Output: x, ea=Calculated error in loop
% Iterative Calculations

while (1)

% Implementation of Secant Algorithm

solution = X-((exp(X)-(2*X^2)-1)*(X0-X))/((exp(X0)-(2*X0^2)-1)-(exp(X)-(2*X^2)-1));
solutionprevious=X;
X0=X;
X=solution;

if (solution-solutionprevious)~=0        % Approximate percent relative error

ea=abs((solution - solutionprevious)/solution)*100;

end

if ea<=etol,

break,
end

x = solution;

disp(x);

end

% Display of output parameters

disp(x);

disp(ea);

%disp(solution-(0.1*abs(ea)*solution));
end

Outputs:

>> secant (3, 2, 1e-5)
% Iterations

2.597424571529533
2.796706966294471
2.858723109017894
2.841817367110900
2.842657964680533
2.842673428005184
2.842673428005184

>> secant(1, 0.1, 1e-5)
% Iterations

0.308929151717719
0.570046187158243
1.157486960694727
0.682985699401547
0.723807551583747
0.742065590882227
0.740827136083267
0.740850398734311
0.740850398734311

So, the solutions for the equation are 2.842673428005184, 0.740850398734311 and 0.

#SecantMethod #RootsofEquations #Matlab #NumericalMethod #Blog #Blogger