<<<<<<< HEAD
/*    Copyright (c) 2010-2018, Delft University of Technology
=======
/*    Copyright (c) 2010-2019, Delft University of Technology
>>>>>>> origin/master
 *    All rigths reserved
 *
 *    This file is part of the Tudat. Redistribution and use in source and
 *    binary forms, with or without modification, are permitted exclusively
 *    under the terms of the Modified BSD license. You should have received
 *    a copy of the license with this file. If not, please or visit:
 *    http://tudat.tudelft.nl/LICENSE.
 */

#define BOOST_TEST_MAIN

#include <boost/test/unit_test.hpp>

#include <vector>

#include "Tudat/Basics/testMacros.h"
#include "Tudat/InputOutput/matrixTextFileReader.h"

#include "Tudat/Mathematics/Interpolators/hermiteCubicSplineInterpolator.h"
#include "Tudat/InputOutput/basicInputOutput.h"

namespace tudat
{
namespace unit_tests
{

BOOST_AUTO_TEST_SUITE( test_hermite_cubic_spline_interpolator )

// Test implementation of cubic spline class.
BOOST_AUTO_TEST_CASE( testHermiteCubicSplineInterpolator )
{
    // Test 1: Compare with analytical function 2 + 3x + 5x^2.
    // dy/dx = 10x + 3
    {
        // Declare and initialize independent variable values.
        std::vector< double > independentVariables;
        independentVariables.resize( 6 );
        independentVariables[ 0 ] = 1.0;
        independentVariables[ 1 ] = 3.0;
        independentVariables[ 2 ] = 5.0;
        independentVariables[ 3 ] = 7.0;
        independentVariables[ 4 ] = 9.0;
        independentVariables[ 5 ] = 11.0;

        // Declare and initialize dependent variable values.
        std::vector< double > dependentVariables;
        dependentVariables.resize( 6 );
        dependentVariables[ 0 ] = 10.0;
        dependentVariables[ 1 ] = 56.0;
        dependentVariables[ 2 ] = 142.0;
        dependentVariables[ 3 ] = 268.0;
        dependentVariables[ 4 ] = 434.0;
        dependentVariables[ 5 ] = 640.0;

        // Declare and initialize dependent variable values.
        std::vector< double > derivatives;
        derivatives.resize( 6 );
        derivatives[ 0 ] = 13.0;
        derivatives[ 1 ] = 33.0;
        derivatives[ 2 ] = 53.0;
        derivatives[ 3 ] = 73.0;
        derivatives[ 4 ] = 93.0;
        derivatives[ 5 ] = 113.0;

        // Declare and initialize target independent variable value.
        double targetIndependentVariableValue = 6.0;

        // Declare and initialize expected result of interpolation from analytical equation.
        double analyticalValue = 200.0;

        // Declare cubic spline object and initialize with input data.
        interpolators::HermiteCubicSplineInterpolatorDouble interpolator(
                    independentVariables, dependentVariables , derivatives );

        // Declare interpolated dependent variable value and execute interpolation.
        double interpolatedDependentVariableValue = interpolator.interpolate(
                    targetIndependentVariableValue );

        // Check if test result match analytical result.
        BOOST_CHECK_SMALL(  std::fabs( analyticalValue - interpolatedDependentVariableValue )
                            / analyticalValue, 1.0e-15 );

        // Second test
        targetIndependentVariableValue = 2.0;
        analyticalValue = 28.0;

        interpolatedDependentVariableValue = interpolator.interpolate(
                    targetIndependentVariableValue );

        // Check if test result match analytical result.
        BOOST_CHECK_SMALL(  std::fabs( analyticalValue - interpolatedDependentVariableValue )
                            / analyticalValue, 1.0e-15 );
    }
}

// Test implementation of cubic Hermite spline class against Matlab (pchipd from Mathworks central).
BOOST_AUTO_TEST_CASE( testHermiteCubicSplineInterpolatorWithMatlab )
{
    // Test 1: Compare with equispace solution for sin(2x)
    {
        // Declare and initialize independent variable values.
        std::vector< double > independentVariables;
        std::vector< double > dependentVariables;
        std::vector< double > derivatives;

        independentVariables.resize( 10 );
        dependentVariables.resize( 10 );
        derivatives.resize( 10 );

        for( unsigned int i = 0; i < 10; i++ )
        {
            independentVariables[ i ] = static_cast< double >( i ) * 2.0 / 3.0;
            dependentVariables[ i ] = std::sin( 2.0 * independentVariables[ i ] );
            derivatives[ i ] = 2.0 * std::cos( 2.0 * independentVariables[ i ] );
        }

        // Declare cubic spline object and initialize with input data.
        interpolators::HermiteCubicSplineInterpolatorDouble interpolator(
                    independentVariables, dependentVariables , derivatives );

        std::vector< double > matlabResults = { 0.0,        -0.500127989105607,        0.860566028073899, -0.995666072885886 };

        for( unsigned int i = 0; i < 4; i++ )
        {
            double targetIndependentVariableValue =  static_cast< double >( i ) * 11.0 / 6.0;
            // Declare interpolated dependent variable value and execute interpolation.
            double interpolatedDependentVariableValue = interpolator.interpolate(
                        targetIndependentVariableValue );

            // Check if test result match analytical result.
            BOOST_CHECK_SMALL( std::fabs( matlabResults.at( i ) - interpolatedDependentVariableValue ), 1.0e-15 );

        }
    }

    // Test 2: Compare with non-equispaced solution for sin(2x)
    {
        // Declare and initialize independent variable values.
        std::vector< double > independentVariables =
        { 0.100,        0.250,        0.600,        0.620,        1.0,        1.40,        1.51,        2.0,        3.0};
        std::vector< double > dependentVariables;
        std::vector< double > derivatives;

        for( unsigned int i = 0; i < independentVariables.size( ); i++ )
        {
            dependentVariables.push_back( std::sin( 2.0 * independentVariables[ i ] ) );
            derivatives.push_back( 2.0 * std::cos( 2.0 * independentVariables[ i ] ) );
        }

        // Declare cubic spline object and initialize with input data.
        interpolators::HermiteCubicSplineInterpolatorDouble interpolator(
                    independentVariables, dependentVariables , derivatives );

        std::vector< double > matlabResults =
        { -0.000114788941438321,        0.956262264186293,        -0.557211110925702,        -0.616700531016027 };

        for( unsigned int i = 0; i < 4; i++ )
        {
            double targetIndependentVariableValue =  static_cast< double >( i ) * 2.8 / 3.0;
            // Declare interpolated dependent variable value and execute interpolation.
            double interpolatedDependentVariableValue = interpolator.interpolate(
                        targetIndependentVariableValue );

            // Check if test result match analytical result.
            BOOST_CHECK_SMALL( std::fabs( matlabResults.at( i ) - interpolatedDependentVariableValue ), 2.0e-15 );

        }
    }
}

BOOST_AUTO_TEST_SUITE_END( )

} // namespace unit_tests

} // namespace tudat


#include <cstdio>

#if defined(USE_OPENGL)
    #include <GL/glut.h>
#endif

#include "Color.h"
#include "Ray.h"
#include "Surface.h"
#include "SurfaceList.h"
#include "Sphere.h"
#include "Plane.h"
#include "Triangle.h"
#include "Intersection.h"
#include "Scene.h"
#include "KD.h"
#include "Mesh.h"

#include <Eigen/Dense>

#include <argparser.h>
#include <easyppm.h>

constexpr int NX = 512;
constexpr int NY = 512;

Color* buffer;

PPM ppm;

#if defined(USE_OPENGL)
void gl_display() {
    glClearColor(0,0,0,1);
    glClear(GL_COLOR_BUFFER_BIT);

    float* float_buffer = new float[3*NX*NY];

    int k = 0;
    for (int i = 0; i < NX; i++) {
        for (int j = 0; j < NY; j++) {
            float_buffer[k++] = buffer[j*NY + i].r;
            float_buffer[k++] = buffer[j*NY + i].g;
            float_buffer[k++] = buffer[j*NY + i].b;
        }
    }

    glDrawPixels(NX, NY, GL_RGB, GL_FLOAT, float_buffer);

    glutSwapBuffers();

    delete[] float_buffer;
}

void gl_keyboard(unsigned char key, int x, int y) {
    switch (key) {
        // ESC
        case 27:
            exit(EXIT_SUCCESS);
    }
}
#endif

int clamp(int x, int min, int max) {
    return std::max(min, std::min(x, max));
}

