<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar
// =============================================================================
//
// ChronoParallel unit test for MPR collision detection
// =============================================================================

#include <stdio.h>
#include <vector>
#include <cmath>

#include "unit_testing.h"
#include "chrono_parallel/math/mat33.h"

using namespace chrono;
int main(int argc, char* argv[]) {
    real3 n = Normalize(real3(rand(), rand(), rand()));
    quaternion R1 = Normalize(quaternion(rand(), rand(), rand(), rand()));
    quaternion R2 = Normalize(quaternion(rand(), rand(), rand(), rand()));

    const Mat33 A1(1, 2, 4, 5, 6, 7, 8, 9, 10);
    const Mat33 A2(10, 2, 4, 7, 2, 5, 8, 3, 1);
    const Mat33 A3(1, 0, 5, 2, 1, 6, 3, 4, 0);
    const Mat33 A4(-24, 20, -5, 18, -15, 4, 5, -4, 1);
    const Mat33 A4_T(-24, 18, 5, 20, -15, -4, -5, 4, 1);
    const Mat33 A5(0.0, 6.4, 3.2, 4.0, -0.8, 3.2, 6.4, 3.2, 5.6);
    ChMatrix33<real> B1 = ChMatrix33<real>(ToChMatrix33(A1));
    ChMatrix33<real> B2 = ChMatrix33<real>(ToChMatrix33(A2));
    real3 a1(1, 2, 3);
    real3 a2(6, 7, 8);
    ChVector<> b1(1, 2, 3);
    ChVector<> b2(6, 7, 8);
    std::cout << "3x3 Matrix Tests ============\n";
    std::cout << "A Matrix\n";
    WeakEqual(Mat33(R1), ToMat33(ToChQuaternion(R1)), C_EPSILON * 3);

    std::cout << "Multiply Matrix\n";
    WeakEqual(A1 * A2, ToMat33(B1 * B2));

    std::cout << "Multiply Matrix Vector\n";
    WeakEqual(A1 * a1, ToReal3(B1 * b1));

    std::cout << "Add Matrix\n";
    WeakEqual(A1 + A2, ToMat33(B1 + B2));

    std::cout << "Subtract Matrix\n";
    WeakEqual(A1 - A2, ToMat33(B1 - B2));

    std::cout << "Post Scale Matrix\n";
    WeakEqual(A1 * 3.1, ToMat33(B1 * 3.1));

    std::cout << "Pre Scale Matrix\n";
    WeakEqual(3.1 * A1, ToMat33(B1 * 3.1));
    {
        std::cout << "Cross Matrix\n";
        Mat33 cross_m1 = SkewSymmetric(n);
        ChMatrix33<real> cross_m2;
        cross_m2.Set_X_matrix(ToChVector(n));
        WeakEqual(cross_m1, ToMat33(cross_m2));
    }
    {
        std::cout << "Multiply T Matrix \n";
        Mat33 Res1 = TransposeMult(A1, A2);
        ChMatrix33<real> Res2;
        Res2.MatrTMultiply(B1, B2);
        WeakEqual(Res1, ToMat33(Res2), C_EPSILON * 2);
    }

    {
        std::cout << "Multiply Matrix T\n";
        ChMatrix33<real> Res2;
        Res2.MatrMultiplyT(B1, B2);
        WeakEqual(MultTranspose(A1, A2), ToMat33(Res2), C_EPSILON * 2);
    }

    {
        std::cout << "Outer Product\n";
        Mat33 Res1 = OuterProduct(a1, a2);
        Mat33 Res2(6, 12, 18, 7, 14, 21, 8, 16, 24);
        WeakEqual(Res1, Res2, C_EPSILON);
    }
    std::cout << "Transpose\n";
    WeakEqual(Transpose(A4), A4_T, C_EPSILON);

    std::cout << "Determinant\n";
    WeakEqual(Determinant(A5), 45.056, C_EPSILON * 400);

    std::cout << "Trace\n";
    WeakEqual(Trace(A5), 4.8, C_EPSILON);

    std::cout << "Adjoint\n";
    WeakEqual(Adjoint(A3), A4, C_EPSILON);

    std::cout << "Adjoint Transpose\n";
    WeakEqual(AdjointTranspose(A4), Transpose(A3), C_EPSILON);

    std::cout << "Inverse\n";
    WeakEqual(Inverse(A3), A4, C_EPSILON);

    std::cout << "Inverse Transpose\n";
    WeakEqual(InverseTranspose(A3), Transpose(Inverse(A3)), C_EPSILON);

    std::cout << "Frobenius Norm\n";
    WeakEqual(Norm(A5), 12.674383614203887588, C_EPSILON);

    std::cout << "Largest Column Normalized\n";
    WeakEqual(LargestColumnNormalized(A4), real3(-.75856744948921676267,0.63213954124101396889, -.15803488531025349222), C_EPSILON);

    std::cout << "Symm3x3 Matrix Tests ============\n";
    std::cout << "Normal Equations Matrix\n";
    WeakEqual(NormalEquationsMatrix(A3), Transpose(A3)*A3, C_EPSILON);
    WeakEqual(NormalEquationsMatrix(A3), Mat33(26,32,3,32,41,10,3,10,25), C_EPSILON);

    return 0;
}
<commit_msg>Add more matrix tests<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2014 projectchrono.org
// All right reserved.
//
// Use of this source code is governed by a BSD-style license that can be found
// in the LICENSE file at the top level of the distribution and at
// http://projectchrono.org/license-chrono.txt.
//
// =============================================================================
// Authors: Hammad Mazhar
// =============================================================================
//
// ChronoParallel unit test for MPR collision detection
// =============================================================================

#include <stdio.h>
#include <vector>
#include <cmath>

#include "unit_testing.h"
#include "chrono_parallel/math/mat33.h"

using namespace chrono;
int main(int argc, char* argv[]) {
    real3 n = Normalize(real3(rand(), rand(), rand()));
    quaternion R1 = Normalize(quaternion(rand(), rand(), rand(), rand()));
    quaternion R2 = Normalize(quaternion(rand(), rand(), rand(), rand()));
    const Mat33 AOne(1, 1, 1, 1, 1, 1, 1, 1, 1);
    const Mat33 A1(1, 2, 4, 5, 6, 7, 8, 9, 10);
    const Mat33 A2(10, 2, 4, 7, 2, 5, 8, 3, 1);
    const Mat33 A3(1, 0, 5, 2, 1, 6, 3, 4, 0);
    const Mat33 A4(-24, 20, -5, 18, -15, 4, 5, -4, 1);
    const Mat33 A4_T(-24, 18, 5, 20, -15, -4, -5, 4, 1);
    const Mat33 A5(0.0, 6.4, 3.2, 4.0, -0.8, 3.2, 6.4, 3.2, 5.6);
    ChMatrix33<real> BOne = ChMatrix33<real>(ToChMatrix33(AOne));
    ChMatrix33<real> B1 = ChMatrix33<real>(ToChMatrix33(A1));
    ChMatrix33<real> B2 = ChMatrix33<real>(ToChMatrix33(A2));

    real3 a1(1, 2, 3);
    real3 a2(6, 7, 8);
    ChVector<> b1(1, 2, 3);
    ChVector<> b2(6, 7, 8);
    std::cout << "3x3 Matrix Tests ============\n";
    std::cout << "0 Matrix\n";
    WeakEqual(Mat33(0), ToMat33(ChMatrix33<real>(0)));

    std::cout << "Diag Matrix\n";
    WeakEqual(Mat33(1), Mat33(1, 0, 0, 0, 1, 0, 0, 0, 1));

    std::cout << "Diag 3 Matrix\n";
    WeakEqual(Mat33(real3(1, 2, 3)), Mat33(1, 0, 0, 0, 2, 0, 0, 0, 3));

    std::cout << "Copy Constructor\n";
    WeakEqual(Mat33(A1), A1);
    {
        std::cout << "= Operator\n";
        Mat33 T = A1;
        WeakEqual(T, A1);
    }

    std::cout << "A Matrix\n";
    WeakEqual(Mat33(R1), ToMat33(ToChQuaternion(R1)), C_EPSILON * 3);

    std::cout << "Multiply Matrix\n";
    WeakEqual(AOne * AOne, ToMat33(BOne * BOne));

    std::cout << "Multiply Matrix\n";
    WeakEqual(A1 * A2, ToMat33(B1 * B2));

    std::cout << "Multiply Matrix Vector\n";
    WeakEqual(A1 * a1, ToReal3(B1 * b1));

    std::cout << "Add Matrix\n";
    WeakEqual(A1 + A2, ToMat33(B1 + B2));

    std::cout << "Subtract Matrix\n";
    WeakEqual(A1 - A2, ToMat33(B1 - B2));

    std::cout << "Post Scale Matrix\n";
    WeakEqual(A1 * 3.1, ToMat33(B1 * 3.1));

    std::cout << "Pre Scale Matrix\n";
    WeakEqual(3.1 * A1, ToMat33(B1 * 3.1));
    {
        std::cout << "Cross Matrix\n";
        Mat33 cross_m1 = SkewSymmetric(n);
        ChMatrix33<real> cross_m2;
        cross_m2.Set_X_matrix(ToChVector(n));
        WeakEqual(cross_m1, ToMat33(cross_m2));
    }
    {
        std::cout << "Multiply T Matrix \n";
        Mat33 Res1 = TransposeMult(A1, A2);
        ChMatrix33<real> Res2;
        Res2.MatrTMultiply(B1, B2);
        WeakEqual(Res1, ToMat33(Res2), C_EPSILON * 2);
    }

    {
        std::cout << "Multiply Matrix T\n";
        ChMatrix33<real> Res2;
        Res2.MatrMultiplyT(B1, B2);
        WeakEqual(MultTranspose(A1, A2), ToMat33(Res2), C_EPSILON * 2);
    }

    {
        std::cout << "Outer Product\n";
        Mat33 Res1 = OuterProduct(a1, a2);
        Mat33 Res2(6, 12, 18, 7, 14, 21, 8, 16, 24);
        WeakEqual(Res1, Res2, C_EPSILON);
    }
    std::cout << "Transpose\n";
    WeakEqual(Transpose(A4), A4_T, C_EPSILON);

    std::cout << "Determinant\n";
    WeakEqual(Determinant(A5), 45.056, C_EPSILON * 400);

    std::cout << "Trace\n";
    WeakEqual(Trace(A5), 4.8, C_EPSILON);

    std::cout << "Adjoint\n";
    WeakEqual(Adjoint(A3), A4, C_EPSILON);

    std::cout << "Adjoint Transpose\n";
    WeakEqual(AdjointTranspose(A4), Transpose(A3), C_EPSILON);

    std::cout << "Inverse\n";
    WeakEqual(Inverse(A3), A4, C_EPSILON);

    std::cout << "Inverse Transpose\n";
    WeakEqual(InverseTranspose(A3), Transpose(Inverse(A3)), C_EPSILON);

    std::cout << "Frobenius Norm\n";
    WeakEqual(Norm(A5), 12.674383614203887588, C_EPSILON);

    std::cout << "Largest Column Normalized\n";
    WeakEqual(LargestColumnNormalized(A4),
              real3(-.75856744948921676267, 0.63213954124101396889, -.15803488531025349222), C_EPSILON);

    std::cout << "Normal Equations Matrix\n";
    WeakEqual(NormalEquationsMatrix(A3), Transpose(A3) * A3, C_EPSILON);
    WeakEqual(NormalEquationsMatrix(A3), Mat33(26, 32, 3, 32, 41, 10, 3, 10, 25), C_EPSILON);

    std::cout << "Symm2x2 Matrix Tests ============\n";
    {
        std::cout << "A^T*B With Symmetric Result\n";

        Mat32 C1(real3(1, 2, 3), real3(3, 2, 6));
        Mat32 C2(real3(2, 3, 1), real3(2, 2, 4));

        SymMat22 RES = TransposeTimesWithSymmetricResult(C1, C2);
        WeakEqual(RES, SymMat22(11, 18, 34));
    }

    return 0;
}
<|endoftext|>


