<commit_before>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_SFMT_HPP_
#define WTL_SFMT_HPP_

#include <limits>

#define HAVE_SSE2
#define SFMT_MEXP 19937
#include "SFMT/SFMT.h"

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

class sfmt19937 {
  public:
    typedef uint32_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 5489U;

    // constructors
    explicit sfmt19937(const result_type s=default_seed) {seed(s);}
    explicit sfmt19937(const state_type& state): state_(state) {}
    sfmt19937(const sfmt19937&) = delete;

    // [0, 2^32-1]
    result_type operator()() {
        return sfmt_genrand_uint32(&state_);
    }

    // [0.0, 1.0)
    double canonical() {
        return sfmt_genrand_real2(&state_);
    }

    void seed(const result_type s) {
        sfmt_init_gen_rand(&state_, s);
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif /* WTL_SFMT_HPP_ */
<commit_msg>Add sfmt19937_64<commit_after>// -*- mode: c++; coding: utf-8 -*-
#pragma once
#ifndef WTL_SFMT_HPP_
#define WTL_SFMT_HPP_

#include <limits>

#define HAVE_SSE2
#define SFMT_MEXP 19937
#include "SFMT/SFMT.h"

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
namespace wtl {
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

class sfmt19937 {
  public:
    typedef uint32_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 5489U;

    // constructors
    explicit sfmt19937(const result_type s=default_seed) {seed(s);}
    explicit sfmt19937(const state_type& state): state_(state) {}
    sfmt19937(const sfmt19937&) = delete;

    // [0, 2^32-1]
    result_type operator()() {
        return sfmt_genrand_uint32(&state_);
    }

    // [0.0, 1.0)
    double canonical() {
        return sfmt_genrand_real2(&state_);
    }

    void seed(const result_type s) {
        sfmt_init_gen_rand(&state_, s);
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

class sfmt19937_64 {
  public:
    typedef uint64_t result_type;
    typedef sfmt_t state_type;

    static constexpr result_type min() {return 0U;}
    static constexpr result_type max() {return std::numeric_limits<result_type>::max();}
    static constexpr result_type default_seed = 5489U;

    // constructors
    explicit sfmt19937_64(const result_type s=default_seed) {seed(s);}
    explicit sfmt19937_64(const state_type& state): state_(state) {}
    sfmt19937_64(const sfmt19937_64&) = delete;

    // [0, 2^64-1]
    result_type operator()() {
        return sfmt_genrand_uint64(&state_);
    }

    // [0.0, 1.0)
    double canonical() {
        return sfmt_genrand_res53(&state_);
    }

    void seed(const result_type s) {
        sfmt_init_gen_rand(&state_, s);
    }

    void discard(unsigned long long n) {
        for (; n != 0ULL; --n) {(*this)();}
    }

    const state_type& getstate() const {return state_;}
    void setstate(const state_type& state) {state_ = state;}

  private:
    state_type state_;
};

/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////
} // namespace wtl
/////////1/////////2/////////3/////////4/////////5/////////6/////////7/////////

#endif /* WTL_SFMT_HPP_ */
<|endoftext|>


<commit_before>#include "sift.hpp"

#include <iostream>
#include <vector>
#include <string>
#include <tuple>
#include <cassert>

#include <vigra/convolution.hxx>
#include <vigra/resizeimage.hxx>
#include <vigra/impex.hxx>
#include <vigra/multi_math.hxx>
#include <vigra/linear_algebra.hxx>
#include <vigra/tinyvector.hxx>

#include "point.hpp"

using namespace vigra::multi_math;

void Sift::calculate(
    vigra::MultiArray<2, f32_t>& img, u16_t epochs, f32_t sigma, f32_t k, u16_t dogPerEpoch) const
{
    auto dogs = _createDOGs(img, epochs, sigma, k, dogPerEpoch);
    auto interestPoints = _findScaleSpaceExtrema(dogs);
    //Save img with found interest points for demonstration purposes
    auto img_output1 = img;
    for (auto& img : interestPoints[0]) {
        for(u16_t x = 0; x < img.width(); x++) {
            for(u16_t y = 0; y < img.height(); y++) {
                if (img[Point(x, y)] > -1) {
                    img_output1(x, y) = 255;
                }
            }
        }
    }

    exportImage(img_output1, vigra::ImageExportInfo("images/interest_points.png"));
    _keypointLocation(interestPoints, dogs);

    auto img_output2 = img;
    for (auto& img : interestPoints[0]) {
        for(u16_t x = 0; x < img.width(); x++) {
            for(u16_t y = 0; y < img.height(); y++) {
                if (img[Point(x, y)] > -1) {
                    img_output2(x, y) = 255;
                }
            }
        }
    }

    exportImage(img_output2, vigra::ImageExportInfo("images/after_keypointLocation.png"));
    }

void Sift::_keypointLocation(interest_point_epochs& interestPoints, const img_epochs& dogs) const {
    assert(dogs.size() == interestPoints.size());
    for(u16_t e = 0; e < dogs.size(); e++) {
        assert(dogs[e].size() >= 3);
        assert(interestPoints[e].size() == dogs[e].size() / 3);
        for (u16_t i = 1; i < dogs[e].size() - 1; i++) {
            assert(dogs[e][i].shape(0) == interestPoints[e][i - 1].width());
            assert(dogs[e][i].shape(1) == interestPoints[e][i - 1].height());
            for (u16_t x = 1; x < dogs[e][i].shape(0) - 1; x++) {
                for (u16_t y = 1; y < dogs[e][i].shape(1) - 1; y++) {
                    if (interestPoints[e][i - 1](x, y) > -1) {
                        auto d = dogs[e][i];
                        assert(d.shape(0) > 2);
                        assert(d.shape(1) > 2);

                        f32_t dx = (d(x - 1, y) - d(x + 1, y)) / 2;
                        f32_t dy = (d(x, y - 1) - d(x, y + 1)) / 2;
                        f32_t ds = (dogs[e][i - 1](x, y) - dogs[e][i + 1](x, y)) / 2;

                        f32_t dxx = d(x + 1, y) + d(x - 1, y) - 2 * d(x, y);
                        f32_t dyy = d(x, y + 1) + d(x, y - 1) - 2 * d(x, y);
                        f32_t dss = dogs[e][i + 1](x, y) + dogs[e][i - 1](x, y) - 2 * d(x, y);
                        f32_t dxy = d(x + 1, y + 1) - d(x - 1, y + 1) - d(x + 1, y - 1)
                            + d(x - 1, y - 1);
                        f32_t dxs = dogs[e][i + 1](x + 1, y) - dogs[e][i + 1](x - 1, y)
                            - dogs[e][i - 1](x + 1, y) + dogs[e][i - 1](x - 1, y);

                        f32_t dys = dogs[e][i + 1](x, y + 1) - dogs[e][i + 1](x, y + 1)
                            - dogs[e][i - 1](x, y + 1) + dogs[e][i - 1](x, y - 1);
                        vigra::MultiArray<2, f32_t> sec_deriv(vigra::Shape2(3, 3));
                        sec_deriv(0, 0) = dxx;
                        sec_deriv(0, 1) = dxy;
                        sec_deriv(0, 2) = dxs;
                        sec_deriv(1, 0) = dxy;
                        sec_deriv(1, 1) = dyy;
                        sec_deriv(1, 2) = dys;
                        sec_deriv(2, 0) = dxs;
                        sec_deriv(2, 1) = dys;
                        sec_deriv(2, 2) = dss;

                        vigra::TinyVector<f32_t, 3> deriv(dx, dy, ds);
                        auto extremum =  vigra::linalg::operator*(vigra::linalg::inverse(sec_deriv), deriv);

                        //Calculated up 0.5 from paper to image values [0,255]
                        if (extremum[0] > 127.5 || extremum[1] > 127.5 || extremum[2] > 127.5) {
                            interestPoints[e][i - 1](x, y) = -1;
                            continue;
                        }

                        auto func_val_extremum = vigra::operator*(deriv, extremum);
                        func_val_extremum *= 0.5;
                        func_val_extremum[0] += d(x,y);
                        func_val_extremum[1] += d(x,y);
                        func_val_extremum[2] += d(x,y);
                        //Calculated up 0.03 from paper to image values[0, 255]
                        if (func_val_extremum[0] + func_val_extremum[1] + func_val_extremum[2] < 7.65) {
                            interestPoints[e][i - 1](x, y) = -1;
                            continue;
                        }
                    }
                }
            }
        }
    }
}

const interest_point_epochs Sift::_findScaleSpaceExtrema(const img_epochs& dogs) const {
    //a Vector with epochs containing tuples of interest points found per epoch
    interest_point_epochs interestPoints;
    for (u16_t e = 0; e < dogs.size(); e++) {
        interestPoints.emplace_back(std::vector<Matrix<f32_t>>());
        for (u16_t i = 1; i < dogs[e].size() - 1; i++) {
            interestPoints[e].emplace_back(Matrix<f32_t>(dogs[e][i].shape(0), dogs[e][i].shape(1), -1));
            for (i32_t x = 0; x < dogs[e][i].shape(0); x++) {
                for (i32_t y = 0; y < dogs[e][i].shape(1); y++) {
                    auto leftUpCorner = vigra::Shape2(x - 1, y - 1);
                    auto rightDownCorner = vigra::Shape2(x + 1, y + 1);

                    //Get the neighborhood of the current pixel
                    auto current = dogs[e][i].subarray(leftUpCorner, rightDownCorner);
                    //Get neighborhood of adjacent DOGs
                    auto under = dogs[e][i - 1].subarray(leftUpCorner, rightDownCorner);
                    auto above = dogs[e][i + 1].subarray(leftUpCorner, rightDownCorner);
                    //Check all neighborhood pixels of current and adjacent DOGs. If there isn't any
                    //pixel bigger or smaller than the current. We found an extremum.
                    if ((!any(current > dogs[e][i](x, y)) &&
                                !any(under > dogs[e][i](x, y)) &&
                                !any(above > dogs[e][i](x, y))) ||
                            (!any(current < dogs[e][i](x, y)) &&
                             !any(under < dogs[e][i](x, y)) &&
                             !any(above < dogs[e][i](x, y))))
                    {
                        interestPoints[e].back()[Point(x, y)] = dogs[e][i](x, y);
                    }
                    else
                        interestPoints[e].back()[Point(x, y)] = -1;
                }
            }
        }
    }
    return interestPoints; // TODO: by ref entgegen nehmen, um copy zu vermeiden?
}

const img_epochs Sift::_createDOGs(vigra::MultiArray<2, f32_t>& img, u16_t epochs, f32_t sigma,
        f32_t k, u16_t dogPerEpoch) const {

    assert(epochs > 0); // pre condition
    assert(dogPerEpoch >= 3); // pre condition

    /*
     * A vector which contains a vector for each epoch. Those are filled with the
     * Images which were created from the laplacianOfGaussians.
     */
    img_epochs laplacians;
    /*
     * a vector which contains a vector for each epoch. Those are filled with the
     * images which were created from gaussians
     */
    img_epochs gaussians;

    //add inital image
    gaussians.emplace_back(std::vector<vigra::MultiArray<2, f32_t>>());
    gaussians[0].emplace_back(_convolveWithGauss(img, sigma));

    //TODO: More elegant way?
    u16_t exp = 0;
    for (i32_t i = 0; i < epochs; i++) {
        laplacians.emplace_back(std::vector<vigra::MultiArray<2, f32_t>>());
        for (i32_t j = 1; j < dogPerEpoch + 1; j++) {
            gaussians[i].emplace_back(_convolveWithGauss(gaussians[i][j - 1], std::pow(k, exp) * sigma));
            laplacians[i].emplace_back(_DOG(gaussians[i][j - 1], gaussians[i][j]));
            exp++;
        }
        /*
         * If we aren't in the last epoch populate the next level with the second
         * last element, scaled won by a half, of the gaussians.
         */
        if (i < (epochs - 1)) {
            gaussians.emplace_back(std::vector<vigra::MultiArray<2, f32_t>>());
            auto scaledElem = _reduceToNextLevel(gaussians[i][dogPerEpoch - 1], sigma);
            gaussians[i + 1].emplace_back(scaledElem);

            exp -= 2;
        }
    }

    //Save laplacianOfGaussian for Demonstration purposes
    for (u16_t i = 0; i < laplacians.size(); i++) {
        for (u16_t j = 0; j < laplacians[i].size(); j++) {
            const std::string fnStr = "images/laplacian" + std::to_string(i) + std::to_string(j) + ".png";
            exportImage(laplacians[i][j], vigra::ImageExportInfo(fnStr.c_str()));
        }
    }

    return laplacians; // TODO: by ref entgegen nehmen um copy zu vermeiden?
}

const vigra::MultiArray<2, f32_t> Sift::_reduceToNextLevel(const vigra::MultiArray<2, f32_t>& in,
        f32_t sigma) const {
    // image size at current level
    const u16_t height = in.height();
    const u16_t width = in.width();

    // image size at next smaller level
    const u16_t newheight = (height + 1) / 2;
    const u16_t newwidth = (width + 1) / 2;

    // resize result image to appropriate size
    vigra::MultiArray<2, f32_t> out(vigra::Shape2(newwidth, newheight));
    // downsample smoothed image
    resizeImageNoInterpolation(_convolveWithGauss(in, sigma), out);

    return out; // TODO by ref entgegen nehmen um copy zu vermeiden?
}

const vigra::MultiArray<2, f32_t> Sift::_convolveWithGauss(const vigra::MultiArray<2, f32_t>& input,
        f32_t sigma) const {

    vigra::Kernel1D<f32_t> filter;
    filter.initGaussian(sigma);
    vigra::MultiArray<2, f32_t> tmp(input.shape());
    vigra::MultiArray<2, f32_t> result(input.shape());

    separableConvolveX(input, tmp, filter);
    separableConvolveY(tmp, result, filter);

    return result;
}

const vigra::MultiArray<2, f32_t> Sift::_DOG(const vigra::MultiArray<2, f32_t>& lower,
        const vigra::MultiArray<2, f32_t>& higher) const {

    vigra::MultiArray<2, f32_t> result(vigra::Shape2(lower.shape()));
    for(u16_t x = 0; x < lower.shape(0); x++) {
        for(u16_t y = 0; y < lower.shape(1); y++) {
            f32_t dif = higher(x, y) - lower(x, y);
            result(x, y) = 128 + dif;
        }
    }
    return result;
}
<commit_msg>Mathematical error fixed and removed asserts<commit_after>#include "sift.hpp"

#include <iostream>
#include <vector>
#include <string>
#include <tuple>
#include <cassert>

#include <vigra/convolution.hxx>
#include <vigra/resizeimage.hxx>
#include <vigra/impex.hxx>
#include <vigra/multi_math.hxx>
#include <vigra/linear_algebra.hxx>
#include <vigra/tinyvector.hxx>

#include "point.hpp"

using namespace vigra::multi_math;

void Sift::calculate(
    vigra::MultiArray<2, f32_t>& img, u16_t epochs, f32_t sigma, f32_t k, u16_t dogPerEpoch) const
{
    auto dogs = _createDOGs(img, epochs, sigma, k, dogPerEpoch);
    auto interestPoints = _findScaleSpaceExtrema(dogs);
    //Save img with found interest points for demonstration purposes
    auto img_output1 = img;
    for (auto& img : interestPoints[0]) {
        for(u16_t x = 0; x < img.width(); x++) {
            for(u16_t y = 0; y < img.height(); y++) {
                if (img[Point(x, y)] > -1) {
                    img_output1(x, y) = 255;
                }
            }
        }
    }

    exportImage(img_output1, vigra::ImageExportInfo("images/interest_points.png"));
    _keypointLocation(interestPoints, dogs);

    auto img_output2 = img;
    for (auto& img : interestPoints[0]) {
        for(u16_t x = 0; x < img.width(); x++) {
            for(u16_t y = 0; y < img.height(); y++) {
                if (img[Point(x, y)] > -1) {
                    img_output2(x, y) = 255;
                }
            }
        }
    }

    exportImage(img_output2, vigra::ImageExportInfo("images/after_keypointLocation.png"));
    }

void Sift::_keypointLocation(interest_point_epochs& interestPoints, const img_epochs& dogs) const {
    for(u16_t e = 0; e < dogs.size(); e++) {
        for (u16_t i = 1; i < dogs[e].size() - 1; i++) {
            for (u16_t x = 1; x < dogs[e][i].shape(0) - 1; x++) {
                for (u16_t y = 1; y < dogs[e][i].shape(1) - 1; y++) {
                    if (interestPoints[e][i - 1](x, y) > -1) {
                        auto d = dogs[e][i];

                        f32_t dx = (d(x - 1, y) - d(x + 1, y)) / 2;
                        f32_t dy = (d(x, y - 1) - d(x, y + 1)) / 2;
                        f32_t ds = (dogs[e][i - 1](x, y) - dogs[e][i + 1](x, y)) / 2;

                        f32_t dxx = d(x + 1, y) + d(x - 1, y) - 2 * d(x, y);
                        f32_t dyy = d(x, y + 1) + d(x, y - 1) - 2 * d(x, y);
                        f32_t dss = dogs[e][i + 1](x, y) + dogs[e][i - 1](x, y) - 2 * d(x, y);
                        f32_t dxy = d(x + 1, y + 1) - d(x - 1, y + 1) - d(x + 1, y - 1)
                            + d(x - 1, y - 1);
                        f32_t dxs = dogs[e][i + 1](x + 1, y) - dogs[e][i + 1](x - 1, y)
                            - dogs[e][i - 1](x + 1, y) + dogs[e][i - 1](x - 1, y);

                        f32_t dys = dogs[e][i + 1](x, y + 1) - dogs[e][i + 1](x, y + 1)
                            - dogs[e][i - 1](x, y + 1) + dogs[e][i - 1](x, y - 1);
                        vigra::MultiArray<2, f32_t> sec_deriv(vigra::Shape2(3, 3));
                        sec_deriv(0, 0) = -dxx;
                        sec_deriv(0, 1) = -dxy;
                        sec_deriv(0, 2) = -dxs;
                        sec_deriv(1, 0) = -dxy;
                        sec_deriv(1, 1) = -dyy;
                        sec_deriv(1, 2) = -dys;
                        sec_deriv(2, 0) = -dxs;
                        sec_deriv(2, 1) = -dys;
                        sec_deriv(2, 2) = -dss;

                        vigra::TinyVector<f32_t, 3> deriv(dx, dy, ds);
                        auto extremum =  vigra::linalg::operator*(vigra::linalg::inverse(sec_deriv), deriv);

                        //Calculated up 0.5 from paper to image values [0,255]
                        if (extremum[0] > 127.5 || extremum[1] > 127.5 || extremum[2] > 127.5) {
                            interestPoints[e][i - 1](x, y) = -1;
                            continue;
                        }

                        auto func_val_extremum = vigra::operator*(deriv, extremum);
                        func_val_extremum *= 0.5;
                        func_val_extremum[0] += d(x,y);
                        func_val_extremum[1] += d(x,y);
                        func_val_extremum[2] += d(x,y);
                        //Calculated up 0.03 from paper to image values[0, 255]
                        if (func_val_extremum[0] + func_val_extremum[1] + func_val_extremum[2] < 7.65) {
                            interestPoints[e][i - 1](x, y) = -1;
                            continue;
                        }
                    }
                }
            }
        }
    }
}

const interest_point_epochs Sift::_findScaleSpaceExtrema(const img_epochs& dogs) const {
    //a Vector with epochs containing tuples of interest points found per epoch
    interest_point_epochs interestPoints;
    for (u16_t e = 0; e < dogs.size(); e++) {
        interestPoints.emplace_back(std::vector<Matrix<f32_t>>());
        for (u16_t i = 1; i < dogs[e].size() - 1; i++) {
            interestPoints[e].emplace_back(Matrix<f32_t>(dogs[e][i].shape(0), dogs[e][i].shape(1), -1));
            for (i32_t x = 0; x < dogs[e][i].shape(0); x++) {
                for (i32_t y = 0; y < dogs[e][i].shape(1); y++) {
                    auto leftUpCorner = vigra::Shape2(x - 1, y - 1);
                    auto rightDownCorner = vigra::Shape2(x + 1, y + 1);

                    //Get the neighborhood of the current pixel
                    auto current = dogs[e][i].subarray(leftUpCorner, rightDownCorner);
                    //Get neighborhood of adjacent DOGs
                    auto under = dogs[e][i - 1].subarray(leftUpCorner, rightDownCorner);
                    auto above = dogs[e][i + 1].subarray(leftUpCorner, rightDownCorner);
                    //Check all neighborhood pixels of current and adjacent DOGs. If there isn't any
                    //pixel bigger or smaller than the current. We found an extremum.
                    if ((!any(current > dogs[e][i](x, y)) &&
                                !any(under > dogs[e][i](x, y)) &&
                                !any(above > dogs[e][i](x, y))) ||
                            (!any(current < dogs[e][i](x, y)) &&
                             !any(under < dogs[e][i](x, y)) &&
                             !any(above < dogs[e][i](x, y))))
                    {
                        interestPoints[e].back()[Point(x, y)] = dogs[e][i](x, y);
                    }
                    else
                        interestPoints[e].back()[Point(x, y)] = -1;
                }
            }
        }
    }
    return interestPoints; // TODO: by ref entgegen nehmen, um copy zu vermeiden?
}

const img_epochs Sift::_createDOGs(vigra::MultiArray<2, f32_t>& img, u16_t epochs, f32_t sigma,
        f32_t k, u16_t dogPerEpoch) const {

    assert(epochs > 0); // pre condition
    assert(dogPerEpoch >= 3); // pre condition

    /*
     * A vector which contains a vector for each epoch. Those are filled with the
     * Images which were created from the laplacianOfGaussians.
     */
    img_epochs laplacians;
    /*
     * a vector which contains a vector for each epoch. Those are filled with the
     * images which were created from gaussians
     */
    img_epochs gaussians;

    //add inital image
    gaussians.emplace_back(std::vector<vigra::MultiArray<2, f32_t>>());
    gaussians[0].emplace_back(_convolveWithGauss(img, sigma));

    //TODO: More elegant way?
    u16_t exp = 0;
    for (i32_t i = 0; i < epochs; i++) {
        laplacians.emplace_back(std::vector<vigra::MultiArray<2, f32_t>>());
        for (i32_t j = 1; j < dogPerEpoch + 1; j++) {
            gaussians[i].emplace_back(_convolveWithGauss(gaussians[i][j - 1], std::pow(k, exp) * sigma));
            laplacians[i].emplace_back(_DOG(gaussians[i][j - 1], gaussians[i][j]));
            exp++;
        }
        /*
         * If we aren't in the last epoch populate the next level with the second
         * last element, scaled won by a half, of the gaussians.
         */
        if (i < (epochs - 1)) {
            gaussians.emplace_back(std::vector<vigra::MultiArray<2, f32_t>>());
            auto scaledElem = _reduceToNextLevel(gaussians[i][dogPerEpoch - 1], sigma);
            gaussians[i + 1].emplace_back(scaledElem);

            exp -= 2;
        }
    }

    //Save laplacianOfGaussian for Demonstration purposes
    for (u16_t i = 0; i < laplacians.size(); i++) {
        for (u16_t j = 0; j < laplacians[i].size(); j++) {
            const std::string fnStr = "images/laplacian" + std::to_string(i) + std::to_string(j) + ".png";
            exportImage(laplacians[i][j], vigra::ImageExportInfo(fnStr.c_str()));
        }
    }

    return laplacians; // TODO: by ref entgegen nehmen um copy zu vermeiden?
}

const vigra::MultiArray<2, f32_t> Sift::_reduceToNextLevel(const vigra::MultiArray<2, f32_t>& in,
        f32_t sigma) const {
    // image size at current level
    const u16_t height = in.height();
    const u16_t width = in.width();

    // image size at next smaller level
    const u16_t newheight = (height + 1) / 2;
    const u16_t newwidth = (width + 1) / 2;

    // resize result image to appropriate size
    vigra::MultiArray<2, f32_t> out(vigra::Shape2(newwidth, newheight));
    // downsample smoothed image
    resizeImageNoInterpolation(_convolveWithGauss(in, sigma), out);

    return out; // TODO by ref entgegen nehmen um copy zu vermeiden?
}

const vigra::MultiArray<2, f32_t> Sift::_convolveWithGauss(const vigra::MultiArray<2, f32_t>& input,
        f32_t sigma) const {

    vigra::Kernel1D<f32_t> filter;
    filter.initGaussian(sigma);
    vigra::MultiArray<2, f32_t> tmp(input.shape());
    vigra::MultiArray<2, f32_t> result(input.shape());

    separableConvolveX(input, tmp, filter);
    separableConvolveY(tmp, result, filter);

    return result;
}

const vigra::MultiArray<2, f32_t> Sift::_DOG(const vigra::MultiArray<2, f32_t>& lower,
        const vigra::MultiArray<2, f32_t>& higher) const {

    vigra::MultiArray<2, f32_t> result(vigra::Shape2(lower.shape()));
    for(u16_t x = 0; x < lower.shape(0); x++) {
        for(u16_t y = 0; y < lower.shape(1); y++) {
            f32_t dif = higher(x, y) - lower(x, y);
            result(x, y) = 128 + dif;
        }
    }
    return result;
}
<|endoftext|>


<commit_before>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_core_access_state.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file  p9_query_core_access_state.C
/// @brief Check the stop level for a core and set boolean scanable, scomable parameters
///
// *HWP HWP Owner: Brian Vanderpool <vanderp@us.ibm.com>
// *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner:  Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: FSP:HS:SBE
///
///
///
/// @verbatim
/// High-level procedure flow:
///     - For the core target, read the Stop State History register in the PPM
///       and use the actual stop level to determine if the core has power and is being
///       clocked.
/// @endverbatim
///
//------------------------------------------------------------------------------

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------

#include "p9_query_core_access_state.H"

#define SSHSRC_STOP_GATED 0
#define NET_CTRL0_FENCED  18

// ----------------------------------------------------------------------
// Procedure Function
// ----------------------------------------------------------------------

fapi2::ReturnCode
p9_query_core_access_state(
    const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
    bool& o_is_scomable,
    bool& o_is_scanable)
{

    fapi2::buffer<uint64_t> l_csshsrc, l_cpfetsense, l_sisr, l_netCtrl0;
    fapi2::buffer<uint64_t> l_data64;
    uint32_t l_coreStopLevel = 0;
    uint8_t  vdd_pfet_disable_core = 0;
    uint8_t  c_exec_hasclocks = 0;
    uint8_t  c_pc_hasclocks = 0;
    uint8_t  l_chpltNumber = 0;

    FAPI_INF("> p9_query_core_access_state...");

    // Get the stop state from the SSHRC in the CPPM
    FAPI_TRY(fapi2::getScom(i_target, C_PPM_SSHSRC, l_csshsrc), "Error reading data from CPPM SSHSRC");

    // A unit is scomable if clocks are running
    // A unit is scannable if the unit is powered up.

    // Extract the core stop state
    if (l_csshsrc.getBit<SSHSRC_STOP_GATED>() == 1)
    {
        l_csshsrc.extractToRight<uint32_t>(l_coreStopLevel, 8, 4);
    }

    if (l_coreStopLevel == 0)
    {
        // Double check the core isn't in stop 1
        auto l_ex_target = i_target.getParent<fapi2::TARGET_TYPE_EX>();

        FAPI_TRY(fapi2::getScom(l_ex_target, EX_CME_LCL_SISR_SCOM, l_sisr), "Error reading data from CME SISR register");

        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),
                 "ERROR: Failed to get the position of the Core:0x%08X",
                 i_target);

        uint32_t l_pos = l_chpltNumber % 2;

        if (l_pos == 0 && l_sisr.getBit<EX_CME_LCL_SISR_PM_STATE_ACTIVE_C0>())
        {
            l_sisr.extractToRight<uint32_t>(l_coreStopLevel, EX_CME_LCL_SISR_PM_STATE_C0, EX_CME_LCL_SISR_PM_STATE_C0_LEN);
        }

        if (l_pos == 1 && l_sisr.getBit<EX_CME_LCL_SISR_PM_STATE_ACTIVE_C1>())
        {
            l_sisr.extractToRight<uint32_t>(l_coreStopLevel, EX_CME_LCL_SISR_PM_STATE_C1, EX_CME_LCL_SISR_PM_STATE_C1_LEN);
        }

    }

    FAPI_INF("Core Stop State: C(%d)", l_coreStopLevel);

    // Set both attributes to 1, then clear them based on the stop state
    o_is_scomable = 1;
    o_is_scanable = 1;

    // STOP1 - NAP
    //  VSU, ISU are clocked off
    if (l_coreStopLevel >= 1)
    {
        o_is_scomable = 0;
    }

    // STOP2 - Fast Sleep
    //   VSU, ISU are clocked off
    //   IFU, LSU are clocked off
    //   PC, Core EPS are clocked off
    if (l_coreStopLevel >= 2)
    {
        o_is_scomable = 0;
    }

    // STOP4 - Deep Sleep  (special exception for stop 9 - lab use only)
    //   VSU, ISU are powered off
    //   IFU, LSU are powered off
    //   PC, Core EPS are powered off
    if (l_coreStopLevel >= 4 && l_coreStopLevel != 9)
    {
        o_is_scanable = 0;
    }

    //----------------------------------------------------------------------------------
    // Read clock status and pfet_sense_disabled to confirm stop state history is accurate
    // If we trust the stop state history, this could be removed to save on code size
    //----------------------------------------------------------------------------------

    FAPI_DBG("   Read CPPM PFETSENSE");
    FAPI_TRY(fapi2::getScom(i_target, C_PPM_PFSNS, l_cpfetsense), "Error reading data from CPPM PFSNS");

    // Extract out the disabled bits
    l_cpfetsense.extractToRight<uint8_t>(vdd_pfet_disable_core, 1, 1);

    FAPI_INF("Core PFET_DISABLE(%d)", vdd_pfet_disable_core);

    // Read clocks running registers
    if (vdd_pfet_disable_core == 0)
    {
        // Get the fence bit for this core from C_NET_CTRL0
        FAPI_TRY(fapi2::getScom(i_target, C_NET_CTRL0, l_netCtrl0), "Error reading data from C_NET_CTRL0");

        if (l_netCtrl0.getBit<NET_CTRL0_FENCED>() == 0)
        {
            FAPI_DBG("   Read Core EPS clock status for core");
            FAPI_TRY(fapi2::getScom(i_target, C_CLOCK_STAT_SL,  l_data64), "Error reading data from C_CLOCK_STAT_SL");

            l_data64.extractToRight<uint8_t>(c_exec_hasclocks, 6, 1);
            l_data64.extractToRight<uint8_t>(c_pc_hasclocks,   5, 1);
        }
        else
        {
            FAPI_INF("Core Fences are up, so skipped reading the C_CLOCK_STAT_SL Register");
        }
    }

    FAPI_INF("Core Clock Status : PC_HASCLOCKS(%d) EXEC_HASCLOCKS(%d)", c_pc_hasclocks, c_exec_hasclocks);

    FAPI_DBG("Comparing Stop State vs Actual HW settings");

    FAPI_DBG("Core Is Scomable STOP_STATE(%d)  CLKSTAT(%d)", o_is_scomable, c_pc_hasclocks && c_exec_hasclocks);
    FAPI_DBG("Core Is Scanable STOP_STATE(%d)  PFET(%d)", o_is_scanable, !vdd_pfet_disable_core);

    //----------------------------------------------------------------------------------
    // Compare Hardware status vs stop state status.   If there is a mismatch, the HW value overrides the stop state
    //----------------------------------------------------------------------------------

    if (o_is_scomable != ( c_pc_hasclocks && c_exec_hasclocks))
    {
        FAPI_INF("Clock status didn't match stop state, overriding is_scomable status");
        o_is_scomable = ( c_pc_hasclocks && c_exec_hasclocks);
    }

    if (o_is_scanable != (vdd_pfet_disable_core == 0))
    {
        FAPI_INF("PFET status didn't match stop state, overriding is_scanable status");
        o_is_scanable = (vdd_pfet_disable_core == 0);
    }

fapi_try_exit:
    FAPI_INF("< p9_query_core_access_state...");
    return fapi2::current_err;
}
<commit_msg>Inverted logic of hasClock bit in Clock Status register<commit_after>/* IBM_PROLOG_BEGIN_TAG                                                   */
/* This is an automatically generated prolog.                             */
/*                                                                        */
/* $Source: src/import/chips/p9/procedures/hwp/pm/p9_query_core_access_state.C $ */
/*                                                                        */
/* OpenPOWER HostBoot Project                                             */
/*                                                                        */
/* Contributors Listed Below - COPYRIGHT 2015,2019                        */
/* [+] International Business Machines Corp.                              */
/*                                                                        */
/*                                                                        */
/* Licensed under the Apache License, Version 2.0 (the "License");        */
/* you may not use this file except in compliance with the License.       */
/* You may obtain a copy of the License at                                */
/*                                                                        */
/*     http://www.apache.org/licenses/LICENSE-2.0                         */
/*                                                                        */
/* Unless required by applicable law or agreed to in writing, software    */
/* distributed under the License is distributed on an "AS IS" BASIS,      */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or        */
/* implied. See the License for the specific language governing           */
/* permissions and limitations under the License.                         */
/*                                                                        */
/* IBM_PROLOG_END_TAG                                                     */
///
/// @file  p9_query_core_access_state.C
/// @brief Check the stop level for a core and set boolean scanable, scomable parameters
///
// *HWP HWP Owner: Brian Vanderpool <vanderp@us.ibm.com>
// *HWP Backup HWP Owner: Greg Still <stillgs@us.ibm.com>
// *HWP FW Owner:  Sangeetha T S <sangeet2@in.ibm.com>
// *HWP Team: PM
// *HWP Level: 2
// *HWP Consumed by: FSP:HS:SBE
///
///
///
/// @verbatim
/// High-level procedure flow:
///     - For the core target, read the Stop State History register in the PPM
///       and use the actual stop level to determine if the core has power and is being
///       clocked.
/// @endverbatim
///
//------------------------------------------------------------------------------

// ----------------------------------------------------------------------
// Includes
// ----------------------------------------------------------------------

#include "p9_query_core_access_state.H"

#define SSHSRC_STOP_GATED 0
#define NET_CTRL0_FENCED  18

// ----------------------------------------------------------------------
// Procedure Function
// ----------------------------------------------------------------------

fapi2::ReturnCode
p9_query_core_access_state(
    const fapi2::Target<fapi2::TARGET_TYPE_CORE>& i_target,
    bool& o_is_scomable,
    bool& o_is_scanable)
{

    fapi2::buffer<uint64_t> l_csshsrc, l_cpfetsense, l_sisr, l_netCtrl0;
    fapi2::buffer<uint64_t> l_data64;
    uint32_t l_coreStopLevel = 0;
    uint8_t  vdd_pfet_disable_core = 0;
    uint8_t  c_exec_hasclocks = 0;
    uint8_t  c_pc_hasclocks = 0;
    uint8_t  l_chpltNumber = 0;

    FAPI_INF("> p9_query_core_access_state...");

    // Get the stop state from the SSHRC in the CPPM
    FAPI_TRY(fapi2::getScom(i_target, C_PPM_SSHSRC, l_csshsrc), "Error reading data from CPPM SSHSRC");

    // A unit is scomable if clocks are running
    // A unit is scannable if the unit is powered up.

    // Extract the core stop state
    if (l_csshsrc.getBit<SSHSRC_STOP_GATED>() == 1)
    {
        l_csshsrc.extractToRight<uint32_t>(l_coreStopLevel, 8, 4);
    }

    if (l_coreStopLevel == 0)
    {
        // Double check the core isn't in stop 1
        auto l_ex_target = i_target.getParent<fapi2::TARGET_TYPE_EX>();

        FAPI_TRY(fapi2::getScom(l_ex_target, EX_CME_LCL_SISR_SCOM, l_sisr), "Error reading data from CME SISR register");

        FAPI_TRY(FAPI_ATTR_GET(fapi2::ATTR_CHIP_UNIT_POS, i_target, l_chpltNumber),
                 "ERROR: Failed to get the position of the Core:0x%08X",
                 i_target);

        uint32_t l_pos = l_chpltNumber % 2;

        if (l_pos == 0 && l_sisr.getBit<EX_CME_LCL_SISR_PM_STATE_ACTIVE_C0>())
        {
            l_sisr.extractToRight<uint32_t>(l_coreStopLevel, EX_CME_LCL_SISR_PM_STATE_C0, EX_CME_LCL_SISR_PM_STATE_C0_LEN);
        }

        if (l_pos == 1 && l_sisr.getBit<EX_CME_LCL_SISR_PM_STATE_ACTIVE_C1>())
        {
            l_sisr.extractToRight<uint32_t>(l_coreStopLevel, EX_CME_LCL_SISR_PM_STATE_C1, EX_CME_LCL_SISR_PM_STATE_C1_LEN);
        }

    }

    FAPI_INF("Core Stop State: C(%d)", l_coreStopLevel);

    // Set both attributes to 1, then clear them based on the stop state
    o_is_scomable = 1;
    o_is_scanable = 1;

    // STOP1 - NAP
    //  VSU, ISU are clocked off
    if (l_coreStopLevel >= 1)
    {
        o_is_scomable = 0;
    }

    // STOP2 - Fast Sleep
    //   VSU, ISU are clocked off
    //   IFU, LSU are clocked off
    //   PC, Core EPS are clocked off
    if (l_coreStopLevel >= 2)
    {
        o_is_scomable = 0;
    }

    // STOP4 - Deep Sleep  (special exception for stop 9 - lab use only)
    //   VSU, ISU are powered off
    //   IFU, LSU are powered off
    //   PC, Core EPS are powered off
    if (l_coreStopLevel >= 4 && l_coreStopLevel != 9)
    {
        o_is_scanable = 0;
    }

    //----------------------------------------------------------------------------------
    // Read clock status and pfet_sense_disabled to confirm stop state history is accurate
    // If we trust the stop state history, this could be removed to save on code size
    //----------------------------------------------------------------------------------

    FAPI_DBG("   Read CPPM PFETSENSE");
    FAPI_TRY(fapi2::getScom(i_target, C_PPM_PFSNS, l_cpfetsense), "Error reading data from CPPM PFSNS");

    // Extract out the disabled bits
    l_cpfetsense.extractToRight<uint8_t>(vdd_pfet_disable_core, 1, 1);

    FAPI_INF("Core PFET_DISABLE(%d)", vdd_pfet_disable_core);

    // Read clocks running registers
    if (vdd_pfet_disable_core == 0)
    {
        // Get the fence bit for this core from C_NET_CTRL0
        FAPI_TRY(fapi2::getScom(i_target, C_NET_CTRL0, l_netCtrl0), "Error reading data from C_NET_CTRL0");

        if (l_netCtrl0.getBit<NET_CTRL0_FENCED>() == 0)
        {
            FAPI_DBG("   Read Core EPS clock status for core");
            FAPI_TRY(fapi2::getScom(i_target, C_CLOCK_STAT_SL,  l_data64), "Error reading data from C_CLOCK_STAT_SL");

            l_data64.extractToRight<uint8_t>(c_exec_hasclocks, 6, 1);
            // Inverted logic in the HW
            c_exec_hasclocks = !c_exec_hasclocks;
            l_data64.extractToRight<uint8_t>(c_pc_hasclocks,   5, 1);
            // Inverted logic in the HW
            c_pc_hasclocks = !c_pc_hasclocks;
        }
        else
        {
            FAPI_INF("Core Fences are up, so skipped reading the C_CLOCK_STAT_SL Register");
        }
    }

    FAPI_INF("Core Clock Status : PC_HASCLOCKS(%d) EXEC_HASCLOCKS(%d)", c_pc_hasclocks, c_exec_hasclocks);

    FAPI_DBG("Comparing Stop State vs Actual HW settings");

    FAPI_DBG("Core Is Scomable STOP_STATE(%d)  CLKSTAT(%d)", o_is_scomable, c_pc_hasclocks && c_exec_hasclocks);
    FAPI_DBG("Core Is Scanable STOP_STATE(%d)  PFET(%d)", o_is_scanable, !vdd_pfet_disable_core);

    //----------------------------------------------------------------------------------
    // Compare Hardware status vs stop state status.   If there is a mismatch, the HW value overrides the stop state
    //----------------------------------------------------------------------------------

    if (o_is_scomable != ( c_pc_hasclocks && c_exec_hasclocks))
    {
        FAPI_INF("Clock status didn't match stop state, overriding is_scomable status");
        o_is_scomable = ( c_pc_hasclocks && c_exec_hasclocks);
    }

    if (o_is_scanable != (vdd_pfet_disable_core == 0))
    {
        FAPI_INF("PFET status didn't match stop state, overriding is_scanable status");
        o_is_scanable = (vdd_pfet_disable_core == 0);
    }

fapi_try_exit:
    FAPI_INF("< p9_query_core_access_state...");
    return fapi2::current_err;
}
<|endoftext|>


<commit_before>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>

#include "mongoBackend/MongoGlobal.h"
#include "convenience/AppendContextElementRequest.h"
#include "convenience/AppendContextElementResponse.h"
#include "convenience/UpdateContextAttributeRequest.h"
#include "ngsi10/UpdateContextRequest.h"
#include "ngsi10/UpdateContextResponse.h"
#include "mongoBackend/mongoUpdateContext.h"
#include "rest/ConnectionInfo.h"
#include "rest/HttpStatusCode.h"

/* ****************************************************************************
*
* mapPostIndividualContextEntityAttribute -
*/
HttpStatusCode mapPostIndividualContextEntityAttribute
(
  const std::string&              entityId,
  const std::string&              entityType,
  const std::string&              attributeName,
  UpdateContextAttributeRequest*  request,
  StatusCode*                     response,
  ConnectionInfo*                 ciP
)
{
  HttpStatusCode         ms;
  UpdateContextRequest   ucRequest;
  UpdateContextResponse  ucResponse;
  ContextElement         ce;
  ContextAttribute       attribute(attributeName, request->type, request->contextValue);

  ce.entityId.fill(entityId, entityType, "false");
  ce.contextAttributeVector.push_back(&attribute);

  attribute.metadataVector.fill(&request->metadataVector);

  ucRequest.contextElementVector.push_back(&ce);
  ucRequest.updateActionType.set("Append");

  ucResponse.errorCode.fill(SccOk);
  ms = mongoUpdateContext(&ucRequest, &ucResponse, ciP->tenant, ciP->servicePathV, ciP->uriParam);

  //
  // Only one contextAttribute in request contextAttributeVector, so there will be only one
  // item in ucResponse.contextElementResponseVector.
  // Completely safe to respond with ucResponse.contextElementResponseVector[0].
  // However, if there is a general error in ucResponse.errorCode, we should pick that
  // response instead.
  //
  if (ucResponse.errorCode.code != SccOk)
  {
    response->fill(&ucResponse.errorCode);
  }
  else
  {
    response->fill(&ucResponse.contextElementResponseVector[0]->statusCode);
  }

  return ms;
}
<commit_msg>Fixed a stupid leak<commit_after>/*
*
* Copyright 2013 Telefonica Investigacion y Desarrollo, S.A.U
*
* This file is part of Orion Context Broker.
*
* Orion Context Broker is free software: you can redistribute it and/or
* modify it under the terms of the GNU Affero General Public License as
* published by the Free Software Foundation, either version 3 of the
* License, or (at your option) any later version.
*
* Orion Context Broker is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero
* General Public License for more details.
*
* You should have received a copy of the GNU Affero General Public License
* along with Orion Context Broker. If not, see http://www.gnu.org/licenses/.
*
* For those usages not covered by this license please contact with
* fermin at tid dot es
*
* Author: Ken Zangelin
*/
#include <string>

#include "mongoBackend/MongoGlobal.h"
#include "convenience/AppendContextElementRequest.h"
#include "convenience/AppendContextElementResponse.h"
#include "convenience/UpdateContextAttributeRequest.h"
#include "ngsi10/UpdateContextRequest.h"
#include "ngsi10/UpdateContextResponse.h"
#include "mongoBackend/mongoUpdateContext.h"
#include "rest/ConnectionInfo.h"
#include "rest/HttpStatusCode.h"

/* ****************************************************************************
*
* mapPostIndividualContextEntityAttribute -
*/
HttpStatusCode mapPostIndividualContextEntityAttribute
(
  const std::string&              entityId,
  const std::string&              entityType,
  const std::string&              attributeName,
  UpdateContextAttributeRequest*  request,
  StatusCode*                     response,
  ConnectionInfo*                 ciP
)
{
  HttpStatusCode         ms;
  UpdateContextRequest   ucRequest;
  UpdateContextResponse  ucResponse;
  ContextElement         ce;
  ContextAttribute       attribute(attributeName, request->type, request->contextValue);

  ce.entityId.fill(entityId, entityType, "false");
  ce.contextAttributeVector.push_back(&attribute);

  attribute.metadataVector.fill(&request->metadataVector);

  ucRequest.contextElementVector.push_back(&ce);
  ucRequest.updateActionType.set("Append");

  ucResponse.errorCode.fill(SccOk);
  ms = mongoUpdateContext(&ucRequest, &ucResponse, ciP->tenant, ciP->servicePathV, ciP->uriParam);

  ucRequest.release();

  //
  // Only one contextAttribute in request contextAttributeVector, so there will be only one
  // item in ucResponse.contextElementResponseVector.
  // Completely safe to respond with ucResponse.contextElementResponseVector[0].
  // However, if there is a general error in ucResponse.errorCode, we should pick that
  // response instead.
  //
  if (ucResponse.errorCode.code != SccOk)
  {
    response->fill(&ucResponse.errorCode);
  }
  else
  {
    response->fill(&ucResponse.contextElementResponseVector[0]->statusCode);
  }

  return ms;
}
<|endoftext|>


<commit_before>// File:  bestObservationTimeEstimator.cpp
// Date:  12/4/2017
// Auth:  K. Loux
// Desc:  Object for estimating best observation times based on observation history.

// Local headers
#include "bestObservationTimeEstimator.h"
#include "kernelDensityEstimation.h"

// Standard C++ headers
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <sstream>

std::string BestObservationTimeEstimator::EstimateBestObservationTime(
	const std::vector<EBirdInterface::ObservationInfo>& observationInfo)
{
	if (observationInfo.size() < 3)
	{
		std::ostringstream ss;
		ss << std::setfill('0');
		for (const auto& o : observationInfo)
		{
			if (ss.str().empty())
				ss << "at ";
			else
				ss << " and ";

			ss << std::setw(2) << o.observationDate.tm_hour << ':' << std::setw(2) << o.observationDate.tm_min;
		}

		return ss.str();
	}

	// For ease of processing, convert times to a double representation of time as fractional hours since midnight
	std::vector<double> inputTimes(observationInfo.size());
	auto inputIt(inputTimes.begin());
	for (const auto& o : observationInfo)
		*(inputIt++) = o.observationDate.tm_hour + o.observationDate.tm_min / 60.0;

	// Estimate the probability distribution by binning into 1-hour wide slots
	const double minimum(0.0);// hours since midnight
	const double maximum(23.0);// hours since midnight
	const unsigned int pdfPointCount(24);
	const double step(1.0);// hours
	std::vector<double> pdfRange(pdfPointCount);
	std::generate(pdfRange.begin(), pdfRange.end(), Sequence(minimum, step));

	KernelDensityEstimation kde;
	std::vector<double> pdfEstimate(kde.ComputePDF(inputTimes, pdfRange,
		KernelDensityEstimation::EstimateOptimalBandwidth(inputTimes)));

	// Examine PDF to give insight into observation times.  There can be (multiple) obvious peaks
	// where we should list out certain hours, or PDF can be flat over several hours, in which
	// case we should report a range.
	if (HasFlatPDF(pdfEstimate))
		return "throughout the day and night";

	const bool isNocturnal(IsNocturnal(pdfEstimate));
	unsigned int shift(0);
	if (isNocturnal)
	{
		std::rotate(pdfEstimate.begin(), pdfEstimate.begin() + pdfPointCount / 2, pdfEstimate.end());
		shift = 12;
	}

	auto peaks(FindPeaks(pdfEstimate));
	assert(peaks.size() > 0);

	std::ostringstream ss;
	ss << std::setfill('0');
	bool lastWasRangeStart(false);
	const auto lastPeakPtr([&peaks]() -> TimeProbability*
	{
		if (peaks.back().type == TimeProbability::Type::Peak)
			return &*peaks.rbegin();
		return &*(peaks.rbegin() + 1);
	}());

	for (const auto& peak : peaks)
	{
		const bool isLast(&peak == lastPeakPtr);
		if (!ss.str().empty() && !lastWasRangeStart)
		{
			if (!isLast)
				ss << ", ";
			else
				ss << " and ";
		}

		if (peak.type == TimeProbability::Type::Peak)
		{
			assert(!lastWasRangeStart);
			if (ss.str().empty())
				ss << "around ";
		}
		else if (peak.type == TimeProbability::Type::RangeStart)
		{
			assert(!lastWasRangeStart);
			ss << "from ";
		}
		else// if (peak.type == TimeProbability::Type::RangeEnd)
		{
			assert(lastWasRangeStart);
			ss << " to ";
		}

		ss << std::setw(2) << static_cast<int>(peak.time + shift) % 24 << ':'
			<< std::setw(2) << static_cast<int>((peak.time - static_cast<int>(peak.time)) * 60.0);

		lastWasRangeStart = peak.type == TimeProbability::Type::RangeStart;
	}

	return ss.str();
}

bool BestObservationTimeEstimator::IsNocturnal(const std::vector<double>& pdf)
{
	// Assume nocturnal if the middle 50% of the day has less liklihood of
	// observation than the first and last quarter combined
	double nighttimeProbability(0.0);
	double daytimeProbability(0.0);

	double hour(0.0);
	const double increment(24.0 / pdf.size());
	for (const auto& p : pdf)
	{
		if (hour < 6.0 || hour > 18.0)
			nighttimeProbability += p;
		else
			daytimeProbability += p;
		hour += increment;
	}

	return nighttimeProbability > daytimeProbability;
}

bool BestObservationTimeEstimator::HasFlatPDF(const std::vector<double>& pdf)
{
	const double uniformProbability(1.0 / pdf.size());
	const double allowedVariation(0.5);// [% of uniform]
	const unsigned int allowedOutliers(3);
	unsigned int outliers(0);
	for (const auto& p : pdf)
	{
		if (p < uniformProbability * (1.0 - allowedVariation) ||
			p > uniformProbability * (1.0 + allowedVariation))
		{
			++outliers;
			if (outliers > allowedOutliers)
				return false;
		}
	}

	return true;
}

std::vector<BestObservationTimeEstimator::TimeProbability> BestObservationTimeEstimator::FindPeaks(
	const std::vector<double>& pdf)
{
	// If there is a time where observation is twice as likely as another time, this
	// is significant.  Less variation than that is not significant.
	const double significanceRatio(0.5);
	const double minimumOnProbability(*std::max_element(pdf.begin(), pdf.end()) * significanceRatio);

	std::vector<TimeProbability> peaks;
	auto pdfIt(pdf.begin());
	for (; pdfIt != pdf.end(); ++pdfIt)
	{
		if (*pdfIt < minimumOnProbability)
			continue;

		auto nextIt(pdfIt + 1);
		if (peaks.size() > 0 &&
			peaks.back().type == TimeProbability::Type::RangeStart &&
			*nextIt >= minimumOnProbability)// If this is in the middle of a wider range
			continue;

		TimeProbability::Type type;
		if (nextIt != pdf.end() && *nextIt > minimumOnProbability)
			type = TimeProbability::Type::RangeStart;
		else if (peaks.size() > 0 && peaks.back().type == TimeProbability::Type::RangeStart)
			type = TimeProbability::RangeEnd;
		else
			type = TimeProbability::Peak;

		peaks.push_back(TimeProbability(std::distance(pdf.begin(), pdfIt), type));
	}

	assert(peaks.back().type != TimeProbability::RangeStart);

	return peaks;
}
<commit_msg>Fixed grammer in info file output<commit_after>// File:  bestObservationTimeEstimator.cpp
// Date:  12/4/2017
// Auth:  K. Loux
// Desc:  Object for estimating best observation times based on observation history.

// Local headers
#include "bestObservationTimeEstimator.h"
#include "kernelDensityEstimation.h"

// Standard C++ headers
#include <algorithm>
#include <cassert>
#include <iomanip>
#include <sstream>

std::string BestObservationTimeEstimator::EstimateBestObservationTime(
	const std::vector<EBirdInterface::ObservationInfo>& observationInfo)
{
	if (observationInfo.size() < 3)
	{
		std::ostringstream ss;
		ss << std::setfill('0');
		for (const auto& o : observationInfo)
		{
			if (ss.str().empty())
				ss << "at ";
			else
				ss << " and ";

			ss << std::setw(2) << o.observationDate.tm_hour << ':' << std::setw(2) << o.observationDate.tm_min;
		}

		return ss.str();
	}

	// For ease of processing, convert times to a double representation of time as fractional hours since midnight
	std::vector<double> inputTimes(observationInfo.size());
	auto inputIt(inputTimes.begin());
	for (const auto& o : observationInfo)
		*(inputIt++) = o.observationDate.tm_hour + o.observationDate.tm_min / 60.0;

	// Estimate the probability distribution by binning into 1-hour wide slots
	const double minimum(0.0);// hours since midnight
	const double maximum(23.0);// hours since midnight
	const unsigned int pdfPointCount(24);
	const double step(1.0);// hours
	std::vector<double> pdfRange(pdfPointCount);
	std::generate(pdfRange.begin(), pdfRange.end(), Sequence(minimum, step));

	KernelDensityEstimation kde;
	std::vector<double> pdfEstimate(kde.ComputePDF(inputTimes, pdfRange,
		KernelDensityEstimation::EstimateOptimalBandwidth(inputTimes)));

	// Examine PDF to give insight into observation times.  There can be (multiple) obvious peaks
	// where we should list out certain hours, or PDF can be flat over several hours, in which
	// case we should report a range.
	if (HasFlatPDF(pdfEstimate))
		return "throughout the day and night";

	const bool isNocturnal(IsNocturnal(pdfEstimate));
	unsigned int shift(0);
	if (isNocturnal)
	{
		std::rotate(pdfEstimate.begin(), pdfEstimate.begin() + pdfPointCount / 2, pdfEstimate.end());
		shift = 12;
	}

	auto peaks(FindPeaks(pdfEstimate));
	assert(peaks.size() > 0);

	std::ostringstream ss;
	ss << std::setfill('0');
	bool lastWasRangeStart(false);
	const auto lastPeakPtr([&peaks]() -> TimeProbability*
	{
		if (peaks.back().type == TimeProbability::Type::Peak)
			return &*peaks.rbegin();
		return &*(peaks.rbegin() + 1);
	}());

	for (const auto& peak : peaks)
	{
		const bool isLast(&peak == lastPeakPtr);
		if (!ss.str().empty() && !lastWasRangeStart)
		{
			if (!isLast)
				ss << ", ";
			else
				ss << " and ";
		}

		if (peak.type == TimeProbability::Type::Peak)
		{
			assert(!lastWasRangeStart);
			ss << "around ";
		}
		else if (peak.type == TimeProbability::Type::RangeStart)
		{
			assert(!lastWasRangeStart);
			ss << "from ";
		}
		else// if (peak.type == TimeProbability::Type::RangeEnd)
		{
			assert(lastWasRangeStart);
			ss << " to ";
		}

		ss << std::setw(2) << static_cast<int>(peak.time + shift) % 24 << ':'
			<< std::setw(2) << static_cast<int>((peak.time - static_cast<int>(peak.time)) * 60.0);

		lastWasRangeStart = peak.type == TimeProbability::Type::RangeStart;
	}

	return ss.str();
}

bool BestObservationTimeEstimator::IsNocturnal(const std::vector<double>& pdf)
{
	// Assume nocturnal if the middle 50% of the day has less liklihood of
	// observation than the first and last quarter combined
	double nighttimeProbability(0.0);
	double daytimeProbability(0.0);

	double hour(0.0);
	const double increment(24.0 / pdf.size());
	for (const auto& p : pdf)
	{
		if (hour < 6.0 || hour > 18.0)
			nighttimeProbability += p;
		else
			daytimeProbability += p;
		hour += increment;
	}

	return nighttimeProbability > daytimeProbability;
}

bool BestObservationTimeEstimator::HasFlatPDF(const std::vector<double>& pdf)
{
	const double uniformProbability(1.0 / pdf.size());
	const double allowedVariation(0.5);// [% of uniform]
	const unsigned int allowedOutliers(3);
	unsigned int outliers(0);
	for (const auto& p : pdf)
	{
		if (p < uniformProbability * (1.0 - allowedVariation) ||
			p > uniformProbability * (1.0 + allowedVariation))
		{
			++outliers;
			if (outliers > allowedOutliers)
				return false;
		}
	}

	return true;
}

std::vector<BestObservationTimeEstimator::TimeProbability> BestObservationTimeEstimator::FindPeaks(
	const std::vector<double>& pdf)
{
	// If there is a time where observation is twice as likely as another time, this
	// is significant.  Less variation than that is not significant.
	const double significanceRatio(0.5);
	const double minimumOnProbability(*std::max_element(pdf.begin(), pdf.end()) * significanceRatio);

	std::vector<TimeProbability> peaks;
	auto pdfIt(pdf.begin());
	for (; pdfIt != pdf.end(); ++pdfIt)
	{
		if (*pdfIt < minimumOnProbability)
			continue;

		auto nextIt(pdfIt + 1);
		if (peaks.size() > 0 &&
			peaks.back().type == TimeProbability::Type::RangeStart &&
			*nextIt >= minimumOnProbability)// If this is in the middle of a wider range
			continue;

		TimeProbability::Type type;
		if (nextIt != pdf.end() && *nextIt > minimumOnProbability)
			type = TimeProbability::Type::RangeStart;
		else if (peaks.size() > 0 && peaks.back().type == TimeProbability::Type::RangeStart)
			type = TimeProbability::RangeEnd;
		else
			type = TimeProbability::Peak;

		peaks.push_back(TimeProbability(std::distance(pdf.begin(), pdfIt), type));
	}

	assert(peaks.back().type != TimeProbability::RangeStart);

	return peaks;
}
<|endoftext|>


<commit_before>#include <cstring>
#include <vector>

#include "gtest/gtest.h"

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"

#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"

namespace caffe {

template <typename TypeParam>
class ConcatLayerTest : public MultiDeviceTest<TypeParam> {
  typedef typename TypeParam::Dtype Dtype;

 protected:
  ConcatLayerTest()
      : blob_bottom_0_(new Blob<Dtype>(2, 3, 6, 5)),
        blob_bottom_1_(new Blob<Dtype>(2, 5, 6, 5)),
        blob_bottom_2_(new Blob<Dtype>(5, 3, 6, 5)),
        blob_top_(new Blob<Dtype>()) {}
  virtual void SetUp() {
    // fill the values
    shared_ptr<ConstantFiller<Dtype> > filler;
    FillerParameter filler_param;
    filler_param.set_value(1.);
    filler.reset(new ConstantFiller<Dtype>(filler_param));
    filler->Fill(this->blob_bottom_0_);
    filler_param.set_value(2.);
    filler.reset(new ConstantFiller<Dtype>(filler_param));
    filler->Fill(this->blob_bottom_1_);
    filler_param.set_value(3.);
    filler.reset(new ConstantFiller<Dtype>(filler_param));
    filler->Fill(this->blob_bottom_2_);
    blob_bottom_vec_0_.push_back(blob_bottom_0_);
    blob_bottom_vec_0_.push_back(blob_bottom_1_);
    blob_bottom_vec_1_.push_back(blob_bottom_0_);
    blob_bottom_vec_1_.push_back(blob_bottom_2_);
    blob_top_vec_.push_back(blob_top_);
  }

  virtual ~ConcatLayerTest() {
    delete blob_bottom_0_; delete blob_bottom_1_;
    delete blob_bottom_2_; delete blob_top_;
  }

  Blob<Dtype>* const blob_bottom_0_;
  Blob<Dtype>* const blob_bottom_1_;
  Blob<Dtype>* const blob_bottom_2_;
  Blob<Dtype>* const blob_top_;
  vector<Blob<Dtype>*> blob_bottom_vec_0_, blob_bottom_vec_1_;
  vector<Blob<Dtype>*> blob_top_vec_;
};

TYPED_TEST_CASE(ConcatLayerTest, TestDtypesAndDevices);

TYPED_TEST(ConcatLayerTest, TestSetupNum) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  layer_param.mutable_concat_param()->set_concat_dim(0);
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_1_, this->blob_top_vec_);
  EXPECT_EQ(this->blob_top_->num(),
      this->blob_bottom_0_->num() + this->blob_bottom_2_->num());
  EXPECT_EQ(this->blob_top_->channels(), this->blob_bottom_0_->channels());
  EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0_->height());
  EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0_->width());
}

