<commit_before>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <Python.h>

#include <OpenColorIO/OpenColorIO.h>

#include "PyProcessor.h"
#include "PyUtil.h"

#include <sstream>

OCIO_NAMESPACE_ENTER
{
    ///////////////////////////////////////////////////////////////////////////
    ///

    bool AddProcessorObjectToModule( PyObject* m )
    {
        PyOCIO_ProcessorType.tp_new = PyType_GenericNew;
        if ( PyType_Ready(&PyOCIO_ProcessorType) < 0 ) return false;

        Py_INCREF( &PyOCIO_ProcessorType );
        PyModule_AddObject(m, "Processor",
                (PyObject *)&PyOCIO_ProcessorType);

        return true;
    }

    PyObject * BuildConstPyProcessor(ConstProcessorRcPtr processor)
    {
        if (!processor)
        {
            Py_RETURN_NONE;
        }

        PyOCIO_Processor * pyProcessor = PyObject_New(
                PyOCIO_Processor, (PyTypeObject * ) &PyOCIO_ProcessorType);

        pyProcessor->constcppobj = new ConstProcessorRcPtr();
        *pyProcessor->constcppobj = processor;

        return ( PyObject * ) pyProcessor;
    }

    bool IsPyProcessor(PyObject * pyobject)
    {
        if(!pyobject) return false;
        return (PyObject_Type(pyobject) == (PyObject *) (&PyOCIO_ProcessorType));
    }

    ConstProcessorRcPtr GetConstProcessor(PyObject * pyobject)
    {
        if(!IsPyProcessor(pyobject))
        {
            throw Exception("PyObject must be an OCIO.Processor.");
        }

        PyOCIO_Processor * pyProcessor = reinterpret_cast<PyOCIO_Processor *> (pyobject);
        if(pyProcessor->constcppobj)
        {
            return *pyProcessor->constcppobj;
        }

        throw Exception("PyObject must be a valid OCIO.Processor.");
    }

    ///////////////////////////////////////////////////////////////////////////
    ///

    namespace
    {
        int PyOCIO_Processor_init( PyOCIO_Processor * self, PyObject * args, PyObject * kwds );
        void PyOCIO_Processor_delete( PyOCIO_Processor * self, PyObject * args );

        PyObject * PyOCIO_Processor_isNoOp( PyObject * self );
        PyObject * PyOCIO_Processor_applyRGB( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_applyRGBA( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getCpuCacheID( PyObject * self );

        PyObject * PyOCIO_Processor_getGpuShaderText( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getGpuShaderTextCacheID( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getGpuLut3D( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getGpuLut3DCacheID( PyObject * self, PyObject * args );

        ///////////////////////////////////////////////////////////////////////
        ///

        PyMethodDef PyOCIO_Processor_methods[] = {
            {"isNoOp", (PyCFunction) PyOCIO_Processor_isNoOp, METH_NOARGS, "" },
            {"applyRGB", PyOCIO_Processor_applyRGB, METH_VARARGS, "" },
            {"applyRGBA", PyOCIO_Processor_applyRGBA, METH_VARARGS, "" },
            {"getCpuCacheID", (PyCFunction) PyOCIO_Processor_getCpuCacheID, METH_NOARGS, "" },

            {"getGpuShaderText", PyOCIO_Processor_getGpuShaderText, METH_VARARGS, "" },
            {"getGpuShaderTextCacheID", PyOCIO_Processor_getGpuShaderTextCacheID, METH_VARARGS, "" },
            {"getGpuLut3D", PyOCIO_Processor_getGpuLut3D, METH_VARARGS, "" },
            {"getGpuLut3DCacheID", PyOCIO_Processor_getGpuLut3DCacheID, METH_VARARGS, "" },

            {NULL, NULL, 0, NULL}
        };

        const char initMessage[] =
            "Processor objects cannot be instantiated directly. "
            "Please use config.getProcessor() instead.";
    }

    ///////////////////////////////////////////////////////////////////////////
    ///

    PyTypeObject PyOCIO_ProcessorType = {
        PyObject_HEAD_INIT(NULL)
        0,                                          //ob_size
        "OCIO.Processor",                               //tp_name
        sizeof(PyOCIO_Processor),                       //tp_basicsize
        0,                                          //tp_itemsize
        (destructor)PyOCIO_Processor_delete,            //tp_dealloc
        0,                                          //tp_print
        0,                                          //tp_getattr
        0,                                          //tp_setattr
        0,                                          //tp_compare
        0,                                          //tp_repr
        0,                                          //tp_as_number
        0,                                          //tp_as_sequence
        0,                                          //tp_as_mapping
        0,                                          //tp_hash
        0,                                          //tp_call
        0,                                          //tp_str
        0,                                          //tp_getattro
        0,                                          //tp_setattro
        0,                                          //tp_as_buffer
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   //tp_flags
        "Processor",                                   //tp_doc
        0,                                          //tp_traverse
        0,                                          //tp_clear
        0,                                          //tp_richcompare
        0,                                          //tp_weaklistoffset
        0,                                          //tp_iter
        0,                                          //tp_iternext
        PyOCIO_Processor_methods,                       //tp_methods
        0,                                          //tp_members
        0,                                          //tp_getset
        0,                                          //tp_base
        0,                                          //tp_dict
        0,                                          //tp_descr_get
        0,                                          //tp_descr_set
        0,                                          //tp_dictoffset
        (initproc) PyOCIO_Processor_init,               //tp_init
        0,                                          //tp_alloc
        0,                                          //tp_new
        0,                                          //tp_free
        0,                                          //tp_is_gc
        0,                                          //tp_bases
        0,                                          //tp_mro
        0,                                          //tp_cache
        0,                                          //tp_subclasses
        0,                                          //tp_weaklist
        0,                                          //tp_del
        #if PY_VERSION_HEX > 0x02060000
        0,                                          //tp_version_tag
        #endif
    };

    ///////////////////////////////////////////////////////////////////////////
    ///

    namespace
    {
        // TODO: The use of a dict, rather than a native class is not ideal
        // in the next API revision, use a native type.

        void FillShaderDescFromPyDict(GpuShaderDesc & shaderDesc,
                                      PyObject * dict)
        {
            if(!PyDict_Check(dict))
            {
                throw Exception("GpuShaderDesc must be a dict type.");
            }

            PyObject *key, *value;
            Py_ssize_t pos = 0;

            while (PyDict_Next(dict, &pos, &key, &value))
            {
                std::string keystr;
                if(!GetStringFromPyObject(key, &keystr))
                    throw Exception("GpuShaderDesc keys must be strings.");

                if(keystr == "language")
                {
                    GpuLanguage language = GPU_LANGUAGE_UNKNOWN;
                    if(ConvertPyObjectToGpuLanguage(value, &language) == 0)
                        throw Exception("GpuShaderDesc language must be a GpuLanguage.");
                    shaderDesc.setLanguage(language);
                }
                else if(keystr == "functionName")
                {
                    std::string functionName;
                    if(!GetStringFromPyObject(value, &functionName))
                        throw Exception("GpuShaderDesc functionName must be a string.");
                    shaderDesc.setFunctionName(functionName.c_str());
                }
                else if(keystr == "lut3DEdgeLen")
                {
                    int lut3DEdgeLen = 0;
                    if(!GetIntFromPyObject(value, &lut3DEdgeLen))
                        throw Exception("GpuShaderDesc lut3DEdgeLen must be an integer.");
                    shaderDesc.setLut3DEdgeLen(lut3DEdgeLen);
                }
                else
                {
                    std::ostringstream os;
                    os << "Unknown GpuShaderDesc key, '";
                    os << keystr << "'. ";
                    os << "Allowed keys: (";
                    os << "'language', 'functionName', 'lut3DEdgeLen').";
                    throw Exception(os.str().c_str());
                }
            }
        }
    }

    namespace
    {
        ///////////////////////////////////////////////////////////////////////
        ///
        int PyOCIO_Processor_init( PyOCIO_Processor */*self*/,
            PyObject * /*args*/, PyObject * /*kwds*/ )
        {
            PyErr_SetString( PyExc_RuntimeError, initMessage);
            return -1;
        }

        void PyOCIO_Processor_delete( PyOCIO_Processor *self, PyObject * /*args*/ )
        {
            delete self->constcppobj;
            self->ob_type->tp_free((PyObject*)self);
        }

        ////////////////////////////////////////////////////////////////////////

        PyObject * PyOCIO_Processor_isNoOp( PyObject * self )
        {
            try
            {
                ConstProcessorRcPtr processor = GetConstProcessor(self);
                return PyBool_FromLong( processor->isNoOp() );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_applyRGB( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O:applyRGB", &pyData)) return NULL;

                ConstProcessorRcPtr processor = GetConstProcessor(self);
                if(processor->isNoOp())
                {
                    Py_INCREF(pyData);
                    return pyData;
                }

                std::vector<float> data;
                if(!FillFloatVectorFromPySequence(pyData, data) || ((data.size()%3) != 0))
                {
                    std::ostringstream os;
                    os << "First argument must be a float array, size multiple of 3. ";
                    os << "Size: " << data.size() << ".";
                    PyErr_SetString(PyExc_TypeError, os.str().c_str());
                    return 0;
                }

                PackedImageDesc img(&data[0], data.size()/3, 1, 3);
                processor->apply(img);

                return CreatePyListFromFloatVector(data);
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_applyRGBA( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O:applyRGBA", &pyData)) return NULL;

                ConstProcessorRcPtr processor = GetConstProcessor(self);
                if(processor->isNoOp())
                {
                    Py_INCREF(pyData);
                    return pyData;
                }

                std::vector<float> data;
                if(!FillFloatVectorFromPySequence(pyData, data) || ((data.size()%4) != 0))
                {
                    std::ostringstream os;
                    os << "First argument must be a float array, size multiple of 4. ";
                    os << "Size: " << data.size() << ".";
                    PyErr_SetString(PyExc_TypeError, os.str().c_str());
                    return 0;
                }

                PackedImageDesc img(&data[0], data.size()/4, 1, 4);
                processor->apply(img);

                return CreatePyListFromFloatVector(data);
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getCpuCacheID( PyObject * self )
        {
            try
            {
                ConstProcessorRcPtr processor = GetConstProcessor(self);
                return PyString_FromString( processor->getCpuCacheID() );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        ////////////////////////////////////////////////////////////////////////

        PyObject * PyOCIO_Processor_getGpuShaderText( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuShaderText",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                return PyString_FromString( processor->getGpuShaderText(shaderDesc) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getGpuShaderTextCacheID( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuShaderTextCacheID",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                return PyString_FromString( processor->getGpuShaderTextCacheID(shaderDesc) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getGpuLut3D( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuLut3D",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                int len = shaderDesc.getLut3DEdgeLen();
                std::vector<float> lut3d(3*len*len*len);

                // TODO: return more compact binary data? (ex array, ...)
                processor->getGpuLut3D(&lut3d[0], shaderDesc);
                return CreatePyListFromFloatVector(lut3d);
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getGpuLut3DCacheID( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuLut3DCacheID",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                return PyString_FromString( processor->getGpuLut3DCacheID(shaderDesc) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

    }

}
OCIO_NAMESPACE_EXIT
<commit_msg>pyglue: expose Processor.hasChannelCrosstalk<commit_after>/*
Copyright (c) 2003-2010 Sony Pictures Imageworks Inc., et al.
All Rights Reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are
met:
* Redistributions of source code must retain the above copyright
  notice, this list of conditions and the following disclaimer.
* Redistributions in binary form must reproduce the above copyright
  notice, this list of conditions and the following disclaimer in the
  documentation and/or other materials provided with the distribution.
* Neither the name of Sony Pictures Imageworks nor the names of its
  contributors may be used to endorse or promote products derived from
  this software without specific prior written permission.
THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS
"AS IS" AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT
LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR
A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT
OWNER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT
LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE,
DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY
THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/

#include <Python.h>

#include <OpenColorIO/OpenColorIO.h>

#include "PyProcessor.h"
#include "PyUtil.h"

#include <sstream>

OCIO_NAMESPACE_ENTER
{
    ///////////////////////////////////////////////////////////////////////////
    ///

    bool AddProcessorObjectToModule( PyObject* m )
    {
        PyOCIO_ProcessorType.tp_new = PyType_GenericNew;
        if ( PyType_Ready(&PyOCIO_ProcessorType) < 0 ) return false;

        Py_INCREF( &PyOCIO_ProcessorType );
        PyModule_AddObject(m, "Processor",
                (PyObject *)&PyOCIO_ProcessorType);

        return true;
    }

    PyObject * BuildConstPyProcessor(ConstProcessorRcPtr processor)
    {
        if (!processor)
        {
            Py_RETURN_NONE;
        }

        PyOCIO_Processor * pyProcessor = PyObject_New(
                PyOCIO_Processor, (PyTypeObject * ) &PyOCIO_ProcessorType);

        pyProcessor->constcppobj = new ConstProcessorRcPtr();
        *pyProcessor->constcppobj = processor;

        return ( PyObject * ) pyProcessor;
    }

    bool IsPyProcessor(PyObject * pyobject)
    {
        if(!pyobject) return false;
        return (PyObject_Type(pyobject) == (PyObject *) (&PyOCIO_ProcessorType));
    }

    ConstProcessorRcPtr GetConstProcessor(PyObject * pyobject)
    {
        if(!IsPyProcessor(pyobject))
        {
            throw Exception("PyObject must be an OCIO.Processor.");
        }

        PyOCIO_Processor * pyProcessor = reinterpret_cast<PyOCIO_Processor *> (pyobject);
        if(pyProcessor->constcppobj)
        {
            return *pyProcessor->constcppobj;
        }

        throw Exception("PyObject must be a valid OCIO.Processor.");
    }

    ///////////////////////////////////////////////////////////////////////////
    ///

    namespace
    {
        int PyOCIO_Processor_init( PyOCIO_Processor * self, PyObject * args, PyObject * kwds );
        void PyOCIO_Processor_delete( PyOCIO_Processor * self, PyObject * args );

        PyObject * PyOCIO_Processor_isNoOp( PyObject * self );
        PyObject * PyOCIO_Processor_hasChannelCrosstalk( PyObject * self );
        PyObject * PyOCIO_Processor_applyRGB( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_applyRGBA( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getCpuCacheID( PyObject * self );

        PyObject * PyOCIO_Processor_getGpuShaderText( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getGpuShaderTextCacheID( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getGpuLut3D( PyObject * self, PyObject * args );
        PyObject * PyOCIO_Processor_getGpuLut3DCacheID( PyObject * self, PyObject * args );

        ///////////////////////////////////////////////////////////////////////
        ///

        PyMethodDef PyOCIO_Processor_methods[] = {
            {"isNoOp", (PyCFunction) PyOCIO_Processor_isNoOp, METH_NOARGS, "" },
            {"hasChannelCrosstalk", (PyCFunction) PyOCIO_Processor_hasChannelCrosstalk, METH_NOARGS, "" },
            {"applyRGB", PyOCIO_Processor_applyRGB, METH_VARARGS, "" },
            {"applyRGBA", PyOCIO_Processor_applyRGBA, METH_VARARGS, "" },
            {"getCpuCacheID", (PyCFunction) PyOCIO_Processor_getCpuCacheID, METH_NOARGS, "" },

            {"getGpuShaderText", PyOCIO_Processor_getGpuShaderText, METH_VARARGS, "" },
            {"getGpuShaderTextCacheID", PyOCIO_Processor_getGpuShaderTextCacheID, METH_VARARGS, "" },
            {"getGpuLut3D", PyOCIO_Processor_getGpuLut3D, METH_VARARGS, "" },
            {"getGpuLut3DCacheID", PyOCIO_Processor_getGpuLut3DCacheID, METH_VARARGS, "" },

            {NULL, NULL, 0, NULL}
        };

        const char initMessage[] =
            "Processor objects cannot be instantiated directly. "
            "Please use config.getProcessor() instead.";
    }

    ///////////////////////////////////////////////////////////////////////////
    ///

    PyTypeObject PyOCIO_ProcessorType = {
        PyObject_HEAD_INIT(NULL)
        0,                                          //ob_size
        "OCIO.Processor",                               //tp_name
        sizeof(PyOCIO_Processor),                       //tp_basicsize
        0,                                          //tp_itemsize
        (destructor)PyOCIO_Processor_delete,            //tp_dealloc
        0,                                          //tp_print
        0,                                          //tp_getattr
        0,                                          //tp_setattr
        0,                                          //tp_compare
        0,                                          //tp_repr
        0,                                          //tp_as_number
        0,                                          //tp_as_sequence
        0,                                          //tp_as_mapping
        0,                                          //tp_hash
        0,                                          //tp_call
        0,                                          //tp_str
        0,                                          //tp_getattro
        0,                                          //tp_setattro
        0,                                          //tp_as_buffer
        Py_TPFLAGS_DEFAULT | Py_TPFLAGS_BASETYPE,   //tp_flags
        "Processor",                                   //tp_doc
        0,                                          //tp_traverse
        0,                                          //tp_clear
        0,                                          //tp_richcompare
        0,                                          //tp_weaklistoffset
        0,                                          //tp_iter
        0,                                          //tp_iternext
        PyOCIO_Processor_methods,                       //tp_methods
        0,                                          //tp_members
        0,                                          //tp_getset
        0,                                          //tp_base
        0,                                          //tp_dict
        0,                                          //tp_descr_get
        0,                                          //tp_descr_set
        0,                                          //tp_dictoffset
        (initproc) PyOCIO_Processor_init,               //tp_init
        0,                                          //tp_alloc
        0,                                          //tp_new
        0,                                          //tp_free
        0,                                          //tp_is_gc
        0,                                          //tp_bases
        0,                                          //tp_mro
        0,                                          //tp_cache
        0,                                          //tp_subclasses
        0,                                          //tp_weaklist
        0,                                          //tp_del
        #if PY_VERSION_HEX > 0x02060000
        0,                                          //tp_version_tag
        #endif
    };

    ///////////////////////////////////////////////////////////////////////////
    ///

    namespace
    {
        // TODO: The use of a dict, rather than a native class is not ideal
        // in the next API revision, use a native type.

        void FillShaderDescFromPyDict(GpuShaderDesc & shaderDesc,
                                      PyObject * dict)
        {
            if(!PyDict_Check(dict))
            {
                throw Exception("GpuShaderDesc must be a dict type.");
            }

            PyObject *key, *value;
            Py_ssize_t pos = 0;

            while (PyDict_Next(dict, &pos, &key, &value))
            {
                std::string keystr;
                if(!GetStringFromPyObject(key, &keystr))
                    throw Exception("GpuShaderDesc keys must be strings.");

                if(keystr == "language")
                {
                    GpuLanguage language = GPU_LANGUAGE_UNKNOWN;
                    if(ConvertPyObjectToGpuLanguage(value, &language) == 0)
                        throw Exception("GpuShaderDesc language must be a GpuLanguage.");
                    shaderDesc.setLanguage(language);
                }
                else if(keystr == "functionName")
                {
                    std::string functionName;
                    if(!GetStringFromPyObject(value, &functionName))
                        throw Exception("GpuShaderDesc functionName must be a string.");
                    shaderDesc.setFunctionName(functionName.c_str());
                }
                else if(keystr == "lut3DEdgeLen")
                {
                    int lut3DEdgeLen = 0;
                    if(!GetIntFromPyObject(value, &lut3DEdgeLen))
                        throw Exception("GpuShaderDesc lut3DEdgeLen must be an integer.");
                    shaderDesc.setLut3DEdgeLen(lut3DEdgeLen);
                }
                else
                {
                    std::ostringstream os;
                    os << "Unknown GpuShaderDesc key, '";
                    os << keystr << "'. ";
                    os << "Allowed keys: (";
                    os << "'language', 'functionName', 'lut3DEdgeLen').";
                    throw Exception(os.str().c_str());
                }
            }
        }
    }

    namespace
    {
        ///////////////////////////////////////////////////////////////////////
        ///
        int PyOCIO_Processor_init( PyOCIO_Processor */*self*/,
            PyObject * /*args*/, PyObject * /*kwds*/ )
        {
            PyErr_SetString( PyExc_RuntimeError, initMessage);
            return -1;
        }

        void PyOCIO_Processor_delete( PyOCIO_Processor *self, PyObject * /*args*/ )
        {
            delete self->constcppobj;
            self->ob_type->tp_free((PyObject*)self);
        }

        ////////////////////////////////////////////////////////////////////////

        PyObject * PyOCIO_Processor_isNoOp( PyObject * self )
        {
            try
            {
                ConstProcessorRcPtr processor = GetConstProcessor(self);
                return PyBool_FromLong( processor->isNoOp() );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_hasChannelCrosstalk( PyObject * self )
        {
            try
            {
                ConstProcessorRcPtr processor = GetConstProcessor(self);
                return PyBool_FromLong( processor->hasChannelCrosstalk() );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_applyRGB( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O:applyRGB", &pyData)) return NULL;

                ConstProcessorRcPtr processor = GetConstProcessor(self);
                if(processor->isNoOp())
                {
                    Py_INCREF(pyData);
                    return pyData;
                }

                std::vector<float> data;
                if(!FillFloatVectorFromPySequence(pyData, data) || ((data.size()%3) != 0))
                {
                    std::ostringstream os;
                    os << "First argument must be a float array, size multiple of 3. ";
                    os << "Size: " << data.size() << ".";
                    PyErr_SetString(PyExc_TypeError, os.str().c_str());
                    return 0;
                }

                PackedImageDesc img(&data[0], data.size()/3, 1, 3);
                processor->apply(img);

                return CreatePyListFromFloatVector(data);
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_applyRGBA( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O:applyRGBA", &pyData)) return NULL;

                ConstProcessorRcPtr processor = GetConstProcessor(self);
                if(processor->isNoOp())
                {
                    Py_INCREF(pyData);
                    return pyData;
                }

                std::vector<float> data;
                if(!FillFloatVectorFromPySequence(pyData, data) || ((data.size()%4) != 0))
                {
                    std::ostringstream os;
                    os << "First argument must be a float array, size multiple of 4. ";
                    os << "Size: " << data.size() << ".";
                    PyErr_SetString(PyExc_TypeError, os.str().c_str());
                    return 0;
                }

                PackedImageDesc img(&data[0], data.size()/4, 1, 4);
                processor->apply(img);

                return CreatePyListFromFloatVector(data);
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getCpuCacheID( PyObject * self )
        {
            try
            {
                ConstProcessorRcPtr processor = GetConstProcessor(self);
                return PyString_FromString( processor->getCpuCacheID() );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        ////////////////////////////////////////////////////////////////////////

        PyObject * PyOCIO_Processor_getGpuShaderText( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuShaderText",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                return PyString_FromString( processor->getGpuShaderText(shaderDesc) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getGpuShaderTextCacheID( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuShaderTextCacheID",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                return PyString_FromString( processor->getGpuShaderTextCacheID(shaderDesc) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getGpuLut3D( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuLut3D",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                int len = shaderDesc.getLut3DEdgeLen();
                std::vector<float> lut3d(3*len*len*len);

                // TODO: return more compact binary data? (ex array, ...)
                processor->getGpuLut3D(&lut3d[0], shaderDesc);
                return CreatePyListFromFloatVector(lut3d);
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

        PyObject * PyOCIO_Processor_getGpuLut3DCacheID( PyObject * self, PyObject * args )
        {
            try
            {
                PyObject * pyData = 0;
                if (!PyArg_ParseTuple(args,"O!:getGpuLut3DCacheID",
                    &PyDict_Type, &pyData)) return NULL;
                ConstProcessorRcPtr processor = GetConstProcessor(self);

                GpuShaderDesc shaderDesc;
                FillShaderDescFromPyDict(shaderDesc, pyData);

                return PyString_FromString( processor->getGpuLut3DCacheID(shaderDesc) );
            }
            catch(...)
            {
                Python_Handle_Exception();
                return NULL;
            }
        }

    }

}
OCIO_NAMESPACE_EXIT
<|endoftext|>


<commit_before>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "absl/container/flat_hash_map.h"
#include "gmock/gmock.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "src/test/cc/testutil/matchers.h"
#include "src/test/cc/testutil/status_macros.h"
#include "wfa/virtual_people/core/model/model_node.h"
#include "wfa/virtual_people/core/model/model_node_factory.h"

namespace wfa_virtual_people {
namespace {

using ::testing::DoubleNear;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
using ::wfa::IsOk;
using ::wfa::StatusIs;

constexpr int kFingerprintNumber = 10000;

TEST(BranchNodeImplTest, TestApplyBranchWithNodeByChance) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a population node always
  // assigns virtual person id 10.
  // The other branch is selected with 60% chance, which is a population node
  // always assigns virtual person id 20.
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node {
            population_node {
              pools {
                population_offset: 10
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          chance: 0.4
        }
        branches {
          node {
            population_node {
              pools {
                population_offset: 20
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> node,
      ModelNodeFactory().NewModelNode(config));

  absl::flat_hash_map<int64_t, double> id_counts;
  for (int fingerprint = 0; fingerprint < kFingerprintNumber; ++fingerprint) {
    LabelerEvent input;
    input.set_acting_fingerprint(fingerprint);
    EXPECT_THAT(node->Apply(input), IsOk());
    ++id_counts[input.virtual_person_activities(0).virtual_person_id()];
  }
  for (auto& [key, value] : id_counts) {
    value /= static_cast<double>(kFingerprintNumber);
  }
  // Absolute error more than 2% is very unlikely.
  EXPECT_THAT(id_counts, UnorderedElementsAre(
      Pair(10, DoubleNear(0.4, 0.02)),
      Pair(20, DoubleNear(0.6, 0.02))));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeIndexByChance) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a population node always
  // assigns virtual person id 10.
  // The other branch is selected with 60% chance, which is a population node
  // always assigns virtual person id 20.
  CompiledNode branch_node_config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.4
        }
        branches {
          node_index: 3
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &branch_node_config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> branch_node,
      ModelNodeFactory().NewModelNode(branch_node_config));

  // Set up map from indexes to child nodes.
  absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs;

  CompiledNode population_node_config_1;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestPopulationNode1"
      index: 2
      population_node {
        pools {
          population_offset: 10
          total_population: 1
        }
        random_seed: "TestPopulationNodeSeed1"
      }
  )pb", &population_node_config_1));
  ASSERT_OK_AND_ASSIGN(
      node_refs[2],
      ModelNodeFactory().NewModelNode(population_node_config_1));

  CompiledNode population_node_config_2;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestPopulationNode2"
      index: 3
      population_node {
        pools {
          population_offset: 20
          total_population: 1
        }
        random_seed: "TestPopulationNodeSeed2"
      }
  )pb", &population_node_config_2));
  ASSERT_OK_AND_ASSIGN(
      node_refs[3],
      ModelNodeFactory().NewModelNode(population_node_config_2));

  EXPECT_THAT(branch_node->ResolveChildReferences(node_refs), IsOk());

  absl::flat_hash_map<int64_t, double> id_counts;
  for (int fingerprint = 0; fingerprint < kFingerprintNumber; ++fingerprint) {
    LabelerEvent input;
    input.set_acting_fingerprint(fingerprint);
    EXPECT_THAT(branch_node->Apply(input), IsOk());
    ++id_counts[input.virtual_person_activities(0).virtual_person_id()];
  }
  for (auto& [key, value] : id_counts) {
    value /= static_cast<double>(kFingerprintNumber);
  }
  // Absolute error more than 2% is very unlikely.
  EXPECT_THAT(id_counts, UnorderedElementsAre(
      Pair(10, DoubleNear(0.4, 0.02)),
      Pair(20, DoubleNear(0.6, 0.02))));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeByCondition) {
  // The branch node has 2 branches.
  // One branch is selected if person_country_code is "country_code_1", which is
  // a population node always assigns virtual person id 10.
  // The other branch is selected if person_country_code is "country_code_2",
  // which is a population node always assigns virtual person id 20.
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node {
            population_node {
              pools {
                population_offset: 10
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          condition {
            name: "person_country_code"
            op: EQUAL
            value: "country_code_1"
          }
        }
        branches {
          node {
            population_node {
              pools {
                population_offset: 20
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          condition {
            name: "person_country_code"
            op: EQUAL
            value: "country_code_2"
          }
        }
      }
  )pb", &config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> node,
      ModelNodeFactory().NewModelNode(config));

  LabelerEvent input_1;
  input_1.set_person_country_code("country_code_1");
  EXPECT_THAT(node->Apply(input_1), IsOk());
  EXPECT_EQ(input_1.virtual_person_activities(0).virtual_person_id(), 10);

  LabelerEvent input_2;
  input_2.set_person_country_code("country_code_2");
  EXPECT_THAT(node->Apply(input_2), IsOk());
  EXPECT_EQ(input_2.virtual_person_activities(0).virtual_person_id(), 20);

  // No branch matches. Returns error status.
  LabelerEvent input_3;
  input_3.set_person_country_code("country_code_3");
  EXPECT_THAT(
      node->Apply(input_3),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeIndexNotResolved) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a population node always
  // assigns virtual person id 10.
  // The other branch is selected with 60% chance, which is a population node
  // always assigns virtual person id 20.
  CompiledNode branch_node_config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.4
        }
        branches {
          node_index: 3
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &branch_node_config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> branch_node,
      ModelNodeFactory().NewModelNode(branch_node_config));

  LabelerEvent input;
  input.set_acting_fingerprint(0);
  EXPECT_THAT(
    branch_node->Apply(input),
    StatusIs(absl::StatusCode::kFailedPrecondition, ""));
}

TEST(BranchNodeImplTest, TestNoBranch) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {}
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestNoChildNode) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          chance: 0.5
        }
      }
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestNoSelectBy) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
        }
      }
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestDifferentSelectBy) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.5
        }
        branches {
          node_index: 3
          condition {}
        }
      }
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestResolveChildReferencesIndexNotFound) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 1
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> node,
      ModelNodeFactory().NewModelNode(config));

  absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs;
  EXPECT_THAT(
      node->ResolveChildReferences(node_refs),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

}  // namespace
}  // namespace wfa_virtual_people
<commit_msg>Add a test for resolving node indexes recursively.<commit_after>// Copyright 2021 The Cross-Media Measurement Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
//      http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.

#include "absl/container/flat_hash_map.h"
#include "gmock/gmock.h"
#include "google/protobuf/text_format.h"
#include "gtest/gtest.h"
#include "src/main/proto/wfa/virtual_people/common/model.pb.h"
#include "src/test/cc/testutil/matchers.h"
#include "src/test/cc/testutil/status_macros.h"
#include "wfa/virtual_people/core/model/model_node.h"
#include "wfa/virtual_people/core/model/model_node_factory.h"

namespace wfa_virtual_people {
namespace {

using ::testing::DoubleNear;
using ::testing::Pair;
using ::testing::UnorderedElementsAre;
using ::wfa::IsOk;
using ::wfa::StatusIs;

constexpr int kFingerprintNumber = 10000;

TEST(BranchNodeImplTest, TestApplyBranchWithNodeByChance) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a population node always
  // assigns virtual person id 10.
  // The other branch is selected with 60% chance, which is a population node
  // always assigns virtual person id 20.
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node {
            population_node {
              pools {
                population_offset: 10
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          chance: 0.4
        }
        branches {
          node {
            population_node {
              pools {
                population_offset: 20
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> node,
      ModelNodeFactory().NewModelNode(config));

  absl::flat_hash_map<int64_t, double> id_counts;
  for (int fingerprint = 0; fingerprint < kFingerprintNumber; ++fingerprint) {
    LabelerEvent input;
    input.set_acting_fingerprint(fingerprint);
    EXPECT_THAT(node->Apply(input), IsOk());
    ++id_counts[input.virtual_person_activities(0).virtual_person_id()];
  }
  for (auto& [key, value] : id_counts) {
    value /= static_cast<double>(kFingerprintNumber);
  }
  // Absolute error more than 2% is very unlikely.
  EXPECT_THAT(id_counts, UnorderedElementsAre(
      Pair(10, DoubleNear(0.4, 0.02)),
      Pair(20, DoubleNear(0.6, 0.02))));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeIndexByChance) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a population node always
  // assigns virtual person id 10.
  // The other branch is selected with 60% chance, which is a population node
  // always assigns virtual person id 20.
  CompiledNode branch_node_config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.4
        }
        branches {
          node_index: 3
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &branch_node_config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> branch_node,
      ModelNodeFactory().NewModelNode(branch_node_config));

  // Set up map from indexes to child nodes.
  absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs;

  CompiledNode population_node_config_1;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestPopulationNode1"
      index: 2
      population_node {
        pools {
          population_offset: 10
          total_population: 1
        }
        random_seed: "TestPopulationNodeSeed1"
      }
  )pb", &population_node_config_1));
  ASSERT_OK_AND_ASSIGN(
      node_refs[2],
      ModelNodeFactory().NewModelNode(population_node_config_1));

  CompiledNode population_node_config_2;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestPopulationNode2"
      index: 3
      population_node {
        pools {
          population_offset: 20
          total_population: 1
        }
        random_seed: "TestPopulationNodeSeed2"
      }
  )pb", &population_node_config_2));
  ASSERT_OK_AND_ASSIGN(
      node_refs[3],
      ModelNodeFactory().NewModelNode(population_node_config_2));

  EXPECT_THAT(branch_node->ResolveChildReferences(node_refs), IsOk());

  absl::flat_hash_map<int64_t, double> id_counts;
  for (int fingerprint = 0; fingerprint < kFingerprintNumber; ++fingerprint) {
    LabelerEvent input;
    input.set_acting_fingerprint(fingerprint);
    EXPECT_THAT(branch_node->Apply(input), IsOk());
    ++id_counts[input.virtual_person_activities(0).virtual_person_id()];
  }
  for (auto& [key, value] : id_counts) {
    value /= static_cast<double>(kFingerprintNumber);
  }
  // Absolute error more than 2% is very unlikely.
  EXPECT_THAT(id_counts, UnorderedElementsAre(
      Pair(10, DoubleNear(0.4, 0.02)),
      Pair(20, DoubleNear(0.6, 0.02))));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeByCondition) {
  // The branch node has 2 branches.
  // One branch is selected if person_country_code is "country_code_1", which is
  // a population node always assigns virtual person id 10.
  // The other branch is selected if person_country_code is "country_code_2",
  // which is a population node always assigns virtual person id 20.
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node {
            population_node {
              pools {
                population_offset: 10
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          condition {
            name: "person_country_code"
            op: EQUAL
            value: "country_code_1"
          }
        }
        branches {
          node {
            population_node {
              pools {
                population_offset: 20
                total_population: 1
              }
              random_seed: "TestPopulationNodeSeed1"
            }
          }
          condition {
            name: "person_country_code"
            op: EQUAL
            value: "country_code_2"
          }
        }
      }
  )pb", &config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> node,
      ModelNodeFactory().NewModelNode(config));

  LabelerEvent input_1;
  input_1.set_person_country_code("country_code_1");
  EXPECT_THAT(node->Apply(input_1), IsOk());
  EXPECT_EQ(input_1.virtual_person_activities(0).virtual_person_id(), 10);

  LabelerEvent input_2;
  input_2.set_person_country_code("country_code_2");
  EXPECT_THAT(node->Apply(input_2), IsOk());
  EXPECT_EQ(input_2.virtual_person_activities(0).virtual_person_id(), 20);

  // No branch matches. Returns error status.
  LabelerEvent input_3;
  input_3.set_person_country_code("country_code_3");
  EXPECT_THAT(
      node->Apply(input_3),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeIndexResolvedRecursively) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a branch node refers to a
  // single population node always assigning virtual person id 10.
  // The other branch is selected with 60% chance, which is a branch node refers
  // to a single population node always assigning virtual person id 20.
  CompiledNode branch_node_config_1;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode1"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.4
        }
        branches {
          node_index: 3
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed1"
      }
  )pb", &branch_node_config_1));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> branch_node_1,
      ModelNodeFactory().NewModelNode(branch_node_config_1));

  // Set up map from indexes to child nodes.
  absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs;

  CompiledNode branch_node_config_2;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode2"
      index: 2
      branch_node {
        branches {
          node_index: 4
          chance: 1
        }
        random_seed: "TestBranchNodeSeed2"
      }
  )pb", &branch_node_config_2));
  ASSERT_OK_AND_ASSIGN(
      node_refs[2],
      ModelNodeFactory().NewModelNode(branch_node_config_2));

  CompiledNode branch_node_config_3;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode3"
      index: 3
      branch_node {
        branches {
          node_index: 5
          chance: 1
        }
        random_seed: "TestBranchNodeSeed3"
      }
  )pb", &branch_node_config_3));
  ASSERT_OK_AND_ASSIGN(
      node_refs[3],
      ModelNodeFactory().NewModelNode(branch_node_config_3));

  CompiledNode population_node_config_1;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestPopulationNode1"
      index: 4
      population_node {
        pools {
          population_offset: 10
          total_population: 1
        }
        random_seed: "TestPopulationNodeSeed1"
      }
  )pb", &population_node_config_1));
  ASSERT_OK_AND_ASSIGN(
      node_refs[4],
      ModelNodeFactory().NewModelNode(population_node_config_1));

  CompiledNode population_node_config_2;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestPopulationNode2"
      index: 5
      population_node {
        pools {
          population_offset: 20
          total_population: 1
        }
        random_seed: "TestPopulationNodeSeed2"
      }
  )pb", &population_node_config_2));
  ASSERT_OK_AND_ASSIGN(
      node_refs[5],
      ModelNodeFactory().NewModelNode(population_node_config_2));

  EXPECT_THAT(branch_node_1->ResolveChildReferences(node_refs), IsOk());

  absl::flat_hash_map<int64_t, double> id_counts;
  for (int fingerprint = 0; fingerprint < kFingerprintNumber; ++fingerprint) {
    LabelerEvent input;
    input.set_acting_fingerprint(fingerprint);
    EXPECT_THAT(branch_node_1->Apply(input), IsOk());
    ++id_counts[input.virtual_person_activities(0).virtual_person_id()];
  }
  for (auto& [key, value] : id_counts) {
    value /= static_cast<double>(kFingerprintNumber);
  }
  // Absolute error more than 2% is very unlikely.
  EXPECT_THAT(id_counts, UnorderedElementsAre(
      Pair(10, DoubleNear(0.4, 0.02)),
      Pair(20, DoubleNear(0.6, 0.02))));
}

TEST(BranchNodeImplTest, TestApplyBranchWithNodeIndexNotResolved) {
  // The branch node has 2 branches.
  // One branch is selected with 40% chance, which is a population node always
  // assigns virtual person id 10.
  // The other branch is selected with 60% chance, which is a population node
  // always assigns virtual person id 20.
  CompiledNode branch_node_config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.4
        }
        branches {
          node_index: 3
          chance: 0.6
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &branch_node_config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> branch_node,
      ModelNodeFactory().NewModelNode(branch_node_config));

  LabelerEvent input;
  input.set_acting_fingerprint(0);
  EXPECT_THAT(
    branch_node->Apply(input),
    StatusIs(absl::StatusCode::kFailedPrecondition, ""));
}

TEST(BranchNodeImplTest, TestNoBranch) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {}
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestNoChildNode) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          chance: 0.5
        }
      }
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestNoSelectBy) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
        }
      }
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestDifferentSelectBy) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 0.5
        }
        branches {
          node_index: 3
          condition {}
        }
      }
  )pb", &config));
  EXPECT_THAT(
      ModelNodeFactory().NewModelNode(config).status(),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

TEST(BranchNodeImplTest, TestResolveChildReferencesIndexNotFound) {
  CompiledNode config;
  ASSERT_TRUE(google::protobuf::TextFormat::ParseFromString(R"pb(
      name: "TestBranchNode"
      index: 1
      branch_node {
        branches {
          node_index: 2
          chance: 1
        }
        random_seed: "TestBranchNodeSeed"
      }
  )pb", &config));
  ASSERT_OK_AND_ASSIGN(
      std::unique_ptr<ModelNode> node,
      ModelNodeFactory().NewModelNode(config));

  absl::flat_hash_map<uint32_t, std::unique_ptr<ModelNode>> node_refs;
  EXPECT_THAT(
      node->ResolveChildReferences(node_refs),
      StatusIs(absl::StatusCode::kInvalidArgument, ""));
}

}  // namespace
}  // namespace wfa_virtual_people
<|endoftext|>


