ce73beef69f62a84ab8a36dc9a736f3659b98e5e
[OpenColorIO-Configs.git] / aces_1.0.0 / python / aces_ocio / colorspaces / aces.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 copy
11 import math
12 import numpy
13 import os
14 import pprint
15 import string
16 import shutil
17
18 import PyOpenColorIO as ocio
19
20 from aces_ocio.generate_lut import (
21     generate_1d_LUT_from_CTL,
22     generate_3d_LUT_from_CTL,
23     write_SPI_1d)
24 from aces_ocio.utilities import (
25     ColorSpace,
26     mat44_from_mat33,
27     sanitize,
28     compact)
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_AP1',
39            'ACES_AP0_TO_XYZ',
40            'ACES_XYZ_TO_AP0',
41            'create_ACES',
42            'create_ACEScc',
43            'create_ACESproxy',
44            'create_ACEScg',
45            'create_ADX',
46            'create_generic_log',
47            'create_Dolby_PQ',
48            'create_Dolby_PQ_shaper',
49            'create_ACES_LMT',
50            'create_LMTs',
51            'create_ACES_RRT_plus_ODT',
52            'create_ODTs',
53            'create_shapers_dolbypq'
54            'create_shapers_log2',
55            'create_shapers',
56            'get_transform_info',
57            'get_ODTs_info',
58            'get_LMTs_info',
59            'create_colorspaces']
60
61 # Matrix converting *ACES AP1* primaries to *ACES AP0*.
62 ACES_AP1_TO_AP0 = [0.6954522414, 0.1406786965, 0.1638690622,
63                    0.0447945634, 0.8596711185, 0.0955343182,
64                    -0.0055258826, 0.0040252103, 1.0015006723]
65
66 # Matrix converting *ACES AP0* primaries to *ACES AP1*.
67 ACES_AP0_TO_AP1 = [1.4514393161, -0.2365107469, -0.2149285693,
68                    -0.0765537734, 1.1762296998, -0.0996759264,
69                    0.0083161484, -0.0060324498, 0.9977163014]
70
71 # Matrix converting *ACES AP0* primaries to *XYZ*.
72 ACES_AP0_TO_XYZ = [0.9525523959, 0.0000000000, 0.0000936786,
73                    0.3439664498, 0.7281660966, -0.0721325464,
74                    0.0000000000, 0.0000000000, 1.0088251844]
75
76 # Matrix converting *ACES AP0* primaries to *XYZ*.
77 ACES_XYZ_TO_AP0 = [1.0498110175, 0.0000000000, -0.0000974845,
78                    -0.4959030231, 1.3733130458, 0.0982400361,
79                    0.0000000000, 0.0000000000, 0.9912520182]
80
81
82 def create_ACES():
83     """
84     Creates the *ACES2065-1* reference color space
85
86     Parameters
87     ----------
88     None
89
90     Returns
91     -------
92     ColorSpace
93          *ACES2065-1* and all its identifying information
94     """
95
96     # Defining the reference colorspace.
97     aces2065_1 = ColorSpace('ACES2065-1')
98     aces2065_1.description = (
99         'The Academy Color Encoding System reference color space')
100     aces2065_1.equality_group = ''
101     aces2065_1.aliases = ['lin_ap0', 'aces']
102     aces2065_1.family = 'ACES'
103     aces2065_1.is_data = False
104     aces2065_1.allocation_type = ocio.Constants.ALLOCATION_LG2
105     aces2065_1.allocation_vars = [-8, 5, 0.00390625]
106
107     return aces2065_1
108
109
110 def create_ACEScc(aces_ctl_directory,
111                   lut_directory,
112                   lut_resolution_1d,
113                   cleanup,
114                   name='ACEScc',
115                   min_value=0,
116                   max_value=1,
117                   input_scale=1):
118     """
119     Creates the *ACEScc* reference color space
120
121     Parameters
122     ----------
123     aces_ctl_directory : str or unicode
124         The path to the aces 'transforms/ctl/utilities'
125     lut_directory : str or unicode 
126         The directory to use when generating LUTs
127     lut_resolution_1d : int
128         The resolution of generated 1D LUTs
129     cleanup : bool
130         Whether or not to clean up the intermediate images 
131     name : str or unicode, optional
132         The name of the ColorSpace
133     min_value : float, optional
134         The minimum value to consider for the space
135     max_value : float, optional
136         The maximum value to consider for the space
137     input_scale : float, optional
138         A scale factor to divide input values
139
140     Returns
141     -------
142     ColorSpace
143          *ACEScc* and all its identifying information
144     """
145
146     cs = ColorSpace(name)
147     cs.description = 'The %s color space' % name
148     cs.aliases = ['acescc', 'acescc_ap1']
149     cs.equality_group = ''
150     cs.family = 'ACES'
151     cs.is_data = False
152     cs.allocation_type = ocio.Constants.ALLOCATION_UNIFORM
153     cs.allocation_vars = [min_value, max_value]
154     cs.aces_transform_id = 'ACEScsc.ACEScc_to_ACES.a1.0.0'
155
156     ctls = [os.path.join(aces_ctl_directory,
157                          'ACEScc',
158                          'ACEScsc.ACEScc_to_ACES.a1.0.0.ctl'),
159             # This transform gets back to the *AP1* primaries.
160             # Useful as the 1d LUT is only covering the transfer function.
161             # The primaries switch is covered by the matrix below:
162             os.path.join(aces_ctl_directory,
163                          'ACEScg',
164                          'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
165     lut = '%s_to_linear.spi1d' % name
166
167     lut = sanitize(lut)
168
169     generate_1d_LUT_from_CTL(
170         os.path.join(lut_directory, lut),
171         ctls,
172         lut_resolution_1d,
173         'float',
174         input_scale,
175         1,
176         {},
177         cleanup,
178         aces_ctl_directory,
179         min_value,
180         max_value,
181         1)
182
183     cs.to_reference_transforms = []
184     cs.to_reference_transforms.append({
185         'type': 'lutFile',
186         'path': lut,
187         'interpolation': 'linear',
188         'direction': 'forward'})
189
190     # *AP1* primaries to *AP0* primaries
191     cs.to_reference_transforms.append({
192         'type': 'matrix',
193         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
194         'direction': 'forward'})
195
196     cs.from_reference_transforms = []
197     return cs
198
199
200 def create_ACESproxy(aces_ctl_directory,
201                      lut_directory,
202                      lut_resolution_1d,
203                      cleanup,
204                      name='ACESproxy'):
205     """
206     Creates the *ACESproxy* color space
207
208     Parameters
209     ----------
210     aces_ctl_directory : str or unicode
211         The path to the aces 'transforms/ctl/utilities'
212     lut_directory : str or unicode 
213         The directory to use when generating LUTs
214     lut_resolution_1d : int
215         The resolution of generated 1D LUTs
216     cleanup : bool
217         Whether or not to clean up the intermediate images 
218     name : str or unicode, optional
219         The name of the ColorSpace
220
221     Returns
222     -------
223     ColorSpace
224          *ACESproxy* and all its identifying information
225     """
226
227     cs = ColorSpace(name)
228     cs.description = 'The %s color space' % name
229     cs.aliases = ['acesproxy', 'acesproxy_ap1']
230     cs.equality_group = ''
231     cs.family = 'ACES'
232     cs.is_data = False
233
234     cs.aces_transform_id = 'ACEScsc.ACESproxy10i_to_ACES.a1.0.0'
235
236     ctls = [os.path.join(aces_ctl_directory,
237                          'ACESproxy',
238                          'ACEScsc.ACESproxy10i_to_ACES.a1.0.0.ctl'),
239             # This transform gets back to the *AP1* primaries.
240             # Useful as the 1d LUT is only covering the transfer function.
241             # The primaries switch is covered by the matrix below:
242             os.path.join(aces_ctl_directory,
243                          'ACEScg',
244                          'ACEScsc.ACES_to_ACEScg.a1.0.0.ctl')]
245     lut = '%s_to_linear.spi1d' % name
246
247     lut = sanitize(lut)
248
249     generate_1d_LUT_from_CTL(
250         os.path.join(lut_directory, lut),
251         ctls,
252         lut_resolution_1d,
253         'float',
254         1,
255         1,
256         {},
257         cleanup,
258         aces_ctl_directory,
259         0,
260         1,
261         1)
262
263     cs.to_reference_transforms = []
264     cs.to_reference_transforms.append({
265         'type': 'lutFile',
266         'path': lut,
267         'interpolation': 'linear',
268         'direction': 'forward'})
269
270     # *AP1* primaries to *AP0* primaries
271     cs.to_reference_transforms.append({
272         'type': 'matrix',
273         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
274         'direction': 'forward'})
275
276     cs.from_reference_transforms = []
277     return cs
278
279
280 # -------------------------------------------------------------------------
281 # *ACEScg*
282 # -------------------------------------------------------------------------
283 def create_ACEScg():
284     """
285     Creates the *ACEScg* color space
286
287     Parameters
288     ----------
289     None
290
291     Returns
292     -------
293     ColorSpace
294          *ACEScg* and all its identifying information
295     """
296
297     name = 'ACEScg'
298
299     cs = ColorSpace(name)
300     cs.description = 'The %s color space' % name
301     cs.aliases = ['acescg', 'lin_ap1']
302     cs.equality_group = ''
303     cs.family = 'ACES'
304     cs.is_data = False
305     cs.allocation_type = ocio.Constants.ALLOCATION_LG2
306     cs.allocation_vars = [-8, 5, 0.00390625]
307
308     cs.aces_transform_id = 'ACEScsc.ACEScg_to_ACES.a1.0.0'
309
310     cs.to_reference_transforms = []
311
312     # *AP1* primaries to *AP0* primaries
313     cs.to_reference_transforms.append({
314         'type': 'matrix',
315         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
316         'direction': 'forward'})
317
318     cs.from_reference_transforms = []
319
320     # Commented out because specifying the inverse matrix causes some
321     # of OCIO's checks to see if a set of transforms can be collapsed
322     # to fail.
323
324     # *AP1* primaries to *AP0* primaries
325     #cs.from_reference_transforms.append({
326     #    'type': 'matrix',
327     #    'matrix': mat44_from_mat33(ACES_AP0_TO_AP1),
328     #    'direction': 'forward'})
329
330     return cs
331
332
333 # -------------------------------------------------------------------------
334 # *ADX*
335 # -------------------------------------------------------------------------
336 def create_ADX(lut_directory,
337                bit_depth=10,
338                name='ADX'):
339     """
340     Creates the *ADX* color space
341
342     Parameters
343     ----------
344     lut_directory : str or unicode 
345         The directory to use when generating LUTs
346     bit_depth : int
347         Choose either 10 or 16 bit ADX
348     name : str or unicode, optional
349         The name of the ColorSpace
350
351     Returns
352     -------
353     ColorSpace
354          *ADX* and all its identifying information
355     """
356
357     name = '%s%s' % (name, bit_depth)
358     cs = ColorSpace(name)
359     cs.description = '%s color space - used for film scans' % name
360     cs.aliases = ['adx%s' % str(bit_depth)]
361     cs.equality_group = ''
362     cs.family = 'ADX'
363     cs.is_data = False
364
365     if bit_depth == 10:
366         cs.aces_transform_id = 'ACEScsc.ADX10_to_ACES.a1.0.0'
367
368         cs.bit_depth = ocio.Constants.BIT_DEPTH_UINT10
369         ADX_to_CDD = [1023 / 500, 0, 0, 0,
370                       0, 1023 / 500, 0, 0,
371                       0, 0, 1023 / 500, 0,
372                       0, 0, 0, 1]
373         offset = [-95 / 500, -95 / 500, -95 / 500, 0]
374     elif bit_depth == 16:
375         cs.aces_transform_id = 'ACEScsc.ADX16_to_ACES.a1.0.0'
376
377         cs.bit_depth = ocio.Constants.BIT_DEPTH_UINT16
378         ADX_to_CDD = [65535 / 8000, 0, 0, 0,
379                       0, 65535 / 8000, 0, 0,
380                       0, 0, 65535 / 8000, 0,
381                       0, 0, 0, 1]
382         offset = [-1520 / 8000, -1520 / 8000, -1520 / 8000, 0]
383
384     cs.to_reference_transforms = []
385
386     # Converting from *ADX* to *Channel-Dependent Density*.
387     cs.to_reference_transforms.append({
388         'type': 'matrix',
389         'matrix': ADX_to_CDD,
390         'offset': offset,
391         'direction': 'forward'})
392
393     # Converting from *Channel-Dependent Density* to
394     # *Channel-Independent Density*.
395     cs.to_reference_transforms.append({
396         'type': 'matrix',
397         'matrix': [0.75573, 0.22197, 0.02230, 0,
398                    0.05901, 0.96928, -0.02829, 0,
399                    0.16134, 0.07406, 0.76460, 0,
400                    0, 0, 0, 1],
401         'direction': 'forward'})
402
403     # Copied from *Alex Fry*'s *adx_cid_to_rle.py*
404     def create_CID_to_RLE_LUT():
405
406         def interpolate_1d(x, xp, fp):
407             return numpy.interp(x, xp, fp)
408
409         LUT_1D_XP = [-0.190000000000000,
410                      0.010000000000000,
411                      0.028000000000000,
412                      0.054000000000000,
413                      0.095000000000000,
414                      0.145000000000000,
415                      0.220000000000000,
416                      0.300000000000000,
417                      0.400000000000000,
418                      0.500000000000000,
419                      0.600000000000000]
420
421         LUT_1D_FP = [-6.000000000000000,
422                      -2.721718645000000,
423                      -2.521718645000000,
424                      -2.321718645000000,
425                      -2.121718645000000,
426                      -1.921718645000000,
427                      -1.721718645000000,
428                      -1.521718645000000,
429                      -1.321718645000000,
430                      -1.121718645000000,
431                      -0.926545676714876]
432
433         REF_PT = ((7120 - 1520) / 8000 * (100 / 55) -
434                   math.log(0.18, 10))
435
436         def cid_to_rle(x):
437             if x <= 0.6:
438                 return interpolate_1d(x, LUT_1D_XP, LUT_1D_FP)
439             return (100 / 55) * x - REF_PT
440
441         def fit(value, from_min, from_max, to_min, to_max):
442             if from_min == from_max:
443                 raise ValueError('from_min == from_max')
444             return (value - from_min) / (from_max - from_min) * (
445                 to_max - to_min) + to_min
446
447         num_samples = 2 ** 12
448         domain = (-0.19, 3)
449         data = []
450         for i in xrange(num_samples):
451             x = i / (num_samples - 1)
452             x = fit(x, 0, 1, domain[0], domain[1])
453             data.append(cid_to_rle(x))
454
455         lut = 'ADX_CID_to_RLE.spi1d'
456         write_SPI_1d(os.path.join(lut_directory, lut),
457                      domain[0],
458                      domain[1],
459                      data,
460                      num_samples, 1)
461
462         return lut
463
464     # Converting *Channel Independent Density* values to
465     # *Relative Log Exposure* values.
466     lut = create_CID_to_RLE_LUT()
467     cs.to_reference_transforms.append({
468         'type': 'lutFile',
469         'path': lut,
470         'interpolation': 'linear',
471         'direction': 'forward'})
472
473     # Converting *Relative Log Exposure* values to
474     # *Relative Exposure* values.
475     cs.to_reference_transforms.append({
476         'type': 'log',
477         'base': 10,
478         'direction': 'inverse'})
479
480     # Convert *Relative Exposure* values to *ACES* values.
481     cs.to_reference_transforms.append({
482         'type': 'matrix',
483         'matrix': [0.72286, 0.12630, 0.15084, 0,
484                    0.11923, 0.76418, 0.11659, 0,
485                    0.01427, 0.08213, 0.90359, 0,
486                    0, 0, 0, 1],
487         'direction': 'forward'})
488
489     cs.from_reference_transforms = []
490     return cs
491
492
493 # -------------------------------------------------------------------------
494 # Generic *Log* Transform
495 # -------------------------------------------------------------------------
496 def create_generic_log(aces_ctl_directory,
497                        lut_directory,
498                        lut_resolution_1d,
499                        cleanup,
500                        name='log',
501                        aliases=None,
502                        min_value=0,
503                        max_value=1,
504                        input_scale=1,
505                        middle_grey=0.18,
506                        min_exposure=-6.5,
507                        max_exposure=6.5):
508     """
509     Creates the *Generic Log* colorspace.
510
511     Parameters
512     ----------
513     aces_ctl_directory : str or unicode
514         The path to the aces 'transforms/ctl/utilities'
515     lut_directory : str or unicode 
516         The directory to use when generating LUTs
517     lut_resolution_1d : int
518         The resolution of generated 1D LUTs
519     cleanup : bool
520         Whether or not to clean up the intermediate images 
521     name : str or unicode, optional
522         The name of the ColorSpace
523     aliases : list of str or unicode, optional
524         The alias names to use for the ColorSpace
525     min_value : float, optional
526         The minimum value to consider for the space
527     max_value : float, optional
528         The maximum value to consider for the space
529     input_scale : float, optional
530         A scale factor to divide input values
531     middle_grey : float, optional
532         The middle of the dynamic range covered by the transfer function
533     min_exposure : float, optional
534         The offset from middle grey, in stops, that defines the low end of the dynamic 
535         range covered by the transfer function
536     max_exposure : float, optional
537         The offset from middle grey, in stops, that defines the high end of the dynamic 
538         range covered by the transfer function
539
540     Returns
541     -------
542     ColorSpace
543          *Generic Log* colorspace.
544     """
545
546     if aliases is None:
547         aliases = []
548
549     cs = ColorSpace(name)
550     cs.description = 'The %s color space' % name
551     cs.aliases = aliases
552     cs.equality_group = name
553     cs.family = 'Utility'
554     cs.is_data = False
555
556     ctls = [os.path.join(
557         aces_ctl_directory,
558         'utilities',
559         'ACESlib.Log2_to_Lin_param.a1.0.0.ctl')]
560     lut = '%s_to_linear.spi1d' % name
561
562     lut = sanitize(lut)
563
564     generate_1d_LUT_from_CTL(
565         os.path.join(lut_directory, lut),
566         ctls,
567         lut_resolution_1d,
568         'float',
569         input_scale,
570         1,
571         {'middleGrey': middle_grey,
572          'minExposure': min_exposure,
573          'maxExposure': max_exposure},
574         cleanup,
575         aces_ctl_directory,
576         min_value,
577         max_value,
578         1)
579
580     cs.to_reference_transforms = []
581     cs.to_reference_transforms.append({
582         'type': 'lutFile',
583         'path': lut,
584         'interpolation': 'linear',
585         'direction': 'forward'})
586
587     cs.from_reference_transforms = []
588     return cs
589
590
591 # -------------------------------------------------------------------------
592 # Base *Dolby PQ* Transform
593 # -------------------------------------------------------------------------
594 def create_Dolby_PQ(aces_ctl_directory,
595                     lut_directory,
596                     lut_resolution_1d,
597                     cleanup,
598                     name='pq',
599                     aliases=None,
600                     min_value=0.0,
601                     max_value=1.0,
602                     input_scale=1.0):
603     """
604     Creates the generic *Dolby PQ* colorspace.
605
606     Parameters
607     ----------
608     aces_ctl_directory : str or unicode
609         The path to the aces 'transforms/ctl/utilities'
610     lut_directory : str or unicode 
611         The directory to use when generating LUTs
612     lut_resolution_1d : int
613         The resolution of generated 1D LUTs
614     cleanup : bool
615         Whether or not to clean up the intermediate images 
616     name : str or unicode, optional
617         The name of the ColorSpace
618     aliases : list of str or unicode, optional
619         The alias names to use for the ColorSpace
620     min_value : float, optional
621         The minimum value to consider for the space
622     max_value : float, optional
623         The maximum value to consider for the space
624     input_scale : float, optional
625         A scale factor to divide input values
626
627     Returns
628     -------
629     ColorSpace
630          Generic *Dolby PQ* colorspace.
631     """
632
633     if aliases is None:
634         aliases = []
635
636     cs = ColorSpace(name)
637     cs.description = 'The %s color space' % name
638     cs.aliases = aliases
639     cs.equality_group = name
640     cs.family = 'Utility'
641     cs.is_data = False
642
643     ctls = [os.path.join(
644         aces_ctl_directory,
645         'utilities',
646         'ACESlib.DolbyPQ_to_Lin.a1.0.0.ctl')]
647     lut = '%s_to_linear.spi1d' % name
648
649     lut = sanitize(lut)
650
651     generate_1d_LUT_from_CTL(
652         os.path.join(lut_directory, lut),
653         ctls,
654         lut_resolution_1d,
655         'float',
656         input_scale,
657         1.0,
658         {},
659         cleanup,
660         aces_ctl_directory,
661         min_value,
662         max_value)
663
664     cs.to_reference_transforms = []
665     cs.to_reference_transforms.append({
666         'type': 'lutFile',
667         'path': lut,
668         'interpolation': 'linear',
669         'direction': 'forward'})
670
671     cs.from_reference_transforms = []
672     return cs
673
674
675 # -------------------------------------------------------------------------
676 # *Dolby PQ* Transform - Fixed Linear Range
677 # -------------------------------------------------------------------------
678 def create_Dolby_PQ_shaper(aces_ctl_directory,
679                            lut_directory,
680                            lut_resolution_1d,
681                            cleanup,
682                            name='pq',
683                            aliases=None,
684                            min_value=0.0,
685                            max_value=1.0,
686                            input_scale=1.0,
687                            middle_grey=0.18,
688                            min_exposure=-6.5,
689                            max_exposure=6.5):
690     """
691     Creates a *Dolby PQ* colorspace that covers a specific dynamic range
692
693     Parameters
694     ----------
695     aces_ctl_directory : str or unicode
696         The path to the aces 'transforms/ctl/utilities'
697     lut_directory : str or unicode 
698         The directory to use when generating LUTs
699     lut_resolution_1d : int
700         The resolution of generated 1D LUTs
701     cleanup : bool
702         Whether or not to clean up the intermediate images 
703     name : str or unicode, optional
704         The name of the ColorSpace
705     aliases : list of str or unicode, optional
706         The alias names to use for the ColorSpace
707     min_value : float, optional
708         The minimum value to consider for the space
709     max_value : float, optional
710         The maximum value to consider for the space
711     input_scale : float, optional
712         A scale factor to divide input values
713     middle_grey : float, optional
714         The middle of the dynamic range covered by the transfer function
715     min_exposure : float, optional
716         The offset from middle grey, in stops, that defines the low end of the dynamic 
717         range covered by the transfer function
718     max_exposure : float, optional
719         The offset from middle grey, in stops, that defines the high end of the dynamic 
720         range covered by the transfer function
721
722     Returns
723     -------
724     ColorSpace
725          A *Dolby PQ* colorspace that covers a specific dynamic range
726     """
727
728     if aliases is None:
729         aliases = []
730
731     cs = ColorSpace(name)
732     cs.description = 'The %s color space' % name
733     cs.aliases = aliases
734     cs.equality_group = name
735     cs.family = 'Utility'
736     cs.is_data = False
737
738     ctls = [os.path.join(
739         aces_ctl_directory,
740         'utilities',
741         'ACESlib.OCIOshaper_to_Lin_param.a1.0.0.ctl')]
742     lut = '%s_to_linear.spi1d' % name
743
744     lut = sanitize(lut)
745
746     generate_1d_LUT_from_CTL(
747         os.path.join(lut_directory, lut),
748         ctls,
749         lut_resolution_1d,
750         'float',
751         input_scale,
752         1.0,
753         {'middleGrey': middle_grey,
754          'minExposure': min_exposure,
755          'maxExposure': max_exposure},
756         cleanup,
757         aces_ctl_directory,
758         min_value,
759         max_value)
760
761     cs.to_reference_transforms = []
762     cs.to_reference_transforms.append({
763         'type': 'lutFile',
764         'path': lut,
765         'interpolation': 'linear',
766         'direction': 'forward'})
767
768     cs.from_reference_transforms = []
769     return cs
770
771
772 # -------------------------------------------------------------------------
773 # Individual *LMT*
774 # -------------------------------------------------------------------------
775 def create_ACES_LMT(lmt_name,
776                     lmt_values,
777                     shaper_info,
778                     aces_ctl_directory,
779                     lut_directory,
780                     lut_resolution_3d=64,
781                     cleanup=True,
782                     aliases=None):
783     """
784     Creates an *ACES Look Transform (LMT)* colorspace.
785
786     Parameters
787     ----------
788     lmt_name : str or unicode
789         The name of the Look Transform (LMT)
790     lmt_values : dict
791         A collection of values that define the Look Transform's attributes and behavior
792     shaper_info : dict
793         A collection of values that define the Shaper to use when generating LUTs to
794         represent the Look Transform
795     aces_ctl_directory : str or unicode
796         The path to the aces 'transforms/ctl/utilities'
797     lut_directory : str or unicode 
798         The directory to use when generating LUTs
799     lut_resolution_3d : int, optional
800         The resolution of generated 3D LUTs
801     cleanup : bool, optional
802         Whether or not to clean up the intermediate images 
803     aliases : list of str or unicode, optional
804         The alias names to use for the ColorSpace
805
806     Returns
807     -------
808     ColorSpace
809          An *ACES LMT* colorspace.
810     """
811
812     if aliases is None:
813         aliases = []
814
815     cs = ColorSpace('%s' % lmt_name)
816     cs.description = 'The ACES Look Transform: %s' % lmt_name
817     cs.aliases = aliases
818     cs.equality_group = ''
819     cs.family = 'Look'
820     cs.is_data = False
821     cs.allocation_type = ocio.Constants.ALLOCATION_LG2
822     cs.allocation_vars = [-8, 5, 0.00390625]
823     cs.aces_transform_id = lmt_values['transformID']
824
825     pprint.pprint(lmt_values)
826
827     # Generating the *shaper* transform.
828     (shaper_name,
829      shaper_to_aces_ctl,
830      shaper_from_aces_ctl,
831      shaper_input_scale,
832      shaper_params) = shaper_info
833
834     shaper_lut = '%s_to_linear.spi1d' % shaper_name
835     shaper_lut = sanitize(shaper_lut)
836
837     shaper_ocio_transform = {
838         'type': 'lutFile',
839         'path': shaper_lut,
840         'interpolation': 'linear',
841         'direction': 'inverse'}
842
843     # Generating the forward transform.
844     cs.from_reference_transforms = []
845
846     if 'transformCTL' in lmt_values:
847         ctls = [shaper_to_aces_ctl % aces_ctl_directory,
848                 os.path.join(aces_ctl_directory,
849                              lmt_values['transformCTL'])]
850         lut = '%s.%s.spi3d' % (shaper_name, lmt_name)
851
852         lut = sanitize(lut)
853
854         generate_3d_LUT_from_CTL(
855             os.path.join(lut_directory, lut),
856             ctls,
857             lut_resolution_3d,
858             'float',
859             1 / shaper_input_scale,
860             1,
861             shaper_params,
862             cleanup,
863             aces_ctl_directory)
864
865         cs.from_reference_transforms.append(shaper_ocio_transform)
866         cs.from_reference_transforms.append({
867             'type': 'lutFile',
868             'path': lut,
869             'interpolation': 'tetrahedral',
870             'direction': 'forward'})
871
872     # Generating the inverse transform.
873     cs.to_reference_transforms = []
874
875     if 'transformCTLInverse' in lmt_values:
876         ctls = [os.path.join(aces_ctl_directory,
877                              lmt_values['transformCTLInverse']),
878                 shaper_from_aces_ctl % aces_ctl_directory]
879         lut = 'Inverse.%s.%s.spi3d' % (lmt_name, shaper_name)
880
881         lut = sanitize(lut)
882
883         generate_3d_LUT_from_CTL(
884             os.path.join(lut_directory, lut),
885             ctls,
886             lut_resolution_3d,
887             'half',
888             1,
889             shaper_input_scale,
890             shaper_params,
891             cleanup,
892             aces_ctl_directory,
893             0)
894
895         cs.to_reference_transforms.append({
896             'type': 'lutFile',
897             'path': lut,
898             'interpolation': 'tetrahedral',
899             'direction': 'forward'})
900
901         shaper_inverse = shaper_ocio_transform.copy()
902         shaper_inverse['direction'] = 'forward'
903         cs.to_reference_transforms.append(shaper_inverse)
904
905     return cs
906
907
908 # -------------------------------------------------------------------------
909 # *LMTs*
910 # -------------------------------------------------------------------------
911 def create_LMTs(aces_ctl_directory,
912                 lut_directory,
913                 lut_resolution_1d,
914                 lut_resolution_3d,
915                 lmt_info,
916                 cleanup):
917     """
918     Create ColorSpaces representing the *ACES Look Transforms*
919
920     Parameters
921     ----------
922     aces_ctl_directory : str or unicode
923         The path to the aces 'transforms/ctl/utilities'
924     lut_directory : str or unicode 
925         The directory to use when generating LUTs
926     lut_resolution_1d : int
927         The resolution of generated 1D LUTs
928     lut_resolution_3d : int
929         The resolution of generated 3D LUTs
930     cleanup : bool
931         Whether or not to clean up the intermediate images 
932     aliases : list of str or unicode, optional
933         The alias names to use for the ColorSpace
934     lmt_info : dict
935         A collection of values that define the Look Transforms that need to be 
936         generated
937
938     Returns
939     -------
940     list of ColorSpaces
941          ColorSpaces representing the *ACES Look Transforms*
942     """
943
944     colorspaces = []
945
946     # -------------------------------------------------------------------------
947     # *LMT Shaper*
948     # -------------------------------------------------------------------------
949     lmt_lut_resolution_1d = max(4096, lut_resolution_1d)
950     lmt_lut_resolution_3d = max(65, lut_resolution_3d)
951
952     # Defining the *Log 2* shaper.
953     lmt_shaper_name = 'LMT Shaper'
954     lmt_shaper_name_aliases = ['crv_lmtshaper']
955     lmt_params = {
956         'middleGrey': 0.18,
957         'minExposure': -10,
958         'maxExposure': 6.5}
959
960     lmt_shaper = create_generic_log(aces_ctl_directory,
961                                     lut_directory,
962                                     lmt_lut_resolution_1d,
963                                     cleanup,
964                                     name=lmt_shaper_name,
965                                     middle_grey=lmt_params['middleGrey'],
966                                     min_exposure=lmt_params['minExposure'],
967                                     max_exposure=lmt_params['maxExposure'],
968                                     aliases=lmt_shaper_name_aliases)
969     colorspaces.append(lmt_shaper)
970
971     shaper_input_scale_generic_log2 = 1
972
973     # *Log 2* shaper name and *CTL* transforms bundled up.
974     lmt_shaper_data = [
975         lmt_shaper_name,
976         os.path.join('%s',
977                      'utilities',
978                      'ACESlib.Log2_to_Lin_param.a1.0.0.ctl'),
979         os.path.join('%s',
980                      'utilities',
981                      'ACESlib.Lin_to_Log2_param.a1.0.0.ctl'),
982         shaper_input_scale_generic_log2,
983         lmt_params]
984
985     sorted_lmts = sorted(lmt_info.iteritems(), key=lambda x: x[1])
986     print(sorted_lmts)
987     for lmt in sorted_lmts:
988         lmt_name, lmt_values = lmt
989         lmt_aliases = ['look_%s' % compact(lmt_values['transformUserName'])]
990         cs = create_ACES_LMT(
991             lmt_values['transformUserName'],
992             lmt_values,
993             lmt_shaper_data,
994             aces_ctl_directory,
995             lut_directory,
996             lmt_lut_resolution_3d,
997             cleanup,
998             lmt_aliases)
999         colorspaces.append(cs)
1000
1001     return colorspaces
1002
1003
1004 # -------------------------------------------------------------------------
1005 # *ACES RRT* with supplied *ODT*.
1006 # -------------------------------------------------------------------------
1007 def create_ACES_RRT_plus_ODT(odt_name,
1008                              odt_values,
1009                              shaper_info,
1010                              aces_ctl_directory,
1011                              lut_directory,
1012                              lut_resolution_3d=64,
1013                              cleanup=True,
1014                              aliases=None):
1015     """
1016     Creates an *ACES Output Transform (RRT + ODT)* colorspace.
1017
1018     Parameters
1019     ----------
1020     odt_name : str or unicode
1021         The name of the Output Transform (RRT + ODT)
1022     odt_values : dict
1023         A collection of values that define the Output Transform's attributes and behavior
1024     shaper_info : dict
1025         A collection of values that define the Shaper to use when generating LUTs to
1026         represent the Output Transform
1027     aces_ctl_directory : str or unicode
1028         The path to the aces 'transforms/ctl/utilities'
1029     lut_directory : str or unicode 
1030         The directory to use when generating LUTs
1031     lut_resolution_3d : int, optional
1032         The resolution of generated 3D LUTs
1033     cleanup : bool, optional
1034         Whether or not to clean up the intermediate images 
1035     aliases : list of str or unicode, optional
1036         The alias names to use for the ColorSpace
1037
1038     Returns
1039     -------
1040     ColorSpace
1041          An *ACES Output Transform (RRT + ODT)* colorspace.
1042     """
1043
1044     if aliases is None:
1045         aliases = []
1046
1047     cs = ColorSpace('%s' % odt_name)
1048     cs.description = '%s - %s Output Transform' % (
1049         odt_values['transformUserNamePrefix'], odt_name)
1050     cs.aliases = aliases
1051     cs.equality_group = ''
1052     cs.family = 'Output'
1053     cs.is_data = False
1054
1055     cs.aces_transform_id = odt_values['transformID']
1056
1057     pprint.pprint(odt_values)
1058
1059     # Generating the *shaper* transform.
1060     (shaper_name,
1061      shaper_to_aces_ctl,
1062      shaper_from_aces_ctl,
1063      shaper_input_scale,
1064      shaper_params) = shaper_info
1065
1066     if 'legalRange' in odt_values:
1067         shaper_params['legalRange'] = odt_values['legalRange']
1068     else:
1069         shaper_params['legalRange'] = 0
1070
1071     shaper_lut = '%s_to_linear.spi1d' % shaper_name
1072     shaper_lut = sanitize(shaper_lut)
1073
1074     shaper_ocio_transform = {
1075         'type': 'lutFile',
1076         'path': shaper_lut,
1077         'interpolation': 'linear',
1078         'direction': 'inverse'}
1079
1080     # Generating the *forward* transform.
1081     cs.from_reference_transforms = []
1082
1083     if 'transformLUT' in odt_values:
1084         transform_lut_file_name = os.path.basename(
1085             odt_values['transformLUT'])
1086         lut = os.path.join(lut_directory, transform_lut_file_name)
1087         shutil.copy(odt_values['transformLUT'], lut)
1088
1089         cs.from_reference_transforms.append(shaper_ocio_transform)
1090         cs.from_reference_transforms.append({
1091             'type': 'lutFile',
1092             'path': transform_lut_file_name,
1093             'interpolation': 'tetrahedral',
1094             'direction': 'forward'})
1095     elif 'transformCTL' in odt_values:
1096         ctls = [
1097             shaper_to_aces_ctl % aces_ctl_directory,
1098             os.path.join(aces_ctl_directory,
1099                          'rrt',
1100                          'RRT.a1.0.0.ctl'),
1101             os.path.join(aces_ctl_directory,
1102                          'odt',
1103                          odt_values['transformCTL'])]
1104         lut = '%s.RRT.a1.0.0.%s.spi3d' % (shaper_name, odt_name)
1105
1106         lut = sanitize(lut)
1107
1108         generate_3d_LUT_from_CTL(
1109             os.path.join(lut_directory, lut),
1110             ctls,
1111             lut_resolution_3d,
1112             'float',
1113             1 / shaper_input_scale,
1114             1,
1115             shaper_params,
1116             cleanup,
1117             aces_ctl_directory)
1118
1119         cs.from_reference_transforms.append(shaper_ocio_transform)
1120         cs.from_reference_transforms.append({
1121             'type': 'lutFile',
1122             'path': lut,
1123             'interpolation': 'tetrahedral',
1124             'direction': 'forward'})
1125
1126     # Generating the *inverse* transform.
1127     cs.to_reference_transforms = []
1128
1129     if 'transformLUTInverse' in odt_values:
1130         transform_lut_inverse_file_name = os.path.basename(
1131             odt_values['transformLUTInverse'])
1132         lut = os.path.join(lut_directory, transform_lut_inverse_file_name)
1133         shutil.copy(odt_values['transformLUTInverse'], lut)
1134
1135         cs.to_reference_transforms.append({
1136             'type': 'lutFile',
1137             'path': transform_lut_inverse_file_name,
1138             'interpolation': 'tetrahedral',
1139             'direction': 'forward'})
1140
1141         shaper_inverse = shaper_ocio_transform.copy()
1142         shaper_inverse['direction'] = 'forward'
1143         cs.to_reference_transforms.append(shaper_inverse)
1144     elif 'transformCTLInverse' in odt_values:
1145         ctls = [os.path.join(aces_ctl_directory,
1146                              'odt',
1147                              odt_values['transformCTLInverse']),
1148                 os.path.join(aces_ctl_directory,
1149                              'rrt',
1150                              'InvRRT.a1.0.0.ctl'),
1151                 shaper_from_aces_ctl % aces_ctl_directory]
1152         lut = 'InvRRT.a1.0.0.%s.%s.spi3d' % (odt_name, shaper_name)
1153
1154         lut = sanitize(lut)
1155
1156         generate_3d_LUT_from_CTL(
1157             os.path.join(lut_directory, lut),
1158             ctls,
1159             lut_resolution_3d,
1160             'half',
1161             1,
1162             shaper_input_scale,
1163             shaper_params,
1164             cleanup,
1165             aces_ctl_directory)
1166
1167         cs.to_reference_transforms.append({
1168             'type': 'lutFile',
1169             'path': lut,
1170             'interpolation': 'tetrahedral',
1171             'direction': 'forward'})
1172
1173         shaper_inverse = shaper_ocio_transform.copy()
1174         shaper_inverse['direction'] = 'forward'
1175         cs.to_reference_transforms.append(shaper_inverse)
1176
1177     return cs
1178
1179 # -------------------------------------------------------------------------
1180 # *Log 2 Shapers*
1181 # -------------------------------------------------------------------------
1182 def create_shapers_log2(aces_ctl_directory,
1183                         lut_directory,
1184                         lut_resolution_1d,
1185                         cleanup,
1186                         shaper_name,
1187                         middle_grey,
1188                         min_exposure,
1189                         max_exposure):
1190     """
1191     Creates a *Log base 2* colorspace that covers a specific dynamic range
1192
1193     Parameters
1194     ----------
1195     aces_ctl_directory : str or unicode
1196         The path to the aces 'transforms/ctl/utilities'
1197     lut_directory : str or unicode 
1198         The directory to use when generating LUTs
1199     lut_resolution_1d : int
1200         The resolution of generated 1D LUTs
1201     cleanup : bool
1202         Whether or not to clean up the intermediate images 
1203     shaper_name : str or unicode, optional
1204         The name of the ColorSpace
1205     middle_grey : float
1206         The middle of the dynamic range covered by the transfer function
1207     min_exposure : float
1208         The offset from middle grey, in stops, that defines the low end of the dynamic 
1209         range covered by the transfer function
1210     max_exposure : float
1211         The offset from middle grey, in stops, that defines the high end of the dynamic 
1212         range covered by the transfer function
1213
1214     Returns
1215     -------
1216     ColorSpace
1217          A *Log base 2* colorspace that covers a specific dynamic range
1218     """
1219
1220     colorspaces = []
1221     shaper_data = {}
1222
1223     # Defining the *Log 2* shaper for *ODTs covering 48 nit output*.
1224     log2_shaper_name = shaper_name
1225     log2_shaper_name_aliases = ['crv_%s' % compact(log2_shaper_name)]
1226     log2_params = {
1227         'middleGrey': middle_grey,
1228         'minExposure': min_exposure,
1229         'maxExposure': max_exposure}
1230
1231     log2_shaper_colorspace = create_generic_log(
1232         aces_ctl_directory,
1233         lut_directory,
1234         lut_resolution_1d,
1235         cleanup,
1236         name=log2_shaper_name,
1237         middle_grey=log2_params['middleGrey'],
1238         min_exposure=log2_params['minExposure'],
1239         max_exposure=log2_params['maxExposure'],
1240         aliases=log2_shaper_name_aliases)
1241     colorspaces.append(log2_shaper_colorspace)
1242
1243     shaper_input_scale_generic_log2 = 1
1244
1245     # *Log 2* shaper name and *CTL* transforms bundled up.
1246     log2_shaper_data = [
1247         log2_shaper_name,
1248         os.path.join('%s',
1249                      'utilities',
1250                      'ACESlib.Log2_to_Lin_param.a1.0.0.ctl'),
1251         os.path.join('%s',
1252                      'utilities',
1253                      'ACESlib.Lin_to_Log2_param.a1.0.0.ctl'),
1254         shaper_input_scale_generic_log2,
1255         log2_params]
1256
1257     shaper_data[log2_shaper_name] = log2_shaper_data
1258
1259     # Defining the *Log2 shaper that includes the AP1* primaries.
1260     log2_shaper_api1_name = '%s - AP1' % log2_shaper_name
1261     log2_shaper_api1_colorspace = copy.deepcopy(log2_shaper_colorspace)
1262
1263     log2_shaper_api1_colorspace.name = log2_shaper_api1_name
1264     log2_shaper_api1_colorspace.description = (
1265         'The %s color space' % log2_shaper_api1_name)
1266     log2_shaper_api1_colorspace.aliases = [
1267         '%s_ap1' % compact(log2_shaper_name)]
1268     log2_shaper_api1_colorspace.equality_group = log2_shaper_api1_name
1269
1270     # *AP1* primaries to *AP0* primaries
1271     log2_shaper_api1_colorspace.to_reference_transforms.append({
1272         'type': 'matrix',
1273         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
1274         'direction': 'forward'
1275     })
1276     colorspaces.append(log2_shaper_api1_colorspace)
1277
1278     return shaper_data, colorspaces
1279
1280 # -------------------------------------------------------------------------
1281 # *Dolby PQ-based Shapers*
1282 # -------------------------------------------------------------------------
1283 def create_shapers_dolbypq(aces_ctl_directory,
1284                            lut_directory,
1285                            lut_resolution_1d,
1286                            cleanup,
1287                            shaper_name,
1288                            middle_grey,
1289                            min_exposure,
1290                            max_exposure):
1291     """
1292     Creates two *Dolby PQ* colorspaces, one with now gamut conversion, the other with
1293     the conversion from *ACES* *AP0* to *AP1*
1294
1295     Parameters
1296     ----------
1297     aces_ctl_directory : str or unicode
1298         The path to the aces 'transforms/ctl/utilities'
1299     lut_directory : str or unicode 
1300         The directory to use when generating LUTs
1301     lut_resolution_1d : int
1302         The resolution of generated 1D LUTs
1303     cleanup : bool
1304         Whether or not to clean up the intermediate images 
1305     shaper_name : str or unicode, optional
1306         The name of the ColorSpace
1307     middle_grey : float
1308         The middle of the dynamic range covered by the transfer function
1309     min_exposure : float
1310         The offset from middle grey, in stops, that defines the low end of the dynamic 
1311         range covered by the transfer function
1312     max_exposure : float
1313         The offset from middle grey, in stops, that defines the high end of the dynamic 
1314         range covered by the transfer function
1315
1316     Returns
1317     -------
1318     dict
1319         Values defining a Shaper
1320     list of ColorSpaces
1321          A list of *Dolby PQ* colorspaces that covers a specific dynamic range
1322     """
1323     colorspaces = []
1324     shaper_data = {}
1325
1326     # Define the *Dolby PQ Shaper that considers a fixed linear range*
1327     dolby_pq_shaper_name = shaper_name
1328     dolby_pq_shaper_name_aliases = ['crv_%s' % compact(dolby_pq_shaper_name)]
1329
1330     dolby_pq_params = {
1331         'middleGrey': middle_grey,
1332         'minExposure': min_exposure,
1333         'maxExposure': max_exposure}
1334
1335     dolby_pq_shaper_colorspace = create_Dolby_PQ_shaper(
1336         aces_ctl_directory,
1337         lut_directory,
1338         lut_resolution_1d,
1339         cleanup,
1340         name=dolby_pq_shaper_name,
1341         aliases=dolby_pq_shaper_name_aliases,
1342         middle_grey=dolby_pq_params['middleGrey'],
1343         min_exposure=dolby_pq_params['minExposure'],
1344         max_exposure=dolby_pq_params['maxExposure'])
1345     colorspaces.append(dolby_pq_shaper_colorspace)
1346
1347     # *Dolby PQ* shaper name and *CTL* transforms bundled up.
1348     dolby_pq_shaper_data = [
1349         dolby_pq_shaper_name,
1350         os.path.join('%s',
1351                      'utilities',
1352                      'ACESlib.OCIOshaper_to_Lin_param.a1.0.0.ctl'),
1353         os.path.join('%s',
1354                      'utilities',
1355                      'ACESlib.Lin_to_OCIOshaper_param.a1.0.0.ctl'),
1356         1.0,
1357         dolby_pq_params]
1358
1359     shaper_data[dolby_pq_shaper_name] = dolby_pq_shaper_data
1360
1361     # Defining the *Dolby PQ shaper that includes the AP1* primaries.
1362     dolby_pq_shaper_api1_name = '%s - AP1' % dolby_pq_shaper_name
1363     dolby_pq_shaper_api1_colorspace = copy.deepcopy(dolby_pq_shaper_colorspace)
1364
1365     dolby_pq_shaper_api1_colorspace.name = dolby_pq_shaper_api1_name
1366     dolby_pq_shaper_api1_colorspace.description = (
1367         'The %s color space' % dolby_pq_shaper_api1_name)
1368     dolby_pq_shaper_api1_colorspace.aliases = [
1369         '%s_ap1' % compact(dolby_pq_shaper_name)]
1370     dolby_pq_shaper_api1_colorspace.equality_group = dolby_pq_shaper_api1_name
1371
1372     # *AP1* primaries to *AP0* primaries
1373     dolby_pq_shaper_api1_colorspace.to_reference_transforms.append({
1374         'type': 'matrix',
1375         'matrix': mat44_from_mat33(ACES_AP1_TO_AP0),
1376         'direction': 'forward'
1377     })
1378     colorspaces.append(dolby_pq_shaper_api1_colorspace)
1379
1380     return shaper_data, colorspaces
1381
1382
1383 # -------------------------------------------------------------------------
1384 # *Shapers*
1385 # -------------------------------------------------------------------------
1386 def create_shapers(aces_ctl_directory,
1387                    lut_directory,
1388                    lut_resolution_1d,
1389                    cleanup):
1390
1391     """
1392     Creates sets of shaper colorspaces covering the *Log 2* and *Dolby PQ* 
1393     transfer functions and dynamic ranges suitable of use with the 48 nit, 
1394     1000 nit, 2000 nit and 4000 nit *ACES Output Transforms*
1395
1396     Parameters
1397     ----------
1398     aces_ctl_directory : str or unicode
1399         The path to the aces 'transforms/ctl/utilities'
1400     lut_directory : str or unicode 
1401         The directory to use when generating LUTs
1402     lut_resolution_1d : int
1403         The resolution of generated 1D LUTs
1404     cleanup : bool
1405         Whether or not to clean up the intermediate images 
1406
1407     Returns
1408     -------
1409     list of dicts
1410         Values defining a set of Shapers
1411     list of ColorSpaces
1412          A list of Shaper colorspaces that covers a varying dynamic ranges and
1413          transfer functions
1414     """
1415
1416     colorspaces = []
1417     shaper_data = {}
1418
1419     # Define the base *Log2 48 nits shaper*
1420     #
1421     (log2_48nits_shaper_data, 
1422      log2_48nits_colorspaces) = create_shapers_log2(aces_ctl_directory,
1423        lut_directory,
1424        lut_resolution_1d,
1425        cleanup,
1426        'Log2 48 nits Shaper',
1427        0.18,
1428        -6.5,
1429        6.5)
1430     colorspaces.extend(log2_48nits_colorspaces)
1431     shaper_data.update(log2_48nits_shaper_data)
1432
1433     # Define the base *Log2 1000 nits shaper*
1434     #
1435     (log2_1000nits_shaper_data, 
1436      log2_1000nits_colorspaces) = create_shapers_log2(aces_ctl_directory,
1437        lut_directory,
1438        lut_resolution_1d,
1439        cleanup,
1440        'Log2 1000 nits Shaper',
1441        0.18,
1442        -12.0,
1443        10.0)
1444     colorspaces.extend(log2_1000nits_colorspaces)
1445     shaper_data.update(log2_1000nits_shaper_data)
1446
1447     # Define the base *Log2 2000 nits shaper*
1448     #
1449     (log2_2000nits_shaper_data, 
1450      log2_2000nits_colorspaces) = create_shapers_log2(aces_ctl_directory,
1451        lut_directory,
1452        lut_resolution_1d,
1453        cleanup,
1454        'Log2 2000 nits Shaper',
1455        0.18,
1456        -12.0,
1457        11.0)
1458     colorspaces.extend(log2_2000nits_colorspaces)
1459     shaper_data.update(log2_2000nits_shaper_data)
1460
1461     # Define the base *Log2 4000 nits shaper*
1462     #
1463     (log2_4000nits_shaper_data, 
1464      log2_4000nits_colorspaces) = create_shapers_log2(aces_ctl_directory,
1465        lut_directory,
1466        lut_resolution_1d,
1467        cleanup,
1468        'Log2 4000 nits Shaper',
1469        0.18,
1470        -12.0,
1471        12.0)
1472     colorspaces.extend(log2_4000nits_colorspaces)
1473     shaper_data.update(log2_4000nits_shaper_data)
1474
1475     # Define the base *Dolby PQ transfer function*
1476     #
1477     dolby_pq_shaper_name = 'Dolby PQ 10000'
1478     dolby_pq_shaper_name_aliases = ['crv_%s' % 'dolbypq_10000']
1479
1480     dolby_pq_shaper_colorspace = create_Dolby_PQ(
1481         aces_ctl_directory,
1482         lut_directory,
1483         lut_resolution_1d,
1484         cleanup,
1485         name=dolby_pq_shaper_name,
1486         aliases=dolby_pq_shaper_name_aliases)
1487     colorspaces.append(dolby_pq_shaper_colorspace)
1488
1489     # *Dolby PQ* shaper name and *CTL* transforms bundled up.
1490     dolby_pq_shaper_data = [
1491         dolby_pq_shaper_name,
1492         os.path.join('%s',
1493                      'utilities',
1494                      'ACESlib.DolbyPQ_to_Lin.a1.0.0.ctl'),
1495         os.path.join('%s',
1496                      'utilities',
1497                      'ACESlib.Lin_to_DolbyPQ.a1.0.0.ctl'),
1498         1.0,
1499         {}]
1500
1501     shaper_data[dolby_pq_shaper_name] = dolby_pq_shaper_data
1502
1503     # Define the *Dolby PQ 48 nits shaper*
1504     #
1505     (dolbypq_48nits_shaper_data, 
1506      dolbypq_48nits_colorspaces) = create_shapers_dolbypq(aces_ctl_directory,
1507        lut_directory,
1508        lut_resolution_1d,
1509        cleanup,
1510        'Dolby PQ 48 nits Shaper',
1511        0.18,
1512        -6.5,
1513        6.5)
1514     colorspaces.extend(dolbypq_48nits_colorspaces)
1515     shaper_data.update(dolbypq_48nits_shaper_data)
1516
1517     # Define the *Dolby PQ 1000 nits shaper*
1518     #
1519     (dolbypq_1000nits_shaper_data, 
1520      dolbypq_1000nits_colorspaces) = create_shapers_dolbypq(aces_ctl_directory,
1521        lut_directory,
1522        lut_resolution_1d,
1523        cleanup,
1524        'Dolby PQ 1000 nits Shaper',
1525        0.18,
1526        -12.0,
1527        10.0)
1528     colorspaces.extend(dolbypq_1000nits_colorspaces)
1529     shaper_data.update(dolbypq_1000nits_shaper_data)
1530
1531     # Define the *Dolby PQ 2000 nits shaper*
1532     #
1533     (dolbypq_2000nits_shaper_data, 
1534      dolbypq_2000nits_colorspaces) = create_shapers_dolbypq(aces_ctl_directory,
1535        lut_directory,
1536        lut_resolution_1d,
1537        cleanup,
1538        'Dolby PQ 2000 nits Shaper',
1539        0.18,
1540        -12.0,
1541        11.0)
1542     colorspaces.extend(dolbypq_2000nits_colorspaces)
1543     shaper_data.update(dolbypq_2000nits_shaper_data)
1544
1545     # Define the *Dolby PQ 4000 nits shaper*
1546     #
1547     (dolbypq_4000nits_shaper_data, 
1548      dolbypq_4000nits_colorspaces) = create_shapers_dolbypq(aces_ctl_directory,
1549        lut_directory,
1550        lut_resolution_1d,
1551        cleanup,
1552        'Dolby PQ 4000 nits Shaper',
1553        0.18,
1554        -12.0,
1555        12.0)
1556     colorspaces.extend(dolbypq_4000nits_colorspaces)
1557     shaper_data.update(dolbypq_4000nits_shaper_data)
1558
1559     return shaper_data, colorspaces
1560
1561 # -------------------------------------------------------------------------
1562 # *ODTs*
1563 # -------------------------------------------------------------------------
1564 def create_ODTs(aces_ctl_directory,
1565                 lut_directory,
1566                 lut_resolution_1d,
1567                 lut_resolution_3d,
1568                 odt_info,
1569                 shaper_name,
1570                 cleanup,
1571                 linear_display_space,
1572                 log_display_space):
1573     """
1574     Create ColorSpaces representing the *ACES Output Transforms*
1575
1576     Parameters
1577     ----------
1578     aces_ctl_directory : str or unicode
1579         The path to the aces 'transforms/ctl/utilities'
1580     lut_directory : str or unicode 
1581         The directory to use when generating LUTs
1582     lut_resolution_1d : int
1583         The resolution of generated 1D LUTs
1584     lut_resolution_3d : int
1585         The resolution of generated 3D LUTs
1586     odt_info : dict
1587         A collection of values that define the Output Transforms that need to be 
1588         generated
1589     shaper_name : str or unicode, optional
1590         The name of Shaper ColorSpace to use when generating LUTs
1591     cleanup : bool
1592         Whether or not to clean up the intermediate images 
1593     linear_display_space : lstr or unicode
1594         The name of the ColorSpace to use for the raw or linear View
1595     log_display_space : lstr or unicode
1596         The name of the ColorSpace to use for the log View
1597
1598     Returns
1599     -------
1600     list of ColorSpaces
1601          ColorSpaces representing the *ACES Output Transforms*
1602     list of dicts
1603         Collections of names and ColorSpaces corresponding to the Displays and
1604         Views
1605     """
1606
1607     colorspaces = []
1608     displays = {}
1609
1610     # -------------------------------------------------------------------------
1611     # *RRT / ODT* Shaper Options
1612     # -------------------------------------------------------------------------
1613     shaper_data, shaper_colorspaces = create_shapers(aces_ctl_directory,
1614         lut_directory,
1615         lut_resolution_1d,
1616         cleanup)
1617
1618     colorspaces.extend(shaper_colorspaces)
1619
1620     # Assumes shaper has variants covering the range expected by the
1621     # 48 nit, 1000 nit, 2000 nit and 4000 nit Ouput Transforms 
1622     rrt_shaper_48nits = shaper_data[shaper_name]
1623     rrt_shaper_1000nits = shaper_data[shaper_name.replace("48 nits", "1000 nits")]
1624     rrt_shaper_2000nits = shaper_data[shaper_name.replace("48 nits", "2000 nits")]
1625     rrt_shaper_4000nits = shaper_data[shaper_name.replace("48 nits", "4000 nits")]
1626
1627     # *RRT + ODT* combinations.
1628     sorted_odts = sorted(odt_info.iteritems(), key=lambda x: x[1])
1629     print(sorted_odts)
1630     for odt in sorted_odts:
1631         (odt_name, odt_values) = odt
1632
1633         if odt_values['transformHasFullLegalSwitch']:
1634             odt_legal['legalRange'] = 0
1635
1636         odt_name_legal = odt_values['transformUserName']
1637         odt_legal = odt_values.copy()
1638         odt_aliases = ['out_%s' % compact(odt_name_legal)]
1639
1640         if odt_name_legal in ['P3-D60 PQ (1000 nits)']:
1641             rrt_shaper = rrt_shaper_1000nits
1642         elif odt_name_legal in ['P3-D60 PQ (2000 nits)']:
1643             rrt_shaper = rrt_shaper_2000nits
1644         elif odt_name_legal in ['P3-D60 PQ (4000 nits)']:
1645             rrt_shaper = rrt_shaper_4000nits
1646         else:
1647             rrt_shaper = rrt_shaper_48nits
1648
1649         cs = create_ACES_RRT_plus_ODT(
1650             odt_name_legal,
1651             odt_legal,
1652             rrt_shaper,
1653             aces_ctl_directory,
1654             lut_directory,
1655             lut_resolution_3d,
1656             cleanup,
1657             odt_aliases)
1658         colorspaces.append(cs)
1659
1660         displays[odt_name_legal] = {
1661             'Raw': linear_display_space,
1662             'Log': log_display_space,
1663             'Output Transform': cs}
1664
1665     return colorspaces, displays
1666
1667
1668 def get_transform_info(ctl_transform):
1669     """
1670     Returns the information stored in first couple of lines of an official
1671     *ACES Transform* CTL file
1672
1673     Parameters
1674     ----------
1675     ctl_transform : str or unicode
1676         The path to the CTL file to be scraped.
1677
1678     Returns
1679     -------
1680     tuple
1681          Combination of Transform ID, User Name, User Name Prefix and Full/Legal
1682          switch
1683     """
1684
1685     with open(ctl_transform, 'rb') as fp:
1686         lines = fp.readlines()
1687
1688     # Retrieving the *transform ID* and *User Name*.
1689     transform_id = lines[1][3:].split('<')[1].split('>')[1].strip()
1690     transform_user_name = '-'.join(
1691         lines[2][3:].split('<')[1].split('>')[1].split('-')[1:]).strip()
1692     transform_user_name_prefix = (
1693         lines[2][3:].split('<')[1].split('>')[1].split('-')[0].strip())
1694
1695     # Figuring out if this transform has options for processing *full* and
1696     # *legal* ranges.
1697     transform_full_legal_switch = False
1698     for line in lines:
1699         if line.strip() == 'input varying int legalRange = 0':
1700             # print( '%s has legal range flag' % transform_user_name)
1701             transform_full_legal_switch = True
1702             break
1703
1704     return (transform_id,
1705             transform_user_name,
1706             transform_user_name_prefix,
1707             transform_full_legal_switch)
1708
1709
1710 def get_ODTs_info(aces_ctl_directory):
1711     """
1712     Returns the information describing the names and CTL files associated with 
1713     the *ACES Output Transforms* in a given ACES release
1714
1715     Parameters
1716     ----------
1717     aces_ctl_directory : str or unicode
1718         The path to the base *ACES* CTL directory
1719
1720     Returns
1721     -------
1722     dict of dicts
1723          Collecton of dicts, one describing each *ACES Output Transform*
1724     """
1725
1726     # TODO: Investigate usage of *files_walker* definition here.
1727     # Credit to *Alex Fry* for the original approach here.
1728     odt_dir = os.path.join(aces_ctl_directory, 'odt')
1729     all_odt = []
1730     for dir_name, subdir_list, file_list in os.walk(odt_dir):
1731         for fname in file_list:
1732             all_odt.append((os.path.join(dir_name, fname)))
1733
1734     odt_ctls = [x for x in all_odt if
1735                 ('InvODT' not in x) and (os.path.split(x)[-1][0] != '.')]
1736
1737     odts = {}
1738
1739     for odt_ctl in odt_ctls:
1740         odt_tokens = os.path.split(odt_ctl)
1741
1742         # Handling nested directories.
1743         odt_path_tokens = os.path.split(odt_tokens[-2])
1744         odt_dir = odt_path_tokens[-1]
1745         while odt_path_tokens[-2][-3:] != 'odt':
1746             odt_path_tokens = os.path.split(odt_path_tokens[-2])
1747             odt_dir = os.path.join(odt_path_tokens[-1], odt_dir)
1748
1749         # Building full name.
1750         transform_ctl = odt_tokens[-1]
1751         odt_name = string.join(transform_ctl.split('.')[1:-1], '.')
1752
1753         # Finding id, user name and user name prefix.
1754         (transform_id,
1755          transform_user_name,
1756          transform_user_name_prefix,
1757          transform_full_legal_switch) = get_transform_info(
1758             os.path.join(aces_ctl_directory, 'odt', odt_dir, transform_ctl))
1759
1760         # Finding inverse.
1761         transform_ctl_inverse = 'InvODT.%s.ctl' % odt_name
1762         if not os.path.exists(
1763                 os.path.join(odt_tokens[-2], transform_ctl_inverse)):
1764             transform_ctl_inverse = None
1765
1766         # Adding to list of *ODTs*.
1767         odts[odt_name] = {}
1768         odts[odt_name]['transformCTL'] = os.path.join(odt_dir, transform_ctl)
1769         if transform_ctl_inverse is not None:
1770             odts[odt_name]['transformCTLInverse'] = os.path.join(
1771                 odt_dir, transform_ctl_inverse)
1772
1773         odts[odt_name]['transformID'] = transform_id
1774         odts[odt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1775         odts[odt_name]['transformUserName'] = transform_user_name
1776         odts[odt_name][
1777             'transformHasFullLegalSwitch'] = transform_full_legal_switch
1778
1779         forward_ctl = odts[odt_name]['transformCTL']
1780
1781         print('ODT : %s' % odt_name)
1782         print('\tTransform ID               : %s' % transform_id)
1783         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1784         print('\tTransform User Name        : %s' % transform_user_name)
1785         print(
1786             '\tHas Full / Legal Switch    : %s' % transform_full_legal_switch)
1787         print('\tForward ctl                : %s' % forward_ctl)
1788         if 'transformCTLInverse' in odts[odt_name]:
1789             inverse_ctl = odts[odt_name]['transformCTLInverse']
1790             print('\tInverse ctl                : %s' % inverse_ctl)
1791         else:
1792             print('\tInverse ctl                : %s' % 'None')
1793
1794     print('\n')
1795
1796     return odts
1797
1798
1799 def get_LMTs_info(aces_ctl_directory):
1800     """
1801     Returns the information describing the names and CTL files associated with 
1802     the *ACES Look Transforms* in a given ACES release
1803
1804     Parameters
1805     ----------
1806     aces_ctl_directory : str or unicode
1807         The path to the base *ACES* CTL directory
1808
1809     Returns
1810     -------
1811     dict of dicts
1812          Collecton of dicts, one describing each *ACES Look Transform*
1813     """
1814
1815     # TODO: Investigate refactoring with previous definition.
1816
1817     # Credit to Alex Fry for the original approach here
1818     lmt_dir = os.path.join(aces_ctl_directory, 'lmt')
1819     all_lmt = []
1820     for dir_name, subdir_list, file_list in os.walk(lmt_dir):
1821         for fname in file_list:
1822             all_lmt.append((os.path.join(dir_name, fname)))
1823
1824     lmt_ctls = [x for x in all_lmt if
1825                 ('InvLMT' not in x) and ('README' not in x) and (
1826                     os.path.split(x)[-1][0] != '.')]
1827
1828     lmts = {}
1829
1830     for lmt_ctl in lmt_ctls:
1831         lmt_tokens = os.path.split(lmt_ctl)
1832
1833         # Handlimg nested directories.
1834         lmt_path_tokens = os.path.split(lmt_tokens[-2])
1835         lmt_dir = lmt_path_tokens[-1]
1836         while lmt_path_tokens[-2][-3:] != 'ctl':
1837             lmt_path_tokens = os.path.split(lmt_path_tokens[-2])
1838             lmt_dir = os.path.join(lmt_path_tokens[-1], lmt_dir)
1839
1840         # Building full name.
1841         transform_ctl = lmt_tokens[-1]
1842         lmt_name = string.join(transform_ctl.split('.')[1:-1], '.')
1843
1844         # Finding id, user name and user name prefix.
1845         (transform_id,
1846          transform_user_name,
1847          transform_user_name_prefix,
1848          transform_full_legal_switch) = get_transform_info(
1849             os.path.join(aces_ctl_directory, lmt_dir, transform_ctl))
1850
1851         # Finding inverse.
1852         transform_ctl_inverse = 'InvLMT.%s.ctl' % lmt_name
1853         if not os.path.exists(
1854                 os.path.join(lmt_tokens[-2], transform_ctl_inverse)):
1855             transform_ctl_inverse = None
1856
1857         lmts[lmt_name] = {}
1858         lmts[lmt_name]['transformCTL'] = os.path.join(lmt_dir, transform_ctl)
1859         if transform_ctl_inverse is not None:
1860             lmts[lmt_name]['transformCTLInverse'] = os.path.join(
1861                 lmt_dir, transform_ctl_inverse)
1862
1863         lmts[lmt_name]['transformID'] = transform_id
1864         lmts[lmt_name]['transformUserNamePrefix'] = transform_user_name_prefix
1865         lmts[lmt_name]['transformUserName'] = transform_user_name
1866
1867         forward_ctl = lmts[lmt_name]['transformCTL']
1868
1869         print('LMT : %s' % lmt_name)
1870         print('\tTransform ID               : %s' % transform_id)
1871         print('\tTransform User Name Prefix : %s' % transform_user_name_prefix)
1872         print('\tTransform User Name        : %s' % transform_user_name)
1873         print('\t Forward ctl               : %s' % forward_ctl)
1874         if 'transformCTLInverse' in lmts[lmt_name]:
1875             inverse_ctl = lmts[lmt_name]['transformCTLInverse']
1876             print('\t Inverse ctl                : %s' % inverse_ctl)
1877         else:
1878             print('\t Inverse ctl                : %s' % 'None')
1879
1880     print('\n')
1881
1882     return lmts
1883
1884
1885 def create_colorspaces(aces_ctl_directory,
1886                        lut_directory,
1887                        lut_resolution_1d,
1888                        lut_resolution_3d,
1889                        lmt_info,
1890                        odt_info,
1891                        shaper_name,
1892                        cleanup):
1893     """
1894     Generates the *ACES* colorspaces, displays and views
1895
1896     Parameters
1897     ----------
1898     aces_ctl_directory : str or unicode
1899         The path to the aces 'transforms/ctl/utilities'
1900     lut_directory : str or unicode 
1901         The directory to use when generating LUTs
1902     lut_resolution_1d : int
1903         The resolution of generated 1D LUTs
1904     lut_resolution_3d : int
1905         The resolution of generated 3D LUTs
1906     lmt_info : dict
1907         A collection of values that define the Look Transforms that need to be 
1908         generated
1909     odt_info : dict
1910         A collection of values that define the Output Transforms that need to be 
1911         generated
1912     shaper_name : str or unicode, optional
1913         The name of Shaper ColorSpace to use when generating LUTs
1914     cleanup : bool
1915         Whether or not to clean up the intermediate images 
1916
1917     Returns
1918     -------
1919     tuple
1920          A collection of values defining
1921             the reference colorspace : ACES
1922             a list of the colorspaces created
1923             a list of the displays created
1924             a list of the general log colorspace
1925             a list of the role assignments
1926             the name of the default display
1927     """
1928
1929     colorspaces = []
1930
1931     ACES = create_ACES()
1932
1933     ACEScc = create_ACEScc(aces_ctl_directory, lut_directory,
1934                            lut_resolution_1d, cleanup,
1935                            min_value=-0.35840, max_value=1.468)
1936     colorspaces.append(ACEScc)
1937
1938     ACESproxy = create_ACESproxy(aces_ctl_directory, lut_directory,
1939                                  lut_resolution_1d, cleanup)
1940     colorspaces.append(ACESproxy)
1941
1942     ACEScg = create_ACEScg()
1943     colorspaces.append(ACEScg)
1944
1945     ADX10 = create_ADX(lut_directory, bit_depth=10)
1946     colorspaces.append(ADX10)
1947
1948     ADX16 = create_ADX(lut_directory, bit_depth=16)
1949     colorspaces.append(ADX16)
1950
1951     lmts = create_LMTs(aces_ctl_directory,
1952                        lut_directory,
1953                        lut_resolution_1d,
1954                        lut_resolution_3d,
1955                        lmt_info,
1956                        cleanup)
1957     colorspaces.extend(lmts)
1958
1959     odts, displays = create_ODTs(aces_ctl_directory,
1960                                  lut_directory,
1961                                  lut_resolution_1d,
1962                                  lut_resolution_3d,
1963                                  odt_info,
1964                                  shaper_name,
1965                                  cleanup,
1966                                  ACES,
1967                                  ACEScc)
1968     colorspaces.extend(odts)
1969
1970     # TODO: Investigate if there is a way to retrieve these values from *CTL*.
1971     default_display = 'sRGB (D60 sim.)'
1972     color_picking = 'Rec.709'
1973
1974     roles = {'color_picking': color_picking,
1975              'color_timing': ACEScc.name,
1976              'compositing_log': ACEScc.name,
1977              'data': '',
1978              'default': ACES.name,
1979              'matte_paint': ACEScc.name,
1980              'reference': '',
1981              'scene_linear': ACEScg.name,
1982              'texture_paint': '',
1983              'compositing_linear': ACEScg.name,
1984              'rendering': ACEScg.name}
1985
1986     return ACES, colorspaces, displays, ACEScc, roles, default_display