<commit_before>// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "dense_matmul_function.h"
#include "dense_tensor_view.h"
#include <vespa/vespalib/objects/objectvisitor.h>
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/operation.h>
#include <cassert>

#include <cblas.h>

namespace vespalib::tensor {

using eval::ValueType;
using eval::TensorFunction;
using eval::TensorEngine;
using eval::as;
using eval::Aggr;
using namespace eval::tensor_function;
using namespace eval::operation;

namespace {

template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
double my_dot_product(const LCT *lhs, const RCT *rhs, size_t lhs_size, size_t common_size, size_t rhs_size) {
    double result = 0.0;
    for (size_t i = 0; i < common_size; ++i) {
        result += ((*lhs) * (*rhs));
        lhs += (lhs_common_inner ? 1 : lhs_size);
        rhs += (rhs_common_inner ? 1 : rhs_size);
    }
    return result;
}

template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
void my_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
    const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
    using OCT = typename eval::UnifyCellTypes<LCT,RCT>::type;
    auto lhs_cells = DenseTensorView::typify_cells<LCT>(state.peek(1));
    auto rhs_cells = DenseTensorView::typify_cells<RCT>(state.peek(0));
    auto dst_cells = state.stash.create_array<OCT>(self.lhs_size * self.rhs_size);
    OCT *dst = dst_cells.begin();
    const LCT *lhs = lhs_cells.cbegin();
    for (size_t i = 0; i < self.lhs_size; ++i) {
        const RCT *rhs = rhs_cells.cbegin();
        for (size_t j = 0; j < self.rhs_size; ++j) {
            *dst++ = my_dot_product<LCT,RCT,lhs_common_inner,rhs_common_inner>(lhs, rhs, self.lhs_size, self.common_size, self.rhs_size);
            rhs += (rhs_common_inner ? self.common_size : 1);
        }
        lhs += (lhs_common_inner ? self.common_size : 1);
    }
    state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}

template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_double_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
    const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
    auto lhs_cells = DenseTensorView::typify_cells<double>(state.peek(1));
    auto rhs_cells = DenseTensorView::typify_cells<double>(state.peek(0));
    auto dst_cells = state.stash.create_array<double>(self.lhs_size * self.rhs_size);
    cblas_dgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
                self.lhs_size, self.rhs_size, self.common_size, 1.0,
                lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
                rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
                0.0, dst_cells.begin(), self.rhs_size);
    state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}

template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_float_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
    const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
    auto lhs_cells = DenseTensorView::typify_cells<float>(state.peek(1));
    auto rhs_cells = DenseTensorView::typify_cells<float>(state.peek(0));
    auto dst_cells = state.stash.create_array<float>(self.lhs_size * self.rhs_size);
    cblas_sgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
                self.lhs_size, self.rhs_size, self.common_size, 1.0,
                lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
                rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
                0.0, dst_cells.begin(), self.rhs_size);
    state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}

bool is_matrix(const ValueType &type) {
    return (type.is_dense() && (type.dimensions().size() == 2));
}

bool is_matmul(const eval::ValueType &a, const eval::ValueType &b,
               const vespalib::string &reduce_dim, const eval::ValueType &result_type)
{
    size_t npos = ValueType::Dimension::npos;
    return (is_matrix(a) && is_matrix(b) && is_matrix(result_type) &&
            (a.dimension_index(reduce_dim) != npos) &&
            (b.dimension_index(reduce_dim) != npos));
}

const ValueType::Dimension &dim(const TensorFunction &expr, size_t idx) {
    return expr.result_type().dimensions()[idx];
}

size_t inv(size_t idx) { return (1 - idx); }

const TensorFunction &create_matmul(const TensorFunction &a, const TensorFunction &b,
                                    const vespalib::string &reduce_dim, const ValueType &result_type, Stash &stash) {
    size_t a_idx = a.result_type().dimension_index(reduce_dim);
    size_t b_idx = b.result_type().dimension_index(reduce_dim);
    assert(a_idx != ValueType::Dimension::npos);
    assert(b_idx != ValueType::Dimension::npos);
    assert(dim(a, a_idx).size == dim(b, b_idx).size);
    bool a_common_inner = (a_idx == 1);
    bool b_common_inner = (b_idx == 1);
    size_t a_size = dim(a, inv(a_idx)).size;
    size_t b_size = dim(b, inv(b_idx)).size;
    size_t common_size = dim(a, a_idx).size;
    bool a_is_lhs = (dim(a, inv(a_idx)).name < dim(b, inv(b_idx)).name);
    if (a_is_lhs) {
        return stash.create<DenseMatMulFunction>(result_type, a, b, a_size, common_size, b_size, a_common_inner, b_common_inner);
    } else {
        return stash.create<DenseMatMulFunction>(result_type, b, a, b_size, common_size, a_size, b_common_inner, a_common_inner);
    }
}

template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp {
    static auto get_fun() {
        return my_matmul_op<LCT, RCT, lhs_common_inner, rhs_common_inner>;
    }
};

template <bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp<double, double, lhs_common_inner, rhs_common_inner> {
    static auto get_fun() {
            return my_cblas_double_matmul_op<lhs_common_inner, rhs_common_inner>;
    }
};

template <bool lhs_common_inner, bool rhs_common_inner>
struct MyMatMulOp<float, float, lhs_common_inner, rhs_common_inner> {
    static auto get_fun() {
        return my_cblas_float_matmul_op<lhs_common_inner, rhs_common_inner>;
    }
};

struct MyTarget {
    template<typename R1, typename R2, typename R3, typename R4>
    static auto invoke() {
        using MyOp = MyMatMulOp<R1, R2, R3::value, R4::value>;
        return MyOp::get_fun();
    }
};

} // namespace vespalib::tensor::<unnamed>

DenseMatMulFunction::Self::Self(const eval::ValueType &result_type_in,
                                size_t lhs_size_in,
                                size_t common_size_in,
                                size_t rhs_size_in)
    : result_type(result_type_in),
      lhs_size(lhs_size_in),
      common_size(common_size_in),
      rhs_size(rhs_size_in)
{
}

DenseMatMulFunction::Self::~Self() = default;

DenseMatMulFunction::DenseMatMulFunction(const eval::ValueType &result_type,
                                         const eval::TensorFunction &lhs_in,
                                         const eval::TensorFunction &rhs_in,
                                         size_t lhs_size,
                                         size_t common_size,
                                         size_t rhs_size,
                                         bool lhs_common_inner,
                                         bool rhs_common_inner)
    : Super(result_type, lhs_in, rhs_in),
      _lhs_size(lhs_size),
      _common_size(common_size),
      _rhs_size(rhs_size),
      _lhs_common_inner(lhs_common_inner),
      _rhs_common_inner(rhs_common_inner)
{
}

DenseMatMulFunction::~DenseMatMulFunction() = default;

eval::InterpretedFunction::Instruction
DenseMatMulFunction::compile_self(const TensorEngine &, Stash &stash) const
{
    using MyTypify = TypifyValue<eval::TypifyCellType,vespalib::TypifyBool>;
    Self &self = stash.create<Self>(result_type(), _lhs_size, _common_size, _rhs_size);
    auto op = typify_invoke<4,MyTypify,MyTarget>(
            lhs().result_type().cell_type(), rhs().result_type().cell_type(),
            _lhs_common_inner, _rhs_common_inner);
    return eval::InterpretedFunction::Instruction(op, (uint64_t)(&self));
}

void
DenseMatMulFunction::visit_self(vespalib::ObjectVisitor &visitor) const
{
    Super::visit_self(visitor);
    visitor.visitInt("lhs_size", _lhs_size);
    visitor.visitInt("common_size", _common_size);
    visitor.visitInt("rhs_size", _rhs_size);
    visitor.visitBool("lhs_common_inner", _lhs_common_inner);
    visitor.visitBool("rhs_common_inner", _rhs_common_inner);
}

const TensorFunction &
DenseMatMulFunction::optimize(const eval::TensorFunction &expr, Stash &stash)
{
    auto reduce = as<Reduce>(expr);
    if (reduce && (reduce->aggr() == Aggr::SUM) && (reduce->dimensions().size() == 1)) {
        auto join = as<Join>(reduce->child());
        if (join && (join->function() == Mul::f)) {
            const TensorFunction &a = join->lhs();
            const TensorFunction &b = join->rhs();
            if (is_matmul(a.result_type(), b.result_type(), reduce->dimensions()[0], expr.result_type())) {
                return create_matmul(a, b, reduce->dimensions()[0], expr.result_type(), stash);
            }
        }
    }
    return expr;
}

} // namespace vespalib::tensor
<commit_msg>replace template magic with if statement<commit_after>// Copyright 2020 Oath Inc. Licensed under the terms of the Apache 2.0 license. See LICENSE in the project root.

