Refactor all and add some tests for the calculations

This commit is contained in:
2026-01-15 16:12:08 +01:00
parent cc3371b73b
commit 2d067013b4
11 changed files with 161 additions and 102 deletions

View File

@@ -1,4 +1,3 @@
from objects.generic import Target, Source
import numpy as np import numpy as np
# Einheitsvektoren # Einheitsvektoren
@@ -39,7 +38,7 @@ def agl(a, b):
"Get the angle between two vectors. This is always between 0 and 180 degree." "Get the angle between two vectors. This is always between 0 and 180 degree."
return np.round(np.acos(np.dot(a, b)/(np.linalg.norm(a) * np.linalg.norm(b)))/(2 * np.pi) * 360) return np.round(np.acos(np.dot(a, b)/(np.linalg.norm(a) * np.linalg.norm(b)))/(2 * np.pi) * 360)
def get_angles(source: Source, target: Target): def get_angles(source, target):
"""Main function to get the phi and theta angles for a source and a target vector. Both vectors must lie on the front half sphere. """Main function to get the phi and theta angles for a source and a target vector. Both vectors must lie on the front half sphere.
Phi is from 0 to 180 where 0 means left when you look at the mirrors. The hardware is bounded between 45 and 135 degree. Thus the here provided angle needs to be subtracted by 45 and then doubled. Phi is from 0 to 180 where 0 means left when you look at the mirrors. The hardware is bounded between 45 and 135 degree. Thus the here provided angle needs to be subtracted by 45 and then doubled.
Theta is from 0 to 90 where 0 means up.""" Theta is from 0 to 90 where 0 means up."""
@@ -51,7 +50,6 @@ def get_angles(source: Source, target: Target):
source_theta = agl(rotate(source, 90 - source_phi, 3), unit_z) source_theta = agl(rotate(source, 90 - source_phi, 3), unit_z)
target_theta = agl(rotate(target, 90 - target_phi, 3), unit_z) target_theta = agl(rotate(target, 90 - target_phi, 3), unit_z)
print(target_theta)
phi = None phi = None
theta = None theta = None
@@ -72,5 +70,4 @@ def get_angles(source: Source, target: Target):
else: else:
theta = source_theta + theta_diff/2 theta = source_theta + theta_diff/2
print(phi, theta)
return (phi, theta) return (phi, theta)

View File

@@ -1,5 +1,10 @@
default: sim
sim: sim:
uv run python simulation.py uv run python simulation.py
test:
uv run python -m unittest discover -v
sync: sync:
rsync -r --exclude=venv ~/solarmotor guest@hahn1.one: rsync -r --exclude=venv ~/solarmotor guest@hahn1.one:

View File

@@ -1,6 +0,0 @@
def main():
print("Hello from solarmotor!")
if __name__ == "__main__":
main()

View File

@@ -3,9 +3,13 @@ from adafruit_servokit import ServoKit
class Board: class Board:
MIN = 500 MIN = 500
MAX = 2500 MAX = 2500
COVER = 180
count = 0
def __init__(self, channels=16, frequency=50): def __init__(self, channels=16, frequency=50):
self.channels = channels self.channels = channels
self.address = "" # For the future
self.frequency = frequency self.frequency = frequency
self.kit = ServoKit(channels=channels, frequency=frequency) self.kit = ServoKit(channels=channels, frequency=frequency)

42
objects/mirror.py Normal file
View File

@@ -0,0 +1,42 @@
import numpy as np
from objects.generic import Source, Target
from objects.motor import Motor
from calculator import get_angles
class Mirror:
def __init__(self, world, cluster_x=0, cluster_y=0):
self.world = world
self.cluster_x = cluster_x
self.cluster_y = cluster_y
# Store the motors
# Need to get first the theta because
# of the ordeing of the cables on the board
self.motor_theta: Motor = Motor(self.world.board)
self.motor_phi: Motor = Motor(self.world.board)
# Position in un-tilted coordinate system
self.pos = np.array(
[cluster_x * self.world.grid_size, cluster_y * self.world.grid_size, 0.0]
)
def get_pos_rotated(self):
return self.world.rotate_point_y(self.pos)
def set_angle_from_source_target(self, source: Source, target: Target):
"Set the angles of a mirror from global source and target vectors."
rot_pos = self.get_pos_rotated()
rel_source = source.pos - rot_pos
rel_target = target.pos - rot_pos
phi, theta = get_angles(rel_source, rel_target) # ty:ignore[unresolved-reference]
# Update the angles based on the normals in rotated positions
self.motor_phi.set_angle(phi)
self.motor_theta.set_angle(theta)
def get_angles(self):
return self.motor_phi.angle, self.motor_theta.angle

