jelka 0.0.1__py3-none-any.whl

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
jelka/__init__.py ADDED
@@ -0,0 +1,7 @@
1
+ from .jelka import Jelka
2
+ from .color import Color
3
+
4
+ __all__ = [
5
+ "Jelka",
6
+ "Color",
7
+ ]
jelka/color.py ADDED
@@ -0,0 +1,66 @@
1
+ from typing import Tuple
2
+ import random
3
+
4
+
5
+ class Color:
6
+ def __init__(self, r: float, g: float, b: float):
7
+ self.r = r
8
+ self.g = g
9
+ self.b = b
10
+
11
+ def __add__(self, other: "Color") -> "Color":
12
+ return Color(self.r + other.r, self.g + other.g, self.b + other.b)
13
+
14
+ def __sub__(self, other: "Color") -> "Color":
15
+ return Color(self.r - other.r, self.g - other.g, self.b - other.b)
16
+
17
+ def __mul__(self, other: "Color") -> "Color":
18
+ return Color(self.r * other.r, self.g * other.g, self.b * other.b)
19
+
20
+ def __truediv__(self, other: "Color") -> "Color":
21
+ return Color(self.r / other.r, self.g / other.g, self.b / other.b)
22
+
23
+ def __mul__(self, other: float) -> "Color":
24
+ return Color(self.r * other, self.g * other, self.b * other)
25
+
26
+ def __truediv__(self, other: float) -> "Color":
27
+ return Color(self.r / other, self.g / other, self.b / other)
28
+
29
+ def __eq__(self, other: "Color") -> bool:
30
+ return self.r == other.r and self.g == other.g and self.b == other.b
31
+
32
+ def __str__(self) -> str:
33
+ return f"Color({self.r}, {self.g}, {self.b})"
34
+
35
+ def __repr__(self) -> str:
36
+ return f"Color({self.r}, {self.g}, {self.b})"
37
+
38
+ def to_tuple(self) -> Tuple[float, float, float]:
39
+ return self.r, self.g, self.b
40
+
41
+ def to_list(self) -> Tuple[float, float, float]:
42
+ return [self.r, self.g, self.b]
43
+
44
+ def to_write(self) -> Tuple[int, int, int]:
45
+ def round_clamp(value):
46
+ return max(0, min(255, round(value)))
47
+
48
+ return round_clamp(self.r), round_clamp(self.g), round_clamp(self.b)
49
+
50
+ def vivid(self):
51
+ """Makes color more vivid."""
52
+ return Color.vivid(self)
53
+
54
+ def random_color() -> "Color":
55
+ return Color(random.uniform(0, 255), random.uniform(0, 255), random.uniform(0, 255))
56
+
57
+ def vivid(c: "Color") -> "Color":
58
+ """Makes color more vivid."""
59
+ min(c.r, c.g, c.b)
60
+ if c.r <= c.g and c.r <= c.b:
61
+ c.r = 0
62
+ elif c.g <= c.r and c.g <= c.b:
63
+ c.g = 0
64
+ else:
65
+ c.b = 0
66
+ return c
jelka/jelka.py ADDED
@@ -0,0 +1,128 @@
1
+ from .color import Color
2
+ from typing import Callable, List
3
+ import jelka_validator.datawriter as dw
4
+ import time
5
+ import sys
6
+ import os
7
+
8
+
9
+ class Jelka:
10
+ def __init__(self, n: int, frame_rate: int, color: Color = Color(0, 0, 0), file: str | None = None):
11
+ self.n = n
12
+ self.color = color
13
+ self.lights: List[Color] = [color for _ in range(n)]
14
+ self.dw = dw.DataWriter(300)
15
+ self.frame = 0
16
+ self.frame_rate = frame_rate
17
+ self.positions_raw = dict()
18
+ self.positions_normalized = dict()
19
+ self.start_time = time.perf_counter()
20
+ self.cur_time = 0
21
+ self.objects: List["Sphere"] = list()
22
+ self.clear = False
23
+ for i in range(n):
24
+ self.positions_raw[i] = (0, 0, 0)
25
+
26
+ # Provide default file locations
27
+ filenames = [
28
+ os.path.join(os.getcwd(), "positions.csv"),
29
+ os.path.join(os.path.dirname(sys.argv[0]), "positions.csv"),
30
+ os.path.join(os.getcwd(), "../data/positions.csv"),
31
+ os.path.join(os.path.dirname(sys.argv[0]), "../data/positions.csv"),
32
+ ]
33
+
34
+ # Allow specifying custom path
35
+ if file:
36
+ filenames = [file]
37
+
38
+ # Try to load positions from various files
39
+ self.load_positions(filenames)
40
+
41
+ # Normalize the positions
42
+ self.normalize_positions(0, 1)
43
+
44
+ def load_positions(self, filenames: List[str]):
45
+ """Loads positions from the first available file."""
46
+
47
+ for filename in filenames:
48
+ if not os.path.isfile(filename):
49
+ continue
50
+
51
+ with open(filename) as file:
52
+ print(f"Loading positions from {filename}", file=sys.stderr, flush=True)
53
+
54
+ for line in file.readlines():
55
+ line = line.strip()
56
+ if line == "":
57
+ continue
58
+ i, x, y, z = line.split(",")
59
+ self.positions_raw[int(i)] = (float(x), float(y), float(z))
60
+
61
+ return
62
+
63
+ raise FileNotFoundError("No valid file found to load positions from")
64
+
65
+ def normalize_positions(self, l: int = 0, r: int = 1, mn_=None, mx_=None):
66
+ mn = min([pos[0] for pos in self.positions_raw.values()])
67
+ mn = min(min([pos[1] for pos in self.positions_raw.values()]), mn)
68
+ mn = min(min([pos[2] for pos in self.positions_raw.values()]), mn)
69
+ if mn_ is not None:
70
+ mn = mn_
71
+
72
+ mx = max([pos[0] for pos in self.positions_raw.values()])
73
+ mx = max(max([pos[1] for pos in self.positions_raw.values()]), mx)
74
+ mx = max(max([pos[2] for pos in self.positions_raw.values()]), mx)
75
+ mx += 0.01 # to avoid division by zero
76
+ if mx_ is not None:
77
+ mx = mx_
78
+
79
+ for i, pos in self.positions_raw.items():
80
+ x = (pos[0] - mn) / (mx - mn) * (r - l) + l
81
+ y = (pos[1] - mn) / (mx - mn) * (r - l) + l
82
+ z = (pos[2] - mn) / (mx - mn) * (r - l) + l
83
+ self.positions_normalized[i] = (x, y, z)
84
+
85
+ def set_light(self, i: int, color: Color):
86
+ self.lights[i] = color
87
+
88
+ def write_lights(self):
89
+ writable = [light.to_write() for light in self.lights]
90
+ self.dw.write_frame(writable)
91
+
92
+ def run(self, callback: Callable[["Jelka"], None] = None, init: Callable[["Jelka"], None] = None):
93
+ dt = 1.0 / self.frame_rate
94
+ if init is not None:
95
+ init(self)
96
+ self.start_time = time.perf_counter()
97
+
98
+ while True:
99
+ self.elapsed_time = time.perf_counter() - self.start_time
100
+ current_time = time.perf_counter()
101
+
102
+ if self.clear:
103
+ for i in range(self.n):
104
+ self.set_light(i, Color(0, 0, 0))
105
+ # print(self.elapsed_time)
106
+ for obj in self.objects:
107
+ obj.update_pos(self.elapsed_time)
108
+ for i in range(self.n):
109
+ if obj.is_inside(self.positions_normalized[i]):
110
+ self.set_light(i, Color(obj.color.r, obj.color.g, obj.color.b))
111
+
112
+ if callback is not None:
113
+ callback(self)
114
+ else:
115
+ break
116
+ self.write_lights()
117
+
118
+ new_time = time.perf_counter()
119
+ frame_time = new_time - current_time
120
+ self.frame += 1
121
+
122
+ if frame_time <= dt:
123
+ time.sleep(dt - frame_time)
124
+ # print(f"FPS: {self.frame_rate}")
125
+ else:
126
+ # print(f"Frame rate is too slow: {frame_time}/ {dt}")
127
+ # print(f"FPS: {int(1.0 / frame_time)}")
128
+ pass
jelka/path.py ADDED
@@ -0,0 +1,37 @@
1
+ from .types import Position
2
+ from typing import List
3
+ import math
4
+
5
+
6
+ class Path:
7
+ def __init__(self):
8
+ self.positions: List[Position] = []
9
+ self.durations: List[float] = []
10
+ self.loop = True
11
+
12
+ def add_position(self, position: Position, time: float):
13
+ self.positions.append(position)
14
+ self.durations.append(time)
15
+
16
+ def current_position(self, time: float) -> Position:
17
+ # print(self.durations)
18
+ total = 0
19
+ for i in range(len(self.durations)):
20
+ total += self.durations[i]
21
+
22
+ if self.loop:
23
+ time = time - math.floor(time / total) * total
24
+ for i in range(len(self.durations)):
25
+ if time <= self.durations[i]:
26
+ # linear interpolation between this and next position
27
+ # do it component-wise
28
+ t = time / self.durations[i]
29
+ if i == len(self.positions) - 1:
30
+ return self.positions[i]
31
+ return (
32
+ self.positions[i][0] + t * (self.positions[i + 1][0] - self.positions[i][0]),
33
+ self.positions[i][1] + t * (self.positions[i + 1][1] - self.positions[i][1]),
34
+ self.positions[i][2] + t * (self.positions[i + 1][2] - self.positions[i][2]),
35
+ )
36
+ time -= self.durations[i]
37
+ return self.positions[-1]
jelka/plane.py ADDED
@@ -0,0 +1,8 @@
1
+ from .types import Position
2
+
3
+
4
+ class Plane:
5
+ def __init__(self, center: Position, normal: Position):
6
+ self.center = center
7
+ self.normal = normal
8
+ self.d = normal[0] * center[0] + normal[1] * center[1] + normal[2] * center[2]
jelka/shapes.py ADDED
@@ -0,0 +1,7 @@
1
+ from .sphere import Sphere
2
+ from .path import Path
3
+
4
+ __all__ = [
5
+ "Sphere",
6
+ "Path",
7
+ ]
jelka/sphere.py ADDED
@@ -0,0 +1,21 @@
1
+ from .types import Position
2
+ from .util import distance
3
+ from jelka import Color
4
+ from jelka.path import Path
5
+
6
+
7
+ class Sphere:
8
+ def __init__(self, center: Position, radius: float, color: Color = Color(255, 192, 203)):
9
+ self.center = center
10
+ self.radius = radius
11
+ self.color: Color = color
12
+ self.path = Path()
13
+ self.path.add_position(center, 0.01)
14
+
15
+ def is_inside(self, pt: Position) -> bool:
16
+ return distance(self.center, pt) <= self.radius
17
+
18
+ def update_pos(self, time: float):
19
+ self.center = self.path.current_position(time)
20
+ # print(self.center)
21
+ return
jelka/types.py ADDED
@@ -0,0 +1,10 @@
1
+ Position = tuple[float, float, float]
2
+
3
+
4
+ # define adding and subtracing of positions
5
+ def __add__(self, other: Position) -> Position:
6
+ return (self[0] + other[0], self[1] + other[1], self[2] + other[2])
7
+
8
+
9
+ def __sub__(self, other: Position) -> Position:
10
+ return (self[0] - other[0], self[1] - other[1], self[2] - other[2])
jelka/util.py ADDED
@@ -0,0 +1,11 @@
1
+ import math
2
+ from .types import Position
3
+
4
+
5
+ def length(p: Position) -> float:
6
+ """Calculates absolute value of a point."""
7
+ return math.sqrt(sum(x**2 for x in p))
8
+
9
+
10
+ def distance(p1: Position, p2: Position) -> float:
11
+ return length((p1[0] - p2[0], p1[1] - p2[1], p1[2] - p2[2]))
@@ -0,0 +1,12 @@
1
+ Metadata-Version: 2.3
2
+ Name: jelka
3
+ Version: 0.0.1
4
+ Summary: API
5
+ Project-URL: Homepage, https://github.com/Jelka-FMF/JelkaPy
6
+ Project-URL: Issues, https://github.com/Jelka-FMF/JelkaPy/issues
7
+ Author-email: Bor Brudar <bor.brudar@gmail.com>
8
+ Classifier: License :: OSI Approved :: MIT License
9
+ Classifier: Operating System :: OS Independent
10
+ Classifier: Programming Language :: Python :: 3
11
+ Requires-Python: >=3.8
12
+ Requires-Dist: jelka-validator
@@ -0,0 +1,13 @@
1
+ jelka/__init__.py,sha256=d1ti6fPMcpU7nTwb4tnwicfT_PqaGGYAerzxfsmNt3s,98
2
+ jelka/color.py,sha256=RqDnH9AfLR4NL85LZv8HHfZ2KbsdodhiPAeJ04AItQk,2165
3
+ jelka/jelka.py,sha256=7-Q1FrfHVE86cABwUTWmDOK1pZnjofQW144b_WsPmmw,4737
4
+ jelka/path.py,sha256=wa0MLg7CMIcDAPDI8S9vPwYDo3wkX02bPY2SJCmkCYU,1405
5
+ jelka/plane.py,sha256=hZNJWaxGajkSFsUBCIrQv2e8xFI3Qg9FotGncv2_SNE,256
6
+ jelka/shapes.py,sha256=3ke6kfMT3xvZq-8pmoAb44GsFUN6FkKbCNLFNSqznM8,98
7
+ jelka/sphere.py,sha256=nzy1RknXTHrSgIOuzQb_-deZX86QNMlQYIQqmkOk-uA,645
8
+ jelka/types.py,sha256=-aFyYZjape_lbo9ux101F_k0cz4RpPNyMi7z_5-M0-w,336
9
+ jelka/util.py,sha256=i6ChwbxojTnWD6ONC7ZOSk4emdTttddsu6Yq3vr7xcA,296
10
+ jelka-0.0.1.dist-info/METADATA,sha256=g0UMyYp6OZxg2k4yE7Dc4_9elgZ84nAI7lVqAXzefSw,435
11
+ jelka-0.0.1.dist-info/WHEEL,sha256=C2FUgwZgiLbznR-k0b_5k3Ai_1aASOXDss3lzCUsUug,87
12
+ jelka-0.0.1.dist-info/licenses/LICENSE,sha256=SD93PwtTvQGiDBYEi4EB56q5x1eDNQdjq_z88RHOKLc,1087
13
+ jelka-0.0.1.dist-info/RECORD,,
@@ -0,0 +1,4 @@
1
+ Wheel-Version: 1.0
2
+ Generator: hatchling 1.26.3
3
+ Root-Is-Purelib: true
4
+ Tag: py3-none-any
@@ -0,0 +1,21 @@
1
+ MIT License
2
+
3
+ Copyright (c) 2024 Jelka FMF
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in all
13
+ copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
21
+ SOFTWARE.