#include "dense_matmul_function.h"
#include "dense_tensor_view.h"
#include <vespa/vespalib/objects/objectvisitor.h>
#include <vespa/eval/eval/value.h>
#include <vespa/eval/eval/operation.h>
#include <cassert>

#include <cblas.h>

namespace vespalib::tensor {

using eval::ValueType;
using eval::TensorFunction;
using eval::TensorEngine;
using eval::as;
using eval::Aggr;
using namespace eval::tensor_function;
using namespace eval::operation;

namespace {

template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
double my_dot_product(const LCT *lhs, const RCT *rhs, size_t lhs_size, size_t common_size, size_t rhs_size) {
    double result = 0.0;
    for (size_t i = 0; i < common_size; ++i) {
        result += ((*lhs) * (*rhs));
        lhs += (lhs_common_inner ? 1 : lhs_size);
        rhs += (rhs_common_inner ? 1 : rhs_size);
    }
    return result;
}

template <typename LCT, typename RCT, bool lhs_common_inner, bool rhs_common_inner>
void my_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
    const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
    using OCT = typename eval::UnifyCellTypes<LCT,RCT>::type;
    auto lhs_cells = DenseTensorView::typify_cells<LCT>(state.peek(1));
    auto rhs_cells = DenseTensorView::typify_cells<RCT>(state.peek(0));
    auto dst_cells = state.stash.create_array<OCT>(self.lhs_size * self.rhs_size);
    OCT *dst = dst_cells.begin();
    const LCT *lhs = lhs_cells.cbegin();
    for (size_t i = 0; i < self.lhs_size; ++i) {
        const RCT *rhs = rhs_cells.cbegin();
        for (size_t j = 0; j < self.rhs_size; ++j) {
            *dst++ = my_dot_product<LCT,RCT,lhs_common_inner,rhs_common_inner>(lhs, rhs, self.lhs_size, self.common_size, self.rhs_size);
            rhs += (rhs_common_inner ? self.common_size : 1);
        }
        lhs += (lhs_common_inner ? self.common_size : 1);
    }
    state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}

template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_double_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
    const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
    auto lhs_cells = DenseTensorView::typify_cells<double>(state.peek(1));
    auto rhs_cells = DenseTensorView::typify_cells<double>(state.peek(0));
    auto dst_cells = state.stash.create_array<double>(self.lhs_size * self.rhs_size);
    cblas_dgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
                self.lhs_size, self.rhs_size, self.common_size, 1.0,
                lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
                rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
                0.0, dst_cells.begin(), self.rhs_size);
    state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}

template <bool lhs_common_inner, bool rhs_common_inner>
void my_cblas_float_matmul_op(eval::InterpretedFunction::State &state, uint64_t param) {
    const DenseMatMulFunction::Self &self = *((const DenseMatMulFunction::Self *)(param));
    auto lhs_cells = DenseTensorView::typify_cells<float>(state.peek(1));
    auto rhs_cells = DenseTensorView::typify_cells<float>(state.peek(0));
    auto dst_cells = state.stash.create_array<float>(self.lhs_size * self.rhs_size);
    cblas_sgemm(CblasRowMajor, lhs_common_inner ? CblasNoTrans : CblasTrans, rhs_common_inner ? CblasTrans : CblasNoTrans,
                self.lhs_size, self.rhs_size, self.common_size, 1.0,
                lhs_cells.cbegin(), lhs_common_inner ? self.common_size : self.lhs_size,
                rhs_cells.cbegin(), rhs_common_inner ? self.common_size : self.rhs_size,
                0.0, dst_cells.begin(), self.rhs_size);
    state.pop_pop_push(state.stash.create<DenseTensorView>(self.result_type, TypedCells(dst_cells)));
}

bool is_matrix(const ValueType &type) {
    return (type.is_dense() && (type.dimensions().size() == 2));
}

bool is_matmul(const eval::ValueType &a, const eval::ValueType &b,
               const vespalib::string &reduce_dim, const eval::ValueType &result_type)
{
    size_t npos = ValueType::Dimension::npos;
    return (is_matrix(a) && is_matrix(b) && is_matrix(result_type) &&
            (a.dimension_index(reduce_dim) != npos) &&
            (b.dimension_index(reduce_dim) != npos));
}

const ValueType::Dimension &dim(const TensorFunction &expr, size_t idx) {
    return expr.result_type().dimensions()[idx];
}

size_t inv(size_t idx) { return (1 - idx); }

const TensorFunction &create_matmul(const TensorFunction &a, const TensorFunction &b,
                                    const vespalib::string &reduce_dim, const ValueType &result_type, Stash &stash) {
    size_t a_idx = a.result_type().dimension_index(reduce_dim);
    size_t b_idx = b.result_type().dimension_index(reduce_dim);
    assert(a_idx != ValueType::Dimension::npos);
    assert(b_idx != ValueType::Dimension::npos);
    assert(dim(a, a_idx).size == dim(b, b_idx).size);
    bool a_common_inner = (a_idx == 1);
    bool b_common_inner = (b_idx == 1);
    size_t a_size = dim(a, inv(a_idx)).size;
    size_t b_size = dim(b, inv(b_idx)).size;
    size_t common_size = dim(a, a_idx).size;
    bool a_is_lhs = (dim(a, inv(a_idx)).name < dim(b, inv(b_idx)).name);
    if (a_is_lhs) {
        return stash.create<DenseMatMulFunction>(result_type, a, b, a_size, common_size, b_size, a_common_inner, b_common_inner);
    } else {
        return stash.create<DenseMatMulFunction>(result_type, b, a, b_size, common_size, a_size, b_common_inner, a_common_inner);
    }
}

struct MyGetFun {
    template<typename R1, typename R2, typename R3, typename R4> static auto invoke() {
        if (std::is_same_v<R1,double> && std::is_same_v<R2,double>) {
            return my_cblas_double_matmul_op<R3::value, R4::value>;
        } else if (std::is_same_v<R1,float> && std::is_same_v<R2,float>) {
            return my_cblas_float_matmul_op<R3::value, R4::value>;
        } else {
            return my_matmul_op<R1, R2, R3::value, R4::value>;
        }
    }
};

} // namespace vespalib::tensor::<unnamed>

DenseMatMulFunction::Self::Self(const eval::ValueType &result_type_in,
                                size_t lhs_size_in,
                                size_t common_size_in,
                                size_t rhs_size_in)
    : result_type(result_type_in),
      lhs_size(lhs_size_in),
      common_size(common_size_in),
      rhs_size(rhs_size_in)
{
}

DenseMatMulFunction::Self::~Self() = default;

DenseMatMulFunction::DenseMatMulFunction(const eval::ValueType &result_type,
                                         const eval::TensorFunction &lhs_in,
                                         const eval::TensorFunction &rhs_in,
                                         size_t lhs_size,
                                         size_t common_size,
                                         size_t rhs_size,
                                         bool lhs_common_inner,
                                         bool rhs_common_inner)
    : Super(result_type, lhs_in, rhs_in),
      _lhs_size(lhs_size),
      _common_size(common_size),
      _rhs_size(rhs_size),
      _lhs_common_inner(lhs_common_inner),
      _rhs_common_inner(rhs_common_inner)
{
}

DenseMatMulFunction::~DenseMatMulFunction() = default;

eval::InterpretedFunction::Instruction
DenseMatMulFunction::compile_self(const TensorEngine &, Stash &stash) const
{
    using MyTypify = TypifyValue<eval::TypifyCellType,TypifyBool>;
    Self &self = stash.create<Self>(result_type(), _lhs_size, _common_size, _rhs_size);
    auto op = typify_invoke<4,MyTypify,MyGetFun>(
            lhs().result_type().cell_type(), rhs().result_type().cell_type(),
            _lhs_common_inner, _rhs_common_inner);
    return eval::InterpretedFunction::Instruction(op, (uint64_t)(&self));
}

void
DenseMatMulFunction::visit_self(vespalib::ObjectVisitor &visitor) const
{
    Super::visit_self(visitor);
    visitor.visitInt("lhs_size", _lhs_size);
    visitor.visitInt("common_size", _common_size);
    visitor.visitInt("rhs_size", _rhs_size);
    visitor.visitBool("lhs_common_inner", _lhs_common_inner);
    visitor.visitBool("rhs_common_inner", _rhs_common_inner);
}

const TensorFunction &
DenseMatMulFunction::optimize(const eval::TensorFunction &expr, Stash &stash)
{
    auto reduce = as<Reduce>(expr);
    if (reduce && (reduce->aggr() == Aggr::SUM) && (reduce->dimensions().size() == 1)) {
        auto join = as<Join>(reduce->child());
        if (join && (join->function() == Mul::f)) {
            const TensorFunction &a = join->lhs();
            const TensorFunction &b = join->rhs();
            if (is_matmul(a.result_type(), b.result_type(), reduce->dimensions()[0], expr.result_type())) {
                return create_matmul(a, b, reduce->dimensions()[0], expr.result_type(), stash);
            }
        }
    }
    return expr;
}

} // namespace vespalib::tensor
<|endoftext|>


<commit_before>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2016 INRIA.
 *
 * 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.
*/

/*!\file BouncingBallTS.cpp
  \brief \ref EMBouncingBall - C++ input file, Time-Stepping version -
  V. Acary, F. Perignon.

  A Ball bouncing on the ground.
  Direct description of the model.
  Simulation with a Time-Stepping scheme.
*/

#include "SiconosKernel.hpp"

using namespace std;

