Debian Codegraph @

DisplayCAL/wx_ccxx_plot.py

raw
1 """Visualize CCMX/CCSS data with wxPython.
2
3 It includes tools for plotting spectral data, matrix 'flower' plots, and CIE
4 1931 chromaticity diagrams, with support for interactive zooming, toggling
5 views, and customized graph rendering.
6 """
7
8 import math
9 import os
10 import sys
11
12 from DisplayCAL import (
13 colormath,
14 config,
15 )
16 from DisplayCAL import localization as lang
17 from DisplayCAL import wx_enhanced_plot as plot
18 from DisplayCAL.argyll_instruments import get_canonical_instrument_name
19 from DisplayCAL.cgats import CGATS
20 from DisplayCAL.config import getcfg
21 from DisplayCAL.debughelpers import UnloggedError
22 from DisplayCAL.icc_profile import CRInterpolation
23 from DisplayCAL.meta import NAME as APPNAME
24 from DisplayCAL.util_str import make_filename_safe
25 from DisplayCAL.worker_base import get_argyll_util
26 from DisplayCAL.wx_addons import wx
27 from DisplayCAL.wx_lut_viewer import LUTCanvas
28 from DisplayCAL.wx_windows import FlatShadedButton, show_result_dialog
29
30 BGCOLOUR = "#101010"
31 FGCOLOUR = "#999999"
32 GRIDCOLOUR = "#202020"
33
34 if sys.platform == "darwin":
35 FONTSIZE_LARGE = 11
36 FONTSIZE_SMALL = 10
37 else:
38 FONTSIZE_LARGE = 9
39 FONTSIZE_SMALL = 8
40
41 NTICK = 10
42
43
44 # Graph labeling functions
45 # See Argyll plot/plot.c
46
47
48 def expt(a, n):
49 """Return a**n."""
50 return math.pow(a, n)
51
52
53 def nicenum(x, do_round):
54 """Return nice number for axis labeling."""
55 if x < 0.0:
56 x = -x
57 ex = math.floor(math.log10(x))
58 f = x / expt(10.0, ex)
59 if do_round:
60 if f < 1.5:
61 nf = 1.0
62 elif f < 3.0:
63 nf = 2.0
64 elif f < 7.0:
65 nf = 5.0
66 else:
67 nf = 10.0
68 elif f < 1.0:
69 nf = 1.0
70 elif f < 2.0:
71 nf = 2.0
72 elif f < 5.0:
73 nf = 5.0
74 else:
75 nf = 10.0
76 return nf * expt(10.0, ex)
77
78
79 class CCXXPlot(wx.Frame):
80 """CCMX/CCSS plot and information.
81
82 Args:
83 parent (wx.Window): Parent window (only used for error dialogs).
84 cgats (CGATS): A CCMX/CCSS CGATS instance.
85 worker (Worker, optional): Worker instance for executing commands.
86 """
87
88 def __init__(self, parent, cgats, worker=None):
89 """Init new CCXPlot window.
90
91 parent Parent window (only used for error dialogs)
92 cgats A CCMX/CCSS CGATS instance
93 worker Worker instance
94
95 """
96 self.is_ccss = cgats[0].type == b"CCSS"
97
98 desc = cgats.get_descriptor()
99
100 if cgats.filename:
101 fn, ext = os.path.splitext(os.path.basename(cgats.filename))
102 else:
103 fn = desc
104 ext = ".ccss" if self.is_ccss else ".ccmx"
105
106 if isinstance(fn, bytes):
107 fn = fn.decode("utf-8")
108
109 desc = lang.getstr(f"{ext[1:]}.{fn}", default=desc)
110 ccxx_type = "spectral" if self.is_ccss else "matrix"
111 title = "{}: {}".format(
112 lang.getstr(ccxx_type),
113 desc if isinstance(desc, str) else desc.decode("utf-8"),
114 )
115
116 if self.is_ccss:
117 # Convert to TI3 so we can get XYZ from spectra for coloring
118
119 temp = worker.create_tempdir()
120 if isinstance(temp, Exception):
121 show_result_dialog(temp, parent)
122 else:
123 basename = make_filename_safe(desc)
124 if isinstance(basename, bytes):
125 basename = basename.decode("utf-8")
126 temp_path = os.path.join(temp, basename + ".ti3")
127
128 cgats[0].type = b"CTI3"
129 cgats[0].DEVICE_CLASS = b"DISPLAY"
130 cgats.write(temp_path)
131
132 temp_out_path = os.path.join(temp, basename + ".CIE.ti3")
133
134 result = worker.exec_cmd(
135 get_argyll_util("spec2cie"),
136 [temp_path, temp_out_path],
137 capture_output=True,
138 )
139 if isinstance(result, Exception) or not result:
140 show_result_dialog(
141 UnloggedError(result or "".join(worker.errors)), parent
142 )
143 worker.wrapup(False)
144 else:
145 try:
146 cgats = CGATS(temp_out_path)
147 except Exception as exception:
148 show_result_dialog(exception, parent)
149 finally:
150 worker.wrapup(False)
151
152 data_format = cgats.queryv1("DATA_FORMAT")
153 data = cgats.queryv1("DATA")
154
155 XYZ_max = 0
156 self.samples = []
157
158 if self.is_ccss:
159 x_min = cgats.queryv1("SPECTRAL_START_NM")
160 x_max = cgats.queryv1("SPECTRAL_END_NM")
161 bands = cgats.queryv1("SPECTRAL_BANDS")
162 lores = bands <= 40
163 if lores:
164 # Interpolate if lores
165 # 1nm intervals
166 steps = int(x_max - x_min) + 1
167 print("Up-interpolating", bands, "spectral bands to", steps)
168 step = (x_max - x_min) / (steps - 1.0)
169 else:
170 step = (x_max - x_min) / (bands - 1.0)
171 y_min = 0
172 y_max = 1
173
174 Y_max = 0
175 for i in data:
176 sample = data[i]
177 # Get nm and spectral power
178 values = []
179 x = x_min
180 for k in data_format.values():
181 if k.startswith(b"SPEC_"):
182 y = sample[k.decode("utf-8")]
183 y_min = min(y, y_min)
184 y_max = max(y, y_max)
185 if lores:
186 values.append(y)
187 else:
188 values.append((x, y))
189 x += step
190 if lores:
191 # Interpolate if lores. Use Catmull-Rom instead of
192 # PolySpline as we want curves to go through points exactly
193 numvalues = len(values)
194 interp = CRInterpolation(values)
195 values = []
196 for i in range(steps):
197 values.append(
198 (x, interp(i / (steps - 1.0) * (numvalues - 1.0)))
199 )
200 x += step
201 # Get XYZ for colorization
202 XYZ = []
203 for component in "XYZ":
204 label = "XYZ_" + component
205 if label in sample:
206 v = sample[label]
207 XYZ_max = max(XYZ_max, v)
208 if label == "XYZ_Y":
209 Y_max = max(Y_max, v)
210 XYZ.append(v)
211 self.samples.append((XYZ, values, {}))
212
213 Plot = plot.PolyLine
214 Plot._attributes["width"] = 1
215 else:
216 # CCMX
217 cube_size = 2
218 x_min = 0
219 y_min = 0
220
221 mtx = colormath.Matrix3x3(
222 [
223 [sample[k.decode("utf-8")] for k in data_format.values()]
224 for sample in data.values()
225 ]
226 )
227 imtx = mtx.inverted()
228
229 # Get XYZ that colorimeter would measure without matrix (sRGB ref,
230 # so not accurate, but useful for visual representation which is all
231 # we care about here)
232 if cube_size == 2:
233 scale = 1
234 x_max = 100 * scale
235 y_max = x_max * (74.6 / 67.4)
236 if sys.platform != "win32":
237 x_center = x_max / 2.0
238 else:
239 x_center = x_max / 2.0 - 2.5
240 y_center = y_max / 2.0
241 x_center *= scale
242 y_center *= scale
243 pos2rgb = [
244 ((x_center - 23.7, y_center - 13.7), (0, 0, 1)),
245 ((x_center, y_center + 27.3), (0, 1, 0)),
246 ((x_center + 23.7, y_center - 13.7), (1, 0, 0)),
247 ((x_center - 23.7, y_center + 13.7), (0, 1, 1)),
248 ((x_center, y_center - 27.3), (1, 0, 1)),
249 ((x_center + 23.7, y_center + 13.7), (1, 1, 0)),
250 ((x_center, y_center), (1, 1, 1)),
251 ]
252 attrs_c = {"size": 10}
253 attrs_r = {"size": 5}
254 else:
255 x_max = 100
256 y_max = 100
257 y = -5
258 pos2rgb = []
259 for R in range(cube_size):
260 for G in range(cube_size):
261 x = -5
262 y += 10
263 for B in range(cube_size):
264 x += 10
265 pos2rgb.append(
266 ((x, y), (v / (cube_size - 1.0) for v in (R, G, B)))
267 )
268 attrs_c = {"marker": "square", "size": 10}
269 attrs_r = {"marker": "square", "size": 5}
270 Y_max = (imtx * colormath.get_whitepoint("D65"))[1]
271 for _i, ((x, y), (R, G, B)) in enumerate(pos2rgb):
272 XYZ = list(colormath.RGB2XYZ(R, G, B))
273 X, Y, Z = imtx * XYZ
274 XYZ_max = max(XYZ_max, X, Y, Z)
275 self.samples.append(([X, Y, Z], [(x, y)], attrs_c))
276 self.samples.append((XYZ, [(x, y)], attrs_r))
277
278 Plot = plot.PolyMarker
279
280 if self.is_ccss:
281 # Protect against division by zero when range is zero
282 if not x_max - x_min:
283 x_min = 350.0
284 x_max = 750.0
285 if not y_max - y_min:
286 y_min = 0.0
287 y_max = 10.0
288
289 y_zero = 0
290
291 self.ccxx_axis_x = (
292 math.floor(x_min / 50.0) * 50,
293 math.ceil(x_max / 50.0) * 50,
294 )
295 self.spec_x = (self.ccxx_axis_x[1] - self.ccxx_axis_x[0]) / 50.0
296 graph_range = nicenum(y_max - y_zero, False)
297 d = nicenum(graph_range / (NTICK - 1.0), True)
298 self.spec_y = math.ceil(y_max / d)
299 self.ccxx_axis_y = (math.floor(y_zero / d) * d, self.spec_y * d)
300 else:
301 self.ccxx_axis_x = (
302 math.floor(x_min / 20.0) * 20,
303 math.ceil(x_max / 20.0) * 20,
304 )
305 self.ccxx_axis_y = (math.floor(y_min), math.ceil(y_max))
306
307 self.gfx = []
308 for XYZ, values, attrs in self.samples:
309 if len(XYZ) == 3:
310 # Got XYZ
311 if attrs.get("size", 0) > 11.25:
312 # Colorimeter XYZ
313 if Y_max > 1:
314 # Colorimeter brighter than ref
315 XYZ[:] = [v / Y_max for v in XYZ]
316 else:
317 # Colorimeter dimmer than ref
318 XYZ[:] = [v * Y_max for v in XYZ]
319 # Ref XYZ
320 elif Y_max > 1:
321 # Colorimeter brighter than ref
322 XYZ[:] = [v / Y_max for v in XYZ]
323 RGB = tuple(
324 int(v) for v in colormath.XYZ2RGB(*XYZ, scale=255, round_=True)
325 )
326 else:
327 RGB = (153, 153, 153)
328 self.gfx.append(Plot(values, colour=wx.Colour(*RGB), **attrs))
329 if self.is_ccss:
330 # Add a few points at the extremes to define a bounding box
331 self.gfx.append(
332 plot.PolyLine(
333 [
334 (self.ccxx_axis_x[0], self.ccxx_axis_y[0]),
335 (self.ccxx_axis_x[1], self.ccxx_axis_y[1] - y_min),
336 ],
337 colour=wx.Colour(0, 0, 0, 0),
338 )
339 )
340
341 ref = cgats.queryv1("REFERENCE")
342 if ref:
343 ref = get_canonical_instrument_name(ref).decode("utf-8")
344
345 if not self.is_ccss:
346 observers_ab = {}
347 for observer in config.VALID_VALUES["observer"]:
348 observers_ab[observer] = lang.getstr("observer." + observer)
349 x_label = [lang.getstr("matrix")]
350 x_label.extend(
351 ["{:9.6f} {:9.6f} {:9.6f}".format(*tuple(row)) for row in mtx]
352 )
353 if ref:
354 ref_observer = cgats.queryv1("REFERENCE_OBSERVER")
355 if ref_observer:
356 # If the .ccmx does not contain this value,
357 # the graph will still draw
358 ref_observer = ref_observer.decode("utf-8")
359 ref += ", " + observers_ab.get(ref_observer, ref_observer)
360 x_label.append("")
361 x_label.append(ref)
362 fit_method = cgats.queryv1("FIT_METHOD")
363 if fit_method == b"xy":
364 # If the .ccmx does not contain this value,
365 # the graph will still draw
366 fit_method = lang.getstr("ccmx.use_four_color_matrix_method")
367 elif fit_method:
368 fit_method = lang.getstr("perceptual")
369 fit_de00_avg = cgats.queryv1("FIT_AVG_DE00")
370 if not isinstance(fit_de00_avg, float):
371 fit_de00_avg = None
372 fit_de00_max = cgats.queryv1("FIT_MAX_DE00")
373 if not isinstance(fit_de00_max, float):
374 fit_de00_max = None
375 if fit_method:
376 x_label.append(fit_method)
377 fit_de00 = []
378 if fit_de00_avg:
379 fit_de00.append(
380 f"ΔE*00 {lang.getstr('profile.self_check.avg')} {fit_de00_avg:.4f}"
381 )
382 if fit_de00_max:
383 fit_de00.append(
384 f"ΔE*00 {lang.getstr('profile.self_check.max')} {fit_de00_max:.4f}"
385 )
386 if fit_de00:
387 x_label.append("\n".join(fit_de00))
388 x_label = "\n".join(x_label)
389 else:
390 x_label = ""
391 if ref:
392 x_label += ref + ", "
393 x_label += f"{(x_max - x_min) / (bands - 1.0):.1f}nm, {x_min}-{x_max}nm"
394
395 scale = max(getcfg("app.dpi") / config.get_default_dpi(), 1)
396
397 style = wx.DEFAULT_FRAME_STYLE
398
399 wx.Frame.__init__(self, None, -1, title, style=style)
400 self.SetIcons(config.get_icon_bundle([256, 48, 32, 16], APPNAME))
401 self.SetBackgroundColour(BGCOLOUR)
402 self.Sizer = wx.GridSizer(1, 1, 0, 0)
403 bg = wx.Panel(self)
404 bg.SetBackgroundColour(BGCOLOUR)
405 bg.Sizer = wx.BoxSizer(wx.VERTICAL)
406 self.canvas = canvas = LUTCanvas(bg)
407 if self.is_ccss:
408 bg.MinSize = (int(513 * scale), int(557 * scale))
409 btnsizer = wx.BoxSizer(wx.HORIZONTAL)
410 bg.Sizer.Add(
411 btnsizer,
412 flag=wx.EXPAND | wx.TOP,
413 border=16,
414 )
415 self.toggle_btn = FlatShadedButton(bg, -1, label=lang.getstr("spectral"))
416 btnsizer.Add(self.toggle_btn, 1)
417 self.Sizer.Add(bg, 1, flag=wx.EXPAND)
418 bg.Sizer.Add(canvas, 1, flag=wx.EXPAND)
419 else:
420 bg.MinSize = (int(400 * scale), int(400 * scale))
421 self.Sizer.Add(bg, flag=wx.ALIGN_CENTER)
422 canvas_w = int(240 * scale)
423 canvas.MinSize = (int(canvas_w), int(canvas_w * (74.6 / 67.4)))
424 bg.Sizer.Add(canvas, flag=wx.ALIGN_CENTER)
425 label = wx.StaticText(
426 bg, -1, x_label.replace("&", "&&"), style=wx.ALIGN_CENTRE_HORIZONTAL
427 )
428 label.SetForegroundColour(FGCOLOUR)
429 label.SetMaxFontSize(11)
430 bg.Sizer.Add(label, flag=wx.ALIGN_CENTER | wx.ALL & ~wx.TOP, border=16 * scale)
431 canvas.SetBackgroundColour(BGCOLOUR)
432 canvas.SetEnableCenterLines(False)
433 canvas.SetEnableDiagonals(False)
434 canvas.SetEnableGrid(True)
435 canvas.enableTicks = (True, True)
436 canvas.tickPen = wx.Pen(GRIDCOLOUR, int(canvas._pointSize[0]))
437 canvas.SetEnablePointLabel(False)
438 canvas.SetEnableTitle(True)
439 canvas.SetForegroundColour(FGCOLOUR)
440 canvas.SetGridColour(GRIDCOLOUR)
441 canvas.canvas.BackgroundColour = BGCOLOUR
442 if self.is_ccss:
443 canvas.HandCursor = wx.StockCursor(wx.CURSOR_SIZING)
444 canvas.SetCursor(canvas.HandCursor)
445 else:
446 canvas.canvas.Unbind(wx.EVT_LEFT_DCLICK)
447 canvas.SetEnableDrag(False)
448 canvas.SetCursor(wx.StockCursor(wx.CURSOR_DEFAULT))
449 canvas.SetXSpec("none")
450 canvas.SetYSpec("none")
451
452 # CallAfter is needed under GTK as usual
453 wx.CallAfter(self.draw_ccxx)
454
455 if self.is_ccss:
456 self.Bind(wx.EVT_KEY_DOWN, self.key_handler)
457 for child in list(self.GetAllChildren()):
458 child.Bind(wx.EVT_KEY_DOWN, self.key_handler)
459 child.Bind(wx.EVT_MOUSEWHEEL, self.OnWheel)
460
461 self.toggle_btn.Bind(wx.EVT_BUTTON, self.toggle_draw)
462
463 self.Bind(wx.EVT_SIZE, self.OnSize)
464 else:
465 bg.Sizer.Add((0, 16))
466 self.Sizer.SetSizeHints(self)
467 self.Sizer.Layout()
468
469 def OnSize(self, event):
470 """Resize the canvas.
471
472 Args:
473 event (wx.SizeEvent): The size event triggered by resizing the
474 window.
475 """
476 if self.canvas.last_draw:
477 wx.CallAfter(self.canvas._DrawCanvas, self.canvas.last_draw[0])
478 event.Skip()
479
480 def OnWheel(self, event):
481 """Mousewheel zoom."""
482 direction = 1.0 if event.WheelRotation < 0 else -1.0
483 self.canvas.zoom(direction)
484
485 def key_handler(self, event):
486 """Keyboard zoom."""
487 key = event.GetKeyCode()
488 if key in (43, wx.WXK_NUMPAD_ADD):
489 # + key zoom in
490 self.canvas.zoom(-1)
491 elif key in (45, wx.WXK_NUMPAD_SUBTRACT):
492 # - key zoom out
493 self.canvas.zoom(1)
494 else:
495 event.Skip()
496
497 def draw(self, objects, title="", xlabel=" ", ylabel=" "):
498 """Draw objects to plot."""
499 graphics = plot.PlotGraphics(objects, title, xlabel, ylabel)
500 self.canvas.Draw(graphics, self.canvas.axis_x, self.canvas.axis_y)
501 if self.is_ccss:
502 self.canvas.OnMouseDoubleClick(None)
503
504 def draw_ccxx(self):
505 """Spectra or matrix 'flower' plot."""
506 self.canvas.SetEnableLegend(False)
507 self.canvas.proportional = not self.is_ccss
508 self.canvas.axis_x = self.ccxx_axis_x
509 self.canvas.axis_y = self.ccxx_axis_y
510 if self.is_ccss:
511 self.canvas.spec_x = self.spec_x
512 self.canvas.spec_y = self.spec_y
513 self.canvas.SetXSpec(self.spec_x)
514 self.canvas.SetYSpec(self.spec_y)
515 self.draw(self.gfx, " ")
516
517 def draw_cie(self):
518 """CIE 1931 2° xy plot."""
519 self.canvas.SetEnableLegend(True)
520 self.canvas.proportional = True
521 gfx = []
522 # Add a few points at the extremes to define a bounding box
523 gfx.append(plot.PolyLine([(0, -0.025), (1, 1)], colour=wx.Colour(0, 0, 0, 0)))
524 # Add CIE 1931 outline
525 gfx.append(
526 plot.PolySpline(
527 colormath.cie1931_2_xy, colour=wx.Colour(102, 102, 102, 153), width=1.75
528 )
529 )
530 gfx.append(
531 plot.PolyLine(
532 [colormath.cie1931_2_xy[0], colormath.cie1931_2_xy[-1]],
533 colour=wx.Colour(102, 102, 102, 153),
534 width=1.75,
535 )
536 )
537 # Add comparison gamuts
538 for rgb_space, pen_style in [
539 ("Rec. 2020", wx.PENSTYLE_SOLID),
540 ("Adobe RGB (1998)", wx.PENSTYLE_SHORT_DASH),
541 ("DCI P3", wx.PENSTYLE_DOT_DASH),
542 ("Rec. 709", wx.PENSTYLE_DOT),
543 ]:
544 values = []
545 for R, G, B in [(1, 0, 0), (0, 1, 0), (0, 0, 1)]:
546 values.append(colormath.RGB2xyY(R, G, B, rgb_space)[:2])
547 values.append(values[0])
548 gfx.append(
549 plot.PolyLine(
550 values,
551 colour=wx.Colour(102, 102, 102, 255),
552 legend=rgb_space.replace(" (1998)", ""),
553 width=2,
554 style=pen_style,
555 )
556 )
557 # Add points
558 for i, (XYZ, _values, _attrs) in enumerate(self.samples):
559 if len(XYZ) != 3:
560 continue
561 xy = colormath.XYZ2xyY(*XYZ)[:2]
562 gfx.append(
563 plot.PolyMarker(
564 [colormath.XYZ2xyY(*XYZ)[:2]],
565 colour=wx.Colour(*self.gfx[i].attributes["colour"]),
566 size=2,
567 width=1.75,
568 marker="plus",
569 legend="{:.4f}\u2009x\u2002{:.4f}\u2009y".format(*xy),
570 )
571 )
572 self.canvas.axis_x = 0, 1
573 self.canvas.axis_y = 0, 1
574 self.canvas.spec_x = 10
575 self.canvas.spec_y = 10
576 self.canvas.SetXSpec(10)
577 self.canvas.SetYSpec(10)
578 self.draw(gfx, " ", "x", "y")
579
580 def toggle_draw(self, event):
581 """Toggle between spectral and CIE plot."""
582 if self.canvas.GetEnableLegend():
583 self.draw_ccxx()
584 self.toggle_btn.SetLabel(lang.getstr("spectral"))
585 else:
586 self.draw_cie()
587 self.toggle_btn.SetLabel(lang.getstr("whitepoint.xy"))