text:
/*
    This file is part of Mitsuba, a physically based rendering system.

    Copyright (c) 2007-2014 by Wenzel Jakob and others.

    Mitsuba is free software; you can redistribute it and/or modify
    it under the terms of the GNU General Public License Version 3
    as published by the Free Software Foundation.

    Mitsuba is distributed in the hope that it will be useful,
    but WITHOUT ANY WARRANTY; without even the implied warranty of
    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
    GNU General Public License for more details.

    You should have received a copy of the GNU General Public License
    along with this program. If not, see <http://www.gnu.org/licenses/>.
*/

#include <mitsuba/render/film.h>
#include <mitsuba/core/fstream.h>
#include <mitsuba/core/bitmap.h>
#include <mitsuba/core/statistics.h>
#include <boost/algorithm/string.hpp>
#include "banner.h"
#include "annotations.h"

MTS_NAMESPACE_BEGIN

/*!\plugin{hdrfilm}{High dynamic range film}
 * \order{1}
 * \parameters{
 *     \parameter{width, height}{\Integer}{
 *       Width and height of the camera sensor in pixels
 *       \default{768, 576}
 *     }
 *     \parameter{fileFormat}{\String}{
 *       Denotes the desired output file format. The options
 *       are \code{openexr} (for ILM's OpenEXR format),
 *       \code{rgbe} (for Greg Ward's RGBE format),
 *       or \code{pfm} (for the Portable Float Map format)
 *       \default{\code{openexr}}
 *     }
 *     \parameter{pixelFormat}{\String}{Specifies the desired pixel format
 *         of output images. The options are \code{luminance},
 *         \code{luminanceAlpha}, \code{rgb}, \code{rgba}, \code{xyz},
 *         \code{xyza}, \code{spectrum}, and \code{spectrumAlpha}.
 *         For the \code{spectrum*} options, the number of written channels depends on
 *         the value assigned to \code{SPECTRUM\_SAMPLES} during compilation
 *         (see \secref{compiling} for details)
 *         \default{\code{rgb}}
 *     }
 *     \parameter{componentFormat}{\String}{Specifies the desired floating
 *         point component format of output images. The options are
 *         \code{float16}, \code{float32}, or \code{uint32}.
 *         \default{\code{float16}}
 *     }
 *     \parameter{cropOffsetX, cropOffsetY, cropWidth, cropHeight}{\Integer}{
 *       These parameters can optionally be provided to select a sub-rectangle
 *       of the output. In this case, Mitsuba will only render the requested
 *       regions. \default{Unused}
 *     }
 *     \parameter{attachLog}{\Boolean}{Mitsuba can optionally attach
 *         the entire rendering log file as a metadata field so that this
 *         information is permanently saved.
 *         \default{\code{true}, i.e. attach it}
 *     }
 *     \parameter{banner}{\Boolean}{Include a small Mitsuba banner in the
 *         output image? \default{\code{true}}
 *     }
 *     \parameter{highQualityEdges}{\Boolean}{
 *        If set to \code{true}, regions slightly outside of the film
 *        plane will also be sampled. This may improve the image
 *        quality at the edges, especially when using very large
 *        reconstruction filters. In general, this is not needed though.
 *        \default{\code{false}, i.e. disabled}
 *     }
 *     \parameter{\Unnamed}{\RFilter}{Reconstruction filter that should
 *     be used by the film. \default{\code{gaussian}, a windowed Gaussian filter}}
 * }
 *
 * This is the default film plugin that is used when none is explicitly
 * specified. It stores the captured image as a high dynamic range OpenEXR file
 * and tries to preserve the rendering as much as possible by not performing any
 * kind of post processing, such as gamma correction---the output file
 * will record linear radiance values.
 *
 * When writing OpenEXR files, the film will either produce a luminance, luminance/alpha,
 * RGB(A), XYZ(A) tristimulus, or spectrum/spectrum-alpha-based bitmap having a
 * \code{float16}, \code{float32}, or \code{uint32}-based internal representation
 * based on the chosen parameters.
 * The default configuration is RGB with a \code{float16} component format,
 * which is appropriate for most purposes. Note that the spectral output options
 * only make sense when using a custom build of Mitsuba that has spectral
 * rendering enabled (this is not the case for the downloadable release builds).
 * For OpenEXR files, Mitsuba also supports fully general multi-channel output;
 * refer to the \pluginref{multichannel} plugin for details on how this works.
 *
 * The plugin can also write RLE-compressed files in the Radiance RGBE format
 * pioneered by Greg Ward (set \code{fileFormat=rgbe}), as well as the
 * Portable Float Map format (set \code{fileFormat=pfm}).
 * In the former case,
 * the \code{componentFormat} and \code{pixelFormat} parameters are ignored,
 * and the output is ``\code{float8}''-compressed RGB data.
 * PFM output is restricted to \code{float32}-valued images using the
 * \code{rgb} or \code{luminance} pixel formats.
 * Due to the superior accuracy and adoption of OpenEXR, the use of these
 * two alternative formats is discouraged however.
 *
 * When RGB(A) output is selected, the measured spectral power distributions are
 * converted to linear RGB based on the CIE 1931 XYZ color matching curves and
 * the ITU-R Rec. BT.709-3 primaries with a D65 white point.
 *
 * \begin{xml}[caption=Instantiation of a film that writes a full-HD RGBA OpenEXR file without the Mitsuba banner]
 * <film type="hdrfilm">
 *     <string name="pixelFormat" value="rgba"/>
 *     <integer name="width" value="1920"/>
 *     <integer name="height" value="1080"/>
 *     <boolean name="banner" value="false"/>
 * </film>
 * \end{xml}
 *
 * \subsubsection*{Render-time annotations:}
 * \label{sec:film-annotations}
 * The \pluginref{ldrfilm} and \pluginref{hdrfilm} plugins support a
 * feature referred to as \emph{render-time annotations} to facilitate
 * record keeping.
 * Annotations are used to embed useful information inside a rendered image so
 * that this information is later available to anyone viewing the image.
 * Exemplary uses of this feature might be to store the frame or take number,
 * rendering time, memory usage, camera parameters, or other relevant scene
 * information.
 *
 * Currently, two different types are supported: a \code{metadata} annotation
 * creates an entry in the metadata table of the image, which is preferable
 * when the image contents should not be touched. Alternatively, a \code{label}
 * annotation creates a line of text that is overlaid on top of the image. Note
 * that this is only visible when opening the output file (i.e. the line is not
 * shown in the interactive viewer).
 * The syntax of this looks as follows:
 *
 * \begin{xml}
 * <film type="hdrfilm">
 *  <!-- Create a new metadata entry 'my_tag_name' and set it to the
 *       value 'my_tag_value' -->
 *  <string name="metadata['key_name']" value="Hello!"/>
 *
 *  <!-- Add the label 'Hello' at the image position X=50, Y=80 -->
 *  <string name="label[50, 80]" value="Hello!"/>
 * </film>
 * \end{xml}
 *
 * The \code{value="..."} argument may also include certain keywords that will be
 * evaluated and substituted when the rendered image is written to disk. A list all available
 * keywords is provided in Table~\ref{tbl:film-keywords}.
 *
 * Apart from querying the render time,
 * memory usage, and other scene-related information, it is also possible
 * to `paste' an existing parameter that was provided to another plugin---for instance,
 * the camera transform matrix would be obtained as \code{\$sensor['toWorld']}. The name of
 * the active integrator plugin is given by \code{\$integrator['type']}, and so on.
 * All of these can be mixed to build larger fragments, as following example demonstrates.
 * The result of this annotation is shown in Figure~\ref{fig:annotation-example}.
 * \begin{xml}[mathescape=false]
 * <string name="label[10, 10]" value="Integrator: $integrator['type'],
 *   $film['width']x$film['height'], $sampler['sampleCount'] spp,
 *   render time: $scene['renderTime'], memory: $scene['memUsage']"/>
 * \end{xml}
 * \vspace{1cm}
 * \renderings{
 * \fbox{\includegraphics[width=.8\textwidth]{images/annotation_example}}\hfill\,
 * \caption{\label{fig:annotation-example}A demonstration of the label annotation feature
 *  given the example string shown above.}
 * }
 * \vspace{2cm}
 * \begin{table}[htb]
 * \centering
 * \begin{savenotes}
 * \begin{tabular}{ll}
 * \toprule
 * \code{\$scene['renderTime']}& Image render time, use \code{renderTimePrecise} for more digits.\\
 * \code{\$scene['memUsage']}& Mitsuba memory usage\footnote{The definition of this quantity unfortunately
 * varies a bit from platform to platform. On Linux and Windows, it denotes the total
 * amount of allocated RAM and disk-based memory that is private to the process (i.e. not
 * shared or shareable), which most intuitively captures the amount of memory required for
 * rendering. On OSX, it denotes the working set size---roughly speaking, this is the
 * amount of RAM apportioned to the process (i.e. excluding disk-based memory).}.
 * Use \code{memUsagePrecise} for more digits.\\
 * \code{\$scene['coreCount']}& Number of local and remote cores working on the rendering job\\
 * \code{\$scene['blockSize']}& Block size used to parallelize up the rendering workload\\
 * \code{\$scene['sourceFile']}& Source file name\\
 * \code{\$scene['destFile']}& Destination file name\\
 * \code{\$integrator['..']}& Copy a named integrator parameter\\
 * \code{\$sensor['..']}& Copy a named sensor parameter\\
 * \code{\$sampler['..']}& Copy a named sampler parameter\\
 * \code{\$film['..']}& Copy a named film parameter\\
 * \bottomrule
 * \end{tabular}
 * \end{savenotes}
 * \caption{\label{tbl:film-keywords}A list of all special
 * keywords supported by the annotation feature}
 * \end{table}
 *
 */

