Skip to main content

1.1 Vektor Algebra โ€” Amaliyot

Laboratoriya ishi: Python va NumPy bilan vektor operatsiyalar


๐ŸŽฏ Maqsadโ€‹

  • NumPy kutubxonasi bilan ishlash
  • Vektor operatsiyalarni kod orqali tushunish
  • Robot/dron simulyatsiyasiga tayyorgarlik

1. Muhit Sozlashโ€‹

# Virtual environment yaratish (tavsiya)
python -m venv venv
source venv/bin/activate # Linux/Mac
# venv\Scripts\activate # Windows

# Kutubxonalarni o'rnatish
pip install numpy matplotlib

2. Asosiy Vektor Operatsiyalarโ€‹

import numpy as np

# Vektorlarni yaratish
a = np.array([3, -2, 5])
b = np.array([-1, 4, 2])

print("Vektor a:", a)
print("Vektor b:", b)

# Qo'shish va ayirish
print("\na + b =", a + b)
print("a - b =", a - b)

# Skalyarga ko'paytirish
print("\n2a =", 2 * a)
print("3b =", 3 * b)
print("2a + 3b =", 2*a + 3*b)

# Uzunlik (magnitudasi)
mag_a = np.linalg.norm(a)
print(f"\n|a| = {mag_a:.4f}")

# Birlik vektor
unit_a = a / np.linalg.norm(a)
print("Birlik vektor a:", unit_a)
print("Tekshirish |รข| =", np.linalg.norm(unit_a))

Natija:

Vektor a: [ 3 -2  5]
Vektor b: [-1 4 2]

a + b = [2 2 7]
a - b = [ 4 -6 3]

2a = [ 6 -4 10]
3b = [-3 12 6]
2a + 3b = [ 3 8 16]

|a| = 6.1644
Birlik vektor a: [ 0.4867 -0.3244 0.8111]
Tekshirish |รข| = 1.0

3. Skalyar va Vektor Ko'paytmaโ€‹

import numpy as np

a = np.array([1, 2, 3])
b = np.array([4, 5, 6])

# Skalyar ko'paytma (dot product)
dot_product = np.dot(a, b)
# Yoki: dot_product = a @ b
print(f"a ยท b = {dot_product}")

# Vektor ko'paytma (cross product)
cross_product = np.cross(a, b)
print(f"a ร— b = {cross_product}")

# Burchakni hisoblash
cos_theta = np.dot(a, b) / (np.linalg.norm(a) * np.linalg.norm(b))
theta_rad = np.arccos(cos_theta)
theta_deg = np.degrees(theta_rad)
print(f"\nBurchak: {theta_deg:.2f}ยฐ")

# Perpendikularlikni tekshirish
c = np.array([2, -3, 1])
d = np.array([1, 1, 1])
print(f"\nc ยท d = {np.dot(c, d)}")
print(f"Perpendikularmi? {np.isclose(np.dot(c, d), 0)}")

4. Proyeksiyaโ€‹

import numpy as np

def projection(a, b):
"""a vektorning b ustiga proyeksiyasi"""
scalar_proj = np.dot(a, b) / np.linalg.norm(b)
vector_proj = (np.dot(a, b) / np.dot(b, b)) * b
return scalar_proj, vector_proj

a = np.array([2, -1, 3])
b = np.array([1, 1, 1])

scalar_p, vector_p = projection(a, b)
print(f"Skalyar proyeksiya: {scalar_p:.4f}")
print(f"Vektor proyeksiya: {vector_p}")

# Tekshirish: a = parallel + perpendicular
parallel = vector_p
perpendicular = a - parallel
print(f"\nParallel komponent: {parallel}")
print(f"Perpendikular komponent: {perpendicular}")
print(f"Tekshirish (a = p + perp): {parallel + perpendicular}")

5. Koordinata O'zgarishlariโ€‹

import numpy as np

def cartesian_to_cylindrical(x, y, z):
"""Dekart -> Silindr"""
rho = np.sqrt(x**2 + y**2)
phi = np.arctan2(y, x) # -pi dan pi gacha
return rho, phi, z

def cylindrical_to_cartesian(rho, phi, z):
"""Silindr -> Dekart"""
x = rho * np.cos(phi)
y = rho * np.sin(phi)
return x, y, z

def cartesian_to_spherical(x, y, z):
"""Dekart -> Sferik"""
r = np.sqrt(x**2 + y**2 + z**2)
theta = np.arccos(z / r) if r != 0 else 0
phi = np.arctan2(y, x)
return r, theta, phi