<commit_before>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "commandlinehandlerbase.h"

// appleseed.shared headers.
#include "application/superlogger.h"

// appleseed.foundation headers.
#include "foundation/core/appleseed.h"
#include "foundation/platform/compiler.h"
#include "foundation/platform/system.h"
#include "foundation/utility/commandlineparser.h"
#include "foundation/utility/log.h"

// Boost headers.
#include "boost/filesystem/path.hpp"

// Standard headers.
#include <cstdlib>
#include <string>

using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;

namespace appleseed {
namespace shared {

struct CommandLineHandlerBase::Impl
{
    const string                m_application_name;

    FlagOptionHandler           m_help;
    FlagOptionHandler           m_version;
    FlagOptionHandler           m_system;
    ValueOptionHandler<string>  m_message_verbosity;
    FlagOptionHandler           m_message_coloring;
    FlagOptionHandler           m_display_options;

    string                      m_executable_name;
    CommandLineParser           m_parser;
    ParseResults                m_parse_results;

    explicit Impl(const char* application_name)
      : m_application_name(application_name)
    {
    }
};

CommandLineHandlerBase::CommandLineHandlerBase(const char* application_name)
  : impl(new Impl(application_name))
{
}

void CommandLineHandlerBase::add_default_options()
{
    add_help_option();
    add_version_option();
    add_system_option();
    add_message_verbosity_option();
    add_message_coloring_option();
    add_display_options_option();
}

void CommandLineHandlerBase::add_help_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_help
            .add_name("--help")
            .add_name("-h")
            .set_description("print program usage and exit"));
}