class HDRFilm : public Film {
public:
    HDRFilm(const Properties &props) : Film(props) {
        /* Should an Mitsuba banner be added to the output image? */
        m_banner = props.getBoolean("banner", true);
        /* Attach the log file as the EXR comment attribute? */
        m_attachLog = props.getBoolean("attachLog", true);

        std::string fileFormat = boost::to_lower_copy(
            props.getString("fileFormat", "openexr"));
        std::vector<std::string> pixelFormats = tokenize(boost::to_lower_copy(
            props.getString("pixelFormat", "rgb")), " ,");
        std::vector<std::string> channelNames = tokenize(
            props.getString("channelNames", ""), ", ");
        std::string componentFormat = boost::to_lower_copy(
            props.getString("componentFormat", "float16"));

        if (fileFormat == "openexr") {
            m_fileFormat = Bitmap::EOpenEXR;
        } else if (fileFormat == "rgbe") {
            m_fileFormat = Bitmap::ERGBE;
        } else if (fileFormat == "pfm") {
            m_fileFormat = Bitmap::EPFM;
        } else {
            Log(EError, "The \"fileFormat\" parameter must either be "
                "equal to \"openexr\", \"pfm\", or \"rgbe\"!");
        }

        if (pixelFormats.empty())
            Log(EError, "At least one pixel format must be specified!");

        if ((pixelFormats.size() != 1 && channelNames.size() != pixelFormats.size()) ||
            (pixelFormats.size() == 1 && channelNames.size() > 1))
            Log(EError, "Number of channel names must match the number of specified pixel formats!");

        if (pixelFormats.size() != 1 && m_fileFormat != Bitmap::EOpenEXR)
            Log(EError, "General multi-channel output is only supported when writing OpenEXR files!");

        for (size_t i=0; i<pixelFormats.size(); ++i) {
            std::string pixelFormat = pixelFormats[i];
            std::string name = i < channelNames.size() ? (channelNames[i] + std::string(".")) : "";

            if (pixelFormat == "luminance") {
                m_pixelFormats.push_back(Bitmap::ELuminance);
                m_channelNames.push_back(name + "Y");
            } else if (pixelFormat == "luminancealpha") {
                m_pixelFormats.push_back(Bitmap::ELuminanceAlpha);
                m_channelNames.push_back(name + "Y");
                m_channelNames.push_back(name + "A");
            } else if (pixelFormat == "rgb") {
                m_pixelFormats.push_back(Bitmap::ERGB);
                m_channelNames.push_back(name + "R");
                m_channelNames.push_back(name + "G");
                m_channelNames.push_back(name + "B");
            } else if (pixelFormat == "rgba") {
                m_pixelFormats.push_back(Bitmap::ERGBA);
                m_channelNames.push_back(name + "R");
                m_channelNames.push_back(name + "G");
                m_channelNames.push_back(name + "B");
                m_channelNames.push_back(name + "A");
            } else if (pixelFormat == "xyz") {
                m_pixelFormats.push_back(Bitmap::EXYZ);
                m_channelNames.push_back(name + "X");
                m_channelNames.push_back(name + "Y");
                m_channelNames.push_back(name + "Z");
            } else if (pixelFormat == "xyza") {
                m_pixelFormats.push_back(Bitmap::EXYZA);
                m_channelNames.push_back(name + "X");
                m_channelNames.push_back(name + "Y");
                m_channelNames.push_back(name + "Z");
                m_channelNames.push_back(name + "A");
            } else if (pixelFormat == "spectrum") {
                m_pixelFormats.push_back(Bitmap::ESpectrum);
                for (int i=0; i<SPECTRUM_SAMPLES; ++i) {
                    std::pair<Float, Float> coverage = Spectrum::getBinCoverage(i);
                    m_channelNames.push_back(name + formatString("%.2f-%.2fnm", coverage.first, coverage.second));
                }
            } else if (pixelFormat == "spectrumalpha") {
                m_pixelFormats.push_back(Bitmap::ESpectrumAlpha);
                for (int i=0; i<SPECTRUM_SAMPLES; ++i) {
                    std::pair<Float, Float> coverage = Spectrum::getBinCoverage(i);
                    m_channelNames.push_back(name + formatString("%.2f-%.2fnm", coverage.first, coverage.second));
                }
                m_channelNames.push_back(name + "A");
            } else {
                Log(EError, "The \"pixelFormat\" parameter must either be equal to "
                    "\"luminance\", \"luminanceAlpha\", \"rgb\", \"rgba\", \"xyz\", \"xyza\", "
                    "\"spectrum\", or \"spectrumAlpha\"!");
            }
        }

        for (size_t i=0; i<m_pixelFormats.size(); ++i) {
            if (SPECTRUM_SAMPLES == 3 && (m_pixelFormats[i] == Bitmap::ESpectrum || m_pixelFormats[i] == Bitmap::ESpectrumAlpha))
                Log(EError, "You requested to render a spectral image, but Mitsuba is currently "
                    "configured for a RGB flow (i.e. SPECTRUM_SAMPLES = 3). You will need to recompile "
                    "it with a different configuration. Please see the documentation for details.");
        }

        if (componentFormat == "float16") {
            m_componentFormat = Bitmap::EFloat16;
        } else if (componentFormat == "float32") {
            m_componentFormat = Bitmap::EFloat32;
        } else if (componentFormat == "uint32") {
            m_componentFormat = Bitmap::EUInt32;
        } else {
            Log(EError, "The \"componentFormat\" parameter must either be "
                "equal to \"float16\", \"float32\", or \"uint32\"!");
        }

        if (m_fileFormat == Bitmap::ERGBE) {
            /* RGBE output; override pixel & component format if necessary */
            if (m_pixelFormats.size() != 1)
                Log(EError, "The RGBE format does not support general multi-channel images!");
            if (m_pixelFormats[0] != Bitmap::ERGB) {
                Log(EWarn, "The RGBE format only supports pixelFormat=\"rgb\". Overriding..");
                m_pixelFormats[0] = Bitmap::ERGB;
            }
            if (m_componentFormat != Bitmap::EFloat32) {
                Log(EWarn, "The RGBE format only supports componentFormat=\"float32\". Overriding..");
                m_componentFormat = Bitmap::EFloat32;
            }
        } else if (m_fileFormat == Bitmap::EPFM) {
            /* PFM output; override pixel & component format if necessary */
            if (m_pixelFormats.size() != 1)
                Log(EError, "The PFM format does not support general multi-channel images!");
            if (m_pixelFormats[0] != Bitmap::ERGB && m_pixelFormats[0] != Bitmap::ELuminance) {
                Log(EWarn, "The PFM format only supports pixelFormat=\"rgb\" or \"luminance\"."
                    " Overriding (setting to \"rgb\")..");
                m_pixelFormats[0] = Bitmap::ERGB;
            }
            if (m_componentFormat != Bitmap::EFloat32) {
                Log(EWarn, "The PFM format only supports componentFormat=\"float32\". Overriding..");
                m_componentFormat = Bitmap::EFloat32;
            }
        }

        std::vector<std::string> keys = props.getPropertyNames();
        for (size_t i=0; i<keys.size(); ++i) {
            std::string key = boost::to_lower_copy(keys[i]);
            key.erase(std::remove_if(key.begin(), key.end(), ::isspace), key.end());

            if ((boost::starts_with(key, "metadata['") && boost::ends_with(key, "']")) ||
                (boost::starts_with(key, "label[") && boost::ends_with(key, "]")))
                props.markQueried(keys[i]);
        }

        if (m_pixelFormats.size() == 1) {
            m_storage = new ImageBlock(Bitmap::ESpectrumAlphaWeight, m_cropSize);
        } else {
            m_storage = new ImageBlock(Bitmap::EMultiSpectrumAlphaWeight, m_cropSize,
                NULL, (int) (SPECTRUM_SAMPLES * m_pixelFormats.size() + 2));
        }
    }

    HDRFilm(Stream *stream, InstanceManager *manager)
        : Film(stream, manager) {
        m_banner = stream->readBool();
        m_attachLog = stream->readBool();
        m_fileFormat = (Bitmap::EFileFormat) stream->readUInt();
        m_pixelFormats.resize((size_t) stream->readUInt());
        for (size_t i=0; i<m_pixelFormats.size(); ++i)
            m_pixelFormats[i] = (Bitmap::EPixelFormat) stream->readUInt();
        m_channelNames.resize((size_t) stream->readUInt());
        for (size_t i=0; i<m_channelNames.size(); ++i)
            m_channelNames[i] = stream->readString();
        m_componentFormat = (Bitmap::EComponentFormat) stream->readUInt();
    }

    void serialize(Stream *stream, InstanceManager *manager) const {
        Film::serialize(stream, manager);
        stream->writeBool(m_banner);
        stream->writeBool(m_attachLog);
        stream->writeUInt(m_fileFormat);
        stream->writeUInt((uint32_t) m_pixelFormats.size());
        for (size_t i=0; i<m_pixelFormats.size(); ++i)
            stream->writeUInt(m_pixelFormats[i]);
        stream->writeUInt((uint32_t) m_channelNames.size());
        for (size_t i=0; i<m_channelNames.size(); ++i)
            stream->writeString(m_channelNames[i]);
        stream->writeUInt(m_componentFormat);
    }

    void clear() {
        m_storage->clear();
    }

    void put(const ImageBlock *block) {
        m_storage->put(block);
    }

    void setBitmap(const Bitmap *bitmap, Float multiplier) {
        bitmap->convert(m_storage->getBitmap(), multiplier);
    }