def spherical_to_cartesian(r, theta, phi):
"""Sferik -> Dekart"""
x = r * np.sin(theta) * np.cos(phi)
y = r * np.sin(theta) * np.sin(phi)
z = r * np.cos(theta)
return x, y, z

# Test
point = (3, 4, 5)
print(f"Dekart: {point}")

cyl = cartesian_to_cylindrical(*point)
print(f"Silindr: ฯ={cyl[0]:.2f}, ฯ†={np.degrees(cyl[1]):.2f}ยฐ, z={cyl[2]}")

sph = cartesian_to_spherical(*point)
print(f"Sferik: r={sph[0]:.2f}, ฮธ={np.degrees(sph[1]):.2f}ยฐ, ฯ†={np.degrees(sph[2]):.2f}ยฐ")

# Qayta o'girish (tekshirish)
back = spherical_to_cartesian(*sph)
print(f"Qayta Dekart: ({back[0]:.2f}, {back[1]:.2f}, {back[2]:.2f})")

6. Robot Qo'li Simulyatsiyasi (2D)โ€‹

import numpy as np
import matplotlib.pyplot as plt

def forward_kinematics_2d(lengths, angles):
"""
2D robot qo'lining forward kinematikasi
lengths: bo'g'in uzunliklari [L1, L2, L3, ...]
angles: burchaklar (gradusda) [ฮธ1, ฮธ2, ฮธ3, ...]
"""
positions = [(0, 0)] # Boshlang'ich nuqta
cumulative_angle = 0
x, y = 0, 0

for L, theta in zip(lengths, angles):
cumulative_angle += np.radians(theta)
x += L * np.cos(cumulative_angle)
y += L * np.sin(cumulative_angle)
positions.append((x, y))

return positions

def plot_robot_arm(positions, title="Robot Qo'li"):
"""Robot qo'lini chizish"""
xs, ys = zip(*positions)

plt.figure(figsize=(10, 8))
plt.plot(xs, ys, 'b-o', linewidth=3, markersize=10)
plt.plot(xs[0], ys[0], 'go', markersize=15, label='Asos')
plt.plot(xs[-1], ys[-1], 'r*', markersize=20, label='End Effector')

# Bo'g'inlarni belgilash
for i, (x, y) in enumerate(positions):
plt.annotate(f'J{i}', (x, y), textcoords="offset points",
xytext=(10,10), fontsize=12)

plt.xlabel('X (m)')
plt.ylabel('Y (m)')
plt.title(title)
plt.legend()
plt.grid(True)
plt.axis('equal')
plt.savefig('robot_arm.png', dpi=150)
plt.show()

return xs[-1], ys[-1]

# Misol: 3 bo'g'inli robot qo'li
lengths = [0.5, 0.3, 0.2] # metrda
angles = [30, 45, -20] # gradusda

positions = forward_kinematics_2d(lengths, angles)
end_x, end_y = plot_robot_arm(positions)

print(f"\nEnd Effector pozitsiyasi: ({end_x:.3f}, {end_y:.3f}) m")

7. Dron Tezlik Simulyatsiyasiโ€‹

import numpy as np
import matplotlib.pyplot as plt
from mpl_toolkits.mplot3d import Axes3D

def simulate_drone_path(v0, wind, duration, dt=0.1):
"""
Dron yo'lini simulyatsiya qilish
v0: boshlang'ich tezlik vektori
wind: shamol tezligi vektori
"""
t = np.arange(0, duration, dt)
positions = []

x, y, z = 0, 0, 0
v = np.array(v0)
w = np.array(wind)

for _ in t:
v_net = v + w
x += v_net[0] * dt
y += v_net[1] * dt
z += v_net[2] * dt
positions.append([x, y, z])

return np.array(positions), t

# Simulyatsiya
v0 = [5, 3, 2] # m/s - dron tezligi
wind = [-2, 1, 0] # m/s - shamol
duration = 10 # sekund

path, time = simulate_drone_path(v0, wind, duration)

# 3D vizualizatsiya
fig = plt.figure(figsize=(12, 8))
ax = fig.add_subplot(111, projection='3d')

ax.plot(path[:, 0], path[:, 1], path[:, 2], 'b-', linewidth=2)
ax.scatter(0, 0, 0, color='green', s=100, label='Boshlash')
ax.scatter(path[-1, 0], path[-1, 1], path[-1, 2], color='red', s=100, label='Tugash')

ax.set_xlabel('X (m)')
ax.set_ylabel('Y (m)')
ax.set_zlabel('Z (m)')
ax.set_title('Dron Traektoriyasi (shamol ta\'sirida)')
ax.legend()

plt.savefig('drone_path.png', dpi=150)
plt.show()

