Improve case consistency.
[OpenColorIO-Configs.git] / aces_1.0.0 / python / aces_ocio / create_aces_colorspaces.py
1 #!/usr/bin/env python
2 # -*- coding: utf-8 -*-
3
4 """
5 Implements support for *ACES* colorspaces conversions and transfer functions.
6 """
7
8 import math
9 import numpy
10 import os
11 import pprint
12 import string
13 import shutil
14
15 import PyOpenColorIO as ocio
16
17 from aces_ocio.generate_lut import (
18     generate_1d_LUT_from_CTL,
19     generate_3d_LUT_from_CTL,
20     write_SPI_1d)
21 from aces_ocio.utilities import (
22     ColorSpace,
23     mat44_from_mat33,
24     sanitize,
25     compact)
26
27
28 __author__ = 'ACES Developers'
29 __copyright__ = 'Copyright (C) 2014 - 2015 - ACES Developers'
30 __license__ = ''
31 __maintainer__ = 'ACES Developers'
32 __email__ = 'aces@oscars.org'
33 __status__ = 'Production'
34
35 __all__ = ['ACES_AP1_TO_AP0',
36            'ACES_AP0_TO_XYZ',
37            'create_ACES',
38            'create_ACEScc',
39            'create_ACESproxy',
40            'create_ACEScg',
41            'create_ADX',
42            'create_ACES_LMT',
43            'create_ACES_RRT_plus_ODT',
44            'create_generic_log',
45            'create_LMTs',
46            'create_ODTs',
47            'get_transform_info',
48            'get_ODTs_info',
49            'get_LMTs_info',
50            'create_colorspaces']
51
52 # Matrix converting *ACES AP1* primaries to *AP0*.
53 ACES_AP1_TO_AP0 = [0.6954522414, 0.1406786965, 0.1638690622,
54                    0.0447945634, 0.8596711185, 0.0955343182,
55                    -0.0055258826, 0.0040252103, 1.0015006723]
56
57 # Matrix converting *ACES AP0* primaries to *XYZ*.
58 ACES_AP0_TO_XYZ = [0.9525523959, 0.0000000000, 0.0000936786,
59                    0.3439664498, 0.7281660966, -0.0721325464,
60                    0.0000000000, 0.0000000000, 1.0088251844]
61
62
63 def create_ACES():
64     """
65     Object description.
66
67     Parameters
68     ----------
69     parameter : type
70         Parameter description.
71
72     Returns
73     -------
74     type
75          Return value description.
76     """
77
78     # Defining the reference colorspace.
79     aces2065_1 = ColorSpace('ACES2065-1')
80     aces2065_1.description = (
81         'The Academy Color Encoding System reference color space')
82     aces2065_1.equality_group = ''
83     aces2065_1.aliases = ["lin_ap0", "aces"]
84     aces2065_1.family = 'ACES'
85     aces2065_1.is_data = False
86     aces2065_1.allocation_type = ocio.Constants.ALLOCATION_LG2
87     aces2065_1.allocation_vars = [-15, 6]
88
89     return aces2065_1
90
91
92 def create_ACEScc(aces_ctl_directory,
93                   lut_directory,
94                   lut_resolution_1d,
95                   cleanup,
96                   name='ACEScc',
97                   min_value=0.0,
98                   max_value=1.0,
99                   input_scale=1.0):
100     """
101     Creates the *ACEScc* colorspace.
102
103     Parameters
104     ----------
105     parameter : type
106         Parameter description.
107
108     Returns
109     -------
110     Colorspace
111          *ACEScc* colorspace.
112     """
113
114     cs = ColorSpace(name)
115     cs.description = 'The %s color space' % name
116     cs.aliases = ["acescc_ap1"]
117     cs.equality_group = ''
118     cs.family = 'ACES'
119     cs.is_data = False
120
121     ctls = [os.path.join(aces_ctl_directory,
122                          'ACEScc',
123                          'ACEScsc.ACEScc_to_ACES.a1.0.0.ctl'),
124             # This transform gets back to the *AP1* primaries.
125             # Useful as the 1d LUT is only covering the transfer function.
126             # The primaries switch is covered by the matrix below:
127             os.path.join(aces_ctl_directory,
128                          'ACEScg',
129                          'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
130     lut = '%s_to_ACES.spi1d' % name
131
132     lut = sanitize(lut)
133
134     generate_1d_LUT_from_CTL(
135         os.path.join(lut_directory, lut),
136         ctls,
137         lut_resolution_1d,
138         'float',
139         input_scale,
140         1.0,
141         {},
142         cleanup,
143         aces_ctl_directory,
144         min_value,
145         max_value)
146
147     cs.to_reference_transforms = []
148     cs.to_reference_transforms.append({
149         'type': 'lutFile',
150         'path': lut,
151         'interpolation': 'linear',
152         'direction': 'forward'})
153
154     # *AP1* primaries to *AP0* primaries.
155     cs.to_reference_transforms.append({
156         'type': 'matrix',
157         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
158         'direction': 'forward'})
159
160     cs.from_reference_transforms = []
161     return cs
162
163
164 def create_ACESproxy(aces_ctl_directory,
165                      lut_directory,
166                      lut_resolution_1d,
167                      cleanup,
168                      name='ACESproxy'):
169     """
170     Creates the *ACESproxy* colorspace.
171
172     Parameters
173     ----------
174     parameter : type
175         Parameter description.
176
177     Returns
178     -------
179     Colorspace
180          *ACESproxy* colorspace.
181     """
182
183     cs = ColorSpace(name)
184     cs.description = 'The %s color space' % name
185     cs.aliases = ["acesproxy_ap1"]
186     cs.equality_group = ''
187     cs.family = 'ACES'
188     cs.is_data = False
189
190     ctls = [os.path.join(aces_ctl_directory,
191                          'ACESproxy',
192                          'ACEScsc.ACESproxy10i_to_ACES.a1.0.0.ctl'),
193             # This transform gets back to the *AP1* primaries.
194             # Useful as the 1d LUT is only covering the transfer function.
195             # The primaries switch is covered by the matrix below:
196             os.path.join(aces_ctl_directory,
197                          'ACEScg',
198                          'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
199     lut = '%s_to_aces.spi1d' % name
200
201     lut = sanitize(lut)
202
203     generate_1d_LUT_from_CTL(
204         os.path.join(lut_directory, lut),
205         ctls,
206         lut_resolution_1d,
207         'uint16',
208         64.0,
209         1.0,
210         {},
211         cleanup,
212         aces_ctl_directory)
213
214     cs.to_reference_transforms = []
215     cs.to_reference_transforms.append({
216         'type': 'lutFile',
217         'path': lut,
218         'interpolation': 'linear',
219         'direction': 'forward'})
220
221     # *AP1* primaries to *AP0* primaries.
222     cs.to_reference_transforms.append({
223         'type': 'matrix',
224         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
225         'direction': 'forward'})
226
227     cs.from_reference_transforms = []
228     return cs
229
230
231 # -------------------------------------------------------------------------
232 # *ACEScg*
233 # -------------------------------------------------------------------------
234 def create_ACEScg(aces_ctl_directory,
235                   lut_directory,
236                   lut_resolution_1d,
237                   cleanup,
238                   name='ACEScg'):
239     """
240     Creates the *ACEScg* colorspace.
241
242     Parameters
243     ----------
244     parameter : type
245         Parameter description.
246
247     Returns
248     -------
249     Colorspace
250          *ACEScg* colorspace.
251     """
252
253     cs = ColorSpace(name)
254     cs.description = 'The %s color space' % name
255     cs.aliases = ["lin_ap1"]
256     cs.equality_group = ''
257     cs.family = 'ACES'
258     cs.is_data = False
259
260     cs.to_reference_transforms = []
261
262     # *AP1* primaries to *AP0* primaries.
263     cs.to_reference_transforms.append({
264         'type': 'matrix',
265         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
266         'direction': 'forward'})
267
268     cs.from_reference_transforms = []
269     return cs
270
271
272 # -------------------------------------------------------------------------
273 # *ADX*
274 # -------------------------------------------------------------------------
275 def create_ADX(lut_directory,
276                lut_resolution_1d,
277                bit_depth=10,
278                name='ADX'):
279     """
280     Creates the *ADX* colorspace.
281
282     Parameters
283     ----------
284     parameter : type
285         Parameter description.
286
287     Returns
288     -------
289     Colorspace
290          *ADX* colorspace.
291     """
292
293     name = '%s%s' % (name, bit_depth)
294     cs = ColorSpace(name)
295     cs.description = '%s color space - used for film scans' % name
296     cs.aliases = ["adx%s" % str(bit_depth)]
297     cs.equality_group = ''
298     cs.family = 'ADX'
299     cs.is_data = False
300
301     if bit_depth == 10:
302         cs.bit_depth = ocio.Constants.BIT_DEPTH_UINT10
303         ADX_to_CDD = [1023.0 / 500.0, 0.0, 0.0, 0.0,
304                       0.0, 1023.0 / 500.0, 0.0, 0.0,
305                       0.0, 0.0, 1023.0 / 500.0, 0.0,
306                       0.0, 0.0, 0.0, 1.0]
307         offset = [-95.0 / 500.0, -95.0 / 500.0, -95.0 / 500.0, 0.0]
308     elif bit_depth == 16:
309         cs.bit_depth = ocio.Constants.BIT_DEPTH_UINT16
310         ADX_to_CDD = [65535.0 / 8000.0, 0.0, 0.0, 0.0,
311                       0.0, 65535.0 / 8000.0, 0.0, 0.0,
312                       0.0, 0.0, 65535.0 / 8000.0, 0.0,
313                       0.0, 0.0, 0.0, 1.0]
314         offset = [-1520.0 / 8000.0, -1520.0 / 8000.0, -1520.0 / 8000.0, 0.0]
315
316     cs.to_reference_transforms = []
317
318     # Converting from *ADX* to *Channel-Dependent Density*.
319     cs.to_reference_transforms.append({
320         'type': 'matrix',
321         'matrix': ADX_to_CDD,
322         'offset': offset,
323         'direction': 'forward'})
324
325     # Convert from Channel-Dependent Density to Channel-Independent Density
326     cs.to_reference_transforms.append({
327         'type': 'matrix',
328         'matrix': [0.75573, 0.22197, 0.02230, 0,
329                    0.05901, 0.96928, -0.02829, 0,
330                    0.16134, 0.07406, 0.76460, 0,
331                    0.0, 0.0, 0.0, 1.0],
332         'direction': 'forward'})
333
334     # Copied from *Alex Fry*'s *adx_cid_to_rle.py*
335     def create_CID_to_RLE_LUT():
336
337         def interpolate_1D(x, xp, fp):
338             return numpy.interp(x, xp, fp)
339
340         LUT_1D_xp = [-0.190000000000000,
341                      0.010000000000000,
342                      0.028000000000000,
343                      0.054000000000000,
344                      0.095000000000000,
345                      0.145000000000000,
346                      0.220000000000000,
347                      0.300000000000000,
348                      0.400000000000000,
349                      0.500000000000000,
350                      0.600000000000000]
351
352         LUT_1D_fp = [-6.000000000000000,
353                      -2.721718645000000,
354                      -2.521718645000000,
355                      -2.321718645000000,
356                      -2.121718645000000,
357                      -1.921718645000000,
358                      -1.721718645000000,
359                      -1.521718645000000,
360                      -1.321718645000000,
361                      -1.121718645000000,
362                      -0.926545676714876]
363
364         REF_PT = ((7120.0 - 1520.0) / 8000.0 * (100.0 / 55.0) -
365                   math.log(0.18, 10.0))
366
367         def cid_to_rle(x):
368             if x <= 0.6:
369                 return interpolate_1D(x, LUT_1D_xp, LUT_1D_fp)
370             return (100.0 / 55.0) * x - REF_PT
371
372         def fit(value, from_min, from_max, to_min, to_max):
373             if from_min == from_max:
374                 raise ValueError('from_min == from_max')
375             return (value - from_min) / (from_max - from_min) * (
376                 to_max - to_min) + to_min
377
378         num_samples = 2 ** 12
379         domain = (-0.19, 3.0)
380         data = []
381         for i in xrange(num_samples):
382             x = i / (num_samples - 1.0)
383             x = fit(x, 0.0, 1.0, domain[0], domain[1])
384             data.append(cid_to_rle(x))
385
386         lut = 'ADX_CID_to_RLE.spi1d'
387         write_SPI_1d(os.path.join(lut_directory, lut),
388                      domain[0],
389                      domain[1],
390                      data,
391                      num_samples, 1)
392
393         return lut
394
395     # Converting *Channel Independent Density* values to
396     # *Relative Log Exposure* values.
397     lut = create_CID_to_RLE_LUT()
398     cs.to_reference_transforms.append({
399         'type': 'lutFile',
400         'path': lut,
401         'interpolation': 'linear',
402         'direction': 'forward'})
403
404     # Converting *Relative Log Exposure* values to
405     # *Relative Exposure* values.
406     cs.to_reference_transforms.append({
407         'type': 'log',
408         'base': 10,
409         'direction': 'inverse'})
410
411     # Convert *Relative Exposure* values to *ACES* values.
412     cs.to_reference_transforms.append({
413         'type': 'matrix',
414         'matrix': [0.72286, 0.12630, 0.15084, 0,
415                    0.11923, 0.76418, 0.11659, 0,
416                    0.01427, 0.08213, 0.90359, 0,
417                    0.0, 0.0, 0.0, 1.0],
418         'direction': 'forward'})
419
420     cs.from_reference_transforms = []
421     return cs
422
423
424 def create_ACES_LMT(lmt_name,
425                     lmt_values,
426                     shaper_info,
427                     aces_ctl_directory,
428                     lut_directory,
429                     lut_resolution_1d=1024,
430                     lut_resolution_3d=64,
431                     cleanup=True,
432                     aliases=[]):
433     """
434     Creates the *ACES LMT* colorspace.
435
436     Parameters
437     ----------
438     parameter : type
439         Parameter description.
440
441     Returns
442     -------
443     Colorspace
444          *ACES LMT* colorspace.
445     """
446
447     cs = ColorSpace('%s' % lmt_name)
448     cs.description = 'The ACES Look Transform: %s' % lmt_name
449     cs.aliases = aliases
450     cs.equality_group = ''
451     cs.family = 'Look'
452     cs.is_data = False
453
454     pprint.pprint(lmt_values)
455
456     # Generating the *shaper* transform.
457     (shaper_name,
458      shaper_to_ACES_CTL,
459      shaper_from_ACES_CTL,
460      shaper_input_scale,
461      shaper_params) = shaper_info
462
463     shaper_lut = '%s_to_aces.spi1d' % shaper_name
464     if not os.path.exists(os.path.join(lut_directory, shaper_lut)):
465         ctls = [shaper_to_ACES_CTL % aces_ctl_directory]
466
467         shaper_lut = sanitize(shaper_lut)
468
469         generate_1d_LUT_from_CTL(
470             os.path.join(lut_directory, shaper_lut),
471             ctls,
472             lut_resolution_1d,
473             'float',
474             1.0 / shaper_input_scale,
475             1.0,
476             shaper_params,
477             cleanup,
478             aces_ctl_directory)
479
480     shaper_OCIO_transform = {
481         'type': 'lutFile',
482         'path': shaper_lut,
483         'interpolation': 'linear',
484         'direction': 'inverse'}
485
486     # Generating the forward transform.
487     cs.from_reference_transforms = []
488
489     if 'transformCTL' in lmt_values:
490         ctls = [shaper_to_ACES_CTL % aces_ctl_directory,
491                 os.path.join(aces_ctl_directory,
492                              lmt_values['transformCTL'])]
493         lut = '%s.%s.spi3d' % (shaper_name, lmt_name)
494
495         lut = sanitize(lut)
496
497         generate_3d_LUT_from_CTL(
498             os.path.join(lut_directory, lut),
499             ctls,
500             lut_resolution_3d,
501             'float',
502             1.0 / shaper_input_scale,
503             1.0,
504             shaper_params,
505             cleanup,
506             aces_ctl_directory)
507
508         cs.from_reference_transforms.append(shaper_OCIO_transform)
509         cs.from_reference_transforms.append({
510             'type': 'lutFile',
511             'path': lut,
512             'interpolation': 'tetrahedral',
513             'direction': 'forward'})
514
515     # Generating the inverse transform.
516     cs.to_reference_transforms = []
517
518     if 'transformCTLInverse' in lmt_values:
519         ctls = [os.path.join(aces_ctl_directory,
520                              # TODO: Investigate "odt_values" undeclared
521                              # variable.
522                              odt_values['transformCTLInverse']),
523                 shaper_from_ACES_CTL % aces_ctl_directory]
524         lut = 'Inverse.%s.%s.spi3d' % (odt_name, shaper_name)
525
526         lut = sanitize(lut)
527
528         generate_3d_LUT_from_CTL(
529             os.path.join(lut_directory, lut),
530             ctls,
531             lut_resolution_3d,
532             'half',
533             1.0,
534             shaper_input_scale,
535             shaper_params,
536             cleanup,
537             aces_ctl_directory)
538
539         cs.to_reference_transforms.append({
540             'type': 'lutFile',
541             'path': lut,
542             'interpolation': 'tetrahedral',
543             'direction': 'forward'})
544
545         shaper_inverse = shaper_OCIO_transform.copy()
546         shaper_inverse['direction'] = 'forward'
547         cs.to_reference_transforms.append(shaper_inverse)
548
549     return cs
550
551
552 def create_ACES_RRT_plus_ODT(odt_name,
553                              odt_values,
554                              shaper_info,
555                              aces_ctl_directory,
556                              lut_directory,
557                              lut_resolution_1d=1024,
558                              lut_resolution_3d=64,
559                              cleanup=True,
560                              aliases=[]):
561     """
562     Object description.
563
564     Parameters
565     ----------
566     parameter : type
567         Parameter description.
568
569     Returns
570     -------
571     type
572          Return value description.
573     """
574
575     cs = ColorSpace('%s' % odt_name)
576     cs.description = '%s - %s Output Transform' % (
577         odt_values['transformUserNamePrefix'], odt_name)
578     cs.aliases = aliases
579     cs.equality_group = ''
580     cs.family = 'Output'
581     cs.is_data = False
582
583     pprint.pprint(odt_values)
584
585     # Generating the *shaper* transform.
586     (shaper_name,
587      shaper_to_ACES_CTL,
588      shaper_from_ACES_CTL,
589      shaper_input_scale,
590      shaper_params) = shaper_info
591
592     if 'legalRange' in odt_values:
593         shaper_params['legalRange'] = odt_values['legalRange']
594     else:
595         shaper_params['legalRange'] = 0
596
597     shaper_lut = '%s_to_aces.spi1d' % shaper_name
598     if not os.path.exists(os.path.join(lut_directory, shaper_lut)):
599         ctls = [shaper_to_ACES_CTL % aces_ctl_directory]
600
601         shaper_lut = sanitize(shaper_lut)
602
603         generate_1d_LUT_from_CTL(
604             os.path.join(lut_directory, shaper_lut),
605             ctls,
606             lut_resolution_1d,
607             'float',
608             1.0 / shaper_input_scale,
609             1.0,
610             shaper_params,
611             cleanup,
612             aces_ctl_directory)
613
614     shaper_OCIO_transform = {
615         'type': 'lutFile',
616         'path': shaper_lut,
617         'interpolation': 'linear',
618         'direction': 'inverse'}
619
620     # Generating the *forward* transform.
621     cs.from_reference_transforms = []
622
623     if 'transformLUT' in odt_values:
624         transform_LUT_file_name = os.path.basename(
625             odt_values['transformLUT'])
626         lut = os.path.join(lut_directory, transform_LUT_file_name)
627         shutil.copy(odt_values['transformLUT'], lut)
628
629         cs.from_reference_transforms.append(shaper_OCIO_transform)
630         cs.from_reference_transforms.append({
631             'type': 'lutFile',
632             'path': transform_LUT_file_name,
633             'interpolation': 'tetrahedral',
634             'direction': 'forward'})
635     elif 'transformCTL' in odt_values:
636         ctls = [
637             shaper_to_ACES_CTL % aces_ctl_directory,
638             os.path.join(aces_ctl_directory,
639                          'rrt',
640                          'RRT.a1.0.0.ctl'),
641             os.path.join(aces_ctl_directory,
642                          'odt',
643                          odt_values['transformCTL'])]
644         lut = '%s.RRT.a1.0.0.%s.spi3d' % (shaper_name, odt_name)
645
646         lut = sanitize(lut)
647
648         generate_3d_LUT_from_CTL(
649             os.path.join(lut_directory, lut),
650             # shaperLUT,
651             ctls,
652             lut_resolution_3d,
653             'float',
654             1.0 / shaper_input_scale,
655             1.0,
656             shaper_params,
657             cleanup,
658             aces_ctl_directory)
659
660         cs.from_reference_transforms.append(shaper_OCIO_transform)
661         cs.from_reference_transforms.append({
662             'type': 'lutFile',
663             'path': lut,
664             'interpolation': 'tetrahedral',
665             'direction': 'forward'})
666
667     # Generating the *inverse* transform.
668     cs.to_reference_transforms = []
669
670     if 'transformLUTInverse' in odt_values:
671         transform_LUT_inverse_file_name = os.path.basename(
672             odt_values['transformLUTInverse'])
673         lut = os.path.join(lut_directory, transform_LUT_inverse_file_name)
674         shutil.copy(odt_values['transformLUTInverse'], lut)
675
676         cs.to_reference_transforms.append({
677             'type': 'lutFile',
678             'path': transform_LUT_inverse_file_name,
679             'interpolation': 'tetrahedral',
680             'direction': 'forward'})
681
682         shaper_inverse = shaper_OCIO_transform.copy()
683         shaper_inverse['direction'] = 'forward'
684         cs.to_reference_transforms.append(shaper_inverse)
685     elif 'transformCTLInverse' in odt_values:
686         ctls = [os.path.join(aces_ctl_directory,
687                              'odt',
688                              odt_values['transformCTLInverse']),
689                 os.path.join(aces_ctl_directory,
690                              'rrt',
691                              'InvRRT.a1.0.0.ctl'),
692                 shaper_from_ACES_CTL % aces_ctl_directory]
693         lut = 'InvRRT.a1.0.0.%s.%s.spi3d' % (odt_name, shaper_name)
694
695         lut = sanitize(lut)
696
697         generate_3d_LUT_from_CTL(
698             os.path.join(lut_directory, lut),
699             # None,
700             ctls,
701             lut_resolution_3d,
702             'half',
703             1.0,
704             shaper_input_scale,
705             shaper_params,
706             cleanup,
707             aces_ctl_directory)
708
709         cs.to_reference_transforms.append({
710             'type': 'lutFile',
711             'path': lut,
712             'interpolation': 'tetrahedral',
713             'direction': 'forward'})
714
715         shaper_inverse = shaper_OCIO_transform.copy()
716         shaper_inverse['direction'] = 'forward'
717         cs.to_reference_transforms.append(shaper_inverse)
718
719     return cs
720
721
722 def create_generic_log(aces_ctl_directory,
723                        lut_directory,
724                        lut_resolution_1d,
725                        cleanup,
726                        name='log',
727                        aliases=[],
728                        min_value=0.0,
729                        max_value=1.0,
730                        input_scale=1.0,
731                        middle_grey=0.18,
732                        min_exposure=-6.0,
733                        max_exposure=6.5):
734     """
735     Creates the *Generic Log* colorspace.
736
737     Parameters
738     ----------
739     parameter : type
740         Parameter description.
741
742     Returns
743     -------
744     Colorspace
745          *Generic Log* colorspace.
746     """
747
748     cs = ColorSpace(name)
749     cs.description = 'The %s color space' % name
750     cs.aliases = aliases
751     cs.equality_group = name
752     cs.family = 'Utility'
753     cs.is_data = False
754
755     ctls = [os.path.join(
756         aces_ctl_directory,
757         'utilities',
758         'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl')]
759     lut = '%s_to_aces.spi1d' % name
760
761     lut = sanitize(lut)
762
763     generate_1d_LUT_from_CTL(
764         os.path.join(lut_directory, lut),
765         ctls,
766         lut_resolution_1d,
767         'float',
768         input_scale,
769         1.0,
770         {'middleGrey': middle_grey,
771          'minExposure': min_exposure,
772          'maxExposure': max_exposure},
773         cleanup,
774         aces_ctl_directory,
775         min_value,
776         max_value)
777
778     cs.to_reference_transforms = []
779     cs.to_reference_transforms.append({
780         'type': 'lutFile',
781         'path': lut,
782         'interpolation': 'linear',
783         'direction': 'forward'})
784
785     cs.from_reference_transforms = []
786     return cs
787
788
789 def create_LMTs(aces_ctl_directory,
790                 lut_directory,
791                 lut_resolution_1d,
792                 lut_resolution_3d,
793                 lmt_info,
794                 shaper_name,
795                 cleanup):
796     """
797     Object description.
798
799     Parameters
800     ----------
801     parameter : type
802         Parameter description.
803
804     Returns
805     -------
806     type
807          Return value description.
808     """
809
810     colorspaces = []
811
812     # -------------------------------------------------------------------------
813     # *LMT Shaper*
814     # -------------------------------------------------------------------------
815     lmt_lut_resolution_1d = max(4096, lut_resolution_1d)
816     lmt_lut_resolution_3d = max(65, lut_resolution_3d)
817
818     # Defining the *Log 2* shaper.
819     lmt_shaper_name = 'LMT Shaper'
820     lmt_shaper_name_aliases = ['crv_lmtshaper']
821     lmt_params = {
822         'middleGrey': 0.18,
823         'minExposure': -10.0,
824         'maxExposure': 6.5}
825
826     lmt_shaper = create_generic_log(aces_ctl_directory,
827                                     lut_directory,
828                                     lmt_lut_resolution_1d,
829                                     cleanup,
830                                     name=lmt_shaper_name,
831                                     middle_grey=lmt_params['middleGrey'],
832                                     min_exposure=lmt_params['minExposure'],
833                                     max_exposure=lmt_params['maxExposure'],
834                                     aliases=lmt_shaper_name_aliases)
835     colorspaces.append(lmt_shaper)
836
837     shaper_input_scale_generic_log2 = 1.0
838
839     # *Log 2* shaper name and *CTL* transforms bundled up.
840     lmt_shaper_data = [
841         lmt_shaper_name,
842         os.path.join('%s',
843                      'utilities',
844                      'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl'),
845         os.path.join('%s',
846                      'utilities',
847                      'ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl'),
848         shaper_input_scale_generic_log2,
849         lmt_params]
850
851     sorted_LMTs = sorted(lmt_info.iteritems(), key=lambda x: x[1])
852     print(sorted_LMTs)
853     for lmt in sorted_LMTs:
854         lmt_name, lmt_values = lmt
855         lmt_aliases = ["look_%s" % compact(lmt_values['transformUserName'])]
856         cs = create_ACES_LMT(
857             lmt_values['transformUserName'],
858             lmt_values,
859             lmt_shaper_data,
860             aces_ctl_directory,
861             lut_directory,
862             lmt_lut_resolution_1d,
863             lmt_lut_resolution_3d,
864             cleanup,
865             lmt_aliases)
866         colorspaces.append(cs)
867
868     return colorspaces
869
870
871 def create_ODTs(aces_ctl_directory,
872                 lut_directory,
873                 lut_resolution_1d,
874                 lut_resolution_3d,
875                 odt_info,
876                 shaper_name,
877                 cleanup,
878                 linear_display_space,
879                 log_display_space):
880     """
881     Object description.
882
883     Parameters
884     ----------
885     parameter : type
886         Parameter description.
887
888     Returns
889     -------
890     type
891          Return value description.
892     """
893
894     colorspaces = []
895     displays = {}
896
897     # -------------------------------------------------------------------------
898     # *RRT / ODT* Shaper Options
899     # -------------------------------------------------------------------------
900     shaper_data = {}
901
902     # Defining the *Log 2* shaper.
903     log2_shaper_name = shaper_name
904     log2_shaper_name_aliases = ["crv_%s" % compact(shaper_name)]
905     log2_params = {
906         'middleGrey': 0.18,
907         'minExposure': -6.0,
908         'maxExposure': 6.5}
909
910     log2_shaper = create_generic_log(
911         aces_ctl_directory,
912         lut_directory,
913         lut_resolution_1d,
914         cleanup,
915         name=log2_shaper_name,
916         middle_grey=log2_params['middleGrey'],
917         min_exposure=log2_params['minExposure'],
918         max_exposure=log2_params['maxExposure'],
919         aliases=log2_shaper_name_aliases)
920     colorspaces.append(log2_shaper)
921
922     shaper_input_scale_generic_log2 = 1.0
923
924     # *Log 2* shaper name and *CTL* transforms bundled up.
925     log2_shaper_data = [
926         log2_shaper_name,
927         os.path.join('%s',
928                      'utilities',
929                      'ACESlib.OCIO_shaper_log2_to_lin_param.a1.0.0.ctl'),
930         os.path.join('%s',
931                      'utilities',
932                      'ACESlib.OCIO_shaper_lin_to_log2_param.a1.0.0.ctl'),
933         shaper_input_scale_generic_log2,
934         log2_params]
935
936     shaper_data[log2_shaper_name] = log2_shaper_data
937
938     # Shaper that also includes the AP1 primaries.
939     # Needed for some LUT baking steps.
940     log2_shaper_api1_name_aliases = ["%s_ap1" % compact(shaper_name)]
941     log2_shaper_ap1 = create_generic_log(
942         aces_ctl_directory,
943         lut_directory,
944         lut_resolution_1d,
945         cleanup,
946         name=log2_shaper_name,
947         middle_grey=log2_params['middleGrey'],
948         min_exposure=log2_params['minExposure'],
949         max_exposure=log2_params['maxExposure'],
950         aliases=log2_shaper_api1_name_aliases)
951     log2_shaper_ap1.name = '%s - AP1' % log2_shaper_ap1.name
952
953     # *AP1* primaries to *AP0* primaries.
954     log2_shaper_ap1.to_reference_transforms.append({
955         'type': 'matrix',
956         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
957         'direction': 'forward'
958     })
959     colorspaces.append(log2_shaper_ap1)
960
961     rrt_shaper = log2_shaper_data
962
963     # *RRT + ODT* combinations.
964     sorted_odts = sorted(odt_info.iteritems(), key=lambda x: x[1])
965     print(sorted_odts)
966     for odt in sorted_odts:
967         (odt_name, odt_values) = odt
968
969         # Generating legal range transform for *ODTs* that can generate 
970         # either *legal* or *full* output.
971         if odt_values['transformHasFullLegalSwitch']:
972             odt_name_legal = '%s - Legal' % odt_values['transformUserName']
973         else:
974             odt_name_legal = odt_values['transformUserName']
975
976         odt_legal = odt_values.copy()
977         odt_legal['legalRange'] = 1
978
979         odt_aliases = ["out_%s" % compact(odt_name_legal)]
980
981         cs = create_ACES_RRT_plus_ODT(
982             odt_name_legal,
983             odt_legal,
984             rrt_shaper,
985             aces_ctl_directory,
986             lut_directory,
987             lut_resolution_1d,
988             lut_resolution_3d,
989             cleanup,
990             odt_aliases)
991         colorspaces.append(cs)
992
993         displays[odt_name_legal] = {
994             'Linear': linear_display_space,
995             'Log': log_display_space,
996             'Output Transform': cs}
997
998
999         # Generating full range transform for *ODTs* that can generate 
1000         # either *legal* or *full* output.
1001         if odt_values['transformHasFullLegalSwitch']:
1002             print('Generating full range ODT for %s' % odt_name)
1003
1004             odt_name_full = '%s - Full' % odt_values['transformUserName']
1005             odt_full = odt_values.copy()
1006             odt_full['legalRange'] = 0
1007
1008             odt_full_aliases = ["out_%s" % compact(odt_name_full)]
1009
1010             cs_full = create_ACES_RRT_plus_ODT(
1011                 odt_name_full,
1012                 odt_full,
1013                 rrt_shaper,
1014                 aces_ctl_directory,
1015                 lut_directory,
1016                 lut_resolution_1d,
1017                 lut_resolution_3d,
1018                 cleanup,
1019                 odt_full_aliases)
1020             colorspaces.append(cs_full)
1021
1022             displays[odt_name_full] = {
1023                 'Linear': linear_display_space,
1024                 'Log': log_display_space,
1025                 'Output Transform': cs_full}
1026
1027     return (colorspaces, displays)
1028
1029
1030 def get_transform_info(ctl_transform):
1031     """
1032     Object description.
1033
1034     Parameters
1035     ----------
1036     parameter : type
1037         Parameter description.
1038
1039     Returns
1040     -------
1041     type
1042          Return value description.
1043     """
1044
1045     with open(ctl_transform, 'rb') as fp:
1046         lines = fp.readlines()
1047
1048     # Retrieving the *transform ID* and *User Name*.
1049     transform_id = lines[1][3:].split('<')[1].split('>')[1].strip()
1050     transform_user_name = '-'.join(
1051         lines[2][3:].split('<')[1].split('>')[1].split('-')[1:]).strip()
1052     transform_user_name_prefix = (
1053         lines[2][3:].split('<')[1].split('>')[1].split('-')[0].strip())
1054
1055     # Figuring out if this transform has options for processing full and legal range
1056     transform_full_legal_switch = False
1057     for line in lines:
1058         if line.strip() == "input varying int legalRange = 0":
1059             # print( "%s has legal range flag" % transform_user_name)
1060             transform_full_legal_switch = True
1061             break
1062
1063     return (transform_id, transform_user_name, transform_user_name_prefix,
1064             transform_full_legal_switch)
1065
1066
1067 def get_ODTs_info(aces_ctl_directory):
1068     """
1069     Object description.
1070
1071     For versions after WGR9.
1072
1073     Parameters
1074     ----------
1075     parameter : type
1076         Parameter description.
1077
1078     Returns
1079     -------
1080     type
1081          Return value description.
1082     """
1083
1084     # TODO: Investigate usage of *files_walker* definition here.
1085     # Credit to *Alex Fry* for the original approach here.
1086     odt_dir = os.path.join(aces_ctl_directory, 'odt')
1087     all_odt = []
1088     for dir_name, subdir_list, file_list in os.walk(odt_dir):
1089         for fname in file_list:
1090             all_odt.append((os.path.join(dir_name, fname)))
1091
1092     odt_CTLs = [x for x in all_odt if
1093                 ('InvODT' not in x) and (os.path.split(x)[-1][0] != '.')]
1094
1095     odts = {}
1096
1097     for odt_CTL in odt_CTLs:
1098         odt_tokens = os.path.split(odt_CTL)
1099
1100         # Handling nested directories.
1101         odt_path_tokens = os.path.split(odt_tokens[-2])
1102         odt_dir = odt_path_tokens[-1]
1103         while odt_path_tokens[-2][-3:] != 'odt':
1104             odt_path_tokens = os.path.split(odt_path_tokens[-2])
1105             odt_dir = os.path.join(odt_path_tokens[-1], odt_dir)
1106
1107         # Building full name,
1108         transform_CTL = odt_tokens[-1]
1109         odt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1110
1111         # Finding id, user name and user name prefix.
1112         (transform_ID,
1113          transform_user_name,
1114          transform_user_name_prefix,
1115          transform_full_legal_switch) = get_transform_info(
1116             os.path.join(aces_ctl_directory, 'odt', odt_dir, transform_CTL))
1117
1118         # Finding inverse.
1119         transform_CTL_inverse = 'InvODT.%s.ctl' % odt_name
1120         if not os.path.exists(
1121                 os.path.join(odt_tokens[-2], transform_CTL_inverse)):
1122             transform_CTL_inverse = None
1123
1124         # Add to list of ODTs
1125         odts[odt_name] = {}
1126         odts[odt_name]['transformCTL'] = os.path.join(odt_dir, transform_CTL)
1127         if transform_CTL_inverse is not None:
1128             odts[odt_name]['transformCTLInverse'] = os.path.join(
1129                 odt_dir, transform_CTL_inverse)
1130
1131         odts[odt_name]['transformID'] = transform_ID
1132         odts[odt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1133         odts[odt_name]['transformUserName'] = transform_user_name
1134         odts[odt_name][
1135             'transformHasFullLegalSwitch'] = transform_full_legal_switch
1136
1137         forward_CTL = odts[odt_name]['transformCTL']
1138
1139         print('ODT : %s' % odt_name)
1140         print('\tTransform ID               : %s' % transform_ID)
1141         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1142         print('\tTransform User Name        : %s' % transform_user_name)
1143         print(
1144             '\tHas Full / Legal Switch    : %s' % transform_full_legal_switch)
1145         print('\tForward ctl                : %s' % forward_CTL)
1146         if 'transformCTLInverse' in odts[odt_name]:
1147             inverse_CTL = odts[odt_name]['transformCTLInverse']
1148             print('\tInverse ctl                : %s' % inverse_CTL)
1149         else:
1150             print('\tInverse ctl                : %s' % 'None')
1151
1152     print('\n')
1153
1154     return odts
1155
1156
1157 def get_LMTs_info(aces_ctl_directory):
1158     """
1159     Object description.
1160
1161     For versions after WGR9.
1162
1163     Parameters
1164     ----------
1165     parameter : type
1166         Parameter description.
1167
1168     Returns
1169     -------
1170     type
1171          Return value description.
1172     """
1173
1174     # TODO: Investigate refactoring with previous definition.
1175
1176     # Credit to Alex Fry for the original approach here
1177     lmt_dir = os.path.join(aces_ctl_directory, 'lmt')
1178     all_lmt = []
1179     for dir_name, subdir_list, file_list in os.walk(lmt_dir):
1180         for fname in file_list:
1181             all_lmt.append((os.path.join(dir_name, fname)))
1182
1183     lmt_CTLs = [x for x in all_lmt if
1184                 ('InvLMT' not in x) and ('README' not in x) and (
1185                     os.path.split(x)[-1][0] != '.')]
1186
1187     lmts = {}
1188
1189     for lmt_CTL in lmt_CTLs:
1190         lmt_tokens = os.path.split(lmt_CTL)
1191
1192         # Handlimg nested directories.
1193         lmt_path_tokens = os.path.split(lmt_tokens[-2])
1194         lmt_dir = lmt_path_tokens[-1]
1195         while lmt_path_tokens[-2][-3:] != 'ctl':
1196             lmt_path_tokens = os.path.split(lmt_path_tokens[-2])
1197             lmt_dir = os.path.join(lmt_path_tokens[-1], lmt_dir)
1198
1199         # Building full name.
1200         transform_CTL = lmt_tokens[-1]
1201         lmt_name = string.join(transform_CTL.split('.')[1:-1], '.')
1202
1203         # Finding id, user name and user name prefix.
1204         (transform_ID,
1205          transform_user_name,
1206          transform_user_name_prefix,
1207          transform_full_legal_switch) = get_transform_info(
1208             os.path.join(aces_ctl_directory, lmt_dir, transform_CTL))
1209
1210         # Finding inverse.
1211         transform_CTL_inverse = 'InvLMT.%s.ctl' % lmt_name
1212         if not os.path.exists(
1213                 os.path.join(lmt_tokens[-2], transform_CTL_inverse)):
1214             transform_CTL_inverse = None
1215
1216         lmts[lmt_name] = {}
1217         lmts[lmt_name]['transformCTL'] = os.path.join(lmt_dir, transform_CTL)
1218         if transform_CTL_inverse is not None:
1219             lmts[lmt_name]['transformCTLInverse'] = os.path.join(
1220                 lmt_dir, transform_CTL_inverse)
1221
1222         lmts[lmt_name]['transformID'] = transform_ID
1223         lmts[lmt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1224         lmts[lmt_name]['transformUserName'] = transform_user_name
1225
1226         forward_CTL = lmts[lmt_name]['transformCTL']
1227
1228         print('LMT : %s' % lmt_name)
1229         print('\tTransform ID               : %s' % transform_ID)
1230         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1231         print('\tTransform User Name        : %s' % transform_user_name)
1232         print('\t Forward ctl               : %s' % forward_CTL)
1233         if 'transformCTLInverse' in lmts[lmt_name]:
1234             inverse_CTL = lmts[lmt_name]['transformCTLInverse']
1235             print('\t Inverse ctl                : %s' % inverse_CTL)
1236         else:
1237             print('\t Inverse ctl                : %s' % 'None')
1238
1239     print('\n')
1240
1241     return lmts
1242
1243
1244 def create_colorspaces(aces_ctl_directory,
1245                        lut_directory,
1246                        lut_resolution_1d,
1247                        lut_resolution_3d,
1248                        lmt_info,
1249                        odt_info,
1250                        shaper_name,
1251                        cleanup):
1252     """
1253     Generates the colorspace conversions.
1254
1255     Parameters
1256     ----------
1257     parameter : type
1258         Parameter description.
1259
1260     Returns
1261     -------
1262     type
1263          Return value description.
1264     """
1265
1266     colorspaces = []
1267
1268     ACES = create_ACES()
1269
1270     ACEScc = create_ACEScc(aces_ctl_directory, lut_directory,
1271                            lut_resolution_1d, cleanup)
1272     colorspaces.append(ACEScc)
1273
1274     ACESproxy = create_ACESproxy(aces_ctl_directory, lut_directory,
1275                                  lut_resolution_1d, cleanup)
1276     colorspaces.append(ACESproxy)
1277
1278     ACEScg = create_ACEScg(aces_ctl_directory, lut_directory,
1279                            lut_resolution_1d, cleanup)
1280     colorspaces.append(ACEScg)
1281
1282     ADX10 = create_ADX(lut_directory, lut_resolution_1d, bit_depth=10)
1283     colorspaces.append(ADX10)
1284
1285     ADX16 = create_ADX(lut_directory, lut_resolution_1d, bit_depth=16)
1286     colorspaces.append(ADX16)
1287
1288     lmts = create_LMTs(aces_ctl_directory,
1289                        lut_directory,
1290                        lut_resolution_1d,
1291                        lut_resolution_3d,
1292                        lmt_info,
1293                        shaper_name,
1294                        cleanup)
1295     colorspaces.extend(lmts)
1296
1297     odts, displays = create_ODTs(aces_ctl_directory,
1298                                  lut_directory,
1299                                  lut_resolution_1d,
1300                                  lut_resolution_3d,
1301                                  odt_info,
1302                                  shaper_name,
1303                                  cleanup,
1304                                  ACES,
1305                                  ACEScc)
1306     colorspaces.extend(odts)
1307
1308     return ACES, colorspaces, displays, ACEScc