TYPED_TEST(ConcatLayerTest, TestSetupChannels) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_0_, this->blob_top_vec_);
  EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_0_->num());
  EXPECT_EQ(this->blob_top_->channels(),
      this->blob_bottom_0_->channels() + this->blob_bottom_1_->channels());
  EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0_->height());
  EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0_->width());
}

TYPED_TEST(ConcatLayerTest, TestNum) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_0_, this->blob_top_vec_);
  layer.Forward(this->blob_bottom_vec_0_, this->blob_top_vec_);
  for (int n = 0; n < this->blob_top_->num(); ++n) {
    for (int c = 0; c < this->blob_bottom_0_->channels(); ++c) {
      for (int h = 0; h < this->blob_top_->height(); ++h) {
        for (int w = 0; w < this->blob_top_->width(); ++w) {
          EXPECT_EQ(this->blob_top_->data_at(n, c, h, w),
              this->blob_bottom_vec_0_[0]->data_at(n, c, h, w));
        }
      }
    }
    for (int c = 0; c < this->blob_bottom_1_->channels(); ++c) {
      for (int h = 0; h < this->blob_top_->height(); ++h) {
        for (int w = 0; w < this->blob_top_->width(); ++w) {
          EXPECT_EQ(this->blob_top_->data_at(n, c + 3, h, w),
              this->blob_bottom_vec_0_[1]->data_at(n, c, h, w));
        }
      }
    }
  }
}