int main(int argc, char* argv[]) {
    int shadows = 0;

    argparser ap = argparser_create(argc, argv, PARSEMODE_LENIENT);
    argparser_add(&ap, "-s", "--shadows", ARGTYPE_BOOL, &shadows, "Use shadows in kd-tree");
    argparser_parse(&ap);

    constexpr float l = -0.1f;
    constexpr float r =  0.1f;
    constexpr float b = -0.1f;
    constexpr float t =  0.1f;

    constexpr float dist = 0.1f;

#ifndef USE_OPENGL
    ppm = easyppm_create(NX, NY, IMAGETYPE_PPM);
#endif

    // Load mesh into k-d tree
    mesh_load("sibenik.obj");
    kd_load("kdtree.simple", kd_tree);

    // Light
    auto light = Light(Eigen::Vector3f(0,0,0), 1);

    // All triangles share the same material
    Material mt(Color(0,0,0), Color(1,1,1), Color(0,0,0), 0, 0);

    // Fill pixel buffer
    buffer = new Color[NX*NY];
    for (int i = 0; i < NX; i++) {
        for (int j = 0; j < NY; j++) {
            float uu = l + ((r-l)*(i+0.5f)/NX);
            float vv = b + ((t-b)*(j+0.5f)/NY);

            auto e = Eigen::Vector3f( 0, -10,   0);
            auto u = Eigen::Vector3f( 0,   0,   1);
            auto v = Eigen::Vector3f( 0,   1,   0);
            auto w = Eigen::Vector3f(-1,   0,   0);

            auto s = e + uu*u + vv*v - dist*w;

            auto p = e;
            auto d = s - e;

            auto ray = Ray(p, d);

            auto triangles = kd_intersect(ray, kd_tree, 0, mt);

            auto scene = Scene(triangles, light);

            auto hit = scene.intersect(ray);
            if (hit) {
                auto color = scene.shade(ray, *hit, 2, shadows, true).correct(2.2f);
            #if defined(USE_OPENGL)
                buffer[i*NY + j] = color;
            #else
                auto r = clamp(color.r * 255, 0, 255);
                auto g = clamp(color.g * 255, 0, 255);
                auto b = clamp(color.b * 255, 0, 255);
                easyppm_set(&ppm, i, j, easyppm_rgb(r, g, b));
            #endif
            }

            #if !defined(USE_OPENGL)
                printf("Rendering complete for pixel (%3d, %3d)\r", i, j);
            #endif
        }
    }
    printf("\n");

    #if defined(USE_OPENGL)
        // Write buffer to OpenGL window
        glutInit(&argc, argv);
        glutInitDisplayMode(GLUT_RGB | GLUT_DEPTH | GLUT_DOUBLE);
        glutInitWindowSize(NX, NY);
        glutCreateWindow(shadows ? "Part 5 (with shadows)" : "Part 5 (without shadows)");
        glutDisplayFunc(gl_display);
        glutKeyboardFunc(gl_keyboard);
        glutMainLoop();
    #else
        // Write buffer to image file
        const char* path = shadows ? "images/part5b.ppm" : "images/part5a.ppm";

        easyppm_invert_y(&ppm);
        easyppm_write(&ppm, path);
        easyppm_destroy(&ppm);

        printf("Image written to %s\n", path);
    #endif

    delete[] buffer;

    return 0;
}


#pragma once

#include <numeric>
#include <vector>
#include <utility>

#include <opencv2/core/core.hpp>
#include <Eigen/Dense>

cv::Mat stitchImages(
    const cv::Mat &sourceImage, const cv::Mat &targetImage);

namespace utility
{

cv::Mat eigenToCv(const Eigen::Matrix3d &rhs);

} // end namespace utility


/*
 ISC License

 Copyright (c) 2016, Autonomous Vehicle Systems Lab, University of Colorado at Boulder

 Permission to use, copy, modify, and/or distribute this software for any
 purpose with or without fee is hereby granted, provided that the above
 copyright notice and this permission notice appear in all copies.

 THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.

 */

#include <stdio.h>
#include <stdlib.h>
#include "saturateCheck.h"
#include <Eigen/Dense>
#include "utilities/avsEigenSupport.h"
#include "utilities/saturate.h"

uint64_t testSaturate()
{
    uint64_t failures = 0;
    Eigen::Vector3d states;
    states << -555, 1.27, 5000000.;
    Saturate saturator = Saturate(3);
    Eigen::MatrixXd bounds;
    bounds.resize(3,2);
    bounds << -400., 0, 5, 10, -1, 5000001;
    saturator.setBounds(bounds);
    states = saturator.saturate(states);
    Eigen::Vector3d expected;
    expected << -400, 5, 5000000;
    failures += expected != states ? 1 : 0;

    return failures;

}


/*
 * GraphBLAS Template Library (GBTL), Version 3.0
 *
 * Copyright 2020 Carnegie Mellon University, Battelle Memorial Institute, and
 * Authors.
 *
 * THIS MATERIAL WAS PREPARED AS AN ACCOUNT OF WORK SPONSORED BY AN AGENCY OF
 * THE UNITED STATES GOVERNMENT.  NEITHER THE UNITED STATES GOVERNMENT NOR THE
 * UNITED STATES DEPARTMENT OF ENERGY, NOR THE UNITED STATES DEPARTMENT OF
 * DEFENSE, NOR CARNEGIE MELLON UNIVERSITY, NOR BATTELLE, NOR ANY OF THEIR
 * EMPLOYEES, NOR ANY JURISDICTION OR ORGANIZATION THAT HAS COOPERATED IN THE
 * DEVELOPMENT OF THESE MATERIALS, MAKES ANY WARRANTY, EXPRESS OR IMPLIED, OR
 * ASSUMES ANY LEGAL LIABILITY OR RESPONSIBILITY FOR THE ACCURACY, COMPLETENESS,
 * OR USEFULNESS OR ANY INFORMATION, APPARATUS, PRODUCT, SOFTWARE, OR PROCESS
 * DISCLOSED, OR REPRESENTS THAT ITS USE WOULD NOT INFRINGE PRIVATELY OWNED
 * RIGHTS.
 *
 * Released under a BSD-style license, please see LICENSE file or contact
 * permission@sei.cmu.edu for full terms.
 *
 * [DISTRIBUTION STATEMENT A] This material has been approved for public release
 * and unlimited distribution.  Please see Copyright notice for non-US
 * Government use and distribution.
 *
 * This Software includes and/or makes use of the following Third-Party Software
 * subject to its own license:
 *
 * 1. Boost Unit Test Framework
 * (https://www.boost.org/doc/libs/1_45_0/libs/test/doc/html/utf.html)
 * Copyright 2001 Boost software license, Gennadiy Rozental.
 *
 * DM20-0442
 */

#define GRAPHBLAS_LOGGING_LEVEL 0

#include <graphblas/graphblas.hpp>

using namespace grb;

#define BOOST_TEST_MAIN
#define BOOST_TEST_MODULE ewisemult_matrix_test_suite

#include <boost/test/included/unit_test.hpp>

BOOST_AUTO_TEST_SUITE(BOOST_TEST_MODULE)

//****************************************************************************

namespace
{
    std::vector<std::vector<double> > m3x3_dense = {{12, 0, 7},
                                                    {1,  0, 0},
                                                    {3,  6, 9}};

    std::vector<std::vector<double> > eye3x3_dense = {{1, 0, 0},
                                                      {0, 1, 0},
                                                      {0, 0, 1}};

    std::vector<std::vector<double> > twos3x3_dense = {{2, 2, 2},
                                                       {2, 2, 2},
                                                       {2, 2, 2}};

    std::vector<std::vector<double> > zero3x3_dense = {{0, 0, 0},
                                                       {0, 0, 0},
                                                       {0, 0, 0}};

    std::vector<std::vector<double> > ans_twos3x3_dense = {{24,  0, 14},
                                                           { 2,  0,  0},
                                                           { 6, 12, 18}};

    std::vector<std::vector<double> > ans_eye3x3_dense = {{12,  0,  0},
                                                          { 0,  0,  0},
                                                          { 0,  0,  9}};

    std::vector<std::vector<double> > m3x4_dense = {{5, 0, 1, 2},
                                                    {6, 7, 0, 0},
                                                    {4, 5, 0, 1}};

    std::vector<std::vector<double> > m4x3_dense = {{5, 6, 4},
                                                    {0, 7, 5},
                                                    {1, 0, 0},
                                                    {2, 0, 1}};

