Debian Codegraph @

DisplayCAL/cgats.py

raw
1 """Simple CGATS file parser class.
2
3 Copyright (C) 2008 Florian Hoech
4 """
5
6 from __future__ import annotations
7
8 import functools
9 import io
10 import math
11 import os
12 import re
13 from pathlib import Path
14 from typing import Any, BinaryIO, Callable
15
16 from DisplayCAL import colormath
17 from DisplayCAL.colorspace_to_vrml import COLORSPACE_NAME_TO_VRML_MAP, ColorSpaceToVRML
18 from DisplayCAL.icc_profile import ICCProfileTag
19 from DisplayCAL.log import safe_print
20 from DisplayCAL.options import DEBUG
21
22
23 def debug_print(*args, other_conditions: bool = True) -> None:
24 """Print debug messages if DEBUG is enabled and other conditions are met.
25
26 Args:
27 *args: The arguments to print.
28 other_conditions (bool): Additional conditions to check before printing.
29 Defaults to True.
30 """
31 if DEBUG and other_conditions:
32 print(*args)
33
34
35 def get_device_value_labels(color_rep: None | str = None) -> list[bytes]:
36 """Return a list of device value labels.
37
38 Args:
39 color_rep (None | str): Color representation. Default is None.
40
41 Returns:
42 list: List of device value labels.
43 """
44 # TODO: Avoid using filter...
45 return list(
46 filter(
47 bool,
48 [
49 v[1] if not color_rep or v[0] == color_rep else False
50 for v in {
51 b"CMYK": (b"CMYK_C", b"CMYK_M", b"CMYK_Y", b"CMYK_K"),
52 b"RGB": (b"RGB_R", b"RGB_G", b"RGB_B"),
53 }
54 ],
55 )
56 )
57
58
59 def rpad(value: int | float | complex | str, width: int) -> bytes: # noqa: PYI041
60 """If value isn't a number, return a quoted string representation.
61
62 If value is greater or equal than 1e+16, return string in scientific
63 notation. Otherwise, return string in decimal notation right-padded to
64 given width (using trailing zeros).
65
66 Args:
67 value (int | float | complex | str): The value to format.
68 width (int): The width to pad the string to.
69 """
70 strval = b""
71 if not isinstance(value, bytes):
72 strval = bytes(str(value), "UTF-8")
73
74 if not isinstance(value, (int, float, complex)):
75 # Return quoted string representation
76 # Also need to escape single quote -> double quote
77 return b'"%s"' % strval.replace(b'"', b'""')
78
79 if value < 1e16:
80 i = strval.find(b".")
81 if i > -1:
82 if i < width - 1:
83 # Avoid scientific notation by formatting to decimal
84 fmt = b"%%%i.%if" % (width, width - i - 1)
85 strval = fmt % value
86 else:
87 strval = bytes(str(round(value)), "UTF-8")
88 return strval
89
90
91 def sort_rgb_gray_to_top(a: tuple, b: tuple) -> int:
92 """Sort RGB values to the top.
93
94 Args:
95 a (tuple): First RGB tuple.
96 b (tuple): Second RGB tuple.
97
98 Returns:
99 int: 1 if a > b, -1 if a < b, 0 if equal.
100 """
101 if a[0] == a[1] == a[2]:
102 if b[0] == b[1] == b[2]:
103 return 0
104 return -1
105 return 0
106
107
108 def sort_rgb_to_top_factory(i1: int, i2: int, i3: int, i4: int) -> Callable:
109 """Return a function to sort RGB values to the top.
110
111 Args:
112 i1 (int): Index of the first RGB value.
113 i2 (int): Index of the second RGB value.
114 i3 (int): Index of the third RGB value.
115 i4 (int): Index of the fourth RGB value.
116
117 Returns:
118 function: A function that sorts two RGB tuples by their values.
119 """
120
121 def sort_rgb_to_top(
122 a: tuple[float, float, float], b: tuple[float, float, float]
123 ) -> int:
124 """Sort two RGB tuples by their values.
125
126 Args:
127 a (tuple[float, float, float]): First RGB tuple.
128 b (tuple[float, float, float]): Second RGB tuple.
129
130 Returns:
131 int: 1 if a > b, -1 if a < b, 0 if equal.
132 """
133 if a[i1] == a[i2] and 0 <= a[i3] < a[i4]:
134 if b[i1] == b[i2] and 0 <= b[i3] < b[i4]:
135 return 0
136 return -1
137 return 0
138
139 return sort_rgb_to_top
140
141
142 def sort_rgb_white_to_top(a: tuple, b: tuple) -> int:
143 """Sort RGB values to the top.
144
145 Args:
146 a (tuple): First RGB tuple.
147 b (tuple): Second RGB tuple.
148
149 Returns:
150 int: 1 if a > b, -1 if a < b, 0 if equal.
151 """
152 sum1 = sum(a[:3])
153 # sum2 = sum(b[:3])
154 return -1 if sum1 == 300 else 0
155
156
157 def sort_by_hsi(a: tuple, b: tuple) -> int:
158 """Sort by HSI value.
159
160 Args:
161 a (tuple): First RGB tuple.
162 b (tuple): Second RGB tuple.
163
164 Returns:
165 int: 1 if a > b, -1 if a < b, 0 if equal.
166 """
167 a = list(colormath.RGB2HSI(*a[:3]))
168 b = list(colormath.RGB2HSI(*b[:3]))
169 a[0] = round(math.degrees(a[0]))
170 b[0] = round(math.degrees(b[0]))
171 if a > b:
172 return 1
173 if a < b:
174 return -1
175 return 0
176
177
178 def sort_by_hsl(a: tuple, b: tuple) -> int:
179 """Sort by HSL value.
180
181 Args:
182 a (tuple): First RGB tuple.
183 b (tuple): Second RGB tuple.
184
185 Returns:
186 int: 1 if a > b, -1 if a < b, 0 if equal.
187 """
188 a = list(colormath.RGB2HSL(*a[:3]))
189 b = list(colormath.RGB2HSL(*b[:3]))
190 a[0] = round(math.degrees(a[0]))
191 b[0] = round(math.degrees(b[0]))
192 if a > b:
193 return 1
194 if a < b:
195 return -1
196 return 0
197
198
199 def sort_by_hsv(a: tuple, b: tuple) -> int:
200 """Sort by HSV value.
201
202 Args:
203 a (tuple): First RGB tuple.
204 b (tuple): Second RGB tuple.
205
206 Returns:
207 int: 1 if a > b, -1 if a < b, 0 if equal.
208 """
209 a = list(colormath.RGB2HSV(*a[:3]))
210 b = list(colormath.RGB2HSV(*b[:3]))
211 a[0] = round(math.degrees(a[0]))
212 b[0] = round(math.degrees(b[0]))
213 if a > b:
214 return 1
215 if a < b:
216 return -1
217 return 0
218
219
220 def sort_by_rgb(a: tuple, b: tuple) -> int:
221 """Sort by RGB value.
222
223 Args:
224 a (tuple): First RGB tuple.
225 b (tuple): Second RGB tuple.
226
227 Returns:
228 int: 1 if a > b, -1 if a < b, 0 if equal.
229 """
230 if a[:3] > b[:3]:
231 return 1
232 if a[:3] < b[:3]:
233 return -1
234 return 0
235
236
237 def sort_by_bgr(a: tuple, b: tuple) -> int:
238 """Sort by BGR value.
239
240 Args:
241 a (tuple): First RGB tuple.
242 b (tuple): Second RGB tuple.
243
244 Returns:
245 int: 1 if a > b, -1 if a < b, 0 if equal.
246 """
247 if a[:3][::-1] > b[:3][::-1]:
248 return 1
249 if a[:3] == b[:3]:
250 return 0
251 return -1
252
253
254 def sort_by_rgb_sum(a: tuple, b: tuple) -> int:
255 """Sort by RGB sum.
256
257 Args:
258 a (tuple): First RGB tuple.
259 b (tuple): Second RGB tuple.
260
261 Returns:
262 int: 1 if a > b, -1 if a < b, 0 if equal.
263 """
264 sum1, sum2 = sum(a[:3]), sum(b[:3])
265 if sum1 > sum2:
266 return 1
267 if sum1 < sum2:
268 return -1
269 return 0
270
271
272 def sort_by_rgb_pow_sum(a: tuple, b: tuple) -> int:
273 """Sort by RGB power sum.
274
275 Args:
276 a (tuple): First RGB tuple.
277 b (tuple): Second RGB tuple.
278
279 Returns:
280 int: 1 if a > b, -1 if a < b, 0 if equal.
281 """
282 sum1, sum2 = sum(v**2.2 for v in a[:3]), sum(v**2.2 for v in b[:3])
283 if sum1 > sum2:
284 return 1
285 if sum1 < sum2:
286 return -1
287 return 0
288
289
290 def stable_sort_by_l(a: tuple, b: tuple) -> int:
291 """Stable sort by L* value.
292
293 Args:
294 a (tuple): First RGB tuple.
295 b (tuple): Second RGB tuple.
296
297 Returns:
298 int: 1 if a > b, -1 if a < b, 0 if equal.
299 """
300 return sort_by_l(a, b, stable=True)
301
302
303 def sort_by_l(a: tuple, b: tuple, stable: bool = False) -> int:
304 """Sort by L* value.
305
306 Args:
307 a (tuple): First RGB tuple.
308 b (tuple): Second RGB tuple.
309 stable (bool): If True, sort stably by L* value.
310
311 Returns:
312 int: 1 if a > b, -1 if a < b, 0 if equal.
313 """
314
315 def sort(a1: float, b1: float) -> int:
316 """Compare two L* values.
317
318 Args:
319 a1 (float): First L* value.
320 b1 (float): Second L* value.
321
322 Returns:
323 int: 1 if a1 > b1, -1 if a1 < b1, 0 if equal.
324 """
325 if a1 > b1:
326 return 1
327 if a1 < b1:
328 return -1
329 return 0
330
331 lab1 = colormath.XYZ2Lab(*a[3:])
332 lab2 = colormath.XYZ2Lab(*b[3:])
333 if stable:
334 for i in range(len(lab1)):
335 v = sort(lab1[i], lab2[i])
336 if v != 0:
337 return v
338 return 0
339 return sort(lab1[0], lab2[0])
340
341
342 def sort_by_luma_factory(ry: float, gy: float, by: float, gamma: float = 1) -> Callable:
343 """Return a function to sort by luma.
344
345 Args:
346 ry (float): Red Y value.
347 gy (float): Green Y value.
348 by (float): Blue Y value.
349 gamma (float): Gamma correction value. Default is 1.
350
351 Returns:
352 function: A function that sorts two RGB tuples by their luma value.
353 """
354
355 def sort_by_luma(
356 a: tuple[float, float, float], b: tuple[float, float, float]
357 ) -> int:
358 """Sort two RGB tuples by their luma value.
359
360 Args:
361 a (tupltuple[float, float, float]e): First RGB tuple.
362 b (tuple[float, float, float]): Second RGB tuple.
363
364 Returns:
365 int: 1 if a > b, -1 if a < b, 0 if equal.
366 """
367 a = ry * a[0] ** gamma + gy * a[1] ** gamma + by * a[2] ** gamma
368 b = ry * b[0] ** gamma + gy * b[1] ** gamma + by * b[2] ** gamma
369 if a > b:
370 return 1
371 if a < b:
372 return -1
373 return 0
374
375 return sort_by_luma
376
377
378 sort_by_rec709_luma = sort_by_luma_factory(0.2126, 0.7152, 0.0722)
379
380
381 class CGATSError(Exception):
382 """Base class for CGATS errors."""
383
384
385 class CGATSInvalidError(CGATSError, IOError):
386 """Invalid CGATS file error."""
387
388
389 class CGATSInvalidOperationError(CGATSError):
390 """Invalid operation error."""
391
392
393 class CGATSKeyError(CGATSError, KeyError):
394 """CGATS key not found error."""
395
396
397 class CGATSTypeError(CGATSError, TypeError):
398 """CGATS type error."""
399
400
401 class CGATSValueError(CGATSError, ValueError):
402 """CGATS value error."""
403
404
405 class CGATS(dict):
406 """CGATS structure.
407
408 CGATS files are treated mostly as 'soup', so only basic checking is in place.
409
410 TODO: Don't derive this from dict, but use a dict as a member variable.
411
412 Args:
413 cgats (None | str | bytes | list | Path | io.IOBase | ICCProfileTag, optional):
414 Can be a path, a string holding CGATS data, or a file object.
415 normalize_fields (bool, optional): If True, convert all KEYWORDs and
416 all fields in DATA_FORMAT to UPPERCASE and SampleId or SampleName
417 to SAMPLE_ID or SAMPLE_NAME respectively. Defaults to False.
418 file_identifier (bytes, optional): The file identifier to use. Defaults
419 to b"CTI3". It is used as fallback if no file identifier is
420 present.
421 emit_keywords (bool, optional): If True, emit KEYWORDs in the output.
422 Defaults to False.
423 strict (bool, optional): If True, raise errors for malformed data.
424 Defaults to False.
425 """
426
427 datetime = None
428 filename = None
429 key = None
430 _lvl = 0
431 _modified = False
432 mtime = None
433 parent = None
434 root = None
435 type = b"ROOT"
436 vmaxlen = 0
437
438 def __init__(
439 self,
440 cgats: None | str | bytes | list | Path | io.IOBase | ICCProfileTag = None,
441 normalize_fields: bool = False,
442 file_identifier: bytes = b"CTI3",
443 emit_keywords: bool = False,
444 strict: bool = False,
445 ) -> None:
446 super().__init__()
447
448 self.normalize_fields = normalize_fields
449 self.file_identifier = file_identifier.strip()
450 self.emit_keywords = emit_keywords
451 self.root = self
452
453 if not cgats:
454 return
455
456 raw_lines = self.read_raw_data(cgats)
457
458 if self.filename:
459 self.mtime = os.stat(self.filename).st_mtime
460
461 self.parse_raw_data(strict, raw_lines)
462
463 def read_raw_data(self, cgats: str | bytes | list | Path | io.IOBase) -> list:
464 """Read raw CGATS data.
465
466 Args:
467 cgats (str | bytes | list | Path | io.IOBase): CGATS data to parse.
468
469 Raises:
470 CGATSInvalidError: If the type of cgats is unsupported.
471
472 Returns:
473 list: Parsed CGATS data lines.
474 """
475 raw_lines = []
476 if isinstance(cgats, list):
477 raw_lines = cgats
478 elif isinstance(cgats, str):
479 if "\n" not in cgats or "\r" not in cgats:
480 # assume filename
481 with open(cgats, "rb") as cgats_:
482 self.filename = cgats_.name
483 cgats_.seek(0)
484 raw_lines = cgats_.readlines()
485 else:
486 # assume text
487 with io.StringIO(cgats) as cgats_:
488 cgats_.seek(0)
489 raw_lines = cgats_.readlines()
490 elif isinstance(cgats, bytes):
491 # assume text
492 with io.BytesIO(cgats) as cgats_:
493 cgats_.seek(0)
494 raw_lines = cgats_.readlines()
495 elif isinstance(cgats, ICCProfileTag):
496 with io.BytesIO(cgats.tagData) as cgats_:
497 cgats_.seek(0)
498 raw_lines = cgats_.readlines()
499 elif isinstance(cgats, Path):
500 self.filename = cgats.absolute()
501 with open(cgats, "rb") as cgats_:
502 cgats_.seek(0)
503 raw_lines = cgats_.readlines()
504 elif isinstance(cgats, io.IOBase):
505 if hasattr(cgats, "readlines"):
506 cgats.seek(0)
507 raw_lines = cgats.readlines()
508 else:
509 # Assume file-like object
510 raw_lines = cgats.read()
511 if isinstance(raw_lines, bytes):
512 raw_lines = [raw_lines]
513 cgats.close()
514 else:
515 raise CGATSInvalidError(f"Unsupported type: {type(cgats)}")
516 return raw_lines
517
518 def parse_raw_data(self, strict: bool, raw_lines: list) -> None:
519 """Parse raw CGATS data.
520
521 Args:
522 strict (bool): If True, raise errors for malformed data.
523 raw_lines (list): List of raw CGATS data lines to parse.
524
525 Raises:
526 CGATSInvalidError: If strict is True and data is malformed.
527
528 """
529 context = self
530 for raw_line in raw_lines:
531 # Replace 1.#IND00 with NaN
532 raw_line = raw_line.replace(b"1.#IND00", b"NaN")
533
534 # strip control chars and leading/trailing whitespace
535 line = re.sub(b"[^\x09\x20-\x7e\x80-\xff]", b"", raw_line.strip())
536 line, values = self._parse_raw_data_deal_with_quotes(line)
537 context = self._parse_raw_data_begin(context, line)
538 context = self._parse_data_begin_and_end(strict, context, line, values)
539
540 if 0 in self and self[0].get("NORMALIZED_TO_Y_100") == b"NO":
541 # Always normalize to Y = 100
542 reprstr = self.filename or (
543 f"<{self.__module__}.{self.__class__.__name__} "
544 f"instance at 0x{id(self):016x}>"
545 )
546 if self[0].normalize_to_y_100():
547 print("Normalized to Y = 100:", reprstr)
548 else:
549 print("Warning: Could not normalize to Y = 100:", reprstr)
550 self.setmodified(False)
551
552 def _parse_data_begin_and_end(
553 self, strict: bool, context: CGATS, line: bytes, values: list
554 ) -> CGATS:
555 """Parse data lines and handle BEGIN_ and END_ sections.
556
557 Args:
558 strict (bool): If True, raise errors for malformed data.
559 context (CGATS): Current CGATS context.
560 line (bytes): The line to parse.
561 values (list): List of values parsed from the line.
562
563 Returns:
564 CGATS: The updated CGATS context.
565 """
566 if line == b"BEGIN_DATA_FORMAT":
567 context["DATA_FORMAT"] = CGATS()
568 context["DATA_FORMAT"].key = "DATA_FORMAT"
569 context["DATA_FORMAT"].parent = context
570 context["DATA_FORMAT"].root = self
571 context["DATA_FORMAT"].type = b"DATA_FORMAT"
572 context = context["DATA_FORMAT"]
573 elif line == b"END_DATA_FORMAT":
574 context = context.parent
575 elif line == b"BEGIN_DATA":
576 context["DATA"] = CGATS()
577 context["DATA"].key = "DATA"
578 context["DATA"].parent = context
579 context["DATA"].root = self
580 context["DATA"].type = b"DATA"
581 context = context["DATA"]
582 elif line == b"END_DATA":
583 context = context.parent
584 elif line[:6] == b"BEGIN_":
585 key = line[6:].decode()
586 context[key] = CGATS()
587 context[key].key = key
588 context[key].parent = context
589 context[key].root = self
590 context[key].type = b"SECTION"
591 context = context[key]
592 elif line[:4] == b"END_":
593 context = context.parent
594 elif context.type in (b"DATA_FORMAT", b"DATA"):
595 if len(values):
596 context = context.add_data(values)
597 elif context.type == b"SECTION":
598 context = context.add_data(line)
599 elif len(values) > 1:
600 context = self.parse_data_multi_values(strict, context, line, values)
601 elif (
602 values
603 and values[0] not in (b"Comment:", b"Date:")
604 and len(line) >= 3
605 and not re.search(b"[^ 0-9A-Za-z/.]", line)
606 ):
607 context = self.add_data(line)
608 return context
609
610 def parse_data_multi_values(
611 self, strict: bool, context: CGATS, line: bytes, values: list
612 ) -> CGATS:
613 """Parse multi-value data lines.
614
615 Args:
616 strict (bool): If True, raise errors for malformed data.
617 context (CGATS): Current CGATS context.
618 line (bytes): The line to parse.
619 values (list): List of values parsed from the line.
620
621 Returns:
622 CGATS: The updated CGATS object.s
623 """
624 if values[0] == b"Date:":
625 context.datetime = line
626 elif len(values) == 2 and b'"' not in values[0]:
627 key, value = values[0].decode(), values[1]
628 if value is not None:
629 context = context.add_data({key: value.strip(b'"')})
630 else:
631 context = context.add_data({key: b""})
632 elif strict:
633 raise CGATSInvalidError(
634 "Malformed {} file: {}".format(
635 (context.parent and context.type) or "CGATS",
636 self.filename or self,
637 )
638 )
639 return context
640
641 def _parse_raw_data_begin(self, context: CGATS, line: bytes) -> CGATS:
642 """Parse raw data line and handle BEGIN_ sections.
643
644 Args:
645 context (CGATS): The current CGATS context.
646 line (bytes): The raw data line to parse.
647
648 Returns:
649 CGATS: The updated CGATS context.
650 """
651 if line[:6] != b"BEGIN_":
652 return context
653 key = line[6:].decode()
654 if key in context:
655 # Start new CGATS
656 new = len(self)
657 self[new] = CGATS()
658 self[new].key = ""
659 self[new].parent = self
660 self[new].root = self.root
661 self[new].type = b""
662 context = self[new]
663 return context
664
665 def _parse_raw_data_deal_with_quotes(self, line: bytes) -> tuple[bytes, list]:
666 """Parse raw data line and deal with comments and quotes.
667
668 Args:
669 line (bytes): The raw data line to parse.
670
671 Returns:
672 tuple[bytes, list]: The processed line and a list of values.
673 """
674 if b"#" not in line and b'"' not in line:
675 # no comments or quotes
676 values = line.split()
677 return line, values
678
679 # Deal with comments and quotes
680 quoted = False
681 values = []
682 token_start = 0
683 end = len(line) - 1
684 for i in range(len(line)):
685 char = line[i : i + 1]
686 if char == b'"':
687 if quoted is False:
688 if not line[token_start:i]:
689 token_start = i
690 quoted = True
691 else:
692 quoted = False
693 if (quoted is False and char in b"# \t") or i == end:
694 if i == end:
695 i += 1
696 value = line[token_start:i]
697 if value:
698 if value[0:1] == b'"' == value[-2:-1]:
699 # Unquote
700 value = value[1:-1]
701 # Need to unescape double quote -> single quote
702 values.append(value.replace(b'""', b'"'))
703 if char == b"#":
704 # Strip comment
705 line = line[:i].strip()
706 break
707 if char in b" \t":
708 token_start = i + 1
709 return line, values
710
711 def __delattr__(self, name: str) -> None:
712 """Delete attributes from CGATS dictionary.
713
714 Args:
715 name (str): The name of the attribute to delete.
716 """
717 del self[name]
718 self.setmodified()
719
720 def __delitem__(self, name: str) -> None:
721 """Delete item from CGATS dictionary.
722
723 Args:
724 name (str): The name of the item to delete.
725 """
726 dict.__delitem__(self, name)
727 self.setmodified()
728
729 def __getattr__(self, name: str) -> Any: # noqa: ANN401
730 """Get attributes from CGATS dictionary.
731
732 Args:
733 name (str): The name of the attribute to get.
734
735 Raises:
736 AttributeError: If the attribute is not found.
737
738 Returns:
739 Any: The value of the attribute.
740 """
741 if name in self:
742 return self[name]
743 raise AttributeError(name)
744
745 def __getitem__(self, name: str) -> Any: # noqa: ANN401
746 """Get item from CGATS dictionary.
747
748 Args:
749 name (str): The name of the item to get.
750
751 Raises:
752 CGATSKeyError: If the item is not found.
753
754 Returns:
755 Any: The value of the item.
756 """
757 if name == -1:
758 return self.get(len(self) - 1)
759 if name in ("NUMBER_OF_FIELDS", "NUMBER_OF_SETS"):
760 return getattr(self, name)
761 if name in self:
762 if str(name).upper() in ("INDEX", "SAMPLE_ID", "SAMPLEID"):
763 if not isinstance(self.get(name), (int, float)):
764 return self.get(name)
765 if str(name).upper() == "INDEX":
766 return self.key
767 if isinstance(self.get(name), float):
768 return 1.0 / (self.NUMBER_OF_SETS - 1) * self.key
769 return self.key + 1
770 return self.get(name)
771 raise CGATSKeyError(name)
772
773 def get(self, name: int | str, default: None | Any = None) -> Any: # noqa: ANN401
774 """Get item from CGATS dictionary.
775
776 Args:
777 name (int | str): The name or index of the item to get.
778 default (None | Any, optional): The value to return if the item is
779 not found.
780
781 Returns:
782 Any: The value of the item or the default value if not found.
783 """
784 if name == -1:
785 return dict.get(self, len(self) - 1, default)
786 if name in ("NUMBER_OF_FIELDS", "NUMBER_OF_SETS"):
787 return getattr(self, name, default)
788 return dict.get(self, name, default)
789
790 def get_colorants(self) -> None | list:
791 """Return colorants from CGATS file.
792
793 Returns:
794 None | list: List of colorants if available, otherwise None.
795 """
796 color_rep = (self.queryv1("COLOR_REP") or b"").split(b"_")
797 if len(color_rep) != 2:
798 return None
799 query = {}
800 colorants = []
801 for i in range(len(color_rep[0])):
802 for j in range(len(color_rep[0])):
803 channelname = color_rep[0][j : j + 1]
804 # the key should be str
805 key = b"_".join([color_rep[0], channelname]).decode("utf-8")
806 query[key] = 100 if i == j else 0
807 colorants.append(self.queryi1(query))
808 return colorants
809
810 def get_descriptor(self, localized: bool = True) -> bytes:
811 """Return CGATS description as string, based on metadata.
812
813 If 'localized' is True (default), include localized technology
814 description for CCSS files.
815
816 Args:
817 localized (bool, optional): If True, include localized technology
818 description for CCSS files. Defaults to True.
819
820 Returns:
821 bytes: CGATS description as bytes.
822 """
823 desc = self.queryv1("DESCRIPTOR")
824 is_ccss = self.get(0, self).type == b"CCSS"
825 if not desc or desc == b"Not specified" or is_ccss:
826 if not is_ccss:
827 desc = self.queryv1("INSTRUMENT")
828 if desc:
829 display = self.queryv1("DISPLAY")
830 if display:
831 desc += b" & %s" % display
832 else:
833 tech = self.queryv1("TECHNOLOGY")
834 if tech:
835 if (
836 desc
837 and desc != b"Not specified"
838 and desc != b"CCSS for %s" % tech
839 ):
840 display = desc
841 else:
842 display = self.queryv1("DISPLAY")
843 if localized:
844 from DisplayCAL import localization as lang
845
846 tech = tech.decode()
847 tech = lang.getstr(f"display.tech.{tech}", default=tech)
848 if display:
849 # Localized `tech` will always be a str,
850 # need to make sure `display` is as well.
851 display = (
852 display.decode("utf-8")
853 if isinstance(display, bytes)
854 else display
855 )
856 if display:
857 tech = f"{tech} ({display})"
858 desc = tech.encode("utf-8") if isinstance(tech, str) else tech
859 if not desc and self.filename:
860 # With Python 3.6+ the encoding is always "utf-8" independent of the OS.
861 desc = bytes(
862 str(os.path.splitext(os.path.basename(self.filename))[0]), "utf-8"
863 )
864 return desc
865
866 def __setattr__(self, name: str, value: Any) -> None: # noqa: ANN401
867 """Set attributes on the CGATS object.
868
869 Args:
870 name (str): The name of the attribute to set.
871 value (Any): The value to set the attribute to.
872 """
873 if name in ("_keys", "_lvl"):
874 object.__setattr__(self, name, value)
875 elif name == "modified":
876 self.setmodified(value)
877 elif name in (
878 "datetime",
879 "filename",
880 "fileName",
881 "file_identifier",
882 "key",
883 "mtime",
884 "normalize_fields",
885 "parent",
886 "root",
887 "type",
888 "vmaxlen",
889 "emit_keywords",
890 ):
891 object.__setattr__(self, name, value)
892 self.setmodified()
893 else:
894 self[name] = value
895
896 def __setitem__(self, name: str, value: Any) -> None: # noqa: ANN401
897 """Set item in CGATS dictionary.
898
899 Args:
900 name (str): The name of the item to set.
901 value (Any): The value to set for the item.
902 """
903 dict.__setitem__(self, name, value)
904 self.setmodified()
905
906 def setmodified(self, modified: bool = True) -> None:
907 """Set 'modified' state on the 'root' object."""
908 if self.root and self.root._modified != modified:
909 object.__setattr__(self.root, "_modified", modified)
910
911 def __bytes__(self) -> bytes:
912 """Return CGATS data as bytes.
913
914 Returns:
915 bytes: CGATS data as bytes.
916 """
917 result = []
918 lvl = self.root._lvl
919 self.root._lvl += 1
920 data = None
921 if self.type == b"SAMPLE":
922 result.append(
923 b" ".join(
924 rpad(self[item], self.parent.vmaxlen + (1 if self[item] < 0 else 0))
925 for item in list(self.parent.parent["DATA_FORMAT"].values())
926 )
927 )
928 elif self.type == b"DATA":
929 data = self
930 elif self.type == b"DATA_FORMAT":
931 result.append(b" ".join(list(self.values())))
932 else:
933 data, result = self.__bytes_from_subsections(data, result)
934 if data and data.parent["DATA_FORMAT"]:
935 if "KEYWORDS" in data.parent and self.emit_keywords:
936 result.extend(
937 b'KEYWORD "%s"' % item
938 for item in list(data.parent["DATA_FORMAT"].values())
939 if item in list(data.parent["KEYWORDS"].values())
940 )
941 result.append(
942 b"NUMBER_OF_FIELDS %s"
943 % bytes(str(len(data.parent["DATA_FORMAT"])), "utf-8")
944 )
945 result.append(b"BEGIN_DATA_FORMAT")
946 result.append(b" ".join(list(data.parent["DATA_FORMAT"].values())))
947 result.append(b"END_DATA_FORMAT")
948 result.append(b"")
949 result.append(b"NUMBER_OF_SETS %s" % (bytes(str(len(data)), "utf-8")))
950 result.append(b"BEGIN_DATA")
951 result.extend(
952 b" ".join(
953 [
954 rpad(
955 data[key][item.decode("utf-8")],
956 data.vmaxlen
957 + (1 if data[key][item.decode("utf-8")] < 0 else 0),
958 )
959 for item in list(data.parent["DATA_FORMAT"].values())
960 ]
961 )
962 for key in data
963 )
964 result.append(b"END_DATA")
965 if (
966 ((self.parent and self.parent.type) or self.type) == b"ROOT"
967 and result
968 and result[-1] != b""
969 and lvl == 0
970 ):
971 # Add empty line at end if not yet present
972 result.append(b"")
973 self.root._lvl -= 1
974 return b"\n".join(result)
975
976 def __bytes_from_subsections(self, data: CGATS, result: list) -> tuple[CGATS, list]:
977 """Generate bytes from subsections.
978
979 Args:
980 data (CGATS): The CGATS data to process.
981 result (list): The list to append the generated bytes to.
982
983 Returns:
984 tuple[CGATS, list]: A tuple containing the data and the result
985 list.
986 """
987 if self.datetime:
988 result.append(self.datetime)
989 if self.type == b"SECTION":
990 result.append(b"BEGIN_" + self.key.encode())
991 elif self.parent and self.parent.type == b"ROOT":
992 # Make sure CGATS file identifiers are always a minimum of 7 characters
993 result.append(self.type.ljust(7))
994 result.append(b"")
995
996 data, result = self.__bytes_from_subsection_data(data, result)
997
998 if self.type == b"SECTION":
999 result.append(b"END_" + self.key.encode())
1000 if self.type == b"SECTION" or data:
1001 result.append(b"")
1002 return data, result
1003
1004 def __bytes_from_subsection_data(
1005 self, data: CGATS, result: list
1006 ) -> tuple[CGATS, list]:
1007 """Generate bytes from subsection data.
1008
1009 Args:
1010 data (CGATS): The CGATS data to process.
1011 result (list): The list to append the generated bytes to.
1012
1013 Returns:
1014 tuple[CGATS, list]: A tuple containing the data and the result
1015 list.
1016 """
1017 if self.type in (b"DATA", b"DATA_FORMAT", b"KEYWORDS", b"SECTION"):
1018 iterable = self
1019 else:
1020 iterable = self.keys()
1021 for key in iterable:
1022 value = self[key]
1023 value = value.encode("utf-8") if isinstance(value, str) else value
1024
1025 if key == "DATA":
1026 data = value
1027 elif isinstance(value, (float, int, bytes)):
1028 if key not in ("NUMBER_OF_FIELDS", "NUMBER_OF_SETS"):
1029 if isinstance(key, int):
1030 result.append(
1031 value
1032 if isinstance(value, bytes)
1033 else bytes(str(value), "utf-8")
1034 )
1035 else:
1036 if (
1037 "KEYWORDS" in self
1038 and key in list(self["KEYWORDS"].values())
1039 and self.emit_keywords
1040 ):
1041 result.append(b'KEYWORD "%s"' % key.encode())
1042 if isinstance(value, bytes):
1043 # Need to escape single quote -> double quote
1044 value = value.replace(b'"', b'""')
1045 if isinstance(value, (float, int)):
1046 value = bytes(str(value), "utf-8")
1047 result.append(b'%s "%s"' % (key.encode(), value))
1048 elif key not in ("DATA_FORMAT", "KEYWORDS"):
1049 if value.type == b"SECTION" and result[-1:] and result[-1:][0] != b"":
1050 result.append(b"")
1051 result.append(bytes(value))
1052 return data, result
1053
1054 def add_keyword(self, keyword: str, value: None | str = None) -> None:
1055 """Add a keyword to the list of keyword values.
1056
1057 Args:
1058 keyword (str): The keyword to add.
1059 value (str, optional): The value associated with the keyword.
1060 Defaults to None.
1061 """
1062 if isinstance(keyword, bytes):
1063 keyword = keyword.decode()
1064
1065 if self.type in (b"DATA", b"DATA_FORMAT", b"KEYWORDS", b"SECTION"):
1066 context = self.parent
1067 elif self.type == b"SAMPLE":
1068 context = self.parent.parent
1069 else:
1070 context = self
1071 if "KEYWORDS" not in context:
1072 context["KEYWORDS"] = CGATS()
1073 context["KEYWORDS"].key = "KEYWORDS"
1074 context["KEYWORDS"].parent = context
1075 context["KEYWORDS"].root = self.root
1076 context["KEYWORDS"].type = b"KEYWORDS"
1077 if keyword.encode() not in list(context["KEYWORDS"].values()):
1078 newkey = len(context["KEYWORDS"])
1079 while newkey in context["KEYWORDS"]:
1080 newkey += 1
1081 context["KEYWORDS"][newkey] = keyword.encode()
1082 if value is not None:
1083 context[keyword] = value
1084
1085 def add_section(self, key: str, value: str) -> None:
1086 """Add a section to the CGATS data.
1087
1088 Args:
1089 key (str): The key for the section.
1090 value (str): The value for the section.
1091 """
1092 self[key] = CGATS()
1093 self[key].key = key
1094 self[key].parent = self
1095 self[key].root = self
1096 self[key].type = b"SECTION"
1097 self[key].add_data(value)
1098
1099 def remove_keyword(self, keyword: str, remove_value: bool = True) -> None:
1100 """Remove a keyword from the list of keyword values.
1101
1102 Args:
1103 keyword (str): The keyword to remove.
1104 remove_value (bool): If True, also remove the value associated
1105 with the keyword. Defaults to True.
1106 """
1107 if self.type in (b"DATA", b"DATA_FORMAT", b"KEYWORDS", b"SECTION"):
1108 context = self.parent
1109 elif self.type == b"SAMPLE":
1110 context = self.parent.parent
1111 else:
1112 context = self
1113 for key in list(context["KEYWORDS"].keys()):
1114 if context["KEYWORDS"][key] == keyword.encode():
1115 del context["KEYWORDS"][key]
1116 if remove_value:
1117 del context[keyword]
1118
1119 def insert(self, key: None | int = None, data: None | CGATS = None) -> None:
1120 """Insert data at index key. Also see add_data method.
1121
1122 Args:
1123 key (int, optional): The index at which to insert the data.
1124 If None, data is appended. Defaults to None.
1125 data (CGATS, optional): The CGATS data to insert. If None,
1126 the current CGATS instance is used. Defaults to None.
1127 """
1128 self.add_data(data, key)
1129
1130 def append(self, data: CGATS) -> None:
1131 """Append data. Also see add_data method.
1132
1133 Args:
1134 data (CGATS): The CGATS data to append.
1135 """
1136 self.add_data(data)
1137
1138 def get_data(self, field_names: None | tuple = None) -> bool | CGATS:
1139 """Get CGATS data.
1140
1141 Args:
1142 field_names (tuple, optional): A tuple of field names to query.
1143 If None, all data is returned. Defaults to None.
1144
1145 Returns:
1146 bool | CGATS: A dictionary containing the CGATS data.
1147 """
1148 data = self.queryv1("DATA")
1149 if not data:
1150 return False
1151 if field_names:
1152 data = data.queryi(field_names)
1153 return data
1154
1155 def get_rgb_xyz_values(self) -> tuple[bool, bool] | tuple[CGATS, list]:
1156 """Get RGB and XYZ values from the CGATS data.
1157
1158 Returns:
1159 tuple: A tuple containing two elements:
1160 - A dictionary with RGB and XYZ values.
1161 - A list of lists containing RGB and XYZ values in the order:
1162 [R, G, B, X, Y, Z].
1163 If no data is found, returns (False, False).
1164 """
1165 field_names = ("RGB_R", "RGB_G", "RGB_B", "XYZ_X", "XYZ_Y", "XYZ_Z")
1166 data = self.get_data(field_names)
1167 if not data:
1168 return False, False
1169 values_list = [
1170 [data[_key][field_name] for field_name in field_names] for _key in data
1171 ]
1172 return data, values_list
1173
1174 def set_rgb_xyz_values(self, values_list: list) -> bool:
1175 """Set RGB and XYZ values in the CGATS data.
1176
1177 Args:
1178 values_list (list): A list of RGB and XYZ values, where each entry
1179 is a list containing RGB and XYZ values in the order:
1180 [R, G, B, X, Y, Z].
1181
1182 Returns:
1183 bool: True if values were set successfully, False otherwise.
1184 """
1185 field_names = ("RGB_R", "RGB_G", "RGB_B", "XYZ_X", "XYZ_Y", "XYZ_Z")
1186 for i, values in enumerate(values_list):
1187 for j, field_name in enumerate(field_names):
1188 self[i][field_name] = values[j]
1189 return True
1190
1191 def checkerboard(
1192 self,
1193 sort1: Callable = sort_by_l,
1194 sort2: Callable = sort_rgb_white_to_top,
1195 split_grays: bool = False,
1196 shift: bool = False,
1197 ) -> bool:
1198 """Return a checkerboard of RGB values.
1199
1200 Args:
1201 sort1 (Callable): Function to sort the first dimension.
1202 sort2 (Callable): Function to sort the second dimension.
1203 split_grays (bool): If True, split grays from colors.
1204 shift (bool): If True, shift values in checkerboard.
1205
1206 Returns:
1207 bool: True if checkerboard was created successfully, False
1208 otherwise.
1209 """
1210 data, values_list = self.get_rgb_xyz_values()
1211 if not values_list:
1212 return False
1213 numvalues = len(values_list)
1214 values_list = (
1215 sorted(values_list, key=functools.cmp_to_key(sort1))
1216 if sort1
1217 else values_list
1218 )
1219 values_list = (
1220 sorted(values_list, key=functools.cmp_to_key(sort2))
1221 if sort2
1222 else values_list
1223 )
1224 gray = []
1225 color = (
1226 self.split_grays(values_list, gray, numvalues)
1227 if split_grays
1228 else values_list
1229 )
1230 checkerboard = []
1231 for values_list in [gray, color]:
1232 if not values_list:
1233 continue
1234 split = round(len(values_list) / 2.0)
1235 values_list1 = values_list[:split]
1236 values_list2 = values_list[split:]
1237 if shift:
1238 # Shift values.
1239 #
1240 # If split is even:
1241 # A1 A2 A3 A4 -> A1 B2 B3 B1 B4
1242 # B1 B2 B3 B4 -> A3 A4 A2
1243 #
1244 # If split is uneven:
1245 # A1 A2 A3 -> A1 B1 B2 B3 B4
1246 # B1 B2 B3 B4 -> A2 A3
1247 offset = 0
1248 if split == len(values_list) / 2.0:
1249 # Even split
1250 offset += 1
1251 values_list1_orig = list(values_list1)
1252 values_list2_orig = list(values_list2)
1253 values_list1 = values_list2_orig[offset:]
1254 values_list2 = values_list1_orig[offset + 1 :]
1255 values_list1.insert(0, values_list1_orig[0])
1256 if offset:
1257 values_list1.insert(-1, values_list2_orig[0])
1258 values_list2.extend(values_list1_orig[1:2])
1259 # Interleave.
1260 # 1 2 3 4 5 6 7 8 -> 1 5 2 6 3 7 4 8
1261 while values_list1 or values_list2:
1262 for values_list in (values_list1, values_list2):
1263 if values_list:
1264 values = values_list.pop(0)
1265 checkerboard.append(values)
1266 if shift and checkerboard[-1][:3] == [100, 100, 100]:
1267 # Move white patch to front
1268 debug_print("INFO - moving white to front")
1269 checkerboard.insert(0, checkerboard.pop())
1270 if len(checkerboard) != numvalues:
1271 # This should never happen
1272 print(
1273 "Number of patches incorrect after re-ordering "
1274 f"(is {len(checkerboard)}, should be {numvalues})"
1275 )
1276 return False
1277 return data.set_rgb_xyz_values(checkerboard)
1278
1279 def split_grays(self, values_list: list, gray: list, numvalues: int) -> list:
1280 """Split values into gray and color.
1281
1282 Args:
1283 values_list (list): List of RGB values.
1284 gray (list): List to store gray values.
1285 numvalues (int): Total number of values.
1286
1287 Returns:
1288 list: List of color and gray values.
1289 """
1290 # Split values into gray and color. First gray in a consecutive
1291 # sequence of two or more grays will be added to color list,
1292 # following grays will be added to gray list.
1293 color = []
1294 prev_i = -1
1295 prev_values = []
1296 added = {prev_i: True} # Keep track of entries we have added
1297 for i, values in enumerate(values_list):
1298 debug_print(i + 1, "IN", values[:3])
1299 is_gray = values[:3] == [values[:3][0]] * 3
1300 prev = color
1301 cur = color
1302 if is_gray:
1303 if not prev_values:
1304 debug_print("WARNING - skipping gray because no prev")
1305 elif values[:3] == prev_values[:3]:
1306 # Same gray as prev value
1307 prev = color
1308 cur = gray
1309 debug_print(
1310 f"INFO - appending prev {prev_values[:3]} to color "
1311 "because prev was same gray but got skipped",
1312 other_conditions=prev_i not in added,
1313 )
1314 debug_print(
1315 "INFO - appending cur to gray because prev "
1316 f"{prev_values[:3]} was same gray"
1317 )
1318 elif prev_values[:3] == [prev_values[:3][0]] * 3:
1319 # Prev value was different gray
1320 prev = gray
1321 cur = gray
1322 debug_print(
1323 f"INFO - appending prev {prev_values[:3]} to gray "
1324 "because prev was different gray but got skipped",
1325 other_conditions=prev_i not in added,
1326 )
1327 debug_print(
1328 "INFO - appending cur to gray because prev "
1329 f"{prev_values[:3]} was different gray"
1330 )
1331 elif i < numvalues - 1:
1332 debug_print(
1333 "WARNING - skipping gray because prev "
1334 f"{prev_values[:3]} was not gray"
1335 )
1336 else:
1337 # Last
1338 debug_print(
1339 "INFO - appending cur to color because prev "
1340 f"{prev_values[:3]} was not gray but cur is last"
1341 )
1342 if not is_gray or cur is gray or i == numvalues - 1:
1343 if prev_i not in added:
1344 debug_print(
1345 f"INFO - appending prev {prev_values[:3]} "
1346 "to color because prev got skipped",
1347 other_conditions=prev is cur is color,
1348 )
1349 prev.append(prev_values)
1350 added[prev_i] = True
1351 debug_print(
1352 "INFO - appending cur to color",
1353 other_conditions=not is_gray and cur is color,
1354 )
1355 cur.append(values)
1356 added[i] = True
1357 prev_i = i
1358 prev_values = values
1359 return color
1360
1361 def sort_rgb_gray_to_top(self) -> bool:
1362 """Sort RGB values with gray at the top.
1363
1364 Returns:
1365 bool: True if sorting was successful, False otherwise.
1366 """
1367 return self.sort_data_rgb_xyz(sort_rgb_gray_to_top)
1368
1369 def sort_rgb_to_top(
1370 self, red: bool = False, green: bool = False, blue: bool = False
1371 ) -> bool:
1372 """Sort quantities of R, G or B (or combinations) to top.
1373
1374 Example: sort_RGB_to_top(True, False, False) - sort red values to top
1375 Example: sort_RGB_to_top(False, True, True) - sort cyan values to top
1376
1377 Args:
1378 red (bool): If True, sort red values to top.
1379 green (bool): If True, sort green values to top.
1380 blue (bool): If True, sort blue values to top.
1381
1382 Returns:
1383 bool: True if sorting was successful, False otherwise.
1384 """
1385 if red and green and blue:
1386 function = sort_rgb_gray_to_top
1387 elif red and green:
1388 function = sort_rgb_to_top_factory(0, 1, 2, 0)
1389 elif red and blue:
1390 function = sort_rgb_to_top_factory(0, 2, 1, 0)
1391 elif green and blue:
1392 function = sort_rgb_to_top_factory(1, 2, 0, 1)
1393 elif red:
1394 function = sort_rgb_to_top_factory(1, 2, 1, 0)
1395 elif green:
1396 function = sort_rgb_to_top_factory(0, 2, 0, 1)
1397 elif blue:
1398 function = sort_rgb_to_top_factory(0, 1, 0, 2)
1399 else:
1400 return False
1401 return self.sort_data_rgb_xyz(function)
1402
1403 def sort_rgb_white_to_top(self) -> bool:
1404 """Sort RGB values with white at the top.
1405
1406 Returns:
1407 bool: True if sorting was successful, False otherwise.
1408 """
1409 return self.sort_data_rgb_xyz(sort_rgb_white_to_top)
1410
1411 def sort_by_hsi(self) -> bool:
1412 """Sort by HSI values.
1413
1414 Returns:
1415 bool: True if sorting was successful, False otherwise.
1416 """
1417 return self.sort_data_rgb_xyz(sort_by_hsi)
1418
1419 def sort_by_hsl(self) -> bool:
1420 """Sort by HSL values.
1421
1422 Returns:
1423 bool: True if sorting was successful, False otherwise.
1424 """
1425 return self.sort_data_rgb_xyz(sort_by_hsl)
1426
1427 def sort_by_hsv(self) -> bool:
1428 """Sort by HSV values.
1429
1430 Returns:
1431 bool: True if sorting was successful, False otherwise.
1432 """
1433 return self.sort_data_rgb_xyz(sort_by_hsv)
1434
1435 def sort_by_l(self) -> bool:
1436 """Sort by L values.
1437
1438 Returns:
1439 bool: True if sorting was successful, False otherwise.
1440 """
1441 return self.sort_data_rgb_xyz(sort_by_l)
1442
1443 def sort_by_rgb(self) -> bool:
1444 """Sort by RGB values.
1445
1446 Returns:
1447 bool: True if sorting was successful, False otherwise.
1448 """
1449 return self.sort_data_rgb_xyz(sort_by_rgb)
1450
1451 def sort_by_bgr(self) -> bool:
1452 """Sort by BGR values.
1453
1454 Returns:
1455 bool: True if sorting was successful, False otherwise.
1456 """
1457 return self.sort_data_rgb_xyz(sort_by_bgr)
1458
1459 def sort_by_rgb_pow_sum(self) -> bool:
1460 """Sort by RGB power sum.
1461
1462 Returns:
1463 bool: True if sorting was successful, False otherwise.
1464 """
1465 return self.sort_data_rgb_xyz(sort_by_rgb_pow_sum)
1466
1467 def sort_by_rgb_sum(self) -> bool:
1468 """Sort by RGB sum.
1469
1470 Returns:
1471 bool: True if sorting was successful, False otherwise.
1472 """
1473 return self.sort_data_rgb_xyz(sort_by_rgb_sum)
1474
1475 def sort_by_rec709_luma(self) -> bool:
1476 """Sort by Rec. 709 luma.
1477
1478 Returns:
1479 bool: True if sorting was successful, False otherwise.
1480 """
1481 return self.sort_data_rgb_xyz(sort_by_rec709_luma)
1482
1483 def sort_data_rgb_xyz(
1484 self,
1485 cmp: None | Callable = None,
1486 key: None | Callable = None,
1487 reverse: bool = False,
1488 ) -> bool:
1489 """Sort RGB/XYZ data.
1490
1491 Args:
1492 cmp (callable, optional): Comparison function to use for sorting.
1493 key (callable, optional): Key function to use for sorting.
1494 reverse (bool, optional): If True, sort in descending order.
1495
1496 Returns:
1497 bool: True if sorting was successful, False otherwise.
1498 """
1499 data, valueslist = self.get_rgb_xyz_values()
1500 if not valueslist:
1501 return False
1502 valueslist = sorted(valueslist, key=functools.cmp_to_key(cmp), reverse=reverse)
1503 return data.set_rgb_xyz_values(valueslist)
1504
1505 @property
1506 def modified(self) -> bool:
1507 """Return whether the CGATS object has been modified.
1508
1509 Returns:
1510 bool: True if modified, False otherwise.
1511 """
1512 if self.root:
1513 return self.root._modified
1514 return self._modified
1515
1516 def moveby1(self, start: int, inc: int = 1) -> None:
1517 """Move items from start by incrementing or decrementing their key by inc.
1518
1519 Args:
1520 start (int): The starting index from which to move items.
1521 inc (int, optional): The increment by which to move items.
1522 Defaults to 1.
1523 """
1524 r = range(start, len(self) + 1)
1525 if inc > 0:
1526 r = reversed(r)
1527 for key in r:
1528 if key in self:
1529 if key + inc < 0:
1530 break
1531 self[key].key += inc
1532 self[key + inc] = self[key]
1533 if key == len(self) - 1:
1534 break
1535
1536 def add_data(
1537 self, data: bytes | str | dict | list | tuple | CGATS, key: None | int = None
1538 ) -> CGATS:
1539 """Add data to the CGATS structure.
1540
1541 Args:
1542 data (bytes | str | dict | list | tuple | CGATS): The data to add.
1543 key (None | int, optional): The index at which to insert the data.
1544 If None, data is appended. Defaults to None.
1545
1546 Returns:
1547 CGATS: The context in which the data was added.
1548 """
1549 context = self
1550 if self.type == b"DATA":
1551 key = self._add_data_array_type(data, key)
1552 elif self.type == b"ROOT":
1553 key, context = self._add_data_root(data, key)
1554 elif self.type == b"SECTION":
1555 self._add_data_section(data, key)
1556 elif self.type in (b"DATA_FORMAT", b"KEYWORDS") or (
1557 self.parent and self.parent.type == b"ROOT"
1558 ):
1559 self._add_data_format_or_keywords(data)
1560 else:
1561 raise CGATSInvalidOperationError(f"Cannot add data to {self.type}")
1562 return context
1563
1564 def _add_data_format_or_keywords(self, data: dict | list | tuple) -> None:
1565 """Add data to DATA_FORMAT or KEYWORDS type.
1566
1567 Args:
1568 data (dict | list | tuple): The data to add.
1569
1570 Raises:
1571 CGATSTypeError: If the data type is invalid.
1572 """
1573 if not isinstance(data, (dict, list, tuple)):
1574 raise CGATSTypeError(
1575 f"Invalid data type for {self.type} (expected "
1576 f"CGATS, dict, list or tuple, got {type(data)})"
1577 )
1578
1579 for var in data:
1580 var = var.decode() if isinstance(var, bytes) else var
1581
1582 if var in ("NUMBER_OF_FIELDS", "NUMBER_OF_SETS"):
1583 self[var] = None
1584 continue
1585
1586 if isinstance(data, dict):
1587 if self.type in (b"DATA_FORMAT", b"KEYWORDS"):
1588 key, value = len(self), data[var]
1589 else:
1590 key, value = var, data[var]
1591 else:
1592 key, value = len(self), var.encode()
1593
1594 if (
1595 self.root.normalize_fields
1596 and (self.type in (b"DATA_FORMAT", b"KEYWORDS") or var == "KEYWORD")
1597 and isinstance(value, bytes)
1598 ):
1599 value = value.upper()
1600 value = value.replace(b"SAMPLEID", b"SAMPLE_ID").replace(
1601 b"SAMPLENAME", b"SAMPLE_NAME"
1602 )
1603 # if value == b"SAMPLEID":
1604 # value = b"SAMPLE_ID"
1605 # elif value == b"SAMPLENAME":
1606 # value = b"SAMPLE_NAME"
1607
1608 if var == "KEYWORD":
1609 self.emit_keywords = True
1610 if value != b"KEYWORD":
1611 self.add_keyword(value)
1612 else:
1613 print('Warning: cannot add keyword "KEYWORD"')
1614 else:
1615 value = self.__add_data_from_bytes_value(key, value)
1616 self[key] = value
1617
1618 def __add_data_from_bytes_value(
1619 self, key: int | str, value: bytes | str
1620 ) -> int | float:
1621 """Add data from bytes value.
1622
1623 Args:
1624 key (int | str): The key for the data.
1625 value (bytes | str): The value to add.
1626
1627 Raises:
1628 CGATSTypeError: If the value type is invalid.
1629
1630 Returns:
1631 int | float: The value converted to int or float if applicable.
1632 """
1633 if isinstance(value, bytes) and key not in (
1634 "DESCRIPTOR",
1635 "ORIGINATOR",
1636 "CREATED",
1637 "DEVICE_CLASS",
1638 "COLOR_REP",
1639 "TARGET_INSTRUMENT",
1640 "LUMINANCE_XYZ_CDM2",
1641 "OBSERVER",
1642 "INSTRUMENT",
1643 "MANUFACTURER_ID",
1644 "MANUFACTURER",
1645 "REFERENCE",
1646 "REFERENCE_OBSERVER",
1647 "DISPLAY",
1648 "TECHNOLOGY",
1649 "REFERENCE_FILENAME",
1650 "REFERENCE_HASH",
1651 "TARGET_FILENAME",
1652 "TARGET_HASH",
1653 "FIT_METHOD",
1654 ):
1655 match = re.match(rb"(?:\d+|((?:\d*\.\d+|\d+)(?:e[+-]?\d+)?))$", value)
1656 if match:
1657 value = float(value) if match.groups()[0] else int(value)
1658 if self.type in (b"DATA_FORMAT", b"KEYWORDS"):
1659 raise CGATSTypeError(
1660 f"Invalid data type for {self.type} "
1661 "(expected bytes or str, "
1662 f"got {type(value)})"
1663 )
1664 return value
1665
1666 def _add_data_section(self, data: str | CGATS, key: None | int = None) -> None:
1667 """Add data to SECTION type.
1668
1669 Args:
1670 data (str | CGATS): The data to add.
1671 key (None | int, optional): The index at which to insert the data.
1672 If None, data is appended. Defaults to None.
1673
1674 Raises:
1675 CGATSTypeError: If the data type is invalid.
1676 """
1677 if isinstance(data, bytes):
1678 if isinstance(key, int):
1679 # accept only integer keys.
1680 # move existing items
1681 self.moveby1(key)
1682 else:
1683 key = len(self)
1684 self[key] = data
1685 else:
1686 raise CGATSTypeError(
1687 f"Invalid data type for {self.type} "
1688 f"(expected bytes or str, got {type(data)})"
1689 )
1690
1691 def _add_data_root(
1692 self, data: bytes | str, key: None | int = None
1693 ) -> tuple[int, CGATS]:
1694 """Add data to ROOT type.
1695
1696 Args:
1697 data (bytes | str): The data to add.
1698 key (None | int, optional): The index at which to insert the data.
1699 If None, data is appended. Defaults to None.
1700
1701 Returns:
1702 tuple[int, CGATS]: A tuple containing the key at which the data was added
1703 and the CGATS context where the data was added.
1704 """
1705 if isinstance(data, bytes) and data.find(b"\n") < 0 and data.find(b"\r") < 0:
1706 if isinstance(key, int):
1707 # accept only integer keys.
1708 # move existing items
1709 self.moveby1(key)
1710 else:
1711 key = len(self)
1712 self[key] = CGATS()
1713 self[key].key = key
1714 self[key].parent = self
1715 self[key].root = self.root
1716 self[key].type = data
1717 context = self[key]
1718 elif not len(self):
1719 context = self.add_data(self.file_identifier) # create root element
1720 context = context.add_data(data, key)
1721 else:
1722 raise CGATSTypeError(
1723 f"Invalid data type for {self.type} "
1724 f"(expected str or unicode without line endings, got {type(data)})"
1725 )
1726
1727 return key, context
1728
1729 def _add_data_array_type(
1730 self, data: dict | list | tuple | CGATS, key: None | int = None
1731 ) -> int:
1732 """Add data to DATA type.
1733
1734 Args:
1735 data (CGATS | dict | list | tuple): The data to add.
1736 key (None | int, optional): The index at which to insert the data.
1737 If None, data is appended. Defaults to None.
1738
1739 Raises:
1740 CGATSTypeError: If the data type is invalid.
1741 CGATSInvalidOperationError: If DATA_FORMAT is missing.
1742
1743 Returns:
1744 int: The key at which the data was added.
1745 """
1746 if not isinstance(data, (dict, list, tuple)):
1747 raise CGATSTypeError(
1748 f"Invalid data type for {self.type} (expected CGATS, dict, list or "
1749 f"tuple, got {type(data)})"
1750 )
1751
1752 if not self.parent["DATA_FORMAT"]:
1753 raise CGATSInvalidOperationError(
1754 "Cannot add to DATA because of missing DATA_FORMAT"
1755 )
1756
1757 fl, il = len(self.parent["DATA_FORMAT"]), len(data)
1758 if fl != il:
1759 raise CGATSTypeError(f"DATA entries take exactly {fl} values ({il} given)")
1760 dataset = CGATS()
1761 dataset = self._add_data_from_data_format_values(data, dataset)
1762 if isinstance(key, int):
1763 # accept only integer keys.
1764 # move existing items
1765 self.moveby1(key)
1766 else:
1767 key = len(self)
1768 dataset.key = key
1769 dataset.parent = self
1770 dataset.root = self.root
1771 dataset.type = b"SAMPLE"
1772 self[key] = dataset
1773
1774 return key
1775
1776 def _add_data_from_data_format_values(
1777 self, data: dict | list | tuple, dataset: CGATS
1778 ) -> CGATS:
1779 """Add data from DATA_FORMAT values.
1780
1781 Args:
1782 data (dict | list | tuple): The data to add.
1783 dataset (CGATS): The CGATS instance to which the data will be added.
1784
1785 Returns:
1786 CGATS: The updated CGATS instance with the added data.
1787 """
1788 for i, item in enumerate(list(self.parent["DATA_FORMAT"].values())):
1789 if isinstance(data, dict):
1790 try:
1791 value = data[item.decode()]
1792 except KeyError as e:
1793 raise CGATSKeyError(item) from e
1794 else:
1795 value = data[i]
1796 if item.upper() in (b"INDEX", b"SAMPLE_ID", b"SAMPLEID"):
1797 item, value = self._add_data_from_sample_id(item, value)
1798 elif item.upper() not in (b"SAMPLE_NAME", b"SAMPLE_LOC", b"SAMPLENAME"):
1799 value = self._add_data_from_sample_name(item, value)
1800 elif self.root.normalize_fields and item.upper() == b"SAMPLENAME":
1801 item = b"SAMPLE_NAME"
1802 dataset[item.decode()] = value
1803 return dataset
1804
1805 def _add_data_from_sample_id(
1806 self, item: bytes, value: bytes | str | float
1807 ) -> tuple[bytes, int | float]:
1808 """Add data from sample ID.
1809
1810 Args:
1811 item (bytes): The item key.
1812 value (bytes | str | float): The value associated with the
1813 item.
1814
1815 Returns:
1816 tuple[bytes, int | float]: The processed item key and value.
1817 """
1818 if self.root.normalize_fields and item.upper() == b"SAMPLEID":
1819 item = b"SAMPLE_ID"
1820 # allow alphanumeric INDEX / SAMPLE_ID
1821 if isinstance(value, bytes):
1822 match = re.match(rb"(?:\d+|((?:\d*\.\d+|\d+)(?:e[+-]?\d+)?))$", value)
1823 if match:
1824 value = float(value) if match.groups()[0] else int(value)
1825 return item, value
1826
1827 def _add_data_from_sample_name(
1828 self, item: bytes, value: bytes | str | float
1829 ) -> float:
1830 """Add data from sample name.
1831
1832 Args:
1833 item (bytes): The item key.
1834 value (bytes | str | float): The value associated with the
1835 item.
1836
1837 Returns:
1838 float: The processed value.
1839 """
1840 try:
1841 value = float(value)
1842 except ValueError as e:
1843 raise CGATSValueError(
1844 f"Invalid data type for {item} "
1845 f"(expected float, got {value.__class__.__name__})"
1846 ) from e
1847 else:
1848 strval = bytes(str(abs(value)), "UTF-8")
1849 if (
1850 self.parent.type != b"CAL" and item.startswith(b"RGB_")
1851 ) or item.startswith(b"CMYK_"):
1852 # Assuming 0..100, 4 decimal digits is
1853 # enough for roughly 19 bits integer
1854 # device values
1855 parts = strval.split(b".")
1856 if len(parts) == 2 and len(parts[-1]) > 4:
1857 value = round(value, 4)
1858 strval = bytes(str(abs(value)), "UTF-8")
1859 parts = strval.split(b"e")
1860 lencheck = len(parts[0])
1861 if len(parts) > 1:
1862 lencheck += abs(int(parts[1]))
1863 self.vmaxlen = max(self.vmaxlen, lencheck)
1864 return value
1865
1866 def export_3d(
1867 self,
1868 filename: str,
1869 colorspace: str = "RGB",
1870 rgb_black_offset: float = 40,
1871 normalize_rgb_white: bool = False,
1872 compress: bool = True,
1873 file_format: str = "VRML",
1874 ) -> None:
1875 """Export 3D data to a file in the specified colorspace.
1876
1877 Args:
1878 filename (str): The name of the file to export to.
1879 colorspace (str): The colorspace to use for the export.
1880 Supported values are: "DIN99", "DIN99b", "DIN99c", "DIN99d",
1881 "LCH(ab)", "LCH(uv)", "Lab", "Luv", "Lu'v'", "RGB", "xyY",
1882 "HSI", "HSL", "HSV", "ICtCp", "IPT", and "Lpt".
1883 rgb_black_offset (float): The offset for black in RGB space.
1884 normalize_rgb_white (bool): Whether to normalize RGB white.
1885 compress (bool): Whether to compress the output file.
1886 file_format (str): The format of the output file, e.g., 'VRML'.
1887
1888 Raises:
1889 ValueError: If the specified colorspace is not supported.
1890 """
1891 if colorspace not in ColorSpaceToVRML.VALID_COLOR_SPACE_NAMES:
1892 raise ValueError(f"export_3d: Unknown colorspace {colorspace!r}")
1893
1894 if self.queryv1("ACCURATE_EXPECTED_VALUES") == "true":
1895 cat = "Bradford"
1896 else:
1897 cat = "XYZ scaling"
1898 data = self.queryv1("DATA")
1899
1900 white = data.queryi1({"RGB_R": 100, "RGB_G": 100, "RGB_B": 100})
1901 white = white["XYZ_X"], white["XYZ_Y"], white["XYZ_Z"] if white else "D50"
1902 white = colormath.get_whitepoint(white)
1903
1904 colorspace_to_vrml: ColorSpaceToVRML = COLORSPACE_NAME_TO_VRML_MAP[colorspace](
1905 data=data,
1906 white_point=white,
1907 cat=cat,
1908 rgb_black_offset=rgb_black_offset,
1909 normalize_rgb_white=normalize_rgb_white,
1910 )
1911 colorspace_to_vrml.generate_vrml()
1912 colorspace_to_vrml.write_vrml(
1913 file_format=file_format,
1914 filename=filename,
1915 compress=compress,
1916 )
1917
1918 @property
1919 def NUMBER_OF_FIELDS(self) -> int: # noqa: N802
1920 """Get number of fields.
1921
1922 Returns:
1923 int: Number of fields in the CGATS object.
1924 """
1925 if "DATA_FORMAT" in self:
1926 return len(self["DATA_FORMAT"])
1927 return 0
1928
1929 @property
1930 def NUMBER_OF_SETS(self) -> int: # noqa: N802
1931 """Get number of sets.
1932
1933 Returns:
1934 int: Number of sets in the CGATS object.
1935 """
1936 if "DATA" in self:
1937 return len(self["DATA"])
1938 return 0
1939
1940 def query( # noqa: C901
1941 self,
1942 query: str | dict | list | tuple,
1943 query_value: None | Any = None, # noqa: ANN401
1944 get_value: bool = False,
1945 get_first: bool = False,
1946 ) -> int | float | bytes | CGATS:
1947 """Return CGATS object of items or values where query matches.
1948
1949 Query can be a dict with key / value pairs, a tuple or a string.
1950 Return empty CGATS object if no matching items found.
1951
1952 Args:
1953 query (str | dict | list | tuple): The query to match against.
1954 query_value (Any, optional): The value to match against the query.
1955 get_value (bool): If True, return values instead of items.
1956 get_first (bool): If True, return only the first matching item or
1957 value.
1958
1959 Returns:
1960 int | float | bytes | CGATS: Matching items or values.
1961 """
1962 # TODO: Simplify this method.
1963 modified = self.modified
1964 result = CGATS() if not get_first else None
1965 if not isinstance(query, (dict, list, tuple)):
1966 query = (query,)
1967
1968 items = [self] + [self[key] for key in self]
1969 for item in items:
1970 if not isinstance(item, (dict, list, tuple)):
1971 continue
1972 if not get_first:
1973 n = len(result)
1974 result_n = CGATS() if get_value else None
1975 match_count = 0
1976 for query_key in query:
1977 if query_key in item or (
1978 isinstance(item, CGATS)
1979 and (
1980 (query_key == "NUMBER_OF_FIELDS" and "DATA_FORMAT" in item)
1981 or (query_key == "NUMBER_OF_SETS" and "DATA" in item)
1982 )
1983 ):
1984 current_query_value = (
1985 query[query_key]
1986 if query_value is None and isinstance(query, dict)
1987 else query_value
1988 )
1989 if (
1990 current_query_value is not None
1991 and item[query_key] != current_query_value
1992 ):
1993 break
1994 if get_value:
1995 result_n[len(result_n)] = item[query_key]
1996 match_count += 1
1997 else:
1998 break
1999
2000 if match_count == len(query):
2001 if not get_value:
2002 result_n = item
2003 if result_n is not None:
2004 if get_first:
2005 result = (
2006 result_n[0]
2007 if (
2008 get_value
2009 and isinstance(result_n, dict)
2010 and len(result_n) == 1
2011 )
2012 else result_n
2013 )
2014 break
2015 if len(result_n):
2016 result[n] = (
2017 result_n[0]
2018 if (
2019 get_value
2020 and isinstance(result_n, dict)
2021 and len(result_n) == 1
2022 )
2023 else result_n
2024 )
2025
2026 if isinstance(item, CGATS) and item != self:
2027 result_n = item.query(query, query_value, get_value, get_first)
2028 if result_n is not None:
2029 if get_first:
2030 result = result_n
2031 break
2032 if len(result_n):
2033 for i in result_n:
2034 n = len(result)
2035 if result_n[i] not in list(result.values()):
2036 result[n] = result_n[i]
2037
2038 if isinstance(result, CGATS):
2039 result.setmodified(modified)
2040 return result
2041
2042 def queryi(
2043 self,
2044 query: str | dict | list | tuple,
2045 query_value: None | Any = None, # noqa: ANN401
2046 ) -> int | float | bytes | CGATS:
2047 """Query and return matching items. See also query method.
2048
2049 Args:
2050 query (str | dict | list | tuple): The query to match against.
2051 query_value (Any, optional): The value to match against the query.
2052
2053 Returns:
2054 int | float | bytes | CGATS: The matching items or CGATS object.
2055 """
2056 return self.query(query, query_value, get_value=False, get_first=False)
2057
2058 def queryi1(
2059 self,
2060 query: str | dict | list | tuple,
2061 query_value: None | Any = None, # noqa: ANN401
2062 ) -> int | float | bytes | CGATS:
2063 """Query and return first matching item. See also query method.
2064
2065 Args:
2066 query (str | dict | list | tuple): The query to match against.
2067 query_value (Any, optional): The value to match against the query.
2068
2069 Returns:
2070 int | float | bytes | CGATS: The first matching item or CGATS object.
2071 """
2072 return self.query(query, query_value, get_value=False, get_first=True)
2073
2074 def queryv(
2075 self,
2076 query: str | dict | list | tuple,
2077 query_value: None | Any = None, # noqa: ANN401
2078 ) -> int | float | bytes | CGATS:
2079 """Query and return matching values. See also query method.
2080
2081 Args:
2082 query (str | dict | list | tuple): The query to match against.
2083 query_value (Any, optional): The value to match against the query.
2084
2085 Returns:
2086 int | float | bytes | CGATS: The matching values or CGATS object.
2087 """
2088 return self.query(query, query_value, get_value=True, get_first=False)
2089
2090 def queryv1(
2091 self,
2092 query: str | dict | list | tuple,
2093 query_value: None | Any = None, # noqa: ANN401
2094 ) -> int | float | bytes | CGATS:
2095 """Query and return first matching value. See also query method.
2096
2097 Args:
2098 query (str | dict | list | tuple): The query to match against.
2099 query_value (Any, optional): The value to match against the query.
2100
2101 Returns:
2102 int | float | bytes | CGATS: The first matching value or CGATS object.
2103 """
2104 return self.query(query, query_value, get_value=True, get_first=True)
2105
2106 def remove(self, item: int | str | CGATS) -> Any: # noqa: ANN401
2107 """Remove an item from the internal CGATS structure."""
2108 key = item.key if isinstance(item, CGATS) else item
2109 maxindex = len(self) - 1
2110 result = self[key]
2111 if isinstance(key, int) and key != maxindex:
2112 self.moveby1(key + 1, -1)
2113 name = len(self) - 1
2114 dict.pop(self, name)
2115 self.setmodified()
2116 return result
2117
2118 def convert_xyz_to_lab(self) -> None:
2119 """Convert XYZ to D50 L*a*b* and add it as additional fields.
2120
2121 Raises:
2122 NotImplementedError: If the color representation is not supported.
2123 CGATSError: If no data or white patch is found.
2124 """
2125 color_rep = (self.queryv1("COLOR_REP") or b"").split(b"_")
2126
2127 if color_rep[1] == b"LAB":
2128 # Nothing to do
2129 return
2130
2131 if (
2132 len(color_rep) != 2
2133 or color_rep[0] not in (b"RGB", b"CMYK")
2134 or color_rep[1] != b"XYZ"
2135 ):
2136 raise NotImplementedError(
2137 "Got unsupported color representation {}".format(
2138 b"_".join(color_rep).decode("utf-8")
2139 )
2140 )
2141
2142 data = self.queryv1("DATA")
2143 if not data:
2144 raise CGATSError("No data")
2145
2146 white = self._get_white_patch(color_rep, data)
2147 if not white:
2148 raise CGATSError("Missing white patch")
2149
2150 device_labels = []
2151 for i in range(len(color_rep[0])):
2152 channel = color_rep[0][i : i + 1]
2153 device_labels.append(color_rep[0] + b"_" + channel)
2154
2155 # Always XYZ
2156 cie_labels = []
2157 for i in range(len(color_rep[1])):
2158 channel = color_rep[1][i : i + 1]
2159 cie_labels.append(color_rep[1] + b"_" + channel)
2160
2161 # Add entries to DATA_FORMAT
2162 lab_data_format = (b"LAB_L", b"LAB_A", b"LAB_B")
2163 for label in lab_data_format:
2164 if label not in list(data.parent.DATA_FORMAT.values()):
2165 data.parent.DATA_FORMAT.add_data((label,))
2166
2167 # Add L*a*b* to each sample
2168 for _key in data:
2169 sample = data[_key]
2170 cie_values = [sample[label.decode("utf-8")] for label in cie_labels]
2171 lab = colormath.XYZ2Lab(*cie_values)
2172 for i, label in enumerate(lab_data_format):
2173 sample[label] = lab[i]
2174
2175 def _get_white_patch(self, color_rep: tuple, data: CGATS) -> None | bytes:
2176 """Get the white patch based on the color representation.
2177
2178 Args:
2179 color_rep (tuple): The color representation of the sample.
2180 data (CGATS): The CGATS data object containing samples.
2181
2182 Returns:
2183 None | bytes: The white patch values for the color representation,
2184 or None if not found.
2185 """
2186 white = None
2187 if color_rep[0] == b"RGB":
2188 white = data.queryv1({"RGB_R": 100, "RGB_G": 100, "RGB_B": 100})
2189 elif color_rep[0] == b"CMYK":
2190 white = data.queryv1({"CMYK_C": 0, "CMYK_M": 0, "CMYK_Y": 0, "CMYK_K": 0})
2191 return white
2192
2193 def fix_zero_measurements(
2194 self, warn_only: bool = False, logfile: Callable = safe_print
2195 ) -> None:
2196 """Fix (or warn about) <= zero measurements.
2197
2198 If XYZ/Lab = 0, the sample gets removed. If only one component of
2199 XYZ/Lab is <= 0, it gets fudged so that the component is nonzero
2200 (because otherwise, Argyll's colprof will remove it, which can have bad
2201 effects if it's an 'essential' sample)
2202
2203 Args:
2204 warn_only (bool): If True, only warn about the issue, do not fix it.
2205 logfile (callable): A function to log messages to, defaults to
2206 safe_print.
2207 """
2208 color_rep = (self.queryv1("COLOR_REP") or b"").split(b"_")
2209 data = self.queryv1("DATA")
2210 if len(color_rep) != 2 or not data:
2211 return
2212
2213 # Check for XYZ/Lab = 0 readings
2214 cie_labels = self._get_cie_labels(color_rep)
2215 device_labels = self._generate_device_labels(color_rep)
2216 remove = []
2217 for _key in data:
2218 sample = data[_key]
2219 cie_values = [sample[label.decode("utf-8")] for label in cie_labels]
2220 # Check if zero
2221 device_label_values = sample.queryv1(device_labels)
2222 if [v for v in cie_values if v]:
2223 # Not all zero. Check if some component(s) equal or below zero
2224 if min(cie_values) <= 0:
2225 for label in cie_labels:
2226 if sample[label.decode("utf-8")] > 0:
2227 continue
2228 if warn_only:
2229 self._warn_sample_below_threshold(
2230 logfile, color_rep, sample, device_label_values, label
2231 )
2232 else:
2233 # Fudge to be nonzero
2234 sample[label.decode("utf-8")] = 0.000001
2235 self._log_fudged_sample(
2236 logfile, color_rep, sample, device_label_values, label
2237 )
2238 continue
2239 # All zero
2240 device_values = [sample[label.decode("utf-8")] for label in device_labels]
2241 if not max(device_values):
2242 # Skip device black
2243 continue
2244 if warn_only:
2245 self._warn_zero_measurement(
2246 logfile, color_rep, sample, device_label_values
2247 )
2248 else:
2249 # Queue sample for removal
2250 remove.insert(0, sample)
2251 self._log_sample_removal(
2252 logfile, color_rep, sample, device_label_values
2253 )
2254 for sample in remove:
2255 # Remove sample
2256 data.pop(sample)
2257
2258 def _get_cie_labels(self, color_rep: tuple) -> list:
2259 """Generate CIE labels based on the color representation.
2260
2261 Args:
2262 color_rep (tuple): The color representation of the sample.
2263
2264 Returns:
2265 list: A list of CIE labels for the color representation.
2266 """
2267 cie_labels = []
2268 for i in range(len(color_rep[1])):
2269 channel = color_rep[1][i : i + 1]
2270 cie_labels.append(color_rep[1] + b"_" + channel)
2271 if color_rep[1] == b"LAB":
2272 # Only check L* for zero values
2273 break
2274 return cie_labels
2275
2276 def _generate_device_labels(self, color_rep: tuple) -> list:
2277 """Generate device labels based on the color representation.
2278
2279 Args:
2280 color_rep (tuple): The color representation of the sample.
2281
2282 Returns:
2283 list: A list of device labels for the color representation.
2284 """
2285 device_labels = []
2286 for i in range(len(color_rep[0])):
2287 channel = color_rep[0][i : i + 1]
2288 device_labels.append(color_rep[0] + b"_" + channel)
2289 return device_labels
2290
2291 def _warn_sample_below_threshold(
2292 self,
2293 logfile: Callable,
2294 color_rep: tuple,
2295 sample: CGATS,
2296 device_label_values: bytes,
2297 label: bytes,
2298 ) -> None:
2299 """Log a warning for a sample with a measurement below or equal to zero.
2300
2301 Args:
2302 logfile (callable): A function to log messages to, if None is given
2303 this function does nothing.
2304 color_rep (tuple): The color representation of the sample.
2305 sample (CGATS): The sample that is being removed.
2306 device_label_values (bytes): The device label values of the sample.
2307 label (bytes): The label of the measurement that is below or equal
2308 to zero.
2309 """
2310 if not logfile:
2311 return
2312 logfile.write(
2313 "Warning: Sample ID {:d} ({} {}) has {} <= 0!\n".format(
2314 int(sample.SAMPLE_ID),
2315 color_rep[0],
2316 " ".join(
2317 device_label_values.decode("utf-8").split()
2318 if device_label_values
2319 else [""]
2320 ),
2321 label.decode("utf-8"),
2322 )
2323 )
2324
2325 def _log_fudged_sample(
2326 self,
2327 logfile: Callable,
2328 color_rep: tuple,
2329 sample: CGATS,
2330 device_label_values: bytes,
2331 label: bytes,
2332 ) -> None:
2333 """Log a message for a sample that was fudged to be non-zero.
2334
2335 Args:
2336 logfile (callable): A function to log messages to, if None is given
2337 this function does nothing.
2338 color_rep (tuple): The color representation of the sample.
2339 sample (CGATS): The sample that is being removed.
2340 device_label_values (bytes): The device label values of the sample.
2341 label (bytes): The label of the measurement that was fudged to be
2342 non-zero.
2343 """
2344 if not logfile:
2345 return
2346 logfile.write(
2347 "Fudged sample ID {:d} ({} {}) {} to be non-zero\n".format(
2348 int(sample.SAMPLE_ID),
2349 color_rep[0],
2350 " ".join(
2351 device_label_values.decode("utf-8").split()
2352 if device_label_values
2353 else [""]
2354 ),
2355 label.decode("utf-8"),
2356 )
2357 )
2358
2359 def _warn_zero_measurement(
2360 self,
2361 logfile: Callable,
2362 color_rep: tuple,
2363 sample: CGATS,
2364 device_label_values: bytes,
2365 ) -> None:
2366 """Log a warning for a sample with zero measurements.
2367
2368 Args:
2369 logfile (callable): A function to log messages to, if None is given
2370 this function does nothing.
2371 color_rep (tuple): The color representation of the sample.
2372 sample (CGATS): The sample that is being removed.
2373 device_label_values (bytes): The device label values of the sample.
2374 """
2375 if not logfile:
2376 return
2377
2378 logfile.write(
2379 "Warning: Sample ID {} ({} {}) has {} = 0!\n".format(
2380 sample.SAMPLE_ID,
2381 color_rep[0],
2382 " ".join(
2383 device_label_values.decode("utf-8").split()
2384 if device_label_values
2385 else [""]
2386 ),
2387 color_rep[1],
2388 )
2389 )
2390
2391 def _log_sample_removal(
2392 self,
2393 logfile: Callable,
2394 color_rep: tuple,
2395 sample: CGATS,
2396 device_label_values: bytes,
2397 ) -> None:
2398 """Log the removal of a sample with zero measurements.
2399
2400 Args:
2401 logfile (callable): A function to log messages to, if None is given
2402 this function does nothing.
2403 color_rep (tuple): The color representation of the sample.
2404 sample (CGATS): The sample that is being removed.
2405 device_label_values (bytes): The device label values of the sample.
2406 """
2407 if not logfile:
2408 return
2409 logfile.write(
2410 "Removed sample ID {:d} ({} {}) with {} = 0\n".format(
2411 int(sample.SAMPLE_ID),
2412 color_rep[0],
2413 " ".join(
2414 device_label_values.decode("utf-8").split()
2415 if device_label_values
2416 else [""]
2417 ),
2418 color_rep[1],
2419 )
2420 )
2421
2422 def fix_device_values_scaling(self, color_rep: None | str = None) -> int:
2423 """Attempt to fix device value scaling so that max = 100.
2424
2425 Args:
2426 color_rep (Nont | str): The color representation to fix. If None,
2427 all device values are fixed. Defaults to None.
2428
2429 Returns:
2430 int: The number of fixed DATA sections.
2431 """
2432 fixed = 0
2433 for labels in get_device_value_labels(color_rep):
2434 for dataset in self.query(b"DATA").values():
2435 for item in dataset.queryi(labels).values():
2436 for label in labels:
2437 if item[label] > 100:
2438 dataset.scale_device_values(color_rep=color_rep)
2439 fixed += 1
2440 break
2441 return fixed
2442
2443 def normalize_to_y_100(self) -> bool:
2444 """Scale XYZ values so that RGB 100 = Y 100.
2445
2446 Returns:
2447 bool: True if normalization was applied, False otherwise.
2448 """
2449 if "DATA" in self:
2450 white_cie = self.get_white_cie()
2451 if white_cie and "XYZ_Y" in white_cie:
2452 white_y = white_cie["XYZ_Y"]
2453 if white_y != 100:
2454 self.add_keyword(
2455 "LUMINANCE_XYZ_CDM2",
2456 "{:.4f} {:.4f} {:.4f}".format(
2457 white_cie["XYZ_X"], white_cie["XYZ_Y"], white_cie["XYZ_Z"]
2458 ),
2459 )
2460 for sample in self.DATA.values():
2461 for label in "XYZ":
2462 v = sample["XYZ_" + label]
2463 sample["XYZ_" + label] = v / white_y * 100
2464 self.add_keyword("NORMALIZED_TO_Y_100", "YES")
2465 return True
2466 return False
2467
2468 def quantize_device_values(
2469 self, bits: int = 8, quantizer: Callable = round
2470 ) -> None:
2471 """Quantize device values to n bits.
2472
2473 Args:
2474 bits (int): The number of bits to quantize to. Defaults to 8.
2475 quantizer (callable): A function to use for quantization. Defaults
2476 to round, which is suitable for most cases.
2477 """
2478 q = 2**bits - 1.0
2479 for data in self.queryv("DATA").values():
2480 if data.parent.type == b"CAL":
2481 maxv = 1.0
2482 digits = 8
2483 else:
2484 maxv = 100.0
2485 # Assuming 0..100, 4 decimal digits is
2486 # enough for roughly 19 bits integer
2487 # device values
2488 digits = 4
2489 color_rep = (data.parent.queryv1("COLOR_REP") or b"").split(b"_")[0]
2490 for labels in get_device_value_labels(color_rep):
2491 for item in data.queryi(labels).values():
2492 for label in labels:
2493 item[label] = round(
2494 quantizer(item[label] / maxv * q) / q * maxv, digits
2495 )
2496
2497 def scale_device_values(
2498 self, factor: float = 100.0 / 255, color_rep: None | str = None
2499 ) -> None:
2500 """Scale device values by multiplying with factor.
2501
2502 Args:
2503 factor (float): The factor to scale the device values by. Defaults
2504 to 100.0 / 255, which is the scaling from 8-bit to 100% device
2505 values.
2506 color_rep (None | str): The color representation to scale. If None, all
2507 device values are scaled. Defaults to None.
2508 """
2509 for labels in get_device_value_labels(color_rep):
2510 for data in self.queryv("DATA").values():
2511 for item in data.queryi(labels).values():
2512 for label in labels:
2513 item[label] *= factor
2514
2515 def adapt(
2516 self,
2517 whitepoint_source: None | str = None,
2518 whitepoint_destination: None | str = None,
2519 cat: str = "Bradford",
2520 ) -> int:
2521 """Perform chromatic adaptation if possible (needs XYZ or LAB).
2522
2523 Args:
2524 whitepoint_source (None | str): The source whitepoint to adapt
2525 from. Defaults to None, which uses the whitepoint of the first
2526 DATA section.
2527 whitepoint_destination (None | str): The destination whitepoint to
2528 adapt to. Defaults to "D50".
2529 cat (str): The chromatic adaptation transform to use. Defaults to
2530 "Bradford".
2531
2532 Returns:
2533 int: The number of affected DATA sections.
2534 """
2535 sections = 0
2536 for dataset in self.query("DATA").values():
2537 if not dataset.get_cie_data_format():
2538 continue
2539 if not whitepoint_source:
2540 whitepoint_source = dataset.get_white_cie("XYZ")
2541 if not whitepoint_source:
2542 continue
2543 sections += 1
2544 for item in dataset.queryv1("DATA").values():
2545 if "XYZ_X" in item:
2546 x, y, z = item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"]
2547 else:
2548 x, y, z = colormath.Lab2XYZ(
2549 item["LAB_L"], item["LAB_A"], item["LAB_B"], scale=100
2550 )
2551 x, y, z = colormath.adapt(
2552 x, y, z, whitepoint_source, whitepoint_destination, cat
2553 )
2554 if "LAB_L" in item:
2555 (
2556 item["LAB_L"],
2557 item["LAB_A"],
2558 item["LAB_B"],
2559 ) = colormath.XYZ2Lab(x, y, z)
2560 if "XYZ_X" in item:
2561 item["XYZ_X"], item["XYZ_Y"], item["XYZ_Z"] = x, y, z
2562 return sections
2563
2564 def apply_bpc(
2565 self, bp_out: tuple[float, float, float] = (0, 0, 0), weight: bool = False
2566 ) -> int:
2567 """Apply black point compensation.
2568
2569 Scales XYZ so that black (RGB 0) = zero.
2570 Needs a CGATS structure with RGB and XYZ data and atleast one black and
2571 white patch.
2572
2573 Args:
2574 bp_out (tuple[float, float, float]): The output black point to use.
2575 Defaults to (0, 0, 0).
2576 weight (bool): If True, use the weight method for BPC, otherwise
2577 use the blend method. Defaults to False.
2578
2579 Returns:
2580 int: The number of DATA sections that were affected by the BPC.
2581 """
2582 n = 0
2583 for dataset in self.query("DATA").values():
2584 is_lab, labels, data, max_v, black, white = (
2585 self._extract_white_black_from_data(dataset)
2586 )
2587 if black is None or white is None:
2588 # Can't apply bpc
2589 continue
2590
2591 # Apply black point compensation
2592 n += 1
2593 for i in data:
2594 values = list(data[i].queryv1(labels).values())
2595 if is_lab:
2596 values = colormath.Lab2XYZ(*values)
2597 else:
2598 values = [v / max_v for v in values]
2599 if weight:
2600 values = colormath.apply_bpc(
2601 values[0], values[1], values[2], black, bp_out, white, weight
2602 )
2603 else:
2604 values = colormath.blend_blackpoint(
2605 values[0], values[1], values[2], black, bp_out, white
2606 )
2607 values = [v * max_v for v in values]
2608 if is_lab:
2609 values = colormath.XYZ2Lab(*values)
2610 for j, label in enumerate(labels):
2611 if is_lab and j > 0:
2612 data[i][label] = values[j]
2613 else:
2614 data[i][label] = max(0.0, values[j])
2615 return n
2616
2617 def _extract_white_black_from_data(
2618 self, dataset: CGATS
2619 ) -> tuple[bool, tuple, CGATS, float, list, list]:
2620 """Extract white and black points from the dataset.
2621
2622 Args:
2623 dataset (CGATS): The dataset to extract white and black points from.
2624
2625 Returns:
2626 tuple[bool, tuple, CGATS, float, list, list]: A tuple containing:
2627 - is_lab (bool): True if the dataset is in Lab color space.
2628 - labels (tuple): The labels for the color channels.
2629 - data (CGATS): The data object containing the color values.
2630 - max_v (float): The maximum value for scaling.
2631 - black (list): The black point values.
2632 - white (list): The white point values.
2633 """
2634 if dataset.type.strip() == b"CAL":
2635 is_lab = False
2636 labels = ("RGB_R", "RGB_G", "RGB_B")
2637 data = dataset.queryi(labels)
2638
2639 # Get black
2640 black1 = data.queryi1({"RGB_I": 0})
2641 # Get white
2642 white1 = data.queryi1({"RGB_I": 1})
2643 if not black1 or not white1:
2644 # Can't apply bpc
2645 return is_lab, labels, data, None, None, None
2646
2647 black = []
2648 white = []
2649 for label in labels:
2650 black.append(black1[label])
2651 white.append(white1[label])
2652 max_v = 1.0
2653 else:
2654 is_lab = b"_LAB" in (dataset.queryv1("COLOR_REP") or b"")
2655 labels = (
2656 ("LAB_L", "LAB_A", "LAB_B") if is_lab else ("XYZ_X", "XYZ_Y", "XYZ_Z")
2657 )
2658 # 0: Index of L* in labels
2659 # 1: Index of Y in labels
2660 index = 0 if is_lab else 1
2661 data = dataset.queryi(("RGB_R", "RGB_G", "RGB_B", *labels))
2662
2663 # Get blacks
2664 blacks = data.queryi({"RGB_R": 0, "RGB_G": 0, "RGB_B": 0})
2665 # Get whites
2666 whites = data.queryi({"RGB_R": 100, "RGB_G": 100, "RGB_B": 100})
2667 if not blacks or not whites:
2668 # Can't apply bpc
2669 return is_lab, labels, data, max_v, None, None
2670
2671 black = [0, 0, 0]
2672 white = [0, 0, 0]
2673
2674 for i in blacks:
2675 if blacks[i][labels[index]] > black[index]:
2676 for j, label in enumerate(labels):
2677 black[j] = blacks[i][label]
2678
2679 for i in whites:
2680 if whites[i][labels[index]] > white[index]:
2681 for j, label in enumerate(labels):
2682 white[j] = whites[i][label]
2683 if is_lab:
2684 max_v = 100.0
2685 black = colormath.Lab2XYZ(*black)
2686 white = colormath.Lab2XYZ(*white)
2687 else:
2688 max_v = white[1]
2689 black = [v / max_v for v in black]
2690 white = [v / max_v for v in white]
2691
2692 return is_lab, labels, data, max_v, black, white
2693
2694 def get_white_cie(
2695 self, colorspace: None | str = None
2696 ) -> None | tuple[float, float, float] | dict:
2697 """Get the 'white' from the CIE values (if any).
2698
2699 Args:
2700 colorspace (str, optional): The colorspace to return the white
2701 point in. If None, returns a dict with XYZ or Lab values.
2702
2703 Returns:
2704 None | tuple[float, float, float] | dict: The white point in the
2705 specified colorspace or a dict with XYZ or Lab values.
2706 """
2707 if not (data_format := self.get_cie_data_format()):
2708 return None
2709
2710 if "RGB_R" in list(data_format.values()):
2711 white = {"RGB_R": 100, "RGB_G": 100, "RGB_B": 100}
2712 elif "CMYK_C" in list(data_format.values()):
2713 white = {"CMYK_C": 0, "CMYK_M": 0, "CMYK_Y": 0, "CMYK_K": 0}
2714 else:
2715 white = None
2716
2717 if white:
2718 white = self.queryi1(white)
2719 if not white:
2720 white = self._get_white_cie_from_luminance_or_approx_white_point()
2721 if not white:
2722 return None
2723 return self._get_white_cie_from_xyz_or_lab(white, colorspace=colorspace)
2724
2725 def _get_white_cie_from_luminance_or_approx_white_point(self) -> None | dict:
2726 """Get the white point from LUMINANCE_XYZ_CDM2 or APPROX_WHITE_POINT.
2727
2728 Returns:
2729 None | dict: None if no white point is found, otherwise a dict
2730 with keys "XYZ_X", "XYZ_Y", and "XYZ_Z" representing the white
2731 point in CIE XYZ format.
2732 """
2733 for key in ("LUMINANCE_XYZ_CDM2", "APPROX_WHITE_POINT"):
2734 if not (white := self.queryv1(key)):
2735 continue
2736 try:
2737 white = [float(v) for v in white.split()]
2738 except ValueError:
2739 white = None
2740 else:
2741 if len(white) == 3:
2742 white = [v / white[1] * 100 for v in white]
2743 white = {
2744 "XYZ_X": white[0],
2745 "XYZ_Y": white[1],
2746 "XYZ_Z": white[2],
2747 }
2748 break
2749 white = None
2750 return white
2751
2752 def _get_white_cie_from_xyz_or_lab(
2753 self, white: dict, colorspace: None | str = None
2754 ) -> None | tuple[float, float, float] | dict:
2755 """Get the white point in the specified colorspace.
2756
2757 Args:
2758 white (dict): The white point in XYZ or Lab format.
2759 colorspace (str, optional): The colorspace to return the white
2760 point in. If None, this function will return the white point as
2761 it is.
2762
2763 Returns:
2764 None | tuple[float, float, float] | dict: The white point in the
2765 specified colorspace or a dict with XYZ or Lab values if the
2766 given colorspace is not "Lab" or "XYZ" or None if the white
2767 point is not given.
2768 """
2769 if white and (
2770 ("XYZ_X" in white and "XYZ_Y" in white and "XYZ_Z" in white)
2771 or ("LAB_L" in white and "LAB_B" in white and "LAB_B" in white)
2772 ):
2773 if colorspace == "XYZ":
2774 if "XYZ_X" in white:
2775 return white["XYZ_X"], white["XYZ_Y"], white["XYZ_Z"]
2776 return colormath.Lab2XYZ(
2777 white["LAB_L"], white["LAB_A"], white["LAB_B"], scale=100
2778 )
2779 if colorspace == "Lab":
2780 if "LAB_L" in white:
2781 return white["LAB_L"], white["LAB_A"], white["LAB_B"]
2782 return colormath.XYZ2Lab(white["XYZ_X"], white["XYZ_Y"], white["XYZ_Z"])
2783 return white
2784 return None
2785
2786 def get_cie_data_format(self) -> None | bytes:
2787 """Check if DATA_FORMAT defines any CIE XYZ or LAB columns.
2788
2789 Returns:
2790 None | bytes: The DATA_FORMAT on success or None on failure.
2791 """
2792 if data_format := self.queryv1("DATA_FORMAT"):
2793 cie = {}
2794 for channel in (b"LAB_L", b"LAB_A", b"LAB_B"):
2795 cie[channel] = channel in list(data_format.values())
2796 if len(list(cie.values())) in [0, 3]:
2797 for channel in (b"XYZ_X", b"XYZ_Y", b"XYZ_Z"):
2798 cie[channel] = channel in list(data_format.values())
2799 if len([v for v in iter(cie.values()) if v is not False]) in {3, 6}:
2800 return data_format
2801 return None
2802
2803 pop = remove
2804
2805 def write(self, stream_or_filename: None | str | BinaryIO = None) -> None:
2806 """Write CGATS text to stream.
2807
2808 Args:
2809 stream_or_filename (str | BinaryIO, optional): The stream
2810 or filename to write the CGATS data to. If None, uses the
2811 filename of the CGATS object. Defaults to None.
2812 """
2813 if not stream_or_filename:
2814 stream_or_filename = self.filename
2815 if isinstance(stream_or_filename, str):
2816 with open(stream_or_filename, "wb") as stream:
2817 stream.write(bytes(self))
2818 else:
2819 stream = stream_or_filename
2820 # This seems like a duplicate, but reduces complexity of the code
2821 stream.write(bytes(self))