void CommandLineHandlerBase::add_version_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_version
            .add_name("--version")
            .add_name("-v")
            .set_description("print program version"));
}

void CommandLineHandlerBase::add_system_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_system
            .add_name("--system")
            .set_description("print system information"));
}

void CommandLineHandlerBase::add_message_verbosity_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_message_verbosity
            .add_name("--message-verbosity")
            .set_description("set message verbosity")
            .set_syntax("level")
            .set_exact_value_count(1));
}

void CommandLineHandlerBase::add_message_coloring_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_message_coloring
            .add_name("--message-coloring")
            .set_description("enable message coloring"));
}

void CommandLineHandlerBase::add_display_options_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_display_options
            .add_name("--display-options")
            .set_description("display the recognized command line options"));
}

CommandLineHandlerBase::~CommandLineHandlerBase()
{
    delete impl;
}

void CommandLineHandlerBase::parse(const int argc, const char* argv[], SuperLogger& logger)
{
    impl->m_executable_name = bf::path(argv[0]).filename().string();

    impl->m_parser.parse(argc, argv, impl->m_parse_results);

    if (impl->m_help.is_set())
    {
        print_program_usage(impl->m_executable_name.c_str(), logger);
        exit(EXIT_SUCCESS);
    }

    if (impl->m_message_coloring.is_set())
        logger.enable_message_coloring();

    if (impl->m_message_verbosity.is_set())
        logger.set_verbosity_level_from_string(impl->m_message_verbosity.value().c_str());
}