print(f"Boshlang'ich pozitsiya: (0, 0, 0)")
print(f"Oxirgi pozitsiya: ({path[-1, 0]:.1f}, {path[-1, 1]:.1f}, {path[-1, 2]:.1f}) m")
print(f"Umumiy masofa: {np.linalg.norm(path[-1]):.1f} m")

8. Moment Hisoblashโ€‹

import numpy as np

def calculate_torque(r, F):
"""
Moment hisoblash: ฯ„ = r ร— F
r: kuch qo'yilgan nuqtaga vektor (m)
F: kuch vektori (N)
"""
torque = np.cross(r, F)
return torque

# Misol: Robot qo'liga kuch ta'sir qilmoqda
r = np.array([0.3, 0.2, 0.5]) # m
F = np.array([10, 5, -3]) # N

tau = calculate_torque(r, F)
print(f"Kuch qo'yilgan nuqta: r = {r} m")
print(f"Kuch vektori: F = {F} N")
print(f"Moment: ฯ„ = {tau} Nยทm")
print(f"Moment kattaligi: |ฯ„| = {np.linalg.norm(tau):.3f} Nยทm")

9. Topshiriq: Quadcopter Kuch Tahliliโ€‹

Quyidagi kodni to'ldiring:

import numpy as np

def quadcopter_forces(motor_thrusts, motor_directions):
"""
Quadcopter kuchlarini hisoblash

motor_thrusts: [F1, F2, F3, F4] - motor kuchlari (N)
motor_directions: [[nx1,ny1,nz1], ...] - birlik vektorlar

Qaytaradi: natijaviy kuch vektori
"""
# TODO: Sizning kodingiz
total_force = np.zeros(3)

for thrust, direction in zip(motor_thrusts, motor_directions):
# Har bir motor kuchini hisoblang
pass

return total_force

# Test ma'lumotlari
thrusts = [5, 6, 5, 4] # N
directions = [
[0, 0, 1],
[0.1, 0, 0.995],
[-0.1, 0.1, 0.990],
[0, -0.1, 0.995]
]

# Sinab ko'ring
result = quadcopter_forces(thrusts, directions)
print(f"Natijaviy kuch: {result} N")
# Kutilgan javob: [0.1, 0.1, 19.9] N (taxminan)
Yechim
def quadcopter_forces(motor_thrusts, motor_directions):
total_force = np.zeros(3)

for thrust, direction in zip(motor_thrusts, motor_directions):
direction = np.array(direction)
# Birlik vektor qilish (agar kerak bo'lsa)
direction = direction / np.linalg.norm(direction)
force = thrust * direction
total_force += force

return total_force

10. Topshiriq: GPS Masofa Hisoblashโ€‹

import numpy as np

def gps_to_ecef(lat, lon, alt):
"""
GPS koordinatalarni ECEF ga o'girish
lat, lon: gradusda
alt: metrda (dengiz sathidan)
"""
# WGS84 parametrlari
a = 6378137.0 # Ekvatorial radius (m)
f = 1/298.257223563 # Yassilik
e2 = 2*f - f**2 # Ekssentrisitet kvadrati

lat_rad = np.radians(lat)
lon_rad = np.radians(lon)

N = a / np.sqrt(1 - e2 * np.sin(lat_rad)**2)

x = (N + alt) * np.cos(lat_rad) * np.cos(lon_rad)
y = (N + alt) * np.cos(lat_rad) * np.sin(lon_rad)
z = (N * (1 - e2) + alt) * np.sin(lat_rad)

return np.array([x, y, z])

def distance_between_gps(point1, point2):
"""
Ikki GPS nuqta orasidagi masofa
point1, point2: (lat, lon, alt) - gradus va metr
"""
# TODO: Sizning kodingiz
pass

# Test
tashkent = (41.2995, 69.2401, 455) # Toshkent
samarkand = (39.6542, 66.9597, 702) # Samarqand

# distance = distance_between_gps(tashkent, samarkand)
# print(f"Masofa: {distance/1000:.1f} km")
# Kutilgan: ~270 km

โœ… Laboratoriya Tekshirish Ro'yxatiโ€‹

  • NumPy o'rnatilgan va import qilinadi
  • Asosiy vektor operatsiyalar ishlaydi
  • Dot va cross product to'g'ri hisoblanyapti
  • Koordinata o'zgarishlari ishlaydi
  • Robot qo'li vizualizatsiyasi chiqadi
  • Dron simulyatsiyasi ishlaydi
  • Quadcopter topshiriq bajarildi
  • GPS topshiriq bajarildi

Keyingi Mavzuโ€‹

๐Ÿ“– 1.2 Matritsa va Chiziqli Algebra