TYPED_TEST(ConcatLayerTest, TestGradient) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  ConcatLayer<Dtype> layer(layer_param);
  GradientChecker<Dtype> checker(1e-2, 1e-2);
  checker.CheckGradient(&layer, this->blob_bottom_vec_0_,
    this->blob_top_vec_);
}

}  // namespace caffe
<commit_msg>TestConcatLayer: add forward/gradient tests for concatenation along num<commit_after>#include <cstring>
#include <vector>

#include "gtest/gtest.h"

#include "caffe/blob.hpp"
#include "caffe/common.hpp"
#include "caffe/filler.hpp"
#include "caffe/vision_layers.hpp"

#include "caffe/test/test_caffe_main.hpp"
#include "caffe/test/test_gradient_check_util.hpp"

namespace caffe {

template <typename TypeParam>
class ConcatLayerTest : public MultiDeviceTest<TypeParam> {
  typedef typename TypeParam::Dtype Dtype;

 protected:
  ConcatLayerTest()
      : blob_bottom_0_(new Blob<Dtype>(2, 3, 6, 5)),
        blob_bottom_1_(new Blob<Dtype>(2, 5, 6, 5)),
        blob_bottom_2_(new Blob<Dtype>(5, 3, 6, 5)),
        blob_top_(new Blob<Dtype>()) {}
  virtual void SetUp() {
    // fill the values
    shared_ptr<ConstantFiller<Dtype> > filler;
    FillerParameter filler_param;
    filler_param.set_value(1.);
    filler.reset(new ConstantFiller<Dtype>(filler_param));
    filler->Fill(this->blob_bottom_0_);
    filler_param.set_value(2.);
    filler.reset(new ConstantFiller<Dtype>(filler_param));
    filler->Fill(this->blob_bottom_1_);
    filler_param.set_value(3.);
    filler.reset(new ConstantFiller<Dtype>(filler_param));
    filler->Fill(this->blob_bottom_2_);
    blob_bottom_vec_0_.push_back(blob_bottom_0_);
    blob_bottom_vec_0_.push_back(blob_bottom_1_);
    blob_bottom_vec_1_.push_back(blob_bottom_0_);
    blob_bottom_vec_1_.push_back(blob_bottom_2_);
    blob_top_vec_.push_back(blob_top_);
  }