int main(int argc, char* argv[])
{
  try
  {

    // ================= Creation of the model =======================

    // User-defined main parameters
    unsigned int nDof = 3;           // degrees of freedom for the ball
    double t0 = 0;                   // initial computation time
    double T = 10;                  // final computation time
    double h = 0.005;                // time step
    double position_init = 1.0;      // initial position for lowest bead.
    double velocity_init = 0.0;      // initial velocity for lowest bead.
    double theta = 0.5;              // theta for MoreauJeanOSI integrator
    double R = 0.1; // Ball radius
    double m = 1; // Ball mass
    double g = 9.81; // Gravity
    // -------------------------
    // --- Dynamical systems ---
    // -------------------------

    cout << "====> Model loading ..." <<  endl;

    SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof));
    (*Mass)(0, 0) = m;
    (*Mass)(1, 1) = m;
    (*Mass)(2, 2) = 2. / 5 * m * R * R;

    // -- Initial positions and velocities --
    SP::SiconosVector q0(new SiconosVector(nDof));
    SP::SiconosVector v0(new SiconosVector(nDof));
    (*q0)(0) = position_init;
    (*v0)(0) = velocity_init;

    // -- The dynamical system --
    SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass));

    // -- Set external forces (weight) --
    SP::SiconosVector weight(new SiconosVector(nDof));
    (*weight)(0) = -m * g;
    ball->setFExtPtr(weight);

    // --------------------
    // --- Interactions ---
    // --------------------

    // -- nslaw --
    double e = 0.9;

    // Interaction ball-floor
    //
    SP::SimpleMatrix H(new SimpleMatrix(1, nDof));
    (*H)(0, 0) = 1.0;

    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
    SP::Relation relation(new LagrangianLinearTIR(H));

    SP::Interaction inter;

    // -------------
    // --- Model ---
    // -------------
    SP::NonSmoothDynamicalSystem bouncingBall(new NonSmoothDynamicalSystem(t0, T));

    // add the dynamical system in the non smooth dynamical system
    bouncingBall->insertDynamicalSystem(ball);

    // ------------------
    // --- Simulation ---
    // ------------------

    // -- (1) OneStepIntegrators --
    SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta));

    // -- (2) Time discretisation --
    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));

    // -- (3) one step non smooth problem
    SP::OneStepNSProblem osnspb(new LCP());

    // -- (4) Simulation setup with (1) (2) (3)
    SP::TimeStepping s(new TimeStepping(bouncingBall, t, OSI, osnspb));

    // =========================== End of model definition ===========================

    // ================================= Computation =================================

    // --- Simulation ---

    int N = ceil((T - t0) / h); // Number of time steps

    // --- Get the values to be plotted ---
    // -> saved in a matrix dataPlot
    unsigned int outputSize = 5;
    SimpleMatrix dataPlot(N + 1, outputSize);

    SP::SiconosVector q = ball->q();
    SP::SiconosVector v = ball->velocity();
    SP::SiconosVector p = ball->p(1);

    // lambda is zero until we create the Interaction
    SP::SiconosVector lambda(new SiconosVector(1));
    lambda->zero();

    dataPlot(0, 0) = bouncingBall->t0();
    dataPlot(0, 1) = (*q)(0);
    dataPlot(0, 2) = (*v)(0);
    dataPlot(0, 3) = (*p)(0);
    dataPlot(0, 4) = (*lambda)(0);
    // --- Time loop ---
    cout << "====> Start computation ... " << endl;
    // ==== Simulation loop - Writing without explicit event handling =====
    int k = 1;
    boost::progress_display show_progress(N);

    boost::timer time;
    time.restart();

    while (s->hasNextEvent())
    {
      if (k==200) {
        inter.reset(new Interaction(nslaw, relation));

        // link the interaction and the dynamical system
        bouncingBall->link(inter, ball);

        // new "lambda" pointer
        lambda = inter->lambda(1);
      }

      s->computeOneStep();

      s->clearNSDSChangeLog();

      // --- Get values to be plotted ---
      dataPlot(k, 0) =  s->nextTime();
      dataPlot(k, 1) = (*q)(0);
      dataPlot(k, 2) = (*v)(0);
      dataPlot(k, 3) = (*p)(0);
      dataPlot(k, 4) = (*lambda)(0);
      s->nextStep();
      ++show_progress;
      k++;
    }
    cout  << "End of computation - Number of iterations done: " << k - 1 << endl;
    cout << "Computation Time " << time.elapsed()  << endl;

    // --- Output files ---
    cout << "====> Output file writing ..." << endl;
    dataPlot.resize(k, outputSize);
    ioMatrix::write("result.dat", "ascii", dataPlot, "noDim");

    double error=0.0, eps=1e-12;
    if (ioMatrix::compareRefFile(dataPlot, "BouncingBallTS-Dynamic.ref", eps, error)
        && error > eps)
      return 1;

  }

  catch (SiconosException e)
  {
    cout << e.report() << endl;
  }
  catch (...)
  {
    cout << "Exception caught in BouncingBallTS.cpp" << endl;
  }

}
<commit_msg>[examples] with the new initialization process the insertion of a new interaction is taken into acount at the good time step<commit_after>/* Siconos is a program dedicated to modeling, simulation and control
 * of non smooth dynamical systems.
 *
 * Copyright 2016 INRIA.
 *
 * 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.
*/

/*!\file BouncingBallTS.cpp
  \brief \ref EMBouncingBall - C++ input file, Time-Stepping version -
  V. Acary, F. Perignon.

  A Ball bouncing on the ground.
  Direct description of the model.
  Simulation with a Time-Stepping scheme.
*/

#include "SiconosKernel.hpp"

using namespace std;

int main(int argc, char* argv[])
{
  try
  {

    // ================= Creation of the model =======================

    // User-defined main parameters
    unsigned int nDof = 3;           // degrees of freedom for the ball
    double t0 = 0;                   // initial computation time
    double T = 10;                  // final computation time
    double h = 0.005;                // time step
    double position_init = 1.0;      // initial position for lowest bead.
    double velocity_init = 0.0;      // initial velocity for lowest bead.
    double theta = 0.5;              // theta for MoreauJeanOSI integrator
    double R = 0.1; // Ball radius
    double m = 1; // Ball mass
    double g = 9.81; // Gravity
    // -------------------------
    // --- Dynamical systems ---
    // -------------------------

    cout << "====> Model loading ..." <<  endl;

    SP::SiconosMatrix Mass(new SimpleMatrix(nDof, nDof));
    (*Mass)(0, 0) = m;
    (*Mass)(1, 1) = m;
    (*Mass)(2, 2) = 2. / 5 * m * R * R;

    // -- Initial positions and velocities --
    SP::SiconosVector q0(new SiconosVector(nDof));
    SP::SiconosVector v0(new SiconosVector(nDof));
    (*q0)(0) = position_init;
    (*v0)(0) = velocity_init;

    // -- The dynamical system --
    SP::LagrangianLinearTIDS ball(new LagrangianLinearTIDS(q0, v0, Mass));

    // -- Set external forces (weight) --
    SP::SiconosVector weight(new SiconosVector(nDof));
    (*weight)(0) = -m * g;
    ball->setFExtPtr(weight);

    // --------------------
    // --- Interactions ---
    // --------------------

    // -- nslaw --
    double e = 0.9;

    // Interaction ball-floor
    //
    SP::SimpleMatrix H(new SimpleMatrix(1, nDof));
    (*H)(0, 0) = 1.0;

    SP::NonSmoothLaw nslaw(new NewtonImpactNSL(e));
    SP::Relation relation(new LagrangianLinearTIR(H));

    SP::Interaction inter;

    // -------------
    // --- Model ---
    // -------------
    SP::NonSmoothDynamicalSystem bouncingBall(new NonSmoothDynamicalSystem(t0, T));

    // add the dynamical system in the non smooth dynamical system
    bouncingBall->insertDynamicalSystem(ball);

    // ------------------
    // --- Simulation ---
    // ------------------

    // -- (1) OneStepIntegrators --
    SP::MoreauJeanOSI OSI(new MoreauJeanOSI(theta));

    // -- (2) Time discretisation --
    SP::TimeDiscretisation t(new TimeDiscretisation(t0, h));

    // -- (3) one step non smooth problem
    SP::OneStepNSProblem osnspb(new LCP());

    // -- (4) Simulation setup with (1) (2) (3)
    SP::TimeStepping s(new TimeStepping(bouncingBall, t, OSI, osnspb));

    // =========================== End of model definition ===========================

    // ================================= Computation =================================

    // --- Simulation ---

    int N = ceil((T - t0) / h); // Number of time steps

    // --- Get the values to be plotted ---
    // -> saved in a matrix dataPlot
    unsigned int outputSize = 5;
    SimpleMatrix dataPlot(N + 1, outputSize);

    SP::SiconosVector q = ball->q();
    SP::SiconosVector v = ball->velocity();
    SP::SiconosVector p = ball->p(1);

    // lambda is zero until we create the Interaction
    SP::SiconosVector lambda(new SiconosVector(1));
    lambda->zero();

    dataPlot(0, 0) = bouncingBall->t0();
    dataPlot(0, 1) = (*q)(0);
    dataPlot(0, 2) = (*v)(0);
    dataPlot(0, 3) = (*p)(0);
    dataPlot(0, 4) = (*lambda)(0);
    // --- Time loop ---
    cout << "====> Start computation ... " << endl;
    // ==== Simulation loop - Writing without explicit event handling =====
    int k = 1;
    boost::progress_display show_progress(N);

    boost::timer time;
    time.restart();

    while (s->hasNextEvent())
    {
      if (k==201) {
        inter.reset(new Interaction(nslaw, relation));

        // link the interaction and the dynamical system
        bouncingBall->link(inter, ball);

        // new "lambda" pointer
        lambda = inter->lambda(1);
      }

      s->computeOneStep();

      s->clearNSDSChangeLog();

      // --- Get values to be plotted ---
      dataPlot(k, 0) =  s->nextTime();
      dataPlot(k, 1) = (*q)(0);
      dataPlot(k, 2) = (*v)(0);
      dataPlot(k, 3) = (*p)(0);
      dataPlot(k, 4) = (*lambda)(0);
      s->nextStep();
      ++show_progress;
      k++;
    }
    cout  << "End of computation - Number of iterations done: " << k - 1 << endl;
    cout << "Computation Time " << time.elapsed()  << endl;

    // --- Output files ---
    cout << "====> Output file writing ..." << endl;
    dataPlot.resize(k, outputSize);
    ioMatrix::write("result.dat", "ascii", dataPlot, "noDim");

    double error=0.0, eps=1e-12;
    if (ioMatrix::compareRefFile(dataPlot, "BouncingBallTS-Dynamic.ref", eps, error)
        && error > eps)
      return 1;

  }

  catch (SiconosException e)
  {
    cout << e.report() << endl;
  }
  catch (...)
  {
    cout << "Exception caught in BouncingBallTS.cpp" << endl;
  }

}
<|endoftext|>