    void addBitmap(const Bitmap *bitmap, Float multiplier) {
        /* Currently, only accumulating spectrum-valued floating point images
           is supported. This function basically just exists to support the
           somewhat peculiar film updates done by BDPT */

        Vector2i size = bitmap->getSize();
        if (bitmap->getPixelFormat() != Bitmap::ESpectrum ||
            bitmap->getComponentFormat() != Bitmap::EFloat ||
            bitmap->getGamma() != 1.0f ||
            size != m_storage->getSize() ||
            m_pixelFormats.size() != 1) {
            Log(EError, "addBitmap(): Unsupported bitmap format!");
        }

        size_t nPixels = (size_t) size.x * (size_t) size.y;
        const Float *source = bitmap->getFloatData();
        Float *target = m_storage->getBitmap()->getFloatData();
        for (size_t i=0; i<nPixels; ++i) {
            Float weight = target[SPECTRUM_SAMPLES + 1];
            if (weight == 0)
                weight = target[SPECTRUM_SAMPLES + 1] = 1;
            weight *= multiplier;
            for (size_t j=0; j<SPECTRUM_SAMPLES; ++j)
                *target++ += *source++ * weight;
            target += 2;
        }
    }

    bool develop(const Point2i &sourceOffset, const Vector2i &size,
            const Point2i &targetOffset, Bitmap *target) const {
        const Bitmap *source = m_storage->getBitmap();
        const FormatConverter *cvt = FormatConverter::getInstance(
            std::make_pair(Bitmap::EFloat, target->getComponentFormat())
        );

        size_t sourceBpp = source->getBytesPerPixel();
        size_t targetBpp = target->getBytesPerPixel();

        const uint8_t *sourceData = source->getUInt8Data()
            + (sourceOffset.x + sourceOffset.y * source->getWidth()) * sourceBpp;
        uint8_t *targetData = target->getUInt8Data()
            + (targetOffset.x + targetOffset.y * target->getWidth()) * targetBpp;

        if (EXPECT_NOT_TAKEN(m_pixelFormats.size() != 1)) {
            /* Special case for general multi-channel images -- just develop the first component(s) */
            for (int i=0; i<size.y; ++i) {
                for (int j=0; j<size.x; ++j) {
                    Float weight = *((Float *) (sourceData + (j+1)*sourceBpp - sizeof(Float)));
                    Float invWeight = weight != 0 ? ((Float) 1 / weight) : (Float) 0;
                    cvt->convert(Bitmap::ESpectrum, 1.0f, sourceData + j*sourceBpp,
                        target->getPixelFormat(), target->getGamma(), targetData + j * targetBpp,
                        1, invWeight);
                }

                sourceData += source->getWidth() * sourceBpp;
                targetData += target->getWidth() * targetBpp;
            }

        } else if (size.x == m_cropSize.x && target->getWidth() == m_storage->getWidth()) {
            /* Develop a connected part of the underlying buffer */
            cvt->convert(source->getPixelFormat(), 1.0f, sourceData,
                target->getPixelFormat(), target->getGamma(), targetData,
                size.x*size.y);
        } else {
            /* Develop a rectangular subregion */
            for (int i=0; i<size.y; ++i) {
                cvt->convert(source->getPixelFormat(), 1.0f, sourceData,
                    target->getPixelFormat(), target->getGamma(), targetData,
                    size.x);

                sourceData += source->getWidth() * sourceBpp;
                targetData += target->getWidth() * targetBpp;
            }
        }

        return true;
    }

    void setDestinationFile(const fs::path &destFile, uint32_t blockSize) {
        m_destFile = destFile;
    }

    void develop(const Scene *scene, Float renderTime) {
        if (m_destFile.empty())
            return;

        Log(EDebug, "Developing film ..");

        ref<Bitmap> bitmap;
        if (m_pixelFormats.size() == 1) {
            bitmap = m_storage->getBitmap()->convert(m_pixelFormats[0], m_componentFormat);
            bitmap->setChannelNames(m_channelNames);
        } else {
            bitmap = m_storage->getBitmap()->convertMultiSpectrumAlphaWeight(m_pixelFormats,
                    m_componentFormat, m_channelNames);
        }

        if (m_banner && m_cropSize.x > bannerWidth+5 && m_cropSize.y > bannerHeight + 5 && m_pixelFormats.size() == 1) {
            int xoffs = m_cropSize.x - bannerWidth - 5,
                yoffs = m_cropSize.y - bannerHeight - 5;
            for (int y=0; y<bannerHeight; y++) {
                for (int x=0; x<bannerWidth; x++) {
                    if (banner[x+y*bannerWidth])
                        continue;
                    bitmap->setPixel(Point2i(x+xoffs, y+yoffs), Spectrum(1024));
                }
            }
        }

        fs::path filename = m_destFile;
        std::string properExtension;
        if (m_fileFormat == Bitmap::EOpenEXR)
            properExtension = ".exr";
        else if (m_fileFormat == Bitmap::ERGBE)
            properExtension = ".rgbe";
        else
            properExtension = ".pfm";

        std::string extension = boost::to_lower_copy(filename.extension().string());
        if (extension != properExtension)
            filename.replace_extension(properExtension);

        Log(EInfo, "Writing image to \"%s\" ..", filename.string().c_str());
        ref<FileStream> stream = new FileStream(filename, FileStream::ETruncWrite);

        if (m_pixelFormats.size() == 1)
            annotate(scene, m_properties, bitmap, renderTime, 1.0f);

        /* Attach the log file to the image if this is requested */
        Logger *logger = Thread::getThread()->getLogger();
        std::string log;
        if (m_attachLog && logger->readLog(log)) {
            log += "\n\n";
            log += Statistics::getInstance()->getStats();
            bitmap->setMetadataString("log", log);
        }

        bitmap->write(m_fileFormat, stream);
    }

    bool hasAlpha() const {
        for (size_t i=0; i<m_pixelFormats.size(); ++i) {
            if (m_pixelFormats[i] == Bitmap::ELuminanceAlpha ||
                m_pixelFormats[i] == Bitmap::ERGBA ||
                m_pixelFormats[i] == Bitmap::EXYZA ||
                m_pixelFormats[i] == Bitmap::ESpectrumAlpha)
                return true;
        }
        return false;
    }

    bool destinationExists(const fs::path &baseName) const {
        std::string properExtension;
        if (m_fileFormat == Bitmap::EOpenEXR)
            properExtension = ".exr";
        else if (m_fileFormat == Bitmap::ERGBE)
            properExtension = ".rgbe";
        else
            properExtension = ".pfm";

        fs::path filename = baseName;
        if (boost::to_lower_copy(filename.extension().string()) != properExtension)
            filename.replace_extension(properExtension);
        return fs::exists(filename);
    }

    std::string toString() const {
        std::ostringstream oss;
        oss << "HDRFilm[" << endl
            << "  size = " << m_size.toString() << "," << endl
            << "  fileFormat = " << m_fileFormat << "," << endl
            << "  pixelFormat = ";
        for (size_t i=0; i<m_pixelFormats.size(); ++i)
            oss << m_pixelFormats[i] << ", ";
        oss << endl
            << "  channelNames = ";
        for (size_t i=0; i<m_channelNames.size(); ++i)
            oss << "\"" << m_channelNames[i] << "\"" << ", ";
        oss << endl
            << "  componentFormat = " << m_componentFormat << "," << endl
            << "  cropOffset = " << m_cropOffset.toString() << "," << endl
            << "  cropSize = " << m_cropSize.toString() << "," << endl
            << "  banner = " << m_banner << "," << endl
            << "  filter = " << indent(m_filter->toString()) << endl
            << "]";
        return oss.str();
    }

    MTS_DECLARE_CLASS()
protected:
    Bitmap::EFileFormat m_fileFormat;
    std::vector<Bitmap::EPixelFormat> m_pixelFormats;
    std::vector<std::string> m_channelNames;
    Bitmap::EComponentFormat m_componentFormat;
    bool m_banner;
    bool m_attachLog;
    fs::path m_destFile;
    ref<ImageBlock> m_storage;
};

MTS_IMPLEMENT_CLASS_S(HDRFilm, false, Film)
MTS_EXPORT_PLUGIN(HDRFilm, "High dynamic range film");
MTS_NAMESPACE_END

max_stars_repo_name: anadodik/sdmm-mitsuba

max_issues_repo_name: anadodik/sdmm-mitsuba

max_forks_repo_name: anadodik/sdmm-mitsuba


text:
/*********************************************************************
 * Software License Agreement (BSD License)
 *
 *  Copyright (c) 2019, University of Stuttgart
 *  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 the University of Stuttgart 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.
 *********************************************************************/

/* Author: Andreas Orthey */

#include "MultiLevelPlanningCommon.h"
#include "../KinematicChain.h"
#include <ompl/base/SpaceInformation.h>
#include <ompl/tools/benchmark/Benchmark.h>
#include <boost/range/irange.hpp>
#include <boost/range/algorithm_ext/push_back.hpp>

const unsigned int numLinks = 15;
const double runtime_limit = 5;
const double memory_limit = 4096;
const int run_count = 2;

const double linkLength = 1.0 / numLinks;

namespace ot = ompl::tools;
namespace og = ompl::geometric;
std::vector<Environment> envs;

Environment createCustomHornEnvironment(unsigned int d)
{
    double narrowPassageWidth = log((double)d) / (double)d;
    return createHornEnvironment(d, narrowPassageWidth);
}