  virtual ~ConcatLayerTest() {
    delete blob_bottom_0_; delete blob_bottom_1_;
    delete blob_bottom_2_; delete blob_top_;
  }

  Blob<Dtype>* const blob_bottom_0_;
  Blob<Dtype>* const blob_bottom_1_;
  Blob<Dtype>* const blob_bottom_2_;
  Blob<Dtype>* const blob_top_;
  vector<Blob<Dtype>*> blob_bottom_vec_0_, blob_bottom_vec_1_;
  vector<Blob<Dtype>*> blob_top_vec_;
};

TYPED_TEST_CASE(ConcatLayerTest, TestDtypesAndDevices);

TYPED_TEST(ConcatLayerTest, TestSetupNum) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  layer_param.mutable_concat_param()->set_concat_dim(0);
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_1_, this->blob_top_vec_);
  EXPECT_EQ(this->blob_top_->num(),
      this->blob_bottom_0_->num() + this->blob_bottom_2_->num());
  EXPECT_EQ(this->blob_top_->channels(), this->blob_bottom_0_->channels());
  EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0_->height());
  EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0_->width());
}

TYPED_TEST(ConcatLayerTest, TestSetupChannels) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_0_, this->blob_top_vec_);
  EXPECT_EQ(this->blob_top_->num(), this->blob_bottom_0_->num());
  EXPECT_EQ(this->blob_top_->channels(),
      this->blob_bottom_0_->channels() + this->blob_bottom_1_->channels());
  EXPECT_EQ(this->blob_top_->height(), this->blob_bottom_0_->height());
  EXPECT_EQ(this->blob_top_->width(), this->blob_bottom_0_->width());
}