<commit_before>//
// ban.hpp
// ********
//
// Copyright (c) 2020 Sharon Fox (sharon at xandium dot io)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//

#pragma once

#include "aegis/config.hpp"
#include "aegis/snowflake.hpp"
#include "aegis/permission.hpp"
#include "aegis/user.hpp"
#include "ban.hpp"
#include <nlohmann/json.hpp>
#include <vector>

namespace aegis
{

    namespace gateway
    {

        namespace objects
        {

            struct bans;

            /// \cond TEMPLATES
            void from_json(const nlohmann::json& j, bans& m);
            void to_json(nlohmann::json& j, const bans& m);
            /// \endcond

            /// Stores info pertaining to guild bans
            struct bans
            {
                bans(const std::string& _json, aegis::core* bot) noexcept
                {
                    from_json(nlohmann::json::parse(_json), *this);
                }

                bans(const nlohmann::json& _json, aegis::core* bot) noexcept
                {
                    from_json(_json, *this);
                }

                bans(aegis::core* bot) noexcept {}

                bans() noexcept {}

                std::vector<aegis::gateway::objects::ban>::iterator begin()
                {
                    return _bans.begin();
                }

                std::vector<aegis::gateway::objects::ban>::iterator end()
                {
                    return _bans.end();
                }

                std::vector<aegis::gateway::objects::ban>::reverse_iterator rbegin()
                {
                    return _bans.rbegin();
                }

                std::vector<aegis::gateway::objects::ban>::reverse_iterator rend()
                {
                    return _bans.rend();
                }

                std::vector<aegis::gateway::objects::ban> _bans; /**< array of messages */

            };

            /// \cond TEMPLATES
            inline void from_json(const nlohmann::json& j, bans& m)
            {
                if (j.size())
                    for (const auto& _ban : j)
                        m._bans.push_back(_ban);
            }

            inline void to_json(nlohmann::json& j, const bans& m)
            {
                if (!m._bans.empty())
                    for (const auto& _ban : m._bans)
                        j.push_back(_ban);
            }
            /// \endcond

        }

    }

}
<commit_msg>Fix comment<commit_after>//
// ban.hpp
// ********
//
// Copyright (c) 2020 Sharon Fox (sharon at xandium dot io)
//
// Distributed under the MIT License. (See accompanying file LICENSE)
//

#pragma once

#include "aegis/config.hpp"
#include "aegis/snowflake.hpp"
#include "aegis/permission.hpp"
#include "aegis/user.hpp"
#include "ban.hpp"
#include <nlohmann/json.hpp>
#include <vector>

namespace aegis
{

    namespace gateway
    {

        namespace objects
        {

            struct bans;

            /// \cond TEMPLATES
            void from_json(const nlohmann::json& j, bans& m);
            void to_json(nlohmann::json& j, const bans& m);
            /// \endcond

            /// Stores info pertaining to guild bans
            struct bans
            {
                bans(const std::string& _json, aegis::core* bot) noexcept
                {
                    from_json(nlohmann::json::parse(_json), *this);
                }

                bans(const nlohmann::json& _json, aegis::core* bot) noexcept
                {
                    from_json(_json, *this);
                }

                bans(aegis::core* bot) noexcept {}

                bans() noexcept {}

                std::vector<aegis::gateway::objects::ban>::iterator begin()
                {
                    return _bans.begin();
                }

                std::vector<aegis::gateway::objects::ban>::iterator end()
                {
                    return _bans.end();
                }

                std::vector<aegis::gateway::objects::ban>::reverse_iterator rbegin()
                {
                    return _bans.rbegin();
                }

                std::vector<aegis::gateway::objects::ban>::reverse_iterator rend()
                {
                    return _bans.rend();
                }

                std::vector<aegis::gateway::objects::ban> _bans; /**< array of bans */

            };

            /// \cond TEMPLATES
            inline void from_json(const nlohmann::json& j, bans& m)
            {
                if (j.size())
                    for (const auto& _ban : j)
                        m._bans.push_back(_ban);
            }

            inline void to_json(nlohmann::json& j, const bans& m)
            {
                if (!m._bans.empty())
                    for (const auto& _ban : m._bans)
                        j.push_back(_ban);
            }
            /// \endcond

        }

    }

}
<|endoftext|>


<commit_before>#ifndef  LIBBITCOIN_UTILITY_SUBSCRIBER_H
#define  LIBBITCOIN_UTILITY_SUBSCRIBER_H

#include <stack>

#include <bitcoin/types.hpp>
#include <bitcoin/utility/assert.hpp>

namespace libbitcoin {

template <typename... Args>
class subscriber
  : public std::enable_shared_from_this<subscriber<Args...>>
{
public:
    typedef std::function<void (Args...)> handler_type;
    typedef std::shared_ptr<subscriber<Args...>> ptr;

    subscriber(io_service::strand& async_strand)
      : strand_(async_strand)
    {
    }

    void subscribe(handler_type handle)
    {
        strand_.dispatch(
            std::bind(&subscriber<Args...>::do_subscribe,
                this->shared_from_this(), handle));
    }

    void relay(Args... params)
    {
        strand_.dispatch(
            std::bind(&subscriber<Args...>::do_relay,
                this->shared_from_this(), std::forward<Args>(params)...));
    }

private:
    typedef std::stack<handler_type> registry_stack;

    void do_subscribe(handler_type handle)
    {
        registry_.push(handle);
    }

    void do_relay(Args... params)
    {
        registry_stack notify_copy = registry_;
        registry_ = registry_stack();
        while (!notify_copy.empty())
        {
            notify_copy.top()(std::forward<Args>(params)...);
            notify_copy.pop();
        }
        BITCOIN_ASSERT(notify_copy.empty());
    }

    io_service::strand& strand_;
    registry_stack registry_;
};

// C++11 - not in g++ yet!
//template <typename Handler>
//using subscriber_ptr = std::shared_ptr<subscribe<Handler>>;

} // libbitcoin

#endif

<commit_msg>copy not forward arguments in subscriber.<commit_after>#ifndef  LIBBITCOIN_UTILITY_SUBSCRIBER_H
#define  LIBBITCOIN_UTILITY_SUBSCRIBER_H

#include <stack>

#include <bitcoin/types.hpp>
#include <bitcoin/utility/assert.hpp>

namespace libbitcoin {

template <typename... Args>
class subscriber
  : public std::enable_shared_from_this<subscriber<Args...>>
{
public:
    typedef std::function<void (Args...)> handler_type;
    typedef std::shared_ptr<subscriber<Args...>> ptr;

    subscriber(io_service::strand& async_strand)
      : strand_(async_strand)
    {
    }

    void subscribe(handler_type handle)
    {
        strand_.dispatch(
            std::bind(&subscriber<Args...>::do_subscribe,
                this->shared_from_this(), handle));
    }

    void relay(Args... params)
    {
        strand_.dispatch(
            std::bind(&subscriber<Args...>::do_relay,
                this->shared_from_this(), std::forward<Args>(params)...));
    }

private:
    typedef std::stack<handler_type> registry_stack;

    void do_subscribe(handler_type handle)
    {
        registry_.push(handle);
    }

    void do_relay(Args... params)
    {
        registry_stack notify_copy = registry_;
        registry_ = registry_stack();
        while (!notify_copy.empty())
        {
            notify_copy.top()(params...);
            notify_copy.pop();
        }
        BITCOIN_ASSERT(notify_copy.empty());
    }

    io_service::strand& strand_;
    registry_stack registry_;
};

// C++11 - not in g++ yet!
//template <typename Handler>
//using subscriber_ptr = std::shared_ptr<subscribe<Handler>>;

} // libbitcoin

#endif

<|endoftext|>


<commit_before>/*
Copyright (c) <2014>, <BenHJ>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/

// an implementation of XTEA

#ifndef BFS_CIPHER_XTEA_BYTE_TRANSFORMER_HPP__
#define BFS_CIPHER_XTEA_BYTE_TRANSFORMER_HPP__

#include "cipher/IByteTransformer.hpp"

namespace bfs { namespace cipher
{

    namespace detail
    {
        // the xtea encipher algorithm as found on wikipedia
        void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4])
        {
            unsigned int i;
            uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
            for (i=0; i < num_rounds; i++) {
                v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + key[sum & 3]);
                sum += delta;
                v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + key[(sum>>11) & 3]);
            }
            v[0]=v0; v[1]=v1;
        }

        // the xtea encipher algorithm as found on wikipedia
        void decipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4])
        {
            unsigned int i;
            uint32_t v0=v[0], v1=v[1], delta=0x9E3779B9, sum=delta*num_rounds;
            for (i=0; i < num_rounds; i++) {
                v1 -= ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + key[(sum>>11) & 3]);
                sum -= delta;
                v0 -= ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + key[sum & 3]);
            }
            v[0]=v0; v[1]=v1;
        }

        // helper code found here:
        // http://codereview.stackexchange.com/questions/2050/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data
        void convertBytesAndEncipher(unsigned int num_rounds, unsigned char * buffer, uint32_t const key[4])
        {
            uint32_t datablock[2];

            datablock[0] = (buffer[0] << 24) | (buffer[1] << 16)  | (buffer[2] << 8) | (buffer[3]);
            datablock[1] = (buffer[4] << 24) | (buffer[5] << 16)  | (buffer[6] << 8) | (buffer[7]);

            encipher(num_rounds, datablock, key);

            buffer[0] = static_cast<unsigned char>((datablock[0] >> 24) & 0xFF);
            buffer[1] = static_cast<unsigned char>((datablock[0] >> 16) & 0xFF);
            buffer[2] = static_cast<unsigned char>((datablock[0] >> 8) & 0xFF);
            buffer[3] = static_cast<unsigned char>((datablock[0]) & 0xFF);
            buffer[4] = static_cast<unsigned char>((datablock[1] >> 24) & 0xFF);
            buffer[5] = static_cast<unsigned char>((datablock[1] >> 16) & 0xFF);
            buffer[6] = static_cast<unsigned char>((datablock[1] >> 8) & 0xFF);
            buffer[7] = static_cast<unsigned char>((datablock[1]) & 0xFF);
        }
    }

    class XTEAByteTransformer : public IByteTransformer
    {
      public:
        explicit XTEAByteTransformer(std::string const &password)
            : IByteTransformer(password)
        {

        }

        ~XTEAByteTransformer()
        {

        }

      private:

        XTEAByteTransformer(); // not required

        void doTransform(char *in, char *out, std::ios_base::streamoff startPosition, long length,
                         bool encrypt) const
        {

        }

      private:
        long m_key[256];
    };

}
}

#endif // BFS_CIPHER_BASIC_TRANSFORMER_CIPHER_HPP__
<commit_msg>Bare bones of xtea implementation finished<commit_after>/*
Copyright (c) <2014>, <BenHJ>
All rights reserved.

Redistribution and use in source and binary forms, with or without
modification, are permitted provided that the following conditions are met:

1. Redistributions of source code must retain the above copyright notice, this
   list of conditions and the following disclaimer.
2. Redistributions in binary form must reproduce the above copyright notice,
   this list of conditions and the following disclaimer in the documentation
   and/or other materials provided with the distribution.

THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND
ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED
WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE
DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE FOR
ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES
(INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES;
LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND
ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT
(INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS
SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.

The views and conclusions contained in the software and documentation are those
of the authors and should not be interpreted as representing official policies,
either expressed or implied, of the FreeBSD Project.
*/