    std::vector<std::vector<double> > twos4x3_dense = {{2, 2, 2},
                                                       {2, 2, 2},
                                                       {2, 2, 2},
                                                       {2, 2, 2}};

    std::vector<std::vector<double> > twos3x4_dense = {{2, 2, 2, 2},
                                                       {2, 2, 2, 2},
                                                       {2, 2, 2, 2}};

    std::vector<std::vector<double> > ans_twos4x3_dense = {{10, 12,  8},
                                                           {0,  14, 10},
                                                           {2,   0,  0},
                                                           {4,   0,  2}};
    std::vector<std::vector<double> > ans_twos3x4_dense = {{10,  0,  2, 4},
                                                           {12, 14,  0, 0},
                                                           { 8, 10,  0, 2}};
}

//****************************************************************************

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_bad_dimensions)
{
    IndexArrayType i_m1    = {0, 0, 1, 1, 2, 2, 3};
    IndexArrayType j_m1    = {0, 1, 1, 2, 2, 3, 3};
    std::vector<double> v_m1 = {1, 2, 2, 3, 3, 4, 4};
    Matrix<double, DirectedMatrixTag> m1(4, 4);
    m1.build(i_m1, j_m1, v_m1);

    IndexArrayType i_m2    = {0, 0, 1, 1, 1, 2, 2};
    IndexArrayType j_m2    = {0, 1, 0, 1, 2, 1, 2};
    std::vector<double> v_m2 = {2, 2, 1, 4, 4, 4, 6};
    Matrix<double, DirectedMatrixTag> m2(3, 4);
    m2.build(i_m2, j_m2, v_m2);

    Matrix<double, DirectedMatrixTag> m3(4, 4);

    BOOST_CHECK_THROW(
        eWiseMult(m3, NoMask(), NoAccumulate(),
                  Times<double>(), m1, m2),
        DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_bad_dimensions2)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(m3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(3, 3);

    // incompatible input dimensions
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(), mA, mB)),
        grb::DimensionException);

    // incompatible output matrix dimensions
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(), mB, mB)),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_overwrite_replace)
{
    using T = int32_t;

    std::vector<std::vector<T> > tmp1_dense = {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}};
    std::vector<std::vector<T> >  a10_dense = {{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1}};

    grb::Matrix<T> tmp1(tmp1_dense, 0);
    grb::Matrix<T> a10(a10_dense, 0);

    grb::eWiseMult(tmp1, grb::NoMask(), grb::NoAccumulate(),
                   grb::Times<T>(),
                   tmp1, a10, REPLACE);
    BOOST_CHECK_EQUAL(0, tmp1.nvals());

    //grb::print_matrix(std::cerr, tmp1, "tmp1");

    T delta(0);
    grb::reduce(delta, grb::Plus<T>(),
                grb::PlusMonoid<T>(), tmp1);

    BOOST_CHECK_EQUAL(delta, 0);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_semiring_matrix_overwrite_replace)
{
    using T = int32_t;

    std::vector<std::vector<T> > tmp1_dense = {{0, 0, 0, 1, 1, 0, 0, 0, 0, 0, 0}};
    std::vector<std::vector<T> >  a10_dense = {{0, 0, 0, 0, 0, 0, 1, 0, 0, 0, 1}};

    grb::Matrix<T> tmp1(tmp1_dense, 0);
    grb::Matrix<T> a10(a10_dense, 0);

    grb::eWiseMult(tmp1, grb::NoMask(), grb::NoAccumulate(),
                   multiply_op(grb::ArithmeticSemiring<T>()),
                   tmp1, a10, REPLACE);
    BOOST_CHECK_EQUAL(0, tmp1.nvals());

    //grb::print_matrix(std::cerr, tmp1, "tmp1");

    T delta(0);
    grb::reduce(delta,
                add_monoid(grb::ArithmeticSemiring<T>()),
                add_monoid(grb::ArithmeticSemiring<T>()),
                tmp1);

    BOOST_CHECK_EQUAL(delta, 0);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_normal)
{
    IndexArrayType i_mat    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};
    IndexArrayType j_mat    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};
    std::vector<double> v_mat = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4};
    Matrix<double, DirectedMatrixTag> mat(4, 4);
    mat.build(i_mat, j_mat, v_mat);

    Matrix<double, DirectedMatrixTag> m3(4, 4);

    IndexArrayType i_answer    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};
    IndexArrayType j_answer    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};
    std::vector<double> v_answer = {1, 1, 1, 4, 4, 4, 9, 9, 9, 16};
    Matrix<double, DirectedMatrixTag> answer(4, 4);
    answer.build(i_answer, j_answer, v_answer);

    eWiseMult(m3, NoMask(), NoAccumulate(),
              Times<double>(),
              mat, mat);

    BOOST_CHECK_EQUAL(m3, answer);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_normal_semiring)
{
    IndexArrayType i_mat    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};
    IndexArrayType j_mat    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};
    std::vector<double> v_mat = {1, 1, 1, 2, 2, 2, 3, 3, 3, 4};
    Matrix<double, DirectedMatrixTag> mat(4, 4);
    mat.build(i_mat, j_mat, v_mat);

    Matrix<double, DirectedMatrixTag> m3(4, 4);

    IndexArrayType i_answer    = {0, 0, 1, 1, 1, 2, 2, 2, 3, 3};
    IndexArrayType j_answer    = {0, 1, 0, 1, 2, 1, 2, 3, 2, 3};
    std::vector<double> v_answer = {1, 1, 1, 4, 4, 4, 9, 9, 9, 16};
    Matrix<double, DirectedMatrixTag> answer(4, 4);
    answer.build(i_answer, j_answer, v_answer);

    eWiseMult(m3, NoMask(), NoAccumulate(),
              multiply_op(ArithmeticSemiring<double>()),
              mat, mat);

    BOOST_CHECK_EQUAL(m3, answer);
}

//****************************************************************************
// Tests without mask
//****************************************************************************

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_reg)
{
    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x3_dense, 0.);

    // ewise mult with dense matrix
    grb::Matrix<double, grb::DirectedMatrixTag> B(twos3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(
        ans_twos3x3_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(3,3);

    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(), A, B);
    BOOST_CHECK_EQUAL(Result, Ans);

    // ewise mult with sparse matrix
    grb::Matrix<double, grb::DirectedMatrixTag> B2(eye3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans2(
        ans_eye3x3_dense, 0.);
    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(), A, B2);
    BOOST_CHECK_EQUAL(Result, Ans2);

    // ewise mult with empty matrix
    grb::Matrix<double, grb::DirectedMatrixTag> B3(zero3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans3(
        zero3x3_dense, 0.);
    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(), A, B3);
    BOOST_CHECK_EQUAL(Result, Ans3);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_stored_zero_result)
{
    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x3_dense, 0.);

    // Add a stored zero on the diagonal
    A.setElement(1, 1, 0);
    BOOST_CHECK_EQUAL(A.nvals(), 7);

    grb::Matrix<double, grb::DirectedMatrixTag> B2(eye3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans2(
        ans_eye3x3_dense, 0.);
    // Add a stored zero on the diagonal
    Ans2.setElement(1, 1, 0);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(3,3);

    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(), A, B2);
    BOOST_CHECK_EQUAL(Result, Ans2);
    BOOST_CHECK_EQUAL(Result.nvals(), 3);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_a_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> B(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(4,3);

    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(),
                   transpose(A), B);
    BOOST_CHECK_EQUAL(Result, Ans);

    grb::Matrix<double, grb::DirectedMatrixTag> B2(m3x4_dense, 0.);
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(),
                        transpose(A), A)),
        grb::DimensionException);

    grb::Matrix<double, grb::DirectedMatrixTag> Result2(3,3);
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result2,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(),
                        transpose(A), B)),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> A(m3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> B(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(3, 4);

    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(),
                   A, transpose(B));
    BOOST_CHECK_EQUAL(Result, Ans);

    grb::Matrix<double, grb::DirectedMatrixTag> B2(m3x4_dense, 0.);
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(),
                        B, transpose(B))),
        grb::DimensionException);

    grb::Matrix<double, grb::DirectedMatrixTag> Result2(3,3);
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result2,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(),
                        A, transpose(B))),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_a_and_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> A(m4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> B(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(3, 4);

    grb::eWiseMult(Result,
                   grb::NoMask(),
                   grb::NoAccumulate(),
                   grb::Times<double>(),
                   transpose(A), transpose(B));
    BOOST_CHECK_EQUAL(Result, Ans);

    grb::Matrix<double, grb::DirectedMatrixTag> B2(m3x4_dense, 0.);
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(),
                        transpose(Ans), transpose(B))),
        grb::DimensionException);

    grb::Matrix<double, grb::DirectedMatrixTag> Result2(3,3);
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result2,
                        grb::NoMask(),
                        grb::NoAccumulate(),
                        grb::Times<double>(),
                        transpose(A), transpose(B))),
        grb::DimensionException);
}