TYPED_TEST(ConcatLayerTest, TestForwardNum) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  layer_param.mutable_concat_param()->set_concat_dim(0);
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_1_, this->blob_top_vec_);
  layer.Forward(this->blob_bottom_vec_1_, this->blob_top_vec_);
  for (int n = 0; n < this->blob_bottom_vec_1_[0]->num(); ++n) {
    for (int c = 0; c < this->blob_top_->channels(); ++c) {
      for (int h = 0; h < this->blob_top_->height(); ++h) {
        for (int w = 0; w < this->blob_top_->width(); ++w) {
          EXPECT_EQ(this->blob_top_->data_at(n, c, h, w),
              this->blob_bottom_vec_1_[0]->data_at(n, c, h, w));
        }
      }
    }
  }
  for (int n = 0; n < this->blob_bottom_vec_1_[1]->num(); ++n) {
    for (int c = 0; c < this->blob_top_->channels(); ++c) {
      for (int h = 0; h < this->blob_top_->height(); ++h) {
        for (int w = 0; w < this->blob_top_->width(); ++w) {
          EXPECT_EQ(this->blob_top_->data_at(n + 2, c, h, w),
              this->blob_bottom_vec_1_[1]->data_at(n, c, h, w));
        }
      }
    }
  }
}

TYPED_TEST(ConcatLayerTest, TestForwardChannels) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  ConcatLayer<Dtype> layer(layer_param);
  layer.SetUp(this->blob_bottom_vec_0_, this->blob_top_vec_);
  layer.Forward(this->blob_bottom_vec_0_, this->blob_top_vec_);
  for (int n = 0; n < this->blob_top_->num(); ++n) {
    for (int c = 0; c < this->blob_bottom_0_->channels(); ++c) {
      for (int h = 0; h < this->blob_top_->height(); ++h) {
        for (int w = 0; w < this->blob_top_->width(); ++w) {
          EXPECT_EQ(this->blob_top_->data_at(n, c, h, w),
              this->blob_bottom_vec_0_[0]->data_at(n, c, h, w));
        }
      }
    }
    for (int c = 0; c < this->blob_bottom_1_->channels(); ++c) {
      for (int h = 0; h < this->blob_top_->height(); ++h) {
        for (int w = 0; w < this->blob_top_->width(); ++w) {
          EXPECT_EQ(this->blob_top_->data_at(n, c + 3, h, w),
              this->blob_bottom_vec_0_[1]->data_at(n, c, h, w));
        }
      }
    }
  }
}