ob::PlannerPtr GetQRRT(std::vector<int> sequenceLinks, ob::SpaceInformationPtr si)
{
    // ompl::msg::setLogLevel(ompl::msg::LOG_DEV2);
    std::vector<ob::SpaceInformationPtr> si_vec;

    for (unsigned int k = 0; k < sequenceLinks.size(); k++)
    {
        int links = sequenceLinks.at(k);
        assert(links < numLinks);

        OMPL_INFORM("Create MultiLevel Chain with %d links.", links);
        auto spaceK(std::make_shared<KinematicChainSpace>(links, linkLength, &envs.at(links)));

        auto siK = std::make_shared<ob::SpaceInformation>(spaceK);
        siK->setStateValidityChecker(std::make_shared<KinematicChainValidityChecker>(siK));
        spaceK->setup();
        si_vec.push_back(siK);
    }

    OMPL_INFORM("Add Original Chain with %d links.", numLinks);
    si_vec.push_back(si);

    auto planner = std::make_shared<ompl::multilevel::QRRT>(si_vec);

    std::string qName = "QRRT[";
    for (unsigned int k = 0; k < sequenceLinks.size(); k++)
    {
        int links = sequenceLinks.at(k);
        qName += std::to_string(links) + ",";
    }
    qName += std::to_string(numLinks);
    qName += "]";
    planner->setName(qName);
    return planner;
}

std::vector<std::vector<int>> getAdmissibleProjections(int dim)
{
    std::vector<std::vector<int>> projections;
    // projections.push_back(std::vector<int>{});
    // projections.push_back(std::vector<int>{2});
    // projections.push_back(std::vector<int>{3});

    // unsigned int K = ceil(dim*0.5);
    // for(uint k = 0; k < K; k++){
    //   std::vector<int> kStep;
    //   if(k>0) boost::push_back(kStep, boost::irange(2, dim, k));
    //   projections.push_back(kStep);
    // }
    // for(int k = 2; k < dim; k++){
    //   std::vector<int> kStep{k};
    //   projections.push_back(kStep);
    //   for(int j = k+1; j < dim; j++){
    //     std::vector<int> kjStep{k,j};
    //     projections.push_back(kjStep);
    //   }
    // }
    std::vector<int> discrete;
    boost::push_back(discrete, boost::irange(2, dim + 1));

    std::vector<int> twoStep;
    boost::push_back(twoStep, boost::irange(2, dim + 1, 2));

    if (twoStep.back() != dim)
        twoStep.push_back(dim);

    projections.push_back(twoStep);
    projections.push_back(discrete);

    auto last = std::unique(projections.begin(), projections.end());
    projections.erase(last, projections.end());

    std::cout << "Projections for dim " << dim << std::endl;
    for(unsigned int k = 0; k < projections.size(); k++){
        std::vector<int> pk = projections.at(k);
        std::cout << k << ": ";
        for(unsigned int j = 0; j < pk.size(); j++){
          std::cout << pk.at(j) << (j<pk.size()-1?",":"");
        }
        std::cout << std::endl;
    }

    return projections;
}

int main()
{
    Environment env = createCustomHornEnvironment(numLinks);
    // Environment env = createHornEnvironment(numLinks, log((double)numLinks) / (double)numLinks);
    OMPL_INFORM("Original Chain has %d links", numLinks);
    for (unsigned int k = 0; k < numLinks; k++)
    {
        envs.push_back(createCustomHornEnvironment((k>0?k:1)));
    }

    auto chain(std::make_shared<KinematicChainSpace>(numLinks, linkLength, &env));
    ompl::geometric::SimpleSetup ss(chain);

    ss.setStateValidityChecker(std::make_shared<KinematicChainValidityChecker>(ss.getSpaceInformation()));

    ompl::base::ScopedState<> start(chain), goal(chain);
    std::vector<double> startVec(numLinks, boost::math::constants::pi<double>() / (double)numLinks);
    std::vector<double> goalVec(numLinks, 0);
    startVec[0] = 0.;
    goalVec[0] = boost::math::constants::pi<double>() - .001;
    chain->setup();
    chain->copyFromReals(start.get(), startVec);
    chain->copyFromReals(goal.get(), goalVec);
    ss.setStartAndGoalStates(start, goal);

    ompl::tools::Benchmark benchmark(ss, "KinematicChain");
    benchmark.addExperimentParameter("num_links", "INTEGER", std::to_string(numLinks));

    //############################################################################
    // Compare QRRT with different QuotientSpace sequences to other OMPL planner
    //############################################################################
    ob::SpaceInformationPtr si = ss.getSpaceInformation();
    ob::ProblemDefinitionPtr pdef = ss.getProblemDefinition();

    addPlanner(benchmark, std::make_shared<og::STRIDE>(si));
    addPlanner(benchmark, std::make_shared<og::KPIECE1>(si));
    addPlanner(benchmark, std::make_shared<og::EST>(si));
    addPlanner(benchmark, std::make_shared<og::PRM>(si));

    std::vector<std::vector<int>> admissibleProjections = getAdmissibleProjections(numLinks-1);
    for (unsigned int k = 0; k < admissibleProjections.size(); k++)
    {
        std::vector<int> proj = admissibleProjections.at(k);
        ob::PlannerPtr plannerK = GetQRRT(proj, si);
        addPlanner(benchmark, plannerK);
    }

    printEstimatedTimeToCompletion(numberPlanners, run_count, runtime_limit);

    ot::Benchmark::Request request;
    request.maxTime = runtime_limit;
    request.maxMem = memory_limit;
    request.runCount = run_count;
    request.simplify = false;
    request.displayProgress = false;
    numberRuns = numberPlanners * run_count;

    benchmark.setPostRunEvent(std::bind(&PostRunEvent, std::placeholders::_1, std::placeholders::_2));

    benchmark.benchmark(request);
    benchmark.saveResultsToFile(boost::str(boost::format("kinematic_%i.log") % numLinks).c_str());

    printBenchmarkResults(benchmark);
    return 0;
}

ext: cpp

max_stars_repo_name: orthez/ompl

max_issues_repo_name: orthez/ompl

max_forks_repo_name: orthez/ompl


text:
// Copyright 2020 Peter Dimov
// Distributed under the Boost Software License, Version 1.0.
// http://www.boost.org/LICENSE_1_0.txt

#if defined(_MSC_VER)
# pragma warning(disable: 4702) // unreachable code
# pragma warning(disable: 4577) // noexcept used without /EHsc
# pragma warning(disable: 4530) // C++ exception handler used
#endif

#define BOOST_EXCEPTION_DISABLE

#include <boost/exception_ptr.hpp>

class my_exception: public std::exception {};

int main()
{
    boost::make_exception_ptr( my_exception() );
}

namespace boost
{

// shared_ptr needs this
void throw_exception( std::exception const & )
{
    std::exit( 1 );
}

} // namespace boost


text:
#include <cstring>
#include <iostream>
#include <fstream>
#include <armadillo>

#include "lap3d.h"
#include "shiftengine3d.h"

using namespace arma;

float CG_PSNR3D(CubeType Base_image, CubeType Recon_image);

int main(int argc, char *argv[])
{
	std::string firstImagePath;
	std::string secondImagePath;
	std::string resultImagePath;

	SizeType rows;
	SizeType cols;
	SizeType slices;

	ColType i1_v;
	ColType i2_v;

	if (argc < 2) {
		std::cerr << "Usage: " << std::endl;
		std::cerr << std::endl;
		std::cerr << "  " << argv[0] << " <path-to-image1> <path-to-image2> <path-to-result-image> <image-rows> <image-columns> <image-slices>" << std::endl;
		std::cerr << "  " << argv[0] << " <pointer-to-image1> <pointer-to-image2> <pointer-to-result-image>, <image-rows> <image-columns> <image-slices>" << std::endl;
		std::cerr << std::endl;
		std::cerr << "Run '" << argv[0] << " --help' for more information" << std::endl;
		std::cerr << std::endl;

		return EXIT_FAILURE;
	}

	// Output help string and exit (otherwise segmentation fault!)
	if (strcmp(argv[1], "--help") == 0) {
		std::cout << "There are no more information implemented yet." << std::endl;

		return EXIT_FAILURE;
	}

	firstImagePath = argv[1];
	secondImagePath = argv[2];
	resultImagePath = argv[3];

	rows = strtol(argv[4], NULL, 10);
	cols = strtol(argv[5], NULL, 10);
	slices = strtol(argv[6], NULL, 10);

	//Load iamges (saved as raw ascii)
	i1_v.load(firstImagePath, raw_binary);
	i2_v.load(secondImagePath, raw_binary);

	//Shape them to 3D pictures with correct dimensions
	CubeType i1(i1_v.memptr(), rows, cols, slices);
	CubeType i2(i2_v.memptr(), rows, cols, slices);

	i1.subcube(span(0,3),span(0,3),span(0,3)).print("i1");

	//Construct two 3D Images
	//Construct the LocalAllpass Algorithm Object with Level min and max
	Gadgetron::LAP3D mLAP3D(i1, i2, 0, 4);

	field<CubeType> flow_estimation = mLAP3D.exec();

	//Shift first image according to estimated optical flow
	Gadgetron::ShiftEngine3D shifter(i1, flow_estimation(0), flow_estimation(1), flow_estimation(2));
	CubeType i_hat_fast = shifter.execCubicShift();
	//Save result image
	Col<PixelType> i_hat_fast_v = vectorise(i_hat_fast);
	i_hat_fast_v.save(resultImagePath, raw_ascii);

	std::cout << "PSNR_uB_Fast: " << CG_PSNR3D(i2, i_hat_fast) << std::endl;

	return EXIT_SUCCESS;
}

float CG_PSNR3D(CubeType Base_image, CubeType Recon_image)
{
	int m = Recon_image.n_rows;
	int n = Recon_image.n_cols;
	int p = Recon_image.n_slices;

	float Max_I = arma::max(arma::abs(vectorise(Base_image)));

	float MSE = accu(arma::pow(arma::abs(Base_image-Recon_image),2)) / (n*m*p);

	float PSNR = 10 * std::log10(std::pow(Max_I, 2) / MSE);

	return PSNR;
}

max_stars_repo_name: noonelikechu/Shearlet

max_issues_repo_name: noonelikechu/Shearlet

max_forks_repo_name: noonelikechu/Shearlet


text: #include <boost/thread/concurrent_queues/queue_views.hpp>