//****************************************************************************
// Tests using a mask with REPLACE
//****************************************************************************

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_replace_bad_dimensions)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);

    // incompatible Mask-Output dimensions
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        Mask,
                        grb::NoAccumulate(),
                        grb::Times<double>(), mA, mB,
                        REPLACE)),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_replace_reg)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  0},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 5);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  2},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 6);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_replace_reg_stored_zero)
{
    // tests a computed and stored zero
    // tests a stored zero in the mask
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense); //, 0.);
    BOOST_CHECK_EQUAL(Mask.nvals(), 12);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  0},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 5);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  2},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 6);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_replace_a_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {0,  14, 10},
                                                   {0,   0,  0},
                                                   {0,   0,  0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   Mask,
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), mB,
                   REPLACE);

    BOOST_CHECK_EQUAL(Result.nvals(), 5);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_replace_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {0,  14, 10},
                                                   {0,   0,  0},
                                                   {0,   0,  0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   Mask,
                   grb::NoAccumulate(),
                   grb::Times<double>(), mA, transpose(mB),
                   REPLACE);

    BOOST_CHECK_EQUAL(Result.nvals(), 5);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_replace_a_and_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {0,  14, 10},
                                                   {0,   0,  0},
                                                   {0,   0,  0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   Mask,
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), transpose(mB),
                   REPLACE);

    BOOST_CHECK_EQUAL(Result.nvals(), 5);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
// Tests using a mask with MERGE semantics
//****************************************************************************

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_bad_dimensions)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);

    // incompatible Mask-Output dimensions
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        Mask,
                        grb::NoAccumulate(),
                        grb::Times<double>(), mA, mB)),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_reg)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  0},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 11);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  2},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 12);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_reg_stored_zero)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense); //, 0.);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  0},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 11);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  2},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       Mask,
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 12);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_a_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {2,  14, 10},
                                                   {2,   2,  0},
                                                   {2,   2,  2}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   Mask,
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), mB);

    BOOST_CHECK_EQUAL(Result.nvals(), 11);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {2,  14, 10},
                                                   {2,   2,  0},
                                                   {2,   2,  2}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   Mask,
                   grb::NoAccumulate(),
                   grb::Times<double>(), mA, transpose(mB));

    BOOST_CHECK_EQUAL(Result.nvals(), 11);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_masked_a_and_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{1, 1, 1},
                                                    {0, 1, 1},
                                                    {0, 0, 1},
                                                    {0, 0, 0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {2,  14, 10},
                                                   {2,   2,  0},
                                                   {2,   2,  2}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   Mask,
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), transpose(mB));

    BOOST_CHECK_EQUAL(Result.nvals(), 11);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
// Tests using a complemented mask with REPLACE semantics
//****************************************************************************

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_replace_bad_dimensions)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);

    // incompatible Mask-Output dimensions
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::complement(Mask),
                        grb::NoAccumulate(),
                        grb::Times<double>(), mA, mB,
                        REPLACE)),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_replace_reg)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  0},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 5);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  2},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 6);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_replace_reg_stored_zero)
{
    // tests a computed and stored zero
    // tests a stored zero in the mask
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense); //, 0.);
    BOOST_CHECK_EQUAL(Mask.nvals(), 12);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  0},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 5);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {0,  14, 10},
                                                       {0,   0,  2},
                                                       {0,   0,  0}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB,
                       REPLACE);

        BOOST_CHECK_EQUAL(Result.nvals(), 6);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_replace_a_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {0,  14, 10},
                                                   {0,   0,  0},
                                                   {0,   0,  0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   grb::complement(Mask),
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), mB,
                   REPLACE);

    BOOST_CHECK_EQUAL(Result.nvals(), 5);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_replace_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {0,  14, 10},
                                                   {0,   0,  0},
                                                   {0,   0,  0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   grb::complement(Mask),
                   grb::NoAccumulate(),
                   grb::Times<double>(), mA, transpose(mB),
                   REPLACE);

    BOOST_CHECK_EQUAL(Result.nvals(), 5);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_replace_a_and_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {0,  14, 10},
                                                   {0,   0,  0},
                                                   {0,   0,  0}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   grb::complement(Mask),
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), transpose(mB),
                   REPLACE);

    BOOST_CHECK_EQUAL(Result.nvals(), 5);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
// Tests using a complemented mask (with merge semantics)
//****************************************************************************

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_bad_dimensions)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(twos3x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> Result(4, 3);

    // incompatible Mask-Output dimensions
    BOOST_CHECK_THROW(
        (grb::eWiseMult(Result,
                        grb::complement(Mask),
                        grb::NoAccumulate(),
                        grb::Times<double>(), mA, mB)),
        grb::DimensionException);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_reg)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  0},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 11);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  2},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 12);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_reg_stored_zero)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense);//, 0.);

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  0},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::NoAccumulate(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 11);
        BOOST_CHECK_EQUAL(Result, Ans);
    }

    {
        grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

        std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                       {2,  14, 10},
                                                       {2,   2,  2},
                                                       {2,   2,  2}};
        grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

        grb::eWiseMult(Result,
                       grb::complement(Mask),
                       grb::Second<double>(),
                       grb::Times<double>(), mA, mB);

        BOOST_CHECK_EQUAL(Result.nvals(), 12);
        BOOST_CHECK_EQUAL(Result, Ans);
    }
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_a_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m4x3_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {2,  14, 10},
                                                   {2,   2,  0},
                                                   {2,   2,  2}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   grb::complement(Mask),
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), mB);

    BOOST_CHECK_EQUAL(Result.nvals(), 11);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos4x3_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {2,  14, 10},
                                                   {2,   2,  0},
                                                   {2,   2,  2}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   grb::complement(Mask),
                   grb::NoAccumulate(),
                   grb::Times<double>(), mA, transpose(mB));

    BOOST_CHECK_EQUAL(Result.nvals(), 11);
    BOOST_CHECK_EQUAL(Result, Ans);
}

//****************************************************************************
BOOST_AUTO_TEST_CASE(test_ewisemult_matrix_scmp_masked_a_and_b_transpose)
{
    grb::Matrix<double, grb::DirectedMatrixTag> mA(twos3x4_dense, 0.);
    grb::Matrix<double, grb::DirectedMatrixTag> mB(m3x4_dense, 0.);

    std::vector<std::vector<double> > mask_dense = {{0, 0, 0},
                                                    {1, 0, 0},
                                                    {1, 1, 0},
                                                    {1, 1, 1}};
    grb::Matrix<double, grb::DirectedMatrixTag> Mask(mask_dense, 0.);

    grb::Matrix<double, grb::DirectedMatrixTag> Result(twos4x3_dense, 0.);

    std::vector<std::vector<double> > ans_dense = {{10, 12,  8},
                                                   {2,  14, 10},
                                                   {2,   2,  0},
                                                   {2,   2,  2}};
    grb::Matrix<double, grb::DirectedMatrixTag> Ans(ans_dense, 0.);

    grb::eWiseMult(Result,
                   grb::complement(Mask),
                   grb::NoAccumulate(),
                   grb::Times<double>(), transpose(mA), transpose(mB));

    BOOST_CHECK_EQUAL(Result.nvals(), 11);
    BOOST_CHECK_EQUAL(Result, Ans);
}

BOOST_AUTO_TEST_SUITE_END()


//  Copyright (c) 2006, Stephan Diederich
//
//  This code may be used under either of the following two licences:
//
//    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. OF SUCH DAMAGE.
//
//  Or:
//
//    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)

#include <boost/config.hpp>
#include <iostream>
#include <string>
#include <boost/graph/adjacency_list.hpp>
#include <boost/graph/read_dimacs.hpp>
#include <boost/graph/write_dimacs.hpp>

/*************************************
*
* example which reads in a max-flow problem from std::cin, augments all paths from
* source->NODE->sink and writes the graph back to std::cout
*
**************************************/

template <typename EdgeCapacityMap>
struct zero_edge_capacity{

  zero_edge_capacity() { }
  zero_edge_capacity(EdgeCapacityMap cap_map):m_cap_map(cap_map){};