void CommandLineHandlerBase::apply(SuperLogger& logger)
{
    if (impl->m_version.is_set())
        print_version_information(logger);

    if (impl->m_system.is_set())
        System::print_information(logger);

    if (impl->m_display_options.is_set())
    {
        LOG_INFO(logger, "recognized options:");
        impl->m_parser.print_recognized_options(logger);
    }

    impl->m_parse_results.m_messages.print(logger);

    if (impl->m_parse_results.m_errors > 0 ||
        impl->m_parse_results.m_warnings > 0)
    {
        LOG(
            logger,
            impl->m_parse_results.m_errors > 0 ? LogMessage::Fatal : LogMessage::Warning,
            FMT_SIZE_T " error%s, " FMT_SIZE_T " warning%s encountered while parsing the command line.",
            impl->m_parse_results.m_errors,
            impl->m_parse_results.m_errors > 1 ? "s" : "",
            impl->m_parse_results.m_warnings,
            impl->m_parse_results.m_warnings > 1 ? "s" : "");
    }
}

CommandLineParser& CommandLineHandlerBase::parser()
{
    return impl->m_parser;
}

const CommandLineParser& CommandLineHandlerBase::parser() const
{
    return impl->m_parser;
}

void CommandLineHandlerBase::print_version_information(SuperLogger& logger) const
{
    LOG_INFO(
        logger,
        "%s, using %s version %s, %s configuration\n"
        "compiled on %s at %s using %s version %s\n"
        "copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited.\n"
        "copyright (c) 2014-2017 The appleseedhq Organization.\n"
        "this software is released under the MIT license (http://opensource.org/licenses/MIT).\n"
        "visit http://appleseedhq.net/ for additional information and resources.",
        impl->m_application_name.c_str(),
        Appleseed::get_lib_name(),
        Appleseed::get_lib_version(),
        Appleseed::get_lib_configuration(),
        Appleseed::get_lib_compilation_date(),
        Appleseed::get_lib_compilation_time(),
        Compiler::get_compiler_name(),
        Compiler::get_compiler_version());
}

}   // namespace shared
}   // namespace appleseed
<commit_msg>Give precedence to message coloring & verbosity set from command line<commit_after>
//
// This source file is part of appleseed.
// Visit http://appleseedhq.net/ for additional information and resources.
//
// This software is released under the MIT license.
//
// Copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited
// Copyright (c) 2014-2017 Francois Beaune, The appleseedhq Organization
//
// Permission is hereby granted, free of charge, to any person obtaining a copy
// of this software and associated documentation files (the "Software"), to deal
// in the Software without restriction, including without limitation the rights
// to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
// copies of the Software, and to permit persons to whom the Software is
// furnished to do so, subject to the following conditions:
//
// The above copyright notice and this permission notice shall be included in
// all copies or substantial portions of the Software.
//
// THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
// IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
// FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
// AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
// LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
// OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
// THE SOFTWARE.
//