ext: hpp

max_stars_repo_name: miathedev/BoostForArduino

max_issues_repo_name: miathedev/BoostForArduino

max_forks_repo_name: miathedev/BoostForArduino


text:
#include <boost/make_shared.hpp>
#include <typeinfo>
#include <iostream>

int main()
{
  auto p1 = boost::make_shared<int>(1);
  std::cout << typeid(p1).name() << '\n';
  auto p2 = boost::make_shared<int[]>(10);
  std::cout << typeid(p2).name() << '\n';
}

max_stars_repo_name: KwangjoJeong/Boost

max_issues_repo_name: KwangjoJeong/Boost

max_forks_repo_name: KwangjoJeong/Boost


text:
//
//=======================================================================
// Copyright 2012
// Author: Alex Hagen-Zanker
//
// Distributed under the Boost Software License, Version 1.0. (See
// accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
//
// distance_visitor implements the dijkstra visitor and interruptor
// concepts. It returns true on do_interrupt() once all vertices within a
// given distance are found.
//
//=======================================================================
//
#ifndef BLINK_GRAPH_DIJKSTRA_VISITOR_DISTANCE_VISITOR_HPP
#define BLINK_GRAPH_DIJKSTRA_VISITOR_DISTANCE_VISITOR_HPP

#include <boost/graph/dijkstra_shortest_paths.hpp> // default_dijkstra_visitor
#include <boost/property_map/property_map.hpp>
#include <boost/smart_ptr.hpp>

#include <functional> //std::less

namespace blink {

template<typename DistanceMap, typename Compare =
  std::less<typename boost::property_traits<DistanceMap>::value_type > >
class distance_visitor : public boost::default_dijkstra_visitor
{
  typedef typename boost::property_traits<DistanceMap>::value_type distance_type;

public:
  distance_visitor(DistanceMap distance_map, distance_type target_distance,
    const Compare& compare = Compare())
    : m_distance_map(distance_map), m_target_distance(target_distance),
    m_compare(compare)
  {
    m_do_interrupt.reset(new bool(false) );
  }

  template<typename U, typename G>
  void finish_vertex(const U& u, const G& g)
  {
    if( !m_compare(get(m_distance_map,u), m_target_distance) ) {
      *m_do_interrupt = true;
    }
  }

  inline bool do_interrupt() const
  {
    return *m_do_interrupt;
  }

private:
  boost::shared_ptr<bool> m_do_interrupt;
  DistanceMap m_distance_map;
  distance_type m_target_distance;
  Compare m_compare;
};

template<typename DijkstraState>
struct distance_visitor_helper
{
  typedef typename DijkstraState::template param<boost::distance_compare_t>::type compare_type;
  typedef typename DijkstraState::template param<boost::vertex_distance_t>::type distance_map_type;
  typedef typename DijkstraState::template param<boost::vertex_index_t>::type index_type;
  typedef typename DijkstraState::template param<boost::distance_inf_t>::type distance_value_type;
  typedef typename distance_visitor<distance_map_type, compare_type> type;

  static type make(DijkstraState& state, distance_value_type d)
  {
    return type(state.get<boost::vertex_distance_t>(), d
      , state.get<boost::distance_compare_t>());
  }
};

template<typename Graph, typename Params>
struct distance_visitor_helper_indirect
  : distance_visitor_helper<typename dijkstra_state_helper<Graph, Params>::type>
{};

template <typename DijkstraState, typename DistanceValue>
typename distance_visitor_helper<DijkstraState>::type
make_distance_visitor(DijkstraState& state, DistanceValue d)
{
  return distance_visitor_helper<DijkstraState>::make(state, d);
}

}; // namespace blink;

#endif //BLINK_GRAPH_DIJKSTRA_VISITOR_DISTANCE_VISITOR_HPP


text:
/*
Copyright 2014 Rogier van Dalen.

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.
*/

#define BOOST_TEST_MODULE test_utility_nested_callable
#include "utility/test/boost_unit_test.hpp"

#include "utility/nested_callable.hpp"

#include <boost/mpl/assert.hpp>
#include <boost/mpl/placeholders.hpp>

#include "utility/returns.hpp"

/* For result_of. */
struct a {};
struct b {};
struct c {};

struct function1 {
    a operator() (a, a);
    b operator() (a, b);
    c operator() (b, b);
};

struct function2 {
    c operator() (c, a);
    b operator() (c, b);
    a operator() (b, b);
};

/*
For all/any.

Imagine function objects are tagged by their member "apply" deriving from
certain base classes.
In this example, some operations derived from "unimplemented"; some from
"approximate".
Only if all operations in a nested call are implemented is the whole call
implemented.
This is where "all" is useful.
If any operation in the nested call is approximate, then the whole call is.
This is where "any" is useful.
*/
struct unimplemented {};
struct approximate {};

template <class Operation> struct is_apply_implemented;
template <class Function, class ... Arguments>
    struct is_apply_implemented <Function (Arguments ...)>
: boost::mpl::not_ <std::is_base_of <unimplemented,
    typename Function::template apply <Arguments ...>>> {};

template <class Operation> struct is_apply_approximate;
template <class Function, class ... Arguments>
    struct is_apply_approximate <Function (Arguments ...)>
: std::is_base_of <approximate,
    typename Function::template apply <Arguments ...>> {};

template <class Expression> struct is_implemented
: nested_callable::all <is_apply_implemented <boost::mpl::_1>, Expression> {};

template <class Expression> struct is_approximate
: nested_callable::any <is_apply_approximate <boost::mpl::_1>, Expression> {};

namespace operation {

    // plus: for implemented.
    template <class ...  Arguments> struct plus
    : unimplemented {};

    template <> struct plus <int, int>
    { int operator() (int a, int b) const {return a + b; } };

    template <> struct plus <float, float>
    { float operator() (float a, float b) const {return a + b; } };
    template <> struct plus <double, float>
    { double operator() (double a, float b) const {return a + b; } };
    template <> struct plus <float, double>
    { double operator() (float a, double b) const {return a + b; } };
    template <> struct plus <double, double>
    { double operator() (double a, double b) const {return a + b; } };

    // times: for approximate.
    template <class ...  Arguments> struct times {};

    template <> struct times <int, int>
    { int operator() (int a, int b) const {return a + b; } };

    template <> struct times <int, float> : approximate
    { float operator() (int a, float b) const {return a + b; } };

    template <> struct times <float, int> : approximate
    { float operator() (float a, int b) const {return a + b; } };

    template <> struct times <float, float> : approximate
    { float operator() (float a, float b) const {return a + b; } };

    // make_approximate: pretend to make operation approximate.
    template <class ... Arguments> struct make_approximate : unimplemented {};

    template <class Operation> struct make_approximate <Operation>
    : approximate
    { Operation operator() (Operation const & o) { return o; } };

} // namespace operation

namespace callable {

    struct plus {
        template <class ...  Arguments> struct apply
        : operation::plus <Arguments ...> {};

        template <class ...  Arguments>
            auto operator() (Arguments const & ... arguments)
        RETURNS (apply <Arguments ...>() (arguments ...));
    };

    struct times {
        template <class ...  Arguments> struct apply
        : operation::times <Arguments ...> {};

        template <class ...  Arguments>
            auto operator() (Arguments const & ... arguments)
        RETURNS (apply <Arguments ...>() (arguments ...));
    };

    struct make_approximate {
        template <class ...  Arguments> struct apply
        : operation::make_approximate <Arguments ...> {};

        template <class ...  Arguments>
            auto operator() (Arguments const & ... arguments)
        RETURNS (apply <Arguments ...>() (arguments ...));
    };

} // namespace callable

BOOST_AUTO_TEST_SUITE(test_utility_nested_callable)

BOOST_AUTO_TEST_CASE (test_utility_nested_callable_result_of) {
    using nested_callable::result_of;
    BOOST_MPL_ASSERT ((std::is_same <typename result_of <a>::type, a>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1>::type, function1>));

    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (a, a)>::type, a>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (a, b)>::type, b>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (b, b)>::type, c>));

    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (a, function2 (b, b))>::type, a>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (a, function2 (c, b))>::type, b>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (function2 (c, b), b)>::type, c>));
    BOOST_MPL_ASSERT ((std::is_same <
        typename result_of <function1 (function2 (b, b), function2 (c, b))
        >::type, b>));
}

BOOST_AUTO_TEST_CASE (test_utility_nested_callable_all) {
    // Test the example implementation.
    BOOST_MPL_ASSERT ((is_apply_implemented <callable::plus (int, int)>));
    BOOST_MPL_ASSERT ((is_apply_implemented <callable::plus (float, float)>));
    BOOST_MPL_ASSERT_NOT ((is_apply_implemented <callable::plus (float, int)>));
    BOOST_MPL_ASSERT_NOT ((is_apply_implemented <callable::plus ()>));
    BOOST_MPL_ASSERT_NOT ((is_apply_implemented <callable::plus (int)>));
    BOOST_MPL_ASSERT_NOT ((
        is_apply_implemented <callable::plus (int, int, int)>));

    // Test the same cases as above.
    BOOST_MPL_ASSERT ((is_implemented <callable::plus (int, int)>));
    BOOST_MPL_ASSERT ((is_implemented <callable::plus (float, float)>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <callable::plus (float, int)>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <callable::plus ()>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <callable::plus (int)>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <callable::plus (int, int, int)>));

    // Test nested cases.
    BOOST_MPL_ASSERT ((is_implemented <
        callable::plus (int, callable::plus (int, int))>));
    BOOST_MPL_ASSERT ((is_implemented <
        callable::plus (float, callable::plus (float, float))>));
    BOOST_MPL_ASSERT ((is_implemented <
        callable::plus (int, callable::plus (
            callable::plus (int, int), int))>));
    BOOST_MPL_ASSERT ((is_implemented <
        callable::plus (float, callable::plus (
            callable::plus (float, float), float))>));

    BOOST_MPL_ASSERT_NOT ((is_implemented <
        callable::plus (int, callable::plus (float, int))>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <
        callable::plus (float, callable::plus (int, int))>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <
        callable::plus (callable::plus (float, int),
            callable::plus (float, int))>));
    BOOST_MPL_ASSERT_NOT ((is_implemented <
        callable::plus (callable::plus (float, int),
            callable::plus (int, int))>));
}