// an implementation of XTEA

#ifndef BFS_CIPHER_XTEA_BYTE_TRANSFORMER_HPP__
#define BFS_CIPHER_XTEA_BYTE_TRANSFORMER_HPP__

#include "cipher/IByteTransformer.hpp"

namespace bfs { namespace cipher
{

    namespace detail
    {
        // the xtea encipher algorithm as found on wikipedia
        void encipher(unsigned int num_rounds, uint32_t v[2], uint32_t const key[4])
        {
            unsigned int i;
            uint32_t v0=v[0], v1=v[1], sum=0, delta=0x9E3779B9;
            for (i=0; i < num_rounds; i++) {
                v0 += ((v1 << 4 ^ v1 >> 5) + v1) ^ (sum + key[sum & 3]);
                sum += delta;
                v1 += ((v0 << 4 ^ v0 >> 5) + v0) ^ (sum + key[(sum>>11) & 3]);
            }
            v[0]=v0; v[1]=v1;
        }

        // helper code found here:
        // http://codereview.stackexchange.com/questions/2050/codereview-tiny-encryption-algorithm-for-arbitrary-sized-data
        void convertBytesAndEncipher(unsigned int num_rounds, unsigned char * buffer, uint32_t const key[4])
        {
            uint32_t datablock[2];

            datablock[0] = (buffer[0] << 24) | (buffer[1] << 16)  | (buffer[2] << 8) | (buffer[3]);
            datablock[1] = (buffer[4] << 24) | (buffer[5] << 16)  | (buffer[6] << 8) | (buffer[7]);

            encipher(num_rounds, datablock, key);

            buffer[0] = static_cast<unsigned char>((datablock[0] >> 24) & 0xFF);
            buffer[1] = static_cast<unsigned char>((datablock[0] >> 16) & 0xFF);
            buffer[2] = static_cast<unsigned char>((datablock[0] >> 8) & 0xFF);
            buffer[3] = static_cast<unsigned char>((datablock[0]) & 0xFF);
            buffer[4] = static_cast<unsigned char>((datablock[1] >> 24) & 0xFF);
            buffer[5] = static_cast<unsigned char>((datablock[1] >> 16) & 0xFF);
            buffer[6] = static_cast<unsigned char>((datablock[1] >> 8) & 0xFF);
            buffer[7] = static_cast<unsigned char>((datablock[1]) & 0xFF);
        }
    }

    class XTEAByteTransformer : public IByteTransformer
    {
      public:
        explicit XTEAByteTransformer(std::string const &password)
            : IByteTransformer(password)
        {

        }

        ~XTEAByteTransformer()
        {

        }

      private:

        XTEAByteTransformer(); // not required

        void doTransform(char *in, char *out, std::ios_base::streamoff startPosition, long length,
                         bool encrypt) const
        {

            // how many blocks required? defaults to 1, if length greater
            // than 8 bytes then more blocks are needed
            long blocksRequired = 0;
            if(length > 8) {
                long remainder = length % 8;
                long roundedDown = length - remainder;
                blocksRequired += (roundedDown / 8);

                long c = 0;
                for(long i = 0;i < blocksRequired; ++i) {
                    uint8_t cipherStream[8];
                    for(int j = 0; j < 8; ++j) {
                        cipherStream[j] = startPosition + c;
                        ++c;
                    }
                    c -= 8;
                    // todo: encipher here!
                    // now xor plain with key stream
                    for(int j = 0; j < 8; ++j) {
                        out[c] = in[c] ^ cipherStream[j];
                        ++c;
                    }
                }

                if(remainder > 0) {

                    uint8_t cipherStream[8];
                    for(int j = 0; j < 8; ++j) {
                        cipherStream[j] = startPosition + c;
                        ++c;
                    }

                    c -= 8;

                    // todo: encipher here!

                    // xor rest of stream
                    for(int j = 0; j < remainder; ++j) {
                        out[c] = in[c] ^ cipherStream[j];
                        ++c;
                    }

                }
            } else {
                uint8_t cipherStream[8];
                for(int j = 0; j < 8; ++j) {
                    cipherStream[j] = startPosition + j;
                }

                // todo: encipher here!

                // xor rest of stream
                for(int j = 0; j < length; ++j) {
                    out[j] = in[j] ^ cipherStream[j];
                }
            }
        }

      private:
        long m_key[256];
    };

}
}

#endif // BFS_CIPHER_BASIC_TRANSFORMER_CIPHER_HPP__
<|endoftext|>


<commit_before>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-corbaserver.
// hpp-corbaserver is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-corbaserver is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-corbaserver. If not, see <http://www.gnu.org/licenses/>.

#ifndef HPP_CORBASERVER_CONVERSIONS_HH
#define HPP_CORBASERVER_CONVERSIONS_HH

# include <hpp/util/exception-factory.hh>

# include <hpp/corbaserver/fwd.hh>
# include <hpp/core/parameter.hh>
# include <hpp/common-idl.hh>

namespace hpp {
  namespace corbaServer {
    typedef Eigen::Matrix<CORBA::Long, Eigen::Dynamic, Eigen::Dynamic> IntMatrix_t;

    void toTransform3f (const Transform_ in, Transform3f& out);

    Transform3f toTransform3f (const Transform_ in);

    std::vector<Transform3f> toTransform3f (const TransformSeq in);

    void toHppTransform (const Transform3f& in, Transform_ out);

    Transform__slice* toHppTransform (const Transform3f& in);

    floatSeq* vectorToFloatSeq (core::vectorIn_t input);

    void vectorToFloatSeq (core::vectorIn_t input, floatSeq& output);

    inline floatSeq* vectorToFloatSeq (core::ConfigurationPtr_t input)
    {
      if (!input) return NULL;
      return vectorToFloatSeq (*input);
    }

    /// Returns a sequence of the rows of the input matrix.
    // Return [ [input.row(0)], [input.row(1)], ...]
    floatSeqSeq* matrixToFloatSeqSeq (core::matrixIn_t input);

    intSeqSeq* matrixToIntSeqSeq (Eigen::Ref<const IntMatrix_t > input);

    vector3_t floatSeqToVector3 (const floatSeq& dofArray);

    vector_t floatSeqToVector (const floatSeq& dofArray, const size_type expectedSize = -1);

    Configuration_t floatSeqToConfig (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized);

    ConfigurationPtr_t floatSeqToConfigPtr (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized);

    core::matrix_t floatSeqSeqToMatrix (const floatSeqSeq& input, const size_type expectedRows = -1, const size_type expectedCols = -1);

    IntMatrix_t intSeqSeqToMatrix (const intSeqSeq& input, const size_type expectedRows = -1, const size_type expectedCols = -1);

    std::vector<bool> boolSeqToVector (const hpp::boolSeq& mask,
                                       unsigned int length = 3);

    inline char* c_str (const std::string& in)
    {
      char* out = new char[in.length()+1];
      strcpy (out, in.c_str());
      return out;
    }

    template <typename InputIt> inline Names_t* toNames_t (InputIt begin, InputIt end)
    {
      std::size_t len = std::distance (begin, end);
      char** nameList = Names_t::allocbuf((CORBA::ULong) len);
      Names_t *ret = new Names_t ((CORBA::ULong) len, (CORBA::ULong) len, nameList);

      std::size_t i = 0;
      while (begin != end) {
        nameList[i] = c_str (*begin);
        ++begin;
        ++i;
      }
      return ret;
    }

    template <typename Iterable> inline Names_t* toNames_t (const Iterable& iterable)
    {
      return toNames_t(iterable.begin(), iterable.end());
    }

    template <typename InputIt> inline intSeq* toIntSeq (InputIt begin, InputIt end)
    {
      std::size_t len = std::distance (begin, end);
      intSeq* indexes = new intSeq ();
      indexes->length ((CORBA::ULong) len);

      std::size_t i = 0;
      while (begin != end) {
        (*indexes)[i] = *begin;
        ++begin;
        ++i;
      }
      return indexes;
    }

    template <typename InputIt> inline boolSeq* toBoolSeq (InputIt begin, InputIt end)
    {
      std::size_t len = std::distance (begin, end);
      boolSeq* indexes = new boolSeq ();
      indexes->length ((CORBA::ULong) len);

      std::size_t i = 0;
      while (begin != end) {
        (*indexes)[(CORBA::ULong)i] = *begin;
        ++begin;
        ++i;
      }
      return indexes;
    }

    template <typename OutputType> inline OutputType toStrings (const Names_t& names)
    {
      OutputType ret;
      for (CORBA::ULong i = 0; i < names.length(); ++i)
        ret.push_back (std::string(names[i]));
      return ret;
    }

    /// Convert CORBA comparison types to C++ comparison type.
    constraints::ComparisonTypes_t convertComparison (ComparisonTypes_t comp);