  template <typename Edge>
      bool operator() (const Edge& e) const {
    return  get(m_cap_map, e) == 0 ;
      }

      EdgeCapacityMap m_cap_map;
};

int main()
{
  using namespace boost;
  typedef adjacency_list_traits < vecS, vecS, directedS > Traits;
  typedef adjacency_list < vecS, vecS, directedS,
  no_property,
  property < edge_capacity_t, long,
  property < edge_reverse_t, Traits::edge_descriptor > > > Graph;

  typedef graph_traits<Graph>::out_edge_iterator out_edge_iterator;
  typedef graph_traits<Graph>::edge_descriptor edge_descriptor;
  typedef graph_traits<Graph>::vertex_descriptor vertex_descriptor;

  Graph g;

  typedef property_map < Graph, edge_capacity_t >::type tCapMap;
  typedef tCapMap::value_type tCapMapValue;

  typedef property_map < Graph, edge_reverse_t >::type tRevEdgeMap;

  tCapMap capacity = get(edge_capacity, g);
  tRevEdgeMap rev = get(edge_reverse, g);

  vertex_descriptor s, t;
  /*reading the graph from stdin*/
  read_dimacs_max_flow(g, capacity, rev, s, t, std::cin);

  /*process graph*/
  tCapMapValue augmented_flow = 0;

  //we take the source node and check for each outgoing edge e which has a target(p) if we can augment that path
  out_edge_iterator oei,oe_end;
  for(tie(oei, oe_end) = out_edges(s, g); oei != oe_end; ++oei){
    edge_descriptor from_source = *oei;
    vertex_descriptor v = target(from_source, g);
    edge_descriptor to_sink;
    bool is_there;
    tie(to_sink, is_there) = edge(v, t, g);
    if( is_there ){
      if( get(capacity, to_sink) > get(capacity, from_source) ){
        tCapMapValue to_augment = get(capacity, from_source);
        capacity[from_source] = 0;
        capacity[to_sink] -= to_augment;
        augmented_flow += to_augment;
      }else{
        tCapMapValue to_augment = get(capacity, to_sink);
        capacity[to_sink] = 0;
        capacity[from_source] -= to_augment;
        augmented_flow += to_augment;
      }
    }
  }

  //remove edges with zero capacity (most of them are the reverse edges)
  zero_edge_capacity<tCapMap> filter(capacity);
  remove_edge_if(filter, g);

  /*write the graph back to stdout */
  write_dimacs_max_flow(g, capacity, identity_property_map(),s, t, std::cout);
  //print flow we augmented to std::cerr
  std::cerr << "removed " << augmented_flow << " from SOURCE->NODE->SINK connects" <<std::endl;
  return 0;
}


#include <stan/io/dump.hpp>
#include <stan/mcmc/hmc/hamiltonians/softabs_metric.hpp>
#include <stan/callbacks/stream_logger.hpp>
#include <stan/mcmc/hmc/hamiltonians/unit_e_metric.hpp>
#include <stan/mcmc/hmc/integrators/impl_leapfrog.hpp>

#include <test/test-models/good/mcmc/hmc/integrators/gauss.hpp>

#include <boost/random/additive_combine.hpp>  // L'Ecuyer RNG

#include <gtest/gtest.h>

#include <sstream>

typedef boost::ecuyer1988 rng_t;

TEST(McmcHmcIntegratorsImplLeapfrog, unit_e_energy_conservation) {
  rng_t base_rng(0);

  std::fstream data_stream(std::string("").c_str(), std::fstream::in);
  stan::io::dump data_var_context(data_stream);
  data_stream.close();

  std::stringstream model_output;
  std::stringstream debug, info, warn, error, fatal;
  stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);

  gauss_model_namespace::gauss_model model(data_var_context, &model_output);

  stan::mcmc::impl_leapfrog<
    stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> >
    integrator;

  stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> metric(model);

  stan::mcmc::unit_e_point z(1);
  z.q(0) = 1;
  z.p(0) = 1;

  metric.init(z, logger);
  double H0 = metric.H(z);
  double aveDeltaH = 0;

  double epsilon = 1e-3;
  double tau = 6.28318530717959;
  size_t L = tau / epsilon;

  for (size_t n = 0; n < L; ++n) {
    integrator.evolve(z, metric, epsilon, logger);

    double deltaH = metric.H(z) - H0;
    aveDeltaH += (deltaH - aveDeltaH) / double(n + 1);
  }

  // Average error in Hamiltonian should be O(epsilon^{2})
  // in general, smaller for the gauss_model in this case due to cancellations
  EXPECT_NEAR(aveDeltaH, 0, epsilon * epsilon);

  EXPECT_EQ("", model_output.str());
  EXPECT_EQ("", debug.str());
  EXPECT_EQ("", info.str());
  EXPECT_EQ("", warn.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", fatal.str());
}

TEST(McmcHmcIntegratorsImplLeapfrog, unit_e_symplecticness) {
  rng_t base_rng(0);

  std::fstream data_stream(std::string("").c_str(), std::fstream::in);
  stan::io::dump data_var_context(data_stream);
  data_stream.close();

  std::stringstream model_output;
  std::stringstream debug, info, warn, error, fatal;
  stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);

  gauss_model_namespace::gauss_model model(data_var_context, &model_output);

  stan::mcmc::impl_leapfrog<
    stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> >
    integrator;

  stan::mcmc::unit_e_metric<gauss_model_namespace::gauss_model, rng_t> metric(model);

  // Create a circle of points
  const int n_points = 1000;

  double pi = 3.141592653589793;
  double r = 1.5;
  double q0 = 1;
  double p0 = 0;

  std::vector<stan::mcmc::unit_e_point> z;

  for (int i = 0; i < n_points; ++i) {
    z.push_back(stan::mcmc::unit_e_point(1));

    double theta = 2 * pi * (double)i / (double)n_points;
    z.back().q(0) = r * cos(theta) + q0;
    z.back().p(0)    = r * sin(theta) + p0;
  }

  // Evolve circle
  double epsilon = 1e-3;
  size_t L = pi / epsilon;

  for (int i = 0; i < n_points; ++i)
    metric.init(z.at(i), logger);

  for (size_t n = 0; n < L; ++n)
    for (int i = 0; i < n_points; ++i)
      integrator.evolve(z.at(i), metric, epsilon, logger);

  // Compute area of evolved shape using divergence theorem in 2D
  double area = 0;

  for (int i = 0; i < n_points; ++i) {

    double x1 = z[i].q(0);
    double y1 = z[i].p(0);
    double x2 = z[(i + 1) % n_points].q(0);
    double y2 = z[(i + 1) % n_points].p(0);

    double x_bary = 0.5 * (x1 + x2);
    double y_bary = 0.5 * (y1 + y2);

    double x_delta = x2 - x1;
    double y_delta = y2 - y1;

    double a = sqrt( x_delta * x_delta + y_delta * y_delta);

    double x_norm = 1;
    double y_norm = - x_delta / y_delta;
    double norm = sqrt( x_norm * x_norm + y_norm * y_norm );

    a *= (x_bary * x_norm + y_bary * y_norm) / norm;
    a = a < 0 ? -a : a;

    area += a;

  }

  area *= 0.5;

  // Symplectic integrators preserve volume (area in 2D)
  EXPECT_NEAR(area, pi * r * r, 1e-2);

  EXPECT_EQ("", model_output.str());
  EXPECT_EQ("", debug.str());
  EXPECT_EQ("", info.str());
  EXPECT_EQ("", warn.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", fatal.str());
}

TEST(McmcHmcIntegratorsImplLeapfrog, softabs_energy_conservation) {
  rng_t base_rng(0);

  std::fstream data_stream(std::string("").c_str(), std::fstream::in);
  stan::io::dump data_var_context(data_stream);
  data_stream.close();

  std::stringstream model_output;
  std::stringstream debug, info, warn, error, fatal;
  stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);

  gauss_model_namespace::gauss_model model(data_var_context, &model_output);

  stan::mcmc::impl_leapfrog<
    stan::mcmc::softabs_metric<gauss_model_namespace::gauss_model, rng_t> >
    integrator;

  stan::mcmc::softabs_metric<gauss_model_namespace::gauss_model, rng_t> metric(model);

  stan::mcmc::softabs_point z(1);
  z.q(0) = 1;
  z.p(0) = 1;

  metric.init(z, logger);
  double H0 = metric.H(z);
  double aveDeltaH = 0;

  double epsilon = 1e-3;
  double tau = 6.28318530717959;
  size_t L = tau / epsilon;

  for (size_t n = 0; n < L; ++n) {
    integrator.evolve(z, metric, epsilon, logger);

    double deltaH = metric.H(z) - H0;
    aveDeltaH += (deltaH - aveDeltaH) / double(n + 1);
  }

  // Average error in Hamiltonian should be O(epsilon^{2})
  // in general, smaller for the gauss_model in this case due to cancellations
  EXPECT_NEAR(aveDeltaH, 0, epsilon * epsilon);

  EXPECT_EQ("", model_output.str());
  EXPECT_EQ("", debug.str());
  EXPECT_EQ("", info.str());
  EXPECT_EQ("", warn.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", fatal.str());
}