BOOST_AUTO_TEST_CASE (test_utility_nested_callable_any) {
    // Test the example implementation.
    BOOST_MPL_ASSERT_NOT ((
        is_apply_approximate <callable::times (int, int)>));
    BOOST_MPL_ASSERT ((
        is_apply_approximate <callable::times (float, int)>));
    BOOST_MPL_ASSERT ((
        is_apply_approximate <callable::times (int, float)>));
    BOOST_MPL_ASSERT ((
        is_apply_approximate <callable::times (float, float)>));

    // Test the same cases as above.
    BOOST_MPL_ASSERT_NOT ((
        is_approximate <callable::times (int, int)>));
    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (float, int)>));
    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (int, float)>));
    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (float, float)>));

    // Test nested cases.
    BOOST_MPL_ASSERT_NOT ((
        is_approximate <callable::times (int, callable::times (int, int))>));
    // plus is not marked as approximate.
    BOOST_MPL_ASSERT_NOT ((
        is_approximate <callable::times (int, callable::plus (int, int))>));
    // The function pointer type for make_approximate (times).
    // Not great, but this does work.
    typedef callable::make_approximate (* approximate_times) (callable::times);
    BOOST_MPL_ASSERT ((
        is_approximate <approximate_times (int, callable::times (int, int))>));
    typedef callable::make_approximate (* approximate_plus) (callable::plus);
    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (int, approximate_plus (int, int))>));

    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (callable::times (float, int), int)>));
    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (int, callable::times (float, int))>));
    BOOST_MPL_ASSERT ((
        is_approximate <callable::times (
            callable::times (float, int), callable::times (float, int))>));
}

BOOST_AUTO_TEST_SUITE_END()

max_stars_repo_name: rogiervd/utility

max_issues_repo_name: rogiervd/utility

max_forks_repo_name: rogiervd/utility


text:
/**
 * Copyright (c) Facebook, Inc. and its affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

#include "Show.h"
#include "Tool.h"

#include <boost/format.hpp>
#include <stdio.h>
#include <sstream>
#include <string>
#include <vector>
#include <unordered_map>
#include "NativeOutliner_generated.h"

/*
 * This tool consumes the outline artifacts generated by the NativeOutliner
 * pass, and generates the native code that contains the outlined code;
 * the equivalent of 'throw new <Throwable>("string literal")'
 */

using namespace facebook::redex::outliner;

namespace {

constexpr static char kOutlineThrowsTemplate[] = R"template(

// Copyright (c) Facebook, Inc. and its affiliates.

#include <fb/fbjni.h>

using namespace facebook::jni;
using facebook::jni::Environment;

namespace facebook { namespace redex {

static constexpr const char* kClassName = "com/facebook/redex/NativeOutlined";

struct JThrowable : public jni::JavaClass<JThrowable, jni::JThrowable> {
  constexpr static auto kJavaDescriptor = "Ljava/lang/Throwable;";
};

static jni::local_ref<JThrowable> dispatchThrows(alias_ref<jobject>, jint idx) {
  const char* cls = nullptr;
  const char* msg = nullptr;
  switch (idx) {
%s
    default:
      cls = "java/lang/RuntimeException";
      msg = "Invalid outline throw index";
      break;
  }

  throwNewJavaException(cls, msg);

  /* unreachable */
  return jni::local_ref<JThrowable>(nullptr);
}

void registerOutlinerDispatch() {
  registerNatives(kClassName, {
    makeNativeMethod("$dispatch$throws", dispatchThrows)
  });
}

}} //facebook::redex

// Called when library is loaded by the first class which uses it.
JNIEXPORT jint JNICALL JNI_OnLoad(JavaVM* vm, void*) {
  return facebook::jni::initialize(vm, [] {
    facebook::redex::registerOutlinerDispatch();
  });
}

)template";

class NativeOutlinerCodegen : public Tool {
 public:
  NativeOutlinerCodegen() : Tool("native-outliner-codegen", "codegen helper for native outliner") {}

  void add_options(po::options_description& options) const override {
    options.add_options()(
        "input,i",
        po::value<std::string>()->value_name("/tmp/artifacts.bin")->required(),
        "(input) path of an artifacts file emitted by NativeOutliner pass")(
        "output,o",
        po::value<std::string>()->value_name("NativeOutlined.cpp")->required(),
        "(output) path of generated code");
  }

  void run(const po::variables_map& options) override {
    auto inpath = options["input"].as<std::string>();
    auto outpath = options["output"].as<std::string>();

    FILE* fdin = fopen(inpath.c_str(), "rb");
    fseek(fdin, 0L, SEEK_END);
    int length = ftell(fdin);
    fseek(fdin, 0L, SEEK_SET);
    char *data = new char[length];
    fread(data, sizeof(char), length, fdin);
    auto outlined_throws = GetOutlinedThrows(data);
    fclose(fdin);

    FILE* fdout = fopen(outpath.c_str(), "w");
    std::string cases = generateOutlineThrowsCases(outlined_throws);
    fprintf(fdout, kOutlineThrowsTemplate, cases.c_str());
    fclose(fdout);

    delete [] data;
  }

 private:
  std::string generateOutlineThrowsCases(const OutlinedThrows* outlined_throws) {
    std::string cases;
    int idx = 0;
    for (auto outlined_throw : *(outlined_throws->outlined_throws())) {
      auto kase = boost::format{ R"template(
    case %0d:
      cls = R"___(%1s)___";
      msg = R"___(%2s)___";
      break;
  )template" } % idx++ % outlined_throw->type()->c_str() % outlined_throw->msg()->c_str();
      cases += kase.str();
    }
    return cases;
  }
};

static NativeOutlinerCodegen s_tool;

}

max_stars_repo_name: parind/redex

max_issues_repo_name: parind/redex

max_forks_repo_name: parind/redex


text:
// Copyright 2008 by BBN Technologies Corp.
// All Rights Reserved.

#include "Generic/common/leak_detection.h"
#include "Generic/common/SessionLogger.h"
#include "Generic/common/OutputUtil.h"
#include "boost/regex.hpp"

#include "Generic/common/UTF8InputStream.h"
#include "Generic/common/UTF8OutputStream.h"
#include "Generic/common/UTF8Token.h"
#include "Generic/common/StringTransliterator.h"

#include "Generic/discourseRel/PennDiscourseTreebank.h"
#include "Generic/discourseRel/CrossSentRelation.h"
#include <boost/scoped_ptr.hpp>

#define MAX_PDTB_INFO_LEN 2500
#define PDTBDOCID_LEN 4

// static member initialization
int PennDiscourseTreebank::_num_documents = 0;
PennDiscourseTreebank::ExplicitConnectiveTable *PennDiscourseTreebank::_connective_table = 0;
PennDiscourseTreebank::CrossSentRelationTable *PennDiscourseTreebank::_crossSentRel_table = 0;

void PennDiscourseTreebank::loadDataFromPDTBFileList (const char *listfile){

	boost::scoped_ptr<UTF8InputStream> fileListStream_scoped_ptr(UTF8InputStream::build(listfile));
	UTF8InputStream& fileListStream(*fileListStream_scoped_ptr);
	UTF8Token token;

	while (!fileListStream.eof()) {
		fileListStream >> token;
		if (wcscmp(token.chars(), L"") == 0)
			break;
		loadDataFromPDTBFile(token.chars());
		_num_documents ++ ;
	}

}

void PennDiscourseTreebank::loadDataFromPDTBFileList (const char* listfile, TargetConnectives::ExplicitConnectiveDict *connectiveDict){

	boost::scoped_ptr<UTF8InputStream> fileListStream_scoped_ptr(UTF8InputStream::build(listfile));
	UTF8InputStream& fileListStream(*fileListStream_scoped_ptr);
	UTF8Token token;

	while (!fileListStream.eof()) {
		fileListStream >> token;
		if (wcscmp(token.chars(), L"") == 0)
			break;
		loadDataFromPDTBFile(token.chars(), connectiveDict);
		_num_documents ++ ;
	}
}

void PennDiscourseTreebank::loadCrossSentDataFromPDTBFileList (const char *listfile){
	boost::scoped_ptr<UTF8InputStream> fileListStream_scoped_ptr(UTF8InputStream::build(listfile));
	UTF8InputStream& fileListStream(*fileListStream_scoped_ptr);
	UTF8Token token;

	while (!fileListStream.eof()) {
		fileListStream >> token;
		if (wcscmp(token.chars(), L"") == 0)
			break;
		loadCrossSentDataFromPDTBFile(token.chars());
		_num_documents ++ ;
	}
}