    /// Convert C++ comparison type to CORBA comparison types.
    ComparisonTypes_t* convertComparison (constraints::ComparisonTypes_t comp);

    core::Parameter toParameter (const CORBA::Any& any);

    CORBA::Any toCorbaAny (const core::Parameter& parameter);

    inline CORBA::Any* toCorbaAnyPtr (const core::Parameter& parameter)
    {
      CORBA::Any* ap = new CORBA::Any;
      *ap = toCorbaAny(parameter);
      return ap;
    }

  } // namespace corbaServer
} // namespace hpp

#endif // HPP_CORBASERVER_CONVERSIONS_HH
<commit_msg>disambiguate ComparisonTypes_t<commit_after>// Copyright (c) 2016, Joseph Mirabel
// Authors: Joseph Mirabel (joseph.mirabel@laas.fr)
//
// This file is part of hpp-corbaserver.
// hpp-corbaserver is free software: you can redistribute it
// and/or modify it under the terms of the GNU Lesser General Public
// License as published by the Free Software Foundation, either version
// 3 of the License, or (at your option) any later version.
//
// hpp-corbaserver is distributed in the hope that it will be
// useful, but WITHOUT ANY WARRANTY; without even the implied warranty
// of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// General Lesser Public License for more details.  You should have
// received a copy of the GNU Lesser General Public License along with
// hpp-corbaserver. If not, see <http://www.gnu.org/licenses/>.

#ifndef HPP_CORBASERVER_CONVERSIONS_HH
#define HPP_CORBASERVER_CONVERSIONS_HH

# include <hpp/util/exception-factory.hh>

# include <hpp/corbaserver/fwd.hh>
# include <hpp/core/parameter.hh>
# include <hpp/common-idl.hh>

namespace hpp {
  namespace corbaServer {
    typedef Eigen::Matrix<CORBA::Long, Eigen::Dynamic, Eigen::Dynamic> IntMatrix_t;

    void toTransform3f (const Transform_ in, Transform3f& out);

    Transform3f toTransform3f (const Transform_ in);

    std::vector<Transform3f> toTransform3f (const TransformSeq in);

    void toHppTransform (const Transform3f& in, Transform_ out);

    Transform__slice* toHppTransform (const Transform3f& in);

    floatSeq* vectorToFloatSeq (core::vectorIn_t input);

    void vectorToFloatSeq (core::vectorIn_t input, floatSeq& output);

    inline floatSeq* vectorToFloatSeq (core::ConfigurationPtr_t input)
    {
      if (!input) return NULL;
      return vectorToFloatSeq (*input);
    }

    /// Returns a sequence of the rows of the input matrix.
    // Return [ [input.row(0)], [input.row(1)], ...]
    floatSeqSeq* matrixToFloatSeqSeq (core::matrixIn_t input);

    intSeqSeq* matrixToIntSeqSeq (Eigen::Ref<const IntMatrix_t > input);

    vector3_t floatSeqToVector3 (const floatSeq& dofArray);

    vector_t floatSeqToVector (const floatSeq& dofArray, const size_type expectedSize = -1);

    Configuration_t floatSeqToConfig (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized);

    ConfigurationPtr_t floatSeqToConfigPtr (const DevicePtr_t& robot, const floatSeq& dofArray, bool throwIfNotNormalized);

    core::matrix_t floatSeqSeqToMatrix (const floatSeqSeq& input, const size_type expectedRows = -1, const size_type expectedCols = -1);

    IntMatrix_t intSeqSeqToMatrix (const intSeqSeq& input, const size_type expectedRows = -1, const size_type expectedCols = -1);

    std::vector<bool> boolSeqToVector (const hpp::boolSeq& mask,
                                       unsigned int length = 3);

    inline char* c_str (const std::string& in)
    {
      char* out = new char[in.length()+1];
      strcpy (out, in.c_str());
      return out;
    }

    template <typename InputIt> inline Names_t* toNames_t (InputIt begin, InputIt end)
    {
      std::size_t len = std::distance (begin, end);
      char** nameList = Names_t::allocbuf((CORBA::ULong) len);
      Names_t *ret = new Names_t ((CORBA::ULong) len, (CORBA::ULong) len, nameList);

      std::size_t i = 0;
      while (begin != end) {
        nameList[i] = c_str (*begin);
        ++begin;
        ++i;
      }
      return ret;
    }

    template <typename Iterable> inline Names_t* toNames_t (const Iterable& iterable)
    {
      return toNames_t(iterable.begin(), iterable.end());
    }

    template <typename InputIt> inline intSeq* toIntSeq (InputIt begin, InputIt end)
    {
      std::size_t len = std::distance (begin, end);
      intSeq* indexes = new intSeq ();
      indexes->length ((CORBA::ULong) len);

      std::size_t i = 0;
      while (begin != end) {
        (*indexes)[i] = *begin;
        ++begin;
        ++i;
      }
      return indexes;
    }

    template <typename InputIt> inline boolSeq* toBoolSeq (InputIt begin, InputIt end)
    {
      std::size_t len = std::distance (begin, end);
      boolSeq* indexes = new boolSeq ();
      indexes->length ((CORBA::ULong) len);

      std::size_t i = 0;
      while (begin != end) {
        (*indexes)[(CORBA::ULong)i] = *begin;
        ++begin;
        ++i;
      }
      return indexes;
    }

    template <typename OutputType> inline OutputType toStrings (const Names_t& names)
    {
      OutputType ret;
      for (CORBA::ULong i = 0; i < names.length(); ++i)
        ret.push_back (std::string(names[i]));
      return ret;
    }

    /// Convert CORBA comparison types to C++ comparison type.
    constraints::ComparisonTypes_t convertComparison (hpp::ComparisonTypes_t comp);

    /// Convert C++ comparison type to CORBA comparison types.
    hpp::ComparisonTypes_t* convertComparison (constraints::ComparisonTypes_t comp);

    core::Parameter toParameter (const CORBA::Any& any);

    CORBA::Any toCorbaAny (const core::Parameter& parameter);

    inline CORBA::Any* toCorbaAnyPtr (const core::Parameter& parameter)
    {
      CORBA::Any* ap = new CORBA::Any;
      *ap = toCorbaAny(parameter);
      return ap;
    }

  } // namespace corbaServer
} // namespace hpp

#endif // HPP_CORBASERVER_CONVERSIONS_HH
<|endoftext|>


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

#ifndef INCLUDED_DRIVER_SOCI_COMMON_HPP
#define INCLUDED_DRIVER_SOCI_COMMON_HPP

#ifdef PDAL_HAVE_SOCI
#include <boost-optional.h>
#include <boost-tuple.h>
#include <boost-fusion.h>
#include <boost-gregorian-date.h>
#include <soci/soci.h>
#include <soci/sqlite3/soci-sqlite3.h>
#include <soci/error.h>
#include <soci/use.h>
#endif

#include <pdal/pdal_error.hpp>
#include <pdal/Options.hpp>

namespace pdal
{
namespace drivers
{
namespace sqlite
{

    class sqlite_driver_error : public pdal_error
    {
    public:
        sqlite_driver_error(std::string const& msg)
            : pdal_error(msg)
        {}
    };

    class connection_failed : public sqlite_driver_error
    {
    public:
        connection_failed(std::string const& msg)
            : sqlite_driver_error(msg)
        {}
    };

    class buffer_too_small : public sqlite_driver_error
    {
    public:
        buffer_too_small(std::string const& msg)
            : sqlite_driver_error(msg)
        {}
    };

    enum QueryType
    {
        QUERY_CLOUD = 0,
        QUERY_BLOCKS_PLUS_CLOUD_VIEW,
        QUERY_UNKNOWN = 512
    };

}
}
} // namespace pdal::driver::soci

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

#ifndef INCLUDED_DRIVER_SOCI_COMMON_HPP
#define INCLUDED_DRIVER_SOCI_COMMON_HPP

#ifdef PDAL_HAVE_SOCI
#include <soci/soci.h>
#include <soci/sqlite3/soci-sqlite3.h>
#include <soci/error.h>
#include <soci/use.h>
#endif

#include <pdal/pdal_error.hpp>
#include <pdal/Options.hpp>

namespace pdal
{
namespace drivers
{
namespace sqlite
{

    class sqlite_driver_error : public pdal_error
    {
    public:
        sqlite_driver_error(std::string const& msg)
            : pdal_error(msg)
        {}
    };

    class connection_failed : public sqlite_driver_error
    {
    public:
        connection_failed(std::string const& msg)
            : sqlite_driver_error(msg)
        {}
    };

    class buffer_too_small : public sqlite_driver_error
    {
    public:
        buffer_too_small(std::string const& msg)
            : sqlite_driver_error(msg)
        {}
    };

    enum QueryType
    {
        QUERY_CLOUD = 0,
        QUERY_BLOCKS_PLUS_CLOUD_VIEW,
        QUERY_UNKNOWN = 512
    };

}
}
} // namespace pdal::driver::soci

#endif
<|endoftext|>


<commit_before>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//
// xx
// xx
// xx
// xx
// xx
//
//  Xianguo Lu
//  lu@physi.uni-heidelberg.de
//  Xianguo.Lu@cern.ch
//
//
#include "THnBase.h"
#include "THnSparse.h"
#include "TCollection.h"

#include "AliTRDdEdxBaseUtils.h"
#include "AliTRDdEdxCalibHistArray.h"

ClassImp(AliTRDdEdxCalibHistArray);

AliTRDdEdxCalibHistArray::AliTRDdEdxCalibHistArray(const Bool_t kNoInv):
  TObjArray(kNoInv ? 4: 8)
{
  //
  //constructor
  //
  SetName(GetArrayName());
  SetOwner(kTRUE);

  const Int_t    nbin[2]={AliTRDdEdxBaseUtils::NTRDtimebin(), 11250};
  const Double_t xmin[2]={0,       0};
  const Double_t xmax[2]={nbin[0], 20};

  for(Int_t iter=0; iter<GetSize(); iter++){
    THnBase *hi = new THnSparseS(GetNameAt(iter), "", 2, nbin, xmin, xmax);
    AddAt(hi, iter);
  }
}