View File

@@ -5,24 +5,17 @@ from objects.board import Board
class Motor: class Motor:
"""Model a type of servo motor.""" """Model a type of servo motor."""
# Default vaules for every motor
MAX_PULSE = 2500
MIN_PULSE = 500
COVERAGE = 180 # Total degree of freedom in degrees
OFFSET = 0 # In degrees a constant to be added OFFSET = 0 # In degrees a constant to be added
SCALE = 1 # Scaling SCALE = 1 # Scaling
# Used for ids
count = 0
def __init__(self, board: Board, angle=0): def __init__(self, board: Board, angle=0):
self.board: Board = board self.board: Board = board
self.id: int = Motor.count self.id: int = Board.count
Motor.count += 1 Board.count += 1
self.angle = angle self.angle = angle
self.offset = Motor.OFFSET # Fine grained controls over every motor self.offset = Motor.OFFSET # Fine grained controls over every motor
self.coverage = Motor.COVERAGE self.coverage = Board.COVER
self.scale = Motor.SCALE self.scale = Motor.SCALE
# Initialization # Initialization
@@ -41,5 +34,5 @@ class Motor:
def inc(self, inc): def inc(self, inc):
self.angle += inc self.angle += inc
self.angle = min(max(self.angle, 0), Motor.COVERAGE) # Clip self.angle = min(max(self.angle, 0), Board.COVER) # Clip
self.set() self.set()

View File

@@ -1,70 +0,0 @@
"""Alle gemessenen Koordinaten der Quelle und der Sonne haben den Ursprung in der linken unteren Ecke des Clusters in einem rechtshaendigen flachen System."""
from objects.generic import Source, Target
import math
import objects.motor as motor
import numpy as np
from objects.calculator import get_angles
class Mirror:
def __init__(self, world, cluster_x=0, cluster_y=0):
self.world: World = world
self.cluster_x = cluster_x
self.cluster_y = cluster_y
# Store the motors
self.theta = motor.Motor(self.world.board)
self.phi = motor.Motor(self.world.board)
# Position in un-tilted coordinate system
self.pos = np.array(
[cluster_x * self.world.grid_size, cluster_y * self.world.grid_size, 0.0]
)
def get_pos_rotated(self):
return self.world.rotate_point_y(self.pos)
def set_angle_from_source_target(self, source: Source, target: Target):
"Set the angles of a mirror from global source and target vectors."
rot_pos = self.get_pos_rotated()
rel_source = source.pos - rot_pos
rel_target = target.pos - rot_pos
phi, theta = get_angles(rel_source, rel_target)
# Update the angles based on the normals in rotated positions
self.phi.set_angle(phi)
self.theta.set_angle(theta)
def get_angles(self):
return self.phi.angle, self.theta.angle
class World:
def __init__(self, board, tilt_deg=0.0):
self.board = board
self.grid_size = 10 # In cm
self.tilt_deg = tilt_deg # Tilt of the grid system around y-axis
self.mirrors: list[Mirror] = []
def add_mirror(self, mirror):
self.mirrors.append(mirror)
def update_mirrors_from_source_target(self, source: Source, target: Target):
for mirror in self.mirrors:
mirror.set_angle_from_source_target(source, target)
def rotate_point_y(self, point):
"""Rotate a point around the y-axis by the world's tilt angle."""
x, y, z = point
theta = math.radians(self.tilt_deg)
cos_t = math.cos(theta)
sin_t = math.sin(theta)
x_rot = x * cos_t + z * sin_t
y_rot = y
z_rot = -x * sin_t + z * cos_t
return np.array([x_rot, y_rot, z_rot])

55
objects/world.py Normal file
View File