// Interface header.
#include "commandlinehandlerbase.h"

// appleseed.shared headers.
#include "application/superlogger.h"

// appleseed.foundation headers.
#include "foundation/core/appleseed.h"
#include "foundation/platform/compiler.h"
#include "foundation/platform/system.h"
#include "foundation/utility/commandlineparser.h"
#include "foundation/utility/log.h"

// Boost headers.
#include "boost/filesystem/path.hpp"

// Standard headers.
#include <cstdlib>
#include <string>

using namespace foundation;
using namespace std;
namespace bf = boost::filesystem;

namespace appleseed {
namespace shared {

struct CommandLineHandlerBase::Impl
{
    const string                m_application_name;

    FlagOptionHandler           m_help;
    FlagOptionHandler           m_version;
    FlagOptionHandler           m_system;
    ValueOptionHandler<string>  m_message_verbosity;
    FlagOptionHandler           m_message_coloring;
    FlagOptionHandler           m_display_options;

    string                      m_executable_name;
    CommandLineParser           m_parser;
    ParseResults                m_parse_results;

    explicit Impl(const char* application_name)
      : m_application_name(application_name)
    {
    }
};

CommandLineHandlerBase::CommandLineHandlerBase(const char* application_name)
  : impl(new Impl(application_name))
{
}

void CommandLineHandlerBase::add_default_options()
{
    add_help_option();
    add_version_option();
    add_system_option();
    add_message_verbosity_option();
    add_message_coloring_option();
    add_display_options_option();
}

void CommandLineHandlerBase::add_help_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_help
            .add_name("--help")
            .add_name("-h")
            .set_description("print program usage and exit"));
}