void PennDiscourseTreebank::loadDataFromPDTBFile(const wchar_t *filename){
	char pdtb_file_name_str[501];
	StringTransliterator::transliterateToEnglish(pdtb_file_name_str, filename, 500);
	std::cerr << "Loading data from " << pdtb_file_name_str << "\n";

	/* read in PDTB file and fill in the table */
	//Create a new hash table to store parameters and values
	//Make sure it doesnt already exist for recursive calls
	if (_connective_table == 0)
	{
		//Allocate Memory for the explicit connective Hash Table
	    _connective_table   = _new ExplicitConnectiveTable();

	}

	//Open file for reading
	ifstream inputFile (pdtb_file_name_str);
	string strFile = pdtb_file_name_str;
    if (! inputFile.is_open())
    {
		string s = "Can't Open PDTB File: " + strFile;
		throw UnexpectedInputException("PennDiscourseTreebank::loadDataFromPDTBFile()", s.c_str());
		return;
	}

	size_t loc;
	loc = strFile.find( ".doc", 0 );
	if (loc == string::npos){

		throw UnexpectedInputException("illegal PDTB file name: ", strFile.c_str());
		return;
	}
	string docName = strFile.substr(loc-PDTBDOCID_LEN,PDTBDOCID_LEN);

    while (! inputFile.eof() )
    {
		char buffer[MAX_PDTB_INFO_LEN];   // Temporary line buffer

		//Get Current Line
		inputFile.getline(buffer,MAX_PDTB_INFO_LEN);

		size_t bufferLen = strlen(buffer);

		if (bufferLen > 0)
		{
			if ((buffer[0] != '\0') && (buffer[0] != '#')){
				findConnLocation (docName, buffer);
			}

		}
	}
}

void PennDiscourseTreebank::loadDataFromPDTBFile (const wchar_t *filename, TargetConnectives::ExplicitConnectiveDict * connectiveDict){
	char pdtb_file_name_str[501];
	StringTransliterator::transliterateToEnglish(pdtb_file_name_str, filename, 500);
	std::cerr << "Loading data from " << pdtb_file_name_str << "\n";

	/* read in PDTB file and fill in the table */
	//Create a new hash table to store parameters and values
	//Make sure it doesnt already exist for recursive calls
	if (_connective_table == 0)
	{
		//Allocate Memory for the explicit connective Hash Table
	    _connective_table   = _new ExplicitConnectiveTable();

	}

	//Open file for reading
	ifstream inputFile (pdtb_file_name_str);
	string strFile = pdtb_file_name_str;
    if (! inputFile.is_open())
    {
		string s = "Can't Open PDTB File: " + strFile;
		throw UnexpectedInputException("PennDiscourseTreebank::loadDataFromPDTBFile()", s.c_str());
		return;
	}

	size_t loc;
	loc = strFile.find( ".doc", 0 );
	if (loc == string::npos){

		throw UnexpectedInputException("illegal PDTB file name: ", strFile.c_str());
		return;
	}
	string docName = strFile.substr(loc-PDTBDOCID_LEN,PDTBDOCID_LEN);

    while (! inputFile.eof() )
    {
		char buffer[MAX_PDTB_INFO_LEN];   // Temporary line buffer

		//Get Current Line
		inputFile.getline(buffer,MAX_PDTB_INFO_LEN);

		size_t bufferLen = strlen(buffer);

		if (bufferLen > 0)
		{
			if ((buffer[0] != '\0') && (buffer[0] != '#')){
				findConnLocation (docName, buffer, connectiveDict);
			}

		}
	}

}