@@ -0,0 +1,55 @@
"""
Alle gemessenen Koordinaten der Quelle und der Sonne haben den Ursprung in der rechten
oberen Ecke des Clusters in einem rechtshaendigen flachen System.
Achsen in der Welt mit der z-Achse nach oben.
Alles in cm gemessen.
Der phi Winkel wird zur x-Achse gemessen.
Der thetha Winkel wird zur z-Achse gemessen.
So sind y und z Koordinaten immer positiv.
x (2,0) (1,0) (0,0)
<-----S----S----S O:z
|
S S S (0,1)
|
v y
"""
from objects.generic import Source, Target
from objects.mirror import Mirror
import numpy as np
import math
class World:
def __init__(self, board, tilt_deg=0.0):
self.board = board
self.grid_size = 10 # In cm
self.tilt_deg = tilt_deg # Tilt of the grid system around y-axis
self.mirrors: list[Mirror] = []
def add_mirror(self, mirror):
self.mirrors.append(mirror)
def update_mirrors_from_source_target(self, source: Source, target: Target):
for mirror in self.mirrors:
mirror.set_angle_from_source_target(source, target)
def rotate_point_y(self, point):
"""Rotate a point around the y-axis by the world's tilt angle."""
x, y, z = point
theta = math.radians(self.tilt_deg)
cos_t = np.cos(theta)
sin_t = np.sin(theta)
x_rot = x * cos_t + z * sin_t
y_rot = y
z_rot = -x * sin_t + z * cos_t
return np.array([x_rot, y_rot, z_rot])

View File

@@ -1,26 +1,27 @@
import time import time
# Solar module for simulation of world from objects.generic import Source, Target
import objects.solar as solar # Modeling of the world from objects.world import World
from objects.mirror import Mirror
from objects.board import Board from objects.board import Board
# Solar module for simulation of world
STEP = 10 STEP = 10
LOOP_DELAY = 0.005 # In seconds LOOP_DELAY = 0.005 # In seconds
# Testing embedding the mirrors in the world # Testing embedding the mirrors in the world
board = Board() board = Board()
world = solar.World(board, tilt_deg=0) world = World(board, tilt_deg=0)
HEIGHT = 30 HEIGHT = 30
source = solar.Source(world, pos=(0, 50, 0)) source = Source(world, pos=(0, 50, 0))
target = solar.Target(world, pos=(0, 50, 0)) target = Target(world, pos=(0, 50, 0))
# Create mirrors in a 3x2 grid # Create mirrors in a 3x2 grid
for x in range(2): for x in range(2):
for y in range(1): for y in range(1):
mirror = solar.Mirror(world, cluster_x=x, cluster_y=y) mirror = Mirror(world, cluster_x=x, cluster_y=y)
world.add_mirror(mirror) world.add_mirror(mirror)
world.update_mirrors_from_source_target(source, target) world.update_mirrors_from_source_target(source, target)
@@ -34,10 +35,10 @@ def print_status():
a = 1 a = 1
t = time.time() t = time.time()
world.mirrors[0].phi.set_angle(180) world.mirrors[0].motor_theta.set_angle(180)
world.mirrors[0].theta.set_angle(180) world.mirrors[0].motor_phi.set_angle(180)
world.mirrors[1].phi.set_angle(0) world.mirrors[1].motor_phi.set_angle(0)
world.mirrors[1].theta.set_angle(0) world.mirrors[1].motor_theta.set_angle(0)
print_status() print_status()

1
tests/__init__.py Normal file
View File

@@ -0,0 +1 @@

37
tests/test_calculator.py Normal file
View File

@@ -0,0 +1,37 @@
import unittest
import numpy as np
import calculator
class TestCalculator(unittest.TestCase):
def test_proj(self):
vec = np.array([123, 325, 1])
self.assertEqual(np.array([123, 0, 0]).all(), calculator.proj(vec, 1).all())
vec = np.array([234, -2134, 12])
self.assertEqual(np.array([-2134, 0, 0]).all(), calculator.proj(vec, 2).all())
vec = np.array([-21, 34, 82])
self.assertEqual(np.array([0, 0, 82]).all(), calculator.proj(vec, 3).all())
def test_rotate(self):
vec = np.array([1, 0, 0])
self.assertEqual(np.array([0, 1, 0]).all(), calculator.rotate(vec).all())
def test_agl(self):
vec1 = np.array([1, 0, 0])
vec2 = np.array([1, 0, 0])
self.assertEqual(0, calculator.agl(vec1, vec2))
vec1 = np.array([1, 0, 0])
vec2 = np.array([0, 1, 0])
self.assertEqual(90, calculator.agl(vec1, vec2))
def test_get_angles(self):
source = np.array([0, 50, 0])
target = np.array([0, 50, 0])
self.assertEqual((90, 90), calculator.get_angles(source, target))
if __name__ == "__main__":
unittest.main()