-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils.py
More file actions
112 lines (84 loc) · 2.34 KB
/
utils.py
File metadata and controls
112 lines (84 loc) · 2.34 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
"""
utils.py
Helper functions that are used in multiple files. Feel free to add more functions.
Dynamic Programming and Optimal Control
Fall 2024
Programming Exercise
Contact: Antonio Terpin aterpin@ethz.ch
Authors: Maximilian Stralz, Philip Pawlowsky, Antonio Terpin
--
ETH Zurich
Institute for Dynamic Systems and Control
--
"""
import numpy as np
from Constants import Constants
def bresenham(start, end):
"""
Generates the coordinates of a line between two points using Bresenham's algorithm.
Parameters:
start (tuple or list): The starting point (x0, y0).
end (tuple or list): The ending point (x1, y1).
Returns:
List[Tuple[int, int]]: A list of (x, y) coordinates.
Example:
>>> bresenham((2, 3), (10, 8))
[(2, 3), (3, 4), (4, 4), (5, 5), (6, 6), (7, 6), (8, 7), (9, 7), (10, 8)]
"""
x0, y0 = start
x1, y1 = end
points = []
dx = x1 - x0
dy = y1 - y0
x_sign = 1 if dx > 0 else -1 if dx < 0 else 0
y_sign = 1 if dy > 0 else -1 if dy < 0 else 0
dx = abs(dx)
dy = abs(dy)
if dx > dy:
xx, xy, yx, yy = x_sign, 0, 0, y_sign
else:
dx, dy = dy, dx
xx, xy, yx, yy = 0, y_sign, x_sign, 0
D = 2 * dy - dx
y = 0
for x in range(dx + 1):
px = x0 + x * xx + y * yx
py = y0 + x * xy + y * yy
points.append((px, py))
if D >= 0:
y += 1
D -= 2 * dx
D += 2 * dy
return points
def idx2state(idx):
"""Converts a given index into the corresponding state.
Args:
idx (int): index of the entry whose state is required
Returns:
np.array: (x,y,x,y) state corresponding to the given index
"""
state = np.empty(4)
for i, j in enumerate(
[
Constants.M,
Constants.N,
Constants.M,
Constants.N,
]
):
state[i] = idx % j
idx = idx // j
return state
def state2idx(state):
"""Converts a given state into the corresponding index.
Args:
state (np.array): (x,y,x,y) entry in the state space
Returns:
int: index corresponding to the given state
"""
idx = 0
factor = 1
for i, j in enumerate([Constants.M, Constants.N, Constants.M, Constants.N]):
idx += state[i] * factor
factor *= j
return idx