I am currently writing a Python script to perform the kinematic analysis of a four-bar linkage.
A four bar linkage can be mathematically expressed as a vector loop equation:
a\*e^(j\*theta1) + b\*e^(j\*theta2) + c\*e^(j\*theta3) + d\*e^(j\*theta4) = 0
where:
ais the length of the driving link andtheta1is the angular displacement of the driving linkbis the length of the coupler link andtheta2is the angular displacement of the coupler linkcis the length of the output link andtheta3is the angular displacement of the output linkdis the length of the base link andtheta4is the angular displacement of the base link
Here, the values of a, b, c, d, and theta4 are known, while theta1 acts as the input variable. Thus, theta2 and theta3 are functions of theta1.
For the first part of the script, I want sympy to do the following:
- Rewrite the equation to its trigonometric form
- Separate the real and imaginary parts of the equations
The current code I have is as follows:
from sympy import *
a, b, c, d, theta1, theta4 = symbols("a b c d theta1 theta4", real=True)
theta2 = Function("theta2")(theta1)
theta3 = Function("theta3")(theta1)
vector_loop = a*exp(I*theta1) + b*exp(I*theta2) + c*exp(I*theta3) + d*exp(I*theta4)
vector_loop_trig = vector_loop.rewrite(cos).expand()
vector_loop_real = re(vector_loop_trig)
vector_loop_im = im(vector_loop_trig)
The output I get from the code is:
Real part:
a⋅cos(θ₁) - b⋅cos(re(θ₂(θ₁)))⋅sinh(im(θ₂(θ₁))) + b⋅cos(re(θ₂(θ₁)))⋅cosh(im(θ₂(θ₁))) - c⋅cos(re(θ₃(θ₁)))⋅sinh(im(θ₃(θ₁))) + c⋅cos(re(θ₃(θ₁)))⋅cosh(im(θ₃(θ₁))) + d⋅cos(θ₄)
Imaginary part:
a⋅sin(θ₁) - b⋅sin(re(θ₂(θ₁)))⋅sinh(im(θ₂(θ₁))) + b⋅sin(re(θ₂(θ₁)))⋅cosh(im(θ₂(θ₁))) - c⋅sin(re(θ₃(θ₁)))⋅sinh(im(θ₃(θ₁))) + c⋅sin(re(θ₃(θ₁)))⋅cosh(im(θ₃(θ₁))) + d⋅sin(θ₄)
However, the output I should be getting is:
Real part:
a⋅cos(θ₁) + b⋅cos(θ₂) + c⋅cos(θ₃) + d⋅cos(θ₄)
Imaginary part:
a⋅sin(θ₁) + b⋅sin(θ₂) + c⋅sin(θ₃) + d⋅sin(θ₄)
How can I fix my code to get the correct output?