TYPED_TEST(ConcatLayerTest, TestGradientNum) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  layer_param.mutable_concat_param()->set_concat_dim(0);
  ConcatLayer<Dtype> layer(layer_param);
  GradientChecker<Dtype> checker(1e-2, 1e-2);
  checker.CheckGradient(&layer, this->blob_bottom_vec_1_,
    this->blob_top_vec_);
}

TYPED_TEST(ConcatLayerTest, TestGradientChannels) {
  typedef typename TypeParam::Dtype Dtype;
  LayerParameter layer_param;
  ConcatLayer<Dtype> layer(layer_param);
  GradientChecker<Dtype> checker(1e-2, 1e-2);
  checker.CheckGradient(&layer, this->blob_bottom_vec_0_,
    this->blob_top_vec_);
}

}  // namespace caffe
<|endoftext|>


<commit_before><commit_msg>Set a few more dependent parameters after reading from a JSON file<commit_after><|endoftext|>


<commit_before>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the qt3to4 porting application of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "filewriter.h"
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <ctype.h>

QT_BEGIN_NAMESPACE

FileWriter *FileWriter::theInstance  = 0;

FileWriter *FileWriter::instance()
{
     if(!theInstance)
        theInstance = new FileWriter();

        return theInstance;
}

void FileWriter::deleteInstance()
{
    if(theInstance) {
        delete theInstance;
        theInstance=0;
    }
}