void CommandLineHandlerBase::add_version_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_version
            .add_name("--version")
            .add_name("-v")
            .set_description("print program version"));
}

void CommandLineHandlerBase::add_system_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_system
            .add_name("--system")
            .set_description("print system information"));
}

void CommandLineHandlerBase::add_message_verbosity_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_message_verbosity
            .add_name("--message-verbosity")
            .set_description("set message verbosity")
            .set_syntax("level")
            .set_exact_value_count(1));
}

void CommandLineHandlerBase::add_message_coloring_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_message_coloring
            .add_name("--message-coloring")
            .set_description("enable message coloring"));
}

void CommandLineHandlerBase::add_display_options_option()
{
    impl->m_parser.add_option_handler(
        &impl->m_display_options
            .add_name("--display-options")
            .set_description("display the recognized command line options"));
}

CommandLineHandlerBase::~CommandLineHandlerBase()
{
    delete impl;
}

void CommandLineHandlerBase::parse(const int argc, const char* argv[], SuperLogger& logger)
{
    impl->m_executable_name = bf::path(argv[0]).filename().string();

    impl->m_parser.parse(argc, argv, impl->m_parse_results);

    if (impl->m_help.is_set())
    {
        print_program_usage(impl->m_executable_name.c_str(), logger);
        exit(EXIT_SUCCESS);
    }

    //
    // Apply message coloring and verbosity settings a first time just after having
    // parsed the command line.
    //

    if (impl->m_message_coloring.is_set())
        logger.enable_message_coloring();

    if (impl->m_message_verbosity.is_set())
        logger.set_verbosity_level_from_string(impl->m_message_verbosity.value().c_str());
}

