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