2.2 Dinamika — Amaliyot
Laboratoriya ishi: Python da kuch va harakat simulyatsiyasi
1. Nyuton Qonunlari Simulyatsiyasi
import numpy as np
import matplotlib.pyplot as plt
class Particle:
def __init__(self, mass, pos, vel):
self.m = mass
self.pos = np.array(pos, dtype=float)
self.vel = np.array(vel, dtype=float)
self.acc = np.zeros(2)
self.history = [self.pos.copy()]
def apply_force(self, force):
"""Nyuton II: F = ma -> a = F/m"""
self.acc = np.array(force) / self.m
def update(self, dt):
"""Euler integratsiya"""
self.vel += self.acc * dt
self.pos += self.vel * dt
self.history.append(self.pos.copy())
def get_trajectory(self):
return np.array(self.history)
# Simulyatsiya: kuch ta'siri
particle = Particle(mass=2, pos=[0, 0], vel=[0, 0])
dt = 0.01
t_max = 5
for t in np.arange(0, t_max, dt):
# Doimiy kuch qo'llash
F = [10, 5] # N
particle.apply_force(F)
particle.update(dt)
traj = particle.get_trajectory()
plt.figure(figsize=(10, 6))
plt.plot(traj[:, 0], traj[:, 1], 'b-', linewidth=2)
plt.xlabel('X (m)')
plt.ylabel('Y (m)')
plt.title('Doimiy Kuch Ta\'sirida Harakat')
plt.grid(True)
plt.axis('equal')
plt.savefig('newton_simulation.png', dpi=150)
plt.show()
2. Ishqalanish Simulyatsiyasi
import numpy as np
import matplotlib.pyplot as plt
def simulate_friction(m, v0, mu_k, F_applied=0, g=10, dt=0.01, t_max=10):
"""Ishqalanish kuchi bilan harakat"""
t_list = [0]
x_list = [0]
v_list = [v0]
v = v0
x = 0
t = 0
while t < t_max and abs(v) > 0.001:
# Normal kuch (gorizontal sirt)
N = m * g
# Ishqalanish kuchi (harakatga qarshi)
if v > 0:
f = -mu_k * N
elif v < 0:
f = mu_k * N
else:
f = 0
# Natijaviy kuch
F_net = F_applied + f
# Tezlanish
a = F_net / m
# Yangilash
v += a * dt
# Tezlik 0 ga yetganda to'xtash
if (v_list[-1] > 0 and v < 0) or (v_list[-1] < 0 and v > 0):
v = 0
x += v * dt
t += dt
t_list.append(t)
x_list.append(x)
v_list.append(v)
return np.array(t_list), np.array(x_list), np.array(v_list)
# Simulyatsiya
m = 5 # kg
v0 = 20 # m/s
mu_k = 0.3
t, x, v = simulate_friction(m, v0, mu_k)
fig, axes = plt.subplots(1, 2, figsize=(14, 5))
axes[0].plot(t, x, 'b-', linewidth=2)
axes[0].set_xlabel('Vaqt (s)')
axes[0].set_ylabel('Pozitsiya (m)')
axes[0].set_title('Pozitsiya-Vaqt')
axes[0].grid(True)
axes[1].plot(t, v, 'r-', linewidth=2)
axes[1].set_xlabel('Vaqt (s)')
axes[1].set_ylabel('Tezlik (m/s)')
axes[1].set_title('Tezlik-Vaqt')
axes[1].grid(True)
plt.tight_layout()
plt.savefig('friction_simulation.png', dpi=150)
plt.show()
print(f"To'xtash vaqti: {t[-1]:.2f} s")
print(f"Bosib o'tilgan masofa: {x[-1]:.2f} m")
3. Qiya Tekislik Simulyatsiyasi
import numpy as np
import matplotlib.pyplot as plt
def inclined_plane(m, theta_deg, mu=0, v0=0, x0=0, g=10, dt=0.01, t_max=5):
"""Qiya tekislikda harakat"""
theta = np.radians(theta_deg)
t_list, x_list, v_list = [0], [x0], [v0]
t, x, v = 0, x0, v0
while t < t_max and x >= 0:
# Kuchlar
F_gravity = m * g * np.sin(theta) # pastga
N = m * g * np.cos(theta)
if v > 0:
F_friction = mu * N # pastga (harakatga qarshi)
F_net = F_gravity - F_friction
elif v < 0:
F_friction = mu * N # yuqoriga
F_net = F_gravity + F_friction
else:
# Tinch holat - statik ishqalanish
if F_gravity > mu * N:
F_net = F_gravity - mu * N
else:
F_net = 0
a = F_net / m
v += a * dt
x += v * dt
t += dt
t_list.append(t)
x_list.append(max(0, x))
v_list.append(v)
return np.array(t_list), np.array(x_list), np.array(v_list)
# Turli burchaklar
angles = [15, 30, 45, 60]
mu = 0.2
plt.figure(figsize=(12, 5))
for theta in angles:
t, x, v = inclined_plane(m=2, theta_deg=theta, mu=mu, x0=10, v0=0)
plt.plot(t, x, linewidth=2, label=f'{theta}°')
plt.xlabel('Vaqt (s)')
plt.ylabel('Pozitsiya (m)')
plt.title(f'Qiya Tekislikda Sirpanish (μ = {mu})')
plt.legend()
plt.grid(True)
plt.savefig('inclined_plane.png', dpi=150)
plt.show()
4. Quadcopter Dinamikasi
import numpy as np
import matplotlib.pyplot as plt
class Quadcopter1D:
"""1D (vertikal) quadcopter simulyatsiyasi"""
def __init__(self, mass=2, g=10):
self.m = mass
self.g = g
self.z = 0 # balandlik
self.vz = 0 # vertikal tezlik
self.history = {'t': [0], 'z': [0], 'vz': [0], 'thrust': [mass*g]}
def set_thrust(self, thrust):
"""Propeller itarish kuchini belgilash"""
self.thrust = thrust
def update(self, dt):
# F = ma
F_net = self.thrust - self.m * self.g
az = F_net / self.m
self.vz += az * dt
self.z += self.vz * dt
# Yerga tegsa
if self.z < 0:
self.z = 0
self.vz = 0
def simple_altitude_controller(self, target_z, Kp=5, Kd=2):
"""PD altitude controller"""
error = target_z - self.z
error_rate = -self.vz
thrust = self.m * self.g + Kp * error + Kd * error_rate
return max(0, thrust) # ijobiy bo'lishi kerak
def simulate(self, target_z, t_max=10, dt=0.01):
t = 0
while t < t_max:
# Controller
thrust = self.simple_altitude_controller(target_z)
self.set_thrust(thrust)
self.update(dt)
t += dt
self.history['t'].append(t)
self.history['z'].append(self.z)
self.history['vz'].append(self.vz)
self.history['thrust'].append(thrust)
# Simulyatsiya
quad = Quadcopter1D(mass=2)
quad.simulate(target_z=10, t_max=15)
fig, axes = plt.subplots(3, 1, figsize=(12, 10))
axes[0].plot(quad.history['t'], quad.history['z'], 'b-', linewidth=2)
axes[0].axhline(y=10, color='r', linestyle='--', label='Target')
axes[0].set_ylabel('Balandlik (m)')
axes[0].set_title('Quadcopter Altitude Control')
axes[0].legend()
axes[0].grid(True)
axes[1].plot(quad.history['t'], quad.history['vz'], 'g-', linewidth=2)
axes[1].set_ylabel('Tezlik (m/s)')
axes[1].grid(True)
axes[2].plot(quad.history['t'], quad.history['thrust'], 'm-', linewidth=2)
axes[2].axhline(y=20, color='r', linestyle='--', label='Hover thrust')
axes[2].set_xlabel('Vaqt (s)')
axes[2].set_ylabel('Thrust (N)')
axes[2].legend()
axes[2].grid(True)
plt.tight_layout()
plt.savefig('quadcopter_dynamics.png', dpi=150)
plt.show()
5. To'qnashuv Simulyatsiyasi
import numpy as np
import matplotlib.pyplot as plt
def elastic_collision_1d(m1, v1, m2, v2):
"""1D elastik to'qnashuv"""
v1_final = ((m1 - m2) * v1 + 2 * m2 * v2) / (m1 + m2)
v2_final = ((m2 - m1) * v2 + 2 * m1 * v1) / (m1 + m2)
return v1_final, v2_final
def inelastic_collision_1d(m1, v1, m2, v2):
"""To'liq noelastik to'qnashuv"""
v_final = (m1 * v1 + m2 * v2) / (m1 + m2)
return v_final, v_final
# Simulyatsiya
def simulate_collision(m1, m2, v1_init, v2_init, collision_type='elastic', dt=0.01, t_max=5):
x1, x2 = 0, 5
v1, v2 = v1_init, v2_init
history = {'t': [], 'x1': [], 'x2': [], 'v1': [], 'v2': []}
collided = False
for t in np.arange(0, t_max, dt):
history['t'].append(t)
history['x1'].append(x1)
history['x2'].append(x2)
history['v1'].append(v1)
history['v2'].append(v2)
# To'qnashuv tekshirish
if not collided and x1 >= x2:
collided = True
if collision_type == 'elastic':
v1, v2 = elastic_collision_1d(m1, v1, m2, v2)
else:
v1, v2 = inelastic_collision_1d(m1, v1, m2, v2)
x1 += v1 * dt
x2 += v2 * dt
return history
# Elastik to'qnashuv
hist_elastic = simulate_collision(2, 3, 4, -2, 'elastic')
# Noelastik to'qnashuv
hist_inelastic = simulate_collision(2, 3, 4, -2, 'inelastic')
fig, axes = plt.subplots(2, 2, figsize=(14, 10))
# Elastik - pozitsiya
axes[0, 0].plot(hist_elastic['t'], hist_elastic['x1'], 'b-', label='m1')
axes[0, 0].plot(hist_elastic['t'], hist_elastic['x2'], 'r-', label='m2')
axes[0, 0].set_title('Elastik To\'qnashuv - Pozitsiya')
axes[0, 0].legend()
axes[0, 0].grid(True)
# Elastik - tezlik
axes[0, 1].plot(hist_elastic['t'], hist_elastic['v1'], 'b-', label='v1')
axes[0, 1].plot(hist_elastic['t'], hist_elastic['v2'], 'r-', label='v2')
axes[0, 1].set_title('Elastik To\'qnashuv - Tezlik')
axes[0, 1].legend()
axes[0, 1].grid(True)
# Noelastik - pozitsiya
axes[1, 0].plot(hist_inelastic['t'], hist_inelastic['x1'], 'b-', label='m1')
axes[1, 0].plot(hist_inelastic['t'], hist_inelastic['x2'], 'r-', label='m2')
axes[1, 0].set_title('Noelastik To\'qnashuv - Pozitsiya')
axes[1, 0].legend()
axes[1, 0].grid(True)
# Noelastik - tezlik
axes[1, 1].plot(hist_inelastic['t'], hist_inelastic['v1'], 'b-', label='v1')
axes[1, 1].plot(hist_inelastic['t'], hist_inelastic['v2'], 'r-', label='v2')
axes[1, 1].set_title('Noelastik To\'qnashuv - Tezlik')
axes[1, 1].legend()
axes[1, 1].grid(True)
plt.tight_layout()
plt.savefig('collision_simulation.png', dpi=150)
plt.show()
6. Topshiriq: Robot Qo'li Dinamikasi
import numpy as np
import matplotlib.pyplot as plt
def robot_arm_dynamics(theta1, theta2, tau1, tau2, L1=0.5, L2=0.3, m1=2, m2=1, g=10, dt=0.01):
"""
2 bo'g'inli robot qo'li dinamikasi (soddalashtirilgan)
TODO:
1. Gravitatsiya momentlarini hisoblang
2. Burchak tezlanishlarini toping
3. Harakat simulyatsiyasini yarating
"""
# Inertsiya momentlari (soddalashtirilgan)
I1 = m1 * L1**2 / 3
I2 = m2 * L2**2 / 3
# Gravitatsiya momentlari
# tau_g1 = ?
# tau_g2 = ?
# Burchak tezlanish
# alpha1 = (tau1 - tau_g1) / I1
# alpha2 = (tau2 - tau_g2) / I2
pass
# Sizning kodingiz...
✅ Laboratoriya Tekshirish Ro'yxati
- Nyuton simulyatsiyasi ishlaydi
- Ishqalanish to'g'ri modellangan
- Qiya tekislik simulyatsiyasi
- Quadcopter controller
- To'qnashuv simulyatsiyasi
- Robot qo'li topshiriq