FileWriter::FileWriter(OverWriteFiles overWrite, QString overwriteMsg)
:overWriteFiles(overWrite)
,overwriteMessage(overwriteMsg)
{
    if(overwriteMessage.isEmpty())
       overwriteMessage = QLatin1String("Convert file ");
}

FileWriter::WriteResult FileWriter::writeFileVerbously(QString filePath, QByteArray contents)
{
    const WriteResult result = writeFile(filePath, contents);
    if (result == WriteSucceeded) {
        QString cleanPath = QDir::cleanPath(filePath);
        printf("Wrote to file: %s \n", QDir::toNativeSeparators(cleanPath).toLocal8Bit().constData());
    }
    return result;
}

FileWriter::WriteResult FileWriter::writeFile(QString filePath, QByteArray contents)
{
    if(filePath.isEmpty())
        return WriteFailed;
    QString path = QFileInfo(filePath).path();
    if (!QDir().mkpath(path)){
         printf("Error creating path %s \n", QDir::toNativeSeparators(path).toLocal8Bit().constData());
    }

    QString cleanPath = QDir::cleanPath(filePath);
    QFile f(cleanPath);
    if (f.exists()) {
        if (overWriteFiles == DontOverWrite) {
            printf("Error writing file %s: It already exists \n",
                QDir::toNativeSeparators(cleanPath).toLatin1().constData());
            return WriteFailed;
        } else if(overWriteFiles == AskOnOverWrite) {
            printf("%s%s? (Y)es, (N)o, (A)ll ", overwriteMessage.toLatin1().constData(),
                QDir::toNativeSeparators(cleanPath).toLatin1().constData());

            char answer = 0;
            while (answer != 'y' && answer != 'n' && answer != 'a') {
#if defined(Q_OS_WIN) && defined(_MSC_VER) && _MSC_VER >= 1400
                scanf_s("%c", &answer);
#else
                scanf("%c", &answer);
#endif
                answer = tolower(answer);
            }

            if(answer == 'n')
                return WriteSkipped;
            else if(answer == 'a')
                overWriteFiles=AlwaysOverWrite;
        }
    }

    f.open(QFile::WriteOnly);
    if (f.isOpen() && f.write(contents) == contents.size())
        return WriteSucceeded;

    printf("Could not write to to file: %s. Is it write protected?\n",
        QDir::toNativeSeparators(filePath).toLatin1().constData());

    return WriteFailed;
}