TEST(McmcHmcIntegratorsImplLeapfrog, softabs_symplecticness) {
  rng_t base_rng(0);

  std::fstream data_stream(std::string("").c_str(), std::fstream::in);
  stan::io::dump data_var_context(data_stream);
  data_stream.close();

  std::stringstream model_output;
  std::stringstream debug, info, warn, error, fatal;
  stan::callbacks::stream_logger logger(debug, info, warn, error, fatal);

  gauss_model_namespace::gauss_model model(data_var_context, &model_output);

  stan::mcmc::impl_leapfrog<
    stan::mcmc::softabs_metric<gauss_model_namespace::gauss_model, rng_t> >
    integrator;

  stan::mcmc::softabs_metric<gauss_model_namespace::gauss_model, rng_t> metric(model);

  // Create a circle of points
  const int n_points = 1000;

  double pi = 3.141592653589793;
  double r = 1.5;
  double q0 = 1;
  double p0 = 0;

  std::vector<stan::mcmc::softabs_point> z;

  for (int i = 0; i < n_points; ++i) {
    z.push_back(stan::mcmc::softabs_point(1));

    double theta = 2 * pi * (double)i / (double)n_points;
    z.back().q(0) = r * cos(theta) + q0;
    z.back().p(0)    = r * sin(theta) + p0;
  }

  // Evolve circle
  double epsilon = 1e-3;
  size_t L = pi / epsilon;

  for (int i = 0; i < n_points; ++i)
    metric.init(z.at(i), logger);

  for (size_t n = 0; n < L; ++n)
    for (int i = 0; i < n_points; ++i)
      integrator.evolve(z.at(i), metric, epsilon, logger);

  // Compute area of evolved shape using divergence theorem in 2D
  double area = 0;

  for (int i = 0; i < n_points; ++i) {

    double x1 = z[i].q(0);
    double y1 = z[i].p(0);
    double x2 = z[(i + 1) % n_points].q(0);
    double y2 = z[(i + 1) % n_points].p(0);

    double x_bary = 0.5 * (x1 + x2);
    double y_bary = 0.5 * (y1 + y2);

    double x_delta = x2 - x1;
    double y_delta = y2 - y1;

    double a = sqrt( x_delta * x_delta + y_delta * y_delta);

    double x_norm = 1;
    double y_norm = - x_delta / y_delta;
    double norm = sqrt( x_norm * x_norm + y_norm * y_norm );

    a *= (x_bary * x_norm + y_bary * y_norm) / norm;
    a = a < 0 ? -a : a;

    area += a;

  }

  area *= 0.5;

  // Symplectic integrators preserve volume (area in 2D)
  EXPECT_NEAR(area, pi * r * r, 1e-2);

  EXPECT_EQ("", model_output.str());
  EXPECT_EQ("", debug.str());
  EXPECT_EQ("", info.str());
  EXPECT_EQ("", warn.str());
  EXPECT_EQ("", error.str());
  EXPECT_EQ("", fatal.str());
}


/*
@copyright Louis Dionne 2015
Distributed under the Boost Software License, Version 1.0.
(See accompanying file LICENSE.md or copy at http://boost.org/LICENSE_1_0.txt)
 */

#include <boost/hana/assert.hpp>
#include <boost/hana/bool.hpp>
#include <boost/hana/either.hpp>
#include <boost/hana/functional.hpp>
#include <boost/hana/tuple.hpp>

#include <string>
using namespace boost::hana;
using namespace std::literals;

//! [main]
template <char op>
auto function = left(op + std::string{" is not a valid operation"});

template <>
auto function<'+'> = right([](auto x, auto y) {
    return x + y;
});

template <>
auto function<'-'> = right([](auto x, auto y) {
    return x - y;
});

// and so on...

template <char n>
auto digit = if_(bool_<(n >= '0' && n <= '9')>,
    right(static_cast<int>(n - 48)),
    left(n + std::string{" is not a valid digit"})
);

template <char x, char op, char y>
auto evaluate = ap(function<op>, digit<x>, digit<y>);

int main() {
    BOOST_HANA_RUNTIME_CHECK(evaluate<'1', '+', '2'> == right(1 + 2));

    BOOST_HANA_RUNTIME_CHECK(evaluate<'?', '+', '2'> == left("? is not a valid digit"s));
    BOOST_HANA_RUNTIME_CHECK(evaluate<'1', '?', '2'> == left("? is not a valid operation"s));
    BOOST_HANA_RUNTIME_CHECK(evaluate<'1', '+', '?'> == left("? is not a valid digit"s));
    BOOST_HANA_RUNTIME_CHECK(evaluate<'?', '?', '?'> == left("? is not a valid operation"s));
}
//! [main]


/***************************************************************************
 *   Copyright (C) 2008 by Regis Behmo,,,   *
 *   regis.behmo@ecp.fr   *
 *                                                                         *
 *   This program is free software; you can redistribute it and/or modify  *
 *   it under the terms of the GNU General Public License as published by  *
 *   the Free Software Foundation; either version 2 of the License, or     *
 *   (at your option) any later version.                                   *
 ***************************************************************************/

#include <cstdlib>
#include <gsl/gsl_multifit.h>
#include <lshkit.h>
#include <boost/tr1/memory.hpp>

using namespace std;
using namespace lshkit;
using namespace tr1;

#include <lshkit/tune.h>

static const int MIN_L = 1;
static const int MAX_L = 20;

static const int MIN_T = 1;
static const int MAX_T = 100;

static const int MIN_M = 1;
static const int MAX_M = 20;

static const double MIN_W = 0.01;
static const double MAX_W = 10;
static const double NUM_W = 400;
static const double DELTA_W = (MAX_W - MIN_W) / NUM_W;

double target_recall;

MultiProbeLshDataModel *model;

bool is_good_value (double v)
{
	return ((v > -std::numeric_limits<double>::max()) && (v < std::numeric_limits<double>::max()));
}

double recall (const lshkit::tune::Input &x) {
	model->setL(x[0]);
	model->setT(x[1]);
	model->setM(MAX_M - x[2]);
	model->setW(MIN_W + DELTA_W * x[3]);
	return model->avgRecall();
}

bool constraint (const tune::Input &x) {
	return recall(x) > target_recall;
}

double cost (const tune::Input &x) {
	model->setL(x[0]);
	model->setT(x[1]);
	model->setM(MAX_M - x[2]);
	model->setW(MIN_W + DELTA_W * x[3]);
	return model->cost();
}

double mplsh_tune(const double& param_M, const double& param_G,
                  const double& param_a_M, const double& param_b_M, const double& param_c_M,
                  const double& param_a_G, const double& param_b_G, const double& param_c_G,
                  int N, int K, int L, int T, int& M, float& W, float R )
{
	M = -1;
	W = -1;
	target_recall = R;
	tune::Interval intervals[]= {{MIN_L, MAX_L + 1}, {MIN_T, MAX_T + 1}, {0, MAX_M - MIN_M + 1}, {0, NUM_W + 1}};
	if (L <= 0 || T <= 0) {
		cout << "mplsh_tune: You need to specify L and T." << endl;
		return 0;
	}

	if (L > 0) {
		intervals[0].begin = L;
		intervals[0].end = L + 1;
	}

	if (T > 0) {
		intervals[1].begin = T;
		intervals[1].end = T + 1;
	}

	if (M > 0) {
		intervals[2].begin = MAX_M - M;
		intervals[2].end = MAX_M - M + 1;
	}

	if (W > 0) {
		intervals[3].begin = (W - MIN_W) / DELTA_W;
		intervals[3].end = intervals[3].begin + 1;
	}

	DataParam param( param_M, param_G, param_a_M, param_b_M, param_c_M, param_a_G, param_b_G, param_c_G );
	double scale = param.scale();

	MultiProbeLshDataModel local_model(param, N, K);
	model = &local_model;

	tune::Range range(intervals, intervals + sizeof intervals /sizeof intervals[0]);
	tune::Input input;
	bool ok = tune::Tune(range, constraint, &input);

	if (ok) {
		M = MAX_M - input[2];
		W = (MIN_W + DELTA_W * input[3])*sqrt(scale);
	} else {
		cout << "mplsh_tune: Failed." << endl;
	}

	double tune_cost = cost( input );
	return tune_cost;
}