void PennDiscourseTreebank::loadCrossSentDataFromPDTBFile (const wchar_t *filename){
	char pdtb_file_name_str[501];
	StringTransliterator::transliterateToEnglish(pdtb_file_name_str, filename, 500);
	std::cerr << "Loading data from " << pdtb_file_name_str << "\n";

	/* read in PDTB file and fill in the table */
	//Create a new hash table to store parameters and values
	//Make sure it doesnt already exist for recursive calls
	if (_crossSentRel_table == 0)
	{
		//Allocate Memory for the cross sentence relation Hash Table
	    _crossSentRel_table   = _new CrossSentRelationTable();

	}

	//Open file for reading
	ifstream inputFile (pdtb_file_name_str);
	string strFile = pdtb_file_name_str;
    if (! inputFile.is_open())
    {
		string s = "Can't Open PDTB File: " + strFile;
		throw UnexpectedInputException("PennDiscourseTreebank::loadCrossSentDataFromPDTBFile()", s.c_str());
		return;
	}

	size_t loc;
	loc = strFile.find( ".doc", 0 );
	if (loc == string::npos){

		throw UnexpectedInputException("illegal PDTB file name: ", strFile.c_str());
		return;
	}
	string docName = strFile.substr(loc-PDTBDOCID_LEN,PDTBDOCID_LEN);

    while (! inputFile.eof() )
    {
		char buffer[MAX_PDTB_INFO_LEN];   // Temporary line buffer

		//Get Current Line
		inputFile.getline(buffer,MAX_PDTB_INFO_LEN);

		size_t bufferLen = strlen(buffer);

		if (bufferLen > 0)
		{
			if ((buffer[0] != '\0') && (buffer[0] != '#')){
				//findCrossSentRelation (docName, buffer);
				string line=buffer;
				if (line.find("___Explicit___") != string::npos ){
					string relType = "Explicit";
					string connective;
					int relPos;
					string relPosStr;
					int sent1;
					string sent1Str;
					int sent2;
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					string line = buffer;
					// read in connective
					if (line.find ("Connective: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						connective=line.substr(loc+2,strLength-loc-2);
					}
					// skip the line "Connective word: ..."
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);

					// read in relation position
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line=buffer;
					if (line.find ("Relation Pos: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						//relPos=atoi((line.substr(loc+2,strLength-loc-2)).c_str());
						relPosStr=line.substr(loc+2,strLength-loc-2);
						relPos=atoi(relPosStr.c_str());
					}

					// read in Relation Context  Sent1 and Sent 2
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line=buffer;
					if (line.find ("Relation context: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						string sentPair=line.substr(loc+2,strLength-loc-2);
						loc = sentPair.find(" ");
						sent1Str=sentPair.substr(0,loc);
						sent1=atoi(sent1Str.c_str());
						sent2=atoi((sentPair.substr(loc+1,sentPair.size()-loc-1)).c_str());
					}

					// skip linking info for explicit connective
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);

					// generate a CrossSentRelation object
					string PDTBindex = docName+"%"+sent1Str;
					CrossSentRelation csRelObj(PDTBindex, relType, sent1, sent2);
					csRelObj.setConnective(connective);
					csRelObj.setRelationPos(relPos);

					// add relation object to _crossSentRel_table
					CrossSentRelationTable::iterator myIterator = _crossSentRel_table->find(PDTBindex);
					if( myIterator == _crossSentRel_table->end()){
						vector<CrossSentRelation> vCSRel;
						(*_crossSentRel_table)[PDTBindex]=vCSRel;
					}
					((*_crossSentRel_table)[PDTBindex]).push_back(csRelObj);

				}else if (line.find("___Implicit___") != string::npos){
					string relType = "Implicit";
					string connective;
					string semType;
					int relPos;
					string relPosStr;
					int sent1;
					string sent1Str;
					int sent2;

					// read in connective
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					string line = buffer;
					if (line.find ("Connective: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						connective=line.substr(loc+2,strLength-loc-2);
					}

					// read in semantic type
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line = buffer;
					if (line.find ("Semantic Type: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						semType=line.substr(loc+2,strLength-loc-2);
					}

					// read in relation position
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line = buffer;
					if (line.find ("Relation Pos: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						//relPos=atoi((line.substr(loc+2,strLength-loc-2)).c_str());
						relPosStr=line.substr(loc+2,strLength-loc-2);
						relPos=atoi(relPosStr.c_str());
					}

					// read in Relation Context  Sent1 and Sent 2
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line=buffer;
					if (line.find ("Relation context: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						string sentPair=line.substr(loc+2,strLength-loc-2);
						loc = sentPair.find(" ");
						sent1Str=sentPair.substr(0,loc);
						sent1=atoi(sent1Str.c_str());
						sent2=atoi((sentPair.substr(loc+1,sentPair.size()-loc-1)).c_str());
					}

					// generate a CrossSentRelation object
					string PDTBindex = docName+"%"+sent1Str;
					CrossSentRelation csRelObj(PDTBindex, relType, sent1, sent2);
					csRelObj.setConnective(connective);
					csRelObj.setSemType(semType);
					csRelObj.setRelationPos(relPos);

					// add relation object to _crossSentRel_table
					CrossSentRelationTable::iterator myIterator = _crossSentRel_table->find(PDTBindex);
					if(myIterator == _crossSentRel_table->end())
					{
						vector<CrossSentRelation> vCSRel;
						(*_crossSentRel_table)[PDTBindex]=vCSRel;
					}
					((*_crossSentRel_table)[PDTBindex]).push_back(csRelObj);

				}else if (line.find("___AltLex___") != string::npos){
					string relType = "AltLex";
					string semType;
					string relPosStr;
					int relPos;
					int sent1;
					string sent1Str;
					int sent2;

					// read in semantic type
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line = buffer;
					if (line.find ("Semantic Type: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						semType=line.substr(loc+2,strLength-loc-2);
					}

					// read in relation position
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line = buffer;
					if (line.find ("Relation Pos: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						//relPos=atoi((line.substr(loc+2,strLength-loc-2)).c_str());
						relPosStr=line.substr(loc+2,strLength-loc-2);
						relPos=atoi(relPosStr.c_str());
					}

					// read in Relation Context  Sent1 and Sent 2
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line=buffer;
					if (line.find ("Relation context: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						string sentPair=line.substr(loc+2,strLength-loc-2);
						loc = sentPair.find(" ");
						sent1Str=sentPair.substr(0,loc);
						sent1=atoi(sent1Str.c_str());
						sent2=atoi((sentPair.substr(loc+1,sentPair.size()-loc-1)).c_str());
					}

					// generate a CrossSentRelation object
					string PDTBindex = docName+"%"+sent1Str;
					CrossSentRelation csRelObj(PDTBindex, relType, sent1, sent2);
					csRelObj.setSemType(semType);
					csRelObj.setRelationPos(relPos);

					// add relation object to _crossSentRel_table
					CrossSentRelationTable::iterator myIterator = _crossSentRel_table->find(PDTBindex);
					if(myIterator == _crossSentRel_table->end())
					{
						vector<CrossSentRelation> vCSRel;
						(*_crossSentRel_table)[PDTBindex]=vCSRel;
					}
					((*_crossSentRel_table)[PDTBindex]).push_back(csRelObj);

				}else if (line.find("___EntRel___") != string::npos){
					string relType = "EntRel";
					int relPos;
					string relPosStr;
					int sent1;
					string sent1Str;
					int sent2;

					// read in relation position
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line = buffer;
					if (line.find ("Relation Pos: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						//relPos=atoi((line.substr(loc+2,strLength-loc-2)).c_str());
						relPosStr=line.substr(loc+2,strLength-loc-2);
						relPos=atoi(relPosStr.c_str());
					}

					// read in Relation Context  Sent1 and Sent 2
					inputFile.getline(buffer,MAX_PDTB_INFO_LEN);
					line=buffer;
					if (line.find ("Relation context: ") == string::npos){
						throw UnexpectedInputException("invalid format of PDTB file: ", docName.c_str());
					}else{
						size_t loc = line.find(": ");
						size_t strLength = line.size();
						string sentPair=line.substr(loc+2,strLength-loc-2);
						loc = sentPair.find(" ");
						sent1Str=sentPair.substr(0,loc);
						sent1=atoi(sent1Str.c_str());
						sent2=atoi((sentPair.substr(loc+1,sentPair.size()-loc-1)).c_str());
					}

					// generate a CrossSentRelation object
					string PDTBindex = docName+"%"+sent1Str;
					CrossSentRelation csRelObj(PDTBindex, relType, sent1, sent2);
					csRelObj.setRelationPos(relPos);

					// add relation object to _crossSentRel_table
					CrossSentRelationTable::iterator myIterator = _crossSentRel_table->find(PDTBindex);
					if(myIterator == _crossSentRel_table->end())
					{
						vector<CrossSentRelation> vCSRel;
						(*_crossSentRel_table)[PDTBindex]=vCSRel;
					}
					((*_crossSentRel_table)[PDTBindex]).push_back(csRelObj);
				}
			}
		}
	}
}

void PennDiscourseTreebank::findConnLocation (string docName, const char *onelineOfPDTB){
	//boost::regex expression("^(template[[:space:]]*<[^;:{]+>[[:space:]]*)?(class|struct)[[:space:]]*(\\<\\w+\\>([[:blank:]]*\\([^)]*\\))?[[:space:]]*)*(\\<\\w*\\>)[[:space:]]*(<[^;:{]+>[[:space:]]*)?(\\{|:[^;\\{()]*\\{)");
	boost::regex expression("^link info\\: (\\w+) @(\\d+)-(\\d+)");
	string line = onelineOfPDTB;
	string::const_iterator start, end;
	start = line.begin();
	end = line.end();
    boost::match_results<string::const_iterator> what;
	boost::match_flag_type flags = boost::match_default;

	if (regex_search(start, end, what, expression, flags)) {
		// what[0] contains the string pattern matching the whole reg expression
		// what[1] contains the word
		// what[2] contains the sent index
		// what[3] contains the position

		/*
		std::cout << "what-0: "+ string(what[0].first, what[0].second) + "\n";
		std::cout << "what-1: "+ string(what[1].first, what[1].second) + "\n";
		std::cout << "what-2: "+ string(what[2].first, what[2].second) + "\n";
		std::cout << "what-3: "+ string(what[3].first, what[3].second) + "\n";
		*/

		string connWord = string(what[1].first, what[1].second);
		string sentIndex = string(what[2].first, what[2].second);
		string synNodeIndex = string(what[3].first, what[3].second) ;
		Symbol label = Symbol (L"CONN");
		string PDTBindex = docName+"%"+connWord+"%"+sentIndex+"%"+synNodeIndex;
		std::cout << "add key-value pair : " + PDTBindex + "-"  << label << "\n"  ;
		(*_connective_table)[PDTBindex]=label;
	}
}

void PennDiscourseTreebank::findConnLocation (string docName, const char *onelineOfPDTB, TargetConnectives::ExplicitConnectiveDict * connectiveDict){
	//boost::regex expression("^(template[[:space:]]*<[^;:{]+>[[:space:]]*)?(class|struct)[[:space:]]*(\\<\\w+\\>([[:blank:]]*\\([^)]*\\))?[[:space:]]*)*(\\<\\w*\\>)[[:space:]]*(<[^;:{]+>[[:space:]]*)?(\\{|:[^;\\{()]*\\{)");
	boost::regex expression("^link info\\: (\\w+) @(\\d+)-(\\d+)");
	string line = onelineOfPDTB;
	string::const_iterator start, end;
	start = line.begin();
	end = line.end();
    boost::match_results<string::const_iterator> what;
	boost::match_flag_type flags = boost::match_default;

	if (regex_search(start, end, what, expression, flags)) {
		// what[0] contains the string pattern matching the whole reg expression
		// what[1] contains the word
		// what[2] contains the sent index
		// what[3] contains the position

		/*
		std::cout << "what-0: "+ string(what[0].first, what[0].second) + "\n";
		std::cout << "what-1: "+ string(what[1].first, what[1].second) + "\n";
		std::cout << "what-2: "+ string(what[2].first, what[2].second) + "\n";
		std::cout << "what-3: "+ string(what[3].first, what[3].second) + "\n";
		*/

		string connWord = string(what[1].first, what[1].second);
		string sentIndex = string(what[2].first, what[2].second);
		string synNodeIndex = string(what[3].first, what[3].second) ;
		Symbol label = Symbol (L"CONN");
		string PDTBindex = docName+"%"+connWord+"%"+sentIndex+"%"+synNodeIndex;

		map <string, int>::iterator myIterator = connectiveDict->find(connWord);

		if(myIterator != connectiveDict->end())
		{
			SessionLogger::info("SERIF") << "add key-value pair : " + PDTBindex + "-"  << label << "\n"  ;
			(*_connective_table)[PDTBindex]=label;
		}
	}
}

Symbol PennDiscourseTreebank::getLabelofExpConnective(string docName, string word, string sentIndex, string SynNodeId){
	string PDTBindex = docName+"%"+word+"%"+sentIndex+"%"+SynNodeId;

	map <string, Symbol>::iterator myIterator = _connective_table->find(PDTBindex);

    if(myIterator != _connective_table->end())
    {
        //Its in the table
		Symbol label = myIterator->second;
		return label;
	}else{
		//throw UnexpectedInputException("invalid key for PDTB dictionary: ", PDTBindex.c_str());
		return Symbol(L"-EMPTY-");
	}
}

Symbol PennDiscourseTreebank::getLabelofCrossSentRel(string docName, string sentIndex){
	string PDTBindex = docName+"%"+sentIndex;
	CrossSentRelationTable::iterator myIterator = _crossSentRel_table->find(PDTBindex);
	if (myIterator != _crossSentRel_table->end()){
		return Symbol(L"CS_REL");
	}else{
		return Symbol(L"-EMPTY-");
	}
}

vector<CrossSentRelation>* PennDiscourseTreebank::getCrossSentRel(string docName, string sentIndex){
	string PDTBindex = docName+"%"+sentIndex;
	CrossSentRelationTable::iterator myIterator = _crossSentRel_table->find(PDTBindex);
	if (myIterator != _crossSentRel_table->end()){
		return &(*_crossSentRel_table)[PDTBindex];
	}else{
		return 0;
	}
}

void PennDiscourseTreebank::finalize()
{
	if (_connective_table != 0)
	{
	    delete _connective_table;
	    _connective_table = 0;
	}

	if (_crossSentRel_table != 0)
	{
		delete _crossSentRel_table;
		_crossSentRel_table = 0;
	}
}

max_stars_repo_name: BBN-E/serif

max_issues_repo_name: BBN-E/serif

max_forks_repo_name: BBN-E/serif


text:
#include <iostream>
#include <fstream>
#include <string>
#include <Eigen/Cholesky>
#include <adept_arrays.h>
#include <chrono>

using namespace adept;
using namespace std;
using namespace std::chrono;
int main(int argc, char **argv)
{
   string output_filename = argv[1];
   cout << output_filename << endl;

   int num_params = 4010;
   int num_vars = 1;

   Stack stack;
   aVector  k(num_params);

   Eigen::VectorXd args(num_params * num_vars);
   Eigen::VectorXd ders(num_params * num_vars);

   std::ifstream file("./tests/utils/params.txt");
   int i = 0;
   for (std::string line; std::getline(file, line);)
   {
       args(i) = stod(line.c_str());
       i++;
   }
   file.close();

   for (int index = 0; index < num_params; index++) {
			k(index) = args[index * num_vars + 0];
    }

   ofstream outfile;
   outfile.open(output_filename);

   auto start = high_resolution_clock::now();
   stack.new_recording();                 // Clear any existing differential statements
   aReal J = sum(((k*k+3*k)-k/4)/k+k*k*k*k+k*k*(22/7*k)+k*k*k*k*k*k*k*k*k);
   J.set_gradient(1.0);                   // Seed the dependent variable
   stack.reverse();                       // Reverse-mode differentiation

   auto stop = high_resolution_clock::now();
   auto duration = duration_cast<microseconds>(stop - start);
   outfile << (double)duration.count() / 1000000.0 << " ";
   for (int index = 0; index < num_params; index++) {
			ders[index * num_vars + 0] = k.get_gradient()[index];
    }
   for (int i = 0; i < num_params * num_vars; i++)
   {
        ostringstream ss;
        ss.precision(3);
       ss << fixed << ders[i];
       outfile << ss.str() << " ";
   }

   outfile.close();

   return 0;
}

max_stars_repo_name: jiangzhongshi/acorns-benchmark

max_issues_repo_name: jiangzhongshi/acorns-benchmark

max_forks_repo_name: jiangzhongshi/acorns-benchmark