/*
    Sets the write mode for the file writer. writeMode is one of
    DontOverWrite, AlwaysOverWrite, AskOnOverWrite.
*/
void FileWriter::setOverwriteFiles(OverWriteFiles writeMode)
{
    overWriteFiles = writeMode;
}

QByteArray detectLineEndings(const QByteArray &array)
{
    if (array.contains("\r\n")) {
        return "\r\n";
    } else {
        return "\n";
    }
}

QT_END_NAMESPACE
<commit_msg>Check the result of scanf<commit_after>/****************************************************************************
**
** Copyright (C) 2009 Nokia Corporation and/or its subsidiary(-ies).
** All rights reserved.
** Contact: Nokia Corporation (qt-info@nokia.com)
**
** This file is part of the qt3to4 porting application of the Qt Toolkit.
**
** $QT_BEGIN_LICENSE:LGPL$
** No Commercial Usage
** This file contains pre-release code and may not be distributed.
** You may use this file in accordance with the terms and conditions
** contained in the Technology Preview License Agreement accompanying
** this package.
**
** GNU Lesser General Public License Usage
** Alternatively, this file may be used under the terms of the GNU Lesser
** General Public License version 2.1 as published by the Free Software
** Foundation and appearing in the file LICENSE.LGPL included in the
** packaging of this file.  Please review the following information to
** ensure the GNU Lesser General Public License version 2.1 requirements
** will be met: http://www.gnu.org/licenses/old-licenses/lgpl-2.1.html.
**
** In addition, as a special exception, Nokia gives you certain additional
** rights.  These rights are described in the Nokia Qt LGPL Exception
** version 1.1, included in the file LGPL_EXCEPTION.txt in this package.
**
** If you have questions regarding the use of this file, please contact
** Nokia at qt-info@nokia.com.
**
**
**
**
**
**
**
**
** $QT_END_LICENSE$
**
****************************************************************************/

#include "filewriter.h"
#include <QFile>
#include <QFileInfo>
#include <QDir>
#include <ctype.h>
#include <errno.h>

QT_BEGIN_NAMESPACE

FileWriter *FileWriter::theInstance  = 0;

FileWriter *FileWriter::instance()
{
     if(!theInstance)
        theInstance = new FileWriter();

        return theInstance;
}

void FileWriter::deleteInstance()
{
    if(theInstance) {
        delete theInstance;
        theInstance=0;
    }
}

FileWriter::FileWriter(OverWriteFiles overWrite, QString overwriteMsg)
:overWriteFiles(overWrite)
,overwriteMessage(overwriteMsg)
{
    if(overwriteMessage.isEmpty())
       overwriteMessage = QLatin1String("Convert file ");
}

FileWriter::WriteResult FileWriter::writeFileVerbously(QString filePath, QByteArray contents)
{
    const WriteResult result = writeFile(filePath, contents);
    if (result == WriteSucceeded) {
        QString cleanPath = QDir::cleanPath(filePath);
        printf("Wrote to file: %s \n", QDir::toNativeSeparators(cleanPath).toLocal8Bit().constData());
    }
    return result;
}

FileWriter::WriteResult FileWriter::writeFile(QString filePath, QByteArray contents)
{
    if(filePath.isEmpty())
        return WriteFailed;
    QString path = QFileInfo(filePath).path();
    if (!QDir().mkpath(path)){
         printf("Error creating path %s \n", QDir::toNativeSeparators(path).toLocal8Bit().constData());
    }

    QString cleanPath = QDir::cleanPath(filePath);
    QFile f(cleanPath);
    if (f.exists()) {
        if (overWriteFiles == DontOverWrite) {
            printf("Error writing file %s: It already exists \n",
                QDir::toNativeSeparators(cleanPath).toLatin1().constData());
            return WriteFailed;
        } else if(overWriteFiles == AskOnOverWrite) {
            printf("%s%s? (Y)es, (N)o, (A)ll ", overwriteMessage.toLatin1().constData(),
                QDir::toNativeSeparators(cleanPath).toLatin1().constData());

            char answer = 0;
            while (answer != 'y' && answer != 'n' && answer != 'a') {
#if defined(Q_OS_WIN) && defined(_MSC_VER) && _MSC_VER >= 1400
                int result = scanf_s("%c", &answer);
#else
                int result = scanf("%c", &answer);
#endif
                if (1 == result)
                    answer = tolower(answer);
                else if (EOF == result) {
                    if (EINTR == errno || EILSEQ == errno)
                        continue;

                    answer = 'n';
                }
            }

            if(answer == 'n')
                return WriteSkipped;
            else if(answer == 'a')
                overWriteFiles=AlwaysOverWrite;
        }
    }

    f.open(QFile::WriteOnly);
    if (f.isOpen() && f.write(contents) == contents.size())
        return WriteSucceeded;

    printf("Could not write to to file: %s. Is it write protected?\n",
        QDir::toNativeSeparators(filePath).toLatin1().constData());

    return WriteFailed;
}

/*
    Sets the write mode for the file writer. writeMode is one of
    DontOverWrite, AlwaysOverWrite, AskOnOverWrite.
*/
void FileWriter::setOverwriteFiles(OverWriteFiles writeMode)
{
    overWriteFiles = writeMode;
}

QByteArray detectLineEndings(const QByteArray &array)
{
    if (array.contains("\r\n")) {
        return "\r\n";
    } else {
        return "\n";
    }
}

QT_END_NAMESPACE
<|endoftext|>


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

/*
   This is some wisdom from Cygnus's web page.  If you just try to use
   the "stringify" operator on a preprocessor directive, you'd get
   "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM
   is).  That's because the stringify operator is a special case, and
   the preprocessor isn't allowed to expand things that are passed to
   it.  However, by defining two layers of macros, you get the right
   behavior, since the first pass converts:

   xstr(PLATFORM) -> str(Intel Linux)

   and the next pass gives:

   str(Intel Linux) -> "Intel Linux"

   This is exactly what we want, so we use it.  -Derek Wright and Jeff
   Ballard, 12/2/99

   Also, because the NT build system is totally different, we have to
   define the correct platform string right in here. :( -Derek 12/3/99
*/

#define xstr(s) str(s)
#define str(s) #s

#if defined(WIN32)
#define PLATFORM INTEL-WINNT50
#endif

/* Via configure, one may have specified a particular buildid string to use
	in the version string. So honor that request here. */
#if defined(BUILDID)
#define BUILDIDSTR " BuildID: " xstr(BUILDID)
#else
#define BUILDIDSTR ""
#endif

/* Here is the version string - update before a public release */
/* --- IMPORTANT!  THE FORMAT OF THE VERSION STRING IS VERY STRICT
   BECAUSE IT IS PARSED AT RUNTIME.  DO NOT ALTER THE FORMAT OR ENTER
   ANYTHING EXTRA BEFORE THE DATE.  IF YOU WISH TO ADD EXTRA INFORMATION,
   DO SO _AFTER_ THE BUILDIDSTR AND BEFORE THE TRAILING '$' CHARACTER.
   EXAMPLES:
       $CondorVersion: 6.9.5 " __DATE__ BUILDIDSTR " WinNTPreview $ [OK]
	   $CondorVersion: 6.9.5 WinNTPreview " __DATE__ BUILDIDSTR " $ [WRONG!!!]
   Any questions?  See Todd or Derek.  Note: if you mess it up, DaemonCore
   will EXCEPT at startup time.
*/

static char* CondorVersionString = "$CondorVersion: 7.1.2 " __DATE__ BUILDIDSTR " PRE-RELEASE-UWCS $";

/* Here is the platform string.  You don't need to edit this */
static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $";

extern "C" {

const char*
CondorVersion( void )
{
	return CondorVersionString;
}

const char*
CondorPlatform( void )
{
	return CondorPlatformString;
}

} /* extern "C" */

<commit_msg>set official version string for 7.1.2<commit_after>/***************************************************************
 *
 * Copyright (C) 1990-2007, Condor Team, Computer Sciences Department,
 * University of Wisconsin-Madison, WI.
 *
 * Licensed under the Apache License, Version 2.0 (the "License"); you
 * may not use this file except in compliance with the License.  You may
 * obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 *
 ***************************************************************/

/*
   This is some wisdom from Cygnus's web page.  If you just try to use
   the "stringify" operator on a preprocessor directive, you'd get
   "PLATFORM", not "Intel Linux" (or whatever the value of PLATFORM
   is).  That's because the stringify operator is a special case, and
   the preprocessor isn't allowed to expand things that are passed to
   it.  However, by defining two layers of macros, you get the right
   behavior, since the first pass converts:

   xstr(PLATFORM) -> str(Intel Linux)

   and the next pass gives:

   str(Intel Linux) -> "Intel Linux"

   This is exactly what we want, so we use it.  -Derek Wright and Jeff
   Ballard, 12/2/99

   Also, because the NT build system is totally different, we have to
   define the correct platform string right in here. :( -Derek 12/3/99
*/

#define xstr(s) str(s)
#define str(s) #s

#if defined(WIN32)
#define PLATFORM INTEL-WINNT50
#endif

/* Via configure, one may have specified a particular buildid string to use
	in the version string. So honor that request here. */
#if defined(BUILDID)
#define BUILDIDSTR " BuildID: " xstr(BUILDID)
#else
#define BUILDIDSTR ""
#endif

/* Here is the version string - update before a public release */
/* --- IMPORTANT!  THE FORMAT OF THE VERSION STRING IS VERY STRICT
   BECAUSE IT IS PARSED AT RUNTIME.  DO NOT ALTER THE FORMAT OR ENTER
   ANYTHING EXTRA BEFORE THE DATE.  IF YOU WISH TO ADD EXTRA INFORMATION,
   DO SO _AFTER_ THE BUILDIDSTR AND BEFORE THE TRAILING '$' CHARACTER.
   EXAMPLES:
       $CondorVersion: 6.9.5 " __DATE__ BUILDIDSTR " WinNTPreview $ [OK]
	   $CondorVersion: 6.9.5 WinNTPreview " __DATE__ BUILDIDSTR " $ [WRONG!!!]
   Any questions?  See Todd or Derek.  Note: if you mess it up, DaemonCore
   will EXCEPT at startup time.
*/

static char* CondorVersionString = "$CondorVersion: 7.1.2 " __DATE__ BUILDIDSTR " $";

/* Here is the platform string.  You don't need to edit this */
static char* CondorPlatformString = "$CondorPlatform: " xstr(PLATFORM) " $";

extern "C" {

const char*
CondorVersion( void )
{
	return CondorVersionString;
}

const char*
CondorPlatform( void )
{
	return CondorPlatformString;
}

} /* extern "C" */

<|endoftext|>