#pragma once

#define _USE_MATH_DEFINES
/// code to make agents
#include <vector>
#include <cassert>

#include <Rcpp.h>
#include <boost/geometry.hpp>
#include <boost/geometry/geometries/point.hpp>
#include <boost/geometry/index/rtree.hpp>

using namespace Rcpp;
#include "parameters.hpp"
#include "FastNoiseLite.h"

// boost geometry types
namespace bg = boost::geometry;
namespace bgi = boost::geometry::index;
typedef bg::model::point<float, 2, bg::cs::cartesian> point;
typedef bg::model::box<point> box;
typedef std::pair<point, unsigned> value;

// Agent class
class Agent {
public:
    Agent() :
        // count agents correctly heritable parameter is s_range
        energy(1e-5f),
        x(0.f),
        y(0.f),
        coefFood(0.f),
        coefNbrs(0.f),
        coefRisk(0.f),
        moved(0.f),
        infected(false),
        timeInfected(-1),
        nbrs(0)

    {}
    ~Agent() {}

    // agent attributes
    float energy, x, y, coefFood, coefNbrs, coefRisk, moved;
    // is agent infected?
    bool infected;
    int timeInfected, nbrs;

    // agent functions
    int countNbrsAt(const float perception,
                    const float xloc, const float yloc,
                    bgi::rtree< value, bgi::quadratic<16> > &agentRtree);
    std::vector<int> getNbrsId(const float perception,
                    const float xloc, const float yloc,
                    bgi::rtree< value, bgi::quadratic<16> > &agentRtree);
    void doSenseMove(FastNoiseLite &noise,
                    const float t_, const float perception,
                    const int directions, const float clamp, const float landsize,
                    bgi::rtree< value, bgi::quadratic<16> > &agentRtree, const float costMove,
                    const bool allow_compete);
    void doEnergetics(FastNoiseLite &noise,
                    bgi::rtree< value, bgi::quadratic<16> > &agentRtree,
                    const float perception,
                    const float t_, const float clamp,
                    const bool allow_compete);

    void randomTraits();
    void randomPosition(const float landsize);

};

/// declare pop level functions
void popRandomPos(std::vector<Agent> &pop, const float landsize);

void popRandomTraits(std::vector<Agent> &pop);

void popMoveForageCompete(std::vector<Agent>& pop, FastNoiseLite &noise,
    const float t_,
    const float perception, const int directions,
    const float landsize, const float clamp,
    const float costMove,
    const bool allow_compete);

void handleFitness(std::vector<float> &vecFitness);

void doReproduce(std::vector<Agent>& pop, const float landsize);

/// function to make Rtree from population
bgi::rtree< value, bgi::quadratic<16> > makeRtree (std::vector<Agent> &pop);


#include "simulation/magnetometer-simulator.h"

#include <iomanip>
#include <memory>
#include <vector>

#include <Eigen/Core>
#include <aslam/common/memory.h>
#include <eigen-checks/gtest.h>
#include <glog/logging.h>
#include <gtest/gtest.h>
#include <maplab-common/file-logger.h>
#include <maplab-common/test/testing-entrypoint.h>
#include <maplab-common/test/testing-predicates.h>

#include "simulation/generic-path-generator.h"

namespace simulation {

class MagnetometerSimulatorTest : public ::testing::Test {
 public:
  EIGEN_MAKE_ALIGNED_OPERATOR_NEW
  virtual void SetUp() {
    settings_.mode = test_trajectory_gen::Path::kCircular;
    settings_.imu_sigmas.acc_bias_random_walk_noise_density = 0.1;
    settings_.imu_sigmas.acc_noise_density = 0.1;
    settings_.gravity_meter_by_second2 = 9.81;
    settings_.imu_sigmas.gyro_bias_random_walk_noise_density = 0.1;
    settings_.imu_sigmas.gyro_noise_density = 0.1;
    settings_.imu_noise_bias_seed = 10u;
    settings_.num_of_path_constraints = 8;
    settings_.sampling_time_second = 0.1;

    simulation::YearMonthDay utc_time;
    utc_time.year = 2017;
    utc_time.month = 7;
    utc_time.day = 1;
    mag_sim_.reset(new MagnetometerSimulator(utc_time));

    if (kSaveMagnetometerSimulationToFile) {
      const std::string filename = "/tmp/simulated_magnetometer.txt";
      logger_.reset(new common::FileLogger(filename));
    }
  }

  test_trajectory_gen::PathAndLandmarkSettings settings_;
  std::shared_ptr<test_trajectory_gen::GenericPathGenerator> path_generator_;
  aslam::TransformationVector ground_truth_transformations_;
  std::unique_ptr<MagnetometerSimulator> mag_sim_;

  const bool kSaveMagnetometerSimulationToFile = false;
  std::unique_ptr<common::FileLogger> logger_;
};

// Test magnetometer simulator using official world magnetic model test data
// from 2015.
TEST_F(MagnetometerSimulatorTest, testWorldMagneticModel) {
  const double latitude_degree = -80.0;
  const double longitude_degree = 240.0;
  const double height_above_wgs84_ellipsoid_meter = 100.0 * 1.0e3;
  Eigen::Vector3d llh(
      latitude_degree, longitude_degree, height_above_wgs84_ellipsoid_meter);

  // No rotation w.r.t. earth magnetic field.
  Eigen::Matrix3d R_B_N;
  R_B_N.setIdentity();

  Eigen::Vector3d simulated_magnetic_field_tesla;
  mag_sim_->calculateMagneticField(llh, R_B_N, &simulated_magnetic_field_tesla);

  // Trusted values from world magnetic model, do not change.
  Eigen::Vector3d true_magnetic_field_tesla;
  true_magnetic_field_tesla << 5683.5175495763 * 1e-9, 14808.8492023104 * 1e-9,
      -50163.0133654779 * 1e-9;

  EXPECT_NEAR_EIGEN(
      simulated_magnetic_field_tesla, true_magnetic_field_tesla, 1e-7);
}

// The test goes as follows:
// 1. Simulate a circular trajectory (rotation on spot).
// 2. Calculate magnetic field for every time step.
// 3. Calculate absolute yaw heading from simulated magnetometer values.
// 4. Compare true heading to calculated heading from magnetometer values.
TEST_F(MagnetometerSimulatorTest, testCircularPath) {
  // 1. Simulate a circular trajectory (rotation on spot).
  path_generator_ =
      aligned_shared<test_trajectory_gen::GenericPathGenerator>(settings_);
  path_generator_->generatePath();
  path_generator_->getGroundTruthTransformations(
      &ground_truth_transformations_);
  // Location in global coordinates.
  const double latitude_degree = 47.6027992;
  const double longitude_degree = 8.5341138;
  const double height_above_wgs84_ellipsoid_meter = 411.083;
  Eigen::Vector3d llh(
      latitude_degree, longitude_degree, height_above_wgs84_ellipsoid_meter);

  // Retrieve magnetometer offset.
  Eigen::Matrix3d R_B0_G;
  R_B0_G.setIdentity();
  Eigen::Vector3d magnetic_field_offset_tesla;
  mag_sim_->calculateMagneticField(llh, R_B0_G, &magnetic_field_offset_tesla);
  double yaw_offset_degree =
      -std::atan2(
          magnetic_field_offset_tesla(1), magnetic_field_offset_tesla(0)) *
      180.0 / M_PI;

  for (size_t sample_idx = 0; sample_idx < ground_truth_transformations_.size();
       ++sample_idx) {
    // 2. Calculate magnetic field for every time step.
    Eigen::Vector3d simulated_magnetic_field_tesla;
    const aslam::Transformation& T_G_B =
        ground_truth_transformations_[sample_idx];
    aslam::Transformation T_B_G = T_G_B.inverted();
    Eigen::Matrix3d R_B_G = T_B_G.getRotationMatrix();
    mag_sim_->calculateMagneticField(
        llh, R_B_G, &simulated_magnetic_field_tesla);

    // 3. Calculate absolute yaw heading from simulated magnetometer values.
    double yaw_simulated_degree = -std::atan2(
                                      simulated_magnetic_field_tesla(1),
                                      simulated_magnetic_field_tesla(0)) *
                                  180.0 / M_PI;
    double yaw_true_degree =
        -std::atan2(R_B_G(1, 0), R_B_G(1, 1)) * 180.0 / M_PI;

    // 4. Compare true heading to calculated heading from magnetometer values.
    double error =
        std::abs(yaw_true_degree - (yaw_simulated_degree - yaw_offset_degree));
    error += (error > 180.0) ? -360.0 : (error < -180.0) ? 360.0 : 0.0;
    // Expect error smaller than 1.0e-13 degrees.
    EXPECT_NEAR(error, 0.0, 1.0e-13);

    // Save simulation results to file for debugging.
    if (kSaveMagnetometerSimulationToFile) {
      *logger_ << std::setprecision(15) << simulated_magnetic_field_tesla(0)
               << " " << simulated_magnetic_field_tesla(1) << " "
               << simulated_magnetic_field_tesla(2) << " "
               << yaw_simulated_degree << " " << yaw_offset_degree << " "
               << yaw_true_degree << " " << error << std::endl;
    }
  }
}

}  // namespace simulation