AliTRDdEdxCalibHistArray::AliTRDdEdxCalibHistArray(const AliTRDdEdxCalibHistArray &obj):
  TObjArray(obj)
{
  //
  //copy constructor
  //
}

AliTRDdEdxCalibHistArray & AliTRDdEdxCalibHistArray::operator=(const AliTRDdEdxCalibHistArray &obj)
{
  //
  //assignment operator
  //

  if(&obj == this) return *this;

  TObjArray::operator=(obj);

  return *this;
}

Long64_t AliTRDdEdxCalibHistArray::Merge(const TCollection* list)
{
  //
  // Merge list of objects (needed by PROOF)
  //

  if(!list)
    return 0;

  if(list->IsEmpty())
    return 1;

  TIterator* iter = list->MakeIterator();
  TObject* obj = 0;

  Int_t count=0;
  while((obj = iter->Next()) != 0)
    {
      AliTRDdEdxCalibHistArray * entry = dynamic_cast<AliTRDdEdxCalibHistArray*>(obj);
      if (entry == 0) continue;

      if(GetSize()!= entry->GetSize()){
        printf("AliTRDdEdxCalibHistArray::Merge GetSize()!= entry->GetSize() %d %d\n", GetSize(), entry->GetSize()); exit(1);
      }

      for(Int_t ii=0; ii<GetSize(); ii++){
        THnBase *h0 = (THnBase*) At(ii);
        THnBase *h1 = (THnBase*) entry->At(ii);
        h0->Add(h1);
      }

      count++;
    }

  return count;

}
<commit_msg>Change THnSparseS to THnSparseF (Xianguo)<commit_after>/**************************************************************************
 * Copyright(c) 1998-1999, ALICE Experiment at CERN, All rights reserved. *
 *                                                                        *
 * Author: The ALICE Off-line Project.                                    *
 * Contributors are mentioned in the code where appropriate.              *
 *                                                                        *
 * Permission to use, copy, modify and distribute this software and its   *
 * documentation strictly for non-commercial purposes is hereby granted   *
 * without fee, provided that the above copyright notice appears in all   *
 * copies and that both the copyright notice and this permission notice   *
 * appear in the supporting documentation. The authors make no claims     *
 * about the suitability of this software for any purpose. It is          *
 * provided "as is" without express or implied warranty.                  *
 **************************************************************************/

//
// xx
// xx
// xx
// xx
// xx
//
//  Xianguo Lu
//  lu@physi.uni-heidelberg.de
//  Xianguo.Lu@cern.ch
//
//
#include "THnBase.h"
#include "THnSparse.h"
#include "TCollection.h"

#include "AliTRDdEdxBaseUtils.h"
#include "AliTRDdEdxCalibHistArray.h"

ClassImp(AliTRDdEdxCalibHistArray);

AliTRDdEdxCalibHistArray::AliTRDdEdxCalibHistArray(const Bool_t kNoInv):
  TObjArray(kNoInv ? 4: 8)
{
  //
  //constructor
  //
  SetName(GetArrayName());
  SetOwner(kTRUE);

  const Int_t    nbin[2]={AliTRDdEdxBaseUtils::NTRDtimebin(), 11250};
  const Double_t xmin[2]={0,       0};
  const Double_t xmax[2]={nbin[0], 20};

  for(Int_t iter=0; iter<GetSize(); iter++){
    THnBase *hi = new THnSparseF(GetNameAt(iter), "", 2, nbin, xmin, xmax);
    AddAt(hi, iter);
  }
}

AliTRDdEdxCalibHistArray::AliTRDdEdxCalibHistArray(const AliTRDdEdxCalibHistArray &obj):
  TObjArray(obj)
{
  //
  //copy constructor
  //
}

AliTRDdEdxCalibHistArray & AliTRDdEdxCalibHistArray::operator=(const AliTRDdEdxCalibHistArray &obj)
{
  //
  //assignment operator
  //

  if(&obj == this) return *this;

  TObjArray::operator=(obj);

  return *this;
}

Long64_t AliTRDdEdxCalibHistArray::Merge(const TCollection* list)
{
  //
  // Merge list of objects (needed by PROOF)
  //

  if(!list)
    return 0;

  if(list->IsEmpty())
    return 1;

  TIterator* iter = list->MakeIterator();
  TObject* obj = 0;

  Int_t count=0;
  while((obj = iter->Next()) != 0)
    {
      AliTRDdEdxCalibHistArray * entry = dynamic_cast<AliTRDdEdxCalibHistArray*>(obj);
      if (entry == 0) continue;

      if(GetSize()!= entry->GetSize()){
        printf("AliTRDdEdxCalibHistArray::Merge GetSize()!= entry->GetSize() %d %d\n", GetSize(), entry->GetSize()); exit(1);
      }

      for(Int_t ii=0; ii<GetSize(); ii++){
        THnBase *h0 = (THnBase*) At(ii);
        THnBase *h1 = (THnBase*) entry->At(ii);
        h0->Add(h1);
      }

      count++;
    }

  return count;

}
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: options.hxx,v $
 *
 *  $Revision: 1.8 $
 *
 *  last change: $Author: hr $ $Date: 2006-06-20 02:22:39 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library 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
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

#ifndef INCLUDED_CODEMAKER_OPTIONS_HXX
#define INCLUDED_CODEMAKER_OPTIONS_HXX

#include <hash_map>

#ifndef INCLUDED_CODEMAKER_GLOBAL_HXX
#include <codemaker/global.hxx>
#endif

#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
    ::rtl::OString,
    ::rtl::OString,
    HashString,
    EqualString,
    NewAlloc
> OptionMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString,
    ::rtl::OString,
    HashString,
    EqualString
> OptionMap;
#endif

class IllegalArgument
{
public:
    IllegalArgument(const ::rtl::OString& msg)
        : m_message(msg) {}

    ::rtl::OString  m_message;
};

class Options
{
public:
    Options();
    virtual ~Options();

    virtual sal_Bool initOptions(int ac, char* av[], sal_Bool bCmdFile=sal_False)
        throw( IllegalArgument ) = 0;

    virtual ::rtl::OString  prepareHelp() = 0;

    const ::rtl::OString&   getProgramName() const;
    sal_Bool                isValid(const ::rtl::OString& option);
    const ::rtl::OString    getOption(const ::rtl::OString& option)
        throw( IllegalArgument );
    const OptionMap&        getOptions();

    const ::rtl::OString    getInputFile(sal_uInt16 index)
        throw( IllegalArgument );

    const StringVector& getInputFiles();

    ::rtl::OString getExtraInputFile(sal_uInt16 index) const throw( IllegalArgument );
    inline sal_uInt16 getNumberOfExtraInputFiles() const
        { return (sal_uInt16)m_extra_input_files.size(); }
    inline const StringVector& getExtraInputFiles() const
        { return m_extra_input_files; }
protected:
    ::rtl::OString  m_program;
    StringVector    m_inputFiles;
    StringVector    m_extra_input_files;
    OptionMap       m_options;
};

#endif // INCLUDED_CODEMAKER_OPTIONS_HXX

<commit_msg>INTEGRATION: CWS changefileheader (1.8.48); FILE MERGED 2008/04/01 12:26:07 thb 1.8.48.2: #i85898# Stripping all external header guards 2008/03/31 07:22:51 rt 1.8.48.1: #i87441# Change license header to LPGL v3.<commit_after>/*************************************************************************
 *
 * DO NOT ALTER OR REMOVE COPYRIGHT NOTICES OR THIS FILE HEADER.
 *
 * Copyright 2008 by Sun Microsystems, Inc.
 *
 * OpenOffice.org - a multi-platform office productivity suite
 *
 * $RCSfile: options.hxx,v $
 * $Revision: 1.9 $
 *
 * This file is part of OpenOffice.org.
 *
 * OpenOffice.org is free software: you can redistribute it and/or modify
 * it under the terms of the GNU Lesser General Public License version 3
 * only, as published by the Free Software Foundation.
 *
 * OpenOffice.org 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 Lesser General Public License version 3 for more details
 * (a copy is included in the LICENSE file that accompanied this code).
 *
 * You should have received a copy of the GNU Lesser General Public License
 * version 3 along with OpenOffice.org.  If not, see
 * <http://www.openoffice.org/license.html>
 * for a copy of the LGPLv3 License.
 *
 ************************************************************************/

#ifndef INCLUDED_CODEMAKER_OPTIONS_HXX
#define INCLUDED_CODEMAKER_OPTIONS_HXX

#include <hash_map>
#include <codemaker/global.hxx>

#if defined( _MSC_VER ) && ( _MSC_VER < 1200 )
typedef ::std::__hash_map__
<
    ::rtl::OString,
    ::rtl::OString,
    HashString,
    EqualString,
    NewAlloc
> OptionMap;
#else
typedef ::std::hash_map
<
    ::rtl::OString,
    ::rtl::OString,
    HashString,
    EqualString
> OptionMap;
#endif

class IllegalArgument
{
public:
    IllegalArgument(const ::rtl::OString& msg)
        : m_message(msg) {}

    ::rtl::OString  m_message;
};

class Options
{
public:
    Options();
    virtual ~Options();

    virtual sal_Bool initOptions(int ac, char* av[], sal_Bool bCmdFile=sal_False)
        throw( IllegalArgument ) = 0;

    virtual ::rtl::OString  prepareHelp() = 0;

    const ::rtl::OString&   getProgramName() const;
    sal_Bool                isValid(const ::rtl::OString& option);
    const ::rtl::OString    getOption(const ::rtl::OString& option)
        throw( IllegalArgument );
    const OptionMap&        getOptions();

    const ::rtl::OString    getInputFile(sal_uInt16 index)
        throw( IllegalArgument );

    const StringVector& getInputFiles();

    ::rtl::OString getExtraInputFile(sal_uInt16 index) const throw( IllegalArgument );
    inline sal_uInt16 getNumberOfExtraInputFiles() const
        { return (sal_uInt16)m_extra_input_files.size(); }
    inline const StringVector& getExtraInputFiles() const
        { return m_extra_input_files; }
protected:
    ::rtl::OString  m_program;
    StringVector    m_inputFiles;
    StringVector    m_extra_input_files;
    OptionMap       m_options;
};

#endif // INCLUDED_CODEMAKER_OPTIONS_HXX

<|endoftext|>