void CommandLineHandlerBase::apply(SuperLogger& logger)
{
    //
    // At this point, a settings file may have been loaded and applied, and message
    // coloring and verbosity settings set in parse() may have been overridden.
    // Apply them again here such that command line parameters have precedence.
    //

    if (impl->m_message_coloring.is_set())
        logger.enable_message_coloring();

    if (impl->m_message_verbosity.is_set())
        logger.set_verbosity_level_from_string(impl->m_message_verbosity.value().c_str());

    if (impl->m_version.is_set())
        print_version_information(logger);

    if (impl->m_system.is_set())
        System::print_information(logger);

    if (impl->m_display_options.is_set())
    {
        LOG_INFO(logger, "recognized options:");
        impl->m_parser.print_recognized_options(logger);
    }

    impl->m_parse_results.m_messages.print(logger);

    if (impl->m_parse_results.m_errors > 0 ||
        impl->m_parse_results.m_warnings > 0)
    {
        LOG(
            logger,
            impl->m_parse_results.m_errors > 0 ? LogMessage::Fatal : LogMessage::Warning,
            FMT_SIZE_T " error%s, " FMT_SIZE_T " warning%s encountered while parsing the command line.",
            impl->m_parse_results.m_errors,
            impl->m_parse_results.m_errors > 1 ? "s" : "",
            impl->m_parse_results.m_warnings,
            impl->m_parse_results.m_warnings > 1 ? "s" : "");
    }
}

CommandLineParser& CommandLineHandlerBase::parser()
{
    return impl->m_parser;
}

const CommandLineParser& CommandLineHandlerBase::parser() const
{
    return impl->m_parser;
}

void CommandLineHandlerBase::print_version_information(SuperLogger& logger) const
{
    LOG_INFO(
        logger,
        "%s, using %s version %s, %s configuration\n"
        "compiled on %s at %s using %s version %s\n"
        "copyright (c) 2010-2013 Francois Beaune, Jupiter Jazz Limited.\n"
        "copyright (c) 2014-2017 The appleseedhq Organization.\n"
        "this software is released under the MIT license (http://opensource.org/licenses/MIT).\n"
        "visit http://appleseedhq.net/ for additional information and resources.",
        impl->m_application_name.c_str(),
        Appleseed::get_lib_name(),
        Appleseed::get_lib_version(),
        Appleseed::get_lib_configuration(),
        Appleseed::get_lib_compilation_date(),
        Appleseed::get_lib_compilation_time(),
        Compiler::get_compiler_name(),
        Compiler::get_compiler_version());
}

}   // namespace shared
}   // namespace appleseed
<|endoftext|>