Source code for skysim.colours
1"""Class and functions for colour management."""
2
3# License: GPLv3+ (see COPYING); Copyright (C) 2025 Tai Withers
4
5from collections.abc import Collection
6from typing import Any
7
8from matplotlib.colors import to_rgb
9from pydantic import computed_field
10from pydantic.dataclasses import dataclass
11
12# Type Aliases
13
14type RGBTuple = tuple[float, float, float]
15type InputColour = list[float | int] | str
16
17
[docs]
18@dataclass
19class RGB:
20 """Tuple of RGB values."""
21
22 original: InputColour
23 """Whatever was passed to the constructor."""
24
25 @computed_field()
26 @property
27 def rgb(self) -> RGBTuple:
28 """Generate an rgb tuple with values [0,1].
29
30 Returns
31 -------
32 RGBTuple
33 RGB value.
34 """
35 if (
36 isinstance(self.original, Collection)
37 and not isinstance(self.original, str)
38 and (len(self.original) in (3, 4))
39 and any(i > 1 for i in self.original)
40 ):
41 self.original = list(i / 255 for i in self.original)
42 return to_rgb(self.original) # type: ignore[arg-type]
43
44
[docs]
45def convert_colour(colour: Any) -> RGBTuple:
46 # pylint: disable=missing-function-docstring
47 return RGB(colour).rgb