MAPLAB_UNITTEST_ENTRYPOINT


#include "CalibTracker/SiStripLorentzAngle/interface/LA_Filler_Fitter.h"
#include "FWCore/Utilities/interface/EDMException.h"

#include <cmath>
#include <boost/algorithm/string/erase.hpp>
#include <TF1.h>

void LA_Filler_Fitter::fit_width_profile(Book& book) {
  for (Book::iterator it = book.begin(".*" + method(WIDTH)); it != book.end(); ++it) {
    it->second->SetTitle("Mean Cluster Width;tan#theta_{t}");
    TH1* const p = it->second;
    if (p->GetEntries() < 400) {
      delete p;
      book[it->first] = nullptr;
      continue;
    }
    p->SetTitle(";tan#theta_{t};");
    const float min = p->GetMinimum();
    const float max = p->GetMaximum();
    float xofmin = p->GetBinCenter(p->GetMinimumBin());
    if (xofmin > 0.0 || xofmin < -0.15)
      xofmin = -0.05;
    const float xofmax = p->GetBinCenter(p->GetMaximumBin());

    TF1* const fit = new TF1("LA_profile_fit", "[2]*(TMath::Abs(x-[0]))+[1]", -1, 1);
    fit->SetParLimits(0, -0.15, 0.01);
    fit->SetParLimits(1, 0.6 * min, 1.25 * min);
    fit->SetParLimits(2, 0.1, 10);
    fit->SetParameters(xofmin, min, (max - min) / fabs(xofmax - xofmin));

    int badfit = p->Fit(fit, "IEQ", "", -.5, .3);
    if (badfit)
      badfit = p->Fit(fit, "IEQ", "", -.46, .26);
    if (badfit) {
      book.erase(it);
    }
  }
}

void LA_Filler_Fitter::make_and_fit_symmchi2(Book& book) {
  for (Book::iterator it = book.begin(".*_all"); it != book.end(); ++it) {
    const std::string base = boost::erase_all_copy(it->first, "_all");

    std::vector<Book::iterator> rebin_hists;
    const Book::iterator& all = it;
    rebin_hists.push_back(all);
    Book::iterator w1 = book.find(base + "_w1");
    rebin_hists.push_back(w1);
    Book::iterator var_w2 = book.find(base + method(AVGV2, false));
    rebin_hists.push_back(var_w2);
    Book::iterator var_w3 = book.find(base + method(AVGV3, false));
    rebin_hists.push_back(var_w3);

    const unsigned rebin = std::max(var_w2 == book.end() ? 0 : find_rebin(var_w2->second),
                                    var_w3 == book.end() ? 0 : find_rebin(var_w3->second));
    for (const auto& it : rebin_hists)
      if (it != book.end())
        it->second->Rebin(rebin > 1 ? rebin < 7 ? rebin : 6 : 1);

    TH1* const prob_w1 =
        w1 == book.end() ? nullptr : subset_probability(base + method(PROB1, false), w1->second, all->second);
    TH1* const rmsv_w2 =
        var_w2 == book.end() ? nullptr : rms_profile(base + method(RMSV2, false), (TProfile* const)var_w2->second);
    TH1* const rmsv_w3 =
        var_w3 == book.end() ? nullptr : rms_profile(base + method(RMSV3, false), (TProfile* const)var_w3->second);

    std::vector<TH1*> fit_hists;
    if (prob_w1) {
      book.book(base + method(PROB1, false), prob_w1);
      fit_hists.push_back(prob_w1);
      prob_w1->SetTitle("Width==1 Probability;tan#theta_{t}-(dx/dz)_{reco}");
    }
    if (var_w2 != book.end()) {
      book.book(base + method(RMSV2, false), rmsv_w2);
      fit_hists.push_back(var_w2->second);
      var_w2->second->SetTitle("Width==2 Mean Variance;tan#theta_{t}-(dx/dz)_{reco}");
      fit_hists.push_back(rmsv_w2);
      rmsv_w2->SetTitle("Width==2 RMS Variance;tan#theta_{t}-(dx/dz)_{reco}");
    }
    if (var_w3 != book.end()) {
      book.book(base + method(RMSV3, false), rmsv_w3);
      fit_hists.push_back(var_w3->second);
      var_w3->second->SetTitle("Width==3 Mean Variance;tan#theta_{t}-(dx/dz)_{reco}");
      fit_hists.push_back(rmsv_w3);
      rmsv_w3->SetTitle("Width==3 RMS Variance;tan#theta_{t}-(dx/dz)_{reco}");
    }

    if (fit_hists.empty())
      continue;
    const unsigned bins = fit_hists[0]->GetNbinsX();
    const unsigned guess = fit_hists[0]->FindBin(0);
    const std::pair<unsigned, unsigned> range(guess - bins / 30, guess + bins / 30);

    for (auto const& hist : fit_hists) {
      TH1* const chi2 = SymmetryFit::symmetryChi2(hist, range);
      if (chi2) {
        book.book(chi2->GetName(), chi2);
        chi2->SetTitle("Symmetry #chi^{2};tan#theta_{t}-(dx/dz)_{reco}");
      }
    }
  }
}

unsigned LA_Filler_Fitter::find_rebin(const TH1* const hist) {
  const double mean = hist->GetMean();
  const double rms = hist->GetRMS();
  const int begin = std::min(1, hist->GetXaxis()->FindFixBin(mean - rms));
  const int end = std::max(hist->GetNbinsX(), hist->GetXaxis()->FindFixBin(mean + rms)) + 1;
  unsigned current_hole(0), max_hole(0);
  for (int i = begin; i < end; i++) {
    if (!hist->GetBinError(i))
      current_hole++;
    else if (current_hole) {
      max_hole = std::max(current_hole, max_hole);
      current_hole = 0;
    }
  }
  return max_hole + 1;
}

TH1* LA_Filler_Fitter::rms_profile(const std::string name, const TProfile* const prof) {
  const int bins = prof->GetNbinsX();
  TH1* const rms =
      new TH1F(name.c_str(), "", bins, prof->GetBinLowEdge(1), prof->GetBinLowEdge(bins) + prof->GetBinWidth(bins));
  for (int i = 1; i <= bins; i++) {
    const double Me = prof->GetBinError(i);
    const double neff = prof->GetBinEntries(
        i);  //Should be prof->GetBinEffectiveEntries(i);, not availible this version ROOT.  This is only ok for unweighted fills
    rms->SetBinContent(i, Me * sqrt(neff));
    rms->SetBinError(i, Me / sqrt(2));
  }
  return rms;
}

TH1* LA_Filler_Fitter::subset_probability(const std::string name, const TH1* const subset, const TH1* const total) {
  const int bins = subset->GetNbinsX();
  TH1* const prob = new TH1F(
      name.c_str(), "", bins, subset->GetBinLowEdge(1), subset->GetBinLowEdge(bins) + subset->GetBinWidth(bins));
  for (int i = 1; i <= bins; i++) {
    const double s = subset->GetBinContent(i);
    const double T = total->GetBinContent(i);
    const double B = T - s;

    const double p = T ? s / T : 0;
    const double perr = T ? ((s && B) ? sqrt(s * s * B + B * B * s) / (T * T) : 1 / T) : 0;

    prob->SetBinContent(i, p);
    prob->SetBinError(i, perr);
  }
  return prob;
}