murex 0.1.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.
murex/__init__.py ADDED
@@ -0,0 +1,32 @@
1
+ """murex: what simulations of artists' media share.
2
+
3
+ Colour as pigments that mix like the real thing (spectral Kubelka-Munk),
4
+ stroke paths, noise for textures, reference images and PNG output. Used by
5
+ ``oilpaint`` and ``fusain``.
6
+ """
7
+
8
+ from . import filters, noise, reference, spectral
9
+ from ._about import __version__
10
+ from .pigment import ColorLike, Pigment, as_pigment, mix_colors
11
+ from .png import write_png
12
+ from .reference import Reference
13
+ from .spline import Bezier, CatmullRom, Path, Polyline, Profile
14
+
15
+ __all__ = [
16
+ "Bezier",
17
+ "CatmullRom",
18
+ "ColorLike",
19
+ "Path",
20
+ "Pigment",
21
+ "Polyline",
22
+ "Profile",
23
+ "Reference",
24
+ "__version__",
25
+ "as_pigment",
26
+ "filters",
27
+ "mix_colors",
28
+ "noise",
29
+ "reference",
30
+ "spectral",
31
+ "write_png",
32
+ ]
murex/_about.py ADDED
@@ -0,0 +1,10 @@
1
+ """The package version: from the git tag (hatch-vcs), written to _version.py
2
+ when the package is built or installed (see pyproject.toml,
3
+ [tool.hatch.version])."""
4
+
5
+ try:
6
+ from ._version import __version__
7
+ except ImportError: # a source checkout that was never built or installed
8
+ __version__ = "0.0.0+unknown"
9
+
10
+ __all__ = ["__version__"]
murex/_version.py ADDED
@@ -0,0 +1,24 @@
1
+ # file generated by vcs-versioning
2
+ # don't change, don't track in version control
3
+ from __future__ import annotations
4
+
5
+ __all__ = [
6
+ "__version__",
7
+ "__version_tuple__",
8
+ "version",
9
+ "version_tuple",
10
+ "__commit_id__",
11
+ "commit_id",
12
+ ]
13
+
14
+ version: str
15
+ __version__: str
16
+ __version_tuple__: tuple[int | str, ...]
17
+ version_tuple: tuple[int | str, ...]
18
+ commit_id: str | None
19
+ __commit_id__: str | None
20
+
21
+ __version__ = version = '0.1.1'
22
+ __version_tuple__ = version_tuple = (0, 1, 1)
23
+
24
+ __commit_id__ = commit_id = None
murex/filters.py ADDED
@@ -0,0 +1,81 @@
1
+ """Small image filters (numpy only)."""
2
+
3
+ import numpy as np
4
+
5
+
6
+ def box_blur(a: np.ndarray, r: int, axis: int | None = None) -> np.ndarray:
7
+ """Box blur of radius r, the edges repeating the border value: along
8
+ ``axis``, or (by default) along the first two axes in turn, in float64
9
+ from first to last. The result has ``a``'s type."""
10
+ if r <= 0:
11
+ return a
12
+ if axis is not None:
13
+ return _box_pass(a, r, axis).astype(a.dtype)
14
+ out = a.astype(np.float64)
15
+ for ax in (0, 1):
16
+ out = _box_pass(out, r, ax)
17
+ return out.astype(a.dtype)
18
+
19
+
20
+ def _box_pass(a: np.ndarray, r: int, axis: int) -> np.ndarray:
21
+ """One pass of :func:`box_blur` along ``axis`` (float64: running sums)."""
22
+ pad = [(0, 0)] * a.ndim
23
+ pad[axis] = (r + 1, r)
24
+ c = np.cumsum(np.pad(a, pad, mode="edge"), axis=axis, dtype=np.float64)
25
+ n = a.shape[axis]
26
+ hi = np.take(c, np.arange(2 * r + 1, 2 * r + 1 + n), axis=axis)
27
+ lo = np.take(c, np.arange(0, n), axis=axis)
28
+ return (hi - lo) / (2 * r + 1)
29
+
30
+
31
+ def max_filter(a: np.ndarray, r: int) -> np.ndarray:
32
+ """Maximum over a (2r+1)-square neighbourhood (separable, edges clamped)."""
33
+ out = a.astype(np.float32)
34
+ for axis in (0, 1):
35
+ n = out.shape[axis]
36
+ pad = [(0, 0), (0, 0)]
37
+ pad[axis] = (r, r)
38
+ p = np.pad(out, pad, mode="edge")
39
+ res = np.take(p, np.arange(0, n), axis=axis)
40
+ for k in range(1, 2 * r + 1):
41
+ np.maximum(res, np.take(p, np.arange(k, k + n), axis=axis), out=res)
42
+ out = res
43
+ return out
44
+
45
+
46
+ def smooth121(a: np.ndarray) -> np.ndarray:
47
+ """Light [1, 2, 1] smoothing in both directions (softens pixel steps, keeps
48
+ fine grooves)."""
49
+ out = a.astype(np.float32)
50
+ for axis in (0, 1):
51
+ p = np.pad(
52
+ out, [(1, 1) if k == axis else (0, 0) for k in range(2)], mode="edge"
53
+ )
54
+ n = out.shape[axis]
55
+ out = (
56
+ 0.25 * np.take(p, np.arange(0, n), axis=axis)
57
+ + 0.5 * out
58
+ + 0.25 * np.take(p, np.arange(2, n + 2), axis=axis)
59
+ )
60
+ return out
61
+
62
+
63
+ def smoothstep(e0, e1, x):
64
+ """0 below ``e0``, 1 beyond ``e1`` (either way round), and a smooth S
65
+ between them."""
66
+ t = np.clip((x - e0) / (e1 - e0), 0.0, 1.0)
67
+ return t * t * (3.0 - 2.0 * t)
68
+
69
+
70
+ def bilinear(grid: np.ndarray, y, x):
71
+ """Sample ``grid`` (H, W, ...) at the fractional indices ``y`` and ``x``
72
+ (arrays, 0..H-1 and 0..W-1), linearly between the four cells around
73
+ each point."""
74
+ H, W = grid.shape[:2]
75
+ y0, x0 = np.minimum(y.astype(int), H - 2), np.minimum(x.astype(int), W - 2)
76
+ fy, fx = y - y0, x - x0
77
+ if grid.ndim == 3:
78
+ fx, fy = fx[..., None], fy[..., None]
79
+ return (grid[y0, x0] * (1 - fx) + grid[y0, x0 + 1] * fx) * (1 - fy) + (
80
+ grid[y0 + 1, x0] * (1 - fx) + grid[y0 + 1, x0 + 1] * fx
81
+ ) * fy
murex/noise.py ADDED
@@ -0,0 +1,169 @@
1
+ """Small procedural noise helpers (numpy only)."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import numpy as np
6
+
7
+
8
+ def _smooth(t):
9
+ return t * t * (3.0 - 2.0 * t)
10
+
11
+
12
+ def value_noise_2d(h: int, w: int, cell: float, rng: np.random.Generator) -> np.ndarray:
13
+ """Smooth value noise in [0, 1] with features about ``cell`` pixels wide."""
14
+ gh, gw = int(h / cell) + 3, int(w / cell) + 3
15
+ grid = rng.random((gh, gw))
16
+ y = np.arange(h) / cell
17
+ x = np.arange(w) / cell
18
+ yi, xi = y.astype(int), x.astype(int)
19
+ fy, fx = _smooth(y - yi)[:, None], _smooth(x - xi)[None, :]
20
+ g00 = grid[yi][:, xi]
21
+ g01 = grid[yi][:, xi + 1]
22
+ g10 = grid[yi + 1][:, xi]
23
+ g11 = grid[yi + 1][:, xi + 1]
24
+ top = g00 + (g01 - g00) * fx
25
+ bot = g10 + (g11 - g10) * fx
26
+ return top + (bot - top) * fy
27
+
28
+
29
+ def fractal_noise_2d(h, w, cell, rng, octaves=4, gain=0.5) -> np.ndarray:
30
+ out = np.zeros((h, w))
31
+ amp, total = 1.0, 0.0
32
+ for _ in range(octaves):
33
+ out += amp * value_noise_2d(h, w, max(cell, 1.0), rng)
34
+ total += amp
35
+ amp *= gain
36
+ cell /= 2.0
37
+ return out / total
38
+
39
+
40
+ def value_noise_1d(n: int, cell: float, rng: np.random.Generator) -> np.ndarray:
41
+ grid = rng.random(int(n / cell) + 3)
42
+ x = np.arange(n) / cell
43
+ xi = x.astype(int)
44
+ f = _smooth(x - xi)
45
+ return grid[xi] + (grid[xi + 1] - grid[xi]) * f
46
+
47
+
48
+ def canvas_weave(h: int, w: int, period: float, rng: np.random.Generator) -> np.ndarray:
49
+ """Height field in [0, 1] resembling primed plain-weave canvas."""
50
+ y, x = np.mgrid[0:h, 0:w].astype(np.float64)
51
+ jitter = fractal_noise_2d(h, w, period * 6, rng, octaves=2) - 0.5
52
+ xs = x + jitter * period * 0.6
53
+ ys = y - jitter * period * 0.6
54
+ cell_x = np.floor(xs / period)
55
+ cell_y = np.floor(ys / period)
56
+ fx = np.sin(np.pi * xs / period) ** 2
57
+ fy = np.sin(np.pi * ys / period) ** 2
58
+ over = ((cell_x + cell_y) % 2) == 0
59
+ weave = np.where(over, fx * (0.6 + 0.4 * fy), fy * (0.6 + 0.4 * fx))
60
+ grain = fractal_noise_2d(h, w, period * 1.5, rng, octaves=3)
61
+ out = 0.75 * weave + 0.25 * grain
62
+ out -= out.min()
63
+ return out / max(out.max(), 1e-9)
64
+
65
+
66
+ # ---------------------------------------------------------------------------
67
+ # Surface textures (height fields in 0..1)
68
+ # ---------------------------------------------------------------------------
69
+
70
+
71
+ def lattice_noise(U, V, rng: np.random.Generator) -> np.ndarray:
72
+ """Smooth value noise evaluated at arbitrary lattice coordinates (U, V)."""
73
+ U = U - U.min()
74
+ V = V - V.min()
75
+ grid = rng.random((int(U.max()) + 3, int(V.max()) + 3))
76
+ iu, iv = U.astype(int), V.astype(int)
77
+ fu, fv = _smooth(U - iu), _smooth(V - iv)
78
+ g00, g01 = grid[iu, iv], grid[iu, iv + 1]
79
+ g10, g11 = grid[iu + 1, iv], grid[iu + 1, iv + 1]
80
+ a = g00 + (g01 - g00) * fv
81
+ b = g10 + (g11 - g10) * fv
82
+ return a + (b - a) * fu
83
+
84
+
85
+ def aniso_noise(h, w, along, across, angle_deg, rng, octaves=2) -> np.ndarray:
86
+ """Noise stretched along a direction: features ``along`` px long and
87
+ ``across`` px wide, oriented ``angle_deg`` from horizontal."""
88
+ y, x = np.mgrid[0:h, 0:w].astype(np.float64)
89
+ a = np.radians(angle_deg)
90
+ u = x * np.cos(a) + y * np.sin(a)
91
+ v = -x * np.sin(a) + y * np.cos(a)
92
+ out = np.zeros((h, w))
93
+ amp, total = 1.0, 0.0
94
+ for _ in range(octaves):
95
+ out += amp * lattice_noise(u / max(along, 1.0), v / max(across, 0.5), rng)
96
+ total += amp
97
+ amp *= 0.5
98
+ along /= 2.0
99
+ across /= 2.0
100
+ return out / total
101
+
102
+
103
+ def _normalize(a: np.ndarray) -> np.ndarray:
104
+ lo, hi = np.percentile(a, [0.5, 99.5])
105
+ return np.clip((a - lo) / max(hi - lo, 1e-9), 0.0, 1.0)
106
+
107
+
108
+ def woven(h, w, period, rng, irregularity=0.3, twill=False) -> np.ndarray:
109
+ """Woven cloth: threads going over and under each other.
110
+
111
+ ``irregularity`` 0 gives machine-even cotton; higher values give linen,
112
+ with wandering threads of uneven thickness and slubs (thick spots).
113
+ """
114
+ y, x = np.mgrid[0:h, 0:w].astype(np.float64)
115
+ wander = 0.2 + 0.8 * irregularity
116
+ x = x + (fractal_noise_2d(h, w, period * 7, rng, octaves=2) - 0.5) * period * wander
117
+ y = y + (fractal_noise_2d(h, w, period * 7, rng, octaves=2) - 0.5) * period * wander
118
+ gx, gy = x / period, y / period
119
+ i, j = np.floor(gx), np.floor(gy)
120
+ fx, fy = gx - i, gy - j
121
+ nx, ny = int(w / period) + 8, int(h / period) + 8
122
+ # thread-to-thread thickness
123
+ warp_t = 1.0 + 0.7 * irregularity * (rng.random(nx) - 0.5) * 2
124
+ weft_t = 1.0 + 0.7 * irregularity * (rng.random(ny) - 0.5) * 2
125
+ tw = warp_t[np.clip(i.astype(int) + 4, 0, nx - 1)]
126
+ tf = weft_t[np.clip(j.astype(int) + 4, 0, ny - 1)]
127
+ sec_x = np.sin(np.pi * fx) ** (0.9 / tw) # rounded thread cross-sections
128
+ sec_y = np.sin(np.pi * fy) ** (0.9 / tf)
129
+ over = (((i - j) % 4) < 2) if twill else (((i + j) % 2) == 0)
130
+ cloth = np.where(
131
+ over, sec_x * tw * (0.55 + 0.45 * sec_y), sec_y * tf * (0.55 + 0.45 * sec_x)
132
+ )
133
+ slubs = (
134
+ aniso_noise(h, w, period * 6, period * 0.9, 90, rng) * 0.5
135
+ + aniso_noise(h, w, period * 6, period * 0.9, 0, rng) * 0.5
136
+ )
137
+ cloth = cloth * (1.0 + 1.2 * irregularity * (slubs - 0.5))
138
+ fibre = fractal_noise_2d(h, w, max(period * 0.6, 1.5), rng, octaves=2)
139
+ return _normalize(0.85 * cloth + 0.15 * fibre)
140
+
141
+
142
+ def paper(h, w, scale, rng) -> np.ndarray:
143
+ """Paper tooth: fine felted fibres."""
144
+ fibres = sum(
145
+ aniso_noise(h, w, scale * 5, scale * 0.6, a, rng, octaves=2)
146
+ for a in (15, 75, 125)
147
+ )
148
+ tooth = fractal_noise_2d(h, w, scale * 1.5, rng, octaves=3)
149
+ return _normalize(0.5 * fibres / 3 + 0.5 * tooth)
150
+
151
+
152
+ def wood(h, w, scale, angle, rng) -> np.ndarray:
153
+ """Wood grain: wavy growth rings and fine fibres along the grain."""
154
+ y, x = np.mgrid[0:h, 0:w].astype(np.float64)
155
+ a = np.radians(angle)
156
+ v = -x * np.sin(a) + y * np.cos(a)
157
+ warp = aniso_noise(h, w, scale * 25, scale * 4, angle, rng)
158
+ rings = 0.5 + 0.5 * np.sin(2 * np.pi * (v / scale + 2.5 * warp))
159
+ rings = rings**3 # narrow dark latewood bands
160
+ fibres = aniso_noise(h, w, scale * 4, 1.2, angle, rng, octaves=2)
161
+ return _normalize(0.6 * rings + 0.4 * fibres)
162
+
163
+
164
+ def brushmarks(h, w, angle, rng) -> np.ndarray:
165
+ """Ridges left by the brush that applied the priming: fine parallel
166
+ striations in broad bands of varying strength."""
167
+ fine = aniso_noise(h, w, 90, 1.8, angle, rng, octaves=2)
168
+ bands = aniso_noise(h, w, 260, 40, angle, rng, octaves=1)
169
+ return _normalize(fine * (0.35 + bands))
murex/pigment.py ADDED
@@ -0,0 +1,264 @@
1
+ """Pigments: absorption and scattering spectra per unit volume."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import functools
6
+ import math
7
+ from collections.abc import Iterable, Sequence
8
+
9
+ import numpy as np
10
+
11
+ from . import spectral as sp
12
+
13
+ #: Scattering per unit thickness of a fully opaque white. A unit-thick layer
14
+ #: of it over black reflects ~92%: a normal layer covers well but a thin one
15
+ #: lets what is underneath show through.
16
+ SCATTER_MAX = 12.0
17
+
18
+
19
+ def _scatter_factor(luminance: float) -> float:
20
+ # Light pigments (titanium white, cadmium yellow) scatter strongly, dark
21
+ # ones (phthalo, black) mostly absorb. Without this, white is far too weak
22
+ # in tints compared with the real thing.
23
+ return 0.1 + 0.9 * luminance
24
+
25
+
26
+ def _check_strength(strength) -> float:
27
+ strength = float(strength)
28
+ if not (math.isfinite(strength) and strength > 0.0):
29
+ raise ValueError(
30
+ f"strength must be a positive number (1 = normal), got {strength!r}"
31
+ )
32
+ return strength
33
+
34
+
35
+ def _check_opacity(opacity) -> float:
36
+ opacity = float(opacity)
37
+ if not math.isfinite(opacity):
38
+ raise ValueError(f"opacity must be a number in 0..1, got {opacity!r}")
39
+ return min(max(opacity, 0.0), 1.0)
40
+
41
+
42
+ class Pigment:
43
+ """A coloured material, described by how it looks.
44
+
45
+ Parameters
46
+ ----------
47
+ color:
48
+ How it looks laid at normal thickness on white. ``"#rrggbb"``, a
49
+ float triple in 0..1, or an int triple in 0..255 (see
50
+ :func:`murex.spectral.parse_color`).
51
+ opacity:
52
+ 0..1. How strongly it hides what is underneath. 1 = opaque body
53
+ color, ~0.3 = glazing color, 0 = pure dye. Values outside 0..1 are
54
+ clipped. Default 1.
55
+ strength:
56
+ Tinting strength, > 0. 2 means half as much of it gives the same
57
+ shift in a mixture. Default 1.
58
+ name:
59
+ Optional label.
60
+
61
+ ``color`` may also be an existing pigment: ``Pigment(pigment, ...)`` is a
62
+ copy, with a new ``name`` if given. ``strength`` then multiplies that
63
+ pigment's own, and ``opacity`` derives it again from its colour with the
64
+ new opacity, keeping its strength. A pigment that was mixed or built from
65
+ optics has no colour to derive from, so it refuses ``opacity``.
66
+
67
+ Internally a pigment is a Kubelka-Munk material: an absorption spectrum
68
+ ``K`` and a scattering coefficient ``S`` per unit volume. Mixing pigments
69
+ adds those, weighted by volume.
70
+ """
71
+
72
+ __slots__ = ("K", "S", "_color", "_strength", "name")
73
+
74
+ def __init__(
75
+ self,
76
+ color: ColorLike,
77
+ opacity: float | None = None,
78
+ strength: float | None = None,
79
+ name: str | None = None,
80
+ ):
81
+ if isinstance(color, Pigment):
82
+ self._derive(color, opacity, strength, name)
83
+ return
84
+ self.name = name
85
+ self._from_color(
86
+ color,
87
+ 1.0 if opacity is None else _check_opacity(opacity),
88
+ 1.0 if strength is None else _check_strength(strength),
89
+ )
90
+
91
+ def _from_color(self, color: ColorLike, opacity: float, strength: float) -> None:
92
+ srgb = sp.parse_color(color)
93
+ srgb.flags.writeable = False
94
+ target = sp.linear_rgb_to_reflectance(sp.srgb_to_linear(srgb))
95
+ lum = float(sp.LUMINANCE @ sp.srgb_to_linear(srgb))
96
+ S = SCATTER_MAX * _scatter_factor(lum) * opacity**2
97
+ K = sp.solve_absorption(target, S)
98
+ self.K = K * strength
99
+ self.S = S * strength
100
+ self._color = srgb
101
+ # kept so that Pigment(this, opacity=...) can derive it again
102
+ self._strength: float | None = strength
103
+
104
+ def _derive(self, pigment: Pigment, opacity, strength, name) -> None:
105
+ """``Pigment(pigment, ...)``: a copy of ``pigment``, changed as asked."""
106
+ self.name = name or pigment.name
107
+ factor = 1.0 if strength is None else _check_strength(strength)
108
+ if opacity is not None:
109
+ if pigment._strength is None or pigment._color is None:
110
+ raise ValueError(
111
+ "opacity can only be changed on a pigment made from a colour; "
112
+ f"{pigment!r} was mixed or built from optics"
113
+ )
114
+ self._from_color(
115
+ pigment._color, _check_opacity(opacity), pigment._strength * factor
116
+ )
117
+ return
118
+ self.K, self.S = pigment.K.copy(), pigment.S
119
+ self._color, self._strength = pigment._color, pigment._strength
120
+ if strength is not None:
121
+ # absorption and scattering scale together
122
+ self.K, self.S = self.K * factor, self.S * factor
123
+ if self._strength is not None:
124
+ # made from a colour: that colour stays its colour
125
+ self._strength *= factor
126
+ else:
127
+ # its colour is how it looks, which the strength changes:
128
+ # worked out again when asked for
129
+ self._color = None
130
+
131
+ @classmethod
132
+ def from_optics(cls, K, S, name: str | None = None) -> Pigment:
133
+ """Build a pigment directly from absorption spectrum K (per band,
134
+ sampled at :data:`murex.spectral.WAVELENGTHS`) and scattering S
135
+ (scalar), both per unit volume. Handy for measured pigment data."""
136
+ p = cls.__new__(cls)
137
+ p.K = np.asarray(K, dtype=np.float64).copy()
138
+ p.S = float(S)
139
+ p.name = name
140
+ p._color = None
141
+ p._strength = None
142
+ return p
143
+
144
+ @classmethod
145
+ def mix(
146
+ cls,
147
+ *parts: ColorLike | tuple[ColorLike, float],
148
+ name: str | None = None,
149
+ ) -> Pigment:
150
+ """Physically mix pigments.
151
+
152
+ ``Pigment.mix((ultramarine, 1), (white, 3))`` mixes one part
153
+ ultramarine with three parts white, by volume. Bare pigments (or
154
+ colours) count as one part each. Parts must not be negative.
155
+ """
156
+ K = np.zeros(sp.N_BANDS)
157
+ S = 0.0
158
+ total = 0.0
159
+ for part in parts:
160
+ pigment, vol = _split_part(part)
161
+ pigment = as_pigment(pigment)
162
+ K += vol * pigment.K
163
+ S += vol * pigment.S
164
+ total += vol
165
+ if total <= 0:
166
+ raise ValueError("mix needs a positive total volume")
167
+ return cls.from_optics(K / total, S / total, name=name)
168
+
169
+ def reflectance(
170
+ self, thickness: float = 1.0, over: ColorLike = "#ffffff"
171
+ ) -> np.ndarray:
172
+ """Reflectance spectrum of a layer of this pigment over a ground color
173
+ (any color form, or a reflectance spectrum)."""
174
+ is_spectrum = isinstance(over, np.ndarray) and over.shape[-1] == sp.N_BANDS
175
+ ground = over if is_spectrum else sp.srgb_to_reflectance(over)
176
+ return sp.km_layer(self.K * thickness, self.S * thickness, ground)
177
+
178
+ def appearance(
179
+ self, thickness: float = 1.0, over: ColorLike = "#ffffff"
180
+ ) -> np.ndarray:
181
+ """sRGB color (0..1) of a layer of this pigment over a ground color."""
182
+ return sp.reflectance_to_srgb(self.reflectance(thickness, over))
183
+
184
+ @property
185
+ def color(self) -> np.ndarray:
186
+ """sRGB color at unit thickness on white."""
187
+ if self._color is None:
188
+ self._color = self.appearance()
189
+ self._color.flags.writeable = False
190
+ # read-only: the pigment's optics were derived from it
191
+ return self._color
192
+
193
+ @property
194
+ def masstone(self) -> np.ndarray:
195
+ """sRGB color of the pigment infinitely thick."""
196
+ return sp.reflectance_to_srgb(sp.km_opaque(self.K, self.S))
197
+
198
+ @property
199
+ def hex(self) -> str:
200
+ return sp.to_hex(self.color)
201
+
202
+ def __repr__(self) -> str:
203
+ label = f"{self.name!r}, " if self.name else ""
204
+ return f"Pigment({label}{self.hex}, S={self.S:.2f})"
205
+
206
+
207
+ # (Defined after Pigment so that it holds the class itself, not its name.)
208
+ ColorLike = str | Sequence[float] | np.ndarray | Pigment
209
+
210
+
211
+ def _split_part(part) -> tuple[ColorLike, float]:
212
+ """A part of a :meth:`Pigment.mix`: ``(pigment or colour, parts)``, or a
213
+ bare pigment or colour for one part."""
214
+ is_pair = (
215
+ isinstance(part, (tuple, list))
216
+ and len(part) == 2
217
+ and not isinstance(part[0], (int, float, np.number))
218
+ )
219
+ if not is_pair:
220
+ return part, 1.0
221
+ pigment, vol = part
222
+ try:
223
+ vol = float(vol)
224
+ except (TypeError, ValueError):
225
+ raise TypeError(
226
+ f"mix parts are (pigment, parts) with parts a number, got {part!r}"
227
+ ) from None
228
+ if not (math.isfinite(vol) and vol >= 0.0):
229
+ raise ValueError(
230
+ f"mix parts must be a non-negative number of parts, got {vol!r}"
231
+ )
232
+ return pigment, vol
233
+
234
+
235
+ def as_pigment(p: ColorLike) -> Pigment:
236
+ """``p`` if it is a pigment, else a new opaque pigment of exactly that
237
+ colour.
238
+
239
+ The last 1024 colours asked for are remembered, so asking again for one
240
+ costs microseconds. A colour not seen before means fitting a spectrum,
241
+ about a millisecond.
242
+ """
243
+ if isinstance(p, Pigment):
244
+ return p
245
+ # Built once per colour, then copied, so that changing the pigment handed
246
+ # out cannot change the next one.
247
+ key = p if isinstance(p, str) else tuple(sp.parse_color(p).tolist())
248
+ return Pigment(_cached_pigment(key))
249
+
250
+
251
+ @functools.lru_cache(maxsize=1024)
252
+ def _cached_pigment(key: str | tuple[float, ...]) -> Pigment:
253
+ return Pigment(key)
254
+
255
+
256
+ def mix_colors(
257
+ colors: Iterable[ColorLike], weights: Iterable[float] | None = None
258
+ ) -> str:
259
+ """Quick helper: hex color of a mix of plain colors or pigments."""
260
+ colors = list(colors)
261
+ weights = [1.0] * len(colors) if weights is None else list(weights)
262
+ return Pigment.mix(
263
+ *[(as_pigment(c), w) for c, w in zip(colors, weights, strict=True)]
264
+ ).hex
murex/png.py ADDED
@@ -0,0 +1,31 @@
1
+ """Minimal PNG writer so saving images needs nothing beyond numpy."""
2
+
3
+ from __future__ import annotations
4
+
5
+ import struct
6
+ import zlib
7
+
8
+ import numpy as np
9
+
10
+
11
+ def write_png(path: str, img: np.ndarray) -> None:
12
+ img = np.ascontiguousarray(img, dtype=np.uint8)
13
+ if img.ndim == 2:
14
+ img = img[..., None]
15
+ h, w, c = img.shape
16
+ color_type = {1: 0, 3: 2, 4: 6}[c]
17
+ raw = b"".join(b"\x00" + img[y].tobytes() for y in range(h))
18
+
19
+ def chunk(tag: bytes, data: bytes) -> bytes:
20
+ return (
21
+ struct.pack(">I", len(data))
22
+ + tag
23
+ + data
24
+ + struct.pack(">I", zlib.crc32(tag + data) & 0xFFFFFFFF)
25
+ )
26
+
27
+ with open(path, "wb") as f:
28
+ f.write(b"\x89PNG\r\n\x1a\n")
29
+ f.write(chunk(b"IHDR", struct.pack(">IIBBBBB", w, h, 8, color_type, 0, 0, 0)))
30
+ f.write(chunk(b"IDAT", zlib.compress(raw, 6)))
31
+ f.write(chunk(b"IEND", b""))
murex/py.typed ADDED
File without changes