text stringlengths 54 60.6k |
|---|
<commit_before>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/comparators.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/shape_util.h"
namespace tensorflow {
namespace {
class DenseBincountOp : public XlaOpKernel {
public:
explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
ctx->GetAttr("binary_output", &binary_output_);
}
private:
bool binary_output_ = false;
void Compile(XlaOpKernelContext* ctx) override {
xla::XlaOp input = ctx->Input(0);
xla::XlaOp weights = ctx->Input(2);
StatusOr<xla::Shape> weights_shape_or = ctx->builder()->GetShape(weights);
OP_REQUIRES_OK(ctx, weights_shape_or.status());
auto weights_shape = weights_shape_or.ValueOrDie();
auto weights_size = weights_shape.dimensions(0);
auto input_xla_type = ctx->input_xla_type(0);
xla::PrimitiveType dtype;
bool has_weights;
if (weights_size) {
has_weights = true;
dtype = ctx->input_xla_type(2);
} else {
has_weights = false;
dtype = input_xla_type;
}
int64_t output_size;
ctx->ConstantInputAsIntScalar("size", &output_size);
StatusOr<xla::Shape> input_shape_or = ctx->builder()->GetShape(input);
OP_REQUIRES_OK(ctx, input_shape_or.status());
auto input_shape = input_shape_or.ValueOrDie();
auto size = input_shape.dimensions(0);
auto rank = input_shape.rank();
xla::Shape output_shape = xla::ShapeUtil::MakeShape(dtype, {output_size});
xla::XlaOp idx, updates, output;
xla::ScatterDimensionNumbers scatter_dnums;
scatter_dnums.set_index_vector_dim(1);
scatter_dnums.add_inserted_window_dims(0);
scatter_dnums.add_scatter_dims_to_operand_dims(0);
auto one = xla::One(ctx->builder(), input_xla_type);
auto zero = xla::Zero(ctx->builder(), input_xla_type);
if (rank == 2) {
output_shape = xla::ShapeUtil::MakeShape(dtype, {size, output_size});
scatter_dnums.add_inserted_window_dims(1);
scatter_dnums.add_scatter_dims_to_operand_dims(1);
auto i_shape =
xla::ShapeUtil::MakeShape(input_xla_type, {input_shape.dimensions()});
auto i = xla::Iota(ctx->builder(), i_shape, 0);
i = xla::Reshape(
i, {input_shape.dimensions(0) * input_shape.dimensions(1), 1});
auto j = xla::Reshape(
input, {input_shape.dimensions(0) * input_shape.dimensions(1), 1});
std::vector<xla::XlaOp> iotas_to_concat;
iotas_to_concat.push_back(i);
iotas_to_concat.push_back(j);
idx = xla::ConcatInDim(ctx->builder(), iotas_to_concat, 1);
updates = xla::Broadcast(
one, {input_shape.dimensions(0) * input_shape.dimensions(1)});
if (has_weights) {
weights = xla::Reshape(
weights, {input_shape.dimensions(0) * input_shape.dimensions(1)});
zero = xla::Zero(ctx->builder(), dtype);
updates = weights;
}
} else {
input = xla::Reshape(input, {size, 1});
idx = xla::Reshape(input, {size, 1});
updates = xla::Broadcast(one, {size});
if (has_weights) {
updates = weights;
zero = xla::Zero(ctx->builder(), dtype);
}
}
output = xla::Broadcast(zero, {output_shape.dimensions()});
xla::XlaComputation assn_computation = [&] {
std::unique_ptr<xla::XlaBuilder> subb =
ctx->builder()->CreateSubBuilder("scatter_bincount");
xla::Shape param_shape = xla::ShapeUtil::MakeShape(dtype, {});
auto p0 = xla::Parameter(subb.get(), 0, param_shape, "p0");
auto p1 = xla::Parameter(subb.get(), 1, param_shape, "p1");
if (!binary_output_) {
xla::Add(p0, p1);
}
return subb->BuildAndNoteError();
}();
output = xla::Scatter(output, idx, updates, assn_computation, scatter_dnums,
false, false);
ctx->SetOutput(0, output);
}
};
REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"),
DenseBincountOp);
REGISTER_XLA_OP(Name("Bincount").CompileTimeConstantInput("size"),
DenseBincountOp);
} // namespace
} // namespace tensorflow
<commit_msg>Make internal compiler flags happy<commit_after>/* Copyright 2020 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/tf2xla/type_util.h"
#include "tensorflow/compiler/tf2xla/xla_helpers.h"
#include "tensorflow/compiler/tf2xla/xla_op_kernel.h"
#include "tensorflow/compiler/tf2xla/xla_op_registry.h"
#include "tensorflow/compiler/xla/client/lib/arithmetic.h"
#include "tensorflow/compiler/xla/client/lib/comparators.h"
#include "tensorflow/compiler/xla/client/lib/constants.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/shape_util.h"
namespace tensorflow {
namespace {
class DenseBincountOp : public XlaOpKernel {
public:
explicit DenseBincountOp(OpKernelConstruction* ctx) : XlaOpKernel(ctx) {
// It is optional for Bincount and required for DenseBincount
(void) ctx->GetAttr("binary_output", &binary_output_);
}
private:
bool binary_output_ = false;
void Compile(XlaOpKernelContext* ctx) override {
xla::XlaOp input = ctx->Input(0);
xla::XlaOp weights = ctx->Input(2);
StatusOr<xla::Shape> weights_shape_or = ctx->builder()->GetShape(weights);
OP_REQUIRES_OK(ctx, weights_shape_or.status());
auto weights_shape = weights_shape_or.ValueOrDie();
auto weights_size = weights_shape.dimensions(0);
auto input_xla_type = ctx->input_xla_type(0);
xla::PrimitiveType dtype;
bool has_weights;
if (weights_size) {
has_weights = true;
dtype = ctx->input_xla_type(2);
} else {
has_weights = false;
dtype = input_xla_type;
}
int64_t output_size;
OP_REQUIRES_OK(ctx, ctx->ConstantInputAsIntScalar("size", &output_size));
StatusOr<xla::Shape> input_shape_or = ctx->builder()->GetShape(input);
OP_REQUIRES_OK(ctx, input_shape_or.status());
auto input_shape = input_shape_or.ValueOrDie();
auto size = input_shape.dimensions(0);
auto rank = input_shape.rank();
xla::Shape output_shape = xla::ShapeUtil::MakeShape(dtype, {output_size});
xla::XlaOp idx, updates, output;
xla::ScatterDimensionNumbers scatter_dnums;
scatter_dnums.set_index_vector_dim(1);
scatter_dnums.add_inserted_window_dims(0);
scatter_dnums.add_scatter_dims_to_operand_dims(0);
auto one = xla::One(ctx->builder(), input_xla_type);
auto zero = xla::Zero(ctx->builder(), input_xla_type);
if (rank == 2) {
output_shape = xla::ShapeUtil::MakeShape(dtype, {size, output_size});
scatter_dnums.add_inserted_window_dims(1);
scatter_dnums.add_scatter_dims_to_operand_dims(1);
auto i_shape =
xla::ShapeUtil::MakeShape(input_xla_type, {input_shape.dimensions()});
auto i = xla::Iota(ctx->builder(), i_shape, 0);
i = xla::Reshape(
i, {input_shape.dimensions(0) * input_shape.dimensions(1), 1});
auto j = xla::Reshape(
input, {input_shape.dimensions(0) * input_shape.dimensions(1), 1});
std::vector<xla::XlaOp> iotas_to_concat;
iotas_to_concat.push_back(i);
iotas_to_concat.push_back(j);
idx = xla::ConcatInDim(ctx->builder(), iotas_to_concat, 1);
updates = xla::Broadcast(
one, {input_shape.dimensions(0) * input_shape.dimensions(1)});
if (has_weights) {
weights = xla::Reshape(
weights, {input_shape.dimensions(0) * input_shape.dimensions(1)});
zero = xla::Zero(ctx->builder(), dtype);
updates = weights;
}
} else {
input = xla::Reshape(input, {size, 1});
idx = xla::Reshape(input, {size, 1});
updates = xla::Broadcast(one, {size});
if (has_weights) {
updates = weights;
zero = xla::Zero(ctx->builder(), dtype);
}
}
output = xla::Broadcast(zero, {output_shape.dimensions()});
xla::XlaComputation assn_computation = [&] {
std::unique_ptr<xla::XlaBuilder> subb =
ctx->builder()->CreateSubBuilder("scatter_bincount");
xla::Shape param_shape = xla::ShapeUtil::MakeShape(dtype, {});
auto p0 = xla::Parameter(subb.get(), 0, param_shape, "p0");
auto p1 = xla::Parameter(subb.get(), 1, param_shape, "p1");
if (!binary_output_) {
xla::Add(p0, p1);
}
return subb->BuildAndNoteError();
}();
output = xla::Scatter(output, idx, updates, assn_computation, scatter_dnums,
false, false);
ctx->SetOutput(0, output);
}
};
REGISTER_XLA_OP(Name("DenseBincount").CompileTimeConstantInput("size"),
DenseBincountOp);
REGISTER_XLA_OP(Name("Bincount").CompileTimeConstantInput("size"),
DenseBincountOp);
} // namespace
} // namespace tensorflow
<|endoftext|> |
<commit_before>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/client/lib/approx_topk.h"
#include <string>
#include "absl/numeric/bits.h"
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/shape.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
const uint64_t kTpuTiling = 128;
namespace xla {
// Converts a comparator to a combiner computation that can be fed to reduce or
// partial reduce ops.
XlaComputation BuildReductionComputation(
XlaBuilder* builder, absl::Span<const PrimitiveType> op_types,
const XlaComputation& comparator) {
auto num_operands = op_types.size();
std::vector<XlaOp> lhs_params;
std::vector<XlaOp> rhs_params;
int64_t param_number = 0;
lhs_params.reserve(num_operands);
rhs_params.reserve(num_operands);
auto reduction_builder = builder->CreateSubBuilder("ReductionFn");
for (const auto& op_type : op_types) {
lhs_params.push_back(Parameter(reduction_builder.get(), param_number,
ShapeUtil::MakeScalarShape(op_type),
absl::StrFormat("lhs.%d", param_number)));
param_number++;
}
for (const auto& op_type : op_types) {
rhs_params.push_back(Parameter(reduction_builder.get(), param_number,
ShapeUtil::MakeScalarShape(op_type),
absl::StrFormat("rhs.%d", param_number)));
param_number++;
}
std::vector<XlaOp> comparator_args;
comparator_args.reserve(num_operands * 2);
for (int i = 0; i < num_operands; ++i) {
comparator_args.push_back(lhs_params[i]);
comparator_args.push_back(rhs_params[i]);
}
auto pred = Call(reduction_builder.get(), comparator, comparator_args);
std::vector<XlaOp> results;
results.reserve(num_operands);
for (int i = 0; i < num_operands; ++i) {
results.push_back(Select(pred, lhs_params[i], rhs_params[i]));
}
Tuple(reduction_builder.get(), results);
return reduction_builder->BuildAndNoteError();
}
XlaOp SortAndSliceBuilder(XlaBuilder* builder, absl::Span<const XlaOp> operands,
int64_t top_k, int64_t reduction_dim,
const XlaComputation& comparator) {
auto operands_shapes = builder->GetOperandShapes(operands).ValueOrDie();
int64_t rank = operands_shapes[0].rank();
int64_t num_operands = operands.size();
auto sorted_results = Sort(operands, comparator, reduction_dim);
std::vector<int64_t> slice_start_indices(rank, 0);
std::vector<int64_t> slice_limit_indices;
std::vector<int64_t> slice_strides(rank, 1);
slice_limit_indices.insert(slice_limit_indices.begin(),
operands_shapes[0].dimensions().begin(),
operands_shapes[0].dimensions().end());
std::vector<XlaOp> sliced_results;
sliced_results.reserve(num_operands);
for (int i = 0; i < num_operands; ++i) {
sliced_results.push_back(Slice(GetTupleElement(sorted_results, i),
slice_start_indices, slice_limit_indices,
slice_strides));
}
return Tuple(builder, sliced_results);
}
XlaOp ApproxTopK(XlaBuilder* builder, absl::Span<const XlaOp> operands,
absl::Span<const XlaOp> init_values, int64_t top_k,
int64_t reduction_dim, const XlaComputation& comparator,
float recall_target, bool aggregate_to_topk) {
// Validates shapes and ranks
if (operands.size() != init_values.size()) {
return builder->ReportError(
InvalidArgument("operands and init_values size mismatch: %d vs %d",
operands.size(), init_values.size()));
}
auto num_operands = operands.size();
auto operands_shapes = builder->GetOperandShapes(operands).ValueOrDie();
auto init_values_shapes = builder->GetOperandShapes(init_values).ValueOrDie();
std::vector<PrimitiveType> op_types;
for (int i = 0; i < num_operands; ++i) {
const auto& op_shape = operands_shapes[i];
const auto& init_shape = init_values_shapes[i];
if (op_shape.rank() < 2) {
return builder->ReportError(
InvalidArgument("Only rank 2+ operands are supported for now"));
}
if (!ShapeUtil::CompatibleIgnoringElementType(operands_shapes[0],
op_shape)) {
return builder->ReportError(InvalidArgument(
"operands shape mismatch: %s vs %s", operands_shapes[0].DebugString(),
op_shape.DebugString()));
}
if (op_shape.element_type() != init_shape.element_type()) {
return builder->ReportError(
InvalidArgument("operands type mismatch: %s vs %s",
op_shape.DebugString(), init_shape.DebugString()));
}
op_types.push_back(op_shape.element_type());
}
if (reduction_dim < 0 || reduction_dim >= operands_shapes[0].rank()) {
return builder->ReportError(InvalidArgument(
"reduction_dim should range in [0,%d)", operands_shapes[0].rank()));
}
auto reduction_computation =
BuildReductionComputation(builder, op_types, comparator);
// Fallback to variadic reduce when top_k == 1.
// TODO(fchern): Approx-topk followed by variadic reduce might run faster
// than running variadic reduce directly.
if (top_k == 1) {
return Reduce(builder, operands, init_values, reduction_computation,
{reduction_dim});
}
uint64_t n = operands_shapes[0].dimensions(reduction_dim);
// ApproxTopK can only reduce elements larger than kTpuTiling.
if (n <= kTpuTiling) {
if (aggregate_to_topk) {
return SortAndSliceBuilder(builder, operands, top_k, reduction_dim,
comparator);
}
return Tuple(builder, operands);
}
// Given number of data points N, K for top-k elements, and W for the size of
// the reduce window, let M = Ceil(N / W) be the number of windows. The
// expected number of top-k elements that doesn't collide in windows is
//
// K * ((M - 1) / M)^{K - 1}
//
// The recall of is the expected number of top-k elements divided by K
//
// recall = ((M - 1) / M)^{K - 1}
// = (1 - 1/M)^{K - 1}
// = (1 - 1/M)^{-M * (K - 1)/(-M)}
// ~= EXP((1 - K) / M) for large M
//
// => M = (1 - K)/LOG(recall)
if (recall_target <= 0. || recall_target > 1.0) {
return builder->ReportError(
InvalidArgument("recall_target should range in (0,1]"));
}
uint64_t m = std::min(
std::max(static_cast<uint64_t>((1.0 - top_k) / std::log(recall_target)),
kTpuTiling),
n);
uint32_t log2_reduction = absl::bit_width(n / m) - 1; // floor(n / m)
if (log2_reduction == 0) {
if (aggregate_to_topk) {
return SortAndSliceBuilder(builder, operands, top_k, reduction_dim,
comparator);
}
return Tuple(builder, operands);
}
std::vector<XlaOp> partial_reduce_args;
for (const auto& op : operands) {
partial_reduce_args.push_back(op);
}
for (const auto& op : init_values) {
partial_reduce_args.push_back(op);
}
int64_t output_reduction_size =
CeilOfRatio<int64_t>(CeilOfRatio(n, kTpuTiling), (1 << log2_reduction)) *
kTpuTiling;
std::vector<Shape> approx_output_shapes;
for (auto op_shape : operands_shapes) {
op_shape.mutable_dimensions()[reduction_dim] = output_reduction_size;
approx_output_shapes.push_back(op_shape);
}
auto approx_output_shape = ShapeUtil::MakeTupleShape(approx_output_shapes);
// PartialReduce option in JSON form
std::string partial_reduce_option =
absl::StrFormat("{\"log2_reduction\": %d, \"reduction_dim\": %d}",
log2_reduction, reduction_dim);
auto approx_topk = CustomCallWithComputation(
builder, "PartialReduce", partial_reduce_args, reduction_computation,
approx_output_shape, partial_reduce_option);
if (aggregate_to_topk) {
std::vector<XlaOp> approx_topk_results;
approx_topk_results.reserve(num_operands);
for (int i = 0; i < num_operands; ++i) {
approx_topk_results.push_back(GetTupleElement(approx_topk, i));
}
return SortAndSliceBuilder(builder, approx_topk_results, top_k,
reduction_dim, comparator);
}
return approx_topk;
}
} // namespace xla
<commit_msg>[XLA:TPU] Enable rank 1 ApproxTopK for JAX<commit_after>/* Copyright 2021 The TensorFlow Authors. All Rights Reserved.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
==============================================================================*/
#include "tensorflow/compiler/xla/client/lib/approx_topk.h"
#include <string>
#include "absl/numeric/bits.h"
#include "absl/strings/str_format.h"
#include "tensorflow/compiler/xla/client/xla_builder.h"
#include "tensorflow/compiler/xla/client/xla_computation.h"
#include "tensorflow/compiler/xla/shape.h"
#include "tensorflow/compiler/xla/shape_util.h"
#include "tensorflow/compiler/xla/util.h"
#include "tensorflow/compiler/xla/xla_data.pb.h"
// Used by rank 2+ operands
const uint64_t kTpuLaneTiling = 128;
// Used by rank 1 operands.
const uint64_t kTpuChunkTiling = 1024;
namespace xla {
// Converts a comparator to a combiner computation that can be fed to reduce or
// partial reduce ops.
XlaComputation BuildReductionComputation(
XlaBuilder* builder, absl::Span<const PrimitiveType> op_types,
const XlaComputation& comparator) {
auto num_operands = op_types.size();
std::vector<XlaOp> lhs_params;
std::vector<XlaOp> rhs_params;
int64_t param_number = 0;
lhs_params.reserve(num_operands);
rhs_params.reserve(num_operands);
auto reduction_builder = builder->CreateSubBuilder("ReductionFn");
for (const auto& op_type : op_types) {
lhs_params.push_back(Parameter(reduction_builder.get(), param_number,
ShapeUtil::MakeScalarShape(op_type),
absl::StrFormat("lhs.%d", param_number)));
param_number++;
}
for (const auto& op_type : op_types) {
rhs_params.push_back(Parameter(reduction_builder.get(), param_number,
ShapeUtil::MakeScalarShape(op_type),
absl::StrFormat("rhs.%d", param_number)));
param_number++;
}
std::vector<XlaOp> comparator_args;
comparator_args.reserve(num_operands * 2);
for (int i = 0; i < num_operands; ++i) {
comparator_args.push_back(lhs_params[i]);
comparator_args.push_back(rhs_params[i]);
}
auto pred = Call(reduction_builder.get(), comparator, comparator_args);
std::vector<XlaOp> results;
results.reserve(num_operands);
for (int i = 0; i < num_operands; ++i) {
results.push_back(Select(pred, lhs_params[i], rhs_params[i]));
}
Tuple(reduction_builder.get(), results);
return reduction_builder->BuildAndNoteError();
}
XlaOp SortAndSliceBuilder(XlaBuilder* builder, absl::Span<const XlaOp> operands,
int64_t top_k, int64_t reduction_dim,
const XlaComputation& comparator) {
auto operands_shapes = builder->GetOperandShapes(operands).ValueOrDie();
int64_t rank = operands_shapes[0].rank();
int64_t num_operands = operands.size();
auto sorted_results = Sort(operands, comparator, reduction_dim);
std::vector<int64_t> slice_start_indices(rank, 0);
std::vector<int64_t> slice_limit_indices;
std::vector<int64_t> slice_strides(rank, 1);
slice_limit_indices.insert(slice_limit_indices.begin(),
operands_shapes[0].dimensions().begin(),
operands_shapes[0].dimensions().end());
std::vector<XlaOp> sliced_results;
sliced_results.reserve(num_operands);
for (int i = 0; i < num_operands; ++i) {
sliced_results.push_back(Slice(GetTupleElement(sorted_results, i),
slice_start_indices, slice_limit_indices,
slice_strides));
}
return Tuple(builder, sliced_results);
}
XlaOp ApproxTopK(XlaBuilder* builder, absl::Span<const XlaOp> operands,
absl::Span<const XlaOp> init_values, int64_t top_k,
int64_t reduction_dim, const XlaComputation& comparator,
float recall_target, bool aggregate_to_topk) {
// Validates shapes and ranks
if (operands.size() != init_values.size()) {
return builder->ReportError(
InvalidArgument("operands and init_values size mismatch: %d vs %d",
operands.size(), init_values.size()));
}
auto num_operands = operands.size();
auto operands_shapes = builder->GetOperandShapes(operands).ValueOrDie();
auto init_values_shapes = builder->GetOperandShapes(init_values).ValueOrDie();
std::vector<PrimitiveType> op_types;
for (int i = 0; i < num_operands; ++i) {
const auto& op_shape = operands_shapes[i];
const auto& init_shape = init_values_shapes[i];
if (op_shape.rank() == 0) {
return builder->ReportError(
InvalidArgument("ApproxTopK operands must have rank 1+."));
}
if (!ShapeUtil::CompatibleIgnoringElementType(operands_shapes[0],
op_shape)) {
return builder->ReportError(InvalidArgument(
"operands shape mismatch: %s vs %s", operands_shapes[0].DebugString(),
op_shape.DebugString()));
}
if (op_shape.element_type() != init_shape.element_type()) {
return builder->ReportError(
InvalidArgument("operands type mismatch: %s vs %s",
op_shape.DebugString(), init_shape.DebugString()));
}
op_types.push_back(op_shape.element_type());
}
int64_t rank = operands_shapes[0].rank();
if (reduction_dim < 0 || reduction_dim >= rank) {
return builder->ReportError(
InvalidArgument("reduction_dim should range in [0,%d)", rank));
}
auto reduction_computation =
BuildReductionComputation(builder, op_types, comparator);
// Fallback to variadic reduce when top_k == 1.
// TODO(fchern): Approx-topk followed by variadic reduce might run faster
// than running variadic reduce directly.
if (top_k == 1) {
return Reduce(builder, operands, init_values, reduction_computation,
{reduction_dim});
}
uint64_t tpu_tiling = rank == 1 ? kTpuChunkTiling : kTpuLaneTiling;
uint64_t n = operands_shapes[0].dimensions(reduction_dim);
// ApproxTopK can only reduce elements larger than the tiling.
if (n <= tpu_tiling) {
if (aggregate_to_topk) {
return SortAndSliceBuilder(builder, operands, top_k, reduction_dim,
comparator);
}
return Tuple(builder, operands);
}
// Given number of data points N, K for top-k elements, and W for the size of
// the reduce window, let M = Ceil(N / W) be the number of windows. The
// expected number of top-k elements that doesn't collide in windows is
//
// K * ((M - 1) / M)^{K - 1}
//
// The recall of is the expected number of top-k elements divided by K
//
// recall = ((M - 1) / M)^{K - 1}
// = (1 - 1/M)^{K - 1}
// = (1 - 1/M)^{-M * (K - 1)/(-M)}
// ~= EXP((1 - K) / M) for large M
//
// => M = (1 - K)/LOG(recall)
if (recall_target <= 0. || recall_target > 1.0) {
return builder->ReportError(
InvalidArgument("recall_target should range in (0,1]"));
}
uint64_t m = std::min(
std::max(static_cast<uint64_t>((1.0 - top_k) / std::log(recall_target)),
tpu_tiling),
n);
uint32_t log2_reduction = absl::bit_width(n / m) - 1; // floor(n / m)
if (log2_reduction == 0) {
if (aggregate_to_topk) {
return SortAndSliceBuilder(builder, operands, top_k, reduction_dim,
comparator);
}
return Tuple(builder, operands);
}
std::vector<XlaOp> partial_reduce_args;
for (const auto& op : operands) {
partial_reduce_args.push_back(op);
}
for (const auto& op : init_values) {
partial_reduce_args.push_back(op);
}
int64_t output_reduction_size =
CeilOfRatio<int64_t>(CeilOfRatio(n, tpu_tiling), (1 << log2_reduction)) *
tpu_tiling;
std::vector<Shape> approx_output_shapes;
for (auto op_shape : operands_shapes) {
op_shape.mutable_dimensions()[reduction_dim] = output_reduction_size;
approx_output_shapes.push_back(op_shape);
}
auto approx_output_shape = ShapeUtil::MakeTupleShape(approx_output_shapes);
// PartialReduce option in JSON form
std::string partial_reduce_option =
absl::StrFormat("{\"log2_reduction\": %d, \"reduction_dim\": %d}",
log2_reduction, reduction_dim);
auto approx_topk = CustomCallWithComputation(
builder, "PartialReduce", partial_reduce_args, reduction_computation,
approx_output_shape, partial_reduce_option);
if (aggregate_to_topk) {
std::vector<XlaOp> approx_topk_results;
approx_topk_results.reserve(num_operands);
for (int i = 0; i < num_operands; ++i) {
approx_topk_results.push_back(GetTupleElement(approx_topk, i));
}
return SortAndSliceBuilder(builder, approx_topk_results, top_k,
reduction_dim, comparator);
}
return approx_topk;
}
} // namespace xla
<|endoftext|> |
<commit_before>#include "stdafx.h"
#include "ProcessAsUser.h"
#include "Settings.h"
#include "ErrorUtilities.h"
#include "ProcessTracker.h"
#include "Result.h"
#include "ExitCode.h"
#include "Environment.h"
#include "Trace.h"
#include "Job.h"
#include "IntegrityLevelManager.h"
class Trace;
class ProcessTracker;
Result<ExitCode> ProcessAsUser::Run(const Settings& settings, ProcessTracker& processTracker) const
{
Trace trace(settings.GetLogLevel());
trace < L"ProcessAsUser::Attempt to log a user on to the local computer";
trace < L"::LogonUser";
auto userName = settings.GetUserName().c_str();
auto domain = settings.GetDomain().c_str();
auto password = settings.GetPassword().c_str();
auto newUserSecurityTokenHandle = Handle(L"New user security token");
if (!LogonUser(
userName,
domain,
password,
LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT,
&newUserSecurityTokenHandle))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"LogonUser"));
}
trace < L"ProcessAsUser::Initialize a new security descriptor";
trace < L"::InitializeSecurityDescriptor";
SECURITY_DESCRIPTOR securityDescriptor = {};
if (!InitializeSecurityDescriptor(
&securityDescriptor,
SECURITY_DESCRIPTOR_REVISION))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"InitializeSecurityDescriptor"));
}
trace < L"::SetSecurityDescriptorDacl";
if (!SetSecurityDescriptorDacl(
&securityDescriptor,
true,
nullptr,
false))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"SetSecurityDescriptorDacl"));
}
trace < L"ProcessAsUser::Creates a new access primary token that duplicates new process's token";
auto primaryNewUserSecurityTokenHandle = Handle(L"Primary new user security token");
SECURITY_ATTRIBUTES processSecAttributes = {};
processSecAttributes.lpSecurityDescriptor = &securityDescriptor;
processSecAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
processSecAttributes.bInheritHandle = true;
trace < L"::DuplicateTokenEx";
if (!DuplicateTokenEx(
newUserSecurityTokenHandle,
0, // MAXIMUM_ALLOWED
&processSecAttributes,
SecurityImpersonation,
TokenPrimary,
&primaryNewUserSecurityTokenHandle))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"DuplicateTokenEx"));
}
SECURITY_ATTRIBUTES threadSecAttributes = {};
threadSecAttributes.lpSecurityDescriptor = nullptr;
threadSecAttributes.nLength = 0;
threadSecAttributes.bInheritHandle = false;
STARTUPINFO startupInfo = {};
trace < L"ProcessTracker::Initialize";
auto error = processTracker.Initialize(processSecAttributes, startupInfo);
if(error.HasError())
{
return Result<ExitCode>(error.GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"DuplicateTokenEx"));
}
trace < L"::LoadUserProfile";
PROFILEINFO profileInfo = {};
profileInfo.dwSize = sizeof(PROFILEINFO);
profileInfo.lpUserName = const_cast<LPWSTR>(userName);
if (!LoadUserProfile(primaryNewUserSecurityTokenHandle, &profileInfo))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"LoadUserProfile"));
}
auto newProcessEnvironmentResult = GetEnvironment(settings, primaryNewUserSecurityTokenHandle, settings.GetInheritanceMode(), trace);
if (newProcessEnvironmentResult.HasError())
{
UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
return Result<ExitCode>(newProcessEnvironmentResult.GetErrorCode(), newProcessEnvironmentResult.GetErrorDescription());
}
auto setIntegrityLevelResult = IntegrityLevelManager::SetIntegrityLevel(settings.GetIntegrityLevel(), primaryNewUserSecurityTokenHandle, trace);
if (setIntegrityLevelResult.HasError())
{
return Result<ExitCode>(setIntegrityLevelResult.GetErrorCode(), setIntegrityLevelResult.GetErrorDescription());
}
trace < L"ProcessAsUser::Create a new process and its primary thread. The new process runs in the security context of the user represented by the specified token.";
PROCESS_INFORMATION processInformation = {};
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
auto cmdLine = settings.GetCommandLine().c_str();
auto workingDirectory = settings.GetWorkingDirectory().c_str();
trace < L"::CreateProcessAsUser";
if (!CreateProcessAsUser(
primaryNewUserSecurityTokenHandle,
nullptr,
const_cast<LPWSTR>(cmdLine),
&processSecAttributes,
&threadSecAttributes,
true,
CREATE_UNICODE_ENVIRONMENT,
newProcessEnvironmentResult.GetResultValue().CreateEnvironment(),
workingDirectory,
&startupInfo,
&processInformation))
{
auto result = Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"CreateProcessAsUser"));
UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
return result;
}
// ReSharper disable once CppInitializedValueIsAlwaysRewritten
auto processHandle = Handle(L"Service Process");
processHandle = processInformation.hProcess;
auto threadHandle = Handle(L"Thread");
threadHandle = processInformation.hThread;
trace < L"ProcessAsUser::Create a job";
Job job;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobObjectInfo = {};
jobObjectInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
trace < L"ProcessAsUser::Configure all child processes associated with the job to terminate when the parent is terminated";
trace < L"Job::SetInformation";
job.SetInformation(JobObjectExtendedLimitInformation, jobObjectInfo);
trace < L"ProcessTracker::WaiteForExit";
auto exitCode = processTracker.WaiteForExit(processInformation.hProcess);
UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
return exitCode;
}
Result<Environment> ProcessAsUser::GetEnvironment(const Settings& settings, Handle& userToken, const InheritanceMode inheritanceMode, Trace& trace)
{
auto callingProcessEnvironmentResult = Environment::CreateForCurrentProcess(trace);
if(callingProcessEnvironmentResult.HasError())
{
return callingProcessEnvironmentResult;
}
if (inheritanceMode == INHERITANCE_MODE_ON)
{
return GetEnvironmentWithSpecifiedByCaller(
settings,
callingProcessEnvironmentResult.GetResultValue(),
trace);
}
// Get target user's environment
auto targetUserEnvironmentResult = Environment::CreateForUser(userToken, false, trace);
if (targetUserEnvironmentResult.HasError())
{
return targetUserEnvironmentResult;
}
if (inheritanceMode == INHERITANCE_MODE_OFF)
{
return GetEnvironmentWithSpecifiedByCaller(
settings,
targetUserEnvironmentResult.GetResultValue(),
trace);
}
return GetEnvironmentWithSpecifiedByCaller(
settings,
Environment::Override(
callingProcessEnvironmentResult.GetResultValue(),
targetUserEnvironmentResult.GetResultValue(),
trace),
trace);
}
Result<Environment> ProcessAsUser::GetEnvironmentWithSpecifiedByCaller(const Settings& settings, const Environment& environment, Trace& trace)
{
return Environment::Apply(
environment,
Environment::CreateFormList(
settings.GetEnvironmentVariables(),
trace),
trace);
}<commit_msg>Revert "Fix tests"<commit_after>#include "stdafx.h"
#include "ProcessAsUser.h"
#include "Settings.h"
#include "ErrorUtilities.h"
#include "ProcessTracker.h"
#include "Result.h"
#include "ExitCode.h"
#include "Environment.h"
#include "Trace.h"
#include "Job.h"
#include "IntegrityLevelManager.h"
class Trace;
class ProcessTracker;
Result<ExitCode> ProcessAsUser::Run(const Settings& settings, ProcessTracker& processTracker) const
{
Trace trace(settings.GetLogLevel());
trace < L"ProcessAsUser::Attempt to log a user on to the local computer";
trace < L"::LogonUser";
auto newUserSecurityTokenHandle = Handle(L"New user security token");
if (!LogonUser(
settings.GetUserName().c_str(),
settings.GetDomain().c_str(),
settings.GetPassword().c_str(),
LOGON32_LOGON_NETWORK,
LOGON32_PROVIDER_DEFAULT,
&newUserSecurityTokenHandle))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"LogonUser"));
}
trace < L"ProcessAsUser::Initialize a new security descriptor";
trace < L"::InitializeSecurityDescriptor";
SECURITY_DESCRIPTOR securityDescriptor = {};
if (!InitializeSecurityDescriptor(
&securityDescriptor,
SECURITY_DESCRIPTOR_REVISION))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"InitializeSecurityDescriptor"));
}
trace < L"::SetSecurityDescriptorDacl";
if (!SetSecurityDescriptorDacl(
&securityDescriptor,
true,
nullptr,
false))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"SetSecurityDescriptorDacl"));
}
trace < L"ProcessAsUser::Creates a new access primary token that duplicates new process's token";
auto primaryNewUserSecurityTokenHandle = Handle(L"Primary new user security token");
SECURITY_ATTRIBUTES processSecAttributes = {};
processSecAttributes.lpSecurityDescriptor = &securityDescriptor;
processSecAttributes.nLength = sizeof(SECURITY_DESCRIPTOR);
processSecAttributes.bInheritHandle = true;
trace < L"::DuplicateTokenEx";
if (!DuplicateTokenEx(
newUserSecurityTokenHandle,
0, // MAXIMUM_ALLOWED
&processSecAttributes,
SecurityImpersonation,
TokenPrimary,
&primaryNewUserSecurityTokenHandle))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"DuplicateTokenEx"));
}
SECURITY_ATTRIBUTES threadSecAttributes = {};
threadSecAttributes.lpSecurityDescriptor = nullptr;
threadSecAttributes.nLength = 0;
threadSecAttributes.bInheritHandle = false;
STARTUPINFO startupInfo = {};
trace < L"ProcessTracker::Initialize";
auto error = processTracker.Initialize(processSecAttributes, startupInfo);
if(error.HasError())
{
return Result<ExitCode>(error.GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"DuplicateTokenEx"));
}
trace < L"::LoadUserProfile";
PROFILEINFO profileInfo = {};
profileInfo.dwSize = sizeof(PROFILEINFO);
profileInfo.lpUserName = const_cast<LPWSTR>(settings.GetUserName().c_str());
if (!LoadUserProfile(primaryNewUserSecurityTokenHandle, &profileInfo))
{
return Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"LoadUserProfile"));
}
auto newProcessEnvironmentResult = GetEnvironment(settings, primaryNewUserSecurityTokenHandle, settings.GetInheritanceMode(), trace);
if (newProcessEnvironmentResult.HasError())
{
UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
return Result<ExitCode>(newProcessEnvironmentResult.GetErrorCode(), newProcessEnvironmentResult.GetErrorDescription());
}
auto setIntegrityLevelResult = IntegrityLevelManager::SetIntegrityLevel(settings.GetIntegrityLevel(), primaryNewUserSecurityTokenHandle, trace);
if (setIntegrityLevelResult.HasError())
{
return Result<ExitCode>(setIntegrityLevelResult.GetErrorCode(), setIntegrityLevelResult.GetErrorDescription());
}
trace < L"ProcessAsUser::Create a new process and its primary thread. The new process runs in the security context of the user represented by the specified token.";
PROCESS_INFORMATION processInformation = {};
startupInfo.dwFlags = STARTF_USESHOWWINDOW;
startupInfo.wShowWindow = SW_HIDE;
auto cmdLine = settings.GetCommandLine();
trace < L"::CreateProcessAsUser";
if (!CreateProcessAsUser(
primaryNewUserSecurityTokenHandle,
nullptr,
const_cast<LPWSTR>(cmdLine.c_str()),
&processSecAttributes,
&threadSecAttributes,
true,
CREATE_UNICODE_ENVIRONMENT,
newProcessEnvironmentResult.GetResultValue().CreateEnvironment(),
settings.GetWorkingDirectory().c_str(),
&startupInfo,
&processInformation))
{
auto result = Result<ExitCode>(ErrorUtilities::GetErrorCode(), ErrorUtilities::GetLastErrorMessage(L"CreateProcessAsUser"));
UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
return result;
}
// ReSharper disable once CppInitializedValueIsAlwaysRewritten
auto processHandle = Handle(L"Service Process");
processHandle = processInformation.hProcess;
auto threadHandle = Handle(L"Thread");
threadHandle = processInformation.hThread;
trace < L"ProcessAsUser::Create a job";
Job job;
JOBOBJECT_EXTENDED_LIMIT_INFORMATION jobObjectInfo = {};
jobObjectInfo.BasicLimitInformation.LimitFlags = JOB_OBJECT_LIMIT_KILL_ON_JOB_CLOSE;
trace < L"ProcessAsUser::Configure all child processes associated with the job to terminate when the parent is terminated";
trace < L"Job::SetInformation";
job.SetInformation(JobObjectExtendedLimitInformation, jobObjectInfo);
trace < L"ProcessTracker::WaiteForExit";
auto exitCode = processTracker.WaiteForExit(processInformation.hProcess);
UnloadUserProfile(primaryNewUserSecurityTokenHandle, profileInfo.hProfile);
return exitCode;
}
Result<Environment> ProcessAsUser::GetEnvironment(const Settings& settings, Handle& userToken, const InheritanceMode inheritanceMode, Trace& trace)
{
auto callingProcessEnvironmentResult = Environment::CreateForCurrentProcess(trace);
if(callingProcessEnvironmentResult.HasError())
{
return callingProcessEnvironmentResult;
}
if (inheritanceMode == INHERITANCE_MODE_ON)
{
return GetEnvironmentWithSpecifiedByCaller(
settings,
callingProcessEnvironmentResult.GetResultValue(),
trace);
}
// Get target user's environment
auto targetUserEnvironmentResult = Environment::CreateForUser(userToken, false, trace);
if (targetUserEnvironmentResult.HasError())
{
return targetUserEnvironmentResult;
}
if (inheritanceMode == INHERITANCE_MODE_OFF)
{
return GetEnvironmentWithSpecifiedByCaller(
settings,
targetUserEnvironmentResult.GetResultValue(),
trace);
}
return GetEnvironmentWithSpecifiedByCaller(
settings,
Environment::Override(
callingProcessEnvironmentResult.GetResultValue(),
targetUserEnvironmentResult.GetResultValue(),
trace),
trace);
}
Result<Environment> ProcessAsUser::GetEnvironmentWithSpecifiedByCaller(const Settings& settings, const Environment& environment, Trace& trace)
{
return Environment::Apply(
environment,
Environment::CreateFormList(
settings.GetEnvironmentVariables(),
trace),
trace);
}<|endoftext|> |
<commit_before>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#include <util/XMLUniDefs.hpp>
#include "AttrNSImpl.hpp"
#include "DocumentImpl.hpp"
#include "DOM_DOMException.hpp"
AttrNSImpl::AttrNSImpl(DocumentImpl *ownerDoc, const DOMString &nam) :
AttrImpl(ownerDoc, name)
{
this->namespaceURI=null; //DOM Level 2
this->localName=null; //DOM Level 2
}
//Introduced in DOM Level 2
AttrNSImpl::AttrNSImpl(DocumentImpl *ownerDoc,
const DOMString &fNamespaceURI,
const DOMString &qualifiedName) :
AttrImpl(ownerDoc, qualifiedName)
{
DOMString xmlns = NodeImpl::getXmlnsString();
DOMString xmlnsURI = NodeImpl::getXmlnsURIString();
this->name = qualifiedName.clone();
int index = DocumentImpl::indexofQualifiedName(qualifiedName);
DOMString prefix;
if (index < 0)
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
bool xmlnsAlone = false; //true if attribute name is "xmlns"
if (index == 0) { //qualifiedName contains no ':'
if (this->name.equals(xmlns)) {
if (!fNamespaceURI.equals(xmlnsURI))
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
xmlnsAlone = true;
}
prefix = null;
this -> localName = this -> name;
} else { //0 < index < this->name.length()-1
prefix = this->name.substringData(0, index);
this -> localName =
this->name.substringData(index+1, this->name.length()-index-1);
}
const DOMString& URI = xmlnsAlone ?
xmlnsURI : mapPrefix(prefix, fNamespaceURI, DOM_Node::ATTRIBUTE_NODE);
this -> namespaceURI = URI == null ? DOMString(null) : URI.clone();
};
AttrNSImpl::AttrNSImpl(const AttrNSImpl &other, bool deep) :
AttrImpl(other, deep)
{
this->namespaceURI = other.namespaceURI.clone(); //DOM Level 2
this->localName = other.localName.clone(); //DOM Level 2
};
NodeImpl * AttrNSImpl::cloneNode(bool deep)
{
return new AttrNSImpl(*this, deep);
};
DOMString AttrNSImpl::getNamespaceURI()
{
return namespaceURI;
}
DOMString AttrNSImpl::getPrefix()
{
int index = DocumentImpl::indexofQualifiedName(name);
if (index == 0)
return null;
else
return name.substringData(0, index);
}
DOMString AttrNSImpl::getLocalName()
{
return localName;
}
void AttrNSImpl::setPrefix(const DOMString &prefix)
{
DOMString xml = NodeImpl::getXmlString();
DOMString xmlURI = NodeImpl::getXmlURIString();
DOMString xmlns = NodeImpl::getXmlnsString();
DOMString xmlnsURI = NodeImpl::getXmlnsURIString();
if (getOwnerDocument()->getErrorChecking()) {
if (isReadOnly()) {
throw DOM_DOMException(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR,
null);
}
if (namespaceURI == null || localName.equals(xmlns)) {
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
}
if (prefix != null && !DocumentImpl::isXMLName(prefix)) {
throw DOM_DOMException(DOM_DOMException::INVALID_CHARACTER_ERR,
null);
}
}
if (prefix == null || prefix.length() == 0) {
name = localName;
return;
}
if (getOwnerDocument()->getErrorChecking() &&
(prefix.equals(xml) && !namespaceURI.equals(xmlURI) ||
prefix.equals(xmlns) && !namespaceURI.equals(xmlnsURI))) {
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
}
const XMLCh *p = prefix.rawBuffer();
for (int i = prefix.length(); --i >= 0;)
if (*p++ == chColon) //prefix is malformed
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
name = prefix + chColon + localName; //nodeName is changed too
}
<commit_msg>fixed typo in constructor - bug #1605<commit_after>/*
* The Apache Software License, Version 1.1
*
* Copyright (c) 1999-2000 The Apache Software Foundation. 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.
*
* 3. The end-user documentation included with the redistribution,
* if any, must include the following acknowledgment:
* "This product includes software developed by the
* Apache Software Foundation (http://www.apache.org/)."
* Alternately, this acknowledgment may appear in the software itself,
* if and wherever such third-party acknowledgments normally appear.
*
* 4. The names "Xerces" and "Apache Software Foundation" must
* not be used to endorse or promote products derived from this
* software without prior written permission. For written
* permission, please contact apache\@apache.org.
*
* 5. Products derived from this software may not be called "Apache",
* nor may "Apache" appear in their name, without prior written
* permission of the Apache Software Foundation.
*
* THIS SOFTWARE IS PROVIDED ``AS IS'' AND ANY EXPRESSED 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 APACHE SOFTWARE FOUNDATION OR
* ITS 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.
* ====================================================================
*
* This software consists of voluntary contributions made by many
* individuals on behalf of the Apache Software Foundation, and was
* originally based on software copyright (c) 1999, International
* Business Machines, Inc., http://www.ibm.com . For more information
* on the Apache Software Foundation, please see
* <http://www.apache.org/>.
*/
/*
* $Id$
*/
#include <util/XMLUniDefs.hpp>
#include "AttrNSImpl.hpp"
#include "DocumentImpl.hpp"
#include "DOM_DOMException.hpp"
AttrNSImpl::AttrNSImpl(DocumentImpl *ownerDoc, const DOMString &nam) :
AttrImpl(ownerDoc, nam)
{
this->namespaceURI=null; //DOM Level 2
this->localName=null; //DOM Level 2
}
//Introduced in DOM Level 2
AttrNSImpl::AttrNSImpl(DocumentImpl *ownerDoc,
const DOMString &fNamespaceURI,
const DOMString &qualifiedName) :
AttrImpl(ownerDoc, qualifiedName)
{
DOMString xmlns = NodeImpl::getXmlnsString();
DOMString xmlnsURI = NodeImpl::getXmlnsURIString();
this->name = qualifiedName.clone();
int index = DocumentImpl::indexofQualifiedName(qualifiedName);
DOMString prefix;
if (index < 0)
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
bool xmlnsAlone = false; //true if attribute name is "xmlns"
if (index == 0) { //qualifiedName contains no ':'
if (this->name.equals(xmlns)) {
if (!fNamespaceURI.equals(xmlnsURI))
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
xmlnsAlone = true;
}
prefix = null;
this -> localName = this -> name;
} else { //0 < index < this->name.length()-1
prefix = this->name.substringData(0, index);
this -> localName =
this->name.substringData(index+1, this->name.length()-index-1);
}
const DOMString& URI = xmlnsAlone ?
xmlnsURI : mapPrefix(prefix, fNamespaceURI, DOM_Node::ATTRIBUTE_NODE);
this -> namespaceURI = URI == null ? DOMString(null) : URI.clone();
};
AttrNSImpl::AttrNSImpl(const AttrNSImpl &other, bool deep) :
AttrImpl(other, deep)
{
this->namespaceURI = other.namespaceURI.clone(); //DOM Level 2
this->localName = other.localName.clone(); //DOM Level 2
};
NodeImpl * AttrNSImpl::cloneNode(bool deep)
{
return new AttrNSImpl(*this, deep);
};
DOMString AttrNSImpl::getNamespaceURI()
{
return namespaceURI;
}
DOMString AttrNSImpl::getPrefix()
{
int index = DocumentImpl::indexofQualifiedName(name);
if (index == 0)
return null;
else
return name.substringData(0, index);
}
DOMString AttrNSImpl::getLocalName()
{
return localName;
}
void AttrNSImpl::setPrefix(const DOMString &prefix)
{
DOMString xml = NodeImpl::getXmlString();
DOMString xmlURI = NodeImpl::getXmlURIString();
DOMString xmlns = NodeImpl::getXmlnsString();
DOMString xmlnsURI = NodeImpl::getXmlnsURIString();
if (getOwnerDocument()->getErrorChecking()) {
if (isReadOnly()) {
throw DOM_DOMException(
DOM_DOMException::NO_MODIFICATION_ALLOWED_ERR,
null);
}
if (namespaceURI == null || localName.equals(xmlns)) {
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
}
if (prefix != null && !DocumentImpl::isXMLName(prefix)) {
throw DOM_DOMException(DOM_DOMException::INVALID_CHARACTER_ERR,
null);
}
}
if (prefix == null || prefix.length() == 0) {
name = localName;
return;
}
if (getOwnerDocument()->getErrorChecking() &&
(prefix.equals(xml) && !namespaceURI.equals(xmlURI) ||
prefix.equals(xmlns) && !namespaceURI.equals(xmlnsURI))) {
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
}
const XMLCh *p = prefix.rawBuffer();
for (int i = prefix.length(); --i >= 0;)
if (*p++ == chColon) //prefix is malformed
throw DOM_DOMException(DOM_DOMException::NAMESPACE_ERR, null);
name = prefix + chColon + localName; //nodeName is changed too
}
<|endoftext|> |
<commit_before>#ifndef BNI_LEARNING_STEPWISE_STRUCTURE_HC_HPP
#define BNI_LEARNING_STEPWISE_STRUCTURE_HC_HPP
#include <array>
#include <string>
#include <random>
#include <bayesian/graph.hpp>
#include <bayesian/sampler.hpp>
#include <bayesian/hash.hpp>
#include <bayesian/evaluation/transinformation.hpp>
#include <bayesian/learning/utility.hpp>
namespace bn {
namespace learning {
// (同時)エントロピーを複数回計算する無駄を省くための辞書ホルダ
// 相互情報量規準
class mutual_information_holder {
public:
using pair_dictionary_type = std::unordered_map<std::pair<vertex_type, vertex_type>, double, bn::hash<std::pair<vertex_type, vertex_type>>>;
mutual_information_holder(bn::sampler const& sampling)
: sampling_(sampling), entropy_machine_(), mutual_machine_()
{
}
// エントロピーを計算して返す
// node: 調べるノード
double calculate_entropy(vertex_type const& node)
{
// 存在しているか
auto it = entropy_dic_.find(node);
if(it != entropy_dic_.end()) return it->second;
// 新たに計算して返す
auto value = entropy_machine_(sampling_, node);
entropy_dic_.emplace(node, value);
return value;
}
// 同時エントロピーを計算して返す
// lhs, rhs: 調べるノード(順不同)
double calculate_joint_entropy(vertex_type const& lhs, vertex_type const& rhs)
{
auto jointed = make_vertex_pair(lhs, rhs);
// 存在しているか
auto it = joint_entropy_dic_.find(jointed);
if(it != joint_entropy_dic_.end()) return it->second;
// 新たに計算して返す
auto value = entropy_machine_(sampling_, {jointed.first, jointed.second});
joint_entropy_dic_.emplace(std::move(jointed), value);
return value;
}
// 類似度を計算して返す
// 必要ならエントロピーを内部で計算する
// lhs, rhs: 調べるノード(順不同)
double calculate_similarity(vertex_type const& lhs, vertex_type const& rhs)
{
auto jointed = make_vertex_pair(lhs, rhs);
// 存在しているか
auto it = similarity_dic_.find(jointed);
if(it != similarity_dic_.end()) return it->second;
// 新たに計算して返す
auto value = mutual_machine_(
calculate_entropy(lhs),
calculate_entropy(rhs),
calculate_joint_entropy(lhs, rhs)
);
similarity_dic_.emplace(std::move(jointed), value);
return value;
}
// 登録済みのエントロピーを消す
void delete_entropy(vertex_type const& node)
{
entropy_dic_.erase(node);
}
// 登録済みの同時エントロピーを消す
void delete_joint_entropy(vertex_type const& lhs, vertex_type const& rhs)
{
joint_entropy_dic_.erase(make_vertex_pair(lhs, rhs));
}
// 登録済みの類似度を消す
void delete_similarity(vertex_type const& lhs, vertex_type const& rhs)
{
similarity_dic_.erase(make_vertex_pair(lhs, rhs));
}
private:
// pairの前半がアドレスの小さいノードになるように正規化する
// (順不同性を保証する)
std::pair<vertex_type, vertex_type> make_vertex_pair(vertex_type const& lhs, vertex_type const& rhs)
{
return (lhs < rhs) ? std::make_pair(lhs, rhs)
: std::make_pair(rhs, lhs);
}
// 学習器
sampler const& sampling_;
bn::evaluation::entropy const entropy_machine_;
bn::evaluation::mutual_information const mutual_machine_;
// 辞書
std::unordered_map<vertex_type, double> entropy_dic_;
pair_dictionary_type joint_entropy_dic_;
pair_dictionary_type similarity_dic_;
};
template<class Eval, template<class> class BetweenLearning>
class stepwise_structure_hc {
public:
using cluster_type = std::shared_ptr<std::vector<vertex_type>>;
using similarity_type = std::tuple<cluster_type, cluster_type, double>;
using Similarity = bn::evaluation::mutual_information;
stepwise_structure_hc(bn::sampler const& sampling)
: sampling_(sampling), eval_(sampling), learning_machine_(sampling_), engine_(make_engine<std::mt19937>()), info_holder_(sampling)
{
}
// 階層的クラスタリング及び確率的枝刈りを用いた段階的構造学習法の実行
// graph: グラフ構造(どんな構造が入っていたとしても,クリアされる)
// alpha: 枝刈りが実行される確率に関する係数
double operator()(graph_t& graph, double const alpha)
{
// graphの初期化
graph.erase_all_edge();
// 初期クラスタと初期類似度を初期化
initial_clustering(graph.vertex_list()); // 初期クラスタ
initial_similarities(); // 初期類似度
// クラスタ間学習(結合)
auto const score = learning_between_clusters(graph, alpha);
return score;
}
private:
// 初期クラスタリングを行い,クラスタリング結果をメンバ変数clusters_に格納する
// 第1引数: クラスタリング対象のノード集合
void initial_clustering(std::vector<vertex_type> const& nodes)
{
// クラスタ集合初期化
clusters_.clear();
clusters_.reserve(nodes.size());
// 1ノード1クラスタ
for(auto const& node : nodes)
{
auto cluster = std::make_shared<cluster_type::element_type>();
cluster->push_back(node);
clusters_.push_back(std::move(cluster));
}
}
// 初期類似度計算を行い,類似度をメンバ変数similarities_に格納する
void initial_similarities()
{
// 類似度集合初期化
similarities_.clear();
similarities_.reserve(clusters_.size() * clusters_.size());
// 全クラスタペアについて,類似度計算
for(std::size_t i = 0; i < clusters_.size(); ++i)
{
for(std::size_t j = i + 1; j < clusters_.size(); ++j)
{
auto const& i_cluster = clusters_[i];
auto const& j_cluster = clusters_[j];
similarities_.push_back(make_similarity_tuple(i_cluster, j_cluster));
}
}
}
// 指定したsimilarityにclusterが関与しているか(clusterに関する類似度か)どうかを返す
bool is_related(similarity_type const& similarity, cluster_type const& cluster)
{
return std::get<0>(similarity) == cluster || std::get<1>(similarity) == cluster;
}
// 指定したsimilarityがlhsとrhsに関する類似度かどうかを返す
bool is_connected(similarity_type const& similarity, cluster_type const& lhs, cluster_type const& rhs)
{
return std::get<0>(similarity) == std::min(lhs, rhs) && std::get<1>(similarity) == std::max(lhs, rhs);
}
// 引数の2つのクラスタを1つのクラスタに結合する
// clusters_に追加されていれば,clusters_から削除する(副作用)
cluster_type combine_clusters(cluster_type const& lhs, cluster_type const& rhs)
{
// 合成クラスタ
auto new_cluster = std::make_shared<cluster_type::element_type>();
new_cluster->reserve(lhs->size() + rhs->size());
new_cluster->insert(new_cluster->end(), lhs->cbegin(), lhs->cend());
new_cluster->insert(new_cluster->end(), rhs->cbegin(), rhs->cend());
// 前のクラスタを消す
clusters_.erase(std::find(clusters_.begin(), clusters_.end(), lhs));
clusters_.erase(std::find(clusters_.begin(), clusters_.end(), rhs));
return new_cluster;
}
// メンバ変数similarities_から最も順位の高いものを取り出し,無作為に親子を決定する
std::tuple<cluster_type, cluster_type, double> most_similarity()
{
// 最も似ているクラスタ間
auto const most_similar = std::max_element(
similarities_.begin(), similarities_.end(),
[](similarity_type const& lhs, similarity_type const& rhs){ return std::get<2>(lhs) < std::get<2>(rhs); }
);
// コピーして元のクラスタ間を消す
auto result = *most_similar;
similarities_.erase(most_similar);
// most_similarのどちらが親か(一定条件で入れ替え)
std::uniform_int_distribution<std::size_t> binary_dist(0, 1);
if(binary_dist(engine_)) std::swap(std::get<0>(result), std::get<1>(result));
return result;
}
// 与えられた2つのクラスタ間の類似度を求め,similarity_typeとして返す
similarity_type make_similarity_tuple(cluster_type const& lhs, cluster_type const& rhs)
{
// 2クラスタ間のノードのそれぞれの組み合わせ数
auto const combination_num = lhs->size() * rhs->size();
// 類似度計算
double value = 0;
for(auto const& lhs_nodes : *lhs)
{
for(auto const& rhs_nodes : *rhs)
{
// 数で割って足す(平均)
value += info_holder_.calculate_similarity(lhs_nodes, rhs_nodes) / combination_num;
}
}
// アドレスが小さいクラスタを先にして返す
return (lhs < rhs) ? std::make_tuple(lhs, rhs, value)
: std::make_tuple(rhs, lhs, value);
}
// クラスタ間学習を行う
// graph, alpha: operator()参照
double learning_between_clusters(graph_t& graph, double const alpha)
{
double score = std::numeric_limits<double>::max();
while(clusters_.size() != 1 && !similarities_.empty())
{
//
// 階層的構造学習 部分
//
// 結合対象を得る
similarity_type const combine_target = most_similarity();
auto const parent = std::get<0>(combine_target);
auto const child = std::get<1>(combine_target);
// learning
score = learning_machine_.learn_with_hint(graph, *parent, *child);
// クラスタ合成
clusters_.push_back(combine_clusters(parent, child));
auto const& inserted_cluster = clusters_.back(); // 挿入後のnew_clusterの参照
//
// 確率的枝刈り 部分
//
stochastic_pruning(alpha, inserted_cluster, combine_target);
}
return score;
}
// 確率的枝刈りを行う
// alpha: operator()に準ずる
// new_cluster: 結合後のクラスタを示す
// old_connection: 結合前の2クラスタ間のsimilarity_typeを示す
void stochastic_pruning(
double const alpha,
cluster_type const& new_cluster, similarity_type const& old_connection
)
{
// 全クラスタと検索
for(auto const cluster : clusters_)
{
// 自分自身及び結合後のクラスタならばパスする
if(cluster == new_cluster) continue;
// 探索中クラスタが元のクラスタと幾つ接続されていたか調べる
std::vector<similarity_type> connection;
for(auto it = similarities_.begin(); it != similarities_.end(); )
{
if(is_connected(*it, cluster, std::get<0>(old_connection)) || is_connected(*it, cluster, std::get<1>(old_connection)))
{
connection.push_back(*it);
it = similarities_.erase(it);
}
else ++it;
}
// 類似度を計算しておく
auto new_similarity = make_similarity_tuple(new_cluster, cluster);
// 枝刈り条件
double probability;
if(connection.size() == 2)
{
// 類似度の平均を求める
double const average_similar = std::accumulate(
similarities_.begin(), similarities_.end(), 0.0,
[this](double val, similarity_type const& similarity) -> double
{
return val + std::get<2>(similarity) / similarities_.size();
});
probability = std::pow(alpha, std::get<2>(new_similarity) / average_similar);
}
else if(connection.size() == 1)
{
probability = std::pow(alpha, std::get<2>(old_connection) / std::get<2>(connection[0]));
}
else if(connection.size() == 0)
{
// 張らない
continue;
}
else throw std::runtime_error("too connection");
// 確率により,probabilityの確率で枝刈り
std::uniform_real_distribution<double> probability_dist(0.0, 1.0);
if(probability_dist(engine_) < probability) continue; // 枝刈り
// 刈らない
similarities_.push_back(std::move(new_similarity));
}
// 消えたノードに関する類似度をすべて消す(ゴリ押し)
for(auto it = similarities_.begin(); it != similarities_.end(); )
{
// 消えたノードに関係しているかどうか
if(is_related(*it, std::get<0>(old_connection)) || is_related(*it, std::get<1>(old_connection)))
{
it = similarities_.erase(it);
}
else ++it;
}
}
sampler sampling_;
Eval eval_;
BetweenLearning<Eval> learning_machine_;
std::mt19937 engine_;
mutual_information_holder info_holder_;
std::vector<cluster_type> clusters_;
std::vector<similarity_type> similarities_;
};
} // namespace learning
} // namespace bn
#endif // BNI_LEARNING_STEPWISE_STRUCTURE_HC_HPP
<commit_msg>change into probability p2 in stochastic_pruning use all node similarities.<commit_after>#ifndef BNI_LEARNING_STEPWISE_STRUCTURE_HC_HPP
#define BNI_LEARNING_STEPWISE_STRUCTURE_HC_HPP
#include <array>
#include <string>
#include <random>
#include <bayesian/graph.hpp>
#include <bayesian/sampler.hpp>
#include <bayesian/hash.hpp>
#include <bayesian/evaluation/transinformation.hpp>
#include <bayesian/learning/utility.hpp>
namespace bn {
namespace learning {
// (同時)エントロピーを複数回計算する無駄を省くための辞書ホルダ
// 相互情報量規準
class mutual_information_holder {
public:
using pair_dictionary_type = std::unordered_map<std::pair<vertex_type, vertex_type>, double, bn::hash<std::pair<vertex_type, vertex_type>>>;
mutual_information_holder(bn::sampler const& sampling)
: sampling_(sampling), entropy_machine_(), mutual_machine_()
{
}
// エントロピーを計算して返す
// node: 調べるノード
double calculate_entropy(vertex_type const& node)
{
// 存在しているか
auto it = entropy_dic_.find(node);
if(it != entropy_dic_.end()) return it->second;
// 新たに計算して返す
auto value = entropy_machine_(sampling_, node);
entropy_dic_.emplace(node, value);
return value;
}
// 同時エントロピーを計算して返す
// lhs, rhs: 調べるノード(順不同)
double calculate_joint_entropy(vertex_type const& lhs, vertex_type const& rhs)
{
auto jointed = make_vertex_pair(lhs, rhs);
// 存在しているか
auto it = joint_entropy_dic_.find(jointed);
if(it != joint_entropy_dic_.end()) return it->second;
// 新たに計算して返す
auto value = entropy_machine_(sampling_, {jointed.first, jointed.second});
joint_entropy_dic_.emplace(std::move(jointed), value);
return value;
}
// 類似度を計算して返す
// 必要ならエントロピーを内部で計算する
// lhs, rhs: 調べるノード(順不同)
double calculate_similarity(vertex_type const& lhs, vertex_type const& rhs)
{
auto jointed = make_vertex_pair(lhs, rhs);
// 存在しているか
auto it = similarity_dic_.find(jointed);
if(it != similarity_dic_.end()) return it->second;
// 新たに計算して返す
auto value = mutual_machine_(
calculate_entropy(lhs),
calculate_entropy(rhs),
calculate_joint_entropy(lhs, rhs)
);
similarity_dic_.emplace(std::move(jointed), value);
return value;
}
// 登録済みのエントロピーを消す
void delete_entropy(vertex_type const& node)
{
entropy_dic_.erase(node);
}
// 登録済みの同時エントロピーを消す
void delete_joint_entropy(vertex_type const& lhs, vertex_type const& rhs)
{
joint_entropy_dic_.erase(make_vertex_pair(lhs, rhs));
}
// 登録済みの類似度を消す
void delete_similarity(vertex_type const& lhs, vertex_type const& rhs)
{
similarity_dic_.erase(make_vertex_pair(lhs, rhs));
}
private:
// pairの前半がアドレスの小さいノードになるように正規化する
// (順不同性を保証する)
std::pair<vertex_type, vertex_type> make_vertex_pair(vertex_type const& lhs, vertex_type const& rhs)
{
return (lhs < rhs) ? std::make_pair(lhs, rhs)
: std::make_pair(rhs, lhs);
}
// 学習器
sampler const& sampling_;
bn::evaluation::entropy const entropy_machine_;
bn::evaluation::mutual_information const mutual_machine_;
// 辞書
std::unordered_map<vertex_type, double> entropy_dic_;
pair_dictionary_type joint_entropy_dic_;
pair_dictionary_type similarity_dic_;
};
template<class Eval, template<class> class BetweenLearning>
class stepwise_structure_hc {
public:
using cluster_type = std::shared_ptr<std::vector<vertex_type>>;
using similarity_type = std::tuple<cluster_type, cluster_type, double>;
using Similarity = bn::evaluation::mutual_information;
stepwise_structure_hc(bn::sampler const& sampling)
: sampling_(sampling), eval_(sampling), learning_machine_(sampling_), engine_(make_engine<std::mt19937>()), info_holder_(sampling)
{
}
// 階層的クラスタリング及び確率的枝刈りを用いた段階的構造学習法の実行
// graph: グラフ構造(どんな構造が入っていたとしても,クリアされる)
// alpha: 枝刈りが実行される確率に関する係数
double operator()(graph_t& graph, double const alpha)
{
// graphの初期化
graph.erase_all_edge();
// 初期クラスタと初期類似度を初期化
initial_clustering(graph.vertex_list()); // 初期クラスタ
initial_similarities(); // 初期類似度
// クラスタ間学習(結合)
auto const score = learning_between_clusters(graph, alpha);
return score;
}
private:
// 初期クラスタリングを行い,クラスタリング結果をメンバ変数clusters_に格納する
// 第1引数: クラスタリング対象のノード集合
void initial_clustering(std::vector<vertex_type> const& nodes)
{
// クラスタ集合初期化
clusters_.clear();
clusters_.reserve(nodes.size());
// 1ノード1クラスタ
for(auto const& node : nodes)
{
auto cluster = std::make_shared<cluster_type::element_type>();
cluster->push_back(node);
clusters_.push_back(std::move(cluster));
}
}
// 初期類似度計算を行い,類似度をメンバ変数similarities_に格納する
void initial_similarities()
{
// 類似度集合初期化
similarities_.clear();
similarities_.reserve(clusters_.size() * clusters_.size());
// 類似度平均初期化
average_similar_ = 0.0;
auto const max_edge_num = clusters_.size() * (clusters_.size() - 1) / 2;
// 全クラスタペアについて,類似度計算
for(std::size_t i = 0; i < clusters_.size(); ++i)
{
for(std::size_t j = i + 1; j < clusters_.size(); ++j)
{
auto const& i_cluster = clusters_[i];
auto const& j_cluster = clusters_[j];
assert(i_cluster->size() == 1 && j_cluster->size() == 1); // 初期状態は1ノードであるはずだから
auto&& similarity = make_similarity_tuple(i_cluster, j_cluster);
average_similar_ += std::get<2>(similarity) / max_edge_num;
similarities_.push_back(std::move(similarity));
}
}
}
// 指定したsimilarityにclusterが関与しているか(clusterに関する類似度か)どうかを返す
bool is_related(similarity_type const& similarity, cluster_type const& cluster)
{
return std::get<0>(similarity) == cluster || std::get<1>(similarity) == cluster;
}
// 指定したsimilarityがlhsとrhsに関する類似度かどうかを返す
bool is_connected(similarity_type const& similarity, cluster_type const& lhs, cluster_type const& rhs)
{
return std::get<0>(similarity) == std::min(lhs, rhs) && std::get<1>(similarity) == std::max(lhs, rhs);
}
// 引数の2つのクラスタを1つのクラスタに結合する
// clusters_に追加されていれば,clusters_から削除する(副作用)
cluster_type combine_clusters(cluster_type const& lhs, cluster_type const& rhs)
{
// 合成クラスタ
auto new_cluster = std::make_shared<cluster_type::element_type>();
new_cluster->reserve(lhs->size() + rhs->size());
new_cluster->insert(new_cluster->end(), lhs->cbegin(), lhs->cend());
new_cluster->insert(new_cluster->end(), rhs->cbegin(), rhs->cend());
// 前のクラスタを消す
clusters_.erase(std::find(clusters_.begin(), clusters_.end(), lhs));
clusters_.erase(std::find(clusters_.begin(), clusters_.end(), rhs));
return new_cluster;
}
// メンバ変数similarities_から最も順位の高いものを取り出し,無作為に親子を決定する
std::tuple<cluster_type, cluster_type, double> most_similarity()
{
// 最も似ているクラスタ間
auto const most_similar = std::max_element(
similarities_.begin(), similarities_.end(),
[](similarity_type const& lhs, similarity_type const& rhs){ return std::get<2>(lhs) < std::get<2>(rhs); }
);
// コピーして元のクラスタ間を消す
auto result = *most_similar;
similarities_.erase(most_similar);
// most_similarのどちらが親か(一定条件で入れ替え)
std::uniform_int_distribution<std::size_t> binary_dist(0, 1);
if(binary_dist(engine_)) std::swap(std::get<0>(result), std::get<1>(result));
return result;
}
// 与えられた2つのクラスタ間の類似度を求め,similarity_typeとして返す
similarity_type make_similarity_tuple(cluster_type const& lhs, cluster_type const& rhs)
{
// 2クラスタ間のノードのそれぞれの組み合わせ数
auto const combination_num = lhs->size() * rhs->size();
// 類似度計算
double value = 0;
for(auto const& lhs_nodes : *lhs)
{
for(auto const& rhs_nodes : *rhs)
{
// 数で割って足す(平均)
value += info_holder_.calculate_similarity(lhs_nodes, rhs_nodes) / combination_num;
}
}
// アドレスが小さいクラスタを先にして返す
return (lhs < rhs) ? std::make_tuple(lhs, rhs, value)
: std::make_tuple(rhs, lhs, value);
}
// クラスタ間学習を行う
// graph, alpha: operator()参照
double learning_between_clusters(graph_t& graph, double const alpha)
{
double score = std::numeric_limits<double>::max();
while(clusters_.size() != 1 && !similarities_.empty())
{
//
// 階層的構造学習 部分
//
// 結合対象を得る
similarity_type const combine_target = most_similarity();
auto const parent = std::get<0>(combine_target);
auto const child = std::get<1>(combine_target);
// learning
score = learning_machine_.learn_with_hint(graph, *parent, *child);
// クラスタ合成
clusters_.push_back(combine_clusters(parent, child));
auto const& inserted_cluster = clusters_.back(); // 挿入後のnew_clusterの参照
//
// 確率的枝刈り 部分
//
stochastic_pruning(alpha, inserted_cluster, combine_target);
}
return score;
}
// 確率的枝刈りを行う
// alpha: operator()に準ずる
// new_cluster: 結合後のクラスタを示す
// old_connection: 結合前の2クラスタ間のsimilarity_typeを示す
void stochastic_pruning(
double const alpha,
cluster_type const& new_cluster, similarity_type const& old_connection
)
{
// 全クラスタと検索
for(auto const cluster : clusters_)
{
// 自分自身及び結合後のクラスタならばパスする
if(cluster == new_cluster) continue;
// 探索中クラスタが元のクラスタと幾つ接続されていたか調べる
std::vector<similarity_type> connection;
for(auto it = similarities_.begin(); it != similarities_.end(); )
{
if(is_connected(*it, cluster, std::get<0>(old_connection)) || is_connected(*it, cluster, std::get<1>(old_connection)))
{
connection.push_back(*it);
it = similarities_.erase(it);
}
else ++it;
}
// 類似度を計算しておく
auto new_similarity = make_similarity_tuple(new_cluster, cluster);
// 枝刈り条件
double probability;
if(connection.size() == 2)
{
probability = std::pow(alpha, std::get<2>(new_similarity) / average_similar_);
}
else if(connection.size() == 1)
{
probability = std::pow(alpha, std::get<2>(old_connection) / std::get<2>(connection[0]));
}
else if(connection.size() == 0)
{
// 張らない
continue;
}
else throw std::runtime_error("too connection");
// 確率により,probabilityの確率で枝刈り
std::uniform_real_distribution<double> probability_dist(0.0, 1.0);
if(probability_dist(engine_) < probability) continue; // 枝刈り
// 刈らない
similarities_.push_back(std::move(new_similarity));
}
// 消えたノードに関する類似度をすべて消す(ゴリ押し)
for(auto it = similarities_.begin(); it != similarities_.end(); )
{
// 消えたノードに関係しているかどうか
if(is_related(*it, std::get<0>(old_connection)) || is_related(*it, std::get<1>(old_connection)))
{
it = similarities_.erase(it);
}
else ++it;
}
}
sampler sampling_;
Eval eval_;
BetweenLearning<Eval> learning_machine_;
std::mt19937 engine_;
mutual_information_holder info_holder_;
std::vector<cluster_type> clusters_;
std::vector<similarity_type> similarities_;
double average_similar_;
};
} // namespace learning
} // namespace bn
#endif // BNI_LEARNING_STEPWISE_STRUCTURE_HC_HPP
<|endoftext|> |
<commit_before>#include "tiramisu/tiramisu.h"
#include "wrapper_optical_flow.h"
// This code is the Tiramisu implementation of the following Matlab code
// https://www.mathworks.com/examples/computer-vision/community/35625-lucas-kanade-method-example-2?s_tid=examples_p1_BOTH
using namespace tiramisu;
int main(int argc, char* argv[])
{
// Declare the function name
tiramisu::init("optical_flow_tiramisu");
// Declare input sizes
// TODO: "input" dimension sizes should be expressions not variables.
input SIZES("SIZES", {var("S", 0, 2)}, p_int32);
constant N0("N0", SIZES(0));
constant N1("N1", SIZES(1));
constant NC("NC", _NC); // Number of corners
// Loop iterators
var x("x", 0, N1-1), y("y", 0, N0-1), k("k", 0, NC);
// input images
input im1("im1", {y, x}, p_uint8);
input im2("im2", {y, x}, p_uint8);
// Corners
input C1("C1", {k}, p_int32);
input C2("C2", {k}, p_int32);
// First convolution (partial on x)
expr e1 = cast(p_float32, cast(p_int32, im1(y, x)) - cast(p_int32, im1(y, x + 1)) +
cast(p_int32, im1(y + 1, x)) - cast(p_int32, im1(y + 1, x + 1)));
computation Ix_m("Ix_m", {y, x}, e1);
// Second convolution (partial on y)
expr e2 = cast(p_float32, cast(p_int32, im1(y, x)) + cast(p_int32, im1(y, x + 1))
- cast(p_int32, im1(y + 1, x)) - cast(p_int32, im1(y + 1, x + 1)));
computation Iy_m("Iy_m", {y, x}, e2);
// Third convolution
expr e3 = cast(p_float32, cast(p_int32, im1(y, x)) + cast(p_int32, im1(y, x + 1))
+ cast(p_int32, im1(y + 1, x)) + cast(p_int32, im1(y + 1, x + 1)));
expr e4 = cast(p_float32, (- cast(p_int32, im2(y, x))) - cast(p_int32, im2(y, x + 1))
- cast(p_int32, im2(y + 1, x)) - cast(p_int32, im2(y + 1, x + 1)));
computation It_m("It_m", {y, x}, e3 + e4);
// Second part of the algorithm
// Compute "u" and "v" for each corner "k"
computation i("i", {k}, C2(k));
computation j("j", {k}, C1(k));
// Ix = Ix_m(i-w:i+w, j-w:j+w);
// Iy = Iy_m(i-w:i+w, j-w:j+w);
// It = It_m(i-w:i+w, j-w:j+w);
// Ix = Ix(:); % flatten the IX 2D array into a vector
// Iy = Iy(:);
// A = [Ix Iy];
// b = -It(:); % get b here
var xp("xp", 0, 2*w);
var yp("yp", 0, 2*w);
computation A1("A1", {k, yp, xp}, Ix_m(i(0)+yp-w, j(0)+xp-w)); //TODO: use i(k) and j(k) instead of i(0) and j(0)
computation A1_right("A1_right", {k, yp, xp}, Iy_m(i(0)+yp-w, j(0)+xp-w)); //i(k), j(k)
computation b1("b1", {k, yp, xp}, (-It_m(i(0)+yp-w, j(0)+xp-w))); //i(k), j(k)
// Reshape A1 to A
var x1("x1", 0, 2);
var y1("y1", 0, 4*w*w);
input A("A", {k, y1, x1}, p_float32); // Use A to reshape A1 and A1_right
input b("b", {k, y1}, p_float32); // Use b to reshape b1
// Compute pinv(A):
// 1) tA = transpose(A)
// 2) tAA = tA * A
// 3) X = inv(tAA)
// 4) pinv(A) = X * tA
// 1) Computing tA = transpose(A)
computation tA("tA", {k, x1, y1}, A(k, y1, x1));
// 2) Computing tAA = tA * A
var y2("y2", 0, 2);
var l1("l1", 0, 4*w*w);
computation tAA("tAA", {k, x1, y2}, expr((float) 0));
computation tAA_update("tAA_update", {k, x1, y2, l1}, tAA(k, x1, y2) + (tA(k, x1, l1) * A(k, l1, y2)));
// 3) Computing X = inv(tAA)
computation determinant("determinant", {k}, cast(p_float64,tAA(k,0,0))*cast(p_float64, tAA(k,1,1)) - (cast(p_float64, tAA(k,0,1))*cast(p_float64, tAA(k,1,0))));
computation tAAp_00("tAAp_00", {k}, cast(p_float64, tAA(k,1,1))/determinant(k));
computation tAAp_11("tAAp_11", {k}, cast(p_float64, tAA(k,0,0))/determinant(k));
computation tAAp_01("tAAp_01", {k}, -cast(p_float64, tAA(k,0,1))/determinant(k));
computation tAAp_10("tAAp_10", {k}, -cast(p_float64, tAA(k,1,0))/determinant(k));
input X("X", {k, x1, y2}, p_float64);
// 4) Computing pinv(A) = X*tA
var l2("l2", 0, 2);
computation pinvA("pinvA", {k, x1, y1}, expr((double) 0));
computation pinvA_update("pinvA_update", {k, x1, y1, l2}, pinvA(k, x1, y1) + X(k, x1, l2)*cast(p_float64, tA(k, l2, y1)));
// Compute nu = pinv(A)*b
computation nu("nu", {k, x1}, expr((float) 0));
computation nu_update("nu_update", {k, x1, y1}, nu(k, x1) + cast(p_float32, pinvA(k, x1, y1))*b(k, y1));
// Results
computation u("u", {k}, nu(k, 0));
computation v("v", {k}, nu(k, 1));
Ix_m.then(Iy_m, x)
.then(It_m, x)
.then(i, computation::root)
.then(j, k)
.then(A1, k)
.then(A1_right, k)
.then(b1, k)
.then(tA, k)
.then(tAA, k)
.then(tAA_update, y2)
.then(determinant, k)
.then(tAAp_00, k)
.then(tAAp_11, k)
.then(tAAp_01, k)
.then(tAAp_10, k)
.then(X, k)
.then(pinvA, k)
.then(pinvA_update, y1)
.then(nu, k)
.then(nu_update, x1)
.then(u, k)
.then(v, k);
// Buffer allocation and mapping computations to buffers
buffer b_SIZES("b_SIZES", {2}, p_int32, a_input);
buffer b_im1("b_im1", {N0, N1}, p_uint8, a_input);
buffer b_im2("b_im2", {N0, N1}, p_uint8, a_input);
buffer b_Ix_m("b_Ix_m", {N0, N1}, p_float32, a_output);
buffer b_Iy_m("b_Iy_m", {N0, N1}, p_float32, a_output);
buffer b_It_m("b_It_m", {N0, N1}, p_float32, a_output);
buffer b_C1("b_C1", {NC}, p_int32, a_input);
buffer b_C2("b_C2", {NC}, p_int32, a_input);
buffer b_i("b_i", {1}, p_int32, a_temporary);
buffer b_j("b_j", {1}, p_int32, a_temporary);
buffer b_A("b_A", {4*w*w, 2}, p_float32, a_output);
buffer b_b("b_b", {4*w*w}, p_float32, a_temporary);
buffer b_tA("b_tA", {2, 4*w*w}, p_float32, a_output);
buffer b_tAA("b_tAA", {2, 2}, p_float32, a_output);
buffer b_determinant("b_determinant", {1}, p_float64, a_output);
buffer b_X("b_X", {2, 2}, p_float64, a_output);
buffer b_pinvA("b_pinvA", {2, 4*w*w}, p_float64, a_output);
buffer b_nu("b_nu", {2}, p_float32, a_temporary);
buffer b_u("b_u", {NC}, p_float32, a_output);
buffer b_v("b_v", {NC}, p_float32, a_output);
SIZES.store_in(&b_SIZES);
im1.store_in(&b_im1);
im2.store_in(&b_im2);
Ix_m.store_in(&b_Ix_m);
Iy_m.store_in(&b_Iy_m);
It_m.store_in(&b_It_m);
C1.store_in(&b_C1);
C2.store_in(&b_C2);
i.store_in(&b_i, {0});
j.store_in(&b_j, {0});
A1.store_in(&b_A, {xp+yp*2*w, 0});
A1_right.store_in(&b_A, {xp+yp*2*w, 1});
b1.store_in(&b_b, {xp+yp*2*w});
A.store_in(&b_A, {y1, x1});
b.store_in(&b_b, {y1});
tA.store_in(&b_tA, {x1, y1});
tAA.store_in(&b_tAA, {x1, y2});
tAA_update.store_in(&b_tAA, {x1, y2});
determinant.store_in(&b_determinant, {0});
tAAp_00.store_in(&b_X, {0, 0});
tAAp_01.store_in(&b_X, {0, 1});
tAAp_10.store_in(&b_X, {1, 0});
tAAp_11.store_in(&b_X, {1, 1});
X.store_in(&b_X, {x1, y2});
pinvA.store_in(&b_pinvA, {x1, y1});
pinvA_update.store_in(&b_pinvA, {x1, y1});
nu.store_in(&b_nu, {x1});
nu_update.store_in(&b_nu, {x1});
u.store_in(&b_u, {k});
v.store_in(&b_v, {k});
tiramisu::codegen({&b_SIZES, &b_im1, &b_im2, &b_Ix_m, &b_Iy_m, &b_It_m, &b_C1, &b_C2, &b_u, &b_v, &b_A, &b_pinvA, &b_determinant, &b_tAA, &b_tA, &b_X}, "build/generated_fct_optical_flow.o");
return 0;
}
<commit_msg>Update optical flow<commit_after>#include "tiramisu/tiramisu.h"
#include "wrapper_optical_flow.h"
// This code is the Tiramisu implementation of the following Matlab code
// https://www.mathworks.com/examples/computer-vision/community/35625-lucas-kanade-method-example-2?s_tid=examples_p1_BOTH
using namespace tiramisu;
int main(int argc, char* argv[])
{
// Declare the function name
tiramisu::init("optical_flow_tiramisu");
// Declare input sizes
input SIZES("SIZES", {var("S", 0, 2)}, p_int32);
constant N0("N0", SIZES(0));
constant N1("N1", SIZES(1));
constant NC("NC", _NC); // Number of corners
// Loop iterators
var x("x", 0, N1-1), y("y", 0, N0-1), k("k", 0, NC);
// input images
input im1("im1", {y, x}, p_uint8);
input im2("im2", {y, x}, p_uint8);
// Corners
input C1("C1", {k}, p_int32);
input C2("C2", {k}, p_int32);
// First convolution (partial on x)
expr e1 = cast(p_float32, cast(p_int32, im1(y, x)) - cast(p_int32, im1(y, x + 1)) +
cast(p_int32, im1(y + 1, x)) - cast(p_int32, im1(y + 1, x + 1)));
computation Ix_m("Ix_m", {y, x}, e1);
// Second convolution (partial on y)
expr e2 = cast(p_float32, cast(p_int32, im1(y, x)) + cast(p_int32, im1(y, x + 1))
- cast(p_int32, im1(y + 1, x)) - cast(p_int32, im1(y + 1, x + 1)));
computation Iy_m("Iy_m", {y, x}, e2);
// Third convolution
expr e3 = cast(p_float32, cast(p_int32, im1(y, x)) + cast(p_int32, im1(y, x + 1))
+ cast(p_int32, im1(y + 1, x)) + cast(p_int32, im1(y + 1, x + 1)));
expr e4 = cast(p_float32, (- cast(p_int32, im2(y, x))) - cast(p_int32, im2(y, x + 1))
- cast(p_int32, im2(y + 1, x)) - cast(p_int32, im2(y + 1, x + 1)));
computation It_m("It_m", {y, x}, e3 + e4);
// Second part of the algorithm
// Compute "u" and "v" for each corner "k"
computation i("i", {k}, C2(k));
computation j("j", {k}, C1(k));
// Ix = Ix_m(i-w:i+w, j-w:j+w);
// Iy = Iy_m(i-w:i+w, j-w:j+w);
// It = It_m(i-w:i+w, j-w:j+w);
// Ix = Ix(:); % flatten the IX 2D array into a vector
// Iy = Iy(:);
// A = [Ix Iy];
// b = -It(:); % get b here
var xp("xp", 0, 2*w);
var yp("yp", 0, 2*w);
computation A1("A1", {k, yp, xp}, Ix_m(i(0)+yp-w, j(0)+xp-w));
computation A1_right("A1_right", {k, yp, xp}, Iy_m(i(0)+yp-w, j(0)+xp-w));
computation b1("b1", {k, yp, xp}, (-It_m(i(0)+yp-w, j(0)+xp-w)));
// Reshape A1 to A
var x1("x1", 0, 2);
var y1("y1", 0, 4*w*w);
input A("A", {k, y1, x1}, p_float32); // Use A to reshape A1 and A1_right
input b("b", {k, y1}, p_float32); // Use b to reshape b1
// Compute pinv(A):
// 1) tA = transpose(A)
// 2) tAA = tA * A
// 3) X = inv(tAA)
// 4) pinv(A) = X * tA
// 1) Computing tA = transpose(A)
computation tA("tA", {k, x1, y1}, A(k, y1, x1));
// 2) Computing tAA = tA * A
var y2("y2", 0, 2);
var l1("l1", 0, 4*w*w);
computation tAA("tAA", {k, x1, y2}, expr((float) 0));
computation tAA_update("tAA_update", {k, x1, y2, l1}, tAA(k, x1, y2) + (tA(k, x1, l1) * A(k, l1, y2)));
// 3) Computing X = inv(tAA)
computation determinant("determinant", {k}, cast(p_float64,tAA(k,0,0))*cast(p_float64, tAA(k,1,1)) - (cast(p_float64, tAA(k,0,1))*cast(p_float64, tAA(k,1,0))));
computation tAAp_00("tAAp_00", {k}, cast(p_float64, tAA(k,1,1))/determinant(k));
computation tAAp_11("tAAp_11", {k}, cast(p_float64, tAA(k,0,0))/determinant(k));
computation tAAp_01("tAAp_01", {k}, -cast(p_float64, tAA(k,0,1))/determinant(k));
computation tAAp_10("tAAp_10", {k}, -cast(p_float64, tAA(k,1,0))/determinant(k));
input X("X", {k, x1, y2}, p_float64);
// 4) Computing pinv(A) = X*tA
var l2("l2", 0, 2);
computation pinvA("pinvA", {k, x1, y1}, expr((double) 0));
computation pinvA_update("pinvA_update", {k, x1, y1, l2}, pinvA(k, x1, y1) + X(k, x1, l2)*cast(p_float64, tA(k, l2, y1)));
// Compute nu = pinv(A)*b
computation nu("nu", {k, x1}, expr((float) 0));
computation nu_update("nu_update", {k, x1, y1}, nu(k, x1) + cast(p_float32, pinvA(k, x1, y1))*b(k, y1));
// Results
computation u("u", {k}, nu(k, 0));
computation v("v", {k}, nu(k, 1));
Ix_m.then(Iy_m, x)
.then(It_m, x)
.then(i, computation::root)
.then(j, k)
.then(A1, k)
.then(A1_right, k)
.then(b1, k)
.then(tA, k)
.then(tAA, k)
.then(tAA_update, y2)
.then(determinant, k)
.then(tAAp_00, k)
.then(tAAp_11, k)
.then(tAAp_01, k)
.then(tAAp_10, k)
.then(X, k)
.then(pinvA, k)
.then(pinvA_update, y1)
.then(nu, k)
.then(nu_update, x1)
.then(u, k)
.then(v, k);
// Buffer allocation and mapping computations to buffers
buffer b_SIZES("b_SIZES", {2}, p_int32, a_input);
buffer b_im1("b_im1", {N0, N1}, p_uint8, a_input);
buffer b_im2("b_im2", {N0, N1}, p_uint8, a_input);
buffer b_Ix_m("b_Ix_m", {N0, N1}, p_float32, a_output);
buffer b_Iy_m("b_Iy_m", {N0, N1}, p_float32, a_output);
buffer b_It_m("b_It_m", {N0, N1}, p_float32, a_output);
buffer b_C1("b_C1", {NC}, p_int32, a_input);
buffer b_C2("b_C2", {NC}, p_int32, a_input);
buffer b_i("b_i", {1}, p_int32, a_temporary);
buffer b_j("b_j", {1}, p_int32, a_temporary);
buffer b_A("b_A", {4*w*w, 2}, p_float32, a_output);
buffer b_b("b_b", {4*w*w}, p_float32, a_temporary);
buffer b_tA("b_tA", {2, 4*w*w}, p_float32, a_output);
buffer b_tAA("b_tAA", {2, 2}, p_float32, a_output);
buffer b_determinant("b_determinant", {1}, p_float64, a_output);
buffer b_X("b_X", {2, 2}, p_float64, a_output);
buffer b_pinvA("b_pinvA", {2, 4*w*w}, p_float64, a_output);
buffer b_nu("b_nu", {2}, p_float32, a_temporary);
buffer b_u("b_u", {NC}, p_float32, a_output);
buffer b_v("b_v", {NC}, p_float32, a_output);
SIZES.store_in(&b_SIZES);
im1.store_in(&b_im1);
im2.store_in(&b_im2);
Ix_m.store_in(&b_Ix_m);
Iy_m.store_in(&b_Iy_m);
It_m.store_in(&b_It_m);
C1.store_in(&b_C1);
C2.store_in(&b_C2);
i.store_in(&b_i, {0});
j.store_in(&b_j, {0});
A1.store_in(&b_A, {xp+yp*2*w, 0});
A1_right.store_in(&b_A, {xp+yp*2*w, 1});
b1.store_in(&b_b, {xp+yp*2*w});
A.store_in(&b_A, {y1, x1});
b.store_in(&b_b, {y1});
tA.store_in(&b_tA, {x1, y1});
tAA.store_in(&b_tAA, {x1, y2});
tAA_update.store_in(&b_tAA, {x1, y2});
determinant.store_in(&b_determinant, {0});
tAAp_00.store_in(&b_X, {0, 0});
tAAp_01.store_in(&b_X, {0, 1});
tAAp_10.store_in(&b_X, {1, 0});
tAAp_11.store_in(&b_X, {1, 1});
X.store_in(&b_X, {x1, y2});
pinvA.store_in(&b_pinvA, {x1, y1});
pinvA_update.store_in(&b_pinvA, {x1, y1});
nu.store_in(&b_nu, {x1});
nu_update.store_in(&b_nu, {x1});
u.store_in(&b_u, {k});
v.store_in(&b_v, {k});
tiramisu::codegen({&b_SIZES, &b_im1, &b_im2, &b_Ix_m, &b_Iy_m, &b_It_m, &b_C1, &b_C2, &b_u, &b_v, &b_A, &b_pinvA, &b_determinant, &b_tAA, &b_tA, &b_X}, "build/generated_fct_optical_flow.o");
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>Fix clang build?<commit_after><|endoftext|> |
<commit_before>#include "thin-stack.h"
using namespace std;
namespace k = kernels;
ThinStack::ThinStack(ModelSpec spec, ThinStackParameters params,
cublasHandle_t handle)
: spec(spec), params(params), stack_size(spec.seq_length), handle(handle) {
stack_total_size = (stack_size * spec.batch_size) * spec.model_dim;
buffer_total_size = spec.batch_size * spec.seq_length * spec.model_dim;
queue_total_size = spec.batch_size * spec.seq_length;
cursors_total_size = spec.batch_size;
// Pre-allocate auxiliary data structures.
cout << stack << endl;
cudaMalloc(&stack, stack_total_size * sizeof(float));
cout << stack << endl;
cudaMalloc(&queue, queue_total_size * sizeof(float));
cudaMalloc(&cursors, cursors_total_size * sizeof(float));
cudaMalloc(&buffer, buffer_total_size * sizeof(int));
// Pre-allocate temporary containers.
cudaMalloc(&buffer_top_idxs_t, spec.batch_size * sizeof(int));
cudaMalloc(&buffer_top_t, spec.batch_size * spec.model_dim * sizeof(float));
cudaMalloc(&stack_1_ptrs, spec.batch_size * sizeof(int));
cudaMalloc(&stack_2_ptrs, spec.batch_size * sizeof(int));
cudaMalloc(&push_output, spec.batch_size * spec.model_dim * sizeof(int));
cudaMalloc(&merge_output, spec.batch_size * spec.model_dim * sizeof(int));
// Pre-allocate accumulators.
cudaMalloc(&buffer_cur_t, spec.batch_size * sizeof(float));
}
ThinStack::init_helpers() {
cudaMalloc(&batch_ones, spec.batch_size * sizeof(int));
cudaMemset(batch_ones, 1, spec.batch_size * sizeof(int));
}
ThinStack::~ThinStack() {
cudaFree(stack);
cudaFree(queue);
cudaFree(cursors);
cudaFree(buffer);
cudaFree(buffer_top_idxs_t);
cudaFree(buffer_top_t);
cudaFree(stack_1_ptrs);
cudaFree(stack_2_ptrs);
cudaFree(push_output);
cudaFree(merge_output);
cudaFree(buffer_cur_t);
}
ThinStack::forward() {
for (int t = 0; t < spec.seq_length; t++) {
step(t);
}
}
ThinStack::step(int t) {
// TODO sync after kernel calls.
// Extract top buffer values.
// TODO subtensor with idxs buffer_cur_t + 0 * 1 + buffer_shift
// == buffer_cur_t * 1 + (batch_range * seq_length)
k::subtensor1(buffer_top_t, buffer, buffer_cur_t,
spec.batch_size, spec.model_dim, 0, spec.seq_length,
batch_range);
// stack_2_ptrs = (cursors - 1) + batch_range * seq_length
k::subtensor1(stack_2_ptrs, queue, cursors, -1, spec.seq_length,
batch_range);
// stack_2_ptrs = stack_2_ptrs * batch_size + batch_range * 1
k::addi_vv(stack_2_ptrs, batch_range, batch_size, 1);
// stack_1, stack_2
k::subtensor1(stack_1_t, stack, batch_range, spec.batch_size,
spec.model_dim, (t - 1) * spec.batch_size);
k::subtensor1(stack_2_t, stack, stack_2_ptrs, spec.batch_size,
spec.model_dim, 0, 0, NULL);
// Run recurrence, which writes into `push_output`, `merge_output`.
recurrence(stack_1_t, stack_2_t, buffer_top_t);
// Write in the next stack top.
mask_and_update_stack(t * spec.batch_size, buffer_top_t, merge_output,
transitions, t);
// cursors += 1 - 2*mask
mask_and_update_cursors(cursors, transitions, t);
// queue[cursors + 0 + batch_range * spec.seq_length] = t
k::set_subtensor1i_s(queue, t, cursors, spec.batch_size, 0, spec.spec_length,
batch_range);
// buffer_cur += (1 - transitions)
update_buffer_cur(buffer_cur_t, transitions, t);
}
ThinStack::recurrence(const float *stack_1_t, const float *stack_2_t,
const float *buffer_top_t) {
// merge_out = W_l l
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, spec.model_dim, spec.batch_size,
spec.model_dim, 1.0, params.W_l, spec.model_dim, stack_2_t,
spec.model_dim, 0.0, merge_output, spec.model_dim);
// merge_out += W_r r
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, spec.model_dim, spec.batch_size,
spec.model_dim, 1.0, params.W_r, spec.model_dim, stack_1_t,
spec.model_dim, 1.0, merge_output, spec.model_dim);
// TODO bias (broadcast-add)
// TODO relu
}
ThinStack::mask_and_update_stack(const int *stack_top_ptrs,
const float *push_value, const float *merge_value, const int *transitions,
int t) {
// TODO
}
ThinStack::mask_and_update_cursors(float *cursors, const int *transitions,
int t) {
// TODO
}
ThinStack::update_buffer_cur(int *buffer_cur_t, int *transitions, int t) {
// TODO
}
ThinStack::zero() {
cudaMemset(stack, 0, stack_total_size * sizeof(float));
cudaMemset(queue, 0, queue_total_size * sizeof(float));
cudaMemset(cursors, 0, cursors_total_size * sizeof(float));
cudaMemset(buffer_cur_t, 0, spec.batch_size * sizeof(float));
}
<commit_msg>Actually include mask_and_update_stack<commit_after>#include "thin-stack.h"
using namespace std;
namespace k = kernels;
ThinStack::ThinStack(ModelSpec spec, ThinStackParameters params,
cublasHandle_t handle)
: spec(spec), params(params), stack_size(spec.seq_length), handle(handle) {
stack_total_size = (stack_size * spec.batch_size) * spec.model_dim;
buffer_total_size = spec.batch_size * spec.seq_length * spec.model_dim;
queue_total_size = spec.batch_size * spec.seq_length;
cursors_total_size = spec.batch_size;
// Pre-allocate auxiliary data structures.
cout << stack << endl;
cudaMalloc(&stack, stack_total_size * sizeof(float));
cout << stack << endl;
cudaMalloc(&queue, queue_total_size * sizeof(float));
cudaMalloc(&cursors, cursors_total_size * sizeof(float));
cudaMalloc(&buffer, buffer_total_size * sizeof(int));
// Pre-allocate temporary containers.
cudaMalloc(&buffer_top_idxs_t, spec.batch_size * sizeof(int));
cudaMalloc(&buffer_top_t, spec.batch_size * spec.model_dim * sizeof(float));
cudaMalloc(&stack_1_ptrs, spec.batch_size * sizeof(int));
cudaMalloc(&stack_2_ptrs, spec.batch_size * sizeof(int));
cudaMalloc(&push_output, spec.batch_size * spec.model_dim * sizeof(int));
cudaMalloc(&merge_output, spec.batch_size * spec.model_dim * sizeof(int));
// Pre-allocate accumulators.
cudaMalloc(&buffer_cur_t, spec.batch_size * sizeof(float));
}
ThinStack::init_helpers() {
cudaMalloc(&batch_ones, spec.batch_size * sizeof(int));
cudaMemset(batch_ones, 1, spec.batch_size * sizeof(int));
}
ThinStack::~ThinStack() {
cudaFree(stack);
cudaFree(queue);
cudaFree(cursors);
cudaFree(buffer);
cudaFree(buffer_top_idxs_t);
cudaFree(buffer_top_t);
cudaFree(stack_1_ptrs);
cudaFree(stack_2_ptrs);
cudaFree(push_output);
cudaFree(merge_output);
cudaFree(buffer_cur_t);
}
ThinStack::forward() {
for (int t = 0; t < spec.seq_length; t++) {
step(t);
}
}
ThinStack::step(int t) {
// TODO sync after kernel calls.
// Extract top buffer values.
// TODO subtensor with idxs buffer_cur_t + 0 * 1 + buffer_shift
// == buffer_cur_t * 1 + (batch_range * seq_length)
k::subtensor1(buffer_top_t, buffer, buffer_cur_t,
spec.batch_size, spec.model_dim, 0, spec.seq_length,
batch_range);
// stack_2_ptrs = (cursors - 1) + batch_range * seq_length
k::subtensor1(stack_2_ptrs, queue, cursors, -1, spec.seq_length,
batch_range);
// stack_2_ptrs = stack_2_ptrs * batch_size + batch_range * 1
k::addi_vv(stack_2_ptrs, batch_range, batch_size, 1);
// stack_1, stack_2
k::subtensor1(stack_1_t, stack, batch_range, spec.batch_size,
spec.model_dim, (t - 1) * spec.batch_size);
k::subtensor1(stack_2_t, stack, stack_2_ptrs, spec.batch_size,
spec.model_dim, 0, 0, NULL);
// Run recurrence, which writes into `push_output`, `merge_output`.
recurrence(stack_1_t, stack_2_t, buffer_top_t);
// Write in the next stack top.
mask_and_update_stack(t * spec.batch_size, buffer_top_t, merge_output,
transitions, t);
// cursors += 1 - 2*mask
mask_and_update_cursors(cursors, transitions, t);
// queue[cursors + 0 + batch_range * spec.seq_length] = t
k::set_subtensor1i_s(queue, t, cursors, spec.batch_size, 0, spec.spec_length,
batch_range);
// buffer_cur += (1 - transitions)
update_buffer_cur(buffer_cur_t, transitions, t);
}
ThinStack::recurrence(const float *stack_1_t, const float *stack_2_t,
const float *buffer_top_t) {
// merge_out = W_l l
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, spec.model_dim, spec.batch_size,
spec.model_dim, 1.0, params.W_l, spec.model_dim, stack_2_t,
spec.model_dim, 0.0, merge_output, spec.model_dim);
// merge_out += W_r r
cublasSgemm(handle, CUBLAS_OP_N, CUBLAS_OP_N, spec.model_dim, spec.batch_size,
spec.model_dim, 1.0, params.W_r, spec.model_dim, stack_1_t,
spec.model_dim, 1.0, merge_output, spec.model_dim);
// TODO bias (broadcast-add)
// TODO relu
}
ThinStack::mask_and_update_stack(const float *push_value,
const float *merge_value, const int *transitions, int t) {
// Find start position of write destination (next-top corresponding to
// timestep `t`).
int stack_offset = t * spec.batch_size * spec.model_dim;
k::switch_m(&stack[stack_offset], transitions, merge_value, push_value,
spec.batch_size, spec.model_dim);
}
ThinStack::mask_and_update_cursors(float *cursors, const int *transitions,
int t) {
// TODO
}
ThinStack::update_buffer_cur(int *buffer_cur_t, int *transitions, int t) {
// TODO
}
ThinStack::zero() {
cudaMemset(stack, 0, stack_total_size * sizeof(float));
cudaMemset(queue, 0, queue_total_size * sizeof(float));
cudaMemset(cursors, 0, cursors_total_size * sizeof(float));
cudaMemset(buffer_cur_t, 0, spec.batch_size * sizeof(float));
}
<|endoftext|> |
<commit_before>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_simple_reshape()
{
Tensor<float, 5> tensor1(2,3,1,7,1);
tensor1.setRandom();
Tensor<float, 3> tensor2(2,3,7);
Tensor<float, 2> tensor3(6,7);
Tensor<float, 2> tensor4(2,21);
Tensor<float, 3>::Dimensions dim1{{2,3,7}};
tensor2 = tensor1.reshape(dim1);
Tensor<float, 2>::Dimensions dim2{{6,7}};
tensor3 = tensor1.reshape(dim2);
Tensor<float, 2>::Dimensions dim3{{2,21}};
tensor4 = tensor1.reshape(dim1).reshape(dim3);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(tensor1(i,j,0,k,0), tensor2(i,j,k));
VERIFY_IS_EQUAL(tensor1(i,j,0,k,0), tensor3(i+2*j,k));
VERIFY_IS_EQUAL(tensor1(i,j,0,k,0), tensor4(i,j+3*k));
}
}
}
}
static void test_reshape_in_expr() {
MatrixXf m1(2,3*5*7*11);
MatrixXf m2(3*5*7*11,13);
m1.setRandom();
m2.setRandom();
MatrixXf m3 = m1 * m2;
TensorMap<Tensor<float, 5>> tensor1(m1.data(), 2,3,5,7,11);
TensorMap<Tensor<float, 5>> tensor2(m2.data(), 3,5,7,11,13);
Tensor<float, 2>::Dimensions newDims1{{2,3*5*7*11}};
Tensor<float, 2>::Dimensions newDims2{{3*5*7*11,13}};
typedef Tensor<float, 1>::DimensionPair DimPair;
array<DimPair, 1> contract_along{{DimPair(1, 0)}};
Tensor<float, 2> tensor3(2,13);
tensor3 = tensor1.reshape(newDims1).contract(tensor2.reshape(newDims2), contract_along);
Map<MatrixXf> res(tensor3.data(), 2, 13);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 13; ++j) {
VERIFY_IS_APPROX(res(i,j), m3(i,j));
}
}
}
void test_cxx11_tensor_morphing()
{
CALL_SUBTEST(test_simple_reshape());
CALL_SUBTEST(test_reshape_in_expr());
}
<commit_msg>Added tests for tensor slicing<commit_after>// This file is part of Eigen, a lightweight C++ template library
// for linear algebra.
//
// Copyright (C) 2014 Benoit Steiner <benoit.steiner.goog@gmail.com>
//
// This Source Code Form is subject to the terms of the Mozilla
// Public License v. 2.0. If a copy of the MPL was not distributed
// with this file, You can obtain one at http://mozilla.org/MPL/2.0/.
#include "main.h"
#include <Eigen/CXX11/Tensor>
using Eigen::Tensor;
static void test_simple_reshape()
{
Tensor<float, 5> tensor1(2,3,1,7,1);
tensor1.setRandom();
Tensor<float, 3> tensor2(2,3,7);
Tensor<float, 2> tensor3(6,7);
Tensor<float, 2> tensor4(2,21);
Tensor<float, 3>::Dimensions dim1{{2,3,7}};
tensor2 = tensor1.reshape(dim1);
Tensor<float, 2>::Dimensions dim2{{6,7}};
tensor3 = tensor1.reshape(dim2);
Tensor<float, 2>::Dimensions dim3{{2,21}};
tensor4 = tensor1.reshape(dim1).reshape(dim3);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(tensor1(i,j,0,k,0), tensor2(i,j,k));
VERIFY_IS_EQUAL(tensor1(i,j,0,k,0), tensor3(i+2*j,k));
VERIFY_IS_EQUAL(tensor1(i,j,0,k,0), tensor4(i,j+3*k));
}
}
}
}
static void test_reshape_in_expr() {
MatrixXf m1(2,3*5*7*11);
MatrixXf m2(3*5*7*11,13);
m1.setRandom();
m2.setRandom();
MatrixXf m3 = m1 * m2;
TensorMap<Tensor<float, 5>> tensor1(m1.data(), 2,3,5,7,11);
TensorMap<Tensor<float, 5>> tensor2(m2.data(), 3,5,7,11,13);
Tensor<float, 2>::Dimensions newDims1{{2,3*5*7*11}};
Tensor<float, 2>::Dimensions newDims2{{3*5*7*11,13}};
array<Tensor<float, 1>::DimensionPair, 1> contract_along{{1, 0}};
Tensor<float, 2> tensor3(2,13);
tensor3 = tensor1.reshape(newDims1).contract(tensor2.reshape(newDims2), contract_along);
Map<MatrixXf> res(tensor3.data(), 2, 13);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 13; ++j) {
VERIFY_IS_APPROX(res(i,j), m3(i,j));
}
}
}
static void test_reshape_as_lvalue()
{
Tensor<float, 3> tensor(2,3,7);
tensor.setRandom();
Tensor<float, 2> tensor2d(6,7);
Tensor<float, 3>::Dimensions dim{{2,3,7}};
tensor2d.reshape(dim) = tensor;
Tensor<float, 5> tensor5d(2,3,1,7,1);
tensor5d.reshape(dim).device(Eigen::DefaultDevice()) = tensor;
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 3; ++j) {
for (int k = 0; k < 7; ++k) {
VERIFY_IS_EQUAL(tensor2d(i+2*j,k), tensor(i,j,k));
VERIFY_IS_EQUAL(tensor5d(i,j,0,k,0), tensor(i,j,k));
}
}
}
}
static void test_simple_slice()
{
Tensor<float, 5> tensor(2,3,5,7,11);
tensor.setRandom();
Tensor<float, 5> slice1(1,1,1,1,1);
Eigen::DSizes<ptrdiff_t, 5> indices(Eigen::array<ptrdiff_t, 5>(1,2,3,4,5));
Eigen::DSizes<ptrdiff_t, 5> sizes(Eigen::array<ptrdiff_t, 5>(1,1,1,1,1));
slice1 = tensor.slice(indices, sizes);
VERIFY_IS_EQUAL(slice1(0,0,0,0,0), tensor(1,2,3,4,5));
Tensor<float, 5> slice2(1,1,2,2,3);
Eigen::DSizes<ptrdiff_t, 5> indices2(Eigen::array<ptrdiff_t, 5>(1,1,3,4,5));
Eigen::DSizes<ptrdiff_t, 5> sizes2(Eigen::array<ptrdiff_t, 5>(1,1,2,2,3));
slice2 = tensor.slice(indices2, sizes2);
for (int i = 0; i < 2; ++i) {
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 3; ++k) {
VERIFY_IS_EQUAL(slice2(0,0,i,j,k), tensor(1,1,3+i,4+j,5+k));
}
}
}
}
static void test_slice_in_expr() {
MatrixXf m1(7,7);
MatrixXf m2(3,3);
m1.setRandom();
m2.setRandom();
MatrixXf m3 = m1.block(1, 2, 3, 3) * m2.block(0, 2, 3, 1);
TensorMap<Tensor<float, 2>> tensor1(m1.data(), 7, 7);
TensorMap<Tensor<float, 2>> tensor2(m2.data(), 3, 3);
Tensor<float, 2> tensor3(3,1);
array<Tensor<float, 1>::DimensionPair, 1> contract_along{{1, 0}};
Eigen::DSizes<ptrdiff_t, 2> indices1(Eigen::array<ptrdiff_t, 2>(1,2));
Eigen::DSizes<ptrdiff_t, 2> sizes1(Eigen::array<ptrdiff_t, 2>(3,3));
Eigen::DSizes<ptrdiff_t, 2> indices2(Eigen::array<ptrdiff_t, 2>(0,2));
Eigen::DSizes<ptrdiff_t, 2> sizes2(Eigen::array<ptrdiff_t, 2>(3,1));
tensor3 = tensor1.slice(indices1, sizes1).contract(tensor2.slice(indices2, sizes2), contract_along);
Map<MatrixXf> res(tensor3.data(), 3, 1);
for (int i = 0; i < 3; ++i) {
for (int j = 0; j < 1; ++j) {
VERIFY_IS_APPROX(res(i,j), m3(i,j));
}
}
}
static void test_slice_as_lvalue()
{
Tensor<float, 3> tensor1(2,2,7);
tensor1.setRandom();
Tensor<float, 3> tensor2(2,2,7);
tensor2.setRandom();
Tensor<float, 3> tensor3(4,3,5);
tensor3.setRandom();
Tensor<float, 3> tensor4(4,3,2);
tensor4.setRandom();
Tensor<float, 3> result(4,5,7);
Eigen::DSizes<ptrdiff_t, 3> sizes12(Eigen::array<ptrdiff_t, 3>(2,2,7));
Eigen::DSizes<ptrdiff_t, 3> first_slice(Eigen::array<ptrdiff_t, 3>(0,0,0));
result.slice(first_slice, sizes12) = tensor1;
Eigen::DSizes<ptrdiff_t, 3> second_slice(Eigen::array<ptrdiff_t, 3>(2,0,0));
result.slice(second_slice, sizes12).device(Eigen::DefaultDevice()) = tensor2;
Eigen::DSizes<ptrdiff_t, 3> sizes3(Eigen::array<ptrdiff_t, 3>(4,3,5));
Eigen::DSizes<ptrdiff_t, 3> third_slice(Eigen::array<ptrdiff_t, 3>(0,2,0));
result.slice(third_slice, sizes3) = tensor3;
Eigen::DSizes<ptrdiff_t, 3> sizes4(Eigen::array<ptrdiff_t, 3>(4,3,2));
Eigen::DSizes<ptrdiff_t, 3> fourth_slice(Eigen::array<ptrdiff_t, 3>(0,2,5));
result.slice(fourth_slice, sizes4) = tensor4;
for (int j = 0; j < 2; ++j) {
for (int k = 0; k < 7; ++k) {
for (int i = 0; i < 2; ++i) {
VERIFY_IS_EQUAL(result(i,j,k), tensor1(i,j,k));
VERIFY_IS_EQUAL(result(i+2,j,k), tensor2(i,j,k));
}
}
}
for (int i = 0; i < 4; ++i) {
for (int j = 2; j < 5; ++j) {
for (int k = 0; k < 5; ++k) {
VERIFY_IS_EQUAL(result(i,j,k), tensor3(i,j-2,k));
}
for (int k = 5; k < 7; ++k) {
VERIFY_IS_EQUAL(result(i,j,k), tensor4(i,j-2,k-5));
}
}
}
}
void test_cxx11_tensor_morphing()
{
CALL_SUBTEST(test_simple_reshape());
CALL_SUBTEST(test_reshape_in_expr());
CALL_SUBTEST(test_reshape_as_lvalue());
CALL_SUBTEST(test_simple_slice());
CALL_SUBTEST(test_slice_in_expr());
CALL_SUBTEST(test_slice_as_lvalue());
}
<|endoftext|> |
<commit_before>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <utility>
#include <map>
#include <iomanip>
#include <cstring>
#include <ArgumentList.hpp>
#include <utils.hpp>
int main(int argc, char * argv[]) {
// DMs
unsigned int nrDMs = 0;
float firstDM = 0.0f;
float stepDM = 0.0f;
// Periods
unsigned int nrPeriods = 0;
unsigned int firstPeriod = 0;
unsigned int stepPeriod = 0;
// Sampling
unsigned int nrSamplesPerSecond = 0;
// I/O
std::string outFilename;
std::ifstream searchFile;
std::ofstream outFile;
// Data
bool exclusive = false;
bool * exclusionMapDM = 0;
bool * exclusionMapP = 0;
float percentile = 0;
std::multimap< float, std::pair< unsigned int, unsigned int > > snrList;
isa::utils::ArgumentList args(argc, argv);
try {
exclusive = args.getSwitch("-exclusive");
if ( exclusive ) {
nrDMs = args.getSwitchArgument< unsigned int >("-dms");
nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
}
outFilename = args.getSwitchArgument< std::string >("-output");
firstDM = args.getSwitchArgument< float >("-dm_first");
stepDM = args.getSwitchArgument< float >("-dm_step");
firstPeriod = args.getSwitchArgument< unsigned int >("-period_first");
stepPeriod = args.getSwitchArgument< unsigned int >("-period_step");
nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples");
percentile = args.getSwitchArgument< float >("-percentile");
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl;
std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Read the SNR data
try {
while ( true ) {
searchFile.open(args.getFirst< std::string >());
while ( ! searchFile.eof() ) {
std::string temp;
unsigned int splitPoint = 0;
unsigned int DM = 0;
unsigned int period = 0;
float snr = 0.0f;
std::getline(searchFile, temp);
if ( ! std::isdigit(temp[0]) ) {
continue;
}
splitPoint = temp.find(" ");
period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
snr = isa::utils::castToType< std::string, float >(temp);
snrList.insert(std::make_pair(snr, std::make_pair(DM, period)));
}
searchFile.close();
}
} catch ( isa::utils::EmptyCommandLine & err ) {
}
// Print the percentile
unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0);
unsigned int counter = snrList.size() - 1;
if ( exclusive ) {
exclusionMapDM = new bool [nrDMs];
std::memset(reinterpret_cast< void * >(exclusionMapDM), 0, nrDMs * sizeof(bool));
exclusionMapP = new bool [nrPeriods];
std::memset(reinterpret_cast< void * >(exclusionMapP), 0, nrDMs * sizeof(bool));
}
outFile.open(outFilename);
outFile << std::fixed;
outFile << "# DMIndex DM periodIndex period snr" << std::endl;
for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) {
++item;
if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) {
continue;
} else if ( exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second] ) {
exclusionMapDM[(*item).second.first] = true;
exclusionMapP[(*item).second.second] = true;
}
outFile << std::setprecision(2);
outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " ";
outFile << std::setprecision(6);
outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " ";
outFile << (*item).first << std::endl;
}
delete [] exclusionMapDM;
delete [] exclusionMapP;
outFile.close();
return 0;
}
<commit_msg>Fixing a bug.<commit_after>// Copyright 2014 Alessio Sclocco <a.sclocco@vu.nl>
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <iostream>
#include <fstream>
#include <exception>
#include <string>
#include <utility>
#include <map>
#include <iomanip>
#include <cstring>
#include <ArgumentList.hpp>
#include <utils.hpp>
int main(int argc, char * argv[]) {
// DMs
unsigned int nrDMs = 0;
float firstDM = 0.0f;
float stepDM = 0.0f;
// Periods
unsigned int nrPeriods = 0;
unsigned int firstPeriod = 0;
unsigned int stepPeriod = 0;
// Sampling
unsigned int nrSamplesPerSecond = 0;
// I/O
std::string outFilename;
std::ifstream searchFile;
std::ofstream outFile;
// Data
bool exclusive = false;
bool * exclusionMapDM = 0;
bool * exclusionMapP = 0;
float percentile = 0;
std::multimap< float, std::pair< unsigned int, unsigned int > > snrList;
isa::utils::ArgumentList args(argc, argv);
try {
exclusive = args.getSwitch("-exclusive");
if ( exclusive ) {
nrDMs = args.getSwitchArgument< unsigned int >("-dms");
nrPeriods = args.getSwitchArgument< unsigned int >("-periods");
}
outFilename = args.getSwitchArgument< std::string >("-output");
firstDM = args.getSwitchArgument< float >("-dm_first");
stepDM = args.getSwitchArgument< float >("-dm_step");
firstPeriod = args.getSwitchArgument< unsigned int >("-period_first");
stepPeriod = args.getSwitchArgument< unsigned int >("-period_step");
nrSamplesPerSecond = args.getSwitchArgument< unsigned int >("-samples");
percentile = args.getSwitchArgument< float >("-percentile");
} catch ( isa::utils::EmptyCommandLine & err ) {
std::cerr << args.getName() << " [-exclusive] -output ... -dm_first ... -dm_step ... -period_first ... -period_step ... -samples ... -percentile ... input" << std::endl;
std::cerr << "\t -exclusive -dms ... -periods ..." << std::endl;
return 1;
} catch ( std::exception & err ) {
std::cerr << err.what() << std::endl;
return 1;
}
// Read the SNR data
try {
while ( true ) {
searchFile.open(args.getFirst< std::string >());
while ( ! searchFile.eof() ) {
std::string temp;
unsigned int splitPoint = 0;
unsigned int DM = 0;
unsigned int period = 0;
float snr = 0.0f;
std::getline(searchFile, temp);
if ( ! std::isdigit(temp[0]) ) {
continue;
}
splitPoint = temp.find(" ");
period = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
DM = isa::utils::castToType< std::string, unsigned int >(temp.substr(0, splitPoint));
temp = temp.substr(splitPoint + 1);
splitPoint = temp.find(" ");
snr = isa::utils::castToType< std::string, float >(temp);
snrList.insert(std::make_pair(snr, std::make_pair(DM, period)));
}
searchFile.close();
}
} catch ( isa::utils::EmptyCommandLine & err ) {
}
// Print the percentile
unsigned int lowerLimit = static_cast< unsigned int >((percentile * snrList.size()) / 100.0);
unsigned int counter = snrList.size() - 1;
if ( exclusive ) {
exclusionMapDM = new bool [nrDMs];
std::memset(reinterpret_cast< void * >(exclusionMapDM), 0, nrDMs * sizeof(bool));
exclusionMapP = new bool [nrPeriods];
std::memset(reinterpret_cast< void * >(exclusionMapP), 0, nrDMs * sizeof(bool));
}
outFile.open(outFilename);
outFile << std::fixed;
outFile << "# DMIndex DM periodIndex period snr" << std::endl;
for ( std::multimap< float, std::pair< unsigned int, unsigned int> >::const_reverse_iterator item = snrList.crend(); counter >= lowerLimit; counter-- ) {
++item;
if ( exclusive && (exclusionMapDM[(*item).second.first] || exclusionMapP[(*item).second.second]) ) {
continue;
}
outFile << std::setprecision(2);
outFile << (*item).second.first << " " << firstDM + ((*item).second.first * stepDM) << " ";
outFile << std::setprecision(6);
outFile << (*item).second.second << " " << (firstPeriod + ((*item).second.second * stepPeriod)) / static_cast< float >(nrSamplesPerSecond) << " ";
outFile << (*item).first << std::endl;
if ( exclusive ) {
exclusionMapDM[(*item).second.first] = true;
exclusionMapP[(*item).second.second] = true;
}
}
delete [] exclusionMapDM;
delete [] exclusionMapP;
outFile.close();
return 0;
}
<|endoftext|> |
<commit_before><commit_msg>dpl: coverity fixes<commit_after><|endoftext|> |
<commit_before>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "Interface/Thread.h"
#include "ThreadPool.h"
#include "Server.h"
CPoolThread::CPoolThread(CThreadPool *pMgr)
{
mgr=pMgr;
dexit=false;
}
void CPoolThread::operator()(void)
{
THREAD_ID tid = Server->getThreadID();
THREADPOOL_TICKET ticket;
IThread *tr=mgr->getRunnable(&ticket, false);
if(tr!=NULL)
(*tr)();
while(dexit==false)
{
IThread *tr=mgr->getRunnable(&ticket, true);
if(tr!=NULL)
{
(*tr)();
Server->clearDatabases(tid);
}
}
mgr->Remove(this);
delete this;
}
void CPoolThread::shutdown(void)
{
dexit=true;
}
IThread * CThreadPool::getRunnable(THREADPOOL_TICKET *todel, bool del)
{
IScopedLock lock(mutex);
if( del==true )
{
--nRunning;
std::map<THREADPOOL_TICKET, ICondition *>::iterator it=running.find(*todel);
if( it!=running.end() )
{
if( it->second!=NULL )
it->second->notify_all();
running.erase(it);
}
}
IThread *ret=NULL;
while(ret==NULL && dexit==false)
{
if( toexecute.size()==0)
cond->wait(&lock);
else
{
ret=toexecute[0].first;
*todel=toexecute[0].second;
toexecute.erase( toexecute.begin() );
}
}
return ret;
}
void CThreadPool::Remove(CPoolThread *pt)
{
IScopedLock lock(mutex);
for(size_t i=0;i<threads.size();++i)
{
if( threads[i]==pt )
{
threads.erase( threads.begin()+i);
return;
}
}
}
CThreadPool::CThreadPool()
{
nRunning=0;
nThreads=0;
currticket=0;
dexit=false;
mutex=Server->createMutex();
cond=Server->createCondition();
}
CThreadPool::~CThreadPool()
{
delete mutex;
delete cond;
}
void CThreadPool::Shutdown(void)
{
bool do_leak_check=(Server->getServerParameter("leak_check")=="true");
IScopedLock lock(mutex);
for(size_t i=0;i<threads.size();++i)
{
threads[i]->shutdown();
}
dexit=true;
unsigned int max=0;
while(threads.size()>0 )
{
lock.relock(NULL);
cond->notify_all();
Server->wait(100);
lock.relock(mutex);
//wait for max 300 msec
if( (!do_leak_check && max>=3) || (do_leak_check && max>=30) )
{
Server->Log("Maximum wait time for thread pool exceeded. Shutting down the hard way", LL_ERROR);
break;
}
++max;
}
}
bool CThreadPool::isRunningInt(THREADPOOL_TICKET ticket)
{
std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(ticket);
if( it!=running.end() )
return true;
else
return false;
}
bool CThreadPool::isRunning(THREADPOOL_TICKET ticket)
{
IScopedLock lock(mutex);
return isRunningInt(ticket);
}
void CThreadPool::waitFor(std::vector<THREADPOOL_TICKET> tickets)
{
IScopedLock lock(mutex);
ICondition *cond=Server->createCondition();
for( size_t i=0;i<tickets.size();++i)
{
std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(tickets[i]);
if( it!=running.end() )
{
it->second=cond;
}
}
while(true)
{
bool r=false;
for(size_t i=0;i<tickets.size();++i)
{
if( isRunningInt(tickets[i])==true )
{
r=true;
break;
}
}
if( r==false )
break;
cond->wait(&lock);
}
Server->destroy(cond);
}
THREADPOOL_TICKET CThreadPool::execute(IThread *runnable)
{
IScopedLock lock(mutex);
if( nThreads-nRunning==0 )
{
CPoolThread *nt=new CPoolThread(this);
Server->createThread(nt);
++nThreads;
threads.push_back(nt);
}
toexecute.push_back(std::pair<IThread*, THREADPOOL_TICKET>(runnable, ++currticket) );
running.insert(std::pair<THREADPOOL_TICKET, ICondition*>(currticket, nullptr) );
++nRunning;
cond->notify_one();
return currticket;
}
void CThreadPool::executeWait(IThread *runnable)
{
THREADPOOL_TICKET ticket=execute(runnable);
waitFor(ticket);
}
void CThreadPool::waitFor(THREADPOOL_TICKET ticket)
{
std::vector<THREADPOOL_TICKET> t;
t.push_back(ticket);
waitFor(t);
}
<commit_msg>Actually remove nullptr usage<commit_after>/*************************************************************************
* UrBackup - Client/Server backup system
* Copyright (C) 2011 Martin Raiber
*
* This program is free software: you can redistribute it and/or modify
* it under the terms of the GNU General Public License as published by
* the Free Software Foundation, either version 3 of the License, or
* (at your option) any later version.
*
* This program is distributed in the hope that it will be useful,
* but WITHOUT ANY WARRANTY; without even the implied warranty of
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
* GNU General Public License for more details.
*
* You should have received a copy of the GNU General Public License
* along with this program. If not, see <http://www.gnu.org/licenses/>.
**************************************************************************/
#include "Interface/Thread.h"
#include "ThreadPool.h"
#include "Server.h"
CPoolThread::CPoolThread(CThreadPool *pMgr)
{
mgr=pMgr;
dexit=false;
}
void CPoolThread::operator()(void)
{
THREAD_ID tid = Server->getThreadID();
THREADPOOL_TICKET ticket;
IThread *tr=mgr->getRunnable(&ticket, false);
if(tr!=NULL)
(*tr)();
while(dexit==false)
{
IThread *tr=mgr->getRunnable(&ticket, true);
if(tr!=NULL)
{
(*tr)();
Server->clearDatabases(tid);
}
}
mgr->Remove(this);
delete this;
}
void CPoolThread::shutdown(void)
{
dexit=true;
}
IThread * CThreadPool::getRunnable(THREADPOOL_TICKET *todel, bool del)
{
IScopedLock lock(mutex);
if( del==true )
{
--nRunning;
std::map<THREADPOOL_TICKET, ICondition *>::iterator it=running.find(*todel);
if( it!=running.end() )
{
if( it->second!=NULL )
it->second->notify_all();
running.erase(it);
}
}
IThread *ret=NULL;
while(ret==NULL && dexit==false)
{
if( toexecute.size()==0)
cond->wait(&lock);
else
{
ret=toexecute[0].first;
*todel=toexecute[0].second;
toexecute.erase( toexecute.begin() );
}
}
return ret;
}
void CThreadPool::Remove(CPoolThread *pt)
{
IScopedLock lock(mutex);
for(size_t i=0;i<threads.size();++i)
{
if( threads[i]==pt )
{
threads.erase( threads.begin()+i);
return;
}
}
}
CThreadPool::CThreadPool()
{
nRunning=0;
nThreads=0;
currticket=0;
dexit=false;
mutex=Server->createMutex();
cond=Server->createCondition();
}
CThreadPool::~CThreadPool()
{
delete mutex;
delete cond;
}
void CThreadPool::Shutdown(void)
{
bool do_leak_check=(Server->getServerParameter("leak_check")=="true");
IScopedLock lock(mutex);
for(size_t i=0;i<threads.size();++i)
{
threads[i]->shutdown();
}
dexit=true;
unsigned int max=0;
while(threads.size()>0 )
{
lock.relock(NULL);
cond->notify_all();
Server->wait(100);
lock.relock(mutex);
//wait for max 300 msec
if( (!do_leak_check && max>=3) || (do_leak_check && max>=30) )
{
Server->Log("Maximum wait time for thread pool exceeded. Shutting down the hard way", LL_ERROR);
break;
}
++max;
}
}
bool CThreadPool::isRunningInt(THREADPOOL_TICKET ticket)
{
std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(ticket);
if( it!=running.end() )
return true;
else
return false;
}
bool CThreadPool::isRunning(THREADPOOL_TICKET ticket)
{
IScopedLock lock(mutex);
return isRunningInt(ticket);
}
void CThreadPool::waitFor(std::vector<THREADPOOL_TICKET> tickets)
{
IScopedLock lock(mutex);
ICondition *cond=Server->createCondition();
for( size_t i=0;i<tickets.size();++i)
{
std::map<THREADPOOL_TICKET, ICondition*>::iterator it=running.find(tickets[i]);
if( it!=running.end() )
{
it->second=cond;
}
}
while(true)
{
bool r=false;
for(size_t i=0;i<tickets.size();++i)
{
if( isRunningInt(tickets[i])==true )
{
r=true;
break;
}
}
if( r==false )
break;
cond->wait(&lock);
}
Server->destroy(cond);
}
THREADPOOL_TICKET CThreadPool::execute(IThread *runnable)
{
IScopedLock lock(mutex);
if( nThreads-nRunning==0 )
{
CPoolThread *nt=new CPoolThread(this);
Server->createThread(nt);
++nThreads;
threads.push_back(nt);
}
toexecute.push_back(std::pair<IThread*, THREADPOOL_TICKET>(runnable, ++currticket) );
running.insert(std::pair<THREADPOOL_TICKET, ICondition*>(currticket, NULL) );
++nRunning;
cond->notify_one();
return currticket;
}
void CThreadPool::executeWait(IThread *runnable)
{
THREADPOOL_TICKET ticket=execute(runnable);
waitFor(ticket);
}
void CThreadPool::waitFor(THREADPOOL_TICKET ticket)
{
std::vector<THREADPOOL_TICKET> t;
t.push_back(ticket);
waitFor(t);
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <utility>
#include <chrono>
#include <string>
#include "util/sstream.h"
#include "util/interrupt.h"
#include "util/lazy_list_fn.h"
#include "library/tactic/tactic_exception.h"
#include "library/tactic/tactic.h"
namespace lean {
tactic & tactic::operator=(tactic const & s) {
LEAN_COPY_REF(tactic, s);
}
tactic & tactic::operator=(tactic && s) {
LEAN_MOVE_REF(tactic, s);
}
expr tactic::solve(environment const & env, io_state const & io, proof_state const & s) {
proof_state_seq r = operator()(env, io, s);
auto p = r.pull();
if (!p)
throw exception("tactic failed to solve input");
proof_state final = p->first;
assignment a(final.get_menv());
proof_map m;
return final.get_proof_builder()(m, env, a);
}
expr tactic::solve(environment const & env, io_state const & io, context const & ctx, expr const & t) {
proof_state s = to_proof_state(env, ctx, t);
return solve(env, io, s);
}
tactic id_tactic() {
return mk_simple_tactic([](environment const &, io_state const &, proof_state const & s) -> proof_state {
return s;
});
}
tactic fail_tactic() {
return mk_tactic([](environment const &, io_state const &, proof_state const &) -> proof_state_seq {
return proof_state_seq();
});
}
tactic now_tactic() {
return mk_tactic([](environment const &, io_state const &, proof_state const & s) -> proof_state_seq {
if (!empty(s.get_goals()))
return proof_state_seq();
else
return to_proof_state_seq(s);
});
}
tactic trace_tactic(std::string const & msg) {
return mk_simple_tactic([=](environment const &, io_state const & io, proof_state const & s) -> proof_state {
io.get_diagnostic_channel() << msg << "\n";
io.get_diagnostic_channel().get_stream().flush();
return s;
});
}
tactic trace_tactic(sstream const & msg) {
return trace_tactic(msg.str());
}
tactic trace_tactic(char const * msg) {
return trace_tactic(std::string(msg));
}
tactic assumption_tactic() {
return mk_simple_tactic([](environment const &, io_state const &, proof_state const & s) -> proof_state {
list<std::pair<name, expr>> proofs;
goals new_goals = map_goals(s, [&](name const & ng, goal const & g) -> goal {
expr const & c = g.get_conclusion();
expr pr;
for (auto const & p : g.get_hypotheses()) {
check_interrupted();
if (p.second == c) {
pr = mk_constant(p.first);
break;
}
}
if (pr) {
proofs.emplace_front(ng, pr);
return goal();
} else {
return g;
}
});
proof_builder p = s.get_proof_builder();
proof_builder new_p = mk_proof_builder([=](proof_map const & m, environment const & env, assignment const & a) -> expr {
proof_map new_m(m);
for (auto const & np : proofs) {
new_m.insert(np.first, np.second);
}
return p(new_m, env, a);
});
return proof_state(s, new_goals, new_p);
});
}
tactic then(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s1) -> proof_state_seq {
tactic _t1(t1);
return map_append(_t1(env, io, s1), [=](proof_state const & s2) {
check_interrupted();
tactic _t2(t2);
return _t2(env, io, s2);
});
});
}
tactic orelse(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return orelse(_t1(env, io, s), _t2(env, io, s));
});
}
tactic try_for(tactic t, unsigned ms, unsigned check_ms) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t(t);
return timeout(_t(env, io, s), ms, check_ms);
});
}
tactic append(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return append(_t1(env, io, s), _t2(env, io, s));
});
}
tactic interleave(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return interleave(_t1(env, io, s), _t2(env, io, s));
});
}
tactic par(tactic t1, tactic t2, unsigned check_ms) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return par(_t1(env, io, s), _t2(env, io, s), check_ms);
});
}
tactic repeat(tactic t) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s1) -> proof_state_seq {
tactic t1(t);
proof_state_seq r = t1(env, io, s1);
// TODO(Leo): pull should be executed lazily
auto p = r.pull();
if (!p) {
return to_proof_state_seq(s1);
} else {
return map_append(to_proof_state_seq(p), [=](proof_state const & s2) {
check_interrupted();
tactic t2 = repeat(t1);
return t2(env, io, s2);
});
}
});
}
tactic repeat_at_most(tactic t, unsigned k) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s1) -> proof_state_seq {
if (k == 0)
return to_proof_state_seq(s1);
tactic t1(t);
proof_state_seq r = t1(env, io, s1);
// TODO(Leo): pull should be executed lazily
auto p = r.pull();
if (!p) {
return to_proof_state_seq(s1);
} else {
return map_append(to_proof_state_seq(p), [=](proof_state const & s2) {
check_interrupted();
tactic t2 = repeat_at_most(t1, k - 1);
return t2(env, io, s2);
});
}
});
}
tactic take(tactic t, unsigned k) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t(t);
return take(k, _t(env, io, s));
});
}
tactic force(tactic t) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t(t);
proof_state_seq r = _t(env, io, s);
buffer<proof_state> buf;
for_each(r, [&](proof_state const & s2) {
buf.push_back(s2);
check_interrupted();
});
return to_lazy(to_list(buf.begin(), buf.end()));
});
}
}
<commit_msg>feat(library/tactic): refine repeat and repeat_at_most tacticals<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <utility>
#include <chrono>
#include <string>
#include "util/sstream.h"
#include "util/interrupt.h"
#include "util/lazy_list_fn.h"
#include "library/tactic/tactic_exception.h"
#include "library/tactic/tactic.h"
namespace lean {
tactic & tactic::operator=(tactic const & s) {
LEAN_COPY_REF(tactic, s);
}
tactic & tactic::operator=(tactic && s) {
LEAN_MOVE_REF(tactic, s);
}
expr tactic::solve(environment const & env, io_state const & io, proof_state const & s) {
proof_state_seq r = operator()(env, io, s);
auto p = r.pull();
if (!p)
throw exception("tactic failed to solve input");
proof_state final = p->first;
assignment a(final.get_menv());
proof_map m;
return final.get_proof_builder()(m, env, a);
}
expr tactic::solve(environment const & env, io_state const & io, context const & ctx, expr const & t) {
proof_state s = to_proof_state(env, ctx, t);
return solve(env, io, s);
}
tactic id_tactic() {
return mk_simple_tactic([](environment const &, io_state const &, proof_state const & s) -> proof_state {
return s;
});
}
tactic fail_tactic() {
return mk_tactic([](environment const &, io_state const &, proof_state const &) -> proof_state_seq {
return proof_state_seq();
});
}
tactic now_tactic() {
return mk_tactic([](environment const &, io_state const &, proof_state const & s) -> proof_state_seq {
if (!empty(s.get_goals()))
return proof_state_seq();
else
return to_proof_state_seq(s);
});
}
tactic trace_tactic(std::string const & msg) {
return mk_simple_tactic([=](environment const &, io_state const & io, proof_state const & s) -> proof_state {
io.get_diagnostic_channel() << msg << "\n";
io.get_diagnostic_channel().get_stream().flush();
return s;
});
}
tactic trace_tactic(sstream const & msg) {
return trace_tactic(msg.str());
}
tactic trace_tactic(char const * msg) {
return trace_tactic(std::string(msg));
}
tactic assumption_tactic() {
return mk_simple_tactic([](environment const &, io_state const &, proof_state const & s) -> proof_state {
list<std::pair<name, expr>> proofs;
goals new_goals = map_goals(s, [&](name const & ng, goal const & g) -> goal {
expr const & c = g.get_conclusion();
expr pr;
for (auto const & p : g.get_hypotheses()) {
check_interrupted();
if (p.second == c) {
pr = mk_constant(p.first);
break;
}
}
if (pr) {
proofs.emplace_front(ng, pr);
return goal();
} else {
return g;
}
});
proof_builder p = s.get_proof_builder();
proof_builder new_p = mk_proof_builder([=](proof_map const & m, environment const & env, assignment const & a) -> expr {
proof_map new_m(m);
for (auto const & np : proofs) {
new_m.insert(np.first, np.second);
}
return p(new_m, env, a);
});
return proof_state(s, new_goals, new_p);
});
}
tactic then(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s1) -> proof_state_seq {
tactic _t1(t1);
return map_append(_t1(env, io, s1), [=](proof_state const & s2) {
check_interrupted();
tactic _t2(t2);
return _t2(env, io, s2);
});
});
}
tactic orelse(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return orelse(_t1(env, io, s), _t2(env, io, s));
});
}
tactic try_for(tactic t, unsigned ms, unsigned check_ms) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t(t);
return timeout(_t(env, io, s), ms, check_ms);
});
}
tactic append(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return append(_t1(env, io, s), _t2(env, io, s));
});
}
tactic interleave(tactic t1, tactic t2) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return interleave(_t1(env, io, s), _t2(env, io, s));
});
}
tactic par(tactic t1, tactic t2, unsigned check_ms) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t1(t1);
tactic _t2(t2);
return par(_t1(env, io, s), _t2(env, io, s), check_ms);
});
}
tactic repeat(tactic t) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s1) -> proof_state_seq {
return repeat(s1, [=](proof_state const & s2) {
tactic _t1(t);
return _t1(env, io, s2);
});
});
}
tactic repeat_at_most(tactic t, unsigned k) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s1) -> proof_state_seq {
return repeat_at_most(s1, [=](proof_state const & s2) {
tactic _t1(t);
return _t1(env, io, s2);
}, k);
});
}
tactic take(tactic t, unsigned k) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t(t);
return take(k, _t(env, io, s));
});
}
tactic force(tactic t) {
return mk_tactic([=](environment const & env, io_state const & io, proof_state const & s) -> proof_state_seq {
tactic _t(t);
proof_state_seq r = _t(env, io, s);
buffer<proof_state> buf;
for_each(r, [&](proof_state const & s2) {
buf.push_back(s2);
check_interrupted();
});
return to_lazy(to_list(buf.begin(), buf.end()));
});
}
}
<|endoftext|> |
<commit_before>/***********************************************************************
created: 7th December 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Null/ShaderWrapper.h"
#include "CEGUI/ShaderParameterBindings.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
NullShaderWrapper::NullShaderWrapper()
{
}
//----------------------------------------------------------------------------//
NullShaderWrapper::~NullShaderWrapper()
{
}
//----------------------------------------------------------------------------//
void NullShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings)
{
}
//----------------------------------------------------------------------------//
}
<commit_msg>MOD: Fixin unused-var warning<commit_after>/***********************************************************************
created: 7th December 2013
author: Lukas Meindl
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2013 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/RendererModules/Null/ShaderWrapper.h"
#include "CEGUI/ShaderParameterBindings.h"
namespace CEGUI
{
//----------------------------------------------------------------------------//
NullShaderWrapper::NullShaderWrapper()
{
}
//----------------------------------------------------------------------------//
NullShaderWrapper::~NullShaderWrapper()
{
}
//----------------------------------------------------------------------------//
void NullShaderWrapper::prepareForRendering(const ShaderParameterBindings* shaderParameterBindings)
{
CEGUI_UNUSED(shaderParameterBindings);
}
//----------------------------------------------------------------------------//
}
<|endoftext|> |
<commit_before>/***********************************************************************
filename: FalButton.cpp
created: Wed Jun 22 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/WindowRendererSets/Falagard/Button.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
// Start of CEGUI namespace section
namespace CEGUI
{
const String FalagardButton::TypeName("Falagard/Button");
FalagardButton::FalagardButton(const String& type) :
WindowRenderer(type)
{
}
void FalagardButton::render()
{
ButtonBase* w = (ButtonBase*)d_window;
const WidgetLookFeel& wlf = getLookNFeel();
bool norm = false;
String state;
if (w->isEffectiveDisabled())
{
state = "Disabled";
}
else if (w->isPushed())
{
state = w->isHovering() ? "Pushed" : "PushedOff";
}
else if (w->isHovering())
{
state = "Hover";
}
else
{
state = "Normal";
norm = true;
}
if (!norm && !wlf.isStateImageryPresent(state))
{
state = "Normal";
}
wlf.getStateImagery(actualStateName(state)).render(*w);
}
} // End of CEGUI namespace section
<commit_msg>Fix: Issue of ToggleButton (checkbox, radiobutton, etc) not falling back to default imagery states as documented. Patch from Hanmac (thanks!) Fixes: http://www.cegui.org.uk/mantis/view.php?id=442<commit_after>/***********************************************************************
filename: FalButton.cpp
created: Wed Jun 22 2005
author: Paul D Turner <paul@cegui.org.uk>
*************************************************************************/
/***************************************************************************
* Copyright (C) 2004 - 2006 Paul D Turner & The CEGUI Development Team
*
* Permission is hereby granted, free of charge, to any person obtaining
* a copy of this software and associated documentation files (the
* "Software"), to deal in the Software without restriction, including
* without limitation the rights to use, copy, modify, merge, publish,
* distribute, sublicense, and/or sell copies of the Software, and to
* permit persons to whom the Software is furnished to do so, subject to
* the following conditions:
*
* The above copyright notice and this permission notice shall be
* included in all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
* EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
* MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
* IN NO EVENT SHALL THE AUTHORS BE LIABLE FOR ANY CLAIM, DAMAGES OR
* OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE,
* ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
* OTHER DEALINGS IN THE SOFTWARE.
***************************************************************************/
#include "CEGUI/WindowRendererSets/Falagard/Button.h"
#include "CEGUI/falagard/WidgetLookManager.h"
#include "CEGUI/falagard/WidgetLookFeel.h"
// Start of CEGUI namespace section
namespace CEGUI
{
const String FalagardButton::TypeName("Falagard/Button");
FalagardButton::FalagardButton(const String& type) :
WindowRenderer(type)
{
}
void FalagardButton::render()
{
ButtonBase* w = (ButtonBase*)d_window;
const WidgetLookFeel& wlf = getLookNFeel();
bool norm = false;
String state;
if (w->isEffectiveDisabled())
{
state = "Disabled";
}
else if (w->isPushed())
{
state = w->isHovering() ? "Pushed" : "PushedOff";
}
else if (w->isHovering())
{
state = "Hover";
}
else
{
state = "Normal";
norm = true;
}
if (!norm && !wlf.isStateImageryPresent(actualStateName(state)))
{
state = "Normal";
}
wlf.getStateImagery(actualStateName(state)).render(*w);
}
} // End of CEGUI namespace section
<|endoftext|> |
<commit_before>// Query binary phrase tables.
// Christian Hardmeier, 16 May 2010
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "PhraseDictionaryTree.h"
#include "Util.h"
void usage();
typedef unsigned int uint;
int main(int argc, char **argv)
{
int nscores = 5;
std::string ttable = "";
bool useAlignments = false;
for(int i = 1; i < argc; i++) {
if(!strcmp(argv[i], "-n")) {
if(i + 1 == argc)
usage();
nscores = atoi(argv[++i]);
} else if(!strcmp(argv[i], "-t")) {
if(i + 1 == argc)
usage();
ttable = argv[++i];
} else if(!strcmp(argv[i], "-a"))
useAlignments = true;
else
usage();
}
if(ttable == "")
usage();
Moses::PhraseDictionaryTree ptree(nscores);
ptree.UseWordAlignment(useAlignments);
ptree.Read(ttable);
std::string line;
while(getline(std::cin, line)) {
std::vector<std::string> srcphrase;
srcphrase = Moses::Tokenize<std::string>(line);
std::vector<Moses::StringTgtCand> tgtcands;
std::vector<std::string> wordAlignment;
if(useAlignments)
ptree.GetTargetCandidates(srcphrase, tgtcands, wordAlignment);
else
ptree.GetTargetCandidates(srcphrase, tgtcands);
for(uint i = 0; i < tgtcands.size(); i++) {
std::cout << line << " |||";
for(uint j = 0; j < tgtcands[i].first.size(); j++)
std::cout << ' ' << *tgtcands[i].first[j];
std::cout << " |||";
if(useAlignments) {
std::cout << " " << wordAlignment[i] << " |||";
}
for(uint j = 0; j < tgtcands[i].second.size(); j++)
std::cout << ' ' << tgtcands[i].second[j];
std::cout << '\n';
}
std::cout << '\n';
std::cout.flush();
}
}
void usage()
{
std::cerr << "Usage: queryPhraseTable [-n <nscores>] [-a] -t <ttable>\n"
"-n <nscores> number of scores in phrase table (default: 5)\n"
"-a binary phrase table contains alignments\n"
"-t <ttable> phrase table\n";
exit(1);
}
<commit_msg>Add option just to give counts<commit_after>// Query binary phrase tables.
// Christian Hardmeier, 16 May 2010
#include <cstdlib>
#include <cstring>
#include <string>
#include <vector>
#include "PhraseDictionaryTree.h"
#include "Util.h"
void usage();
typedef unsigned int uint;
int main(int argc, char **argv)
{
int nscores = 5;
std::string ttable = "";
bool useAlignments = false;
bool reportCounts = false;
for(int i = 1; i < argc; i++) {
if(!strcmp(argv[i], "-n")) {
if(i + 1 == argc)
usage();
nscores = atoi(argv[++i]);
} else if(!strcmp(argv[i], "-t")) {
if(i + 1 == argc)
usage();
ttable = argv[++i];
} else if(!strcmp(argv[i], "-a")) {
useAlignments = true;
} else if (!strcmp(argv[i], "-c")) {
reportCounts = true;
}
else
usage();
}
if(ttable == "")
usage();
Moses::PhraseDictionaryTree ptree(nscores);
ptree.UseWordAlignment(useAlignments);
ptree.Read(ttable);
std::string line;
while(getline(std::cin, line)) {
std::vector<std::string> srcphrase;
srcphrase = Moses::Tokenize<std::string>(line);
std::vector<Moses::StringTgtCand> tgtcands;
std::vector<std::string> wordAlignment;
if(useAlignments)
ptree.GetTargetCandidates(srcphrase, tgtcands, wordAlignment);
else
ptree.GetTargetCandidates(srcphrase, tgtcands);
if (reportCounts) {
std::cout << line << " " << tgtcands.size() << "\n";
} else {
for(uint i = 0; i < tgtcands.size(); i++) {
std::cout << line << " |||";
for(uint j = 0; j < tgtcands[i].first.size(); j++)
std::cout << ' ' << *tgtcands[i].first[j];
std::cout << " |||";
if(useAlignments) {
std::cout << " " << wordAlignment[i] << " |||";
}
for(uint j = 0; j < tgtcands[i].second.size(); j++)
std::cout << ' ' << tgtcands[i].second[j];
std::cout << '\n';
}
std::cout << '\n';
}
std::cout.flush();
}
}
void usage()
{
std::cerr << "Usage: queryPhraseTable [-n <nscores>] [-a] -t <ttable>\n"
"-n <nscores> number of scores in phrase table (default: 5)\n"
"-c only report counts of entries\n"
"-a binary phrase table contains alignments\n"
"-t <ttable> phrase table\n";
exit(1);
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "eventql/eventql.h"
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "eventql/util/application.h"
#include "eventql/util/thread/eventloop.h"
#include "eventql/util/cli/flagparser.h"
#include <eventql/config/process_config.h>
#include <eventql/cli/commands/cluster_add_server.h>
#include <eventql/cli/commands/cluster_create.h>
#include <eventql/cli/commands/cluster_status.h>
#include <eventql/cli/commands/cluster_list.h>
#include <eventql/cli/commands/cluster_remove_server.h>
#include <eventql/cli/commands/database_create.h>
#include <eventql/cli/commands/table_split.h>
#include <eventql/cli/commands/table_split_finalize.h>
#include <eventql/cli/commands/table_config_set.h>
using namespace eventql;
thread::EventLoop ev;
int main(int argc, const char** argv) {
::cli::FlagParser flags;
flags.defineFlag(
"help",
::cli::FlagParser::T_SWITCH,
false,
"?",
NULL,
"help",
"<help>");
flags.defineFlag(
"version",
::cli::FlagParser::T_SWITCH,
false,
"v",
NULL,
"print version",
"<switch>");
flags.defineFlag(
"config",
::cli::FlagParser::T_STRING,
false,
"c",
NULL,
"path to config file",
"<config_file>");
flags.defineFlag(
"config_set",
::cli::FlagParser::T_STRING,
false,
"C",
NULL,
"set config option",
"<key>=<val>");
flags.parseArgv(argc, argv);
auto stdin_is = FileInputStream::getStdin();
auto stdout_os = OutputStream::getStdout();
auto stderr_os = OutputStream::getStderr();
Vector<String> cmd_argv = flags.getArgv();
Application::init();
Application::logToStderr("evqlctl");
/* load config */
ProcessConfigBuilder config_builder;
if (flags.isSet("config")) {
auto rc = config_builder.loadFile(flags.getString("config"));
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
return 1;
}
} else {
config_builder.loadDefaultConfigFile("evqlctl");
}
for (const auto& opt : flags.getStrings("config_set")) {
auto opt_key_end = opt.find("=");
if (opt_key_end == String::npos) {
stderr_os->write(
StringUtil::format("ERROR: invalid config option: $0\n", opt));
return 1;
}
config_builder.setProperty(
opt.substr(0, opt_key_end),
opt.substr(opt_key_end + 1));
}
auto process_config = config_builder.getConfig();
/* init commands */
List<eventql::cli::CLICommand*> commands;
commands.emplace_back(new eventql::cli::ClusterAddServer(process_config));
commands.emplace_back(new eventql::cli::ClusterCreate(process_config));
commands.emplace_back(new eventql::cli::ClusterRemoveServer(process_config));
commands.emplace_back(new eventql::cli::ClusterStatus(process_config));
commands.emplace_back(new eventql::cli::ClusterList(process_config));
commands.emplace_back(new eventql::cli::DatabaseCreate(process_config));
commands.emplace_back(new eventql::cli::TableSplit(process_config));
commands.emplace_back(new eventql::cli::TableSplitFinalize(process_config));
commands.emplace_back(new eventql::cli::TableConfigSet(process_config));
/* print help/version and exit */
bool print_help = flags.isSet("help");
bool print_version = flags.isSet("version");
if (cmd_argv.size() > 0 && cmd_argv[0] == "help") {
print_help = true;
cmd_argv.erase(cmd_argv.begin());
}
auto help_topic = cmd_argv.size() > 0 ? cmd_argv.front() : "";
if (print_version || (print_help && help_topic.empty())) {
auto stdout_os = OutputStream::getStdout();
stdout_os->write(
StringUtil::format(
"EventQL $0 ($1)\n"
"Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n",
kVersionString,
kBuildID));
}
if (print_version) {
return 1;
}
if (print_help) {
if (help_topic.empty()) {
stdout_os->write(
"Usage: $ evqlctl [OPTIONS] <command> [<args>]\n\n"
" -c, --config <file> Load config from file\n"
" -C name=value Define a config value on the command line\n"
" -?, --help <topic> Display a command's help text and exit\n"
" -v, --version Display the version of this binary and exit\n\n"
"evqctl commands:\n"
);
for (const auto c : commands) {
stdout_os->printf(" %-26.26s", c->getName().c_str());
stdout_os->printf("%-80.80s\n", c->getDescription().c_str());
}
stdout_os->write(
"\nSee 'evqlctl help <command>' to read about a specific subcommand.\n"
);
return 0;
}
for (auto c : commands) {
if (c->getName() == help_topic) {
c->printHelp(stdout_os.get());
return 0;
}
}
stderr_os->write(StringUtil::format(
"evqlctl: No manual entry for evqlctl '$0'\n",
help_topic));
return 1;
}
/* execute command */
{
String cmd_name;
if (cmd_argv.empty()) {
stderr_os->write(
"evqlctl: command is not specified. See 'evqlctl --help'.\n");
return 1;
} else {
cmd_name = cmd_argv.front();
cmd_argv.erase(cmd_argv.begin());
}
for (auto c : commands) {
if (c->getName() == cmd_name) {
auto ret = c->execute(
cmd_argv,
stdin_is.get(),
stdout_os.get(),
stderr_os.get());
if (!ret.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", ret.message()));
}
return ret.isSuccess() ? 0 : 1;
}
}
stderr_os->write(StringUtil::format(
"evqlctl: '$0' is not a evqlctl command. See 'evqlctl --help'.\n",
cmd_name));
return 1;
}
}
<commit_msg>cleanup<commit_after>/**
* Copyright (c) 2016 DeepCortex GmbH <legal@eventql.io>
* Authors:
* - Paul Asmuth <paul@eventql.io>
*
* This program is free software: you can redistribute it and/or modify it under
* the terms of the GNU Affero General Public License ("the license") as
* published by the Free Software Foundation, either version 3 of the License,
* or any later version.
*
* In accordance with Section 7(e) of the license, the licensing of the Program
* under the license does not imply a trademark license. Therefore any rights,
* title and interest in our trademarks remain entirely with us.
*
* This program 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 license for more details.
*
* You can be released from the requirements of the license by purchasing a
* commercial license. Buying such a license is mandatory as soon as you develop
* commercial activities involving this program without disclosing the source
* code of your own applications
*/
#include "eventql/eventql.h"
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "eventql/util/application.h"
#include "eventql/util/thread/eventloop.h"
#include "eventql/util/cli/flagparser.h"
#include <eventql/config/process_config.h>
#include <eventql/cli/commands/cluster_add_server.h>
#include <eventql/cli/commands/cluster_create.h>
#include <eventql/cli/commands/cluster_status.h>
#include <eventql/cli/commands/cluster_list.h>
#include <eventql/cli/commands/cluster_remove_server.h>
#include <eventql/cli/commands/database_create.h>
#include <eventql/cli/commands/table_split.h>
#include <eventql/cli/commands/table_split_finalize.h>
#include <eventql/cli/commands/table_config_set.h>
using namespace eventql;
thread::EventLoop ev;
int main(int argc, const char** argv) {
::cli::FlagParser flags;
flags.defineFlag(
"help",
::cli::FlagParser::T_SWITCH,
false,
"?",
NULL,
"help",
"<help>");
flags.defineFlag(
"version",
::cli::FlagParser::T_SWITCH,
false,
"v",
NULL,
"print version",
"<switch>");
flags.defineFlag(
"config",
::cli::FlagParser::T_STRING,
false,
"c",
NULL,
"path to config file",
"<config_file>");
flags.defineFlag(
"config_set",
::cli::FlagParser::T_STRING,
false,
"C",
NULL,
"set config option",
"<key>=<val>");
flags.parseArgv(argc, argv);
auto stdin_is = FileInputStream::getStdin();
auto stdout_os = OutputStream::getStdout();
auto stderr_os = OutputStream::getStderr();
Vector<String> cmd_argv = flags.getArgv();
Application::init();
Application::logToStderr("evqlctl");
/* load config */
ProcessConfigBuilder config_builder;
if (flags.isSet("config")) {
auto rc = config_builder.loadFile(flags.getString("config"));
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
return 1;
}
} else {
config_builder.loadDefaultConfigFile("evqlctl");
}
for (const auto& opt : flags.getStrings("config_set")) {
auto opt_key_end = opt.find("=");
if (opt_key_end == String::npos) {
stderr_os->write(
StringUtil::format("ERROR: invalid config option: $0\n", opt));
return 1;
}
config_builder.setProperty(
opt.substr(0, opt_key_end),
opt.substr(opt_key_end + 1));
}
auto process_config = config_builder.getConfig();
/* init commands */
List<eventql::cli::CLICommand*> commands;
commands.emplace_back(new eventql::cli::ClusterAddServer(process_config));
commands.emplace_back(new eventql::cli::ClusterCreate(process_config));
commands.emplace_back(new eventql::cli::ClusterRemoveServer(process_config));
commands.emplace_back(new eventql::cli::ClusterStatus(process_config));
commands.emplace_back(new eventql::cli::ClusterList(process_config));
commands.emplace_back(new eventql::cli::DatabaseCreate(process_config));
commands.emplace_back(new eventql::cli::TableSplit(process_config));
commands.emplace_back(new eventql::cli::TableSplitFinalize(process_config));
commands.emplace_back(new eventql::cli::TableConfigSet(process_config));
/* print help/version and exit */
bool print_help = flags.isSet("help");
bool print_version = flags.isSet("version");
if (cmd_argv.size() > 0 && cmd_argv[0] == "help") {
print_help = true;
cmd_argv.erase(cmd_argv.begin());
}
auto help_topic = cmd_argv.size() > 0 ? cmd_argv.front() : "";
if (print_version || (print_help && help_topic.empty())) {
auto stdout_os = OutputStream::getStdout();
stdout_os->write(
StringUtil::format(
"EventQL $0 ($1)\n"
"Copyright (c) 2016, DeepCortex GmbH. All rights reserved.\n\n",
kVersionString,
kBuildID));
}
if (print_version) {
return 0;
}
if (print_help) {
if (help_topic.empty()) {
stdout_os->write(
"Usage: $ evqlctl [OPTIONS] <command> [<args>]\n\n"
" -c, --config <file> Load config from file\n"
" -C name=value Define a config value on the command line\n"
" -?, --help <topic> Display a command's help text and exit\n"
" -v, --version Display the version of this binary and exit\n\n"
"evqctl commands:\n"
);
for (const auto c : commands) {
stdout_os->printf(" %-26.26s", c->getName().c_str());
stdout_os->printf("%-80.80s\n", c->getDescription().c_str());
}
stdout_os->write(
"\nSee 'evqlctl help <command>' to read about a specific subcommand.\n"
);
return 0;
}
for (auto c : commands) {
if (c->getName() == help_topic) {
c->printHelp(stdout_os.get());
return 0;
}
}
stderr_os->write(StringUtil::format(
"evqlctl: No manual entry for evqlctl '$0'\n",
help_topic));
return 1;
}
/* execute command */
String cmd_name;
if (cmd_argv.empty()) {
stderr_os->write(
"evqlctl: command is not specified. See 'evqlctl --help'.\n");
return 1;
} else {
cmd_name = cmd_argv.front();
cmd_argv.erase(cmd_argv.begin());
}
for (auto c : commands) {
if (c->getName() == cmd_name) {
auto rc = c->execute(
cmd_argv,
stdin_is.get(),
stdout_os.get(),
stderr_os.get());
if (!rc.isSuccess()) {
stderr_os->write(StringUtil::format("ERROR: $0\n", rc.message()));
}
return rc.isSuccess() ? 0 : 1;
}
}
stderr_os->write(StringUtil::format(
"evqlctl: '$0' is not a evqlctl command. See 'evqlctl --help'.\n",
cmd_name));
return 1;
}
<|endoftext|> |
<commit_before>/*
* test1.cpp
*
* Created on: 2012-9-21
* Author: yanghuan
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <functional>
#include <boost/mpl/at.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/sort.hpp>
#include "refection/method_wrap.hpp"
#include "utility.hpp"
using namespace std;
using namespace boost;
using namespace refection;
namespace test {
struct AA : public refection::Object
{
public:
REFECTION_CLASS_DECLARE();
public:
void f() {}
static int aa() {
cout << "aa function is invoke" << endl;
return 10;
}
void e(int) {
cout << "e function is invoke" << endl;
}
};
REFECTION_CLASS_IMPLEMENT_BEGIN(AA)
REFECTION_METHOD_IMPLEMENT(f, void(AA::*)()),
REFECTION_METHOD_IMPLEMENT(e, void(AA::*)(int)),
REFECTION_METHOD_IMPLEMENT(aa, int(*)()),
REFECTION_CLASS_IMPLEMENT_END()
} // namespace test
void test1() {
test::AA aa;
const Type& t = aa.getType();
const MethodInfo* array = t.package_.method_list_;
const size_t size = t.package_.method_list_size_;
for(size_t i = 0 ; i < size; ++i) {
cout << getDemangleString(array[i].declaring_type_.package_.type_info_.name()) << endl;
cout << getDemangleString(array[i].signature_.name()) << endl;
cout << array[i].name_ << endl;
cout << array[i].declaring_type_.package_.name_ << endl;
cout << reinterpret_cast<const void*>(array[i].ptr_.func_ptr) << endl;
}
/* invoke function */
const MethodInfo* func = t.getMethod("e");
if(func != nullptr) {
func->invoke<void>(&aa,30);
}
func = t.getMethod("aa");
if (func != nullptr) {
int resoult = func->invoke<int>(nullptr);
cout << "resoult:" << resoult << endl;
}
}
<commit_msg>add one comment<commit_after>/*
* test1.cpp
*
* Created on: 2012-9-21
* Author: yanghuan
*/
#include <cstdlib>
#include <cstring>
#include <iostream>
#include <tuple>
#include <type_traits>
#include <functional>
#include <boost/mpl/at.hpp>
#include <boost/mpl/vector.hpp>
#include <boost/mpl/sort.hpp>
#include "refection/method_wrap.hpp"
#include "utility.hpp"
using namespace std;
using namespace boost;
using namespace refection;
namespace test {
struct AA : public refection::Object
{
public:
REFECTION_CLASS_DECLARE();
public:
void f() {}
static int aa() {
cout << "aa function is invoke" << endl;
return 10;
}
void e(int) {
cout << "e function is invoke" << endl;
}
};
REFECTION_CLASS_IMPLEMENT_BEGIN(AA)
REFECTION_METHOD_IMPLEMENT(f, void(AA::*)()),
REFECTION_METHOD_IMPLEMENT(e, void(AA::*)(int)),
REFECTION_METHOD_IMPLEMENT(aa, int(*)()),
REFECTION_CLASS_IMPLEMENT_END()
} // namespace test
void test1() {
test::AA aa;
const Type& t = aa.getType();
const MethodInfo* array = t.package_.method_list_;
const size_t size = t.package_.method_list_size_;
/* show function info */
for(size_t i = 0 ; i < size; ++i) {
cout << getDemangleString(array[i].declaring_type_.package_.type_info_.name()) << endl;
cout << getDemangleString(array[i].signature_.name()) << endl;
cout << array[i].name_ << endl;
cout << array[i].declaring_type_.package_.name_ << endl;
cout << reinterpret_cast<const void*>(array[i].ptr_.func_ptr) << endl;
}
/* invoke function */
const MethodInfo* func = t.getMethod("e");
if(func != nullptr) {
func->invoke<void>(&aa,30);
}
func = t.getMethod("aa");
if (func != nullptr) {
int resoult = func->invoke<int>(nullptr);
cout << "resoult:" << resoult << endl;
}
}
<|endoftext|> |
<commit_before>#include <utki/config.hpp>
#include "init_guard.hpp"
#include "dns_resolver.hpp"
#if M_OS == M_OS_WINDOWS
# include <winsock2.h>
# include <utki/windows.hpp>
#elif M_OS == M_OS_LINUX || M_OS == M_OS_UNIX || M_OS == M_OS_MACOSX
# include <signal.h>
#else
# error "Unsupported OS"
#endif
using namespace setka;
utki::intrusive_singleton<init_guard>::T_Instance init_guard::instance;
init_guard::init_guard(){
#if M_OS == M_OS_WINDOWS
WORD versionWanted = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup(versionWanted, &wsaData) != 0 ){
throw std::exception("SocketLib::SocketLib(): Winsock 2.2 initialization failed");
}
#elif M_OS == M_OS_LINUX || M_OS == M_OS_UNIX || M_OS == M_OS_MACOSX
// SIGPIPE is generated when a remote socket is closed
void (*handler)(int);
handler = signal(SIGPIPE, SIG_IGN);
if(handler != SIG_DFL){
signal(SIGPIPE, handler);
}
#else
#error "Unknown OS"
#endif
}
init_guard::~init_guard()noexcept{
// check that there are no active dns lookups and finish the DNS request thread
dns_resolver::clean_up();
#if M_OS == M_OS_WINDOWS
// clean up windows networking
if(WSACleanup() == SOCKET_ERROR){
if(WSAGetLastError() == WSAEINPROGRESS){
WSACancelBlockingCall();
WSACleanup();
}
}
#elif M_OS == M_OS_LINUX || M_OS == M_OS_UNIX || M_OS == M_OS_MACOSX
// restore the SIGPIPE handler
void (*handler)(int);
handler = signal(SIGPIPE, SIG_DFL);
if(handler != SIG_IGN){
signal(SIGPIPE, handler);
}
#else
#error "Unknown OS"
#endif
}
<commit_msg>stuff<commit_after>#include <utki/config.hpp>
#include "init_guard.hpp"
#include "dns_resolver.hpp"
#if M_OS == M_OS_WINDOWS
# include <winsock2.h>
# include <utki/windows.hpp>
#elif M_OS == M_OS_LINUX || M_OS == M_OS_UNIX || M_OS == M_OS_MACOSX
# include <signal.h>
#else
# error "Unsupported OS"
#endif
using namespace setka;
utki::intrusive_singleton<init_guard>::T_Instance init_guard::instance;
init_guard::init_guard(){
#if M_OS == M_OS_WINDOWS
WORD versionWanted = MAKEWORD(2,2);
WSADATA wsaData;
if(WSAStartup(versionWanted, &wsaData) != 0 ){
// TODO: use std::system_error?
throw std::runtime_error("SocketLib::SocketLib(): Winsock 2.2 initialization failed");
}
#elif M_OS == M_OS_LINUX || M_OS == M_OS_UNIX || M_OS == M_OS_MACOSX
// SIGPIPE is generated when a remote socket is closed
void (*handler)(int);
handler = signal(SIGPIPE, SIG_IGN);
if(handler != SIG_DFL){
signal(SIGPIPE, handler);
}
#else
#error "Unknown OS"
#endif
}
init_guard::~init_guard()noexcept{
// check that there are no active dns lookups and finish the DNS request thread
dns_resolver::clean_up();
#if M_OS == M_OS_WINDOWS
// clean up windows networking
if(WSACleanup() == SOCKET_ERROR){
if(WSAGetLastError() == WSAEINPROGRESS){
WSACancelBlockingCall();
WSACleanup();
}
}
#elif M_OS == M_OS_LINUX || M_OS == M_OS_UNIX || M_OS == M_OS_MACOSX
// restore the SIGPIPE handler
void (*handler)(int);
handler = signal(SIGPIPE, SIG_DFL);
if(handler != SIG_IGN){
signal(SIGPIPE, handler);
}
#else
#error "Unknown OS"
#endif
}
<|endoftext|> |
<commit_before>#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMessageBox>
#include <qrkernel/settingsManager.h>
#include "mainWindow/projectManager/projectManager.h"
#include "mainWindow/projectManager/autosaver.h"
using namespace qReal;
Autosaver::Autosaver(ProjectManager *projectManager)
: QObject(projectManager)
, mProjectManager(projectManager)
, mTimer(new QTimer(this))
{
connect(mTimer, SIGNAL(timeout()), this, SLOT(saveAutoSave()));
}
void Autosaver::reinit()
{
resume();
}
void Autosaver::resume()
{
if (SettingsManager::value("Autosave").toBool()) {
mTimer->start(interval() * 1000);
} else {
mTimer->stop();
}
}
void Autosaver::suspend()
{
mTimer->stop();
}
uint Autosaver::interval() const
{
uint result = SettingsManager::value("AutosaveInterval").toUInt();
if (result == 0) {
result = defaultInterval;
}
return result;
}
Autosaver::Pauser::Pauser(Autosaver &autosaver)
: mAutosaver(autosaver)
{
autosaver.suspend();
}
Autosaver::Pauser::~Pauser()
{
mAutosaver.resume();
}
QString Autosaver::autosaveFilePath() const
{
return autosaveFilePath(mProjectManager->saveFilePath());
}
QString Autosaver::autosaveFilePath(QString const ¤tFilePath) const
{
if (currentFilePath.isEmpty() || currentFilePath == tempFilePath()) {
return tempFilePath();
}
QFileInfo const currentProject(currentFilePath);
QString const autosaveDirectory = currentProject.absoluteDir().exists()
? currentProject.absolutePath()
: QApplication::applicationDirPath();
QString const currentFileName = currentProject.fileName();
QString const autosaveFile = currentFileName.startsWith("~")
? currentFileName : "~" + currentFileName;
return autosaveDirectory + "/" + autosaveFile;
}
QString Autosaver::tempFilePath() const
{
return QString("%1/%2.qrs").arg(
QApplication::applicationDirPath()
, SettingsManager::value("AutosaveTempFile").toString());
}
bool Autosaver::isAutosave(QString const &fileName) const
{
return QFileInfo(fileName).fileName().contains("~");
}
bool Autosaver::isTempFile(QString const &fileName) const
{
return fileName == tempFilePath();
}
QString Autosaver::originalFile(QString const &fileName) const
{
if (!isAutosave(fileName)) {
return fileName;
}
QFileInfo fileInfo(fileName);
return fileInfo.absolutePath() + "/" + fileInfo.fileName().remove("~");
}
bool Autosaver::openTemp()
{
return mProjectManager->open(tempFilePath());
}
bool Autosaver::openAutosave(QString const &fileName)
{
return mProjectManager->open(autosaveFilePath(fileName));
}
void Autosaver::saveTemp()
{
mProjectManager->saveTo(tempFilePath());
}
bool Autosaver::checkAutoSavedVersion(QString const &originalProjectPath)
{
QString const autosave = autosaveFilePath(originalProjectPath);
QFileInfo const autosaveInfo(autosave);
if (!autosaveInfo.exists() || autosave == originalProjectPath) {
return false;
}
if (QMessageBox::question(QApplication::activeWindow(), tr("Question")
, openAutosavePrompt()) != QMessageBox::Yes) {
return false;
}
return openAutosave(originalProjectPath);
}
bool Autosaver::checkTempFile()
{
QFileInfo const tempFileInfo(tempFilePath());
if (!tempFileInfo.exists()) {
return false;
}
if (QMessageBox::question(QApplication::activeWindow(), tr("Question")
, openTempFilePrompt()) != QMessageBox::Yes) {
return false;
}
return openTemp();
}
QString Autosaver::openAutosavePrompt() const
{
return tr("More recent autosaved version of this file was found. "\
"Do you wish to open it instead?");
}
QString Autosaver::openTempFilePrompt() const
{
return tr("It seems like the last application session was terminated in an "\
"unusial way. Do you wish to recover unsaved project?");
}
void Autosaver::saveAutoSave()
{
mProjectManager->saveTo(autosaveFilePath());
}
bool Autosaver::removeFile(QString const &fileName)
{
return QFile::remove(fileName);
}
bool Autosaver::removeTemp()
{
return removeFile(tempFilePath());
}
bool Autosaver::removeAutoSave()
{
return removeFile(autosaveFilePath());
}
bool Autosaver::removeAutoSave(QString const &fileName)
{
return removeFile(autosaveFilePath(fileName));
}
<commit_msg>double restore diagram bug is fixed<commit_after>#include <QtCore/QFileInfo>
#include <QtCore/QDir>
#include <QtWidgets/QApplication>
#include <QtWidgets/QMessageBox>
#include <qrkernel/settingsManager.h>
#include "mainWindow/projectManager/projectManager.h"
#include "mainWindow/projectManager/autosaver.h"
using namespace qReal;
Autosaver::Autosaver(ProjectManager *projectManager)
: QObject(projectManager)
, mProjectManager(projectManager)
, mTimer(new QTimer(this))
{
connect(mTimer, SIGNAL(timeout()), this, SLOT(saveAutoSave()));
}
void Autosaver::reinit()
{
resume();
}
void Autosaver::resume()
{
if (SettingsManager::value("Autosave").toBool()) {
mTimer->start(interval() * 1000);
} else {
mTimer->stop();
}
}
void Autosaver::suspend()
{
mTimer->stop();
}
uint Autosaver::interval() const
{
uint result = SettingsManager::value("AutosaveInterval").toUInt();
if (result == 0) {
result = defaultInterval;
}
return result;
}
Autosaver::Pauser::Pauser(Autosaver &autosaver)
: mAutosaver(autosaver)
{
autosaver.suspend();
}
Autosaver::Pauser::~Pauser()
{
mAutosaver.resume();
}
QString Autosaver::autosaveFilePath() const
{
return autosaveFilePath(mProjectManager->saveFilePath());
}
QString Autosaver::autosaveFilePath(QString const ¤tFilePath) const
{
if (currentFilePath.isEmpty() || currentFilePath == tempFilePath()) {
return tempFilePath();
}
QFileInfo const currentProject(currentFilePath);
QString const autosaveDirectory = currentProject.absoluteDir().exists()
? currentProject.absolutePath()
: QApplication::applicationDirPath();
QString const currentFileName = currentProject.fileName();
QString const autosaveFile = currentFileName.startsWith("~")
? currentFileName : "~" + currentFileName;
return autosaveDirectory + "/" + autosaveFile;
}
QString Autosaver::tempFilePath() const
{
return QString("%1/%2.qrs").arg(
QApplication::applicationDirPath()
, SettingsManager::value("AutosaveTempFile").toString());
}
bool Autosaver::isAutosave(QString const &fileName) const
{
return QFileInfo(fileName).fileName().contains("~");
}
bool Autosaver::isTempFile(QString const &fileName) const
{
return fileName == tempFilePath();
}
QString Autosaver::originalFile(QString const &fileName) const
{
if (!isAutosave(fileName)) {
return fileName;
}
QFileInfo fileInfo(fileName);
return fileInfo.absolutePath() + "/" + fileInfo.fileName().remove("~");
}
bool Autosaver::openTemp()
{
return mProjectManager->open(tempFilePath());
}
bool Autosaver::openAutosave(QString const &fileName)
{
return mProjectManager->open(autosaveFilePath(fileName));
}
void Autosaver::saveTemp()
{
mProjectManager->saveTo(tempFilePath());
}
bool Autosaver::checkAutoSavedVersion(QString const &originalProjectPath)
{
QString const autosave = autosaveFilePath(originalProjectPath);
QFileInfo const autosaveInfo(autosave);
if (!autosaveInfo.exists() || autosave == originalProjectPath) {
return false;
}
if (QMessageBox::question(QApplication::activeWindow(), tr("Question")
, openAutosavePrompt()) != QMessageBox::Yes) {
return false;
}
return openAutosave(originalProjectPath);
}
bool Autosaver::checkTempFile()
{
QFileInfo const tempFileInfo(tempFilePath());
if (!tempFileInfo.exists()) {
return false;
}
if (QMessageBox::question(QApplication::activeWindow(), tr("Question")
, openTempFilePrompt()) != QMessageBox::Yes) {
QFile(tempFileInfo.absoluteFilePath()).remove();
return false;
}
return openTemp();
}
QString Autosaver::openAutosavePrompt() const
{
return tr("More recent autosaved version of this file was found. "\
"Do you wish to open it instead?");
}
QString Autosaver::openTempFilePrompt() const
{
return tr("It seems like the last application session was terminated in an "\
"unusial way. Do you wish to recover unsaved project?");
}
void Autosaver::saveAutoSave()
{
mProjectManager->saveTo(autosaveFilePath());
}
bool Autosaver::removeFile(QString const &fileName)
{
return QFile::remove(fileName);
}
bool Autosaver::removeTemp()
{
return removeFile(tempFilePath());
}
bool Autosaver::removeAutoSave()
{
return removeFile(autosaveFilePath());
}
bool Autosaver::removeAutoSave(QString const &fileName)
{
return removeFile(autosaveFilePath(fileName));
}
<|endoftext|> |
<commit_before>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Leonardo de Moura, Sebastian Ullrich
*/
#if defined(LEAN_JSON)
#include <algorithm>
#include <string>
#include <vector>
#include "util/lean_path.h"
#include "util/sexpr/option_declarations.h"
#include "util/bitap_fuzzy_search.h"
#include "library/protected.h"
#include "library/util.h"
#include "library/scoped_ext.h"
#include "library/class.h"
#include "frontends/lean/util.h"
#include "shell/server.h"
#include "shell/completion.h"
namespace lean {
#define LEAN_FUZZY_MAX_ERRORS 3
#define LEAN_FUZZY_MAX_ERRORS_FACTOR 3
/** \brief Return an (atomic) name if \c n can be referenced by this atomic
name in the given environment. */
optional<name> is_essentially_atomic(environment const & env, name const & n) {
if (n.is_atomic())
return optional<name>(n);
list<name> const & ns_list = get_namespaces(env);
for (name const & ns : ns_list) {
if (is_prefix_of(ns, n)) {
auto n_prime = n.replace_prefix(ns, name());
if (n_prime.is_atomic() && !is_protected(env, n))
return optional<name>(n_prime);
break;
}
}
if (auto it = is_uniquely_aliased(env, n))
if (it->is_atomic())
return it;
return optional<name>();
}
unsigned get_fuzzy_match_max_errors(unsigned prefix_sz) {
unsigned r = (prefix_sz / LEAN_FUZZY_MAX_ERRORS_FACTOR);
if (r > LEAN_FUZZY_MAX_ERRORS)
return LEAN_FUZZY_MAX_ERRORS;
return r;
}
optional<name> exact_prefix_match(environment const & env, std::string const & pattern, declaration const & d) {
if (auto it = is_essentially_atomic(env, d.get_name())) {
std::string it_str = it->to_string();
// if pattern "perfectly" matches beginning of declaration name, we just display d on the top of the list
if (it_str.compare(0, pattern.size(), pattern) == 0)
return it;
} else {
std::string d_str = d.get_name().to_string();
if (d_str.compare(0, pattern.size(), pattern) == 0)
return optional<name>(d.get_name());
}
return optional<name>();
}
void filter_completions(std::string const & pattern, std::vector<pair<std::string, name>> & selected,
std::vector<json> & completions, unsigned max_results, std::function<json(name)> serialize) {
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<name, name>> exact_matches;
bitap_fuzzy_search matcher(pattern, max_errors);
unsigned num_results = 0;
unsigned sz = selected.size();
if (sz == 1) {
completions.push_back(serialize(selected[0].second));
} else if (sz > 1) {
std::vector<pair<std::string, name>> next_selected;
for (unsigned k = 0; k <= max_errors && num_results < max_results; k++) {
bitap_fuzzy_search matcher(pattern, k);
for (auto const & s : selected) {
if (matcher.match(s.first)) {
completions.push_back(serialize(s.second));
num_results++;
if (num_results >= max_results)
break;
} else {
next_selected.push_back(s);
}
}
std::swap(selected, next_selected);
next_selected.clear();
}
}
}
std::vector<json> get_decl_completions(std::string const & pattern, environment const & env, options const & opts) {
std::vector<json> completions;
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<name, name>> exact_matches;
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
env.for_each_declaration([&](declaration const & d) {
if (is_projection(env, d.get_name())) {
auto s_name = d.get_name().get_prefix();
if (is_class(env, s_name))
return;
}
if (is_internal_name(d.get_name())) {
return;
}
if (auto it = exact_prefix_match(env, pattern, d)) {
exact_matches.emplace_back(*it, d.get_name());
} else {
std::string text = d.get_name().to_string();
if (matcher.match(text))
selected.emplace_back(text, d.get_name());
}
});
unsigned num_results = 0;
if (!exact_matches.empty()) {
std::sort(exact_matches.begin(), exact_matches.end(),
[](pair<name, name> const & p1, pair<name, name> const & p2) {
return p1.first.size() < p2.first.size();
});
for (pair<name, name> const & p : exact_matches) {
completions.push_back(serialize_decl(p.first, p.second, env, opts));
num_results++;
if (num_results >= max_results)
break;
}
}
filter_completions(pattern, selected, completions, max_results - num_results, [&](name const & n) {
return serialize_decl(n, env, opts);
});
return completions;
}
std::vector<json> get_option_completions(std::string const & pattern, options const & opts) {
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
std::vector<json> completions;
get_option_declarations().for_each([&](name const & n, option_declaration const &) {
std::string text = n.to_string();
if (matcher.match(text))
selected.emplace_back(text, n);
});
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
json completion;
completion["text"] = n.to_string();
std::stringstream ss;
get_option_declarations().find(n)->display_value(ss, opts);
completion["type"] = ss.str();
return completion;
});
return completions;
}
std::vector<json> get_import_completions(std::string const & pattern, std::string const & curr_dir,
options const & opts) {
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
std::vector<json> completions;
optional<unsigned> depth;
if (pattern.size() && pattern[0] == '.') {
unsigned i = 1;
while (i < pattern.size() && pattern[i] == '.')
i++;
depth = {i - 1};
}
std::vector<std::string> imports;
find_imports(curr_dir, depth, imports);
for (auto const & candidate : imports) {
if (matcher.match(candidate))
selected.emplace_back(candidate, candidate);
}
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
json completion;
completion["text"] = n.to_string();
return completion;
});
return completions;
}
std::vector<json> get_interactive_tactic_completions(std::string const & pattern, name const & tac_class,
environment const & env, options const & opts) {
std::vector<json> completions;
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
name namespc = tac_class + name("interactive");
env.for_each_declaration([&](declaration const & d) {
auto const & n = d.get_name();
if (n.get_prefix() == namespc && n.is_string() && matcher.match(n.get_string())) {
selected.emplace_back(n.get_string(), n);
}
});
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
return serialize_decl(n.get_string(), n, env, opts);
});
// append regular completions
for (auto candidate : get_decl_completions(pattern, env, opts))
completions.push_back(candidate);
return completions;
}
std::vector<json> get_attribute_completions(std::string const & pattern, environment const & env,
options const & opts) {
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
std::vector<json> completions;
buffer<attribute const *> attrs;
get_attributes(env, attrs);
for (auto const & attr : attrs) {
auto s = attr->get_name().to_string();
if (matcher.match(s))
selected.emplace_back(s, attr->get_name());
}
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
json completion;
completion["text"] = n.to_string();
completion["type"] = get_attribute(env, n).get_description();
return completion;
});
return completions;
}
}
#endif
<commit_msg>feat(shell/completion): sort completions alphabetically (secondary)<commit_after>/*
Copyright (c) 2016 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Authors: Gabriel Ebner, Leonardo de Moura, Sebastian Ullrich
*/
#if defined(LEAN_JSON)
#include <algorithm>
#include <string>
#include <vector>
#include "util/lean_path.h"
#include "util/sexpr/option_declarations.h"
#include "util/bitap_fuzzy_search.h"
#include "library/protected.h"
#include "library/util.h"
#include "library/scoped_ext.h"
#include "library/class.h"
#include "frontends/lean/util.h"
#include "shell/server.h"
#include "shell/completion.h"
namespace lean {
#define LEAN_FUZZY_MAX_ERRORS 3
#define LEAN_FUZZY_MAX_ERRORS_FACTOR 3
/** \brief Return an (atomic) name if \c n can be referenced by this atomic
name in the given environment. */
optional<name> is_essentially_atomic(environment const & env, name const & n) {
if (n.is_atomic())
return optional<name>(n);
list<name> const & ns_list = get_namespaces(env);
for (name const & ns : ns_list) {
if (is_prefix_of(ns, n)) {
auto n_prime = n.replace_prefix(ns, name());
if (n_prime.is_atomic() && !is_protected(env, n))
return optional<name>(n_prime);
break;
}
}
if (auto it = is_uniquely_aliased(env, n))
if (it->is_atomic())
return it;
return optional<name>();
}
unsigned get_fuzzy_match_max_errors(unsigned prefix_sz) {
unsigned r = (prefix_sz / LEAN_FUZZY_MAX_ERRORS_FACTOR);
if (r > LEAN_FUZZY_MAX_ERRORS)
return LEAN_FUZZY_MAX_ERRORS;
return r;
}
optional<name> exact_prefix_match(environment const & env, std::string const & pattern, declaration const & d) {
if (auto it = is_essentially_atomic(env, d.get_name())) {
std::string it_str = it->to_string();
// if pattern "perfectly" matches beginning of declaration name, we just display d on the top of the list
if (it_str.compare(0, pattern.size(), pattern) == 0)
return it;
} else {
std::string d_str = d.get_name().to_string();
if (d_str.compare(0, pattern.size(), pattern) == 0)
return optional<name>(d.get_name());
}
return optional<name>();
}
void filter_completions(std::string const & pattern, std::vector<pair<std::string, name>> & selected,
std::vector<json> & completions, unsigned max_results, std::function<json(name)> serialize) {
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<name, name>> exact_matches;
bitap_fuzzy_search matcher(pattern, max_errors);
unsigned num_results = 0;
unsigned sz = selected.size();
if (sz == 1) {
completions.push_back(serialize(selected[0].second));
} else if (sz > 1) {
std::sort(selected.begin(), selected.end());
std::vector<pair<std::string, name>> next_selected;
for (unsigned k = 0; k <= max_errors && num_results < max_results; k++) {
bitap_fuzzy_search matcher(pattern, k);
for (auto const & s : selected) {
if (matcher.match(s.first)) {
completions.push_back(serialize(s.second));
num_results++;
if (num_results >= max_results)
break;
} else {
next_selected.push_back(s);
}
}
std::swap(selected, next_selected);
next_selected.clear();
}
}
}
std::vector<json> get_decl_completions(std::string const & pattern, environment const & env, options const & opts) {
std::vector<json> completions;
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<name, name>> exact_matches;
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
env.for_each_declaration([&](declaration const & d) {
if (is_projection(env, d.get_name())) {
auto s_name = d.get_name().get_prefix();
if (is_class(env, s_name))
return;
}
if (is_internal_name(d.get_name())) {
return;
}
if (auto it = exact_prefix_match(env, pattern, d)) {
exact_matches.emplace_back(*it, d.get_name());
} else {
std::string text = d.get_name().to_string();
if (matcher.match(text))
selected.emplace_back(text, d.get_name());
}
});
unsigned num_results = 0;
if (!exact_matches.empty()) {
std::sort(exact_matches.begin(), exact_matches.end(),
[](pair<name, name> const & p1, pair<name, name> const & p2) {
return p1.first.size() < p2.first.size();
});
for (pair<name, name> const & p : exact_matches) {
completions.push_back(serialize_decl(p.first, p.second, env, opts));
num_results++;
if (num_results >= max_results)
break;
}
}
filter_completions(pattern, selected, completions, max_results - num_results, [&](name const & n) {
return serialize_decl(n, env, opts);
});
return completions;
}
std::vector<json> get_option_completions(std::string const & pattern, options const & opts) {
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
std::vector<json> completions;
get_option_declarations().for_each([&](name const & n, option_declaration const &) {
std::string text = n.to_string();
if (matcher.match(text))
selected.emplace_back(text, n);
});
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
json completion;
completion["text"] = n.to_string();
std::stringstream ss;
get_option_declarations().find(n)->display_value(ss, opts);
completion["type"] = ss.str();
return completion;
});
return completions;
}
std::vector<json> get_import_completions(std::string const & pattern, std::string const & curr_dir,
options const & opts) {
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
std::vector<json> completions;
optional<unsigned> depth;
if (pattern.size() && pattern[0] == '.') {
unsigned i = 1;
while (i < pattern.size() && pattern[i] == '.')
i++;
depth = {i - 1};
}
std::vector<std::string> imports;
find_imports(curr_dir, depth, imports);
for (auto const & candidate : imports) {
if (matcher.match(candidate))
selected.emplace_back(candidate, candidate);
}
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
json completion;
completion["text"] = n.to_string();
return completion;
});
return completions;
}
std::vector<json> get_interactive_tactic_completions(std::string const & pattern, name const & tac_class,
environment const & env, options const & opts) {
std::vector<json> completions;
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
name namespc = tac_class + name("interactive");
env.for_each_declaration([&](declaration const & d) {
auto const & n = d.get_name();
if (n.get_prefix() == namespc && n.is_string() && matcher.match(n.get_string())) {
selected.emplace_back(n.get_string(), n);
}
});
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
return serialize_decl(n.get_string(), n, env, opts);
});
// append regular completions
for (auto candidate : get_decl_completions(pattern, env, opts))
completions.push_back(candidate);
return completions;
}
std::vector<json> get_attribute_completions(std::string const & pattern, environment const & env,
options const & opts) {
unsigned max_results = get_auto_completion_max_results(opts);
unsigned max_errors = get_fuzzy_match_max_errors(pattern.size());
std::vector<pair<std::string, name>> selected;
bitap_fuzzy_search matcher(pattern, max_errors);
std::vector<json> completions;
buffer<attribute const *> attrs;
get_attributes(env, attrs);
for (auto const & attr : attrs) {
auto s = attr->get_name().to_string();
if (matcher.match(s))
selected.emplace_back(s, attr->get_name());
}
filter_completions(pattern, selected, completions, max_results, [&](name const & n) {
json completion;
completion["text"] = n.to_string();
completion["type"] = get_attribute(env, n).get_description();
return completion;
});
return completions;
}
}
#endif
<|endoftext|> |
<commit_before>// Copyright (c) 2015, Ming Wen
#include "fys_algorithms.hpp"
using namespace std;
using namespace cv;
namespace fys {
// -------- FEATURE DETECTOR --------
FysFeatureDetector::FysFeatureDetector(string name)
{
if (name == "SIFT") {
this->detector = new SIFT();
}
else if (name == "SURF") {
this->detector = new SURF();
}
else {
this->detector = NULL;
}
}
FysFeatureDetector::FysFeatureDetector(string name, vector<string> parameters)
{
if (name == "SIFT") {
int para1 = atoi(parameters[0].c_str());
int para2 = atoi(parameters[1].c_str());
double para3 = atof(parameters[2].c_str());
double para4 = atof(parameters[2].c_str());
double para5 = atof(parameters[2].c_str());
this->detector = new SIFT(para1, para2, para3, para4, para5);
}
else {
this->detector = NULL;
}
}
FysFeatureDetector::~FysFeatureDetector() {}
cv::FeatureDetector*
FysFeatureDetector::getDetector()
{
return this->detector;
}
// -------- DESCRIPTOR EXTRACTOR --------
FysDescriptorExtractor::FysDescriptorExtractor(string name)
{
if (name == "SIFT") {
this->extractor = new SIFT();
}
else if (name == "SURF") {
this->extractor = new SURF();
}
else if (name == "FREAK") {
this->extractor = new FREAK();
}
else {
this->extractor = NULL;
}
}
FysDescriptorExtractor::FysDescriptorExtractor(string name, vector<string> parameters)
{
if (name == "SIFT") {
int para1 = atoi(parameters[0].c_str());
int para2 = atoi(parameters[1].c_str());
double para3 = atof(parameters[2].c_str());
double para4 = atof(parameters[2].c_str());
double para5 = atof(parameters[2].c_str());
this->extractor = new SIFT(para1, para2, para3, para4, para5);
}
else {
this->extractor = NULL;
}
}
FysDescriptorExtractor::~FysDescriptorExtractor() {}
cv::DescriptorExtractor*
FysDescriptorExtractor::getExtractor()
{
return this->extractor;
}
// -------- DESCRIPTOR MATCHER --------
FysDescriptorMatcher::FysDescriptorMatcher(string name)
{
if (name == "BFMatcher") {
this->matcher = new BFMatcher();
}
else {
this->matcher = NULL;
}
}
FysDescriptorMatcher::FysDescriptorMatcher(string name, vector<string> parameters)
{
if (name == "BFMatcher") {
int para1 = atoi(parameters[0].c_str());
bool para2 = atob(parameters[1].c_str());
this->matcher = new BFMatcher(para1, para2);
}
else {
this->matcher = NULL;
}
}
FysDescriptorMatcher::~FysDescriptorMatcher() {}
cv::DescriptorMatcher*
FysDescriptorMatcher::getMatcher()
{
return this->matcher;
}
// -------- ALGORITHMS --------
FysAlgorithms::FysAlgorithms(string featureJsonFile, string imageJsonFile)
: jf(featureJsonFile), ji(imageJsonFile)
{
fysDetector = new FysFeatureDetector(jf.getDetectorType(jf.doc),
jf.getParameters("detector"));
fysExtractor = new FysDescriptorExtractor(jf.getExtractorType(jf.doc),
jf.getParameters("extractor"));
fysMatcher = new FysDescriptorMatcher(jf.getMatcherType(jf.doc),
jf.getParameters("matcher"));
d = fysDetector->getDetector();
e = fysExtractor->getExtractor();
m = fysMatcher->getMatcher();
queryMats = new cv::Mat[MAT_ARRAY_SIZE];
testMats = new cv::Mat[MAT_ARRAY_SIZE];
numImages = this->ji.getNumImages(this->ji.doc);
}
FysAlgorithms::~FysAlgorithms() {}
vector<string>
FysAlgorithms::getFilenames(int groupType)
{
vector<string> names;
if (groupType == TRAIN_TYPE) {
for (int i = 0; i < this->numImages.train; ++i) {
names.push_back(this->ji.getFullName(this->ji.doc, groupType, i));
}
}
else if (groupType == VALIDATE_TYPE) {
for (int i = 0; i < this->numImages.validate; ++i) {
names.push_back(this->ji.getFullName(this->ji.doc, groupType, i));
}
}
else if (groupType == TEST_TYPE) {
for (int i = 0; i < this->numImages.test; ++i) {
names.push_back(this->ji.getFullName(this->ji.doc, groupType, i));
}
}
return names;
}
void
FysAlgorithms::readImage(cv::Mat* images, unsigned int idx, const string& filename, int flags)
{
images[idx] = imread(filename, flags);
}
void
FysAlgorithms::readImages(cv::Mat* images, const vector<string>& filenames, int flags)
{
for (unsigned int i = 0; i < filenames.size(); ++i) {
images[i] = imread(filenames[i], flags);
}
}
cv::Mat
FysAlgorithms::getImage(const string& type, unsigned int idx)
{
if (type == "query") {
return queryMats[idx];
}
else if (type == "test") {
return testMats[idx];
}
// Should not reach here
return cv::Mat();
}
// -------- OpenCV Features2D Interface --------
void
FysAlgorithms::detect(cv::Mat* images, vector<KeyPoint> keys, unsigned int idx)
{
d->detect(images[idx], keys);
}
void
FysAlgorithms::compute(cv::Mat* images, vector<KeyPoint> keys,
cv::Mat* descriptions, unsigned int idx)
{
e->compute(images[idx], keys, descriptions[idx]);
}
void
FysAlgorithms::match(cv::Mat* queryDescriptions, cv::Mat* testDescriptions,
vector<DMatch> mapping, unsigned int queryIdx, unsigned int testIdx)
{
m->match(queryDescriptions[queryIdx], testDescriptions[testIdx], mapping);
}
void
FysAlgorithms::draw(cv::Mat* querys, vector<KeyPoint> queryKeys, unsigned int queryIdx,
cv::Mat* tests, vector<KeyPoint> testKeys, unsigned int testIdx,
vector<DMatch> mapping, cv::Mat* outputs, unsigned int outputIdx)
{
drawMatches(querys[queryIdx], queryKeys, tests[testIdx], testKeys,
mapping, outputs[outputIdx]);
}
// -------- RUN ANALYSIS --------
void
FysAlgorithms::loadInfo(int groupType)
{
vector<string> filenames;
vector<cv::KeyPoint> points;
if (groupType == TRAIN_TYPE) {
filenames = this->getFilenames(groupType);
readImages(queryMats, filenames, 1); // Load 3-channel color images
this->queryKeys = vector<vector<cv::KeyPoint> >(); // clear
int i = 0;
while (i < this->numImages.train) {
this->detect(queryMats, points, i);
// Reduce the keypoints here
this->queryKeys.push_back(points);
++i;
}
i = 0;
while (i < this->numImages.train) {
this->compute(queryMats, queryKeys[i], queryDescriptions, i);
++i;
}
}
else if (groupType == VALIDATE_TYPE || groupType == TEST_TYPE) {
filenames = this->getFilenames(groupType);
readImages(testMats, filenames, 1); // Load 3-channel color images
this->testKeys = vector<vector<cv::KeyPoint> >(); // clear
int i = 0;
int numTestImages = 0;
if (groupType == VALIDATE_TYPE) {
numTestImages = this->numImages.validate;
}
else if (groupType == TEST_TYPE) {
numTestImages = this->numImages.test;
}
while (i < numTestImages) {
this->detect(testMats, points, i);
// Reduce the keypoinst here
this->queryKeys.push_back(points);
++i;
}
i = 0;
while (i < numTestImages) {
this->compute(testMats, testKeys[i], testDescriptions, i);
++i;
}
}
else {
std::cerr << "Invalid group type of images!" << std::endl;
}
return;
}
void
FysAlgorithms::runValidate()
{
this->loadInfo(TRAIN_TYPE);
this->loadInfo(VALIDATE_TYPE);
this->runAlgorithm(VALIDATE_TYPE);
}
void
FysAlgorithms::runTest()
{
this->loadInfo(TRAIN_TYPE);
this->loadInfo(TEST_TYPE);
this->runAlgorithm(TEST_TYPE);
}
void
FysAlgorithms::runAlgorithm(int runType)
{
}
} // namespace fys
<commit_msg>implement runAlgorithm(), the main method<commit_after>// Copyright (c) 2015, Ming Wen
#include "fys_algorithms.hpp"
using namespace std;
using namespace cv;
namespace fys {
// -------- FEATURE DETECTOR --------
FysFeatureDetector::FysFeatureDetector(string name)
{
if (name == "SIFT") {
this->detector = new SIFT();
}
else if (name == "SURF") {
this->detector = new SURF();
}
else {
this->detector = NULL;
}
}
FysFeatureDetector::FysFeatureDetector(string name, vector<string> parameters)
{
if (name == "SIFT") {
int para1 = atoi(parameters[0].c_str());
int para2 = atoi(parameters[1].c_str());
double para3 = atof(parameters[2].c_str());
double para4 = atof(parameters[2].c_str());
double para5 = atof(parameters[2].c_str());
this->detector = new SIFT(para1, para2, para3, para4, para5);
}
else {
this->detector = NULL;
}
}
FysFeatureDetector::~FysFeatureDetector() {}
cv::FeatureDetector*
FysFeatureDetector::getDetector()
{
return this->detector;
}
// -------- DESCRIPTOR EXTRACTOR --------
FysDescriptorExtractor::FysDescriptorExtractor(string name)
{
if (name == "SIFT") {
this->extractor = new SIFT();
}
else if (name == "SURF") {
this->extractor = new SURF();
}
else if (name == "FREAK") {
this->extractor = new FREAK();
}
else {
this->extractor = NULL;
}
}
FysDescriptorExtractor::FysDescriptorExtractor(string name, vector<string> parameters)
{
if (name == "SIFT") {
int para1 = atoi(parameters[0].c_str());
int para2 = atoi(parameters[1].c_str());
double para3 = atof(parameters[2].c_str());
double para4 = atof(parameters[2].c_str());
double para5 = atof(parameters[2].c_str());
this->extractor = new SIFT(para1, para2, para3, para4, para5);
}
else {
this->extractor = NULL;
}
}
FysDescriptorExtractor::~FysDescriptorExtractor() {}
cv::DescriptorExtractor*
FysDescriptorExtractor::getExtractor()
{
return this->extractor;
}
// -------- DESCRIPTOR MATCHER --------
FysDescriptorMatcher::FysDescriptorMatcher(string name)
{
if (name == "BFMatcher") {
this->matcher = new BFMatcher();
}
else {
this->matcher = NULL;
}
}
FysDescriptorMatcher::FysDescriptorMatcher(string name, vector<string> parameters)
{
if (name == "BFMatcher") {
int para1 = atoi(parameters[0].c_str());
bool para2 = atob(parameters[1].c_str());
this->matcher = new BFMatcher(para1, para2);
}
else {
this->matcher = NULL;
}
}
FysDescriptorMatcher::~FysDescriptorMatcher() {}
cv::DescriptorMatcher*
FysDescriptorMatcher::getMatcher()
{
return this->matcher;
}
// -------- ALGORITHMS --------
FysAlgorithms::FysAlgorithms(string featureJsonFile, string imageJsonFile)
: jf(featureJsonFile), ji(imageJsonFile)
{
fysDetector = new FysFeatureDetector(jf.getDetectorType(jf.doc),
jf.getParameters("detector"));
fysExtractor = new FysDescriptorExtractor(jf.getExtractorType(jf.doc),
jf.getParameters("extractor"));
fysMatcher = new FysDescriptorMatcher(jf.getMatcherType(jf.doc),
jf.getParameters("matcher"));
d = fysDetector->getDetector();
e = fysExtractor->getExtractor();
m = fysMatcher->getMatcher();
queryMats = new cv::Mat[MAT_ARRAY_SIZE];
testMats = new cv::Mat[MAT_ARRAY_SIZE];
numImages = this->ji.getNumImages(this->ji.doc);
}
FysAlgorithms::~FysAlgorithms() {}
vector<string>
FysAlgorithms::getFilenames(int groupType)
{
vector<string> names;
if (groupType == TRAIN_TYPE) {
for (int i = 0; i < this->numImages.train; ++i) {
names.push_back(this->ji.getFullName(this->ji.doc, groupType, i));
}
}
else if (groupType == VALIDATE_TYPE) {
for (int i = 0; i < this->numImages.validate; ++i) {
names.push_back(this->ji.getFullName(this->ji.doc, groupType, i));
}
}
else if (groupType == TEST_TYPE) {
for (int i = 0; i < this->numImages.test; ++i) {
names.push_back(this->ji.getFullName(this->ji.doc, groupType, i));
}
}
return names;
}
void
FysAlgorithms::readImage(cv::Mat* images, unsigned int idx, const string& filename, int flags)
{
images[idx] = imread(filename, flags);
}
void
FysAlgorithms::readImages(cv::Mat* images, const vector<string>& filenames, int flags)
{
for (unsigned int i = 0; i < filenames.size(); ++i) {
images[i] = imread(filenames[i], flags);
}
}
cv::Mat
FysAlgorithms::getImage(const string& type, unsigned int idx)
{
if (type == "query") {
return queryMats[idx];
}
else if (type == "test") {
return testMats[idx];
}
// Should not reach here
return cv::Mat();
}
// -------- OpenCV Features2D Interface --------
void
FysAlgorithms::detect(cv::Mat* images, vector<KeyPoint> keys, unsigned int idx)
{
d->detect(images[idx], keys);
}
void
FysAlgorithms::compute(cv::Mat* images, vector<KeyPoint> keys,
cv::Mat* descriptions, unsigned int idx)
{
e->compute(images[idx], keys, descriptions[idx]);
}
void
FysAlgorithms::match(cv::Mat* queryDescriptions, cv::Mat* testDescriptions,
vector<DMatch> mapping, unsigned int queryIdx, unsigned int testIdx)
{
m->match(queryDescriptions[queryIdx], testDescriptions[testIdx], mapping);
}
void
FysAlgorithms::draw(cv::Mat* querys, vector<KeyPoint> queryKeys, unsigned int queryIdx,
cv::Mat* tests, vector<KeyPoint> testKeys, unsigned int testIdx,
vector<DMatch> mapping, cv::Mat* outputs, unsigned int outputIdx)
{
drawMatches(querys[queryIdx], queryKeys, tests[testIdx], testKeys,
mapping, outputs[outputIdx]);
}
// -------- RUN ANALYSIS --------
void
FysAlgorithms::loadInfo(int groupType)
{
vector<string> filenames;
vector<cv::KeyPoint> points;
if (groupType == TRAIN_TYPE) {
filenames = this->getFilenames(groupType);
readImages(queryMats, filenames, 1); // Load 3-channel color images
this->queryKeys = vector<vector<cv::KeyPoint> >(); // clear
int i = 0;
while (i < this->numImages.train) {
this->detect(queryMats, points, i);
// Reduce the keypoints here
this->queryKeys.push_back(points);
++i;
}
i = 0;
while (i < this->numImages.train) {
this->compute(queryMats, queryKeys[i], queryDescriptions, i);
++i;
}
}
else if (groupType == VALIDATE_TYPE || groupType == TEST_TYPE) {
filenames = this->getFilenames(groupType);
readImages(testMats, filenames, 1); // Load 3-channel color images
this->testKeys = vector<vector<cv::KeyPoint> >(); // clear
int i = 0;
int numTestImages = 0;
if (groupType == VALIDATE_TYPE) {
numTestImages = this->numImages.validate;
}
else if (groupType == TEST_TYPE) {
numTestImages = this->numImages.test;
}
while (i < numTestImages) {
this->detect(testMats, points, i);
// Reduce the keypoinst here
this->queryKeys.push_back(points);
++i;
}
i = 0;
while (i < numTestImages) {
this->compute(testMats, testKeys[i], testDescriptions, i);
++i;
}
}
else {
std::cerr << "Invalid group type of images!" << std::endl;
}
return;
}
void
FysAlgorithms::runValidate()
{
this->loadInfo(TRAIN_TYPE);
this->loadInfo(VALIDATE_TYPE);
this->runAlgorithm(VALIDATE_TYPE);
}
void
FysAlgorithms::runTest()
{
this->loadInfo(TRAIN_TYPE);
this->loadInfo(TEST_TYPE);
this->runAlgorithm(TEST_TYPE);
}
void
FysAlgorithms::runAlgorithm(int runType)
{
int numTestImages = 0;
if (runType == VALIDATE_TYPE) {
numTestImages = this->numImages.validate;
}
else if (runType == TEST_TYPE) {
numTestImages = this->numImages.test;
}
int i = 0;
int j = 0;
vector<DMatch> mapping;
while (i < numTestImages) {
j = 0;
while (j < this->numImages.train) {
this->match(queryDescriptions, testDescriptions, mapping, j, i);
this->matches.push_back(mapping);
++j;
}
++i;
}
}
} // namespace fys
<|endoftext|> |
<commit_before>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library 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 2.1 of the License, or (at your option) any later version.
// 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
// Local includes
#include "libmesh/elem_cutter.h"
#include "libmesh/elem.h"
#include "libmesh/serial_mesh.h"
#include "libmesh/mesh_triangle_interface.h"
#include "libmesh/mesh_tetgen_interface.h"
// C++ includes
namespace
{
unsigned int cut_cntr;
}
namespace libMesh
{
// ------------------------------------------------------------
// ElemCutter implementation
ElemCutter::ElemCutter()
{
_inside_mesh_2D.reset (new SerialMesh(2)); /**/ _triangle_inside.reset (new TriangleInterface (*_inside_mesh_2D));
_outside_mesh_2D.reset (new SerialMesh(2)); /**/ _triangle_outside.reset (new TriangleInterface (*_outside_mesh_2D));
_inside_mesh_3D.reset (new SerialMesh(3)); /**/ _tetgen_inside.reset (new TetGenMeshInterface (*_inside_mesh_3D));
_outside_mesh_3D.reset (new SerialMesh(3)); /**/ _tetgen_outside.reset (new TetGenMeshInterface (*_outside_mesh_3D));
cut_cntr = 0;
}
ElemCutter::~ElemCutter()
{}
bool ElemCutter::is_inside (const Elem &elem,
const std::vector<Real> &vertex_distance_func) const
{
libmesh_assert_equal_to (elem.n_vertices(), vertex_distance_func.size());
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
if (*it > 0.) return false;
// if the distance function is nonpositive, we are outside
return true;
}
bool ElemCutter::is_outside (const Elem &elem,
const std::vector<Real> &vertex_distance_func) const
{
libmesh_assert_equal_to (elem.n_vertices(), vertex_distance_func.size());
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
if (*it < 0.) return false;
// if the distance function is nonnegative, we are outside
return true;
}
bool ElemCutter::is_cut (const Elem &elem,
const std::vector<Real> &vertex_distance_func) const
{
libmesh_assert_equal_to (elem.n_vertices(), vertex_distance_func.size());
Real
vmin = vertex_distance_func.front(),
vmax = vmin;
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
{
vmin = std::min (vmin, *it);
vmax = std::max (vmax, *it);
}
// if the distance function changes sign, we're cut.
return (vmin*vmax < 0.);
}
void ElemCutter::operator()(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
libmesh_assert_equal_to (vertex_distance_func.size(), elem.n_vertices());
_inside_elem.clear();
_outside_elem.clear();
// check for quick return?
{
// completely outside?
if (this->is_outside(elem, vertex_distance_func))
{
//std::cout << "element completely outside\n";
_outside_elem.push_back(&elem);
return;
}
// completely inside?
else if (this->is_inside(elem, vertex_distance_func))
{
//std::cout << "element completely inside\n";
_inside_elem.push_back(&elem);
return;
}
libmesh_assert (this->is_cut (elem, vertex_distance_func));
}
// we now know we are in a cut element, find the intersecting points.
this->find_intersection_points (elem, vertex_distance_func);
// and then dispatch the proper method
switch (elem.dim())
{
case 1: this->cut_1D(elem, vertex_distance_func); break;
case 2: this->cut_2D(elem, vertex_distance_func); break;
case 3: this->cut_3D(elem, vertex_distance_func); break;
default: libmesh_error();
}
}
void ElemCutter::find_intersection_points(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
_intersection_pts.clear();
for (unsigned int e=0; e<elem.n_edges(); e++)
{
AutoPtr<Elem> edge (elem.build_edge(e));
// find the element nodes el0, el1 that map
unsigned int
el0 = elem.get_node_index(edge->get_node(0)),
el1 = elem.get_node_index(edge->get_node(1));
libmesh_assert (elem.is_vertex(el0));
libmesh_assert (elem.is_vertex(el1));
libmesh_assert_less (el0, vertex_distance_func.size());
libmesh_assert_less (el1, vertex_distance_func.size());
const Real
d0 = vertex_distance_func[el0],
d1 = vertex_distance_func[el1];
// if this egde has a 0 crossing
if (d0*d1 < 0.)
{
libmesh_assert_not_equal_to (d0, d1);
// then find d_star in [0,1], the
// distance from el0 to el1 where the 0 lives.
const Real d_star = d0 / (d0 - d1);
// Prevent adding nodes trivially close to existing
// nodes.
const Real endpoint_tol = 0.01;
if ( (d_star > endpoint_tol) &&
(d_star < (1.-endpoint_tol)) )
{
const Point x_star = (edge->point(0)*(1.-d_star) +
edge->point(1)*d_star);
std::cout << "adding cut point (d_star, x_star) = "
<< d_star << " , " << x_star << std::endl;
_intersection_pts.push_back (x_star);
}
}
}
}
void ElemCutter::cut_1D (const Elem & /*elem*/,
const std::vector<Real> &/*vertex_distance_func*/)
{
libmesh_not_implemented();
}
void ElemCutter::cut_2D (const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
#ifndef LIBMESH_HAVE_TRIANGLE
// current implementation requires triangle!
libMesh::err << "ERROR: current libMesh ElemCutter 2D implementation requires\n"
<< " the \"triangle\" library!\n"
<< std::endl;
libmesh_not_implemented();
#else // OK, LIBMESH_HAVE_TRIANGLE
std::cout << "Inside cut face element!\n";
libmesh_assert (_inside_mesh_2D.get() != NULL);
libmesh_assert (_outside_mesh_2D.get() != NULL);
_inside_mesh_2D->clear();
_outside_mesh_2D->clear();
for (unsigned int v=0; v<elem.n_vertices(); v++)
{
if (vertex_distance_func[v] >= 0.)
_outside_mesh_2D->add_point (elem.point(v));
if (vertex_distance_func[v] <= 0.)
_inside_mesh_2D->add_point (elem.point(v));
}
for (std::vector<Point>::const_iterator it=_intersection_pts.begin();
it != _intersection_pts.end(); ++it)
{
_inside_mesh_2D->add_point(*it);
_outside_mesh_2D->add_point(*it);
}
// Customize the variables for the triangulation
// we will be cutting reference cell, and want as few triangles
// as possible, so jack this up larger than the area we will be
// triangulating so we are governed only by accurately defining
// the boundaries.
_triangle_inside->desired_area() = 100.;
_triangle_outside->desired_area() = 100.;
// allow for small angles
_triangle_inside->minimum_angle() = 5.;
_triangle_outside->minimum_angle() = 5.;
// Turn off Laplacian mesh smoothing after generation.
_triangle_inside->smooth_after_generating() = false;
_triangle_outside->smooth_after_generating() = false;
// Triangulate!
_triangle_inside->triangulate();
_triangle_outside->triangulate();
// std::ostringstream name;
// name << "cut_face_"
// << cut_cntr++
// << ".dat";
// _inside_mesh_2D->write ("in_" + name.str());
// _outside_mesh_2D->write ("out_" + name.str());
// finally, add the elements to our lists.
{
_inside_elem.clear(); /**/ _outside_elem.clear();
MeshBase::const_element_iterator
it = _inside_mesh_2D->elements_begin(),
end = _inside_mesh_2D->elements_end();
for (; it!=end; ++it)
_inside_elem.push_back (*it);
it = _outside_mesh_2D->elements_begin();
end = _outside_mesh_2D->elements_end();
for (; it!=end; ++it)
_outside_elem.push_back (*it);
}
#endif
}
void ElemCutter::cut_3D (const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
#ifndef LIBMESH_HAVE_TETGEN
// current implementation requires tetgen!
libMesh::err << "ERROR: current libMesh ElemCutter 3D implementation requires\n"
<< " the \"tetgen\" library!\n"
<< std::endl;
libmesh_not_implemented();
#else // OK, LIBMESH_HAVE_TETGEN
std::cout << "Inside cut cell element!\n";
libmesh_assert (_inside_mesh_3D.get() != NULL);
libmesh_assert (_outside_mesh_3D.get() != NULL);
_inside_mesh_3D->clear();
_outside_mesh_3D->clear();
for (unsigned int v=0; v<elem.n_vertices(); v++)
{
if (vertex_distance_func[v] >= 0.)
_outside_mesh_3D->add_point (elem.point(v));
if (vertex_distance_func[v] <= 0.)
_inside_mesh_3D->add_point (elem.point(v));
}
for (std::vector<Point>::const_iterator it=_intersection_pts.begin();
it != _intersection_pts.end(); ++it)
{
_inside_mesh_3D->add_point(*it);
_outside_mesh_3D->add_point(*it);
}
// // Customize the variables for the triangulation
// // we will be cutting reference cell, and want as few triangles
// // as possible, so jack this up larger than the area we will be
// // triangulating so we are governed only by accurately defining
// // the boundaries.
// _tetgen_inside->desired_area() = 100.;
// _tetgen_outside->desired_area() = 100.;
// // allow for small angles
// _tetgen_inside->minimum_angle() = 5.;
// _tetgen_outside->minimum_angle() = 5.;
// // Turn off Laplacian mesh smoothing after generation.
// _tetgen_inside->smooth_after_generating() = false;
// _tetgen_outside->smooth_after_generating() = false;
// Triangulate!
_tetgen_inside->triangulate_pointset();
_tetgen_outside->triangulate_pointset();
std::ostringstream name;
name << "cut_cell_"
<< cut_cntr++
<< ".dat";
_inside_mesh_3D->write ("in_" + name.str());
_outside_mesh_3D->write ("out_" + name.str());
// finally, add the elements to our lists.
{
_inside_elem.clear(); /**/ _outside_elem.clear();
MeshBase::const_element_iterator
it = _inside_mesh_3D->elements_begin(),
end = _inside_mesh_3D->elements_end();
for (; it!=end; ++it)
_inside_elem.push_back (*it);
it = _outside_mesh_3D->elements_begin();
end = _outside_mesh_3D->elements_end();
for (; it!=end; ++it)
_outside_elem.push_back (*it);
}
#endif
}
} // namespace libMesh
<commit_msg>workaround for 0-volume cells<commit_after>// The libMesh Finite Element Library.
// Copyright (C) 2002-2013 Benjamin S. Kirk, John W. Peterson, Roy H. Stogner
// This library 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 2.1 of the License, or (at your option) any later version.
// 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
// Local includes
#include "libmesh/elem_cutter.h"
#include "libmesh/elem.h"
#include "libmesh/serial_mesh.h"
#include "libmesh/mesh_triangle_interface.h"
#include "libmesh/mesh_tetgen_interface.h"
// C++ includes
namespace
{
unsigned int cut_cntr;
}
namespace libMesh
{
// ------------------------------------------------------------
// ElemCutter implementation
ElemCutter::ElemCutter()
{
_inside_mesh_2D.reset (new SerialMesh(2)); /**/ _triangle_inside.reset (new TriangleInterface (*_inside_mesh_2D));
_outside_mesh_2D.reset (new SerialMesh(2)); /**/ _triangle_outside.reset (new TriangleInterface (*_outside_mesh_2D));
_inside_mesh_3D.reset (new SerialMesh(3)); /**/ _tetgen_inside.reset (new TetGenMeshInterface (*_inside_mesh_3D));
_outside_mesh_3D.reset (new SerialMesh(3)); /**/ _tetgen_outside.reset (new TetGenMeshInterface (*_outside_mesh_3D));
cut_cntr = 0;
}
ElemCutter::~ElemCutter()
{}
bool ElemCutter::is_inside (const Elem &elem,
const std::vector<Real> &vertex_distance_func) const
{
libmesh_assert_equal_to (elem.n_vertices(), vertex_distance_func.size());
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
if (*it > 0.) return false;
// if the distance function is nonpositive, we are outside
return true;
}
bool ElemCutter::is_outside (const Elem &elem,
const std::vector<Real> &vertex_distance_func) const
{
libmesh_assert_equal_to (elem.n_vertices(), vertex_distance_func.size());
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
if (*it < 0.) return false;
// if the distance function is nonnegative, we are outside
return true;
}
bool ElemCutter::is_cut (const Elem &elem,
const std::vector<Real> &vertex_distance_func) const
{
libmesh_assert_equal_to (elem.n_vertices(), vertex_distance_func.size());
Real
vmin = vertex_distance_func.front(),
vmax = vmin;
for (std::vector<Real>::const_iterator it=vertex_distance_func.begin();
it!=vertex_distance_func.end(); ++it)
{
vmin = std::min (vmin, *it);
vmax = std::max (vmax, *it);
}
// if the distance function changes sign, we're cut.
return (vmin*vmax < 0.);
}
void ElemCutter::operator()(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
libmesh_assert_equal_to (vertex_distance_func.size(), elem.n_vertices());
_inside_elem.clear();
_outside_elem.clear();
// check for quick return?
{
// completely outside?
if (this->is_outside(elem, vertex_distance_func))
{
//std::cout << "element completely outside\n";
_outside_elem.push_back(&elem);
return;
}
// completely inside?
else if (this->is_inside(elem, vertex_distance_func))
{
//std::cout << "element completely inside\n";
_inside_elem.push_back(&elem);
return;
}
libmesh_assert (this->is_cut (elem, vertex_distance_func));
}
// we now know we are in a cut element, find the intersecting points.
this->find_intersection_points (elem, vertex_distance_func);
// and then dispatch the proper method
switch (elem.dim())
{
case 1: this->cut_1D(elem, vertex_distance_func); break;
case 2: this->cut_2D(elem, vertex_distance_func); break;
case 3: this->cut_3D(elem, vertex_distance_func); break;
default: libmesh_error();
}
}
void ElemCutter::find_intersection_points(const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
_intersection_pts.clear();
for (unsigned int e=0; e<elem.n_edges(); e++)
{
AutoPtr<Elem> edge (elem.build_edge(e));
// find the element nodes el0, el1 that map
unsigned int
el0 = elem.get_node_index(edge->get_node(0)),
el1 = elem.get_node_index(edge->get_node(1));
libmesh_assert (elem.is_vertex(el0));
libmesh_assert (elem.is_vertex(el1));
libmesh_assert_less (el0, vertex_distance_func.size());
libmesh_assert_less (el1, vertex_distance_func.size());
const Real
d0 = vertex_distance_func[el0],
d1 = vertex_distance_func[el1];
// if this egde has a 0 crossing
if (d0*d1 < 0.)
{
libmesh_assert_not_equal_to (d0, d1);
// then find d_star in [0,1], the
// distance from el0 to el1 where the 0 lives.
const Real d_star = d0 / (d0 - d1);
// Prevent adding nodes trivially close to existing
// nodes.
const Real endpoint_tol = 0.01;
if ( (d_star > endpoint_tol) &&
(d_star < (1.-endpoint_tol)) )
{
const Point x_star = (edge->point(0)*(1.-d_star) +
edge->point(1)*d_star);
std::cout << "adding cut point (d_star, x_star) = "
<< d_star << " , " << x_star << std::endl;
_intersection_pts.push_back (x_star);
}
}
}
}
void ElemCutter::cut_1D (const Elem & /*elem*/,
const std::vector<Real> &/*vertex_distance_func*/)
{
libmesh_not_implemented();
}
void ElemCutter::cut_2D (const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
#ifndef LIBMESH_HAVE_TRIANGLE
// current implementation requires triangle!
libMesh::err << "ERROR: current libMesh ElemCutter 2D implementation requires\n"
<< " the \"triangle\" library!\n"
<< std::endl;
libmesh_not_implemented();
#else // OK, LIBMESH_HAVE_TRIANGLE
std::cout << "Inside cut face element!\n";
libmesh_assert (_inside_mesh_2D.get() != NULL);
libmesh_assert (_outside_mesh_2D.get() != NULL);
_inside_mesh_2D->clear();
_outside_mesh_2D->clear();
for (unsigned int v=0; v<elem.n_vertices(); v++)
{
if (vertex_distance_func[v] >= 0.)
_outside_mesh_2D->add_point (elem.point(v));
if (vertex_distance_func[v] <= 0.)
_inside_mesh_2D->add_point (elem.point(v));
}
for (std::vector<Point>::const_iterator it=_intersection_pts.begin();
it != _intersection_pts.end(); ++it)
{
_inside_mesh_2D->add_point(*it);
_outside_mesh_2D->add_point(*it);
}
// Customize the variables for the triangulation
// we will be cutting reference cell, and want as few triangles
// as possible, so jack this up larger than the area we will be
// triangulating so we are governed only by accurately defining
// the boundaries.
_triangle_inside->desired_area() = 100.;
_triangle_outside->desired_area() = 100.;
// allow for small angles
_triangle_inside->minimum_angle() = 5.;
_triangle_outside->minimum_angle() = 5.;
// Turn off Laplacian mesh smoothing after generation.
_triangle_inside->smooth_after_generating() = false;
_triangle_outside->smooth_after_generating() = false;
// Triangulate!
_triangle_inside->triangulate();
_triangle_outside->triangulate();
// std::ostringstream name;
// name << "cut_face_"
// << cut_cntr++
// << ".dat";
// _inside_mesh_2D->write ("in_" + name.str());
// _outside_mesh_2D->write ("out_" + name.str());
// finally, add the elements to our lists.
{
_inside_elem.clear(); /**/ _outside_elem.clear();
MeshBase::const_element_iterator
it = _inside_mesh_2D->elements_begin(),
end = _inside_mesh_2D->elements_end();
for (; it!=end; ++it)
_inside_elem.push_back (*it);
it = _outside_mesh_2D->elements_begin();
end = _outside_mesh_2D->elements_end();
for (; it!=end; ++it)
_outside_elem.push_back (*it);
}
#endif
}
void ElemCutter::cut_3D (const Elem &elem,
const std::vector<Real> &vertex_distance_func)
{
#ifndef LIBMESH_HAVE_TETGEN
// current implementation requires tetgen!
libMesh::err << "ERROR: current libMesh ElemCutter 3D implementation requires\n"
<< " the \"tetgen\" library!\n"
<< std::endl;
libmesh_not_implemented();
#else // OK, LIBMESH_HAVE_TETGEN
std::cout << "Inside cut cell element!\n";
libmesh_assert (_inside_mesh_3D.get() != NULL);
libmesh_assert (_outside_mesh_3D.get() != NULL);
_inside_mesh_3D->clear();
_outside_mesh_3D->clear();
for (unsigned int v=0; v<elem.n_vertices(); v++)
{
if (vertex_distance_func[v] >= 0.)
_outside_mesh_3D->add_point (elem.point(v));
if (vertex_distance_func[v] <= 0.)
_inside_mesh_3D->add_point (elem.point(v));
}
for (std::vector<Point>::const_iterator it=_intersection_pts.begin();
it != _intersection_pts.end(); ++it)
{
_inside_mesh_3D->add_point(*it);
_outside_mesh_3D->add_point(*it);
}
// Triangulate!
_tetgen_inside->triangulate_pointset();
//_inside_mesh_3D->print_info();
_tetgen_outside->triangulate_pointset();
//_outside_mesh_3D->print_info();
// (below generates some horribly expensive meshes,
// but seems immune to the 0 volume problem).
// _tetgen_inside->pointset_convexhull();
// _inside_mesh_3D->find_neighbors();
// _inside_mesh_3D->print_info();
// _tetgen_inside->triangulate_conformingDelaunayMesh (1.e3, 100.);
// _inside_mesh_3D->print_info();
// _tetgen_outside->pointset_convexhull();
// _outside_mesh_3D->find_neighbors();
// _outside_mesh_3D->print_info();
// _tetgen_outside->triangulate_conformingDelaunayMesh (1.e3, 100.);
// _outside_mesh_3D->print_info();
std::ostringstream name;
name << "cut_cell_"
<< cut_cntr++
<< ".dat";
_inside_mesh_3D->write ("in_" + name.str());
_outside_mesh_3D->write ("out_" + name.str());
// finally, add the elements to our lists.
{
_inside_elem.clear(); /**/ _outside_elem.clear();
MeshBase::const_element_iterator
it = _inside_mesh_3D->elements_begin(),
end = _inside_mesh_3D->elements_end();
for (; it!=end; ++it)
if ((*it)->volume() > std::numeric_limits<Real>::epsilon())
_inside_elem.push_back (*it);
it = _outside_mesh_3D->elements_begin();
end = _outside_mesh_3D->elements_end();
for (; it!=end; ++it)
if ((*it)->volume() > std::numeric_limits<Real>::epsilon())
_outside_elem.push_back (*it);
}
#endif
}
} // namespace libMesh
<|endoftext|> |
<commit_before>// glfw3_skeleton.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <sstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#ifdef USE_CUDA
#else
# include "vector_make_helpers.h"
#endif
#include "GL/ShaderFunctions.h"
#include "MatrixMath.h"
#include "utils/Logger.h"
#include "paramgl.h"
#include "AntAppSkeleton.h"
AntAppSkeleton g_app;
int running = 0;
GLFWwindow* g_pWindow;
void display()
{
g_app.display();
glfwSwapBuffers(g_pWindow);
}
void mouseDown(GLFWwindow* pWin, int button, int action, int mods)
{
double x,y;
glfwGetCursorPos(g_pWindow, &x, &y);
g_app.mouseDown(button, action, x, y);
}
void mouseMove(GLFWwindow* window, double x, double y)
{
//int x,y;
//glfwGetMousePos(&x, &y);
g_app.mouseMove(x, y);
}
void mouseWheel(GLFWwindow* window, double x, double y)
{
g_app.mouseWheel(x, y);
}
void keyboard(GLFWwindow* window, int key, int action, int, int)
{
g_app.keyboard(key, 0,0);
}
void charkey(GLFWwindow* window, unsigned int key)
{
g_app.charkey(key);
}
void resize(GLFWwindow* window, int w, int h)
{
g_app.resize(w,h);
TwWindowSize(w,h);
}
bool initGL(int argc, char **argv)
{
return g_app.initGL(argc, argv);
}
bool initGlfw(int argc, char **argv)
{
if (!glfwInit())
return -1;
const int w = 640;
const int h = 480;
g_pWindow = glfwCreateWindow(w, h, "GLSkeleton - GLFW 3", NULL, NULL);
if (!g_pWindow)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(g_pWindow);
glfwSetWindowSizeCallback (g_pWindow, resize);
glfwSetMouseButtonCallback(g_pWindow, mouseDown);
glfwSetCursorPosCallback (g_pWindow, mouseMove);
glfwSetScrollCallback (g_pWindow, mouseWheel);
glfwSetKeyCallback (g_pWindow, keyboard);
glfwSetCharCallback (g_pWindow, charkey);
///@note Bad size errors will be thrown if this is not called at init
TwWindowSize(w, h);
return 1;
}
/// Dump a list of monitor info to Log and stdout.
/// http://www.glfw.org/docs/3.0/monitor.html
void PrintMonitorInfo()
{
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
printf("Found %d monitors:\n", count);
LOG_INFO("Found %d monitors:", count);
for (int i=0; i<count; ++i)
{
GLFWmonitor* pMonitor = monitors[i];
if (pMonitor == NULL)
continue;
printf(" Monitor %d:\n", i);
LOG_INFO(" Monitor %d:", i);
/// Monitor name
const char* pName = glfwGetMonitorName(pMonitor);
printf(" Name: %s\n", pName);
LOG_INFO(" Name: %s", pName);
/// Monitor Physical Size
int widthMM, heightMM;
glfwGetMonitorPhysicalSize(pMonitor, &widthMM, &heightMM);
//const double dpi = mode->width / (widthMM / 25.4);
printf(" physical size: %d x %d mm\n");
LOG_INFO(" physical size: %d x %d mm");
/// Modes
const GLFWvidmode* mode = glfwGetVideoMode(pMonitor);
printf(" Current mode: %dx%d @ %dHz (RGB %d %d %d bits)\n",
mode->width,
mode->height,
mode->refreshRate,
mode->redBits,
mode->greenBits,
mode->blueBits);
LOG_INFO(" Current mode: %dx%d @ %dHz (RGB %d %d %d bits)",
mode->width,
mode->height,
mode->refreshRate,
mode->redBits,
mode->greenBits,
mode->blueBits);
#if 0
int modeCount;
const GLFWvidmode* modes = glfwGetVideoModes(pMonitor, &modeCount);
printf(" %d Modes:\n", modeCount);
LOG_INFO(" %d Modes:", modeCount);
for (int j=0; j<modeCount; ++j)
{
const GLFWvidmode& m = modes[j];
printf(" %dx%d @ %dHz (RGB %d %d %d bits)\n",
m.width, m.height, m.refreshRate, m.redBits, m.greenBits, m.blueBits);
LOG_INFO(" %dx%d @ %dHz (RGB %d %d %d bits)",
m.width, m.height, m.refreshRate, m.redBits, m.greenBits, m.blueBits);
}
#endif
}
}
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
if (!initGlfw(argc, argv))
return 0;
if (!initGL(argc, argv))
return 0;
PrintMonitorInfo();
LOG_INFO("Starting main loop.");
running = GL_TRUE;
//g_timer.reset();
while (running && !glfwWindowShouldClose(g_pWindow))
{
//float dt = (float)g_timer.seconds();
//timestep(dt);
//g_timer.reset();
display();
//running = running && glfwGetWindowParam(GLFW_OPENED);
glfwPollEvents();
}
TwTerminate();
glfwTerminate();
return 0;
}
<commit_msg>Fix build for glfw3 skeleton in case where Ant is turned off.<commit_after>// glfw3_skeleton.cpp
#ifdef _WIN32
# define WINDOWS_LEAN_AND_MEAN
# define NOMINMAX
# include <windows.h>
#endif
#include <sstream>
#include <GL/glew.h>
#include <GLFW/glfw3.h>
#ifdef USE_CUDA
#else
# include "vector_make_helpers.h"
#endif
#include "GL/ShaderFunctions.h"
#include "MatrixMath.h"
#include "utils/Logger.h"
#include "paramgl.h"
#include "AntAppSkeleton.h"
AntAppSkeleton g_app;
int running = 0;
GLFWwindow* g_pWindow;
void display()
{
g_app.display();
glfwSwapBuffers(g_pWindow);
}
void mouseDown(GLFWwindow* pWin, int button, int action, int mods)
{
double x,y;
glfwGetCursorPos(g_pWindow, &x, &y);
g_app.mouseDown(button, action, x, y);
}
void mouseMove(GLFWwindow* window, double x, double y)
{
//int x,y;
//glfwGetMousePos(&x, &y);
g_app.mouseMove(x, y);
}
void mouseWheel(GLFWwindow* window, double x, double y)
{
g_app.mouseWheel(x, y);
}
void keyboard(GLFWwindow* window, int key, int action, int, int)
{
g_app.keyboard(key, 0,0);
}
void charkey(GLFWwindow* window, unsigned int key)
{
g_app.charkey(key);
}
void resize(GLFWwindow* window, int w, int h)
{
g_app.resize(w,h);
#ifdef USE_ANTTWEAKBAR
TwWindowSize(w,h);
#endif
}
bool initGL(int argc, char **argv)
{
return g_app.initGL(argc, argv);
}
bool initGlfw(int argc, char **argv)
{
if (!glfwInit())
return -1;
const int w = 640;
const int h = 480;
g_pWindow = glfwCreateWindow(w, h, "GLSkeleton - GLFW 3", NULL, NULL);
if (!g_pWindow)
{
glfwTerminate();
return -1;
}
glfwMakeContextCurrent(g_pWindow);
glfwSetWindowSizeCallback (g_pWindow, resize);
glfwSetMouseButtonCallback(g_pWindow, mouseDown);
glfwSetCursorPosCallback (g_pWindow, mouseMove);
glfwSetScrollCallback (g_pWindow, mouseWheel);
glfwSetKeyCallback (g_pWindow, keyboard);
glfwSetCharCallback (g_pWindow, charkey);
#ifdef USE_ANTTWEAKBAR
///@note Bad size errors will be thrown if this is not called at init
TwWindowSize(w, h);
#endif
return 1;
}
/// Dump a list of monitor info to Log and stdout.
/// http://www.glfw.org/docs/3.0/monitor.html
void PrintMonitorInfo()
{
int count;
GLFWmonitor** monitors = glfwGetMonitors(&count);
printf("Found %d monitors:\n", count);
LOG_INFO("Found %d monitors:", count);
for (int i=0; i<count; ++i)
{
GLFWmonitor* pMonitor = monitors[i];
if (pMonitor == NULL)
continue;
printf(" Monitor %d:\n", i);
LOG_INFO(" Monitor %d:", i);
/// Monitor name
const char* pName = glfwGetMonitorName(pMonitor);
printf(" Name: %s\n", pName);
LOG_INFO(" Name: %s", pName);
/// Monitor Physical Size
int widthMM, heightMM;
glfwGetMonitorPhysicalSize(pMonitor, &widthMM, &heightMM);
//const double dpi = mode->width / (widthMM / 25.4);
printf(" physical size: %d x %d mm\n");
LOG_INFO(" physical size: %d x %d mm");
/// Modes
const GLFWvidmode* mode = glfwGetVideoMode(pMonitor);
printf(" Current mode: %dx%d @ %dHz (RGB %d %d %d bits)\n",
mode->width,
mode->height,
mode->refreshRate,
mode->redBits,
mode->greenBits,
mode->blueBits);
LOG_INFO(" Current mode: %dx%d @ %dHz (RGB %d %d %d bits)",
mode->width,
mode->height,
mode->refreshRate,
mode->redBits,
mode->greenBits,
mode->blueBits);
#if 0
int modeCount;
const GLFWvidmode* modes = glfwGetVideoModes(pMonitor, &modeCount);
printf(" %d Modes:\n", modeCount);
LOG_INFO(" %d Modes:", modeCount);
for (int j=0; j<modeCount; ++j)
{
const GLFWvidmode& m = modes[j];
printf(" %dx%d @ %dHz (RGB %d %d %d bits)\n",
m.width, m.height, m.refreshRate, m.redBits, m.greenBits, m.blueBits);
LOG_INFO(" %dx%d @ %dHz (RGB %d %d %d bits)",
m.width, m.height, m.refreshRate, m.redBits, m.greenBits, m.blueBits);
}
#endif
}
}
////////////////////////////////////////////////////////////////////////////////
// Program main
////////////////////////////////////////////////////////////////////////////////
int main(int argc, char *argv[])
{
if (!initGlfw(argc, argv))
return 0;
if (!initGL(argc, argv))
return 0;
PrintMonitorInfo();
LOG_INFO("Starting main loop.");
running = GL_TRUE;
//g_timer.reset();
while (running && !glfwWindowShouldClose(g_pWindow))
{
//float dt = (float)g_timer.seconds();
//timestep(dt);
//g_timer.reset();
display();
//running = running && glfwGetWindowParam(GLFW_OPENED);
glfwPollEvents();
}
#ifdef USE_ANTTWEAKBAR
TwTerminate();
#endif
glfwTerminate();
return 0;
}
<|endoftext|> |
<commit_before>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// 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.
// Internal Includes
#include "DriverLoader.h"
#include "FindDriver.h"
#include "GetProvider.h"
#include "ViveServerDriverHost.h"
// Library/third-party includes
#include <openvr_driver.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <iostream>
namespace osvr {
namespace vive {} // namespace vive
} // namespace osvr
int main() {
auto driverLocation = osvr::vive::findDriver();
if (driverLocation.found) {
std::cout << "Found the Vive driver at " << driverLocation.driverFile
<< std::endl;
} else {
std::cout << "Could not find the native SteamVR Vive driver, exiting!"
<< std::endl;
return 1;
}
auto vive = osvr::vive::DriverLoader::make(driverLocation.driverRoot,
driverLocation.driverFile);
if (vive->isHMDPresent()) {
std::cout << "Vive is connected." << std::endl;
std::unique_ptr<vr::ViveServerDriverHost> serverDriverHost(
new vr::ViveServerDriverHost);
osvr::vive::getProvider<vr::IServerTrackedDeviceProvider>(
std::move(vive), nullptr, serverDriverHost.get(), ".");
}
return 0;
}
<commit_msg>use new file names in ViveLoader<commit_after>/** @file
@brief Implementation
@date 2016
@author
Sensics, Inc.
<http://sensics.com/osvr>
*/
// Copyright 2016 Sensics, Inc.
//
// 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.
// Internal Includes
#include "DriverLoader.h"
#include "FindDriver.h"
#include "GetProvider.h"
#include "ServerDriverHost.h"
// Library/third-party includes
#include <openvr_driver.h>
#include <osvr/Util/PlatformConfig.h>
// Standard includes
#include <iostream>
namespace osvr {
namespace vive {} // namespace vive
} // namespace osvr
int main() {
auto driverLocation = osvr::vive::findDriver();
if (driverLocation.found) {
std::cout << "Found the Vive driver at " << driverLocation.driverFile
<< std::endl;
} else {
std::cout << "Could not find the native SteamVR Vive driver, exiting!"
<< std::endl;
return 1;
}
auto vive = osvr::vive::DriverLoader::make(driverLocation.driverRoot,
driverLocation.driverFile);
if (vive->isHMDPresent()) {
std::cout << "Vive is connected." << std::endl;
std::unique_ptr<vr::ServerDriverHost> serverDriverHost(
new vr::ServerDriverHost);
osvr::vive::getProvider<vr::IServerTrackedDeviceProvider>(
std::move(vive), nullptr, serverDriverHost.get(), ".");
}
return 0;
}
<|endoftext|> |
<commit_before>//
// function.cpp
// integral
//
// Copyright (C) 2017 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// integral is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with integral. If not, see <http://www.gnu.org/licenses/>.
//
#include <cstdio>
#include <iostream>
#include <lua.hpp>
#include <integral.hpp>
double getSum(double x, double y) {
return x + y;
}
double luaGetSum(lua_State *luaState) {
integral::pushCopy(luaState, integral::get<double>(luaState, 1) + integral::get<double>(luaState, 2));
return 1;
}
int main(int argc, char* argv[]) {
try {
integral::State luaState;
luaState.openLibs();
luaState["getSum"].setFunction(getSum);
luaState.doString("print('getSum(1, -.2) = ' .. getSum(1, -.2))");
luaState["luaGetSum"].setLuaFunction(luaGetSum);
luaState.doString("print('luaGetSum(1, -.2) = ' .. luaGetSum(1, -.2))");
luaState["printHello"].setFunction([]{
std::puts("hello!");
});
luaState.doString("printHello()");
luaState["getQuoted"].setFunction([](const std::string &string) {
return std::string("\"") + string + '"';
});
luaState.doString(R"(print('getQuoted("quoted") = ' .. getQuoted('quoted')))");
luaState["luaGetQuoted"].setLuaFunction([](lua_State *lambdaLuaState) {
integral::push<std::string>(lambdaLuaState, std::string("\"") + integral::get<const char *>(lambdaLuaState, 1) + '"');
return 1;
});
luaState.doString(R"(print('luaGetQuoted("quoted") = ' .. luaGetQuoted('quoted')))");
try {
//TODO
} catch (const integral::ReferenceException &referenceException) {
std::cout << "expected exception: {" << referenceException.what() << "}\n";
}
return EXIT_SUCCESS;
} catch (const std::exception &exception) {
std::cerr << "[function] " << exception.what() << std::endl;
} catch (...) {
std::cerr << "unknown exception thrown" << std::endl;
}
return EXIT_FAILURE;
}
<commit_msg>error handling<commit_after>//
// function.cpp
// integral
//
// Copyright (C) 2017 André Pereira Henriques
// aphenriques (at) outlook (dot) com
//
// This file is part of integral.
//
// integral is free software: you can redistribute it and/or modify
// it under the terms of the GNU General Public License as published by
// the Free Software Foundation, either version 3 of the License, or
// (at your option) any later version.
//
// integral is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
// GNU General Public License for more details.
//
// You should have received a copy of the GNU General Public License
// along with integral. If not, see <http://www.gnu.org/licenses/>.
//
#include <cstdio>
#include <iostream>
#include <lua.hpp>
#include <integral.hpp>
double getSum(double x, double y) {
return x + y;
}
double luaGetSum(lua_State *luaState) {
integral::pushCopy(luaState, integral::get<double>(luaState, 1) + integral::get<double>(luaState, 2));
return 1;
}
int main(int argc, char* argv[]) {
try {
integral::State luaState;
luaState.openLibs();
luaState["getSum"].setFunction(getSum);
luaState.doString("print('getSum(1, -.2) = ' .. getSum(1, -.2))");
luaState["luaGetSum"].setLuaFunction(luaGetSum);
luaState.doString("print('luaGetSum(1, -.2) = ' .. luaGetSum(1, -.2))");
luaState["printHello"].setFunction([]{
std::puts("hello!");
});
luaState.doString("printHello()");
luaState["getQuoted"].setFunction([](const std::string &string) {
return std::string("\"") + string + '"';
});
luaState.doString(R"(print('getQuoted("quoted") = ' .. getQuoted('quoted')))");
luaState["luaGetQuoted"].setLuaFunction([](lua_State *lambdaLuaState) {
integral::push<std::string>(lambdaLuaState, std::string("\"") + integral::get<const char *>(lambdaLuaState, 1) + '"');
return 1;
});
luaState.doString(R"(print('luaGetQuoted("quoted") = ' .. luaGetQuoted('quoted')))");
try {
luaState.doString("getSum(1, 2, 3)");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("getSum(1)");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("getSum(1, 'two')");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
try {
luaState.doString("luaGetSum(1, 'two')");
} catch (const integral::StateException &stateException) {
std::cout << "expected exception: {" << stateException.what() << "}\n";
}
return EXIT_SUCCESS;
} catch (const std::exception &exception) {
std::cerr << "[function] " << exception.what() << std::endl;
} catch (...) {
std::cerr << "unknown exception thrown" << std::endl;
}
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
using namespace fnord;
struct PosiInfo {
PosiInfo() : views(0), clicks(0) {}
uint64_t views;
uint64_t clicks;
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
HashMap<uint32_t, PosiInfo> click_posis;
auto start_time = std::numeric_limits<uint64_t>::max();
auto end_time = std::numeric_limits<uint64_t>::min();
auto eligibility = cm::ItemEligibility::DAWANDA_ALL_NOBOTS;
/* read input tables */
auto sstables = flags.getArgv();
int row_idx = 0;
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* read report header */
auto hdr = json::parseJSON(reader.readHeader());
auto tbl_start_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"start_time").get();
auto tbl_end_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"end_time").get();
if (tbl_start_time < start_time) {
start_time = tbl_start_time;
}
if (tbl_end_time > end_time) {
end_time = tbl_end_time;
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.ctrstats",
"[$1/$2] [$0%] Reading sstable... rows=$3",
(size_t) ((cursor->position() / (double) body_size) * 100),
tbl_idx + 1, sstables.size(), row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
//fnord::logWarning("cm.ctrstats", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty() && isQueryEligible(eligibility, q.get())) {
for (auto& item : q.get().items) {
if (!isItemEligible(eligibility, q.get(), item) ||
item.position < 1) {
continue;
}
auto& pi = click_posis[item.position];
++pi.views;
pi.clicks += item.clicked;
}
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
uint64_t total_clicks = 0;
uint64_t total_views = 0;
Vector<Pair<uint64_t, PosiInfo>> posis;
for (const auto& p : click_posis) {
total_clicks += p.second.clicks;
total_views += p.second.views;
posis.emplace_back(p);
}
std::sort(posis.begin(), posis.end(), [] (
const Pair<uint64_t, PosiInfo>& a,
const Pair<uint64_t, PosiInfo>& b) {
return a.first < b.first;
});
for (const auto& p : posis) {
auto share = (p.second.clicks / (double) total_clicks) * 100;
auto ctr = p.second.clicks / (double) p.second.views;
fnord::iputs(" position $0 => views=$1 clicks=$2 share=$3 ctr=$4",
p.first,
p.second.views,
p.second.clicks,
share,
ctr);
}
return 0;
}
<commit_msg>better output in clickposihisto<commit_after>/**
* Copyright (c) 2015 - The CM Authors <legal@clickmatcher.com>
* All Rights Reserved.
*
* This file is CONFIDENTIAL -- Distribution or duplication of this material or
* the information contained herein is strictly forbidden unless prior written
* permission is obtained.
*/
#include <algorithm>
#include <stdlib.h>
#include <unistd.h>
#include <signal.h>
#include "fnord-base/io/fileutil.h"
#include "fnord-base/application.h"
#include "fnord-base/logging.h"
#include "fnord-base/cli/flagparser.h"
#include "fnord-base/util/SimpleRateLimit.h"
#include "fnord-base/InternMap.h"
#include "fnord-json/json.h"
#include "fnord-mdb/MDB.h"
#include "fnord-mdb/MDBUtil.h"
#include "fnord-sstable/sstablereader.h"
#include "fnord-sstable/sstablewriter.h"
#include "fnord-sstable/SSTableColumnSchema.h"
#include "fnord-sstable/SSTableColumnReader.h"
#include "fnord-sstable/SSTableColumnWriter.h"
#include "common.h"
#include "CustomerNamespace.h"
#include "FeatureSchema.h"
#include "JoinedQuery.h"
#include "CTRCounter.h"
using namespace fnord;
struct PosiInfo {
PosiInfo() : views(0), clicks(0) {}
uint64_t views;
uint64_t clicks;
};
int main(int argc, const char** argv) {
fnord::Application::init();
fnord::Application::logToStderr();
fnord::cli::FlagParser flags;
flags.defineFlag(
"loglevel",
fnord::cli::FlagParser::T_STRING,
false,
NULL,
"INFO",
"loglevel",
"<level>");
flags.parseArgv(argc, argv);
Logger::get()->setMinimumLogLevel(
strToLogLevel(flags.getString("loglevel")));
HashMap<uint32_t, PosiInfo> click_posis;
auto start_time = std::numeric_limits<uint64_t>::max();
auto end_time = std::numeric_limits<uint64_t>::min();
auto eligibility = cm::ItemEligibility::DAWANDA_ALL_NOBOTS;
util::SimpleRateLimitedFn print_results(kMicrosPerSecond * 10, [&] () {
uint64_t total_clicks = 0;
uint64_t total_views = 0;
Vector<Pair<uint64_t, PosiInfo>> posis;
for (const auto& p : click_posis) {
total_clicks += p.second.clicks;
total_views += p.second.views;
posis.emplace_back(p);
}
std::sort(posis.begin(), posis.end(), [] (
const Pair<uint64_t, PosiInfo>& a,
const Pair<uint64_t, PosiInfo>& b) {
return a.first < b.first;
});
for (const auto& p : posis) {
auto share = (p.second.clicks / (double) total_clicks) * 100;
auto ctr = p.second.clicks / (double) p.second.views;
fnord::iputs(" position $0 => views=$1 clicks=$2 share=$3 ctr=$4",
p.first,
p.second.views,
p.second.clicks,
share,
ctr);
}
});
/* read input tables */
auto sstables = flags.getArgv();
int row_idx = 0;
for (int tbl_idx = 0; tbl_idx < sstables.size(); ++tbl_idx) {
const auto& sstable = sstables[tbl_idx];
fnord::logInfo("cm.ctrstats", "Importing sstable: $0", sstable);
/* read sstable header */
sstable::SSTableReader reader(File::openFile(sstable, File::O_READ));
if (reader.bodySize() == 0) {
fnord::logCritical("cm.ctrstats", "unfinished sstable: $0", sstable);
exit(1);
}
/* read report header */
auto hdr = json::parseJSON(reader.readHeader());
auto tbl_start_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"start_time").get();
auto tbl_end_time = json::JSONUtil::objectGetUInt64(
hdr.begin(),
hdr.end(),
"end_time").get();
if (tbl_start_time < start_time) {
start_time = tbl_start_time;
}
if (tbl_end_time > end_time) {
end_time = tbl_end_time;
}
/* get sstable cursor */
auto cursor = reader.getCursor();
auto body_size = reader.bodySize();
/* status line */
util::SimpleRateLimitedFn status_line(kMicrosPerSecond, [&] () {
fnord::logInfo(
"cm.ctrstats",
"[$1/$2] [$0%] Reading sstable... rows=$3",
(size_t) ((cursor->position() / (double) body_size) * 100),
tbl_idx + 1, sstables.size(), row_idx);
});
/* read sstable rows */
for (; cursor->valid(); ++row_idx) {
status_line.runMaybe();
print_results.runMaybe();
auto val = cursor->getDataBuffer();
Option<cm::JoinedQuery> q;
try {
q = Some(json::fromJSON<cm::JoinedQuery>(val));
} catch (const Exception& e) {
//fnord::logWarning("cm.ctrstats", e, "invalid json: $0", val.toString());
}
if (!q.isEmpty() && isQueryEligible(eligibility, q.get())) {
for (auto& item : q.get().items) {
if (!isItemEligible(eligibility, q.get(), item) ||
item.position < 1) {
continue;
}
auto& pi = click_posis[item.position];
++pi.views;
pi.clicks += item.clicked;
}
}
if (!cursor->next()) {
break;
}
}
status_line.runForce();
}
print_results.runForce();
return 0;
}
<|endoftext|> |
<commit_before>#include "sceneview.h"
#include "editor/world_editor.h"
#include "core/crc32.h"
#include "editor/ieditor_command.h"
#include "editor/measure_tool.h"
#include "engine/engine.h"
#include "engine/iplugin.h"
#include "graphics/pipeline.h"
#include "graphics/render_scene.h"
#include "insert_mesh_command.h"
#include <qapplication.h>
#include <QDoubleSpinBox>
#include <QDragEnterEvent>
#include <QLabel>
#include <QMimeData>
#include <QMouseEvent>
#include <qpushbutton.h>
#include <QVBoxLayout>
class ViewWidget : public QWidget
{
public:
ViewWidget(SceneView& view, QWidget* parent)
: QWidget(parent)
, m_view(view)
{
setMouseTracking(true);
}
virtual void mousePressEvent(QMouseEvent* event) override
{
m_world_editor->onMouseDown(event->x(), event->y(), event->button() == Qt::RightButton ? Lumix::MouseButton::RIGHT : Lumix::MouseButton::LEFT);
m_last_x = event->x();
m_last_y = event->y();
setFocus();
}
virtual void wheelEvent(QWheelEvent* event) override
{
m_view.changeNavigationSpeed(event->delta() * 0.001f);
}
virtual void mouseMoveEvent(QMouseEvent* event) override
{
int flags = 0;
flags |= Qt::ControlModifier & QApplication::keyboardModifiers() ? (int)Lumix::WorldEditor::MouseFlags::CONTROL : 0;
flags |= Qt::AltModifier & QApplication::keyboardModifiers() ? (int)Lumix::WorldEditor::MouseFlags::ALT : 0;
m_world_editor->onMouseMove(event->x(), event->y(), event->x() - m_last_x, event->y() - m_last_y, flags);
m_last_x = event->x();
m_last_y = event->y();
}
virtual void mouseReleaseEvent(QMouseEvent* event) override
{
m_world_editor->onMouseUp(event->x(), event->y(), event->button() == Qt::RightButton ? Lumix::MouseButton::RIGHT : Lumix::MouseButton::LEFT);
}
Lumix::WorldEditor* m_world_editor;
int m_last_x;
int m_last_y;
SceneView& m_view;
};
SceneView::SceneView(QWidget* parent)
: QDockWidget(parent)
, m_is_frame_requested(false)
, m_is_frame_debugger_active(false)
{
m_pipeline = NULL;
m_measure_tool_label = new QLabel("");
QWidget* root = new QWidget();
QVBoxLayout* vertical_layout = new QVBoxLayout(root);
QHBoxLayout* horizontal_layout = new QHBoxLayout(root);
m_view = new ViewWidget(*this, root);
m_speed_input = new QDoubleSpinBox(root);
m_speed_input->setSingleStep(0.1f);
m_speed_input->setValue(0.1f);
QPushButton* stop_button = new QPushButton("Stop", root);
QPushButton* next_button = new QPushButton("Next", root);
m_time_delta_multiplier_input = new QDoubleSpinBox(root);
m_time_delta_multiplier_input->setDecimals(2);
m_time_delta_multiplier_input->setValue(1.0);
m_time_delta_multiplier_input->setSingleStep(0.1);
m_time_delta_multiplier_input->setMinimumWidth(60);
stop_button->connect(stop_button, &QPushButton::clicked, [this]()
{
m_is_frame_debugger_active = !m_is_frame_debugger_active;
});
next_button->connect(next_button, &QPushButton::clicked, [this]()
{
m_is_frame_requested = true;
});
horizontal_layout->addWidget(stop_button);
horizontal_layout->addWidget(next_button);
horizontal_layout->addWidget(m_time_delta_multiplier_input);
horizontal_layout->addStretch();
horizontal_layout->addWidget(m_measure_tool_label);
horizontal_layout->addStretch();
horizontal_layout->addWidget(m_speed_input);
horizontal_layout->setContentsMargins(0, 0, 0, 0);
vertical_layout->addWidget(m_view);
vertical_layout->addLayout(horizontal_layout);
vertical_layout->setContentsMargins(0, 0, 0, 0);
setWidget(root);
setWindowTitle("Scene");
setObjectName("sceneView");
setAcceptDrops(true);
}
void SceneView::setWorldEditor(Lumix::WorldEditor* world_editor)
{
static_cast<ViewWidget*>(m_view)->m_world_editor = world_editor;
m_world_editor = world_editor;
if (world_editor)
{
world_editor->getMeasureTool()->distanceMeasured().bind<SceneView, &SceneView::onDistanceMeasured>(this);
}
}
void SceneView::onDistanceMeasured(float distance)
{
m_measure_tool_label->setText(QString("Measured distance: %1").arg(distance));
}
void SceneView::changeNavigationSpeed(float value)
{
m_speed_input->setValue(Lumix::Math::maxValue(0.1f, (float)m_speed_input->value() + value));
}
float SceneView::getTimeDeltaMultiplier() const
{
return m_time_delta_multiplier_input->value();
}
float SceneView::getNavigationSpeed() const
{
return m_speed_input->value();
}
void SceneView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void SceneView::dropEvent(QDropEvent *event)
{
const QList<QUrl>& list = event->mimeData()->urls();
if(!list.empty())
{
QString file = list[0].toLocalFile();
if(file.endsWith(".msh"))
{
Lumix::Vec3 position;
Lumix::RenderScene* scene = static_cast<Lumix::RenderScene*>(m_world_editor->getEditCamera().scene);
Lumix::Vec3 origin;
Lumix::Vec3 dir;
scene->getRay(m_world_editor->getEditCamera(), event->pos().x(), event->pos().y(), origin, dir);
Lumix::RayCastModelHit hit = scene->castRay(origin, dir, Lumix::Component::INVALID);
if (hit.m_is_hit)
{
position = hit.m_origin + hit.m_dir * hit.m_t;
}
else
{
position.set(0, 0, 0);
}
InsertMeshCommand* command = m_world_editor->getAllocator().newObject<InsertMeshCommand>(*static_cast<ViewWidget&>(*m_view).m_world_editor, position, Lumix::Path(file.toLatin1().data()));
m_world_editor->executeCommand(command);
m_world_editor->selectEntities(&command->getEntity(), 1);
}
}
}
void SceneView::resizeEvent(QResizeEvent*)
{
if (m_pipeline)
{
m_pipeline->resize(m_view->width(), m_view->height());
}
}<commit_msg>fixed blinking - close #419<commit_after>#include "sceneview.h"
#include "editor/world_editor.h"
#include "core/crc32.h"
#include "editor/ieditor_command.h"
#include "editor/measure_tool.h"
#include "engine/engine.h"
#include "engine/iplugin.h"
#include "graphics/pipeline.h"
#include "graphics/render_scene.h"
#include "insert_mesh_command.h"
#include <qapplication.h>
#include <QDoubleSpinBox>
#include <QDragEnterEvent>
#include <QLabel>
#include <QMimeData>
#include <QMouseEvent>
#include <qpushbutton.h>
#include <QVBoxLayout>
class ViewWidget : public QWidget
{
public:
ViewWidget(SceneView& view, QWidget* parent)
: QWidget(parent)
, m_view(view)
{
setAttribute(Qt::WA_PaintOnScreen);
setMouseTracking(true);
}
virtual void mousePressEvent(QMouseEvent* event) override
{
m_world_editor->onMouseDown(event->x(), event->y(), event->button() == Qt::RightButton ? Lumix::MouseButton::RIGHT : Lumix::MouseButton::LEFT);
m_last_x = event->x();
m_last_y = event->y();
setFocus();
}
virtual QPaintEngine* paintEngine() const override
{
return NULL;
}
virtual void wheelEvent(QWheelEvent* event) override
{
m_view.changeNavigationSpeed(event->delta() * 0.001f);
}
virtual void mouseMoveEvent(QMouseEvent* event) override
{
int flags = 0;
flags |= Qt::ControlModifier & QApplication::keyboardModifiers() ? (int)Lumix::WorldEditor::MouseFlags::CONTROL : 0;
flags |= Qt::AltModifier & QApplication::keyboardModifiers() ? (int)Lumix::WorldEditor::MouseFlags::ALT : 0;
m_world_editor->onMouseMove(event->x(), event->y(), event->x() - m_last_x, event->y() - m_last_y, flags);
m_last_x = event->x();
m_last_y = event->y();
}
virtual void mouseReleaseEvent(QMouseEvent* event) override
{
m_world_editor->onMouseUp(event->x(), event->y(), event->button() == Qt::RightButton ? Lumix::MouseButton::RIGHT : Lumix::MouseButton::LEFT);
}
Lumix::WorldEditor* m_world_editor;
int m_last_x;
int m_last_y;
SceneView& m_view;
};
SceneView::SceneView(QWidget* parent)
: QDockWidget(parent)
, m_is_frame_requested(false)
, m_is_frame_debugger_active(false)
{
m_pipeline = NULL;
m_measure_tool_label = new QLabel("");
QWidget* root = new QWidget();
QVBoxLayout* vertical_layout = new QVBoxLayout(root);
QHBoxLayout* horizontal_layout = new QHBoxLayout(root);
m_view = new ViewWidget(*this, root);
m_speed_input = new QDoubleSpinBox(root);
m_speed_input->setSingleStep(0.1f);
m_speed_input->setValue(0.1f);
QPushButton* stop_button = new QPushButton("Stop", root);
QPushButton* next_button = new QPushButton("Next", root);
m_time_delta_multiplier_input = new QDoubleSpinBox(root);
m_time_delta_multiplier_input->setDecimals(2);
m_time_delta_multiplier_input->setValue(1.0);
m_time_delta_multiplier_input->setSingleStep(0.1);
m_time_delta_multiplier_input->setMinimumWidth(60);
stop_button->connect(stop_button, &QPushButton::clicked, [this]()
{
m_is_frame_debugger_active = !m_is_frame_debugger_active;
});
next_button->connect(next_button, &QPushButton::clicked, [this]()
{
m_is_frame_requested = true;
});
horizontal_layout->addWidget(stop_button);
horizontal_layout->addWidget(next_button);
horizontal_layout->addWidget(m_time_delta_multiplier_input);
horizontal_layout->addStretch();
horizontal_layout->addWidget(m_measure_tool_label);
horizontal_layout->addStretch();
horizontal_layout->addWidget(m_speed_input);
horizontal_layout->setContentsMargins(0, 0, 0, 0);
vertical_layout->addWidget(m_view);
vertical_layout->addLayout(horizontal_layout);
vertical_layout->setContentsMargins(0, 0, 0, 0);
setWidget(root);
setWindowTitle("Scene");
setObjectName("sceneView");
setAcceptDrops(true);
}
void SceneView::setWorldEditor(Lumix::WorldEditor* world_editor)
{
static_cast<ViewWidget*>(m_view)->m_world_editor = world_editor;
m_world_editor = world_editor;
if (world_editor)
{
world_editor->getMeasureTool()->distanceMeasured().bind<SceneView, &SceneView::onDistanceMeasured>(this);
}
}
void SceneView::onDistanceMeasured(float distance)
{
m_measure_tool_label->setText(QString("Measured distance: %1").arg(distance));
}
void SceneView::changeNavigationSpeed(float value)
{
m_speed_input->setValue(Lumix::Math::maxValue(0.1f, (float)m_speed_input->value() + value));
}
float SceneView::getTimeDeltaMultiplier() const
{
return m_time_delta_multiplier_input->value();
}
float SceneView::getNavigationSpeed() const
{
return m_speed_input->value();
}
void SceneView::dragEnterEvent(QDragEnterEvent *event)
{
if (event->mimeData()->hasUrls())
{
event->acceptProposedAction();
}
}
void SceneView::dropEvent(QDropEvent *event)
{
const QList<QUrl>& list = event->mimeData()->urls();
if(!list.empty())
{
QString file = list[0].toLocalFile();
if(file.endsWith(".msh"))
{
Lumix::Vec3 position;
Lumix::RenderScene* scene = static_cast<Lumix::RenderScene*>(m_world_editor->getEditCamera().scene);
Lumix::Vec3 origin;
Lumix::Vec3 dir;
scene->getRay(m_world_editor->getEditCamera(), event->pos().x(), event->pos().y(), origin, dir);
Lumix::RayCastModelHit hit = scene->castRay(origin, dir, Lumix::Component::INVALID);
if (hit.m_is_hit)
{
position = hit.m_origin + hit.m_dir * hit.m_t;
}
else
{
position.set(0, 0, 0);
}
InsertMeshCommand* command = m_world_editor->getAllocator().newObject<InsertMeshCommand>(*static_cast<ViewWidget&>(*m_view).m_world_editor, position, Lumix::Path(file.toLatin1().data()));
m_world_editor->executeCommand(command);
m_world_editor->selectEntities(&command->getEntity(), 1);
}
}
}
void SceneView::resizeEvent(QResizeEvent*)
{
if (m_pipeline)
{
m_pipeline->resize(m_view->width(), m_view->height());
}
}<|endoftext|> |
<commit_before>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef ATOMIC_HH
#define ATOMIC_HH
#include <pthread.h>
#include <queue>
#include <sched.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "callbacks.hh"
#include "locks.hh"
#define MAX_THREADS 100
#if defined(HAVE_GCC_ATOMICS)
#include "atomic/gcc_atomics.h"
#elif defined(HAVE_ATOMIC_H)
#include "atomic/libatomic.h"
#else
#error "Don't know how to use atomics on your target system!"
#endif
extern "C" {
typedef void (*ThreadLocalDestructor)(void *);
}
/**
* Container of thread-local data.
*/
template<typename T>
class ThreadLocal {
public:
ThreadLocal(ThreadLocalDestructor destructor = NULL) {
int rc = pthread_key_create(&key, destructor);
if (rc != 0) {
fprintf(stderr, "Failed to create a thread-specific key: %s\n", strerror(rc));
abort();
}
}
~ThreadLocal() {
pthread_key_delete(key);
}
void set(const T &newValue) {
int rc = pthread_setspecific(key, newValue);
if (rc != 0) {
std::stringstream ss;
ss << "Failed to store thread specific value: " << strerror(rc);
throw std::runtime_error(ss.str().c_str());
}
}
T get() const {
return reinterpret_cast<T>(pthread_getspecific(key));
}
void operator =(const T &newValue) {
set(newValue);
}
operator T() const {
return get();
}
private:
pthread_key_t key;
};
/**
* Holder of atomic values.
*/
template <typename T>
class Atomic {
public:
Atomic(const T &initial = 0) {
set(initial);
}
~Atomic() {}
T get() const {
return value;
}
void set(const T &newValue) {
value = newValue;
ep_sync_synchronize();
}
operator T() const {
return get();
}
void operator =(const T &newValue) {
set(newValue);
}
bool cas(const T &oldValue, const T &newValue) {
return ep_sync_bool_compare_and_swap(&value, oldValue, newValue);
}
T operator ++() { // prefix
return ep_sync_add_and_fetch(&value, 1);
}
T operator ++(int) { // postfix
return ep_sync_fetch_and_add(&value, 1);
}
T operator --() { // prefix
return ep_sync_add_and_fetch(&value, -1);
}
T operator --(int) { // postfix
return ep_sync_fetch_and_add(&value, -1);
}
T operator +=(T increment) {
// Returns the new value
return ep_sync_add_and_fetch(&value, increment);
}
T operator -=(T decrement) {
return ep_sync_add_and_fetch(&value, -decrement);
}
T incr(const T &increment) {
// Returns the old value
return ep_sync_fetch_and_add(&value, increment);
}
T decr(const T &decrement) {
return ep_sync_add_and_fetch(&value, -decrement);
}
T swap(const T &newValue) {
T rv;
while (true) {
rv = get();
if (cas(rv, newValue)) {
break;
}
}
return rv;
}
T swapIfNot(const T &badValue, const T &newValue) {
T oldValue;
while (true) {
oldValue = get();
if (oldValue != badValue) {
if (cas(oldValue, newValue)) {
break;
}
} else {
break;
}
}
return oldValue;
}
void setIfLess(const T &newValue) {
T oldValue = get();
while (newValue < oldValue) {
if (cas(oldValue, newValue)) {
break;
}
oldValue = get();
}
}
void setIfBigger(const T &newValue) {
T oldValue = get();
while (newValue > oldValue) {
if (cas(oldValue, newValue)) {
break;
}
oldValue = get();
}
}
private:
volatile T value;
};
/**
* Atomic pointer.
*
* This does *not* make the item that's pointed to atomic.
*/
template <typename T>
class AtomicPtr : public Atomic<T*> {
public:
AtomicPtr(T *initial = NULL) : Atomic<T*>(initial) {}
~AtomicPtr() {}
T *operator ->() {
return Atomic<T*>::get();
}
T operator *() {
return *Atomic<T*>::get();
}
operator bool() const {
return Atomic<T*>::get() != NULL;
}
bool operator !() const {
return Atomic<T*>::get() == NULL;
}
};
/**
* A lighter-weight, smaller lock than a mutex.
*
* This is primarily useful when contention is rare.
*/
class SpinLock {
public:
// It seems like inlining the code caused the dtrace probe to
// be optimized away ;)
SpinLock();
~SpinLock();
void acquire(void);
void release(void);
private:
bool tryAcquire() {
return ep_sync_lock_test_and_set(&lock, 1) == 0;
}
volatile int lock;
DISALLOW_COPY_AND_ASSIGN(SpinLock);
};
/**
* Safe LockHolder for SpinLock instances.
*/
class SpinLockHolder {
public:
SpinLockHolder(SpinLock *theLock) : sl(theLock) {
lock();
}
~SpinLockHolder() {
unlock();
}
void lock() {
sl->acquire();
locked = true;
}
void unlock() {
if (locked) {
sl->release();
locked = false;
}
}
private:
SpinLock *sl;
bool locked;
};
template <class T> class RCPtr;
template <class S> class SingleThreadedRCPtr;
/**
* A reference counted value (used by RCPtr and SingleThreadedRCPtr).
*/
class RCValue {
public:
RCValue() : _rc_refcount(0) {}
RCValue(const RCValue &) : _rc_refcount(0) {}
~RCValue() {}
private:
template <class TT> friend class RCPtr;
template <class SS> friend class SingleThreadedRCPtr;
int _rc_incref() const {
return ++_rc_refcount;
}
int _rc_decref() const {
return --_rc_refcount;
}
mutable Atomic<int> _rc_refcount;
};
/**
* Concurrent reference counted pointer.
*/
template <class C>
class RCPtr {
public:
RCPtr(C *init = NULL) : value(init) {
if (init != NULL) {
static_cast<RCValue*>(value)->_rc_incref();
}
}
RCPtr(const RCPtr<C> &other) : value(other.gimme()) {}
~RCPtr() {
if (value && static_cast<RCValue *>(value)->_rc_decref() == 0) {
delete value;
}
}
void reset(C *newValue = NULL) {
if (newValue != NULL) {
static_cast<RCValue *>(newValue)->_rc_incref();
}
swap(newValue);
}
void reset(const RCPtr<C> &other) {
swap(other.gimme());
}
bool cas(RCPtr<C> &oldValue, RCPtr<C> &newValue) {
SpinLockHolder lh(&lock);
if (value == oldValue.get()) {
C *tmp = value;
value = newValue.gimme();
if (tmp != NULL &&
static_cast<RCValue *>(tmp)->_rc_decref() == 0) {
lh.unlock();
delete tmp;
}
return true;
}
return false;
}
// safe for the lifetime of this instance
C *get() const {
return value;
}
RCPtr<C> & operator =(const RCPtr<C> &other) {
reset(other);
return *this;
}
C &operator *() const {
return *value;
}
C *operator ->() const {
return value;
}
bool operator! () const {
return !value;
}
operator bool () const {
return (bool)value;
}
private:
C *gimme() const {
SpinLockHolder lh(&lock);
if (value) {
static_cast<RCValue *>(value)->_rc_incref();
}
return value;
}
void swap(C *newValue) {
SpinLockHolder lh(&lock);
C *tmp(value.swap(newValue));
lh.unlock();
if (tmp != NULL && static_cast<RCValue *>(tmp)->_rc_decref() == 0) {
delete tmp;
}
}
AtomicPtr<C> value;
mutable SpinLock lock; // exists solely for the purpose of implementing reset() safely
};
/**
* Single-threaded reference counted pointer.
* "Single-threaded" means that the reference counted pointer should be accessed
* by only one thread at any time or accesses to the reference counted pointer
* by multiple threads should be synchronized by the external lock.
*/
template <class T>
class SingleThreadedRCPtr {
public:
SingleThreadedRCPtr(T *init = NULL) : value(init) {
if (init != NULL) {
static_cast<RCValue*>(value)->_rc_incref();
}
}
SingleThreadedRCPtr(const SingleThreadedRCPtr<T> &other) : value(other.gimme()) {}
~SingleThreadedRCPtr() {
if (value && static_cast<RCValue *>(value)->_rc_decref() == 0) {
delete value;
}
}
void reset(T *newValue = NULL) {
if (newValue != NULL) {
static_cast<RCValue *>(newValue)->_rc_incref();
}
swap(newValue);
}
void reset(const SingleThreadedRCPtr<T> &other) {
swap(other.gimme());
}
// safe for the lifetime of this instance
T *get() const {
return value;
}
SingleThreadedRCPtr<T> & operator =(const SingleThreadedRCPtr<T> &other) {
reset(other);
return *this;
}
T &operator *() const {
return *value;
}
T *operator ->() const {
return value;
}
bool operator! () const {
return !value;
}
operator bool () const {
return (bool)value;
}
private:
T *gimme() const {
if (value) {
static_cast<RCValue *>(value)->_rc_incref();
}
return value;
}
void swap(T *newValue) {
T *old = value;
value = newValue;
if (old != NULL && static_cast<RCValue *>(old)->_rc_decref() == 0) {
delete old;
}
}
T *value;
};
#endif // ATOMIC_HH
<commit_msg>MB-6080: Rename template name<commit_after>/* -*- Mode: C++; tab-width: 4; c-basic-offset: 4; indent-tabs-mode: nil -*- */
#ifndef ATOMIC_HH
#define ATOMIC_HH
#include <pthread.h>
#include <queue>
#include <sched.h>
#include <errno.h>
#include <stdio.h>
#include <stdlib.h>
#include "callbacks.hh"
#include "locks.hh"
#define MAX_THREADS 100
#if defined(HAVE_GCC_ATOMICS)
#include "atomic/gcc_atomics.h"
#elif defined(HAVE_ATOMIC_H)
#include "atomic/libatomic.h"
#else
#error "Don't know how to use atomics on your target system!"
#endif
extern "C" {
typedef void (*ThreadLocalDestructor)(void *);
}
/**
* Container of thread-local data.
*/
template<typename T>
class ThreadLocal {
public:
ThreadLocal(ThreadLocalDestructor destructor = NULL) {
int rc = pthread_key_create(&key, destructor);
if (rc != 0) {
fprintf(stderr, "Failed to create a thread-specific key: %s\n", strerror(rc));
abort();
}
}
~ThreadLocal() {
pthread_key_delete(key);
}
void set(const T &newValue) {
int rc = pthread_setspecific(key, newValue);
if (rc != 0) {
std::stringstream ss;
ss << "Failed to store thread specific value: " << strerror(rc);
throw std::runtime_error(ss.str().c_str());
}
}
T get() const {
return reinterpret_cast<T>(pthread_getspecific(key));
}
void operator =(const T &newValue) {
set(newValue);
}
operator T() const {
return get();
}
private:
pthread_key_t key;
};
/**
* Holder of atomic values.
*/
template <typename T>
class Atomic {
public:
Atomic(const T &initial = 0) {
set(initial);
}
~Atomic() {}
T get() const {
return value;
}
void set(const T &newValue) {
value = newValue;
ep_sync_synchronize();
}
operator T() const {
return get();
}
void operator =(const T &newValue) {
set(newValue);
}
bool cas(const T &oldValue, const T &newValue) {
return ep_sync_bool_compare_and_swap(&value, oldValue, newValue);
}
T operator ++() { // prefix
return ep_sync_add_and_fetch(&value, 1);
}
T operator ++(int) { // postfix
return ep_sync_fetch_and_add(&value, 1);
}
T operator --() { // prefix
return ep_sync_add_and_fetch(&value, -1);
}
T operator --(int) { // postfix
return ep_sync_fetch_and_add(&value, -1);
}
T operator +=(T increment) {
// Returns the new value
return ep_sync_add_and_fetch(&value, increment);
}
T operator -=(T decrement) {
return ep_sync_add_and_fetch(&value, -decrement);
}
T incr(const T &increment) {
// Returns the old value
return ep_sync_fetch_and_add(&value, increment);
}
T decr(const T &decrement) {
return ep_sync_add_and_fetch(&value, -decrement);
}
T swap(const T &newValue) {
T rv;
while (true) {
rv = get();
if (cas(rv, newValue)) {
break;
}
}
return rv;
}
T swapIfNot(const T &badValue, const T &newValue) {
T oldValue;
while (true) {
oldValue = get();
if (oldValue != badValue) {
if (cas(oldValue, newValue)) {
break;
}
} else {
break;
}
}
return oldValue;
}
void setIfLess(const T &newValue) {
T oldValue = get();
while (newValue < oldValue) {
if (cas(oldValue, newValue)) {
break;
}
oldValue = get();
}
}
void setIfBigger(const T &newValue) {
T oldValue = get();
while (newValue > oldValue) {
if (cas(oldValue, newValue)) {
break;
}
oldValue = get();
}
}
private:
volatile T value;
};
/**
* Atomic pointer.
*
* This does *not* make the item that's pointed to atomic.
*/
template <typename T>
class AtomicPtr : public Atomic<T*> {
public:
AtomicPtr(T *initial = NULL) : Atomic<T*>(initial) {}
~AtomicPtr() {}
T *operator ->() {
return Atomic<T*>::get();
}
T operator *() {
return *Atomic<T*>::get();
}
operator bool() const {
return Atomic<T*>::get() != NULL;
}
bool operator !() const {
return Atomic<T*>::get() == NULL;
}
};
/**
* A lighter-weight, smaller lock than a mutex.
*
* This is primarily useful when contention is rare.
*/
class SpinLock {
public:
// It seems like inlining the code caused the dtrace probe to
// be optimized away ;)
SpinLock();
~SpinLock();
void acquire(void);
void release(void);
private:
bool tryAcquire() {
return ep_sync_lock_test_and_set(&lock, 1) == 0;
}
volatile int lock;
DISALLOW_COPY_AND_ASSIGN(SpinLock);
};
/**
* Safe LockHolder for SpinLock instances.
*/
class SpinLockHolder {
public:
SpinLockHolder(SpinLock *theLock) : sl(theLock) {
lock();
}
~SpinLockHolder() {
unlock();
}
void lock() {
sl->acquire();
locked = true;
}
void unlock() {
if (locked) {
sl->release();
locked = false;
}
}
private:
SpinLock *sl;
bool locked;
};
template <class T> class RCPtr;
template <class S> class SingleThreadedRCPtr;
/**
* A reference counted value (used by RCPtr and SingleThreadedRCPtr).
*/
class RCValue {
public:
RCValue() : _rc_refcount(0) {}
RCValue(const RCValue &) : _rc_refcount(0) {}
~RCValue() {}
private:
template <class MyTT> friend class RCPtr;
template <class MySS> friend class SingleThreadedRCPtr;
int _rc_incref() const {
return ++_rc_refcount;
}
int _rc_decref() const {
return --_rc_refcount;
}
mutable Atomic<int> _rc_refcount;
};
/**
* Concurrent reference counted pointer.
*/
template <class C>
class RCPtr {
public:
RCPtr(C *init = NULL) : value(init) {
if (init != NULL) {
static_cast<RCValue*>(value)->_rc_incref();
}
}
RCPtr(const RCPtr<C> &other) : value(other.gimme()) {}
~RCPtr() {
if (value && static_cast<RCValue *>(value)->_rc_decref() == 0) {
delete value;
}
}
void reset(C *newValue = NULL) {
if (newValue != NULL) {
static_cast<RCValue *>(newValue)->_rc_incref();
}
swap(newValue);
}
void reset(const RCPtr<C> &other) {
swap(other.gimme());
}
bool cas(RCPtr<C> &oldValue, RCPtr<C> &newValue) {
SpinLockHolder lh(&lock);
if (value == oldValue.get()) {
C *tmp = value;
value = newValue.gimme();
if (tmp != NULL &&
static_cast<RCValue *>(tmp)->_rc_decref() == 0) {
lh.unlock();
delete tmp;
}
return true;
}
return false;
}
// safe for the lifetime of this instance
C *get() const {
return value;
}
RCPtr<C> & operator =(const RCPtr<C> &other) {
reset(other);
return *this;
}
C &operator *() const {
return *value;
}
C *operator ->() const {
return value;
}
bool operator! () const {
return !value;
}
operator bool () const {
return (bool)value;
}
private:
C *gimme() const {
SpinLockHolder lh(&lock);
if (value) {
static_cast<RCValue *>(value)->_rc_incref();
}
return value;
}
void swap(C *newValue) {
SpinLockHolder lh(&lock);
C *tmp(value.swap(newValue));
lh.unlock();
if (tmp != NULL && static_cast<RCValue *>(tmp)->_rc_decref() == 0) {
delete tmp;
}
}
AtomicPtr<C> value;
mutable SpinLock lock; // exists solely for the purpose of implementing reset() safely
};
/**
* Single-threaded reference counted pointer.
* "Single-threaded" means that the reference counted pointer should be accessed
* by only one thread at any time or accesses to the reference counted pointer
* by multiple threads should be synchronized by the external lock.
*/
template <class T>
class SingleThreadedRCPtr {
public:
SingleThreadedRCPtr(T *init = NULL) : value(init) {
if (init != NULL) {
static_cast<RCValue*>(value)->_rc_incref();
}
}
SingleThreadedRCPtr(const SingleThreadedRCPtr<T> &other) : value(other.gimme()) {}
~SingleThreadedRCPtr() {
if (value && static_cast<RCValue *>(value)->_rc_decref() == 0) {
delete value;
}
}
void reset(T *newValue = NULL) {
if (newValue != NULL) {
static_cast<RCValue *>(newValue)->_rc_incref();
}
swap(newValue);
}
void reset(const SingleThreadedRCPtr<T> &other) {
swap(other.gimme());
}
// safe for the lifetime of this instance
T *get() const {
return value;
}
SingleThreadedRCPtr<T> & operator =(const SingleThreadedRCPtr<T> &other) {
reset(other);
return *this;
}
T &operator *() const {
return *value;
}
T *operator ->() const {
return value;
}
bool operator! () const {
return !value;
}
operator bool () const {
return (bool)value;
}
private:
T *gimme() const {
if (value) {
static_cast<RCValue *>(value)->_rc_incref();
}
return value;
}
void swap(T *newValue) {
T *old = value;
value = newValue;
if (old != NULL && static_cast<RCValue *>(old)->_rc_decref() == 0) {
delete old;
}
}
T *value;
};
#endif // ATOMIC_HH
<|endoftext|> |
<commit_before>/***************************************************************************
* Copyright (C) 2006 by Jeroen Broekhuizen *
* jengine.sse@live.nl *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "guitreebox.h"
#ifndef JENGINE_INLINE
# include "guitreebox.inl"
#endif
#include "../containers/treedepthfirstiterator.h"
#include "../scriptmanager.h"
#include "guidesigner.h"
#include "guidefines.h"
#include "guifont.h"
#include "guieventhandler.h"
#include "guieventhandlers.h"
#include "guieventhandlerdefinition.h"
#include "guieventhandlerdefinitions.h"
#include "guimanager.h"
#include "guiscopedtransform.h"
#include "guitext.h"
REGISTER_DESIGNER(GuiTreeBox, GuiTreeBoxId, "Treebox", 40, 15, 392)
GuiTreeBox::GuiTreeBox():
GuiControl(),
_items(),
_selections()
{
}
GuiTreeBox::~GuiTreeBox()
{
}
//////////////////////////////////////////////////////////////////////////
// - get/set interface
//////////////////////////////////////////////////////////////////////////
bool GuiTreeBox::hasSelection() const
{
return !_selections.empty();
}
const GuiTreeBox::Handle GuiTreeBox::getSelection() const
{
ASSERT(_selections.size() > 0)
return *_selections.front();
}
GuiTreeBox::Handle GuiTreeBox::getSelection()
{
ASSERT(_selections.size() > 0)
return *_selections.front();
}
//////////////////////////////////////////////////////////////////////////
// - creation
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::onCreate (const GuiRect& rect, const char* caption, GuiStyle style, GuiWnd* parent)
{
GuiControl::onCreate(rect, caption, style, parent);
GuiTreeBoxItem* pitem = new GuiTreeBoxItem();
pitem->setText("'Designer'");
pitem->setIcon("../images/folder.png");
GuiTreeBoxItem* pchild = new GuiTreeBoxItem();
pchild->setText("Dialogs");
pchild->setIcon("../images/application_double.png");
GuiTreeBoxItem* pdialog = new GuiTreeBoxItem();
pdialog->setText("des_openfile");
pdialog->setIcon("../images/application_form.png");
_items.insert(NULL, *pitem);
HandlePtr pnode = _items.findElement(*pitem);
_items.insert(pnode, *pchild);
pnode = _items.findElement(*pchild);
_items.insert(pnode, *pdialog);
}
//////////////////////////////////////////////////////////////////////////
// - painting
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::paint(Uint32 tick, const GuiGraphics& graphics)
{
if ( _items.hasRoot() )
{
int y = 5;
Handle root = _items.getRoot();
GuiScopedTransform transform(*this);
recursePaint(root, 5, y, graphics);
}
}
void GuiTreeBox::recursePaint(Handle item, int x, int& y, const GuiGraphics& graphics)
{
drawItem(item, x, y, graphics);
y += 16;
if ( item.isExpanded() )
{
TreeNode<GuiTreeBoxItem>::Children& children = item.getChildren();
ListIterator< TreeNode<GuiTreeBoxItem> > it(children);
while ( it.isValid() )
{
recursePaint(it.item(), x + 20, y, graphics);
++it;
}
}
}
void GuiTreeBox::drawItem(const Handle item, int x, int y, const GuiGraphics& graphics)
{
graphics.setColor(1, 1, 1);
paintCheck(item, x, y + getParent()->getFont()->getBaseHeight(), graphics);
if ( item.getData().hasIcon() )
graphics.drawImage(*item.getData().getIcon(), GuiRect(x+15, x+31, y, y+16));
paintText(item, x, y, graphics);
}
void GuiTreeBox::paintText(const Handle item, int x, int y, const GuiGraphics& graphics)
{
const std::string& title = item.getData().getText();
if ( item.getData().isSelected() )
{
int width = getFont()->getAverageWidth() * title.length() + 34;
GuiRect rect(x+34, x+width, y + 1, y + getFont()->getHeight() - 1);
graphics.setColor(0, 0, 1);
graphics.drawRect(rect);
graphics.setColor(1, 1, 1);
GuiText::printfn(*getFont(), x + 34, y+getFont()->getBaseHeight(), title.c_str(), title.size());
}
else
{
graphics.setColor(GuiManager::getInstance().getDefaultTextColor());
GuiText::printfn(*getFont(), x + 34, y+getFont()->getBaseHeight(), title.c_str(), title.size());
}
}
void GuiTreeBox::paintCheck(const Handle item, int x, int y, const GuiGraphics& graphics)
{
if ( item.hasChildren() )
{
graphics.drawWireRect(GuiRect(x, x+8, y, y-8));
glBegin(GL_LINES);
glVertex2i(x+2, y-4);
glVertex2i(x+7, y-4);
if ( !item.isExpanded() )
{
glVertex2i(x+4, y-2);
glVertex2i(x+4, y-7);
}
glEnd();
}
}
//////////////////////////////////////////////////////////////////////////
// - event handler interface
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::initializeEventHandlerDefinitions()
{
GuiControl::initializeEventHandlerDefinitions();
GuiEventHandlerDefinition* pdefinition = new GuiEventHandlerDefinition(GuiTreeSelChangeEvent, "onSelectionChanged");
pdefinition->addArgument("selection");
getEventHandlerDefinitions().add(pdefinition);
}
//////////////////////////////////////////////////////////////////////////
// - input interface
//////////////////////////////////////////////////////////////////////////
int GuiTreeBox::onLButtonUp (const GuiPoint& point, int flag)
{
select(point);
return 0;
}
//////////////////////////////////////////////////////////////////////////
// - operations
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::insert(HandlePtr position, GuiTreeBoxItem& item)
{
_items.insert(position, item);
}
void GuiTreeBox::select(const GuiPoint& point)
{
int index = (point.y - 5) / 16;
HandlePtr pitem = findItemByIndex(index);
if ( pitem != NULL )
{
if ( isAboveCheckbox(*pitem, point.x) )
{
if ( pitem->isExpanded() )
pitem->collapse();
else
pitem->expand();
}
else
{
select(pitem);
}
}
}
void GuiTreeBox::select(HandlePtr pitem)
{
deselectAll();
_selections.push_back(pitem);
GuiTreeBoxItem& item = pitem->getData();
item.setSelected(true);
GuiEventHandler* phandler = getEventHandlers().findByEventType(GuiTreeSelChangeEvent);
if ( phandler != NULL )
{
ScriptManager& mgr = ScriptManager::getInstance();
Script& script = mgr.getTemporaryScript();
script.setSelf(this, "GuiTreeBox");
script.prepareCall(phandler->getFunctionName().c_str());
script.addParam(findIndex(pitem));
script.run(1);
}
}
void GuiTreeBox::deselectAll()
{
while ( !_selections.empty() )
{
HandlePtr pitem = _selections.front();
pitem->getData().setSelected(false);
_selections.pop_front();
}
}
bool GuiTreeBox::isAboveCheckbox(Handle item, int x)
{
int depth = item.getDepth();
int xpos = depth * 20 + 5;
return x >= xpos && x <= xpos + 8;
}
GuiTreeBox::HandlePtr GuiTreeBox::findItemByIndex(int index)
{
int pos = 0;
TreeDepthFirstIterator<GuiTreeBoxItem> iterator(_items);
while ( pos < index && iterator.isValid() )
{
GuiTreeBoxItem& item = iterator.item();
++iterator;
++pos;
}
return iterator.isValid() ? reinterpret_cast< TreeNode<GuiTreeBoxItem>* >(iterator.key()) : NULL;
}
//////////////////////////////////////////////////////////////////////////
// - search interface
//////////////////////////////////////////////////////////////////////////
GuiTreeBoxItem* GuiTreeBox::findItemByText(const std::string& text)
{
TreeDepthFirstIterator<GuiTreeBoxItem> it(_items);
while ( it.isValid() )
{
GuiTreeBoxItem& item = it.item();
if ( item.getText() == text )
{
return &item;
}
++it;
}
return NULL;
}
int GuiTreeBox::findIndex(HandlePtr pitem)
{
TreeDepthFirstIterator<GuiTreeBoxItem> it(_items);
int index = 0;
while ( it.isValid() )
{
if ( it.key() == pitem)
return index;
++index;
++it;
}
return -1;
}
<commit_msg>* fixed tree icons<commit_after>/***************************************************************************
* Copyright (C) 2006 by Jeroen Broekhuizen *
* jengine.sse@live.nl *
* *
* This program is free software; you can redistribute it and/or modify *
* it under the terms of the GNU Library General Public License as *
* published by the Free Software Foundation; either version 2 of the *
* License, or (at your option) any later version. *
* *
* This program is distributed in the hope that it will be useful, *
* but WITHOUT ANY WARRANTY; without even the implied warranty of *
* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the *
* GNU General Public License for more details. *
* *
* You should have received a copy of the GNU Library General Public *
* License along with this program; if not, write to the *
* Free Software Foundation, Inc., *
* 59 Temple Place - Suite 330, Boston, MA 02111-1307, USA. *
***************************************************************************/
#include "guitreebox.h"
#ifndef JENGINE_INLINE
# include "guitreebox.inl"
#endif
#include "../containers/treedepthfirstiterator.h"
#include "../scriptmanager.h"
#include "guidesigner.h"
#include "guidefines.h"
#include "guifont.h"
#include "guieventhandler.h"
#include "guieventhandlers.h"
#include "guieventhandlerdefinition.h"
#include "guieventhandlerdefinitions.h"
#include "guimanager.h"
#include "guiscopedtransform.h"
#include "guitext.h"
REGISTER_DESIGNER(GuiTreeBox, GuiTreeBoxId, "Treebox", 40, 15, 392)
GuiTreeBox::GuiTreeBox():
GuiControl(),
_items(),
_selections()
{
}
GuiTreeBox::~GuiTreeBox()
{
}
//////////////////////////////////////////////////////////////////////////
// - get/set interface
//////////////////////////////////////////////////////////////////////////
bool GuiTreeBox::hasSelection() const
{
return !_selections.empty();
}
const GuiTreeBox::Handle GuiTreeBox::getSelection() const
{
ASSERT(_selections.size() > 0)
return *_selections.front();
}
GuiTreeBox::Handle GuiTreeBox::getSelection()
{
ASSERT(_selections.size() > 0)
return *_selections.front();
}
//////////////////////////////////////////////////////////////////////////
// - creation
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::onCreate (const GuiRect& rect, const char* caption, GuiStyle style, GuiWnd* parent)
{
GuiControl::onCreate(rect, caption, style, parent);
GuiTreeBoxItem* pitem = new GuiTreeBoxItem();
pitem->setText("'Designer'");
pitem->setIcon("folder.png");
GuiTreeBoxItem* pchild = new GuiTreeBoxItem();
pchild->setText("Dialogs");
pchild->setIcon("application_double.png");
GuiTreeBoxItem* pdialog = new GuiTreeBoxItem();
pdialog->setText("des_openfile");
pdialog->setIcon("application_form.png");
_items.insert(NULL, *pitem);
HandlePtr pnode = _items.findElement(*pitem);
_items.insert(pnode, *pchild);
pnode = _items.findElement(*pchild);
_items.insert(pnode, *pdialog);
}
//////////////////////////////////////////////////////////////////////////
// - painting
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::paint(Uint32 tick, const GuiGraphics& graphics)
{
if ( _items.hasRoot() )
{
int y = 5;
Handle root = _items.getRoot();
GuiScopedTransform transform(*this);
recursePaint(root, 5, y, graphics);
}
}
void GuiTreeBox::recursePaint(Handle item, int x, int& y, const GuiGraphics& graphics)
{
drawItem(item, x, y, graphics);
y += 16;
if ( item.isExpanded() )
{
TreeNode<GuiTreeBoxItem>::Children& children = item.getChildren();
ListIterator< TreeNode<GuiTreeBoxItem> > it(children);
while ( it.isValid() )
{
recursePaint(it.item(), x + 20, y, graphics);
++it;
}
}
}
void GuiTreeBox::drawItem(const Handle item, int x, int y, const GuiGraphics& graphics)
{
graphics.setColor(1, 1, 1);
paintCheck(item, x, y + getParent()->getFont()->getBaseHeight(), graphics);
if ( item.getData().hasIcon() )
graphics.drawImage(*item.getData().getIcon(), GuiRect(x+15, x+31, y, y+16));
paintText(item, x, y, graphics);
}
void GuiTreeBox::paintText(const Handle item, int x, int y, const GuiGraphics& graphics)
{
const std::string& title = item.getData().getText();
if ( item.getData().isSelected() )
{
int width = getFont()->getAverageWidth() * title.length() + 34;
GuiRect rect(x+34, x+width, y + 1, y + getFont()->getHeight() - 1);
graphics.setColor(0, 0, 1);
graphics.drawRect(rect);
graphics.setColor(1, 1, 1);
GuiText::printfn(*getFont(), x + 34, y+getFont()->getBaseHeight(), title.c_str(), title.size());
}
else
{
graphics.setColor(GuiManager::getInstance().getDefaultTextColor());
GuiText::printfn(*getFont(), x + 34, y+getFont()->getBaseHeight(), title.c_str(), title.size());
}
}
void GuiTreeBox::paintCheck(const Handle item, int x, int y, const GuiGraphics& graphics)
{
if ( item.hasChildren() )
{
graphics.drawWireRect(GuiRect(x, x+8, y, y-8));
glBegin(GL_LINES);
glVertex2i(x+2, y-4);
glVertex2i(x+7, y-4);
if ( !item.isExpanded() )
{
glVertex2i(x+4, y-2);
glVertex2i(x+4, y-7);
}
glEnd();
}
}
//////////////////////////////////////////////////////////////////////////
// - event handler interface
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::initializeEventHandlerDefinitions()
{
GuiControl::initializeEventHandlerDefinitions();
GuiEventHandlerDefinition* pdefinition = new GuiEventHandlerDefinition(GuiTreeSelChangeEvent, "onSelectionChanged");
pdefinition->addArgument("selection");
getEventHandlerDefinitions().add(pdefinition);
}
//////////////////////////////////////////////////////////////////////////
// - input interface
//////////////////////////////////////////////////////////////////////////
int GuiTreeBox::onLButtonUp (const GuiPoint& point, int flag)
{
select(point);
return 0;
}
//////////////////////////////////////////////////////////////////////////
// - operations
//////////////////////////////////////////////////////////////////////////
void GuiTreeBox::insert(HandlePtr position, GuiTreeBoxItem& item)
{
_items.insert(position, item);
}
void GuiTreeBox::select(const GuiPoint& point)
{
int index = (point.y - 5) / 16;
HandlePtr pitem = findItemByIndex(index);
if ( pitem != NULL )
{
if ( isAboveCheckbox(*pitem, point.x) )
{
if ( pitem->isExpanded() )
pitem->collapse();
else
pitem->expand();
}
else
{
select(pitem);
}
}
}
void GuiTreeBox::select(HandlePtr pitem)
{
deselectAll();
_selections.push_back(pitem);
GuiTreeBoxItem& item = pitem->getData();
item.setSelected(true);
GuiEventHandler* phandler = getEventHandlers().findByEventType(GuiTreeSelChangeEvent);
if ( phandler != NULL )
{
ScriptManager& mgr = ScriptManager::getInstance();
Script& script = mgr.getTemporaryScript();
script.setSelf(this, "GuiTreeBox");
script.prepareCall(phandler->getFunctionName().c_str());
script.addParam(findIndex(pitem));
script.run(1);
}
}
void GuiTreeBox::deselectAll()
{
while ( !_selections.empty() )
{
HandlePtr pitem = _selections.front();
pitem->getData().setSelected(false);
_selections.pop_front();
}
}
bool GuiTreeBox::isAboveCheckbox(Handle item, int x)
{
int depth = item.getDepth();
int xpos = depth * 20 + 5;
return x >= xpos && x <= xpos + 8;
}
GuiTreeBox::HandlePtr GuiTreeBox::findItemByIndex(int index)
{
int pos = 0;
TreeDepthFirstIterator<GuiTreeBoxItem> iterator(_items);
while ( pos < index && iterator.isValid() )
{
GuiTreeBoxItem& item = iterator.item();
++iterator;
++pos;
}
return iterator.isValid() ? reinterpret_cast< TreeNode<GuiTreeBoxItem>* >(iterator.key()) : NULL;
}
//////////////////////////////////////////////////////////////////////////
// - search interface
//////////////////////////////////////////////////////////////////////////
GuiTreeBoxItem* GuiTreeBox::findItemByText(const std::string& text)
{
TreeDepthFirstIterator<GuiTreeBoxItem> it(_items);
while ( it.isValid() )
{
GuiTreeBoxItem& item = it.item();
if ( item.getText() == text )
{
return &item;
}
++it;
}
return NULL;
}
int GuiTreeBox::findIndex(HandlePtr pitem)
{
TreeDepthFirstIterator<GuiTreeBoxItem> it(_items);
int index = 0;
while ( it.isValid() )
{
if ( it.key() == pitem)
return index;
++index;
++it;
}
return -1;
}
<|endoftext|> |
<commit_before>#include "sprite.h"
#include "gfx.h"
#include "CodeAttributes.h"
#ifndef DEDICATED_ONLY
#include "blitters/context.h"
#endif
#include "gusanos/allegro.h"
#include <iostream>
#include <algorithm>
using namespace std;
// LIGHTHAX!!
#include "CVec.h"
Sprite* genLight( int radius )
{
ALLEGRO_BITMAP* lightHax;
{
//LocalSetColorDepth cd(8);
lightHax = create_bitmap_ex(8, 2*radius, 2*radius );
}
for ( int x = 0; x < lightHax->w; ++x )
for ( int y = 0; y < lightHax->h; ++y ) {
int color = (int)(255 - ( 255 * Vec( (float)(radius-x), (float)(radius-y) ).length() ) / (float)radius);
if ( color < 0 )
color = 0;
putpixel(lightHax,x,y,color);
}
return new Sprite(lightHax, radius, radius);
}
Sprite::Sprite( ALLEGRO_BITMAP* bitmap, int xPivot, int yPivot)
: m_bitmap(bitmap) //, m_mirror(0)
{
if ( xPivot == -1 )
m_xPivot = m_bitmap->w / 2;
else
m_xPivot = xPivot * 2;
if ( yPivot == -1 )
m_yPivot = m_bitmap->h / 2;
else
m_yPivot = yPivot * 2;
}
INLINE int scaleColor(int a, int b, int bmax)
{
return makecol(
getr(a) * b / bmax,
getg(a) * b / bmax,
getb(a) * b / bmax);
}
INLINE int brightenColor(int a, int b)
{
return makecol(
std::min(getr(a) + b, 255),
std::min(getg(a) + b, 255),
std::min(getb(a) + b, 255));
}
#ifndef DEDICATED_ONLY
Sprite::Sprite(Sprite const& b, Sprite const& mask, int color)
: m_bitmap(
create_bitmap_ex(
bitmap_color_depth(b.m_bitmap),
b.m_bitmap->w,
b.m_bitmap->h
)
)/*, m_mirror(0)*/, m_xPivot(b.m_xPivot), m_yPivot(b.m_yPivot)
{
int colorDepth = bitmap_color_depth(b.m_bitmap);
LocalSetColorDepth cd(colorDepth);
//int unchanged = makecol(255, 0, 255); //unused
int wormColor = makecol(0, 0, 0);
//int max = getr(makecol(255, 0, 0)); //unused
ALLEGRO_BITMAP* maskBitmap = mask.m_bitmap;
ALLEGRO_BITMAP* srcBitmap = b.m_bitmap;
/*
for(int y = 0; y < m_bitmap->h; ++y)
for(int x = 0; x < m_bitmap->w; ++x)
{
int col = getpixel_solid(srcBitmap, x, y);
int m = getpixel(maskBitmap, x, y);
if(m == wormColor)
col = specialTint(colorDepth, color, lightness(colorDepth, col));
putpixel_solid(m_bitmap, x, y, col);
}*/
static const int limit = 104;
for(int y = 0; y < m_bitmap->h; ++y)
for(int x = 0; x < m_bitmap->w; ++x) {
int col = getpixel(srcBitmap, x, y);
int m = getpixel(maskBitmap, x, y);
if(m == wormColor) {
int magn = getr(col);
if(magn <= limit)
col = scaleColor(color, magn, limit);
else {
int fact = 256*limit / magn;
col = brightenColor(scaleColor(color, fact, 256), 256-fact);
}
}
putpixel_solid(m_bitmap, x, y, col);
}
}
#endif
Sprite::Sprite(Sprite const& b, MirrorTag)
: m_bitmap(
create_bitmap_ex(
bitmap_color_depth(b.m_bitmap),
b.m_bitmap->w,
b.m_bitmap->h
)
)/*, m_mirror(0)*/, m_xPivot( (b.m_bitmap->w -1 ) - b.m_xPivot), m_yPivot(b.m_yPivot)
{
clear_to_color(m_bitmap, makecol(255,0,255));
draw_sprite_h_flip(m_bitmap, b.m_bitmap, 0, 0);
}
Sprite::~Sprite()
{
destroy_bitmap( m_bitmap );
}
#ifndef DEDICATED_ONLY
void Sprite::drawCut(ALLEGRO_BITMAP *where, int x, int y, BlitterContext const& blender, int alignment, int left, int top, int bottom, int right)
{
int realX = x + left, realY = y + top;
if ( alignment & ALIGN_LEFT ) /* Do nothing */
;
else if ( alignment & ALIGN_RIGHT )
realX += m_bitmap->w;
else
realX += m_xPivot;
if ( alignment & ALIGN_TOP ) /* Do nothing */
;
else if ( alignment & ALIGN_BOTTOM )
realY += m_bitmap->h;
else
realY += m_yPivot;
blender.drawSpriteCut(where, m_bitmap, realX, realY, left, top, right, bottom);
}
void Sprite::draw(ALLEGRO_BITMAP *where, int x, int y/*, bool flipped*/, int alignment)
{
draw(where, x, y, BlitterContext()/*, flipped*/, alignment);
}
void Sprite::draw(ALLEGRO_BITMAP *where, int x, int y, BlitterContext const& blender/*, bool flipped*/, int alignment )
{
int _x,_y;
if ( alignment & ALIGN_LEFT )
_x = 0;
else if ( alignment & ALIGN_RIGHT )
_x = m_bitmap->w;
else
_x = m_xPivot;
if ( alignment & ALIGN_TOP )
_y = 0;
else if ( alignment & ALIGN_BOTTOM )
_y = m_bitmap->h;
else
_y = m_yPivot;
/*
if ( flipped )
{
if(!m_mirror)
{
LocalSetColorConversion cc(COLORCONV_NONE);
LocalSetColorDepth cd(bitmap_color_depth(m_bitmap));
m_mirror = create_bitmap(m_bitmap->w,m_bitmap->h);
clear_to_color(m_mirror,makecol(255,0,255));
draw_sprite_h_flip(m_mirror, m_bitmap, 0, 0);
}
blender.drawSprite(where, m_mirror, x - ( m_bitmap->w - 1 ) + _x, y - _y);
}
else*/ {
blender.drawSprite(where, m_bitmap, x - _x, y - _y);
}
}
#ifdef RLE
void Sprite::writeRun(bool state, int startx, int starty, int len)
{
if(state) {
runs.insert(runs.end(), sizeof(int), 0);
int* r = reinterpret_cast<int *>(&runs[runs.size() - sizeof(int)]);
*r = len;
switch(bitmap_color_depth(m_bitmap)) {
case 32: {
for(; len > 0; --len, ++startx) {
runs.insert(runs.end(), sizeof(Pixel32), 0);
Pixel32* p = reinterpret_cast<Pixel32 *>(&runs[runs.size() - sizeof(Pixel32)]);
*p = getpixel(m_bitmap, startx, starty);
}
}
break;
case 16: {
for(; len > 0; --len, ++startx) {
runs.insert(runs.end(), sizeof(Pixel16), 0);
Pixel16* p = reinterpret_cast<Pixel16 *>(&runs[runs.size() - sizeof(Pixel16)]);
*p = getpixel(m_bitmap, startx, starty);
}
}
break;
}
else {
runs.insert(runs.end(), sizeof(int), 0);
int* r = reinterpret_cast<int *>(&runs[runs.size() - sizeof(int)]);
*r = len;
}
}
void Sprite::compileRLE(int flags) {
bool state = false;
int run = 0;
for(int y = 0; y < m_bitmap->h; ++y) {
int startx = 0;
for(int x = 0; x < m_bitmap->w; ++x) {
int pix = getpixel(m_bitmap, x, y);
if(isTrans(pix, flags) == state) {
++run;
} else {
writeRun(state, startx, y, run);
state = !state;
run = 1;
startx = x;
}
}
if(run > 0) {
writeRun(state, startx, y, run);
run = 0;
}
state = false;
}
}
#endif
#endif
<commit_msg>small fix<commit_after>#include "sprite.h"
#include "gfx.h"
#include "CodeAttributes.h"
#ifndef DEDICATED_ONLY
#include "blitters/context.h"
#endif
#include "gusanos/allegro.h"
#include <iostream>
#include <algorithm>
using namespace std;
// LIGHTHAX!!
#include "CVec.h"
Sprite* genLight( int radius )
{
radius *= 2; // doubleRes
ALLEGRO_BITMAP* lightHax;
{
//LocalSetColorDepth cd(8);
lightHax = create_bitmap_ex(8, 2*radius, 2*radius );
}
for ( int x = 0; x < lightHax->w; ++x )
for ( int y = 0; y < lightHax->h; ++y ) {
int color = (int)(255 - ( 255 * Vec( (float)(radius-x), (float)(radius-y) ).length() ) / (float)radius);
if ( color < 0 )
color = 0;
putpixel(lightHax,x,y,color);
}
return new Sprite(lightHax, radius, radius);
}
Sprite::Sprite( ALLEGRO_BITMAP* bitmap, int xPivot, int yPivot)
: m_bitmap(bitmap) //, m_mirror(0)
{
if ( xPivot == -1 )
m_xPivot = m_bitmap->w / 2;
else
m_xPivot = xPivot * 2;
if ( yPivot == -1 )
m_yPivot = m_bitmap->h / 2;
else
m_yPivot = yPivot * 2;
}
INLINE int scaleColor(int a, int b, int bmax)
{
return makecol(
getr(a) * b / bmax,
getg(a) * b / bmax,
getb(a) * b / bmax);
}
INLINE int brightenColor(int a, int b)
{
return makecol(
std::min(getr(a) + b, 255),
std::min(getg(a) + b, 255),
std::min(getb(a) + b, 255));
}
#ifndef DEDICATED_ONLY
Sprite::Sprite(Sprite const& b, Sprite const& mask, int color)
: m_bitmap(
create_bitmap_ex(
bitmap_color_depth(b.m_bitmap),
b.m_bitmap->w,
b.m_bitmap->h
)
)/*, m_mirror(0)*/, m_xPivot(b.m_xPivot), m_yPivot(b.m_yPivot)
{
int colorDepth = bitmap_color_depth(b.m_bitmap);
LocalSetColorDepth cd(colorDepth);
//int unchanged = makecol(255, 0, 255); //unused
int wormColor = makecol(0, 0, 0);
//int max = getr(makecol(255, 0, 0)); //unused
ALLEGRO_BITMAP* maskBitmap = mask.m_bitmap;
ALLEGRO_BITMAP* srcBitmap = b.m_bitmap;
/*
for(int y = 0; y < m_bitmap->h; ++y)
for(int x = 0; x < m_bitmap->w; ++x)
{
int col = getpixel_solid(srcBitmap, x, y);
int m = getpixel(maskBitmap, x, y);
if(m == wormColor)
col = specialTint(colorDepth, color, lightness(colorDepth, col));
putpixel_solid(m_bitmap, x, y, col);
}*/
static const int limit = 104;
for(int y = 0; y < m_bitmap->h; ++y)
for(int x = 0; x < m_bitmap->w; ++x) {
int col = getpixel(srcBitmap, x, y);
int m = getpixel(maskBitmap, x, y);
if(m == wormColor) {
int magn = getr(col);
if(magn <= limit)
col = scaleColor(color, magn, limit);
else {
int fact = 256*limit / magn;
col = brightenColor(scaleColor(color, fact, 256), 256-fact);
}
}
putpixel_solid(m_bitmap, x, y, col);
}
}
#endif
Sprite::Sprite(Sprite const& b, MirrorTag)
: m_bitmap(
create_bitmap_ex(
bitmap_color_depth(b.m_bitmap),
b.m_bitmap->w,
b.m_bitmap->h
)
)/*, m_mirror(0)*/, m_xPivot( (b.m_bitmap->w -1 ) - b.m_xPivot), m_yPivot(b.m_yPivot)
{
clear_to_color(m_bitmap, makecol(255,0,255));
draw_sprite_h_flip(m_bitmap, b.m_bitmap, 0, 0);
}
Sprite::~Sprite()
{
destroy_bitmap( m_bitmap );
}
#ifndef DEDICATED_ONLY
void Sprite::drawCut(ALLEGRO_BITMAP *where, int x, int y, BlitterContext const& blender, int alignment, int left, int top, int bottom, int right)
{
int realX = x + left, realY = y + top;
if ( alignment & ALIGN_LEFT ) /* Do nothing */
;
else if ( alignment & ALIGN_RIGHT )
realX += m_bitmap->w;
else
realX += m_xPivot;
if ( alignment & ALIGN_TOP ) /* Do nothing */
;
else if ( alignment & ALIGN_BOTTOM )
realY += m_bitmap->h;
else
realY += m_yPivot;
blender.drawSpriteCut(where, m_bitmap, realX, realY, left, top, right, bottom);
}
void Sprite::draw(ALLEGRO_BITMAP *where, int x, int y/*, bool flipped*/, int alignment)
{
draw(where, x, y, BlitterContext()/*, flipped*/, alignment);
}
void Sprite::draw(ALLEGRO_BITMAP *where, int x, int y, BlitterContext const& blender/*, bool flipped*/, int alignment )
{
int _x,_y;
if ( alignment & ALIGN_LEFT )
_x = 0;
else if ( alignment & ALIGN_RIGHT )
_x = m_bitmap->w;
else
_x = m_xPivot;
if ( alignment & ALIGN_TOP )
_y = 0;
else if ( alignment & ALIGN_BOTTOM )
_y = m_bitmap->h;
else
_y = m_yPivot;
/*
if ( flipped )
{
if(!m_mirror)
{
LocalSetColorConversion cc(COLORCONV_NONE);
LocalSetColorDepth cd(bitmap_color_depth(m_bitmap));
m_mirror = create_bitmap(m_bitmap->w,m_bitmap->h);
clear_to_color(m_mirror,makecol(255,0,255));
draw_sprite_h_flip(m_mirror, m_bitmap, 0, 0);
}
blender.drawSprite(where, m_mirror, x - ( m_bitmap->w - 1 ) + _x, y - _y);
}
else*/ {
blender.drawSprite(where, m_bitmap, x - _x, y - _y);
}
}
#ifdef RLE
void Sprite::writeRun(bool state, int startx, int starty, int len)
{
if(state) {
runs.insert(runs.end(), sizeof(int), 0);
int* r = reinterpret_cast<int *>(&runs[runs.size() - sizeof(int)]);
*r = len;
switch(bitmap_color_depth(m_bitmap)) {
case 32: {
for(; len > 0; --len, ++startx) {
runs.insert(runs.end(), sizeof(Pixel32), 0);
Pixel32* p = reinterpret_cast<Pixel32 *>(&runs[runs.size() - sizeof(Pixel32)]);
*p = getpixel(m_bitmap, startx, starty);
}
}
break;
case 16: {
for(; len > 0; --len, ++startx) {
runs.insert(runs.end(), sizeof(Pixel16), 0);
Pixel16* p = reinterpret_cast<Pixel16 *>(&runs[runs.size() - sizeof(Pixel16)]);
*p = getpixel(m_bitmap, startx, starty);
}
}
break;
}
else {
runs.insert(runs.end(), sizeof(int), 0);
int* r = reinterpret_cast<int *>(&runs[runs.size() - sizeof(int)]);
*r = len;
}
}
void Sprite::compileRLE(int flags) {
bool state = false;
int run = 0;
for(int y = 0; y < m_bitmap->h; ++y) {
int startx = 0;
for(int x = 0; x < m_bitmap->w; ++x) {
int pix = getpixel(m_bitmap, x, y);
if(isTrans(pix, flags) == state) {
++run;
} else {
writeRun(state, startx, y, run);
state = !state;
run = 1;
startx = x;
}
}
if(run > 0) {
writeRun(state, startx, y, run);
run = 0;
}
state = false;
}
}
#endif
#endif
<|endoftext|> |
<commit_before>#ifndef INSANITY_SYSTEM_HPP
#define INSANITY_SYSTEM_HPP
#include "game.hpp"
#include "game_config.hpp"
#include "components/velocity.hpp"
#include "entityx/entityx.h"
#include "glm/common.hpp"
#include <iostream>
#ifdef __EMSCRIPTEN__
#include <SDL/SDL_mixer.h>
#else
#include <SDL_mixer.h>
#endif
class InsanitySystem : public entityx::System<InsanitySystem> {
public:
InsanitySystem(Game *game) : game(game), time(0.0), factor(1.0f) {
}
void update(entityx::EntityManager &es, entityx::EventManager &events, double dt) {
if(this->game->isFrozen()){
factor += dt / 10;
this->time += dt;
game->addInsanity(dt * INSANITY_SPEED * factor);
if (this->time > glm::max(glm::min(20.0f / game->getInsanity(), 4.0f), 1.0f)) {
game->addInsanity(-0.5);
this->time = 0.0f;
Mix_Volume(3, 100);
Mix_PlayChannel(3, game->res_manager().sound("heartbeat"), 0);
}
} else {
factor = 1.0f;
}
}
private:
Game *game;
double time;
float factor;
};
#endif
<commit_msg>stop stomper if insanity<commit_after>#ifndef INSANITY_SYSTEM_HPP
#define INSANITY_SYSTEM_HPP
#include "game.hpp"
#include "game_config.hpp"
#include "components/velocity.hpp"
#include "components/stomper.hpp"
#include "entityx/entityx.h"
#include "glm/common.hpp"
#include <iostream>
#ifdef __EMSCRIPTEN__
#include <SDL/SDL_mixer.h>
#else
#include <SDL_mixer.h>
#endif
class InsanitySystem : public entityx::System<InsanitySystem> {
public:
InsanitySystem(Game *game) : game(game), time(0.0), factor(1.0f) {
}
void update(entityx::EntityManager &es, entityx::EventManager &events, double dt) {
entityx::ComponentHandle<Stomper> stomper;
if(this->game->isFrozen()){
for (entityx::Entity stomp : es.entities_with_components(stomper)) {
(void) stomp;
stomper->setRunning(false);
}
factor += dt / 10;
this->time += dt;
game->addInsanity(dt * INSANITY_SPEED * factor);
if (this->time > glm::max(glm::min(20.0f / game->getInsanity(), 4.0f), 1.0f)) {
game->addInsanity(-0.5);
this->time = 0.0f;
Mix_Volume(3, 100);
Mix_PlayChannel(3, game->res_manager().sound("heartbeat"), 0);
}
} else {
factor = 1.0f;
for (entityx::Entity stomp : es.entities_with_components(stomper)) {
(void) stomp;
stomper->setRunning(true);
}
}
}
private:
Game *game;
double time;
float factor;
};
#endif
<|endoftext|> |
<commit_before>#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <functional>
#include <GLFW/glfw3.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
static int xioctl(int fh, int request, void *arg)
{
int r;
do {
r = ioctl(fh, request, arg);
} while (r < 0 && errno == EINTR);
return r;
}
struct buffer { void * start; size_t length; };
#pragma pack(push, 1)
struct z16y8_pixel { uint16_t z; uint8_t y; };
#pragma pack(pop)
void throw_error(const char * s)
{
std::ostringstream ss;
ss << s << " error " << errno << ", " << strerror(errno);
throw std::runtime_error(s);
}
void warn_error(const char * s)
{
std::cerr << s << " error " << errno << ", " << strerror(errno) << std::endl;
}
class subdevice
{
std::string dev_name;
int fd;
std::vector<buffer> buffers;
std::function<void(const void *, size_t)> callback;
public:
subdevice(const std::string & dev_name) : dev_name(dev_name), fd()
{
struct stat st;
if(stat(dev_name.c_str(), &st) < 0)
{
std::ostringstream ss; ss << "Cannot identify '" << dev_name << "': " << errno << ", " << strerror(errno);
throw std::runtime_error(ss.str());
}
if(!S_ISCHR(st.st_mode)) throw std::runtime_error(dev_name + " is no device");
fd = open(dev_name.c_str(), O_RDWR | O_NONBLOCK, 0);
if(fd < 0)
{
std::ostringstream ss; ss << "Cannot open '" << dev_name << "': " << errno << ", " << strerror(errno);
throw std::runtime_error(ss.str());
}
v4l2_capability cap = {};
if(xioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
{
if(errno == EINVAL) throw std::runtime_error(dev_name + " is no V4L2 device");
else throw_error("VIDIOC_QUERYCAP");
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) throw std::runtime_error(dev_name + " is no video capture device");
if (!(cap.capabilities & V4L2_CAP_STREAMING)) throw std::runtime_error(dev_name + " does not support streaming I/O");
// Select video input, video standard and tune here.
v4l2_cropcap cropcap = {};
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap))
{
v4l2_crop crop = {};
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect; // reset to default
if (xioctl(fd, VIDIOC_S_CROP, &crop) < 0)
{
switch (errno)
{
case EINVAL: break; // Cropping not supported
default: break; // Errors ignored
}
}
} else {} // Errors ignored
}
~subdevice()
{
v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(fd, VIDIOC_STREAMOFF, &type) < 0) warn_error("VIDIOC_STREAMOFF");
for(int i = 0; i < buffers.size(); ++i)
{
if(munmap(buffers[i].start, buffers[i].length) < 0) warn_error("munmap");
}
if(close(fd) < 0) warn_error("close");
}
void set_format(int width, int height, int pixelformat)
{
v4l2_format fmt = {};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = width;
fmt.fmt.pix.height = height;
fmt.fmt.pix.pixelformat = pixelformat;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if(xioctl(fd, VIDIOC_S_FMT, &fmt) < 0) throw_error("VIDIOC_S_FMT");
// Note VIDIOC_S_FMT may change width and height
}
void start_capture(std::function<void(const void * data, size_t size)> callback)
{
v4l2_format fmt = {};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(fd, VIDIOC_G_FMT, &fmt) < 0) throw_error("VIDIOC_G_FMT");
// Buggy driver paranoia.
unsigned int min = fmt.fmt.pix.width * 2;
if(fmt.fmt.pix.bytesperline < min) fmt.fmt.pix.bytesperline = min;
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if(fmt.fmt.pix.sizeimage < min) fmt.fmt.pix.sizeimage = min;
// Init memory mapped IO
v4l2_requestbuffers req = {};
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if(xioctl(fd, VIDIOC_REQBUFS, &req) < 0)
{
if(errno == EINVAL) throw std::runtime_error(dev_name + " does not support memory mapping");
else throw_error("VIDIOC_REQBUFS");
}
if(req.count < 2)
{
throw std::runtime_error("Insufficient buffer memory on " + dev_name);
}
buffers.resize(req.count);
for(int i=0; i<buffers.size(); ++i)
{
v4l2_buffer buf = {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if(xioctl(fd, VIDIOC_QUERYBUF, &buf) < 0) throw_error("VIDIOC_QUERYBUF");
buffers[i].length = buf.length;
buffers[i].start = mmap(NULL /* start anywhere */,
buf.length,
PROT_READ | PROT_WRITE /* required */,
MAP_SHARED /* recommended */,
fd, buf.m.offset);
if(buffers[i].start == MAP_FAILED) throw_error("mmap");
}
// Start capturing
for(int i = 0; i < buffers.size(); ++i)
{
v4l2_buffer buf = {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if(xioctl(fd, VIDIOC_QBUF, &buf) < 0) throw_error("VIDIOC_QBUF");
}
v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(fd, VIDIOC_STREAMON, &type) < 0) throw_error("VIDIOC_STREAMON");
this->callback = callback;
}
static void poll(std::initializer_list<subdevice *> subdevices)
{
int max_fd = 0;
fd_set fds;
FD_ZERO(&fds);
for(auto * sub : subdevices)
{
FD_SET(sub->fd, &fds);
max_fd = std::max(max_fd, sub->fd);
}
struct timeval tv;
tv.tv_sec = 2;
tv.tv_usec = 0;
int r = select(max_fd + 1, &fds, NULL, NULL, &tv);
if(r < 0)
{
if (errno == EINTR) return;
throw_error("select");
}
for(auto * sub : subdevices)
{
if(FD_ISSET(sub->fd, &fds))
{
v4l2_buffer buf = {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(xioctl(sub->fd, VIDIOC_DQBUF, &buf) < 0)
{
if(errno == EAGAIN) return;
throw_error("VIDIOC_DQBUF");
}
assert(buf.index < sub->buffers.size());
sub->callback(sub->buffers[buf.index].start, buf.bytesused);
if(xioctl(sub->fd, VIDIOC_QBUF, &buf) < 0) throw_error("VIDIOC_QBUF");
}
}
}
};
int main(int argc, char * argv[])
{
uint16_t z[640*480] = {};
uint8_t yuy2[640*480*2] = {};
subdevice dev0("/dev/video0"), dev1("/dev/video1");
dev0.set_format(640, 480, V4L2_PIX_FMT_YUYV);
dev0.start_capture([&](const void * data, size_t size) { if(size == sizeof(yuy2)) memcpy(yuy2, data, size); });
dev1.set_format(640, 480, v4l2_fourcc('I','N','V','R'));
dev1.start_capture([&](const void * data, size_t size) { if(size == sizeof(z)) memcpy(z, data, size); });
// Open a GLFW window
glfwInit();
GLFWwindow * win = glfwCreateWindow(1280, 480, "V4L2 test", 0, 0);
glfwMakeContextCurrent(win);
// While window is open
while (!glfwWindowShouldClose(win))
{
glfwPollEvents();
subdevice::poll({&dev0, &dev1});
int w,h;
glfwGetFramebufferSize(win, &w, &h);
glViewport(0, 0, w, h);
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glfwGetWindowSize(win, &w, &h);
glOrtho(0, w, h, 0, -1, +1);
glRasterPos2i(0, 480);
glDrawPixels(640, 480, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, yuy2);
glRasterPos2i(640, 480);
glDrawPixels(640, 480, GL_LUMINANCE, GL_UNSIGNED_SHORT, z);
glPopMatrix();
glfwSwapBuffers(win);
}
glfwDestroyWindow(win);
glfwTerminate();
return EXIT_SUCCESS;
}
<commit_msg>Instant timeout on select<commit_after>#include <cassert>
#include <cstdlib>
#include <cstdio>
#include <cstring>
#include <vector>
#include <sstream>
#include <iostream>
#include <stdexcept>
#include <functional>
#include <GLFW/glfw3.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#include <sys/stat.h>
#include <sys/mman.h>
#include <sys/ioctl.h>
#include <linux/videodev2.h>
static int xioctl(int fh, int request, void *arg)
{
int r;
do {
r = ioctl(fh, request, arg);
} while (r < 0 && errno == EINTR);
return r;
}
struct buffer { void * start; size_t length; };
#pragma pack(push, 1)
struct z16y8_pixel { uint16_t z; uint8_t y; };
#pragma pack(pop)
void throw_error(const char * s)
{
std::ostringstream ss;
ss << s << " error " << errno << ", " << strerror(errno);
throw std::runtime_error(s);
}
void warn_error(const char * s)
{
std::cerr << s << " error " << errno << ", " << strerror(errno) << std::endl;
}
class subdevice
{
std::string dev_name;
int fd;
std::vector<buffer> buffers;
std::function<void(const void *, size_t)> callback;
public:
subdevice(const std::string & dev_name) : dev_name(dev_name), fd()
{
struct stat st;
if(stat(dev_name.c_str(), &st) < 0)
{
std::ostringstream ss; ss << "Cannot identify '" << dev_name << "': " << errno << ", " << strerror(errno);
throw std::runtime_error(ss.str());
}
if(!S_ISCHR(st.st_mode)) throw std::runtime_error(dev_name + " is no device");
fd = open(dev_name.c_str(), O_RDWR | O_NONBLOCK, 0);
if(fd < 0)
{
std::ostringstream ss; ss << "Cannot open '" << dev_name << "': " << errno << ", " << strerror(errno);
throw std::runtime_error(ss.str());
}
v4l2_capability cap = {};
if(xioctl(fd, VIDIOC_QUERYCAP, &cap) < 0)
{
if(errno == EINVAL) throw std::runtime_error(dev_name + " is no V4L2 device");
else throw_error("VIDIOC_QUERYCAP");
}
if (!(cap.capabilities & V4L2_CAP_VIDEO_CAPTURE)) throw std::runtime_error(dev_name + " is no video capture device");
if (!(cap.capabilities & V4L2_CAP_STREAMING)) throw std::runtime_error(dev_name + " does not support streaming I/O");
// Select video input, video standard and tune here.
v4l2_cropcap cropcap = {};
cropcap.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if (0 == xioctl(fd, VIDIOC_CROPCAP, &cropcap))
{
v4l2_crop crop = {};
crop.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
crop.c = cropcap.defrect; // reset to default
if (xioctl(fd, VIDIOC_S_CROP, &crop) < 0)
{
switch (errno)
{
case EINVAL: break; // Cropping not supported
default: break; // Errors ignored
}
}
} else {} // Errors ignored
}
~subdevice()
{
v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(fd, VIDIOC_STREAMOFF, &type) < 0) warn_error("VIDIOC_STREAMOFF");
for(int i = 0; i < buffers.size(); ++i)
{
if(munmap(buffers[i].start, buffers[i].length) < 0) warn_error("munmap");
}
if(close(fd) < 0) warn_error("close");
}
void set_format(int width, int height, int pixelformat)
{
v4l2_format fmt = {};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
fmt.fmt.pix.width = width;
fmt.fmt.pix.height = height;
fmt.fmt.pix.pixelformat = pixelformat;
fmt.fmt.pix.field = V4L2_FIELD_INTERLACED;
if(xioctl(fd, VIDIOC_S_FMT, &fmt) < 0) throw_error("VIDIOC_S_FMT");
// Note VIDIOC_S_FMT may change width and height
}
void start_capture(std::function<void(const void * data, size_t size)> callback)
{
v4l2_format fmt = {};
fmt.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(fd, VIDIOC_G_FMT, &fmt) < 0) throw_error("VIDIOC_G_FMT");
// Buggy driver paranoia.
unsigned int min = fmt.fmt.pix.width * 2;
if(fmt.fmt.pix.bytesperline < min) fmt.fmt.pix.bytesperline = min;
min = fmt.fmt.pix.bytesperline * fmt.fmt.pix.height;
if(fmt.fmt.pix.sizeimage < min) fmt.fmt.pix.sizeimage = min;
// Init memory mapped IO
v4l2_requestbuffers req = {};
req.count = 4;
req.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
req.memory = V4L2_MEMORY_MMAP;
if(xioctl(fd, VIDIOC_REQBUFS, &req) < 0)
{
if(errno == EINVAL) throw std::runtime_error(dev_name + " does not support memory mapping");
else throw_error("VIDIOC_REQBUFS");
}
if(req.count < 2)
{
throw std::runtime_error("Insufficient buffer memory on " + dev_name);
}
buffers.resize(req.count);
for(int i=0; i<buffers.size(); ++i)
{
v4l2_buffer buf = {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if(xioctl(fd, VIDIOC_QUERYBUF, &buf) < 0) throw_error("VIDIOC_QUERYBUF");
buffers[i].length = buf.length;
buffers[i].start = mmap(NULL /* start anywhere */,
buf.length,
PROT_READ | PROT_WRITE /* required */,
MAP_SHARED /* recommended */,
fd, buf.m.offset);
if(buffers[i].start == MAP_FAILED) throw_error("mmap");
}
// Start capturing
for(int i = 0; i < buffers.size(); ++i)
{
v4l2_buffer buf = {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
buf.index = i;
if(xioctl(fd, VIDIOC_QBUF, &buf) < 0) throw_error("VIDIOC_QBUF");
}
v4l2_buf_type type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
if(xioctl(fd, VIDIOC_STREAMON, &type) < 0) throw_error("VIDIOC_STREAMON");
this->callback = callback;
}
static void poll(std::initializer_list<subdevice *> subdevices)
{
int max_fd = 0;
fd_set fds;
FD_ZERO(&fds);
for(auto * sub : subdevices)
{
FD_SET(sub->fd, &fds);
max_fd = std::max(max_fd, sub->fd);
}
struct timeval tv = {};
if(select(max_fd + 1, &fds, NULL, NULL, &tv) < 0)
{
if (errno == EINTR) return;
throw_error("select");
}
for(auto * sub : subdevices)
{
if(FD_ISSET(sub->fd, &fds))
{
v4l2_buffer buf = {};
buf.type = V4L2_BUF_TYPE_VIDEO_CAPTURE;
buf.memory = V4L2_MEMORY_MMAP;
if(xioctl(sub->fd, VIDIOC_DQBUF, &buf) < 0)
{
if(errno == EAGAIN) return;
throw_error("VIDIOC_DQBUF");
}
assert(buf.index < sub->buffers.size());
sub->callback(sub->buffers[buf.index].start, buf.bytesused);
if(xioctl(sub->fd, VIDIOC_QBUF, &buf) < 0) throw_error("VIDIOC_QBUF");
}
}
}
};
int main(int argc, char * argv[])
{
uint16_t z[640*480] = {};
uint8_t yuy2[640*480*2] = {};
subdevice dev0("/dev/video0"), dev1("/dev/video1");
dev0.set_format(640, 480, V4L2_PIX_FMT_YUYV);
dev0.start_capture([&](const void * data, size_t size) { if(size == sizeof(yuy2)) memcpy(yuy2, data, size); });
dev1.set_format(640, 480, v4l2_fourcc('I','N','V','R'));
dev1.start_capture([&](const void * data, size_t size) { if(size == sizeof(z)) memcpy(z, data, size); });
// Open a GLFW window
glfwInit();
GLFWwindow * win = glfwCreateWindow(1280, 480, "V4L2 test", 0, 0);
glfwMakeContextCurrent(win);
// While window is open
while (!glfwWindowShouldClose(win))
{
glfwPollEvents();
subdevice::poll({&dev0, &dev1});
int w,h;
glfwGetFramebufferSize(win, &w, &h);
glViewport(0, 0, w, h);
glClear(GL_COLOR_BUFFER_BIT);
glPushMatrix();
glfwGetWindowSize(win, &w, &h);
glOrtho(0, w, h, 0, -1, +1);
glRasterPos2i(0, 480);
glDrawPixels(640, 480, GL_LUMINANCE_ALPHA, GL_UNSIGNED_BYTE, yuy2);
glRasterPos2i(640, 480);
glDrawPixels(640, 480, GL_LUMINANCE, GL_UNSIGNED_SHORT, z);
glPopMatrix();
glfwSwapBuffers(win);
}
glfwDestroyWindow(win);
glfwTerminate();
return EXIT_SUCCESS;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for alert system
#include "alert.h"
#include "chain.h"
#include "chainparams.h"
#include "clientversion.h"
namespace alert_tests {
#include "data/alertTests.raw.h"
}
#include "serialize.h"
#include "streams.h"
#include "utilstrencodings.h"
#include "test/testutil.h"
#include "test/test_dash.h"
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
//
// Sign a CAlert and serialize it
//
bool SignAndSave(CAlert &alert)
{
// Sign
if(!alert.Sign())
{
printf("SignAndSave() : could not sign alert:\n%s", alert.ToString().c_str());
return false;
}
std::string strFilePath = "src/test/data/alertTests.raw";
// open output file and associate it with CAutoFile
FILE *file = fopen(strFilePath.c_str(), "ab+");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, strFilePath);
try {
fileout << alert;
}
catch (std::exception &e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
return true;
}
//
// alertTests contains 8 alerts, generated with this code
//
void GenerateAlertTests()
{
CAlert alert;
alert.nRelayUntil = 60;
alert.nExpiration = 24 * 60 * 60;
alert.nID = 1;
alert.nCancel = 0; // cancels previous messages up to this ID number
alert.nMinVer = 0; // These versions are protocol versions
alert.nMaxVer = 999001;
alert.nPriority = 1;
alert.strComment = "Alert comment";
alert.strStatusBar = "Alert 1";
SignAndSave(alert);
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0";
SignAndSave(alert);
alert.setSubVer.insert(std::string("/Satoshi:0.2.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0";
SignAndSave(alert);
alert.setSubVer.clear();
++alert.nID;
alert.nCancel = 1;
alert.nPriority = 100;
alert.strStatusBar = "Alert 2, cancels 1";
SignAndSave(alert);
alert.nExpiration += 60;
++alert.nID;
SignAndSave(alert);
++alert.nID;
alert.nMinVer = 11;
alert.nMaxVer = 22;
SignAndSave(alert);
++alert.nID;
alert.strStatusBar = "Alert 2 for Satoshi 0.1.0";
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
SignAndSave(alert);
++alert.nID;
alert.nMinVer = 0;
alert.nMaxVer = 999999;
alert.strStatusBar = "Evil Alert'; /bin/ls; echo '";
alert.setSubVer.clear();
SignAndSave(alert);
}
struct ReadAlerts : public TestingSetup
{
ReadAlerts()
{
std::vector<unsigned char> vch(alert_tests::alertTests, alert_tests::alertTests + sizeof(alert_tests::alertTests));
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
try {
while (!stream.eof())
{
CAlert alert;
stream >> alert;
alerts.push_back(alert);
}
}
catch (const std::exception&) { }
}
~ReadAlerts() { }
static std::vector<std::string> read_lines(boost::filesystem::path filepath)
{
std::vector<std::string> result;
std::ifstream f(filepath.string().c_str());
std::string line;
while (std::getline(f,line))
result.push_back(line);
return result;
}
std::vector<CAlert> alerts;
};
BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts)
// Steps to generate alert tests:
// - update alerts in GenerateAlertTests() (optional)
// - enable code below (#if 1)
// - replace "fffffffffffffffffffffffffffffffffffffffffffffffffff" with the actual MAINNET privkey
// - recompile and run "/path/to/test_dash -t Alert_test"
//
// NOTE: make sure to disable code and remove alert privkey when you're done!
//
#if 0
BOOST_AUTO_TEST_CASE(GenerateAlerts)
{
SoftSetArg("-alertkey", "fffffffffffffffffffffffffffffffffffffffffffffffffff");
GenerateAlertTests();
}
#endif
BOOST_AUTO_TEST_CASE(AlertApplies)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
BOOST_FOREACH(const CAlert& alert, alerts)
{
BOOST_CHECK(alert.CheckSignature(alertKey));
}
BOOST_CHECK(alerts.size() >= 3);
// Matches:
BOOST_CHECK(alerts[0].AppliesTo(1, ""));
BOOST_CHECK(alerts[0].AppliesTo(999001, ""));
BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
BOOST_CHECK(!alerts[0].AppliesTo(-1, ""));
BOOST_CHECK(!alerts[0].AppliesTo(999002, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
SetMockTime(0);
}
BOOST_AUTO_TEST_CASE(AlertNotify)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
boost::filesystem::path temp = GetTempPath() /
boost::filesystem::unique_path("alertnotify-%%%%.txt");
mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string();
BOOST_FOREACH(CAlert alert, alerts)
alert.ProcessAlert(alertKey, false);
std::vector<std::string> r = read_lines(temp);
BOOST_CHECK_EQUAL(r.size(), 4u);
// Windows built-in echo semantics are different than posixy shells. Quotes and
// whitespace are printed literally.
#ifndef WIN32
BOOST_CHECK_EQUAL(r[0], "Alert 1");
BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed
#else
BOOST_CHECK_EQUAL(r[0], "'Alert 1' ");
BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' ");
#endif
boost::filesystem::remove(temp);
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
<commit_msg>Remove namespace alert_tests when including alert test data<commit_after>// Copyright (c) 2013-2015 The Bitcoin Core developers
// Distributed under the MIT software license, see the accompanying
// file COPYING or http://www.opensource.org/licenses/mit-license.php.
// Unit tests for alert system
#include "alert.h"
#include "chain.h"
#include "chainparams.h"
#include "clientversion.h"
#include "data/alertTests.raw.h"
#include "serialize.h"
#include "streams.h"
#include "utilstrencodings.h"
#include "test/testutil.h"
#include "test/test_dash.h"
#include <fstream>
#include <boost/filesystem/operations.hpp>
#include <boost/foreach.hpp>
#include <boost/test/unit_test.hpp>
//
// Sign a CAlert and serialize it
//
bool SignAndSave(CAlert &alert)
{
// Sign
if(!alert.Sign())
{
printf("SignAndSave() : could not sign alert:\n%s", alert.ToString().c_str());
return false;
}
std::string strFilePath = "src/test/data/alertTests.raw";
// open output file and associate it with CAutoFile
FILE *file = fopen(strFilePath.c_str(), "ab+");
CAutoFile fileout(file, SER_DISK, CLIENT_VERSION);
if (fileout.IsNull())
return error("%s: Failed to open file %s", __func__, strFilePath);
try {
fileout << alert;
}
catch (std::exception &e) {
return error("%s: Serialize or I/O error - %s", __func__, e.what());
}
fileout.fclose();
return true;
}
//
// alertTests contains 8 alerts, generated with this code
//
void GenerateAlertTests()
{
CAlert alert;
alert.nRelayUntil = 60;
alert.nExpiration = 24 * 60 * 60;
alert.nID = 1;
alert.nCancel = 0; // cancels previous messages up to this ID number
alert.nMinVer = 0; // These versions are protocol versions
alert.nMaxVer = 999001;
alert.nPriority = 1;
alert.strComment = "Alert comment";
alert.strStatusBar = "Alert 1";
SignAndSave(alert);
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0";
SignAndSave(alert);
alert.setSubVer.insert(std::string("/Satoshi:0.2.0/"));
alert.strStatusBar = "Alert 1 for Satoshi 0.1.0, 0.2.0";
SignAndSave(alert);
alert.setSubVer.clear();
++alert.nID;
alert.nCancel = 1;
alert.nPriority = 100;
alert.strStatusBar = "Alert 2, cancels 1";
SignAndSave(alert);
alert.nExpiration += 60;
++alert.nID;
SignAndSave(alert);
++alert.nID;
alert.nMinVer = 11;
alert.nMaxVer = 22;
SignAndSave(alert);
++alert.nID;
alert.strStatusBar = "Alert 2 for Satoshi 0.1.0";
alert.setSubVer.insert(std::string("/Satoshi:0.1.0/"));
SignAndSave(alert);
++alert.nID;
alert.nMinVer = 0;
alert.nMaxVer = 999999;
alert.strStatusBar = "Evil Alert'; /bin/ls; echo '";
alert.setSubVer.clear();
SignAndSave(alert);
}
struct ReadAlerts : public TestingSetup
{
ReadAlerts()
{
std::vector<unsigned char> vch(alertTests, alertTests + sizeof(alertTests));
CDataStream stream(vch, SER_DISK, CLIENT_VERSION);
try {
while (!stream.eof())
{
CAlert alert;
stream >> alert;
alerts.push_back(alert);
}
}
catch (const std::exception&) { }
}
~ReadAlerts() { }
static std::vector<std::string> read_lines(boost::filesystem::path filepath)
{
std::vector<std::string> result;
std::ifstream f(filepath.string().c_str());
std::string line;
while (std::getline(f,line))
result.push_back(line);
return result;
}
std::vector<CAlert> alerts;
};
BOOST_FIXTURE_TEST_SUITE(Alert_tests, ReadAlerts)
// Steps to generate alert tests:
// - update alerts in GenerateAlertTests() (optional)
// - enable code below (#if 1)
// - replace "fffffffffffffffffffffffffffffffffffffffffffffffffff" with the actual MAINNET privkey
// - recompile and run "/path/to/test_dash -t Alert_test"
//
// NOTE: make sure to disable code and remove alert privkey when you're done!
//
#if 0
BOOST_AUTO_TEST_CASE(GenerateAlerts)
{
SoftSetArg("-alertkey", "fffffffffffffffffffffffffffffffffffffffffffffffffff");
GenerateAlertTests();
}
#endif
BOOST_AUTO_TEST_CASE(AlertApplies)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
BOOST_FOREACH(const CAlert& alert, alerts)
{
BOOST_CHECK(alert.CheckSignature(alertKey));
}
BOOST_CHECK(alerts.size() >= 3);
// Matches:
BOOST_CHECK(alerts[0].AppliesTo(1, ""));
BOOST_CHECK(alerts[0].AppliesTo(999001, ""));
BOOST_CHECK(alerts[0].AppliesTo(1, "/Satoshi:11.11.11/"));
BOOST_CHECK(alerts[1].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[1].AppliesTo(999001, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.1.0/"));
BOOST_CHECK(alerts[2].AppliesTo(1, "/Satoshi:0.2.0/"));
// Don't match:
BOOST_CHECK(!alerts[0].AppliesTo(-1, ""));
BOOST_CHECK(!alerts[0].AppliesTo(999002, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, ""));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.1.0"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(-1, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(999002, "/Satoshi:0.1.0/"));
BOOST_CHECK(!alerts[1].AppliesTo(1, "/Satoshi:0.2.0/"));
BOOST_CHECK(!alerts[2].AppliesTo(1, "/Satoshi:0.3.0/"));
SetMockTime(0);
}
BOOST_AUTO_TEST_CASE(AlertNotify)
{
SetMockTime(11);
const std::vector<unsigned char>& alertKey = Params(CBaseChainParams::MAIN).AlertKey();
boost::filesystem::path temp = GetTempPath() /
boost::filesystem::unique_path("alertnotify-%%%%.txt");
mapArgs["-alertnotify"] = std::string("echo %s >> ") + temp.string();
BOOST_FOREACH(CAlert alert, alerts)
alert.ProcessAlert(alertKey, false);
std::vector<std::string> r = read_lines(temp);
BOOST_CHECK_EQUAL(r.size(), 4u);
// Windows built-in echo semantics are different than posixy shells. Quotes and
// whitespace are printed literally.
#ifndef WIN32
BOOST_CHECK_EQUAL(r[0], "Alert 1");
BOOST_CHECK_EQUAL(r[1], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[2], "Alert 2, cancels 1");
BOOST_CHECK_EQUAL(r[3], "Evil Alert; /bin/ls; echo "); // single-quotes should be removed
#else
BOOST_CHECK_EQUAL(r[0], "'Alert 1' ");
BOOST_CHECK_EQUAL(r[1], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[2], "'Alert 2, cancels 1' ");
BOOST_CHECK_EQUAL(r[3], "'Evil Alert; /bin/ls; echo ' ");
#endif
boost::filesystem::remove(temp);
SetMockTime(0);
}
BOOST_AUTO_TEST_SUITE_END()
<|endoftext|> |
<commit_before>/// Tests chunked upload and zipped upload against the Rackspace cloud files API
/// https://developer.rackspace.com/docs/cloud-files/v1/developer-guide/#create-or-update-object
#include <RESTClient/base/logger.hpp>
#include <RESTClient/http/HTTP.hpp>
#include <RESTClient/http/Services.hpp>
#include <RESTClient/jobManagement/JobRunner.hpp>
// From jsonpp11 external project in cmake
#include <parse_to_json_class.hpp>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>
int main(int argc, char *argv[]) {
using namespace std::placeholders;
std::vector<RESTClient::QueuedJob> tests;
// First we need to authenticate against the RS API, before we can get the URL for all the tests
RESTClient::JobRunner jobs;
using json::JSON;
using json::JMap;
JSON info;
jobs.queue("https://identity.api.rackspacecloud.com").emplace(RESTClient::QueuedJob{
"Login", "https://identity.api.rackspacecloud.com/v2.0/tokens",
[&info](const std::string &name, const std::string &hostname,
RESTClient::HTTP &conn) {
JSON j(JMap{{"auth", JMap{{"RAX-KSKEY:apiKeyCredentials",
JMap{{"username", RS_USERNAME},
{"apiKey", RS_APIKEY}}}}}});
RESTClient::HTTPRequest request{
"POST", "/v2.0/tokens", {{"Content-type", "application/json"}}};
std::ostream& putter(request.body);
putter << j;
RESTClient::HTTPResponse response = conn.action(request);
if (!((response.code >= 200) && (response.code < 300)))
LOG_ERROR("Couldn't log in to RS: code("
<< response.code << ") message (" << response.body << ")");
std::string data(response.body);
info = json::readValue(data.begin(), data.end());
return true;
}});
jobs.startProcessing();
RESTClient::Services::instance().io_service.run();
// Now get the sydney cloud files URL
const std::string& token = info["access"]["token"]["id"];
std::cout << token << std::endl;
return 0;
}
<commit_msg>Now gets cloud files URL<commit_after>/// Tests chunked upload and zipped upload against the Rackspace cloud files API
/// https://developer.rackspace.com/docs/cloud-files/v1/developer-guide/#create-or-update-object
#include <RESTClient/base/logger.hpp>
#include <RESTClient/http/HTTP.hpp>
#include <RESTClient/http/Services.hpp>
#include <RESTClient/jobManagement/JobRunner.hpp>
// From jsonpp11 external project in cmake
#include <parse_to_json_class.hpp>
#include <iostream>
#include <sstream>
#include <boost/regex.hpp>
#include <boost/algorithm/string/predicate.hpp>
int main(int argc, char *argv[]) {
using namespace std::placeholders;
std::vector<RESTClient::QueuedJob> tests;
// First we need to authenticate against the RS API, before we can get the URL for all the tests
RESTClient::JobRunner jobs;
using json::JSON;
using json::JMap;
JSON info;
jobs.queue("https://identity.api.rackspacecloud.com").emplace(RESTClient::QueuedJob{
"Login", "https://identity.api.rackspacecloud.com/v2.0/tokens",
[&info](const std::string &name, const std::string &hostname,
RESTClient::HTTP &conn) {
JSON j(JMap{{"auth", JMap{{"RAX-KSKEY:apiKeyCredentials",
JMap{{"username", RS_USERNAME},
{"apiKey", RS_APIKEY}}}}}});
RESTClient::HTTPRequest request{
"POST", "/v2.0/tokens", {{"Content-type", "application/json"}}};
std::ostream& putter(request.body);
putter << j;
RESTClient::HTTPResponse response = conn.action(request);
if (!((response.code >= 200) && (response.code < 300)))
LOG_ERROR("Couldn't log in to RS: code("
<< response.code << ") message (" << response.body << ")");
std::string data(response.body);
info = json::readValue(data.begin(), data.end());
return true;
}});
jobs.startProcessing();
RESTClient::Services::instance().io_service.run();
// Now get the sydney cloud files URL
const std::string& token = info["access"]["token"]["id"];
std::cout << "Token: " << token << std::endl;
const std::string* syd_cf = nullptr;
const json::JList& catalog = info["access"]["serviceCatalog"];
for (const JMap& service : catalog)
if (service.at("name") == "cloudFiles") {
const json::JList& endpoints = service.at("endpoints");
for (const JMap &point : endpoints)
if (point.at("region") == "SYD") {
const std::string& tmp = point.at("publicURL");
syd_cf = &tmp;
}
}
if (syd_cf == nullptr)
std::cout << "NO URL" << std::endl;
else
std::cout << "Syd URL: " << (*syd_cf) << std::endl;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/BlockHDF5.hpp>
#include <nix/util/util.hpp>
#include <nix/Block.hpp>
#include <nix/hdf5/SourceHDF5.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/TagHDF5.hpp>
#include <nix/hdf5/MultiTagHDF5.hpp>
#include <boost/range/irange.hpp>
using namespace std;
using namespace nix::base;
namespace nix {
namespace hdf5 {
BlockHDF5::BlockHDF5(const std::shared_ptr<base::IFile> &file, const Group &group)
: EntityWithMetadataHDF5(file, group) {
data_array_group = this->group().openOptGroup("data_arrays");
tag_group = this->group().openOptGroup("tags");
multi_tag_group = this->group().openOptGroup("multi_tags");
source_group = this->group().openOptGroup("sources");
}
BlockHDF5::BlockHDF5(const shared_ptr<IFile> &file, const Group &group, const string &id, const string &type, const string &name)
: BlockHDF5(file, group, id, type, name, util::getTime()) {
}
BlockHDF5::BlockHDF5(const shared_ptr<IFile> &file, const Group &group, const string &id, const string &type, const string &name, time_t time)
: EntityWithMetadataHDF5(file, group, id, type, name, time) {
data_array_group = this->group().openOptGroup("data_arrays");
tag_group = this->group().openOptGroup("tags");
multi_tag_group = this->group().openOptGroup("multi_tags");
source_group = this->group().openOptGroup("sources");
}
//--------------------------------------------------
// Methods concerning sources
//--------------------------------------------------
bool BlockHDF5::hasSource(const string &name_or_id) const {
return getSource(name_or_id) != nullptr;
}
shared_ptr<ISource> BlockHDF5::getSource(const string &name_or_id) const {
shared_ptr<SourceHDF5> source;
boost::optional<Group> g = source_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
source = make_shared<SourceHDF5>(file(), *group);
}
return source;
}
shared_ptr<ISource> BlockHDF5::getSource(ndsize_t index) const {
boost::optional<Group> g = source_group();
string name = g ? g->objectName(index) : "";
return getSource(name);
}
ndsize_t BlockHDF5::sourceCount() const {
boost::optional<Group> g = source_group();
return g ? g->objectCount() : size_t(0);
}
shared_ptr<ISource> BlockHDF5::createSource(const string &name, const string &type) {
if (name.empty()) {
throw EmptyString("name");
}
if (hasSource(name)) {
throw DuplicateName("createSource");
}
string id = util::createId();
boost::optional<Group> g = source_group(true);
Group group = g->openGroup(name, true);
return make_shared<SourceHDF5>(file(), group, id, type, name);
}
bool BlockHDF5::deleteSource(const string &name_or_id) {
boost::optional<Group> g = source_group();
bool deleted = false;
if (g) {
// call deleteSource on sources to trigger recursive call to all sub-sources
if (hasSource(name_or_id)) {
// get instance of source about to get deleted
Source source = getSource(name_or_id);
// loop through all child sources and call deleteSource on them
for (auto &child : source.sources()) {
source.deleteSource(child.id());
}
// if hasSource is true then source_group always exists
deleted = g->removeAllLinks(source.name());
}
}
return deleted;
}
//--------------------------------------------------
// Methods related to Tag
//--------------------------------------------------
shared_ptr<ITag> BlockHDF5::createTag(const std::string &name, const std::string &type,
const std::vector<double> &position) {
if (hasTag(name)) {
throw DuplicateName("createTag");
}
string id = util::createId();
boost::optional<Group> g = tag_group(true);
Group group = g->openGroup(name);
return make_shared<TagHDF5>(file(), block(), group, id, type, name, position);
}
bool BlockHDF5::hasTag(const string &name_or_id) const {
return getTag(name_or_id) != nullptr;
}
shared_ptr<ITag> BlockHDF5::getTag(const string &name_or_id) const {
shared_ptr<TagHDF5> tag;
boost::optional<Group> g = tag_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
tag = make_shared<TagHDF5>(file(), block(), *group);
}
return tag;
}
shared_ptr<ITag> BlockHDF5::getTag(ndsize_t index) const {
boost::optional<Group> g = tag_group();
string name = g ? g->objectName(index) : "";
return getTag(name);
}
ndsize_t BlockHDF5::tagCount() const {
boost::optional<Group> g = tag_group();
return g ? g->objectCount() : size_t(0);
}
bool BlockHDF5::deleteTag(const std::string &name_or_id) {
boost::optional<Group> g = tag_group();
bool deleted = false;
if (hasTag(name_or_id) && g) {
// we get first "entity" link by name, but delete all others whatever their name with it
deleted = g->removeAllLinks(getTag(name_or_id)->name());
}
return deleted;
}
//--------------------------------------------------
// Methods related to DataArray
//--------------------------------------------------
bool BlockHDF5::hasDataArray(const string &name_or_id) const {
return getDataArray(name_or_id) != nullptr;
}
shared_ptr<IDataArray> BlockHDF5::getDataArray(const string &name_or_id) const {
shared_ptr<DataArrayHDF5> da;
boost::optional<Group> g = data_array_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
da = make_shared<DataArrayHDF5>(file(), block(), *group);
}
return da;
}
shared_ptr<IDataArray> BlockHDF5::getDataArray(ndsize_t index) const {
boost::optional<Group> g = data_array_group();
string name = g ? g->objectName(index) : "";
return getDataArray(name);
}
ndsize_t BlockHDF5::dataArrayCount() const {
boost::optional<Group> g = data_array_group();
return g ? g->objectCount() : size_t(0);
}
shared_ptr<IDataArray> BlockHDF5::createDataArray(const std::string &name,
const std::string &type,
nix::DataType data_type,
const NDSize &shape) {
if (hasDataArray(name)) {
throw DuplicateName("createDataArray");
}
string id = util::createId();
boost::optional<Group> g = data_array_group(true);
Group group = g->openGroup(name, true);
auto da = make_shared<DataArrayHDF5>(file(), block(), group, id, type, name);
// now create the actual H5::DataSet
da->createData(data_type, shape);
return da;
}
bool BlockHDF5::deleteDataArray(const string &name_or_id) {
bool deleted = false;
boost::optional<Group> g = data_array_group();
if (hasDataArray(name_or_id) && g) {
// we get first "entity" link by name, but delete all others whatever their name with it
deleted = g->removeAllLinks(getDataArray(name_or_id)->name());
}
return deleted;
}
//--------------------------------------------------
// Methods related to MultiTag
//--------------------------------------------------
shared_ptr<IMultiTag> BlockHDF5::createMultiTag(const std::string &name, const std::string &type,
const DataArray &positions) {
if (hasMultiTag(name)) {
throw DuplicateName("createMultiTag");
}
if (!positions) {
throw UninitializedEntity();
}
string id = util::createId();
boost::optional<Group> g = multi_tag_group(true);
Group group = g->openGroup(name);
return make_shared<MultiTagHDF5>(file(), block(), group, id, type, name, positions);
}
bool BlockHDF5::hasMultiTag(const string &name_or_id) const {
return getMultiTag(name_or_id) != nullptr;
}
shared_ptr<IMultiTag> BlockHDF5::getMultiTag(const string &name_or_id) const {
shared_ptr<MultiTagHDF5> mtag;
boost::optional<Group> g = multi_tag_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
mtag = make_shared<MultiTagHDF5>(file(), block(), *group);
}
return mtag;
}
shared_ptr<IMultiTag> BlockHDF5::getMultiTag(ndsize_t index) const {
boost::optional<Group> g = multi_tag_group();
string name = g ? g->objectName(index) : "";
return getMultiTag(name);
}
ndsize_t BlockHDF5::multiTagCount() const {
boost::optional<Group> g = multi_tag_group();
return g ? g->objectCount() : size_t(0);
}
bool BlockHDF5::deleteMultiTag(const std::string &name_or_id) {
boost::optional<Group> g = multi_tag_group();
bool deleted = false;
if (hasMultiTag(name_or_id) && g) {
// we get first "entity" link by name, but delete all others whatever their name with it
deleted = g->removeAllLinks(getMultiTag(name_or_id)->name());
}
return deleted;
}
shared_ptr<IBlock> BlockHDF5::block() const {
return const_pointer_cast<BlockHDF5>(shared_from_this());
}
BlockHDF5::~BlockHDF5() {
}
} // ns nix::hdf5
} // ns nix<commit_msg>[BlockHDF5] createDataArray: add check for empty name<commit_after>// Copyright (c) 2013, German Neuroinformatics Node (G-Node)
//
// All rights reserved.
//
// Redistribution and use in source and binary forms, with or without
// modification, are permitted under the terms of the BSD License. See
// LICENSE file in the root of the Project.
#include <nix/hdf5/BlockHDF5.hpp>
#include <nix/util/util.hpp>
#include <nix/Block.hpp>
#include <nix/hdf5/SourceHDF5.hpp>
#include <nix/hdf5/DataArrayHDF5.hpp>
#include <nix/hdf5/TagHDF5.hpp>
#include <nix/hdf5/MultiTagHDF5.hpp>
#include <boost/range/irange.hpp>
using namespace std;
using namespace nix::base;
namespace nix {
namespace hdf5 {
BlockHDF5::BlockHDF5(const std::shared_ptr<base::IFile> &file, const Group &group)
: EntityWithMetadataHDF5(file, group) {
data_array_group = this->group().openOptGroup("data_arrays");
tag_group = this->group().openOptGroup("tags");
multi_tag_group = this->group().openOptGroup("multi_tags");
source_group = this->group().openOptGroup("sources");
}
BlockHDF5::BlockHDF5(const shared_ptr<IFile> &file, const Group &group, const string &id, const string &type, const string &name)
: BlockHDF5(file, group, id, type, name, util::getTime()) {
}
BlockHDF5::BlockHDF5(const shared_ptr<IFile> &file, const Group &group, const string &id, const string &type, const string &name, time_t time)
: EntityWithMetadataHDF5(file, group, id, type, name, time) {
data_array_group = this->group().openOptGroup("data_arrays");
tag_group = this->group().openOptGroup("tags");
multi_tag_group = this->group().openOptGroup("multi_tags");
source_group = this->group().openOptGroup("sources");
}
//--------------------------------------------------
// Methods concerning sources
//--------------------------------------------------
bool BlockHDF5::hasSource(const string &name_or_id) const {
return getSource(name_or_id) != nullptr;
}
shared_ptr<ISource> BlockHDF5::getSource(const string &name_or_id) const {
shared_ptr<SourceHDF5> source;
boost::optional<Group> g = source_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
source = make_shared<SourceHDF5>(file(), *group);
}
return source;
}
shared_ptr<ISource> BlockHDF5::getSource(ndsize_t index) const {
boost::optional<Group> g = source_group();
string name = g ? g->objectName(index) : "";
return getSource(name);
}
ndsize_t BlockHDF5::sourceCount() const {
boost::optional<Group> g = source_group();
return g ? g->objectCount() : size_t(0);
}
shared_ptr<ISource> BlockHDF5::createSource(const string &name, const string &type) {
if (name.empty()) {
throw EmptyString("name");
}
if (hasSource(name)) {
throw DuplicateName("createSource");
}
string id = util::createId();
boost::optional<Group> g = source_group(true);
Group group = g->openGroup(name, true);
return make_shared<SourceHDF5>(file(), group, id, type, name);
}
bool BlockHDF5::deleteSource(const string &name_or_id) {
boost::optional<Group> g = source_group();
bool deleted = false;
if (g) {
// call deleteSource on sources to trigger recursive call to all sub-sources
if (hasSource(name_or_id)) {
// get instance of source about to get deleted
Source source = getSource(name_or_id);
// loop through all child sources and call deleteSource on them
for (auto &child : source.sources()) {
source.deleteSource(child.id());
}
// if hasSource is true then source_group always exists
deleted = g->removeAllLinks(source.name());
}
}
return deleted;
}
//--------------------------------------------------
// Methods related to Tag
//--------------------------------------------------
shared_ptr<ITag> BlockHDF5::createTag(const std::string &name, const std::string &type,
const std::vector<double> &position) {
if (hasTag(name)) {
throw DuplicateName("createTag");
}
string id = util::createId();
boost::optional<Group> g = tag_group(true);
Group group = g->openGroup(name);
return make_shared<TagHDF5>(file(), block(), group, id, type, name, position);
}
bool BlockHDF5::hasTag(const string &name_or_id) const {
return getTag(name_or_id) != nullptr;
}
shared_ptr<ITag> BlockHDF5::getTag(const string &name_or_id) const {
shared_ptr<TagHDF5> tag;
boost::optional<Group> g = tag_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
tag = make_shared<TagHDF5>(file(), block(), *group);
}
return tag;
}
shared_ptr<ITag> BlockHDF5::getTag(ndsize_t index) const {
boost::optional<Group> g = tag_group();
string name = g ? g->objectName(index) : "";
return getTag(name);
}
ndsize_t BlockHDF5::tagCount() const {
boost::optional<Group> g = tag_group();
return g ? g->objectCount() : size_t(0);
}
bool BlockHDF5::deleteTag(const std::string &name_or_id) {
boost::optional<Group> g = tag_group();
bool deleted = false;
if (hasTag(name_or_id) && g) {
// we get first "entity" link by name, but delete all others whatever their name with it
deleted = g->removeAllLinks(getTag(name_or_id)->name());
}
return deleted;
}
//--------------------------------------------------
// Methods related to DataArray
//--------------------------------------------------
bool BlockHDF5::hasDataArray(const string &name_or_id) const {
return getDataArray(name_or_id) != nullptr;
}
shared_ptr<IDataArray> BlockHDF5::getDataArray(const string &name_or_id) const {
shared_ptr<DataArrayHDF5> da;
boost::optional<Group> g = data_array_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
da = make_shared<DataArrayHDF5>(file(), block(), *group);
}
return da;
}
shared_ptr<IDataArray> BlockHDF5::getDataArray(ndsize_t index) const {
boost::optional<Group> g = data_array_group();
string name = g ? g->objectName(index) : "";
return getDataArray(name);
}
ndsize_t BlockHDF5::dataArrayCount() const {
boost::optional<Group> g = data_array_group();
return g ? g->objectCount() : size_t(0);
}
shared_ptr<IDataArray> BlockHDF5::createDataArray(const std::string &name,
const std::string &type,
nix::DataType data_type,
const NDSize &shape) {
if (name.empty()) {
throw EmptyString("Block::createDataArray: empty name provided!");
}
if (hasDataArray(name)) {
throw DuplicateName("createDataArray");
}
string id = util::createId();
boost::optional<Group> g = data_array_group(true);
Group group = g->openGroup(name, true);
auto da = make_shared<DataArrayHDF5>(file(), block(), group, id, type, name);
// now create the actual H5::DataSet
da->createData(data_type, shape);
return da;
}
bool BlockHDF5::deleteDataArray(const string &name_or_id) {
bool deleted = false;
boost::optional<Group> g = data_array_group();
if (hasDataArray(name_or_id) && g) {
// we get first "entity" link by name, but delete all others whatever their name with it
deleted = g->removeAllLinks(getDataArray(name_or_id)->name());
}
return deleted;
}
//--------------------------------------------------
// Methods related to MultiTag
//--------------------------------------------------
shared_ptr<IMultiTag> BlockHDF5::createMultiTag(const std::string &name, const std::string &type,
const DataArray &positions) {
if (hasMultiTag(name)) {
throw DuplicateName("createMultiTag");
}
if (!positions) {
throw UninitializedEntity();
}
string id = util::createId();
boost::optional<Group> g = multi_tag_group(true);
Group group = g->openGroup(name);
return make_shared<MultiTagHDF5>(file(), block(), group, id, type, name, positions);
}
bool BlockHDF5::hasMultiTag(const string &name_or_id) const {
return getMultiTag(name_or_id) != nullptr;
}
shared_ptr<IMultiTag> BlockHDF5::getMultiTag(const string &name_or_id) const {
shared_ptr<MultiTagHDF5> mtag;
boost::optional<Group> g = multi_tag_group();
if (g) {
boost::optional<Group> group = g->findGroupByNameOrAttribute("entity_id", name_or_id);
if (group)
mtag = make_shared<MultiTagHDF5>(file(), block(), *group);
}
return mtag;
}
shared_ptr<IMultiTag> BlockHDF5::getMultiTag(ndsize_t index) const {
boost::optional<Group> g = multi_tag_group();
string name = g ? g->objectName(index) : "";
return getMultiTag(name);
}
ndsize_t BlockHDF5::multiTagCount() const {
boost::optional<Group> g = multi_tag_group();
return g ? g->objectCount() : size_t(0);
}
bool BlockHDF5::deleteMultiTag(const std::string &name_or_id) {
boost::optional<Group> g = multi_tag_group();
bool deleted = false;
if (hasMultiTag(name_or_id) && g) {
// we get first "entity" link by name, but delete all others whatever their name with it
deleted = g->removeAllLinks(getMultiTag(name_or_id)->name());
}
return deleted;
}
shared_ptr<IBlock> BlockHDF5::block() const {
return const_pointer_cast<BlockHDF5>(shared_from_this());
}
BlockHDF5::~BlockHDF5() {
}
} // ns nix::hdf5
} // ns nix<|endoftext|> |
<commit_before>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ipc/client_impl.h"
#include <fcntl.h>
#include <inttypes.h>
#include <unistd.h>
#include <utility>
#include "perfetto/base/task_runner.h"
#include "perfetto/base/utils.h"
#include "perfetto/ipc/service_descriptor.h"
#include "perfetto/ipc/service_proxy.h"
// TODO(primiano): Add ThreadChecker everywhere.
// TODO(primiano): Add timeouts.
namespace perfetto {
namespace ipc {
// static
std::unique_ptr<Client> Client::CreateInstance(const char* socket_name,
base::TaskRunner* task_runner) {
std::unique_ptr<Client> client(new ClientImpl(socket_name, task_runner));
return client;
}
ClientImpl::ClientImpl(const char* socket_name, base::TaskRunner* task_runner)
: task_runner_(task_runner), weak_ptr_factory_(this) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
sock_ = UnixSocket::Connect(socket_name, this, task_runner);
}
ClientImpl::~ClientImpl() {
// Ensure we are not destroyed in the middle of invoking a reply.
PERFETTO_DCHECK(!invoking_method_reply_);
OnDisconnect(nullptr); // The UnixSocket* ptr is not used in OnDisconnect().
}
void ClientImpl::BindService(base::WeakPtr<ServiceProxy> service_proxy) {
if (!service_proxy)
return;
if (!sock_->is_connected())
return queued_bindings_.emplace_back(service_proxy);
RequestID request_id = ++last_request_id_;
Frame frame;
frame.set_request_id(request_id);
Frame::BindService* req = frame.mutable_msg_bind_service();
const char* const service_name = service_proxy->GetDescriptor().service_name;
req->set_service_name(service_name);
if (!SendFrame(frame)) {
PERFETTO_DLOG("BindService(%s) failed", service_name);
return service_proxy->OnConnect(false /* success */);
}
QueuedRequest qr;
qr.type = Frame::kMsgBindService;
qr.request_id = request_id;
qr.service_proxy = service_proxy;
queued_requests_.emplace(request_id, std::move(qr));
}
void ClientImpl::UnbindService(ServiceID service_id) {
service_bindings_.erase(service_id);
}
RequestID ClientImpl::BeginInvoke(ServiceID service_id,
const std::string& method_name,
MethodID remote_method_id,
const ProtoMessage& method_args,
bool drop_reply,
base::WeakPtr<ServiceProxy> service_proxy,
int fd) {
std::string args_proto;
RequestID request_id = ++last_request_id_;
Frame frame;
frame.set_request_id(request_id);
Frame::InvokeMethod* req = frame.mutable_msg_invoke_method();
req->set_service_id(service_id);
req->set_method_id(remote_method_id);
req->set_drop_reply(drop_reply);
bool did_serialize = method_args.SerializeToString(&args_proto);
req->set_args_proto(args_proto);
if (!did_serialize || !SendFrame(frame, fd)) {
PERFETTO_DLOG("BeginInvoke() failed while sending the frame");
return 0;
}
if (drop_reply)
return 0;
QueuedRequest qr;
qr.type = Frame::kMsgInvokeMethod;
qr.request_id = request_id;
qr.method_name = method_name;
qr.service_proxy = std::move(service_proxy);
queued_requests_.emplace(request_id, std::move(qr));
return request_id;
}
bool ClientImpl::SendFrame(const Frame& frame, int fd) {
// Serialize the frame into protobuf, add the size header, and send it.
std::string buf = BufferedFrameDeserializer::Serialize(frame);
// TODO(primiano): this should do non-blocking I/O. But then what if the
// socket buffer is full? We might want to either drop the request or throttle
// the send and PostTask the reply later? Right now we are making Send()
// blocking as a workaround. Propagate bakpressure to the caller instead.
bool res = sock_->Send(buf.data(), buf.size(), fd,
UnixSocket::BlockingMode::kBlocking);
PERFETTO_CHECK(res || !sock_->is_connected());
return res;
}
void ClientImpl::OnConnect(UnixSocket*, bool connected) {
// Drain the BindService() calls that were queued before establishig the
// connection with the host.
for (base::WeakPtr<ServiceProxy>& service_proxy : queued_bindings_) {
if (connected) {
BindService(service_proxy);
} else if (service_proxy) {
service_proxy->OnConnect(false /* success */);
}
}
queued_bindings_.clear();
}
void ClientImpl::OnDisconnect(UnixSocket*) {
for (auto it : service_bindings_) {
base::WeakPtr<ServiceProxy>& service_proxy = it.second;
task_runner_->PostTask([service_proxy] {
if (service_proxy)
service_proxy->OnDisconnect();
});
}
service_bindings_.clear();
queued_bindings_.clear();
}
void ClientImpl::OnDataAvailable(UnixSocket*) {
size_t rsize;
do {
auto buf = frame_deserializer_.BeginReceive();
base::ScopedFile fd;
rsize = sock_->Receive(buf.data, buf.size, &fd);
if (fd) {
PERFETTO_DCHECK(!received_fd_);
int res = fcntl(*fd, F_SETFD, FD_CLOEXEC);
PERFETTO_DCHECK(res == 0);
received_fd_ = std::move(fd);
}
if (!frame_deserializer_.EndReceive(rsize)) {
// The endpoint tried to send a frame that is way too large.
return sock_->Shutdown(true); // In turn will trigger an OnDisconnect().
// TODO(fmayer): check this.
}
} while (rsize > 0);
while (std::unique_ptr<Frame> frame = frame_deserializer_.PopNextFrame())
OnFrameReceived(*frame);
}
void ClientImpl::OnFrameReceived(const Frame& frame) {
auto queued_requests_it = queued_requests_.find(frame.request_id());
if (queued_requests_it == queued_requests_.end()) {
PERFETTO_DLOG("OnFrameReceived(): got invalid request_id=%" PRIu64,
static_cast<uint64_t>(frame.request_id()));
return;
}
QueuedRequest req = std::move(queued_requests_it->second);
queued_requests_.erase(queued_requests_it);
if (req.type == Frame::kMsgBindService &&
frame.msg_case() == Frame::kMsgBindServiceReply) {
return OnBindServiceReply(std::move(req), frame.msg_bind_service_reply());
}
if (req.type == Frame::kMsgInvokeMethod &&
frame.msg_case() == Frame::kMsgInvokeMethodReply) {
return OnInvokeMethodReply(std::move(req), frame.msg_invoke_method_reply());
}
if (frame.msg_case() == Frame::kMsgRequestError) {
PERFETTO_DLOG("Host error: %s", frame.msg_request_error().error().c_str());
return;
}
PERFETTO_DLOG(
"OnFrameReceived() request msg_type=%d, received msg_type=%d in reply to "
"request_id=%" PRIu64,
req.type, frame.msg_case(), static_cast<uint64_t>(frame.request_id()));
}
void ClientImpl::OnBindServiceReply(QueuedRequest req,
const Frame::BindServiceReply& reply) {
base::WeakPtr<ServiceProxy>& service_proxy = req.service_proxy;
if (!service_proxy)
return;
const char* svc_name = service_proxy->GetDescriptor().service_name;
if (!reply.success()) {
PERFETTO_DLOG("BindService(): unknown service_name=\"%s\"", svc_name);
return service_proxy->OnConnect(false /* success */);
}
auto prev_service = service_bindings_.find(reply.service_id());
if (prev_service != service_bindings_.end() && prev_service->second.get()) {
PERFETTO_DLOG(
"BindService(): Trying to bind service \"%s\" but another service "
"named \"%s\" is already bound with the same ID.",
svc_name, prev_service->second->GetDescriptor().service_name);
return service_proxy->OnConnect(false /* success */);
}
// Build the method [name] -> [remote_id] map.
std::map<std::string, MethodID> methods;
for (const auto& method : reply.methods()) {
if (method.name().empty() || method.id() <= 0) {
PERFETTO_DLOG("OnBindServiceReply(): invalid method \"%s\" -> %" PRIu64,
method.name().c_str(), static_cast<uint64_t>(method.id()));
continue;
}
methods[method.name()] = method.id();
}
service_proxy->InitializeBinding(weak_ptr_factory_.GetWeakPtr(),
reply.service_id(), std::move(methods));
service_bindings_[reply.service_id()] = service_proxy;
service_proxy->OnConnect(true /* success */);
}
void ClientImpl::OnInvokeMethodReply(QueuedRequest req,
const Frame::InvokeMethodReply& reply) {
base::WeakPtr<ServiceProxy> service_proxy = req.service_proxy;
if (!service_proxy)
return;
std::unique_ptr<ProtoMessage> decoded_reply;
if (reply.success()) {
// TODO(fmayer): this could be optimized, stop doing method name string
// lookups.
for (const auto& method : service_proxy->GetDescriptor().methods) {
if (req.method_name == method.name) {
decoded_reply = method.reply_proto_decoder(reply.reply_proto());
break;
}
}
}
const RequestID request_id = req.request_id;
invoking_method_reply_ = true;
service_proxy->EndInvoke(request_id, std::move(decoded_reply),
reply.has_more());
invoking_method_reply_ = false;
// If this is a streaming method and future replies will be resolved, put back
// the |req| with the callback into the set of active requests.
if (reply.has_more())
queued_requests_.emplace(request_id, std::move(req));
}
ClientImpl::QueuedRequest::QueuedRequest() = default;
base::ScopedFile ClientImpl::TakeReceivedFD() {
return std::move(received_fd_);
}
} // namespace ipc
} // namespace perfetto
<commit_msg>Build fix on a C++17 mode build<commit_after>/*
* Copyright (C) 2017 The Android Open Source Project
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/
#include "src/ipc/client_impl.h"
#include <fcntl.h>
#include <inttypes.h>
#include <unistd.h>
#include <utility>
#include "perfetto/base/task_runner.h"
#include "perfetto/base/utils.h"
#include "perfetto/ipc/service_descriptor.h"
#include "perfetto/ipc/service_proxy.h"
// TODO(primiano): Add ThreadChecker everywhere.
// TODO(primiano): Add timeouts.
namespace perfetto {
namespace ipc {
// static
std::unique_ptr<Client> Client::CreateInstance(const char* socket_name,
base::TaskRunner* task_runner) {
std::unique_ptr<Client> client(new ClientImpl(socket_name, task_runner));
return client;
}
ClientImpl::ClientImpl(const char* socket_name, base::TaskRunner* task_runner)
: task_runner_(task_runner), weak_ptr_factory_(this) {
GOOGLE_PROTOBUF_VERIFY_VERSION;
sock_ = UnixSocket::Connect(socket_name, this, task_runner);
}
ClientImpl::~ClientImpl() {
// Ensure we are not destroyed in the middle of invoking a reply.
PERFETTO_DCHECK(!invoking_method_reply_);
OnDisconnect(nullptr); // The UnixSocket* ptr is not used in OnDisconnect().
}
void ClientImpl::BindService(base::WeakPtr<ServiceProxy> service_proxy) {
if (!service_proxy)
return;
if (!sock_->is_connected()) {
queued_bindings_.emplace_back(service_proxy);
return;
}
RequestID request_id = ++last_request_id_;
Frame frame;
frame.set_request_id(request_id);
Frame::BindService* req = frame.mutable_msg_bind_service();
const char* const service_name = service_proxy->GetDescriptor().service_name;
req->set_service_name(service_name);
if (!SendFrame(frame)) {
PERFETTO_DLOG("BindService(%s) failed", service_name);
return service_proxy->OnConnect(false /* success */);
}
QueuedRequest qr;
qr.type = Frame::kMsgBindService;
qr.request_id = request_id;
qr.service_proxy = service_proxy;
queued_requests_.emplace(request_id, std::move(qr));
}
void ClientImpl::UnbindService(ServiceID service_id) {
service_bindings_.erase(service_id);
}
RequestID ClientImpl::BeginInvoke(ServiceID service_id,
const std::string& method_name,
MethodID remote_method_id,
const ProtoMessage& method_args,
bool drop_reply,
base::WeakPtr<ServiceProxy> service_proxy,
int fd) {
std::string args_proto;
RequestID request_id = ++last_request_id_;
Frame frame;
frame.set_request_id(request_id);
Frame::InvokeMethod* req = frame.mutable_msg_invoke_method();
req->set_service_id(service_id);
req->set_method_id(remote_method_id);
req->set_drop_reply(drop_reply);
bool did_serialize = method_args.SerializeToString(&args_proto);
req->set_args_proto(args_proto);
if (!did_serialize || !SendFrame(frame, fd)) {
PERFETTO_DLOG("BeginInvoke() failed while sending the frame");
return 0;
}
if (drop_reply)
return 0;
QueuedRequest qr;
qr.type = Frame::kMsgInvokeMethod;
qr.request_id = request_id;
qr.method_name = method_name;
qr.service_proxy = std::move(service_proxy);
queued_requests_.emplace(request_id, std::move(qr));
return request_id;
}
bool ClientImpl::SendFrame(const Frame& frame, int fd) {
// Serialize the frame into protobuf, add the size header, and send it.
std::string buf = BufferedFrameDeserializer::Serialize(frame);
// TODO(primiano): this should do non-blocking I/O. But then what if the
// socket buffer is full? We might want to either drop the request or throttle
// the send and PostTask the reply later? Right now we are making Send()
// blocking as a workaround. Propagate bakpressure to the caller instead.
bool res = sock_->Send(buf.data(), buf.size(), fd,
UnixSocket::BlockingMode::kBlocking);
PERFETTO_CHECK(res || !sock_->is_connected());
return res;
}
void ClientImpl::OnConnect(UnixSocket*, bool connected) {
// Drain the BindService() calls that were queued before establishig the
// connection with the host.
for (base::WeakPtr<ServiceProxy>& service_proxy : queued_bindings_) {
if (connected) {
BindService(service_proxy);
} else if (service_proxy) {
service_proxy->OnConnect(false /* success */);
}
}
queued_bindings_.clear();
}
void ClientImpl::OnDisconnect(UnixSocket*) {
for (auto it : service_bindings_) {
base::WeakPtr<ServiceProxy>& service_proxy = it.second;
task_runner_->PostTask([service_proxy] {
if (service_proxy)
service_proxy->OnDisconnect();
});
}
service_bindings_.clear();
queued_bindings_.clear();
}
void ClientImpl::OnDataAvailable(UnixSocket*) {
size_t rsize;
do {
auto buf = frame_deserializer_.BeginReceive();
base::ScopedFile fd;
rsize = sock_->Receive(buf.data, buf.size, &fd);
if (fd) {
PERFETTO_DCHECK(!received_fd_);
int res = fcntl(*fd, F_SETFD, FD_CLOEXEC);
PERFETTO_DCHECK(res == 0);
received_fd_ = std::move(fd);
}
if (!frame_deserializer_.EndReceive(rsize)) {
// The endpoint tried to send a frame that is way too large.
return sock_->Shutdown(true); // In turn will trigger an OnDisconnect().
// TODO(fmayer): check this.
}
} while (rsize > 0);
while (std::unique_ptr<Frame> frame = frame_deserializer_.PopNextFrame())
OnFrameReceived(*frame);
}
void ClientImpl::OnFrameReceived(const Frame& frame) {
auto queued_requests_it = queued_requests_.find(frame.request_id());
if (queued_requests_it == queued_requests_.end()) {
PERFETTO_DLOG("OnFrameReceived(): got invalid request_id=%" PRIu64,
static_cast<uint64_t>(frame.request_id()));
return;
}
QueuedRequest req = std::move(queued_requests_it->second);
queued_requests_.erase(queued_requests_it);
if (req.type == Frame::kMsgBindService &&
frame.msg_case() == Frame::kMsgBindServiceReply) {
return OnBindServiceReply(std::move(req), frame.msg_bind_service_reply());
}
if (req.type == Frame::kMsgInvokeMethod &&
frame.msg_case() == Frame::kMsgInvokeMethodReply) {
return OnInvokeMethodReply(std::move(req), frame.msg_invoke_method_reply());
}
if (frame.msg_case() == Frame::kMsgRequestError) {
PERFETTO_DLOG("Host error: %s", frame.msg_request_error().error().c_str());
return;
}
PERFETTO_DLOG(
"OnFrameReceived() request msg_type=%d, received msg_type=%d in reply to "
"request_id=%" PRIu64,
req.type, frame.msg_case(), static_cast<uint64_t>(frame.request_id()));
}
void ClientImpl::OnBindServiceReply(QueuedRequest req,
const Frame::BindServiceReply& reply) {
base::WeakPtr<ServiceProxy>& service_proxy = req.service_proxy;
if (!service_proxy)
return;
const char* svc_name = service_proxy->GetDescriptor().service_name;
if (!reply.success()) {
PERFETTO_DLOG("BindService(): unknown service_name=\"%s\"", svc_name);
return service_proxy->OnConnect(false /* success */);
}
auto prev_service = service_bindings_.find(reply.service_id());
if (prev_service != service_bindings_.end() && prev_service->second.get()) {
PERFETTO_DLOG(
"BindService(): Trying to bind service \"%s\" but another service "
"named \"%s\" is already bound with the same ID.",
svc_name, prev_service->second->GetDescriptor().service_name);
return service_proxy->OnConnect(false /* success */);
}
// Build the method [name] -> [remote_id] map.
std::map<std::string, MethodID> methods;
for (const auto& method : reply.methods()) {
if (method.name().empty() || method.id() <= 0) {
PERFETTO_DLOG("OnBindServiceReply(): invalid method \"%s\" -> %" PRIu64,
method.name().c_str(), static_cast<uint64_t>(method.id()));
continue;
}
methods[method.name()] = method.id();
}
service_proxy->InitializeBinding(weak_ptr_factory_.GetWeakPtr(),
reply.service_id(), std::move(methods));
service_bindings_[reply.service_id()] = service_proxy;
service_proxy->OnConnect(true /* success */);
}
void ClientImpl::OnInvokeMethodReply(QueuedRequest req,
const Frame::InvokeMethodReply& reply) {
base::WeakPtr<ServiceProxy> service_proxy = req.service_proxy;
if (!service_proxy)
return;
std::unique_ptr<ProtoMessage> decoded_reply;
if (reply.success()) {
// TODO(fmayer): this could be optimized, stop doing method name string
// lookups.
for (const auto& method : service_proxy->GetDescriptor().methods) {
if (req.method_name == method.name) {
decoded_reply = method.reply_proto_decoder(reply.reply_proto());
break;
}
}
}
const RequestID request_id = req.request_id;
invoking_method_reply_ = true;
service_proxy->EndInvoke(request_id, std::move(decoded_reply),
reply.has_more());
invoking_method_reply_ = false;
// If this is a streaming method and future replies will be resolved, put back
// the |req| with the callback into the set of active requests.
if (reply.has_more())
queued_requests_.emplace(request_id, std::move(req));
}
ClientImpl::QueuedRequest::QueuedRequest() = default;
base::ScopedFile ClientImpl::TakeReceivedFD() {
return std::move(received_fd_);
}
} // namespace ipc
} // namespace perfetto
<|endoftext|> |
<commit_before>#ifndef TURBO_IPC_POSIX_PIPE_HPP
#define TURBO_IPC_POSIX_PIPE_HPP
#include <utility>
#include <vector>
namespace turbo {
namespace ipc {
namespace posix {
class pipe
{
public:
class front
{
public:
~front();
private:
friend class pipe;
typedef int handle;
front(handle front);
front(const front& other) = delete;
front& operator=(const front& other) = delete;
handle front_;
};
class back
{
public:
~back();
private:
friend class pipe;
typedef int handle;
back(handle back);
back(const back& other) = delete;
back& operator=(const back& other) = delete;
handle back_;
};
struct process_limit_reached_error {};
struct system_limit_reached_error {};
enum class option
{
non_blocking,
fork_compatible
};
pipe(std::vector<option>& options);
private:
static std::pair<front::handle, back::handle> init(std::vector<option>& options);
pipe(std::pair<front::handle, back::handle> handles);
front front_;
back back_;
};
} // namespace posix
} // namespace ipc
} // namespace turbo
#endif
<commit_msg>* made pipe non-copyable * added in getter functions for front & back<commit_after>#ifndef TURBO_IPC_POSIX_PIPE_HPP
#define TURBO_IPC_POSIX_PIPE_HPP
#include <utility>
#include <vector>
namespace turbo {
namespace ipc {
namespace posix {
class pipe
{
public:
class front
{
public:
~front();
private:
friend class pipe;
typedef int handle;
front(handle front);
front(const front& other) = delete;
front& operator=(const front& other) = delete;
handle front_;
};
class back
{
public:
~back();
private:
friend class pipe;
typedef int handle;
back(handle back);
back(const back& other) = delete;
back& operator=(const back& other) = delete;
handle back_;
};
struct process_limit_reached_error {};
struct system_limit_reached_error {};
enum class option
{
non_blocking,
fork_compatible
};
pipe(std::vector<option>& options);
inline front& get_front() { return front_; }
inline back& get_back() { return back_; }
private:
static std::pair<front::handle, back::handle> init(std::vector<option>& options);
pipe(std::pair<front::handle, back::handle> handles);
pipe(const pipe& other) = delete;
pipe& operator=(const pipe& other) = delete;
front front_;
back back_;
};
} // namespace posix
} // namespace ipc
} // namespace turbo
#endif
<|endoftext|> |
<commit_before>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <limits>
#include <algorithm>
#include "util/exception.h"
#include "kernel/metavar.h"
#include "kernel/free_vars.h"
#include "kernel/instantiate.h"
#include "kernel/occurs.h"
#include "kernel/for_each.h"
namespace lean {
void swap(substitution & s1, substitution & s2) {
swap(s1.m_subst, s2.m_subst);
std::swap(s1.m_size, s2.m_size);
}
substitution::substitution(bool beta_reduce_mv):
m_size(0),
m_beta_reduce_mv(beta_reduce_mv) {
}
bool substitution::is_assigned(name const & m) const {
return const_cast<substitution*>(this)->m_subst.splay_find(m);
}
bool substitution::is_assigned(expr const & m) const {
return is_assigned(metavar_name(m));
}
void substitution::assign(name const & m, expr const & t) {
lean_assert(!is_assigned(m));
m_subst.insert(m, t);
m_size++;
}
void substitution::assign(expr const & m, expr const & t) {
lean_assert(is_metavar(m));
lean_assert(!has_local_context(m));
assign(metavar_name(m), t);
}
expr apply_local_context(expr const & a, local_context const & lctx) {
if (lctx) {
if (is_metavar(a)) {
return mk_metavar(metavar_name(a), append(lctx, metavar_lctx(a)));
} else {
expr r = apply_local_context(a, tail(lctx));
local_entry const & e = head(lctx);
if (e.is_lift()) {
return lift_free_vars(r, e.s(), e.n());
} else {
lean_assert(e.is_inst());
return instantiate(r, e.s(), e.v());
}
}
} else {
return a;
}
}
expr substitution::get_subst(expr const & m) const {
lean_assert(is_metavar(m));
name2expr::entry const * e = const_cast<substitution*>(this)->m_subst.splay_find(metavar_name(m));
if (e) {
expr r = e->second;
if (has_assigned_metavar(r, *this)) {
r = instantiate_metavars(r, *this);
const_cast<substitution*>(this)->m_subst.insert(metavar_name(m), r);
}
local_context const & lctx = metavar_lctx(m);
if (lctx) {
r = apply_local_context(r, lctx);
if (has_assigned_metavar(r, *this))
r = instantiate_metavars(r, *this);
}
return r;
} else {
return expr();
}
}
static name g_unique_name = name::mk_internal_unique_name();
void swap(metavar_env & a, metavar_env & b) {
swap(a.m_name_generator, b.m_name_generator);
swap(a.m_substitution, b.m_substitution);
swap(a.m_metavar_types, b.m_metavar_types);
swap(a.m_metavar_contexts, b.m_metavar_contexts);
swap(a.m_metavar_justifications, b.m_metavar_justifications);
std::swap(a.m_timestamp, b.m_timestamp);
}
void metavar_env::inc_timestamp() {
if (m_timestamp == std::numeric_limits<unsigned>::max()) {
// This should not happen in real examples. We add it just to be safe.
throw exception("metavar_env timestamp overflow");
}
m_timestamp++;
}
metavar_env::metavar_env(name const & prefix):
m_name_generator(prefix),
m_timestamp(0) {
}
metavar_env::metavar_env():
metavar_env(g_unique_name) {
}
expr metavar_env::mk_metavar(context const & ctx, expr const & type) {
inc_timestamp();
name m = m_name_generator.next();
expr r = ::lean::mk_metavar(m);
if (ctx)
m_metavar_contexts.insert(m, ctx);
if (type)
m_metavar_types.insert(m, type);
return r;
}
context metavar_env::get_context(expr const & m) const {
lean_assert(is_metavar(m));
lean_assert(!has_local_context(m));
return get_context(metavar_name(m));
}
context metavar_env::get_context(name const & m) const {
auto e = const_cast<metavar_env*>(this)->m_metavar_contexts.splay_find(m);
if (e)
return e->second;
else
return context();
}
expr metavar_env::get_type(expr const & m) {
lean_assert(is_metavar(m));
expr t = get_type(metavar_name(m));
if (has_local_context(m)) {
if (is_metavar(t)) {
return update_metavar(t, append(metavar_lctx(m), metavar_lctx(t)));
} else {
return apply_local_context(t, metavar_lctx(m));
}
} else {
return t;
}
}
expr metavar_env::get_type(name const & m) {
auto e = const_cast<metavar_env*>(this)->m_metavar_types.splay_find(m);
if (e) {
return e->second;
} else {
expr t = mk_metavar(get_context(m));
m_metavar_types.insert(m, t);
return t;
}
}
bool metavar_env::has_type(name const & m) const {
auto e = const_cast<metavar_env*>(this)->m_metavar_types.splay_find(m);
return e;
}
bool metavar_env::has_type(expr const & m) const {
lean_assert(is_metavar(m));
return has_type(metavar_name(m));
}
justification metavar_env::get_justification(expr const & m) const {
lean_assert(is_metavar(m));
return get_justification(metavar_name(m));
}
justification metavar_env::get_justification(name const & m) const {
auto e = const_cast<metavar_env*>(this)->m_metavar_justifications.splay_find(m);
if (e) {
return e->second;
} else {
return justification();
}
}
bool metavar_env::is_assigned(name const & m) const {
return m_substitution.is_assigned(m);
}
bool metavar_env::is_assigned(expr const & m) const {
lean_assert(is_metavar(m));
return is_assigned(metavar_name(m));
}
void metavar_env::assign(name const & m, expr const & t, justification const & j) {
lean_assert(!is_assigned(m));
inc_timestamp();
m_substitution.assign(m, t);
if (j)
m_metavar_justifications.insert(m, j);
}
void metavar_env::assign(expr const & m, expr const & t, justification const & j) {
lean_assert(is_metavar(m));
lean_assert(!has_local_context(m));
assign(metavar_name(m), t, j);
}
struct found_unassigned{};
name metavar_env::find_unassigned_metavar() const {
name r;
try {
m_metavar_types.for_each([&](name const & m, expr const &) {
if (!m_substitution.is_assigned(m)) {
r = m;
throw found_unassigned();
}
});
} catch (found_unassigned &) {
}
return r;
}
void instantiate_metavars_proc::instantiated_metavar(expr const &) {
}
expr instantiate_metavars_proc::visit_metavar(expr const & m, context const &) {
if (is_metavar(m) && m_subst.is_assigned(m)) {
instantiated_metavar(m);
return m_subst.get_subst(m);
} else {
return m;
}
}
expr instantiate_metavars_proc::visit_app(expr const & e, context const & ctx) {
if (m_subst.beta_reduce_metavar_application() && is_metavar(arg(e, 0)) && m_subst.is_assigned(arg(e, 0))) {
instantiated_metavar(arg(e, 0));
expr new_f = m_subst.get_subst(arg(e, 0));
if (is_lambda(new_f)) {
buffer<expr> new_args;
for (unsigned i = 1; i < num_args(e); i++)
new_args.push_back(visit(arg(e, i), ctx));
return apply_beta(new_f, new_args.size(), new_args.data());
}
}
return replace_visitor::visit_app(e, ctx);
}
instantiate_metavars_proc::instantiate_metavars_proc(substitution const & s):m_subst(s) {
}
expr instantiate_metavars(expr const & e, substitution const & s) {
if (!has_metavar(e)) {
return e;
} else {
return instantiate_metavars_proc(s)(e);
}
}
struct found_assigned {};
bool has_assigned_metavar(expr const & e, substitution const & s) {
if (!has_metavar(e)) {
return false;
} else {
auto proc = [&](expr const & n, unsigned) {
if (is_metavar(n) && s.is_assigned(n))
throw found_assigned();
};
for_each_fn<decltype(proc)> visitor(proc);
try {
visitor(e);
return false;
} catch (found_assigned&) {
return true;
}
}
}
local_context add_lift(local_context const & lctx, unsigned s, unsigned n) {
if (n == 0) {
return lctx;
} else if (lctx) {
local_entry e = head(lctx);
// Simplification rule
// lift:(s1+n1):n2 lift:s1:n1 ---> lift:s1:n1+n2
if (e.is_lift() && s == e.s() + e.n()) {
return add_lift(tail(lctx), e.s(), e.n() + n);
}
}
return cons(mk_lift(s, n), lctx);
}
expr add_lift(expr const & m, unsigned s, unsigned n) {
return update_metavar(m, add_lift(metavar_lctx(m), s, n));
}
local_context add_inst(local_context const & lctx, unsigned s, expr const & v) {
if (lctx) {
local_entry e = head(lctx);
if (e.is_lift() && e.s() <= s && s < e.s() + e.n()) {
return add_lift(tail(lctx), e.s(), e.n() - 1);
}
// Simplifications such as
// inst:4 #6 lift:5:3 --> lift:4:2
// inst:3 #7 lift:4:5 --> lift:3:4
// General rule is:
// inst:(s-1) #(s+n-2) lift:s:n --> lift:s-1:n-1
if (e.is_lift() && is_var(v) && e.s() > 0 && s == e.s() - 1 && e.s() + e.n() > 2 && var_idx(v) == e.s() + e.n() - 2) {
return add_lift(tail(lctx), e.s() - 1, e.n() - 1);
}
}
return cons(mk_inst(s, v), lctx);
}
expr add_inst(expr const & m, unsigned s, expr const & v) {
return update_metavar(m, add_inst(metavar_lctx(m), s, v));
}
bool has_local_context(expr const & m) {
return metavar_lctx(m);
}
expr pop_meta_context(expr const & m) {
lean_assert(has_local_context(m));
return update_metavar(m, tail(metavar_lctx(m)));
}
/**
\brief Auxiliary exception used to sign that a metavariable was
found in an expression.
*/
struct found_metavar {};
bool has_metavar(expr const & e, expr const & m, substitution const & s) {
lean_assert(is_metavar(m));
lean_assert(!s.is_assigned(m));
auto f = [&](expr const & m2, unsigned) {
if (is_metavar(m2)) {
if (metavar_name(m) == metavar_name(m2))
throw found_metavar();
if (s.is_assigned(m2) &&
has_metavar(s.get_subst(m2), m, s))
throw found_metavar();
}
};
try {
for_each_fn<decltype(f)> proc(f);
proc(e);
return false;
} catch (found_metavar) {
return true;
}
}
}
<commit_msg>perf(kernel/metavar): add quick test that catches many cases<commit_after>/*
Copyright (c) 2013 Microsoft Corporation. All rights reserved.
Released under Apache 2.0 license as described in the file LICENSE.
Author: Leonardo de Moura
*/
#include <limits>
#include <algorithm>
#include "util/exception.h"
#include "kernel/metavar.h"
#include "kernel/free_vars.h"
#include "kernel/instantiate.h"
#include "kernel/occurs.h"
#include "kernel/for_each.h"
namespace lean {
void swap(substitution & s1, substitution & s2) {
swap(s1.m_subst, s2.m_subst);
std::swap(s1.m_size, s2.m_size);
}
substitution::substitution(bool beta_reduce_mv):
m_size(0),
m_beta_reduce_mv(beta_reduce_mv) {
}
bool substitution::is_assigned(name const & m) const {
return const_cast<substitution*>(this)->m_subst.splay_find(m);
}
bool substitution::is_assigned(expr const & m) const {
return is_assigned(metavar_name(m));
}
void substitution::assign(name const & m, expr const & t) {
lean_assert(!is_assigned(m));
m_subst.insert(m, t);
m_size++;
}
void substitution::assign(expr const & m, expr const & t) {
lean_assert(is_metavar(m));
lean_assert(!has_local_context(m));
assign(metavar_name(m), t);
}
expr apply_local_context(expr const & a, local_context const & lctx) {
if (lctx) {
if (is_metavar(a)) {
return mk_metavar(metavar_name(a), append(lctx, metavar_lctx(a)));
} else {
expr r = apply_local_context(a, tail(lctx));
local_entry const & e = head(lctx);
if (e.is_lift()) {
return lift_free_vars(r, e.s(), e.n());
} else {
lean_assert(e.is_inst());
return instantiate(r, e.s(), e.v());
}
}
} else {
return a;
}
}
expr substitution::get_subst(expr const & m) const {
lean_assert(is_metavar(m));
name2expr::entry const * e = const_cast<substitution*>(this)->m_subst.splay_find(metavar_name(m));
if (e) {
expr r = e->second;
if (has_assigned_metavar(r, *this)) {
r = instantiate_metavars(r, *this);
const_cast<substitution*>(this)->m_subst.insert(metavar_name(m), r);
}
local_context const & lctx = metavar_lctx(m);
if (lctx) {
r = apply_local_context(r, lctx);
if (has_assigned_metavar(r, *this))
r = instantiate_metavars(r, *this);
}
return r;
} else {
return expr();
}
}
static name g_unique_name = name::mk_internal_unique_name();
void swap(metavar_env & a, metavar_env & b) {
swap(a.m_name_generator, b.m_name_generator);
swap(a.m_substitution, b.m_substitution);
swap(a.m_metavar_types, b.m_metavar_types);
swap(a.m_metavar_contexts, b.m_metavar_contexts);
swap(a.m_metavar_justifications, b.m_metavar_justifications);
std::swap(a.m_timestamp, b.m_timestamp);
}
void metavar_env::inc_timestamp() {
if (m_timestamp == std::numeric_limits<unsigned>::max()) {
// This should not happen in real examples. We add it just to be safe.
throw exception("metavar_env timestamp overflow");
}
m_timestamp++;
}
metavar_env::metavar_env(name const & prefix):
m_name_generator(prefix),
m_timestamp(0) {
}
metavar_env::metavar_env():
metavar_env(g_unique_name) {
}
expr metavar_env::mk_metavar(context const & ctx, expr const & type) {
inc_timestamp();
name m = m_name_generator.next();
expr r = ::lean::mk_metavar(m);
if (ctx)
m_metavar_contexts.insert(m, ctx);
if (type)
m_metavar_types.insert(m, type);
return r;
}
context metavar_env::get_context(expr const & m) const {
lean_assert(is_metavar(m));
lean_assert(!has_local_context(m));
return get_context(metavar_name(m));
}
context metavar_env::get_context(name const & m) const {
auto e = const_cast<metavar_env*>(this)->m_metavar_contexts.splay_find(m);
if (e)
return e->second;
else
return context();
}
expr metavar_env::get_type(expr const & m) {
lean_assert(is_metavar(m));
expr t = get_type(metavar_name(m));
if (has_local_context(m)) {
if (is_metavar(t)) {
return update_metavar(t, append(metavar_lctx(m), metavar_lctx(t)));
} else {
return apply_local_context(t, metavar_lctx(m));
}
} else {
return t;
}
}
expr metavar_env::get_type(name const & m) {
auto e = const_cast<metavar_env*>(this)->m_metavar_types.splay_find(m);
if (e) {
return e->second;
} else {
expr t = mk_metavar(get_context(m));
m_metavar_types.insert(m, t);
return t;
}
}
bool metavar_env::has_type(name const & m) const {
auto e = const_cast<metavar_env*>(this)->m_metavar_types.splay_find(m);
return e;
}
bool metavar_env::has_type(expr const & m) const {
lean_assert(is_metavar(m));
return has_type(metavar_name(m));
}
justification metavar_env::get_justification(expr const & m) const {
lean_assert(is_metavar(m));
return get_justification(metavar_name(m));
}
justification metavar_env::get_justification(name const & m) const {
auto e = const_cast<metavar_env*>(this)->m_metavar_justifications.splay_find(m);
if (e) {
return e->second;
} else {
return justification();
}
}
bool metavar_env::is_assigned(name const & m) const {
return m_substitution.is_assigned(m);
}
bool metavar_env::is_assigned(expr const & m) const {
lean_assert(is_metavar(m));
return is_assigned(metavar_name(m));
}
void metavar_env::assign(name const & m, expr const & t, justification const & j) {
lean_assert(!is_assigned(m));
inc_timestamp();
m_substitution.assign(m, t);
if (j)
m_metavar_justifications.insert(m, j);
}
void metavar_env::assign(expr const & m, expr const & t, justification const & j) {
lean_assert(is_metavar(m));
lean_assert(!has_local_context(m));
assign(metavar_name(m), t, j);
}
struct found_unassigned{};
name metavar_env::find_unassigned_metavar() const {
name r;
try {
m_metavar_types.for_each([&](name const & m, expr const &) {
if (!m_substitution.is_assigned(m)) {
r = m;
throw found_unassigned();
}
});
} catch (found_unassigned &) {
}
return r;
}
void instantiate_metavars_proc::instantiated_metavar(expr const &) {
}
expr instantiate_metavars_proc::visit_metavar(expr const & m, context const &) {
if (is_metavar(m) && m_subst.is_assigned(m)) {
instantiated_metavar(m);
return m_subst.get_subst(m);
} else {
return m;
}
}
expr instantiate_metavars_proc::visit_app(expr const & e, context const & ctx) {
if (m_subst.beta_reduce_metavar_application() && is_metavar(arg(e, 0)) && m_subst.is_assigned(arg(e, 0))) {
instantiated_metavar(arg(e, 0));
expr new_f = m_subst.get_subst(arg(e, 0));
if (is_lambda(new_f)) {
buffer<expr> new_args;
for (unsigned i = 1; i < num_args(e); i++)
new_args.push_back(visit(arg(e, i), ctx));
return apply_beta(new_f, new_args.size(), new_args.data());
}
}
return replace_visitor::visit_app(e, ctx);
}
instantiate_metavars_proc::instantiate_metavars_proc(substitution const & s):m_subst(s) {
}
expr instantiate_metavars(expr const & e, substitution const & s) {
if (!has_metavar(e)) {
return e;
} else {
return instantiate_metavars_proc(s)(e);
}
}
struct found_assigned {};
bool has_assigned_metavar(expr const & e, substitution const & s) {
if (!has_metavar(e)) {
return false;
} else {
auto proc = [&](expr const & n, unsigned) {
if (is_metavar(n) && s.is_assigned(n))
throw found_assigned();
};
for_each_fn<decltype(proc)> visitor(proc);
try {
visitor(e);
return false;
} catch (found_assigned&) {
return true;
}
}
}
local_context add_lift(local_context const & lctx, unsigned s, unsigned n) {
if (n == 0) {
return lctx;
} else if (lctx) {
local_entry e = head(lctx);
// Simplification rule
// lift:(s1+n1):n2 lift:s1:n1 ---> lift:s1:n1+n2
if (e.is_lift() && s == e.s() + e.n()) {
return add_lift(tail(lctx), e.s(), e.n() + n);
}
}
return cons(mk_lift(s, n), lctx);
}
expr add_lift(expr const & m, unsigned s, unsigned n) {
return update_metavar(m, add_lift(metavar_lctx(m), s, n));
}
local_context add_inst(local_context const & lctx, unsigned s, expr const & v) {
if (lctx) {
local_entry e = head(lctx);
if (e.is_lift() && e.s() <= s && s < e.s() + e.n()) {
return add_lift(tail(lctx), e.s(), e.n() - 1);
}
// Simplifications such as
// inst:4 #6 lift:5:3 --> lift:4:2
// inst:3 #7 lift:4:5 --> lift:3:4
// General rule is:
// inst:(s-1) #(s+n-2) lift:s:n --> lift:s-1:n-1
if (e.is_lift() && is_var(v) && e.s() > 0 && s == e.s() - 1 && e.s() + e.n() > 2 && var_idx(v) == e.s() + e.n() - 2) {
return add_lift(tail(lctx), e.s() - 1, e.n() - 1);
}
}
return cons(mk_inst(s, v), lctx);
}
expr add_inst(expr const & m, unsigned s, expr const & v) {
return update_metavar(m, add_inst(metavar_lctx(m), s, v));
}
bool has_local_context(expr const & m) {
return metavar_lctx(m);
}
expr pop_meta_context(expr const & m) {
lean_assert(has_local_context(m));
return update_metavar(m, tail(metavar_lctx(m)));
}
/**
\brief Auxiliary exception used to sign that a metavariable was
found in an expression.
*/
struct found_metavar {};
bool has_metavar(expr const & e, expr const & m, substitution const & s) {
if (has_metavar(e)) {
lean_assert(is_metavar(m));
lean_assert(!s.is_assigned(m));
auto f = [&](expr const & m2, unsigned) {
if (is_metavar(m2)) {
if (metavar_name(m) == metavar_name(m2))
throw found_metavar();
if (s.is_assigned(m2) &&
has_metavar(s.get_subst(m2), m, s))
throw found_metavar();
}
};
try {
for_each_fn<decltype(f)> proc(f);
proc(e);
return false;
} catch (found_metavar) {
return true;
}
} else {
return false;
}
}
}
<|endoftext|> |
<commit_before>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <profile>
#include <common>
#include <hw/pit.hpp>
#include <kernel/elf.hpp>
#include <kernel/irq_manager.hpp>
#include <utility/fixedvec.hpp>
#include <unordered_map>
#include <cassert>
#include <algorithm>
#define BUFFER_COUNT 1024
extern "C" {
void parasite_interrupt_handler();
void profiler_stack_sampler(void*);
void gather_stack_sampling();
}
extern char _irq_cb_return_location;
typedef uint32_t func_sample;
struct Sampler
{
fixedvector<uintptr_t, BUFFER_COUNT>* samplerq;
fixedvector<uintptr_t, BUFFER_COUNT>* transferq;
std::unordered_map<uintptr_t, func_sample> dict;
func_sample total = 0;
int lockless;
bool discard; // discard results as long as true
Sampler() {
// make room for these only when requested
#define blargh(T) std::remove_pointer<decltype(T)>::type;
samplerq = new blargh(samplerq);
transferq = new blargh(transferq);
total = 0;
lockless = 0;
discard = false;
}
void begin() {
// gather samples repeatedly over small periods
using namespace std::chrono;
static const milliseconds GATHER_PERIOD_MS = 150ms;
hw::PIT::instance().on_repeated_timeout(
GATHER_PERIOD_MS, gather_stack_sampling);
}
void add(void* ra)
{
// need free space to take more samples
if (samplerq->free_capacity())
samplerq->add((uintptr_t) ra);
// return when its not our turn
if (lockless) return;
// transfer all the built up samplings
transferq->copy(samplerq->first(), samplerq->size());
samplerq->clear();
lockless = 1;
}
};
Sampler& get() {
static Sampler sampler;
return sampler;
}
void StackSampler::begin()
{
// install interrupt handler
IRQ_manager::cpu(0).set_irq_handler(0, parasite_interrupt_handler);
// start taking samples using PIT interrupts
get().begin();
}
void profiler_stack_sampler(void* esp)
{
void* ra = esp; //__builtin_return_address(1);
// maybe qemu, maybe some bullshit we don't care about
if (UNLIKELY(ra == nullptr || get().discard)) return;
// ignore event loop
if (ra == &_irq_cb_return_location) return;
// add address to sampler queue
get().add(ra);
}
void gather_stack_sampling()
{
// gather results on our turn only
if (get().lockless == 1)
{
for (auto* addr = get().transferq->first(); addr < get().transferq->end(); addr++)
{
// convert return address to function entry address
uintptr_t resolved = Elf::resolve_addr(*addr);
// insert into unordered map
auto it = get().dict.find(resolved);
if (it != get().dict.end()) {
it->second++;
}
else {
// add to dictionary
get().dict.emplace(
std::piecewise_construct,
std::forward_as_tuple(resolved),
std::forward_as_tuple(1));
}
}
get().total += get().transferq->size();
get().lockless = 0;
}
}
void print_heap_info()
{
static intptr_t last = 0;
// show information on heap status, to discover leaks etc.
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
intptr_t heap_size = heap_end - heap_begin;
last = heap_size - last;
printf("[!] Heap information:\n");
printf("[!] begin %#x size %#x (%u Kb)\n", heap_begin, heap_size, heap_size / 1024);
printf("[!] end %#x diff %#x (%d Kb)\n", heap_end, last, last / 1024);
last = (int32_t) heap_size;
}
int StackSampler::samples_total()
{
return get().total;
}
std::vector<Sample> StackSampler::results(int N)
{
using sample_pair = std::pair<uintptr_t, func_sample>;
std::vector<sample_pair> vec(get().dict.begin(), get().dict.end());
// sort by count
std::sort(vec.begin(), vec.end(),
[] (const sample_pair& sample1, const sample_pair& sample2) -> int {
return sample1.second > sample2.second;
});
std::vector<Sample> res;
N = (N > (int)vec.size()) ? vec.size() : N;
if (N <= 0) return res;
for (auto& sa : vec)
{
// resolve the addr
auto func = Elf::resolve_symbol(sa.first);
res.push_back(Sample {sa.second, (void*) func.addr, func.name});
if (N-- == 0) break;
}
return res;
}
void StackSampler::set_mask(bool mask)
{
get().discard = mask;
}
void __panic_failure(char const* where, size_t id)
{
printf("\n[FAILURE] %s, id=%u\n", where, id);
print_heap_info();
while (true)
asm volatile("cli; hlt");
}
void __validate_backtrace(char const* where, size_t id)
{
func_offset func;
func = Elf::resolve_symbol((void*) &__validate_backtrace);
if (func.name != "__validate_backtrace")
__panic_failure(where, id);
func = Elf::resolve_symbol((void*) &StackSampler::set_mask);
if (func.name != "StackSampler::set_mask(bool)")
__panic_failure(where, id);
}
<commit_msg>profile: Fix one result too many, tweak heap info output<commit_after>// This file is a part of the IncludeOS unikernel - www.includeos.org
//
// Copyright 2015 Oslo and Akershus University College of Applied Sciences
// and Alfred Bratterud
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <profile>
#include <common>
#include <hw/pit.hpp>
#include <kernel/elf.hpp>
#include <kernel/irq_manager.hpp>
#include <utility/fixedvec.hpp>
#include <unordered_map>
#include <cassert>
#include <algorithm>
#define BUFFER_COUNT 1024
extern "C" {
void parasite_interrupt_handler();
void profiler_stack_sampler(void*);
void gather_stack_sampling();
}
extern char _irq_cb_return_location;
typedef uint32_t func_sample;
struct Sampler
{
fixedvector<uintptr_t, BUFFER_COUNT>* samplerq;
fixedvector<uintptr_t, BUFFER_COUNT>* transferq;
std::unordered_map<uintptr_t, func_sample> dict;
func_sample total = 0;
int lockless;
bool discard; // discard results as long as true
Sampler() {
// make room for these only when requested
#define blargh(T) std::remove_pointer<decltype(T)>::type;
samplerq = new blargh(samplerq);
transferq = new blargh(transferq);
total = 0;
lockless = 0;
discard = false;
}
void begin() {
// gather samples repeatedly over small periods
using namespace std::chrono;
static const milliseconds GATHER_PERIOD_MS = 150ms;
hw::PIT::instance().on_repeated_timeout(
GATHER_PERIOD_MS, gather_stack_sampling);
}
void add(void* ra)
{
// need free space to take more samples
if (samplerq->free_capacity())
samplerq->add((uintptr_t) ra);
// return when its not our turn
if (lockless) return;
// transfer all the built up samplings
transferq->copy(samplerq->first(), samplerq->size());
samplerq->clear();
lockless = 1;
}
};
Sampler& get() {
static Sampler sampler;
return sampler;
}
void StackSampler::begin()
{
// install interrupt handler
IRQ_manager::cpu(0).set_irq_handler(0, parasite_interrupt_handler);
// start taking samples using PIT interrupts
get().begin();
}
void profiler_stack_sampler(void* esp)
{
void* ra = esp; //__builtin_return_address(1);
// maybe qemu, maybe some bullshit we don't care about
if (UNLIKELY(ra == nullptr || get().discard)) return;
// ignore event loop
if (ra == &_irq_cb_return_location) return;
// add address to sampler queue
get().add(ra);
}
void gather_stack_sampling()
{
// gather results on our turn only
if (get().lockless == 1)
{
for (auto* addr = get().transferq->first(); addr < get().transferq->end(); addr++)
{
// convert return address to function entry address
uintptr_t resolved = Elf::resolve_addr(*addr);
// insert into unordered map
auto it = get().dict.find(resolved);
if (it != get().dict.end()) {
it->second++;
}
else {
// add to dictionary
get().dict.emplace(
std::piecewise_construct,
std::forward_as_tuple(resolved),
std::forward_as_tuple(1));
}
}
get().total += get().transferq->size();
get().lockless = 0;
}
}
void print_heap_info()
{
static intptr_t last = 0;
// show information on heap status, to discover leaks etc.
extern uintptr_t heap_begin;
extern uintptr_t heap_end;
intptr_t heap_size = heap_end - heap_begin;
last = heap_size - last;
printf("Heap begin %#x size %u Kb\n", heap_begin, heap_size / 1024);
printf("Heap end %#x diff %u (%d Kb)\n", heap_end, last, last / 1024);
last = (int32_t) heap_size;
}
int StackSampler::samples_total()
{
return get().total;
}
std::vector<Sample> StackSampler::results(int N)
{
using sample_pair = std::pair<uintptr_t, func_sample>;
std::vector<sample_pair> vec(get().dict.begin(), get().dict.end());
// sort by count
std::sort(vec.begin(), vec.end(),
[] (const sample_pair& sample1, const sample_pair& sample2) -> int {
return sample1.second > sample2.second;
});
std::vector<Sample> res;
N = (N > (int)vec.size()) ? vec.size() : N;
if (N <= 0) return res;
for (auto& sa : vec)
{
// resolve the addr
auto func = Elf::resolve_symbol(sa.first);
res.push_back(Sample {sa.second, (void*) func.addr, func.name});
if (--N == 0) break;
}
return res;
}
void StackSampler::set_mask(bool mask)
{
get().discard = mask;
}
void __panic_failure(char const* where, size_t id)
{
printf("\n[FAILURE] %s, id=%u\n", where, id);
print_heap_info();
while (true)
asm volatile("cli; hlt");
}
void __validate_backtrace(char const* where, size_t id)
{
func_offset func;
func = Elf::resolve_symbol((void*) &__validate_backtrace);
if (func.name != "__validate_backtrace")
__panic_failure(where, id);
func = Elf::resolve_symbol((void*) &StackSampler::set_mask);
if (func.name != "StackSampler::set_mask(bool)")
__panic_failure(where, id);
}
<|endoftext|> |
<commit_before>#include <annis/api/search.h>
using namespace annis;
using namespace annis::api;
Search::Search(std::string databaseDir)
: databaseDir(databaseDir)
{
cache = std::unique_ptr<DBCache>(new DBCache());
}
Search::~Search() {}
long long Search::count(std::vector<std::string> corpora, std::string queryAsJSON)
{
long long result = 0;
// sort corpora by their name
std::sort(corpora.begin(), corpora.end());
for(const std::string& c : corpora)
{
std::weak_ptr<DB> dbWeakPtr = cache->get(databaseDir + "/" + c, true);
if(std::shared_ptr<DB> db = dbWeakPtr.lock())
{
std::stringstream ss;
ss << queryAsJSON;
std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss);
while(q->next())
{
result++;
}
}
}
return result;
}
Search::CountResult Search::countExtra(std::vector<std::string> corpora, std::string queryAsJSON)
{
CountResult result = {0,0};
std::set<std::uint32_t> documents;
// sort corpora by their name
std::sort(corpora.begin(), corpora.end());
for(const std::string& c : corpora)
{
std::weak_ptr<DB> dbWeakPtr = cache->get(databaseDir + "/" + c, true);
if(std::shared_ptr<DB> db = dbWeakPtr.lock())
{
std::stringstream ss;
ss << queryAsJSON;
std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss);
while(q->next())
{
result.matchCount++;
const std::vector<Match>& m = q->getCurrent();
if(!m.empty())
{
const Match& n = m[0];
std::pair<bool, Annotation> anno = db->nodeAnnos.getNodeAnnotation(n.node, annis_ns, "document");
if(anno.first)
{
documents.insert(anno.second.val);
}
}
}
}
}
result.documentCount = documents.size();
return result;
}
std::vector<std::string> Search::find(std::vector<std::string> corpora, std::string queryAsJSON, long long offset, long long limit)
{
std::vector<std::string> result;
long long counter = 0;
// sort corpora by their name
std::sort(corpora.begin(), corpora.end());
for(const std::string& c : corpora)
{
std::weak_ptr<DB> dbWeakPtr = cache->get(databaseDir + "/" + c, false);
if(std::shared_ptr<DB> db = dbWeakPtr.lock())
{
std::stringstream ss;
ss << queryAsJSON;
std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss);
while(counter < (offset + limit) && q->next())
{
if(counter >= offset)
{
const std::vector<Match>& m = q->getCurrent();
std::stringstream matchDesc;
for(size_t i = 0; i < m.size(); i++)
{
const Match& n = m[i];
if(n.anno.ns != 0 && n.anno.name != 0
&& n.anno.ns != db->getNamespaceStringID() && n.anno.name != db->getNodeNameStringID())
{
matchDesc << db->strings.str(n.anno.ns)
<< "::" << db->strings.str(n.anno.name)
<< "::";
}
matchDesc << "salt://" << c << "/";
matchDesc << db->getNodeDocument(n.node) << "/#" << db->getNodeName(n.node);
if(i < m.size()-1)
{
matchDesc << " ";
}
}
result.push_back(matchDesc.str());
} // end if result in offset-limit range
counter++;
}
}
}
return result;
}
<commit_msg>Salt IDs start with "salt:/" not "salt://"<commit_after>#include <annis/api/search.h>
using namespace annis;
using namespace annis::api;
Search::Search(std::string databaseDir)
: databaseDir(databaseDir)
{
cache = std::unique_ptr<DBCache>(new DBCache());
}
Search::~Search() {}
long long Search::count(std::vector<std::string> corpora, std::string queryAsJSON)
{
long long result = 0;
// sort corpora by their name
std::sort(corpora.begin(), corpora.end());
for(const std::string& c : corpora)
{
std::weak_ptr<DB> dbWeakPtr = cache->get(databaseDir + "/" + c, true);
if(std::shared_ptr<DB> db = dbWeakPtr.lock())
{
std::stringstream ss;
ss << queryAsJSON;
std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss);
while(q->next())
{
result++;
}
}
}
return result;
}
Search::CountResult Search::countExtra(std::vector<std::string> corpora, std::string queryAsJSON)
{
CountResult result = {0,0};
std::set<std::uint32_t> documents;
// sort corpora by their name
std::sort(corpora.begin(), corpora.end());
for(const std::string& c : corpora)
{
std::weak_ptr<DB> dbWeakPtr = cache->get(databaseDir + "/" + c, true);
if(std::shared_ptr<DB> db = dbWeakPtr.lock())
{
std::stringstream ss;
ss << queryAsJSON;
std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss);
while(q->next())
{
result.matchCount++;
const std::vector<Match>& m = q->getCurrent();
if(!m.empty())
{
const Match& n = m[0];
std::pair<bool, Annotation> anno = db->nodeAnnos.getNodeAnnotation(n.node, annis_ns, "document");
if(anno.first)
{
documents.insert(anno.second.val);
}
}
}
}
}
result.documentCount = documents.size();
return result;
}
std::vector<std::string> Search::find(std::vector<std::string> corpora, std::string queryAsJSON, long long offset, long long limit)
{
std::vector<std::string> result;
long long counter = 0;
// sort corpora by their name
std::sort(corpora.begin(), corpora.end());
for(const std::string& c : corpora)
{
std::weak_ptr<DB> dbWeakPtr = cache->get(databaseDir + "/" + c, false);
if(std::shared_ptr<DB> db = dbWeakPtr.lock())
{
std::stringstream ss;
ss << queryAsJSON;
std::shared_ptr<annis::Query> q = annis::JSONQueryParser::parse(*db, db->edges, ss);
while(counter < (offset + limit) && q->next())
{
if(counter >= offset)
{
const std::vector<Match>& m = q->getCurrent();
std::stringstream matchDesc;
for(size_t i = 0; i < m.size(); i++)
{
const Match& n = m[i];
if(n.anno.ns != 0 && n.anno.name != 0
&& n.anno.ns != db->getNamespaceStringID() && n.anno.name != db->getNodeNameStringID())
{
matchDesc << db->strings.str(n.anno.ns)
<< "::" << db->strings.str(n.anno.name)
<< "::";
}
matchDesc << "salt:/" << c << "/";
matchDesc << db->getNodeDocument(n.node) << "/#" << db->getNodeName(n.node);
if(i < m.size()-1)
{
matchDesc << " ";
}
}
result.push_back(matchDesc.str());
} // end if result in offset-limit range
counter++;
}
}
}
return result;
}
<|endoftext|> |
<commit_before>/*
Copyright (C) 2012 Rohan Garg <rohangarg@kubuntu.org>
This library 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 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "contactnotify.h"
#include <KDebug>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Contact>
#include <KNotification>
#include <KAboutData>
#include <KTp/presence.h>
ContactNotify::ContactNotify(const Tp::AccountManagerPtr accountMgr, QObject *parent) :
QObject(parent)
{
m_accountManager = accountMgr;
if (!m_accountManager) {
return;
}
QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts();
Q_FOREACH(const Tp::AccountPtr &account, accounts) {
// Accounts that are already online should be handled immediately
if (account.data()->isOnline()) {
kDebug() << "Account" << account.data()->normalizedName() << "is already Online";
accountIsOnline(account.data());
} else {
// Handle accounts coming online
connect(account.data(), SIGNAL(onlinenessChanged(bool)),
SLOT(accountCameOnline(bool)));
}
}
}
void ContactNotify::accountCameOnline(bool online)
{
if (online) {
const Tp::Account *account = (Tp::Account *)QObject::sender();
if (account) {
kDebug() << "Account" << account->normalizedName() << "came Online";
accountIsOnline(account);
}
}
}
void ContactNotify::accountIsOnline(const Tp::Account *account)
{
Q_ASSERT(account);
m_connection = account->connection();
if(m_connection.data()) {
connect(m_connection.data(), SIGNAL(statusChanged(Tp::ConnectionStatus)),
SLOT(onStatusChanged(Tp::ConnectionStatus)));
}
}
void ContactNotify::onStatusChanged(const Tp::ConnectionStatus status)
{
if (status == Tp::ConnectionStatusConnected) {
Tp::ContactManagerPtr contactManager = m_connection.data()->contactManager();
Tp::Contacts contacts = contactManager.data()->allKnownContacts();
// This is going to be *slow* when the user has alot of contacts
// Optimize it later on
Q_FOREACH (const Tp::ContactPtr &contact, contacts) {
connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)),
SLOT(contactPresenceChanged(Tp::Presence)));
}
}
}
void ContactNotify::contactPresenceChanged(const Tp::Presence presence)
{
KTp::Presence ktpPresence(presence);
Tp::Contact *contact = (Tp::Contact *)QObject::sender();
sendNotification(i18nc("%1 is the contact name, %2 is the presence message",
"%1 is now %2",
contact->alias(),
ktpPresence.displayString()),
ktpPresence.icon(),
contact);
}
void ContactNotify::sendNotification(QString text, KIcon icon, const Tp::Contact *contact)
{
//The pointer is automatically deleted when the event is closed
KNotification *notification;
notification = new KNotification(QLatin1String("contactInfo"), KNotification::CloseOnTimeout);
KAboutData aboutData("ktelepathy",0,KLocalizedString(),0);
notification->setComponentData(KComponentData(aboutData));
notification->setPixmap(icon.pixmap(48));
notification->setText(text);
notification->addContext(QLatin1String("contact"), contact->id());
notification->sendEvent();
}
<commit_msg>Minor styling fixup<commit_after>/*
Copyright (C) 2012 Rohan Garg <rohangarg@kubuntu.org>
This library 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 2.1 of the License, or (at your option) any later version.
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., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301 USA
*/
#include "contactnotify.h"
#include <KDebug>
#include <TelepathyQt/ContactManager>
#include <TelepathyQt/AccountManager>
#include <TelepathyQt/Contact>
#include <KNotification>
#include <KAboutData>
#include <KTp/presence.h>
ContactNotify::ContactNotify(const Tp::AccountManagerPtr accountMgr, QObject *parent) :
QObject(parent)
{
m_accountManager = accountMgr;
if (!m_accountManager) {
return;
}
QList<Tp::AccountPtr> accounts = m_accountManager->allAccounts();
Q_FOREACH(const Tp::AccountPtr &account, accounts) {
// Accounts that are already online should be handled immediately
if (account.data()->isOnline()) {
kDebug() << "Account" << account.data()->normalizedName() << "is already Online";
accountIsOnline(account.data());
} else {
// Handle accounts coming online
connect(account.data(), SIGNAL(onlinenessChanged(bool)),
SLOT(accountCameOnline(bool)));
}
}
}
void ContactNotify::accountCameOnline(bool online)
{
if (online) {
const Tp::Account *account = (Tp::Account *)QObject::sender();
if (account) {
kDebug() << "Account" << account->normalizedName() << "came Online";
accountIsOnline(account);
}
}
}
void ContactNotify::accountIsOnline(const Tp::Account *account)
{
Q_ASSERT(account);
m_connection = account->connection();
if (m_connection.data()) {
connect(m_connection.data(), SIGNAL(statusChanged(Tp::ConnectionStatus)),
SLOT(onStatusChanged(Tp::ConnectionStatus)));
}
}
void ContactNotify::onStatusChanged(const Tp::ConnectionStatus status)
{
if (status == Tp::ConnectionStatusConnected) {
Tp::ContactManagerPtr contactManager = m_connection.data()->contactManager();
Tp::Contacts contacts = contactManager.data()->allKnownContacts();
// This is going to be *slow* when the user has alot of contacts
// Optimize it later on
Q_FOREACH (const Tp::ContactPtr &contact, contacts) {
connect(contact.data(), SIGNAL(presenceChanged(Tp::Presence)),
SLOT(contactPresenceChanged(Tp::Presence)));
}
}
}
void ContactNotify::contactPresenceChanged(const Tp::Presence presence)
{
KTp::Presence ktpPresence(presence);
Tp::Contact *contact = (Tp::Contact *)QObject::sender();
sendNotification(i18nc("%1 is the contact name, %2 is the presence message",
"%1 is now %2",
contact->alias(),
ktpPresence.displayString()),
ktpPresence.icon(),
contact);
}
void ContactNotify::sendNotification(QString text, KIcon icon, const Tp::Contact *contact)
{
//The pointer is automatically deleted when the event is closed
KNotification *notification;
notification = new KNotification(QLatin1String("contactInfo"), KNotification::CloseOnTimeout);
KAboutData aboutData("ktelepathy",0,KLocalizedString(),0);
notification->setComponentData(KComponentData(aboutData));
notification->setPixmap(icon.pixmap(48));
notification->setText(text);
notification->addContext(QLatin1String("contact"), contact->id());
notification->sendEvent();
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include <string>
#pragma warning(push, 0)
#include "HTTPHeaderMap.h"
#include "ResourceHandle.h"
#include "ResourceHandleClient.h"
#include "String.h"
#pragma warning(pop)
#undef LOG
#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/glue/multipart_response_delegate.h"
#include "webkit/glue/glue_util.h"
#include "net/base/net_util.h"
MultipartResponseDelegate::MultipartResponseDelegate(
WebCore::ResourceHandleClient* client,
WebCore::ResourceHandle* job,
const WebCore::ResourceResponse& response,
const std::string& boundary)
: client_(client),
job_(job),
original_response_(response),
boundary_("--"),
first_received_data_(true),
processing_headers_(false),
stop_sending_(false) {
boundary_.append(boundary);
}
void MultipartResponseDelegate::OnReceivedData(const char* data, int data_len) {
// stop_sending_ means that we've already received the final boundary token.
// The server should stop sending us data at this point, but if it does, we
// just throw it away.
if (stop_sending_)
return;
// TODO(tc): Figure out what to use for length_received. Maybe we can just
// pass the value on from our caller. See note in
// resource_handle_win.cc:ResourceHandleInternal::OnReceivedData.
int length_received = -1;
data_.append(data, data_len);
if (first_received_data_) {
// Some servers don't send a boundary token before the first chunk of
// data. We handle this case anyway (Gecko does too).
first_received_data_ = false;
// Eat leading \r\n
int pos = PushOverLine(data_, 0);
if (pos)
data_ = data_.substr(pos);
if (data_.length() < boundary_.length() + 2) {
// We don't have enough data yet to make a boundary token. Just wait
// until the next chunk of data arrives.
first_received_data_ = true;
return;
}
if (data_.substr(0, boundary_.length()) != boundary_) {
data_ = boundary_ + "\n" + data_;
}
}
DCHECK(!first_received_data_);
// Headers
if (processing_headers_) {
// Eat leading \r\n
int pos = PushOverLine(data_, 0);
if (pos)
data_ = data_.substr(pos);
if (ParseHeaders()) {
// Successfully parsed headers.
processing_headers_ = false;
} else {
// Get more data before trying again.
return;
}
}
DCHECK(!processing_headers_);
int token_line_feed = 1;
size_t boundary_pos;
while ((boundary_pos = FindBoundary()) != std::string::npos) {
if (boundary_pos > 0) {
// Send the last data chunk.
client_->didReceiveData(job_, data_.substr(0, boundary_pos).data(),
static_cast<int>(boundary_pos), length_received);
}
size_t boundary_end_pos = boundary_pos + boundary_.length();
if (boundary_end_pos < data_.length() && '-' == data_[boundary_end_pos]) {
// This was the last boundary so we can stop processing.
stop_sending_ = true;
data_.clear();
return;
}
// We can now throw out data up through the boundary
int offset = PushOverLine(data_, boundary_end_pos);
data_ = data_.substr(boundary_end_pos + offset);
// Ok, back to parsing headers
if (!ParseHeaders()) {
processing_headers_ = true;
break;
}
}
}
void MultipartResponseDelegate::OnCompletedRequest() {
// If we have any pending data and we're not in a header, go ahead and send
// it to WebCore.
if (!processing_headers_ && !data_.empty()) {
// TODO(tc): Figure out what to use for length_received. Maybe we can just
// pass the value on from our caller.
int length_received = -1;
client_->didReceiveData(job_, data_.data(),
static_cast<int>(data_.length()), length_received);
}
}
int MultipartResponseDelegate::PushOverLine(const std::string& data, size_t pos) {
int offset = 0;
if (pos < data.length() && (data[pos] == '\r' || data[pos] == '\n')) {
++offset;
if (pos + 1 < data.length() && data[pos + 1] == '\n')
++offset;
}
return offset;
}
bool MultipartResponseDelegate::ParseHeaders() {
int line_feed_increment = 1;
// Grab the headers being liberal about line endings.
size_t line_start_pos = 0;
size_t line_end_pos = data_.find('\n');
while (line_end_pos != std::string::npos) {
// Handle CRLF
if (line_end_pos > line_start_pos && data_[line_end_pos - 1] == '\r') {
line_feed_increment = 2;
--line_end_pos;
} else {
line_feed_increment = 1;
}
if (line_start_pos == line_end_pos) {
// A blank line, end of headers
line_end_pos += line_feed_increment;
break;
}
// Find the next header line.
line_start_pos = line_end_pos + line_feed_increment;
line_end_pos = data_.find('\n', line_start_pos);
}
// Truncated in the middle of a header, stop parsing.
if (line_end_pos == std::string::npos)
return false;
// Eat headers
std::string headers("\n");
headers.append(data_.substr(0, line_end_pos));
data_ = data_.substr(line_end_pos);
// Create a ResourceResponse based on the original set of headers + the
// replacement headers. We only replace the same few headers that gecko
// does. See netwerk/streamconv/converters/nsMultiMixedConv.cpp.
std::string mime_type = net::GetSpecificHeader(headers, "content-type");
std::string charset = net::GetHeaderParamValue(mime_type, "charset");
WebCore::ResourceResponse response(original_response_.url(),
webkit_glue::StdStringToString(mime_type.c_str()),
-1,
charset.c_str(),
WebCore::String());
const WebCore::HTTPHeaderMap& orig_headers =
original_response_.httpHeaderFields();
for (WebCore::HTTPHeaderMap::const_iterator it = orig_headers.begin();
it != orig_headers.end(); ++it) {
if (!(equalIgnoringCase("content-type", it->first) ||
equalIgnoringCase("content-length", it->first) ||
equalIgnoringCase("content-disposition", it->first) ||
equalIgnoringCase("content-range", it->first) ||
equalIgnoringCase("range", it->first) ||
equalIgnoringCase("set-cookie", it->first))) {
response.setHTTPHeaderField(it->first, it->second);
}
}
static const char* replace_headers[] = {
"Content-Type",
"Content-Length",
"Content-Disposition",
"Content-Range",
"Range",
"Set-Cookie"
};
for (int i = 0; i < arraysize(replace_headers); ++i) {
std::string name(replace_headers[i]);
std::string value = net::GetSpecificHeader(headers, name);
if (!value.empty()) {
response.setHTTPHeaderField(webkit_glue::StdStringToString(name.c_str()),
webkit_glue::StdStringToString(value.c_str()));
}
}
// Send the response!
client_->didReceiveResponse(job_, response);
return true;
}
// Boundaries are supposed to be preceeded with --, but it looks like gecko
// doesn't require the dashes to exist. See nsMultiMixedConv::FindToken.
size_t MultipartResponseDelegate::FindBoundary() {
size_t boundary_pos = data_.find(boundary_);
if (boundary_pos != std::string::npos) {
// Back up over -- for backwards compat
// TODO(tc): Don't we only want to do this once? Gecko code doesn't seem
// to care.
if (boundary_pos >= 2) {
if ('-' == data_[boundary_pos - 1] && '-' == data_[boundary_pos - 2]) {
boundary_pos -= 2;
boundary_ = "--" + boundary_;
}
}
}
return boundary_pos;
}
bool MultipartResponseDelegate::ReadMultipartBoundary(
const WebCore::ResourceResponse& response,
std::string* multipart_boundary) {
WebCore::String content_type = response.httpHeaderField("Content-Type");
std::string content_type_as_string =
webkit_glue::StringToStdString(content_type);
size_t boundary_start_offset = content_type_as_string.find("boundary=");
if (boundary_start_offset == std::wstring::npos) {
return false;
}
boundary_start_offset += strlen("boundary=");
size_t boundary_end_offset = content_type.length();
size_t boundary_length = boundary_end_offset - boundary_start_offset;
*multipart_boundary =
content_type_as_string.substr(boundary_start_offset, boundary_length);
return true;
}
bool MultipartResponseDelegate::ReadContentRanges(
const WebCore::ResourceResponse& response,
int* content_range_lower_bound,
int* content_range_upper_bound) {
std::string content_range =
webkit_glue::StringToStdString(
response.httpHeaderField("Content-Range"));
size_t byte_range_lower_bound_start_offset =
content_range.find(" ");
if (byte_range_lower_bound_start_offset == std::string::npos) {
return false;
}
// Skip over the initial space.
byte_range_lower_bound_start_offset++;
size_t byte_range_lower_bound_end_offset =
content_range.find("-", byte_range_lower_bound_start_offset);
if (byte_range_lower_bound_end_offset == std::string::npos) {
return false;
}
size_t byte_range_lower_bound_characters =
byte_range_lower_bound_end_offset - byte_range_lower_bound_start_offset;
std::string byte_range_lower_bound =
content_range.substr(byte_range_lower_bound_start_offset,
byte_range_lower_bound_characters);
size_t byte_range_upper_bound_start_offset =
byte_range_lower_bound_end_offset + 1;
size_t byte_range_upper_bound_end_offset =
content_range.find("/", byte_range_upper_bound_start_offset);
if (byte_range_upper_bound_end_offset == std::string::npos) {
return false;
}
size_t byte_range_upper_bound_characters =
byte_range_upper_bound_end_offset - byte_range_upper_bound_start_offset;
std::string byte_range_upper_bound =
content_range.substr(byte_range_upper_bound_start_offset,
byte_range_upper_bound_characters);
if (!StringToInt(byte_range_lower_bound, content_range_lower_bound))
return false;
if (!StringToInt(byte_range_upper_bound, content_range_upper_bound))
return false;
return true;
}
<commit_msg>Remove unused variable (warnings are compile errors)<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "config.h"
#include <string>
#pragma warning(push, 0)
#include "HTTPHeaderMap.h"
#include "ResourceHandle.h"
#include "ResourceHandleClient.h"
#include "PlatformString.h"
#pragma warning(pop)
#undef LOG
#include "base/logging.h"
#include "base/string_util.h"
#include "webkit/glue/multipart_response_delegate.h"
#include "webkit/glue/glue_util.h"
#include "net/base/net_util.h"
MultipartResponseDelegate::MultipartResponseDelegate(
WebCore::ResourceHandleClient* client,
WebCore::ResourceHandle* job,
const WebCore::ResourceResponse& response,
const std::string& boundary)
: client_(client),
job_(job),
original_response_(response),
boundary_("--"),
first_received_data_(true),
processing_headers_(false),
stop_sending_(false) {
boundary_.append(boundary);
}
void MultipartResponseDelegate::OnReceivedData(const char* data, int data_len) {
// stop_sending_ means that we've already received the final boundary token.
// The server should stop sending us data at this point, but if it does, we
// just throw it away.
if (stop_sending_)
return;
// TODO(tc): Figure out what to use for length_received. Maybe we can just
// pass the value on from our caller. See note in
// resource_handle_win.cc:ResourceHandleInternal::OnReceivedData.
int length_received = -1;
data_.append(data, data_len);
if (first_received_data_) {
// Some servers don't send a boundary token before the first chunk of
// data. We handle this case anyway (Gecko does too).
first_received_data_ = false;
// Eat leading \r\n
int pos = PushOverLine(data_, 0);
if (pos)
data_ = data_.substr(pos);
if (data_.length() < boundary_.length() + 2) {
// We don't have enough data yet to make a boundary token. Just wait
// until the next chunk of data arrives.
first_received_data_ = true;
return;
}
if (data_.substr(0, boundary_.length()) != boundary_) {
data_ = boundary_ + "\n" + data_;
}
}
DCHECK(!first_received_data_);
// Headers
if (processing_headers_) {
// Eat leading \r\n
int pos = PushOverLine(data_, 0);
if (pos)
data_ = data_.substr(pos);
if (ParseHeaders()) {
// Successfully parsed headers.
processing_headers_ = false;
} else {
// Get more data before trying again.
return;
}
}
DCHECK(!processing_headers_);
size_t boundary_pos;
while ((boundary_pos = FindBoundary()) != std::string::npos) {
if (boundary_pos > 0) {
// Send the last data chunk.
client_->didReceiveData(job_, data_.substr(0, boundary_pos).data(),
static_cast<int>(boundary_pos), length_received);
}
size_t boundary_end_pos = boundary_pos + boundary_.length();
if (boundary_end_pos < data_.length() && '-' == data_[boundary_end_pos]) {
// This was the last boundary so we can stop processing.
stop_sending_ = true;
data_.clear();
return;
}
// We can now throw out data up through the boundary
int offset = PushOverLine(data_, boundary_end_pos);
data_ = data_.substr(boundary_end_pos + offset);
// Ok, back to parsing headers
if (!ParseHeaders()) {
processing_headers_ = true;
break;
}
}
}
void MultipartResponseDelegate::OnCompletedRequest() {
// If we have any pending data and we're not in a header, go ahead and send
// it to WebCore.
if (!processing_headers_ && !data_.empty()) {
// TODO(tc): Figure out what to use for length_received. Maybe we can just
// pass the value on from our caller.
int length_received = -1;
client_->didReceiveData(job_, data_.data(),
static_cast<int>(data_.length()), length_received);
}
}
int MultipartResponseDelegate::PushOverLine(const std::string& data, size_t pos) {
int offset = 0;
if (pos < data.length() && (data[pos] == '\r' || data[pos] == '\n')) {
++offset;
if (pos + 1 < data.length() && data[pos + 1] == '\n')
++offset;
}
return offset;
}
bool MultipartResponseDelegate::ParseHeaders() {
int line_feed_increment = 1;
// Grab the headers being liberal about line endings.
size_t line_start_pos = 0;
size_t line_end_pos = data_.find('\n');
while (line_end_pos != std::string::npos) {
// Handle CRLF
if (line_end_pos > line_start_pos && data_[line_end_pos - 1] == '\r') {
line_feed_increment = 2;
--line_end_pos;
} else {
line_feed_increment = 1;
}
if (line_start_pos == line_end_pos) {
// A blank line, end of headers
line_end_pos += line_feed_increment;
break;
}
// Find the next header line.
line_start_pos = line_end_pos + line_feed_increment;
line_end_pos = data_.find('\n', line_start_pos);
}
// Truncated in the middle of a header, stop parsing.
if (line_end_pos == std::string::npos)
return false;
// Eat headers
std::string headers("\n");
headers.append(data_.substr(0, line_end_pos));
data_ = data_.substr(line_end_pos);
// Create a ResourceResponse based on the original set of headers + the
// replacement headers. We only replace the same few headers that gecko
// does. See netwerk/streamconv/converters/nsMultiMixedConv.cpp.
std::string mime_type = net::GetSpecificHeader(headers, "content-type");
std::string charset = net::GetHeaderParamValue(mime_type, "charset");
WebCore::ResourceResponse response(original_response_.url(),
webkit_glue::StdStringToString(mime_type.c_str()),
-1,
charset.c_str(),
WebCore::String());
const WebCore::HTTPHeaderMap& orig_headers =
original_response_.httpHeaderFields();
for (WebCore::HTTPHeaderMap::const_iterator it = orig_headers.begin();
it != orig_headers.end(); ++it) {
if (!(equalIgnoringCase("content-type", it->first) ||
equalIgnoringCase("content-length", it->first) ||
equalIgnoringCase("content-disposition", it->first) ||
equalIgnoringCase("content-range", it->first) ||
equalIgnoringCase("range", it->first) ||
equalIgnoringCase("set-cookie", it->first))) {
response.setHTTPHeaderField(it->first, it->second);
}
}
static const char* replace_headers[] = {
"Content-Type",
"Content-Length",
"Content-Disposition",
"Content-Range",
"Range",
"Set-Cookie"
};
for (size_t i = 0; i < arraysize(replace_headers); ++i) {
std::string name(replace_headers[i]);
std::string value = net::GetSpecificHeader(headers, name);
if (!value.empty()) {
response.setHTTPHeaderField(webkit_glue::StdStringToString(name.c_str()),
webkit_glue::StdStringToString(value.c_str()));
}
}
// Send the response!
client_->didReceiveResponse(job_, response);
return true;
}
// Boundaries are supposed to be preceeded with --, but it looks like gecko
// doesn't require the dashes to exist. See nsMultiMixedConv::FindToken.
size_t MultipartResponseDelegate::FindBoundary() {
size_t boundary_pos = data_.find(boundary_);
if (boundary_pos != std::string::npos) {
// Back up over -- for backwards compat
// TODO(tc): Don't we only want to do this once? Gecko code doesn't seem
// to care.
if (boundary_pos >= 2) {
if ('-' == data_[boundary_pos - 1] && '-' == data_[boundary_pos - 2]) {
boundary_pos -= 2;
boundary_ = "--" + boundary_;
}
}
}
return boundary_pos;
}
bool MultipartResponseDelegate::ReadMultipartBoundary(
const WebCore::ResourceResponse& response,
std::string* multipart_boundary) {
WebCore::String content_type = response.httpHeaderField("Content-Type");
std::string content_type_as_string =
webkit_glue::StringToStdString(content_type);
size_t boundary_start_offset = content_type_as_string.find("boundary=");
if (boundary_start_offset == std::wstring::npos) {
return false;
}
boundary_start_offset += strlen("boundary=");
size_t boundary_end_offset = content_type.length();
size_t boundary_length = boundary_end_offset - boundary_start_offset;
*multipart_boundary =
content_type_as_string.substr(boundary_start_offset, boundary_length);
return true;
}
bool MultipartResponseDelegate::ReadContentRanges(
const WebCore::ResourceResponse& response,
int* content_range_lower_bound,
int* content_range_upper_bound) {
std::string content_range =
webkit_glue::StringToStdString(
response.httpHeaderField("Content-Range"));
size_t byte_range_lower_bound_start_offset =
content_range.find(" ");
if (byte_range_lower_bound_start_offset == std::string::npos) {
return false;
}
// Skip over the initial space.
byte_range_lower_bound_start_offset++;
size_t byte_range_lower_bound_end_offset =
content_range.find("-", byte_range_lower_bound_start_offset);
if (byte_range_lower_bound_end_offset == std::string::npos) {
return false;
}
size_t byte_range_lower_bound_characters =
byte_range_lower_bound_end_offset - byte_range_lower_bound_start_offset;
std::string byte_range_lower_bound =
content_range.substr(byte_range_lower_bound_start_offset,
byte_range_lower_bound_characters);
size_t byte_range_upper_bound_start_offset =
byte_range_lower_bound_end_offset + 1;
size_t byte_range_upper_bound_end_offset =
content_range.find("/", byte_range_upper_bound_start_offset);
if (byte_range_upper_bound_end_offset == std::string::npos) {
return false;
}
size_t byte_range_upper_bound_characters =
byte_range_upper_bound_end_offset - byte_range_upper_bound_start_offset;
std::string byte_range_upper_bound =
content_range.substr(byte_range_upper_bound_start_offset,
byte_range_upper_bound_characters);
if (!StringToInt(byte_range_lower_bound, content_range_lower_bound))
return false;
if (!StringToInt(byte_range_upper_bound, content_range_upper_bound))
return false;
return true;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <iostream>
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/http/http_cache.h"
#include "net/base/ssl_test_util.h"
#include "net/url_request/url_request_context.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
using namespace std;
static const size_t kPathBufSize = 2048;
namespace {
// StatsTable initialization parameters.
static const char* kStatsFilePrefix = "testshell_";
static int kStatsFileThreads = 20;
static int kStatsFileCounters = 200;
} // namespace
int main(int argc, char* argv[]) {
base::EnableTerminationOnHeapCorruption();
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
CommandLine::Init(argc, argv);
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
TestShellPlatformDelegate platform(parsed_command_line);
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
TestShell::ShowStartupDebuggingDialog();
if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
}
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
bool suppress_error_dialogs = (
base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
bool enable_gp_fault_error_box = false;
enable_gp_fault_error_box =
parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);
TestShell::InitLogging(suppress_error_dialogs,
layout_test_mode,
enable_gp_fault_error_box);
// Initialize WebKit for this scope.
TestShellWebKitInit test_shell_webkit_init(layout_test_mode);
// Suppress abort message in v8 library in debugging mode (but not
// actually under a debugger). V8 calls abort() when it hits
// assertion errors.
if (suppress_error_dialogs) {
platform.SuppressErrorReporting();
}
if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
base::TraceLog::StartTracing();
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
// This is a special mode where JS helps the browser implement
// playback/record mode. Generally, in this mode, some functions
// of client-side randomness are removed. For example, in
// this mode Math.random() and Date.getTime() may not return
// values which vary.
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
FilePath cache_path = FilePath::FromWStringHack(
parsed_command_line.GetSwitchValue(test_shell::kCacheDir));
// If the cache_path is empty and it's layout_test_mode, leave it empty
// so we use an in-memory cache. This makes running multiple test_shells
// in parallel less flaky.
if (cache_path.empty() && !layout_test_mode) {
PathService::Get(base::DIR_EXE, &cache_path);
cache_path = cache_path.AppendASCII("cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path.ToWStringHack(),
cache_mode, layout_test_mode));
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);
// On Linux, load the test root certificate.
net::TestServerLauncher ssl_util;
ssl_util.LoadTestRootCert();
platform.InitializeGUI();
TestShell::InitializeTestShell(layout_test_mode);
if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
TestShell::SetAllowScriptsToCloseWindows();
// Disable user themes for layout tests so pixel tests are consistent.
if (layout_test_mode) {
platform.SelectUnifiedTheme();
}
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms =
static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str())));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Treat the first loose value as the initial URL to open.
FilePath uri;
// Default to a homepage if we're interactive.
if (!layout_test_mode) {
PathService::Get(base::DIR_SOURCE_ROOT, &uri);
uri = uri.AppendASCII("webkit");
uri = uri.AppendASCII("data");
uri = uri.AppendASCII("test_shell");
uri = uri.AppendASCII("index.html");
}
std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues();
if (loose_values.size() > 0)
uri = FilePath::FromWStringHack(loose_values[0]);
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
js_flags += L" --expose-gc";
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript.
WebKit::registerExtension(extensions_v8::GCExtension::Get());
if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
WebKit::registerExtension(extensions_v8::ProfilerExtension::Get());
}
// Load and initialize the stats table. Attempt to construct a somewhat
// unique name to isolate separate instances from each other.
StatsTable *table = new StatsTable(
// truncate the random # to 32 bits for the benefit of Mac OS X, to
// avoid tripping over its maximum shared memory segment name length
kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL),
kStatsFileThreads,
kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(uri.ToWStringHack(), &shell)) {
if (record_mode || playback_mode) {
platform.SetWindowPositionForRecording(shell);
WebKit::registerExtension(extensions_v8::PlaybackExtension::Get());
}
shell->Show(shell->webView(), NEW_WINDOW);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
FilePath script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
script_path = script_path.AppendASCII("script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
if (false) {
// TODO(scherkus): check for any DLL dependencies.
webkit_glue::SetMediaPlayerAvailable(true);
}
// See if we need to run the tests.
if (layout_test_mode) {
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValue(
test_shell::kDumpPixels);
if (params.pixel_file_name.size() == 0) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (uri.empty()) {
// Watch stdin for URLs.
char filenameBuffer[kPathBufSize];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
// When running layout tests we pass new line separated
// tests to TestShell. Each line is a space separated list
// of filename, timeout and expected pixel hash. The timeout
// and the pixel hash are optional.
char* newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
params.test_url = strtok(filenameBuffer, " ");
int old_timeout_ms = TestShell::GetLayoutTestTimeout();
char* timeout = strtok(NULL, " ");
if (timeout) {
TestShell::SetFileTestTimeout(atoi(timeout));
char* pixel_hash = strtok(NULL, " ");
if (pixel_hash)
params.pixel_hash = pixel_hash;
}
if (!TestShell::RunFileTest(params))
break;
TestShell::SetFileTestTimeout(old_timeout_ms);
}
} else {
// TODO(ojan): Provide a way for run-singly tests to pass
// in a hash and then set params.pixel_hash here.
params.test_url = WideToUTF8(uri.ToWStringHack()).c_str();
TestShell::RunFileTest(params);
}
shell->CallJSGC();
shell->CallJSGC();
if (shell) {
// When we finish the last test, cleanup the LayoutTestController.
// It may have references to not-yet-cleaned up windows. By
// cleaning up here we help purify reports.
shell->ResetTestController();
delete shell;
}
} else {
MessageLoop::current()->Run();
}
// Flush any remaining messages. This ensures that any accumulated
// Task objects get destroyed before we exit, which avoids noise in
// purify leak-test results.
MessageLoop::current()->RunAllPending();
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
return 0;
}
<commit_msg>test_shell: flush message loop before destroying the shell.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include <iostream>
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_path.h"
#include "base/file_util.h"
#include "base/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/process_util.h"
#include "base/rand_util.h"
#include "base/stats_table.h"
#include "base/string_util.h"
#include "base/sys_info.h"
#include "base/trace_event.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/http/http_cache.h"
#include "net/base/ssl_test_util.h"
#include "net/url_request/url_request_context.h"
#include "webkit/api/public/WebKit.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/extensions/v8/gc_extension.h"
#include "webkit/extensions/v8/playback_extension.h"
#include "webkit/extensions/v8/profiler_extension.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_platform_delegate.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
#include "webkit/tools/test_shell/test_shell_webkit_init.h"
using namespace std;
static const size_t kPathBufSize = 2048;
namespace {
// StatsTable initialization parameters.
static const char* kStatsFilePrefix = "testshell_";
static int kStatsFileThreads = 20;
static int kStatsFileCounters = 200;
} // namespace
int main(int argc, char* argv[]) {
base::EnableTerminationOnHeapCorruption();
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
TestShellPlatformDelegate::PreflightArgs(&argc, &argv);
CommandLine::Init(argc, argv);
const CommandLine& parsed_command_line = *CommandLine::ForCurrentProcess();
TestShellPlatformDelegate platform(parsed_command_line);
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
TestShell::ShowStartupDebuggingDialog();
if (parsed_command_line.HasSwitch(test_shell::kCheckLayoutTestSystemDeps)) {
exit(platform.CheckLayoutTestSystemDependencies() ? 0 : 1);
}
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
bool suppress_error_dialogs = (
base::SysInfo::HasEnvVar(L"CHROME_HEADLESS") ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
bool enable_gp_fault_error_box = false;
enable_gp_fault_error_box =
parsed_command_line.HasSwitch(test_shell::kGPFaultErrorBox);
TestShell::InitLogging(suppress_error_dialogs,
layout_test_mode,
enable_gp_fault_error_box);
// Initialize WebKit for this scope.
TestShellWebKitInit test_shell_webkit_init(layout_test_mode);
// Suppress abort message in v8 library in debugging mode (but not
// actually under a debugger). V8 calls abort() when it hits
// assertion errors.
if (suppress_error_dialogs) {
platform.SuppressErrorReporting();
}
if (parsed_command_line.HasSwitch(test_shell::kEnableTracing))
base::TraceLog::StartTracing();
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
// This is a special mode where JS helps the browser implement
// playback/record mode. Generally, in this mode, some functions
// of client-side randomness are removed. For example, in
// this mode Math.random() and Date.getTime() may not return
// values which vary.
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
FilePath cache_path = FilePath::FromWStringHack(
parsed_command_line.GetSwitchValue(test_shell::kCacheDir));
// If the cache_path is empty and it's layout_test_mode, leave it empty
// so we use an in-memory cache. This makes running multiple test_shells
// in parallel less flaky.
if (cache_path.empty() && !layout_test_mode) {
PathService::Get(base::DIR_EXE, &cache_path);
cache_path = cache_path.AppendASCII("cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path.ToWStringHack(),
cache_mode, layout_test_mode));
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(TestShell::NetResourceProvider);
// On Linux, load the test root certificate.
net::TestServerLauncher ssl_util;
ssl_util.LoadTestRootCert();
platform.InitializeGUI();
TestShell::InitializeTestShell(layout_test_mode);
if (parsed_command_line.HasSwitch(test_shell::kAllowScriptsToCloseWindows))
TestShell::SetAllowScriptsToCloseWindows();
// Disable user themes for layout tests so pixel tests are consistent.
if (layout_test_mode) {
platform.SelectUnifiedTheme();
}
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms =
static_cast<int>(StringToInt64(WideToUTF16Hack(timeout_str.c_str())));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Treat the first loose value as the initial URL to open.
FilePath uri;
// Default to a homepage if we're interactive.
if (!layout_test_mode) {
PathService::Get(base::DIR_SOURCE_ROOT, &uri);
uri = uri.AppendASCII("webkit");
uri = uri.AppendASCII("data");
uri = uri.AppendASCII("test_shell");
uri = uri.AppendASCII("index.html");
}
std::vector<std::wstring> loose_values = parsed_command_line.GetLooseValues();
if (loose_values.size() > 0)
uri = FilePath::FromWStringHack(loose_values[0]);
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
js_flags += L" --expose-gc";
webkit_glue::SetJavaScriptFlags(js_flags);
// Expose GCController to JavaScript.
WebKit::registerExtension(extensions_v8::GCExtension::Get());
if (parsed_command_line.HasSwitch(test_shell::kProfiler)) {
WebKit::registerExtension(extensions_v8::ProfilerExtension::Get());
}
// Load and initialize the stats table. Attempt to construct a somewhat
// unique name to isolate separate instances from each other.
StatsTable *table = new StatsTable(
// truncate the random # to 32 bits for the benefit of Mac OS X, to
// avoid tripping over its maximum shared memory segment name length
kStatsFilePrefix + Uint64ToString(base::RandUint64() & 0xFFFFFFFFL),
kStatsFileThreads,
kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(uri.ToWStringHack(), &shell)) {
if (record_mode || playback_mode) {
platform.SetWindowPositionForRecording(shell);
WebKit::registerExtension(extensions_v8::PlaybackExtension::Get());
}
shell->Show(shell->webView(), NEW_WINDOW);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
FilePath script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
script_path = script_path.AppendASCII("script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
if (false) {
// TODO(scherkus): check for any DLL dependencies.
webkit_glue::SetMediaPlayerAvailable(true);
}
// See if we need to run the tests.
if (layout_test_mode) {
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValue(
test_shell::kDumpPixels);
if (params.pixel_file_name.size() == 0) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (uri.empty()) {
// Watch stdin for URLs.
char filenameBuffer[kPathBufSize];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
// When running layout tests we pass new line separated
// tests to TestShell. Each line is a space separated list
// of filename, timeout and expected pixel hash. The timeout
// and the pixel hash are optional.
char* newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
params.test_url = strtok(filenameBuffer, " ");
int old_timeout_ms = TestShell::GetLayoutTestTimeout();
char* timeout = strtok(NULL, " ");
if (timeout) {
TestShell::SetFileTestTimeout(atoi(timeout));
char* pixel_hash = strtok(NULL, " ");
if (pixel_hash)
params.pixel_hash = pixel_hash;
}
if (!TestShell::RunFileTest(params))
break;
TestShell::SetFileTestTimeout(old_timeout_ms);
}
} else {
// TODO(ojan): Provide a way for run-singly tests to pass
// in a hash and then set params.pixel_hash here.
params.test_url = WideToUTF8(uri.ToWStringHack()).c_str();
TestShell::RunFileTest(params);
}
shell->CallJSGC();
shell->CallJSGC();
// When we finish the last test, cleanup the LayoutTestController.
// It may have references to not-yet-cleaned up windows. By
// cleaning up here we help purify reports.
shell->ResetTestController();
// Flush any remaining messages before we kill ourselves.
// http://code.google.com/p/chromium/issues/detail?id=9500
MessageLoop::current()->RunAllPending();
delete shell;
} else {
MessageLoop::current()->Run();
}
// Flush any remaining messages. This ensures that any accumulated
// Task objects get destroyed before we exit, which avoids noise in
// purify leak-test results.
MessageLoop::current()->RunAllPending();
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Creates an instance of the test_shell.
#include <stdlib.h> // required by _set_abort_behavior
#include <windows.h>
#include <commctrl.h>
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_util.h"
#include "base/gfx/native_theme.h"
#include "base/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/stack_container.h"
#include "base/stats_table.h"
#include "base/string_util.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
// This is only set for layout tests.
static wchar_t g_currentTestName[MAX_PATH];
namespace {
// StatsTable initialization parameters.
static wchar_t* kStatsFile = L"testshell";
static int kStatsFileThreads = 20;
static int kStatsFileCounters = 200;
std::string GetDataResource(HMODULE module, int resource_id) {
void* data_ptr;
size_t data_size;
return base::GetDataResourceFromModule(module, resource_id, &data_ptr,
&data_size) ?
std::string(static_cast<char*>(data_ptr), data_size) : std::string();
}
// This is called indirectly by the network layer to access resources.
std::string NetResourceProvider(int key) {
return GetDataResource(::GetModuleHandle(NULL), key);
}
void SetCurrentTestName(char* path)
{
char* lastSlash = strrchr(path, '/');
if (lastSlash) {
++lastSlash;
} else {
lastSlash = path;
}
wcscpy_s(g_currentTestName, arraysize(g_currentTestName),
UTF8ToWide(lastSlash).c_str());
}
bool MinidumpCallback(const wchar_t *dumpPath,
const wchar_t *minidumpID,
void *context,
EXCEPTION_POINTERS *exinfo,
MDRawAssertionInfo *assertion,
bool succeeded)
{
// Warning: Don't use the heap in this function. It may be corrupted.
if (!g_currentTestName[0])
return false;
// Try to rename the minidump file to include the crashed test's name.
// StackString uses the stack but overflows onto the heap. But we don't
// care too much about being completely correct here, since most crashes
// will be happening on developers' machines where they have debuggers.
StackWString<MAX_PATH*2> origPath;
origPath->append(dumpPath);
origPath->push_back(file_util::kPathSeparator);
origPath->append(minidumpID);
origPath->append(L".dmp");
StackWString<MAX_PATH*2> newPath;
newPath->append(dumpPath);
newPath->push_back(file_util::kPathSeparator);
newPath->append(g_currentTestName);
newPath->append(L"-");
newPath->append(minidumpID);
newPath->append(L".dmp");
// May use the heap, but oh well. If this fails, we'll just have the
// original dump file lying around.
_wrename(origPath->c_str(), newPath->c_str());
return false;
}
} // namespace
int main(int argc, char* argv[])
{
#ifdef _CRTDBG_MAP_ALLOC
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
CommandLine parsed_command_line;
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
MessageBox(NULL, L"attach to me?", L"test_shell", MB_OK);
//webkit_glue::SetLayoutTestMode(true);
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoop main_message_loop;
bool suppress_error_dialogs =
(GetEnvironmentVariable(L"CHROME_HEADLESS", NULL, 0) ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
TestShell::InitLogging(suppress_error_dialogs);
// Suppress abort message in v8 library in debugging mode.
// V8 calls abort() when it hits assertion errors.
if (suppress_error_dialogs) {
_set_abort_behavior(0, _WRITE_ABORT_MSG);
}
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
std::wstring cache_path =
parsed_command_line.GetSwitchValue(test_shell::kCacheDir);
if (cache_path.empty()) {
PathService::Get(base::DIR_EXE, &cache_path);
file_util::AppendToPath(&cache_path, L"cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path, cache_mode));
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(NetResourceProvider);
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&InitCtrlEx);
bool interactive = !layout_test_mode;
TestShell::InitializeTestShell(interactive);
// Disable user themes for layout tests so pixel tests are consistent.
if (!interactive)
gfx::NativeTheme::instance()->DisableTheming();
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str()));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Initialize global strings
TestShell::RegisterWindowClass();
// Treat the first loose value as the initial URL to open.
std::wstring uri;
// Default to a homepage if we're interactive.
if (interactive) {
PathService::Get(base::DIR_SOURCE_ROOT, &uri);
file_util::AppendToPath(&uri, L"webkit");
file_util::AppendToPath(&uri, L"data");
file_util::AppendToPath(&uri, L"test_shell");
file_util::AppendToPath(&uri, L"index.html");
}
if (parsed_command_line.GetLooseValueCount() > 0) {
CommandLine::LooseValueIterator iter = parsed_command_line.GetLooseValuesBegin();
uri = *iter;
}
if (parsed_command_line.HasSwitch(test_shell::kCrashDumps)) {
std::wstring dir = parsed_command_line.GetSwitchValue(test_shell::kCrashDumps);
new google_breakpad::ExceptionHandler(dir, 0, &MinidumpCallback, 0, true);
}
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
CommandLine::AppendSwitch(&js_flags, L"expose-gc");
webkit_glue::SetJavaScriptFlags(js_flags);
// load and initialize the stats table.
StatsTable *table = new StatsTable(kStatsFile, kStatsFileThreads, kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(uri, &shell)) {
if (record_mode || playback_mode) {
// Move the window to the upper left corner for consistent
// record/playback mode. For automation, we want this to work
// on build systems where the script invoking us is a background
// process. So for this case, make our window the topmost window
// as well.
ForegroundHelper::SetForeground(shell->mainWnd());
::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
// Tell webkit as well.
webkit_glue::SetRecordPlaybackMode(true);
}
shell->Show(shell->webView(), NEW_WINDOW);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
std::wstring script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
file_util::AppendToPath(&script_path, L"script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
// See if we need to run the tests.
if (layout_test_mode) {
webkit_glue::SetLayoutTestMode(true);
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValue(
test_shell::kDumpPixels);
if (params.pixel_file_name.size() == 0) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (uri.length() == 0) {
// Watch stdin for URLs.
char filenameBuffer[2048];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
char *newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
SetCurrentTestName(filenameBuffer);
if (!TestShell::RunFileTest(filenameBuffer, params))
break;
}
} else {
TestShell::RunFileTest(WideToUTF8(uri).c_str(), params);
}
shell->CallJSGC();
shell->CallJSGC();
if (shell) delete shell;
} else {
MessageLoop::current()->Run();
}
// Flush any remaining messages. This ensures that any accumulated
// Task objects get destroyed before we exit, which avoids noise in
// purify leak-test results.
MessageLoop::current()->RunAllPending();
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif
return 0;
}
<commit_msg>The main thread of test_shell.exe needs to have a UI message loop.<commit_after>// Copyright (c) 2006-2008 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
// Creates an instance of the test_shell.
#include <stdlib.h> // required by _set_abort_behavior
#include <windows.h>
#include <commctrl.h>
#include "base/at_exit.h"
#include "base/basictypes.h"
#include "base/command_line.h"
#include "base/event_recorder.h"
#include "base/file_util.h"
#include "base/gfx/native_theme.h"
#include "base/icu_util.h"
#include "base/memory_debug.h"
#include "base/message_loop.h"
#include "base/path_service.h"
#include "base/resource_util.h"
#include "base/stack_container.h"
#include "base/stats_table.h"
#include "base/string_util.h"
#include "breakpad/src/client/windows/handler/exception_handler.h"
#include "net/base/cookie_monster.h"
#include "net/base/net_module.h"
#include "net/http/http_cache.h"
#include "net/url_request/url_request_context.h"
#include "webkit/glue/webkit_glue.h"
#include "webkit/glue/window_open_disposition.h"
#include "webkit/tools/test_shell/foreground_helper.h"
#include "webkit/tools/test_shell/simple_resource_loader_bridge.h"
#include "webkit/tools/test_shell/test_shell.h"
#include "webkit/tools/test_shell/test_shell_request_context.h"
#include "webkit/tools/test_shell/test_shell_switches.h"
// This is only set for layout tests.
static wchar_t g_currentTestName[MAX_PATH];
namespace {
// StatsTable initialization parameters.
static wchar_t* kStatsFile = L"testshell";
static int kStatsFileThreads = 20;
static int kStatsFileCounters = 200;
std::string GetDataResource(HMODULE module, int resource_id) {
void* data_ptr;
size_t data_size;
return base::GetDataResourceFromModule(module, resource_id, &data_ptr,
&data_size) ?
std::string(static_cast<char*>(data_ptr), data_size) : std::string();
}
// This is called indirectly by the network layer to access resources.
std::string NetResourceProvider(int key) {
return GetDataResource(::GetModuleHandle(NULL), key);
}
void SetCurrentTestName(char* path)
{
char* lastSlash = strrchr(path, '/');
if (lastSlash) {
++lastSlash;
} else {
lastSlash = path;
}
wcscpy_s(g_currentTestName, arraysize(g_currentTestName),
UTF8ToWide(lastSlash).c_str());
}
bool MinidumpCallback(const wchar_t *dumpPath,
const wchar_t *minidumpID,
void *context,
EXCEPTION_POINTERS *exinfo,
MDRawAssertionInfo *assertion,
bool succeeded)
{
// Warning: Don't use the heap in this function. It may be corrupted.
if (!g_currentTestName[0])
return false;
// Try to rename the minidump file to include the crashed test's name.
// StackString uses the stack but overflows onto the heap. But we don't
// care too much about being completely correct here, since most crashes
// will be happening on developers' machines where they have debuggers.
StackWString<MAX_PATH*2> origPath;
origPath->append(dumpPath);
origPath->push_back(file_util::kPathSeparator);
origPath->append(minidumpID);
origPath->append(L".dmp");
StackWString<MAX_PATH*2> newPath;
newPath->append(dumpPath);
newPath->push_back(file_util::kPathSeparator);
newPath->append(g_currentTestName);
newPath->append(L"-");
newPath->append(minidumpID);
newPath->append(L".dmp");
// May use the heap, but oh well. If this fails, we'll just have the
// original dump file lying around.
_wrename(origPath->c_str(), newPath->c_str());
return false;
}
} // namespace
int main(int argc, char* argv[])
{
#ifdef _CRTDBG_MAP_ALLOC
_CrtSetReportFile(_CRT_WARN, _CRTDBG_FILE_STDERR);
_CrtSetReportMode(_CRT_WARN, _CRTDBG_MODE_FILE);
#endif
// Some tests may use base::Singleton<>, thus we need to instanciate
// the AtExitManager or else we will leak objects.
base::AtExitManager at_exit_manager;
CommandLine parsed_command_line;
if (parsed_command_line.HasSwitch(test_shell::kStartupDialog))
MessageBox(NULL, L"attach to me?", L"test_shell", MB_OK);
//webkit_glue::SetLayoutTestMode(true);
// Allocate a message loop for this thread. Although it is not used
// directly, its constructor sets up some necessary state.
MessageLoopForUI main_message_loop;
bool suppress_error_dialogs =
(GetEnvironmentVariable(L"CHROME_HEADLESS", NULL, 0) ||
parsed_command_line.HasSwitch(test_shell::kNoErrorDialogs) ||
parsed_command_line.HasSwitch(test_shell::kLayoutTests));
TestShell::InitLogging(suppress_error_dialogs);
// Suppress abort message in v8 library in debugging mode.
// V8 calls abort() when it hits assertion errors.
if (suppress_error_dialogs) {
_set_abort_behavior(0, _WRITE_ABORT_MSG);
}
bool layout_test_mode =
parsed_command_line.HasSwitch(test_shell::kLayoutTests);
net::HttpCache::Mode cache_mode = net::HttpCache::NORMAL;
bool playback_mode =
parsed_command_line.HasSwitch(test_shell::kPlaybackMode);
bool record_mode =
parsed_command_line.HasSwitch(test_shell::kRecordMode);
if (playback_mode)
cache_mode = net::HttpCache::PLAYBACK;
else if (record_mode)
cache_mode = net::HttpCache::RECORD;
if (layout_test_mode ||
parsed_command_line.HasSwitch(test_shell::kEnableFileCookies))
net::CookieMonster::EnableFileScheme();
std::wstring cache_path =
parsed_command_line.GetSwitchValue(test_shell::kCacheDir);
if (cache_path.empty()) {
PathService::Get(base::DIR_EXE, &cache_path);
file_util::AppendToPath(&cache_path, L"cache");
}
// Initializing with a default context, which means no on-disk cookie DB,
// and no support for directory listings.
SimpleResourceLoaderBridge::Init(
new TestShellRequestContext(cache_path, cache_mode));
// Load ICU data tables
icu_util::Initialize();
// Config the network module so it has access to a limited set of resources.
net::NetModule::SetResourceProvider(NetResourceProvider);
INITCOMMONCONTROLSEX InitCtrlEx;
InitCtrlEx.dwSize = sizeof(INITCOMMONCONTROLSEX);
InitCtrlEx.dwICC = ICC_STANDARD_CLASSES;
InitCommonControlsEx(&InitCtrlEx);
bool interactive = !layout_test_mode;
TestShell::InitializeTestShell(interactive);
// Disable user themes for layout tests so pixel tests are consistent.
if (!interactive)
gfx::NativeTheme::instance()->DisableTheming();
if (parsed_command_line.HasSwitch(test_shell::kTestShellTimeOut)) {
const std::wstring timeout_str = parsed_command_line.GetSwitchValue(
test_shell::kTestShellTimeOut);
int timeout_ms = static_cast<int>(StringToInt64(timeout_str.c_str()));
if (timeout_ms > 0)
TestShell::SetFileTestTimeout(timeout_ms);
}
// Initialize global strings
TestShell::RegisterWindowClass();
// Treat the first loose value as the initial URL to open.
std::wstring uri;
// Default to a homepage if we're interactive.
if (interactive) {
PathService::Get(base::DIR_SOURCE_ROOT, &uri);
file_util::AppendToPath(&uri, L"webkit");
file_util::AppendToPath(&uri, L"data");
file_util::AppendToPath(&uri, L"test_shell");
file_util::AppendToPath(&uri, L"index.html");
}
if (parsed_command_line.GetLooseValueCount() > 0) {
CommandLine::LooseValueIterator iter = parsed_command_line.GetLooseValuesBegin();
uri = *iter;
}
if (parsed_command_line.HasSwitch(test_shell::kCrashDumps)) {
std::wstring dir = parsed_command_line.GetSwitchValue(test_shell::kCrashDumps);
new google_breakpad::ExceptionHandler(dir, 0, &MinidumpCallback, 0, true);
}
std::wstring js_flags =
parsed_command_line.GetSwitchValue(test_shell::kJavaScriptFlags);
// Test shell always exposes the GC.
CommandLine::AppendSwitch(&js_flags, L"expose-gc");
webkit_glue::SetJavaScriptFlags(js_flags);
// load and initialize the stats table.
StatsTable *table = new StatsTable(kStatsFile, kStatsFileThreads, kStatsFileCounters);
StatsTable::set_current(table);
TestShell* shell;
if (TestShell::CreateNewWindow(uri, &shell)) {
if (record_mode || playback_mode) {
// Move the window to the upper left corner for consistent
// record/playback mode. For automation, we want this to work
// on build systems where the script invoking us is a background
// process. So for this case, make our window the topmost window
// as well.
ForegroundHelper::SetForeground(shell->mainWnd());
::SetWindowPos(shell->mainWnd(), HWND_TOP, 0, 0, 600, 800, 0);
// Tell webkit as well.
webkit_glue::SetRecordPlaybackMode(true);
}
shell->Show(shell->webView(), NEW_WINDOW);
if (parsed_command_line.HasSwitch(test_shell::kDumpStatsTable))
shell->DumpStatsTableOnExit();
bool no_events = parsed_command_line.HasSwitch(test_shell::kNoEvents);
if ((record_mode || playback_mode) && !no_events) {
std::wstring script_path = cache_path;
// Create the cache directory in case it doesn't exist.
file_util::CreateDirectory(cache_path);
file_util::AppendToPath(&script_path, L"script.log");
if (record_mode)
base::EventRecorder::current()->StartRecording(script_path);
if (playback_mode)
base::EventRecorder::current()->StartPlayback(script_path);
}
if (parsed_command_line.HasSwitch(test_shell::kDebugMemoryInUse)) {
base::MemoryDebug::SetMemoryInUseEnabled(true);
// Dump all in use memory at startup
base::MemoryDebug::DumpAllMemoryInUse();
}
// See if we need to run the tests.
if (layout_test_mode) {
webkit_glue::SetLayoutTestMode(true);
// Set up for the kind of test requested.
TestShell::TestParams params;
if (parsed_command_line.HasSwitch(test_shell::kDumpPixels)) {
// The pixel test flag also gives the image file name to use.
params.dump_pixels = true;
params.pixel_file_name = parsed_command_line.GetSwitchValue(
test_shell::kDumpPixels);
if (params.pixel_file_name.size() == 0) {
fprintf(stderr, "No file specified for pixel tests");
exit(1);
}
}
if (parsed_command_line.HasSwitch(test_shell::kNoTree)) {
params.dump_tree = false;
}
if (uri.length() == 0) {
// Watch stdin for URLs.
char filenameBuffer[2048];
while (fgets(filenameBuffer, sizeof(filenameBuffer), stdin)) {
char *newLine = strchr(filenameBuffer, '\n');
if (newLine)
*newLine = '\0';
if (!*filenameBuffer)
continue;
SetCurrentTestName(filenameBuffer);
if (!TestShell::RunFileTest(filenameBuffer, params))
break;
}
} else {
TestShell::RunFileTest(WideToUTF8(uri).c_str(), params);
}
shell->CallJSGC();
shell->CallJSGC();
if (shell) delete shell;
} else {
MessageLoop::current()->Run();
}
// Flush any remaining messages. This ensures that any accumulated
// Task objects get destroyed before we exit, which avoids noise in
// purify leak-test results.
MessageLoop::current()->RunAllPending();
if (record_mode)
base::EventRecorder::current()->StopRecording();
if (playback_mode)
base::EventRecorder::current()->StopPlayback();
}
TestShell::ShutdownTestShell();
TestShell::CleanupLogging();
// Tear down shared StatsTable; prevents unit_tests from leaking it.
StatsTable::set_current(NULL);
delete table;
#ifdef _CRTDBG_MAP_ALLOC
_CrtDumpMemoryLeaks();
#endif
return 0;
}
<|endoftext|> |
<commit_before>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
// STL
#include <memory>
#include <string>
// po6
#include <po6/net/ipaddr.h>
#include <po6/net/location.h>
// e
#include <e/convert.h>
#include <e/timer.h>
// HyperDex
#include <hyperclient/client.h>
const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28",
"29", "30", "31", "32"};
static int
usage();
void
handle_put(hyperclient::returncode ret)
{
if (ret != hyperclient::SUCCESS)
{
std::cerr << "Put returned " << ret << "." << std::endl;
}
}
void
handle_search(size_t* count,
const e::buffer& expected_key,
hyperclient::returncode ret,
const e::buffer& key,
const std::vector<e::buffer>& value)
{
if (ret != hyperclient::SUCCESS)
{
std::cerr << "Equality returned !SUCCESS: " << ret << std::endl;
return;
}
++*count;
if (expected_key != key)
{
std::cerr << "Equality returned unexpected key: "
<< expected_key.size() << ":" << expected_key.hex()
<< " != " << key.size() << ":" << key.hex() << std::endl;
}
}
void
handle_range(size_t* count,
const e::buffer& expected_key,
hyperclient::returncode ret,
const e::buffer& key,
const std::vector<e::buffer>& value)
{
if (ret != hyperclient::SUCCESS)
{
std::cerr << "Range returned !SUCCESS: " << ret << std::endl;
return;
}
++*count;
if (expected_key != key)
{
std::cerr << "Range returned unexpected key: "
<< expected_key.size() << ":" << expected_key.hex()
<< " != " << key.size() << ":" << key.hex() << std::endl;
}
}
int
main(int argc, char* argv[])
{
if (argc != 5)
{
return usage();
}
po6::net::ipaddr ip;
uint16_t port;
std::string space = argv[3];
uint32_t numbers;
try
{
ip = argv[1];
}
catch (std::invalid_argument& e)
{
std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl;
return EXIT_FAILURE;
}
try
{
port = e::convert::to_uint16_t(argv[2]);
}
catch (std::domain_error& e)
{
std::cerr << "The port number must be an integer." << std::endl;
return EXIT_FAILURE;
}
catch (std::out_of_range& e)
{
std::cerr << "The port number must be suitably small." << std::endl;
return EXIT_FAILURE;
}
try
{
numbers = e::convert::to_uint32_t(argv[4]);
}
catch (std::domain_error& e)
{
std::cerr << "The number must be an integer." << std::endl;
return EXIT_FAILURE;
}
catch (std::out_of_range& e)
{
std::cerr << "The number must be suitably small." << std::endl;
return EXIT_FAILURE;
}
try
{
hyperclient::client cl(po6::net::location(ip, port));
cl.connect();
e::buffer one("one", 3);
e::buffer zero("zero", 4);
for (uint32_t num = 0; num < numbers; ++num)
{
e::buffer key;
key.pack() << num;
std::vector<e::buffer> value;
for (size_t i = 0; i < 32; ++i)
{
value.push_back(e::buffer());
if ((num & (1 << i)))
{
value.back() = one;
}
else
{
value.back() = zero;
}
}
char buf[4];
memmove(buf, &num, sizeof(4));
value.push_back(e::buffer(buf, 4));
cl.put(space, key, value, handle_put);
if (cl.outstanding() > 1000)
{
cl.flush(-1);
}
}
cl.flush(-1);
e::sleep_ms(1, 0);
std::cerr << "Starting searches." << std::endl;
timespec start;
timespec end;
clock_gettime(CLOCK_REALTIME, &start);
for (uint32_t num = 0; num < numbers; ++num)
{
e::buffer key;
key.pack() << num;
std::map<std::string, e::buffer> search;
for (size_t i = 0; i < 32; ++i)
{
if ((num & (1 << i)))
{
search.insert(std::make_pair(colnames[i], one));
}
else
{
search.insert(std::make_pair(colnames[i], zero));
}
}
using std::tr1::bind;
using std::tr1::placeholders::_1;
using std::tr1::placeholders::_2;
using std::tr1::placeholders::_3;
size_t count = 0;
cl.search(argv[3], search, std::tr1::bind(handle_search, &count, key, _1, _2, _3));
cl.flush(100);
if (count < 1)
{
std::cerr << "Equality returned less than 1 result." << std::endl;
}
if (count > 1)
{
std::cerr << "Equality returned more than 1 result." << std::endl;
}
count = 0;
std::map<std::string, std::pair<uint64_t, uint64_t> > range;
range.insert(std::make_pair("range", std::make_pair(num, num + 1)));
cl.search(argv[3], range, std::tr1::bind(handle_range, &count, key, _1, _2, _3));
cl.flush(100);
if (count < 1)
{
std::cerr << "Range returned less than 1 result." << std::endl;
}
if (count > 1)
{
std::cerr << "Range returned more than 1 result." << std::endl;
}
}
clock_gettime(CLOCK_REALTIME, &end);
timespec diff;
if ((end.tv_nsec < start.tv_nsec) < 0)
{
diff.tv_sec = end.tv_sec - start.tv_sec - 1;
diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
}
else
{
diff.tv_sec = end.tv_sec - start.tv_sec;
diff.tv_nsec = end.tv_nsec - start.tv_nsec;
}
uint64_t nanosecs = diff.tv_sec * 1000000000 + diff.tv_nsec;
std::cerr << "test took " << nanosecs << " nanoseconds for " << numbers << " searches" << std::endl;
}
catch (po6::error& e)
{
std::cerr << "There was a system error: " << e.what();
return EXIT_FAILURE;
}
catch (std::runtime_error& e)
{
std::cerr << "There was a runtime error: " << e.what();
return EXIT_FAILURE;
}
catch (std::bad_alloc& e)
{
std::cerr << "There was a memory allocation error: " << e.what();
return EXIT_FAILURE;
}
catch (std::exception& e)
{
std::cerr << "There was a generic error: " << e.what();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int
usage()
{
std::cerr << "Usage: binary <coordinator ip> <coordinator port> <space name> <numbers>\n"
<< "This will create <numbers> points whose key is a number [0, <numbers>) and "
<< "then perform searches over the bits of the number. The space should have 32 "
<< "secondary dimensions so that all bits of a number may be stored."
<< std::endl;
return EXIT_FAILURE;
}
<commit_msg>Don't timeout in the binary test.<commit_after>// Copyright (c) 2011, Cornell University
// 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 HyperDex 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.
// STL
#include <memory>
#include <string>
// po6
#include <po6/net/ipaddr.h>
#include <po6/net/location.h>
// e
#include <e/convert.h>
#include <e/timer.h>
// HyperDex
#include <hyperclient/client.h>
const char* colnames[] = {"1", "2", "3", "4", "5", "6", "7", "8", "9", "10",
"11", "12", "13", "14", "15", "16", "17", "18", "19",
"20", "21", "22", "23", "24", "25", "26", "27", "28",
"29", "30", "31", "32"};
static int
usage();
void
handle_put(hyperclient::returncode ret)
{
if (ret != hyperclient::SUCCESS)
{
std::cerr << "Put returned " << ret << "." << std::endl;
}
}
void
handle_search(size_t* count,
const e::buffer& expected_key,
hyperclient::returncode ret,
const e::buffer& key,
const std::vector<e::buffer>& value)
{
if (ret != hyperclient::SUCCESS)
{
std::cerr << "Equality returned !SUCCESS: " << ret << std::endl;
return;
}
++*count;
if (expected_key != key)
{
std::cerr << "Equality returned unexpected key: "
<< expected_key.size() << ":" << expected_key.hex()
<< " != " << key.size() << ":" << key.hex() << std::endl;
}
}
void
handle_range(size_t* count,
const e::buffer& expected_key,
hyperclient::returncode ret,
const e::buffer& key,
const std::vector<e::buffer>& value)
{
if (ret != hyperclient::SUCCESS)
{
std::cerr << "Range returned !SUCCESS: " << ret << std::endl;
return;
}
++*count;
if (expected_key != key)
{
std::cerr << "Range returned unexpected key: "
<< expected_key.size() << ":" << expected_key.hex()
<< " != " << key.size() << ":" << key.hex() << std::endl;
}
}
int
main(int argc, char* argv[])
{
if (argc != 5)
{
return usage();
}
po6::net::ipaddr ip;
uint16_t port;
std::string space = argv[3];
uint32_t numbers;
try
{
ip = argv[1];
}
catch (std::invalid_argument& e)
{
std::cerr << "The IP address must be an IPv4 or IPv6 address." << std::endl;
return EXIT_FAILURE;
}
try
{
port = e::convert::to_uint16_t(argv[2]);
}
catch (std::domain_error& e)
{
std::cerr << "The port number must be an integer." << std::endl;
return EXIT_FAILURE;
}
catch (std::out_of_range& e)
{
std::cerr << "The port number must be suitably small." << std::endl;
return EXIT_FAILURE;
}
try
{
numbers = e::convert::to_uint32_t(argv[4]);
}
catch (std::domain_error& e)
{
std::cerr << "The number must be an integer." << std::endl;
return EXIT_FAILURE;
}
catch (std::out_of_range& e)
{
std::cerr << "The number must be suitably small." << std::endl;
return EXIT_FAILURE;
}
try
{
hyperclient::client cl(po6::net::location(ip, port));
cl.connect();
e::buffer one("one", 3);
e::buffer zero("zero", 4);
for (uint32_t num = 0; num < numbers; ++num)
{
e::buffer key;
key.pack() << num;
std::vector<e::buffer> value;
for (size_t i = 0; i < 32; ++i)
{
value.push_back(e::buffer());
if ((num & (1 << i)))
{
value.back() = one;
}
else
{
value.back() = zero;
}
}
char buf[4];
memmove(buf, &num, sizeof(4));
value.push_back(e::buffer(buf, 4));
cl.put(space, key, value, handle_put);
if (cl.outstanding() > 1000)
{
cl.flush(-1);
}
}
cl.flush(-1);
e::sleep_ms(1, 0);
std::cerr << "Starting searches." << std::endl;
timespec start;
timespec end;
clock_gettime(CLOCK_REALTIME, &start);
for (uint32_t num = 0; num < numbers; ++num)
{
e::buffer key;
key.pack() << num;
std::map<std::string, e::buffer> search;
for (size_t i = 0; i < 32; ++i)
{
if ((num & (1 << i)))
{
search.insert(std::make_pair(colnames[i], one));
}
else
{
search.insert(std::make_pair(colnames[i], zero));
}
}
using std::tr1::bind;
using std::tr1::placeholders::_1;
using std::tr1::placeholders::_2;
using std::tr1::placeholders::_3;
size_t count = 0;
cl.search(argv[3], search, std::tr1::bind(handle_search, &count, key, _1, _2, _3));
cl.flush(-1);
if (count < 1)
{
std::cerr << "Equality returned less than 1 result." << std::endl;
}
if (count > 1)
{
std::cerr << "Equality returned more than 1 result." << std::endl;
}
count = 0;
std::map<std::string, std::pair<uint64_t, uint64_t> > range;
range.insert(std::make_pair("range", std::make_pair(num, num + 1)));
cl.search(argv[3], range, std::tr1::bind(handle_range, &count, key, _1, _2, _3));
cl.flush(-1);
if (count < 1)
{
std::cerr << "Range returned less than 1 result." << std::endl;
}
if (count > 1)
{
std::cerr << "Range returned more than 1 result." << std::endl;
}
}
clock_gettime(CLOCK_REALTIME, &end);
timespec diff;
if ((end.tv_nsec < start.tv_nsec) < 0)
{
diff.tv_sec = end.tv_sec - start.tv_sec - 1;
diff.tv_nsec = 1000000000 + end.tv_nsec - start.tv_nsec;
}
else
{
diff.tv_sec = end.tv_sec - start.tv_sec;
diff.tv_nsec = end.tv_nsec - start.tv_nsec;
}
uint64_t nanosecs = diff.tv_sec * 1000000000 + diff.tv_nsec;
std::cerr << "test took " << nanosecs << " nanoseconds for " << numbers << " searches" << std::endl;
}
catch (po6::error& e)
{
std::cerr << "There was a system error: " << e.what();
return EXIT_FAILURE;
}
catch (std::runtime_error& e)
{
std::cerr << "There was a runtime error: " << e.what();
return EXIT_FAILURE;
}
catch (std::bad_alloc& e)
{
std::cerr << "There was a memory allocation error: " << e.what();
return EXIT_FAILURE;
}
catch (std::exception& e)
{
std::cerr << "There was a generic error: " << e.what();
return EXIT_FAILURE;
}
return EXIT_SUCCESS;
}
int
usage()
{
std::cerr << "Usage: binary <coordinator ip> <coordinator port> <space name> <numbers>\n"
<< "This will create <numbers> points whose key is a number [0, <numbers>) and "
<< "then perform searches over the bits of the number. The space should have 32 "
<< "secondary dimensions so that all bits of a number may be stored."
<< std::endl;
return EXIT_FAILURE;
}
<|endoftext|> |
<commit_before>#include "condor_common.h"
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "condor_classad.h"
#include "proc_obj.h"
#include "dgram_io_handle.h"
#include "condor_attributes.h"
#include "condor_expressions.h"
#include "condor_collector.h"
int send_classad_to_machine(DGRAM_IO_HANDLE *UdpHandle, int cmd, const ClassAd* ad);
extern "C" {
int
send_classad_to_negotiator(DGRAM_IO_HANDLE *handle, CONTEXT *cp)
{
int ret;
ClassAd *ad;
ad = new ClassAd(cp);
ad->SetMyTypeName ("Machine");
ad->SetTargetTypeName ("Job");
ret = send_classad_to_machine(handle, UPDATE_STARTD_AD, ad);
delete ad;
return ret;
}
}
<commit_msg>replace XDR with condor_io<commit_after>#include "condor_common.h"
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include "condor_classad.h"
#include "proc_obj.h"
#include "dgram_io_handle.h"
#include "condor_attributes.h"
#include "condor_expressions.h"
#include "condor_collector.h"
#include "condor_io.h"
#include "condor_adtypes.h"
extern "C" {
int
send_classad_to_machine(char *host, int port, int sd, CONTEXT *cp)
{
ClassAd ad(cp);
SafeSock sock(host, port);
ad.SetMyTypeName (STARTD_ADTYPE);
ad.SetTargetTypeName (JOB_ADTYPE);
sock.attach_to_file_desc(sd);
sock.encode();
sock.put(UPDATE_STARTD_AD);
ad.put(sock);
sock.end_of_message();
return 0;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015-2016 Fotonic
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You can redistribute this code under either of these licenses.
* For more information; see http://www.arrowhead.eu/licensing
*/
/**
* @file
* @brief Service Registry interface implementation
*
* @author Joakim Gebart Nohlgård <joakim@nohlgard.se>
*/
#include "arrowhead/config.h"
#if ARROWHEAD_USE_LIBCURL
#include <string>
#include <iterator>
#include <sstream>
#include "arrowhead/core_services/serviceregistry.hpp"
namespace Arrowhead {
namespace {
/**
* @brief Perform a libcurl request and throw exception if an error occurs
*
* @param[in] ctx Context for the request
*
* @throw TransportError if libcurl signals an error
* @throw TransportError if the HTTP response code is not 200
*/
void libcurl_perform_checked_throw(HTTP::CURLContext& ctx)
{
/* Perform the request */
CURLcode curl_code = curl_easy_perform(ctx.curl);
/* Check for errors */
if (curl_code != CURLE_OK) {
std::ostringstream ss;
ss << "CURLError " << curl_code <<
": " << curl_easy_strerror(curl_code) <<
", " << ctx.errbuf;
throw TransportError(ss.str());
}
long http_code = 0;
curl_easy_getinfo (ctx.curl, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code != 200)
{
std::ostringstream ss;
ss << "HTTPError " << http_code;
/* Fail */
throw TransportError(ss.str());
}
}
}
std::string ServiceRegistryHTTP::list(std::string type)
{
ARROWHEAD_LIB_LOGGER(logger, "ServiceRegistryHTTP::list");
ARROWHEAD_LIB_TRACE(logger, "+ServiceRegistryHTTP::list");
HTTP::CURLContext ctx;
std::ostringstream buf;
/* Set URL */
std::string url = url_base;
if (!type.empty()) {
/* List only specific type of service */
url += "/type/" + type;
}
else {
/* List all services */
url += "/service";
}
curl_easy_setopt(ctx.curl, CURLOPT_URL, url.c_str());
/* Set Accept: header */
ctx.add_header("Accept: application/xml");
/* Set up callback */
ctx.set_write_iterator(std::ostream_iterator<char>(buf));
try {
libcurl_perform_checked_throw(ctx);
}
catch (TransportError &e) {
ARROWHEAD_LIB_ERROR(logger, e.what());
ARROWHEAD_LIB_DEBUG(logger, std::string("Remote said: ") + buf.str());
throw e;
}
/* Success, proceed with parsing XML */
return buf.str();
}
std::string ServiceRegistryHTTP::publish(ServiceDescription service)
{
ARROWHEAD_LIB_LOGGER(logger, "ServiceRegistryHTTP::publish");
ARROWHEAD_LIB_TRACE(logger, "+ServiceRegistryHTTP::publish");
HTTP::CURLContext ctx;
std::ostringstream buf;
std::ostringstream postdata;
/* Create request data */
postdata << "<service>";
postdata
<< "<domain>" << service.domain << "</domain>"
<< "<host>" << service.host << "</host>"
<< "<name>" << service.name << "</name>"
<< "<port>" << service.port << "</port>"
<< "<type>" << service.type << "</type>";
postdata << "<properties>";
for (auto& kv: service.properties) {
postdata << "<property>"
<< "<name>" << kv.first << "</name>"
<< "<value>" << kv.second << "</value>"
<< "</property>";
}
postdata << "</properties>";
postdata << "</service>";
ARROWHEAD_LIB_DEBUG(logger, "POST: " << postdata.str());
/* Set POST data */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDS, postdata.str().c_str());
/* if we don't provide POSTFIELDSIZE, libcurl will call strlen() by itself */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDSIZE, postdata.str().size());
/* Set URL */
std::string url = url_base + "/publish";
curl_easy_setopt(ctx.curl, CURLOPT_URL, url.c_str());
/* Set Accept: header */
ctx.add_header("Accept: application/xml");
/* Set Content-Type: header */
ctx.add_header("Content-Type: application/xml");
/* Set up callback */
ctx.set_write_iterator(std::ostream_iterator<char>(buf));
try {
libcurl_perform_checked_throw(ctx);
}
catch (TransportError &e) {
ARROWHEAD_LIB_ERROR(logger, e.what());
ARROWHEAD_LIB_DEBUG(logger, std::string("Remote said: ") + buf.str());
throw e;
}
/* Success, proceed with parsing XML */
ARROWHEAD_LIB_TRACE(logger, "-ServiceRegistryHTTP::publish");
return buf.str();
}
std::string ServiceRegistryHTTP::unpublish(std::string name)
{
ARROWHEAD_LIB_LOGGER(logger, "ServiceRegistryHTTP::unpublish");
ARROWHEAD_LIB_TRACE(logger, "+ServiceRegistryHTTP::unpublish");
HTTP::CURLContext ctx;
std::ostringstream buf;
std::ostringstream postdata;
/* Create request data, only the name is needed to unpublish something */
postdata << "<service>"
<< "<name>" << name << "</name>"
<< "</service>";
ARROWHEAD_LIB_DEBUG(logger, "POST: " << postdata.str());
/* Set POST data */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDS, postdata.str().c_str());
/* if we don't provide POSTFIELDSIZE, libcurl will call strlen() by itself */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDSIZE, postdata.str().size());
/* Set URL */
std::string url = url_base + "/unpublish";
curl_easy_setopt(ctx.curl, CURLOPT_URL, url.c_str());
/* Set Accept: header */
ctx.add_header("Accept: application/xml");
/* Set Content-Type: header */
ctx.add_header("Content-Type: application/xml");
/* Set up callback */
ctx.set_write_iterator(std::ostream_iterator<char>(buf));
try {
libcurl_perform_checked_throw(ctx);
}
catch (TransportError &e) {
ARROWHEAD_LIB_ERROR(logger, e.what());
ARROWHEAD_LIB_DEBUG(logger, std::string("Remote said: ") + buf.str());
throw e;
}
/* Success, proceed with parsing XML */
ARROWHEAD_LIB_TRACE(logger, "-ServiceRegistryHTTP::unpublish");
return buf.str();
}
} /* namespace Arrowhead */
#endif /* ARROWHEAD_USE_LIBCURL */
<commit_msg>ServiceRegistry: bugfix: Store POST data in a string while calling curl instead of discarding immediately<commit_after>/*
* Copyright (c) 2015-2016 Fotonic
*
* All rights reserved. This program and the accompanying materials
* are made available under the terms of the Eclipse Public License v1.0
* and Apache License v2.0 which accompanies this distribution.
*
* The Eclipse Public License is available at
* http://www.eclipse.org/legal/epl-v10.html
*
* The Apache License v2.0 is available at
* http://www.opensource.org/licenses/apache2.0.php
*
* You can redistribute this code under either of these licenses.
* For more information; see http://www.arrowhead.eu/licensing
*/
/**
* @file
* @brief Service Registry interface implementation
*
* @author Joakim Gebart Nohlgård <joakim@nohlgard.se>
*/
#include "arrowhead/config.h"
#if ARROWHEAD_USE_LIBCURL
#include <string>
#include <iterator>
#include <sstream>
#include "arrowhead/core_services/serviceregistry.hpp"
namespace Arrowhead {
namespace {
/**
* @brief Perform a libcurl request and throw exception if an error occurs
*
* @param[in] ctx Context for the request
*
* @throw TransportError if libcurl signals an error
* @throw TransportError if the HTTP response code is not 200
*/
void libcurl_perform_checked_throw(HTTP::CURLContext& ctx)
{
/* Perform the request */
CURLcode curl_code = curl_easy_perform(ctx.curl);
/* Check for errors */
if (curl_code != CURLE_OK) {
std::ostringstream ss;
ss << "CURLError " << curl_code <<
": " << curl_easy_strerror(curl_code) <<
", " << ctx.errbuf;
throw TransportError(ss.str());
}
long http_code = 0;
curl_easy_getinfo (ctx.curl, CURLINFO_RESPONSE_CODE, &http_code);
if (http_code != 200)
{
std::ostringstream ss;
ss << "HTTPError " << http_code;
/* Fail */
throw TransportError(ss.str());
}
}
}
std::string ServiceRegistryHTTP::list(std::string type)
{
ARROWHEAD_LIB_LOGGER(logger, "ServiceRegistryHTTP::list");
ARROWHEAD_LIB_TRACE(logger, "+ServiceRegistryHTTP::list");
HTTP::CURLContext ctx;
std::ostringstream buf;
/* Set URL */
std::string url = url_base;
if (!type.empty()) {
/* List only specific type of service */
url += "/type/" + type;
}
else {
/* List all services */
url += "/service";
}
curl_easy_setopt(ctx.curl, CURLOPT_URL, url.c_str());
/* Set Accept: header */
ctx.add_header("Accept: application/xml");
/* Set up callback */
ctx.set_write_iterator(std::ostream_iterator<char>(buf));
try {
libcurl_perform_checked_throw(ctx);
}
catch (TransportError &e) {
ARROWHEAD_LIB_ERROR(logger, e.what());
ARROWHEAD_LIB_DEBUG(logger, std::string("Remote said: ") + buf.str());
throw e;
}
/* Success, proceed with parsing XML */
return buf.str();
}
std::string ServiceRegistryHTTP::publish(ServiceDescription service)
{
ARROWHEAD_LIB_LOGGER(logger, "ServiceRegistryHTTP::publish");
ARROWHEAD_LIB_TRACE(logger, "+ServiceRegistryHTTP::publish");
HTTP::CURLContext ctx;
std::ostringstream buf;
std::ostringstream postdata;
/* Create request data */
postdata << "<service>";
postdata
<< "<domain>" << service.domain << "</domain>"
<< "<host>" << service.host << "</host>"
<< "<name>" << service.name << "</name>"
<< "<port>" << service.port << "</port>"
<< "<type>" << service.type << "</type>";
postdata << "<properties>";
for (auto& kv: service.properties) {
postdata << "<property>"
<< "<name>" << kv.first << "</name>"
<< "<value>" << kv.second << "</value>"
<< "</property>";
}
postdata << "</properties>";
postdata << "</service>";
ARROWHEAD_LIB_DEBUG(logger, "POST: " << postdata.str());
std::string poststr = postdata.str();
/* Set POST data */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDS, poststr.c_str());
/* if we don't provide POSTFIELDSIZE, libcurl will call strlen() by itself */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDSIZE, poststr.size());
/* Set URL */
std::string url = url_base + "/publish";
curl_easy_setopt(ctx.curl, CURLOPT_URL, url.c_str());
/* Set Accept: header */
ctx.add_header("Accept: application/xml");
/* Set Content-Type: header */
ctx.add_header("Content-Type: application/xml");
/* Set up callback */
ctx.set_write_iterator(std::ostream_iterator<char>(buf));
try {
libcurl_perform_checked_throw(ctx);
}
catch (TransportError &e) {
ARROWHEAD_LIB_ERROR(logger, e.what());
ARROWHEAD_LIB_DEBUG(logger, std::string("Remote said: ") + buf.str());
throw e;
}
/* Success, proceed with parsing XML */
ARROWHEAD_LIB_TRACE(logger, "-ServiceRegistryHTTP::publish");
return buf.str();
}
std::string ServiceRegistryHTTP::unpublish(std::string name)
{
ARROWHEAD_LIB_LOGGER(logger, "ServiceRegistryHTTP::unpublish");
ARROWHEAD_LIB_TRACE(logger, "+ServiceRegistryHTTP::unpublish");
HTTP::CURLContext ctx;
std::ostringstream buf;
std::ostringstream postdata;
/* Create request data, only the name is needed to unpublish something */
postdata << "<service>"
<< "<name>" << name << "</name>"
<< "</service>";
ARROWHEAD_LIB_DEBUG(logger, "POST: " << postdata.str());
/* Set POST data */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDS, postdata.str().c_str());
/* if we don't provide POSTFIELDSIZE, libcurl will call strlen() by itself */
curl_easy_setopt(ctx.curl, CURLOPT_POSTFIELDSIZE, postdata.str().size());
/* Set URL */
std::string url = url_base + "/unpublish";
curl_easy_setopt(ctx.curl, CURLOPT_URL, url.c_str());
/* Set Accept: header */
ctx.add_header("Accept: application/xml");
/* Set Content-Type: header */
ctx.add_header("Content-Type: application/xml");
/* Set up callback */
ctx.set_write_iterator(std::ostream_iterator<char>(buf));
try {
libcurl_perform_checked_throw(ctx);
}
catch (TransportError &e) {
ARROWHEAD_LIB_ERROR(logger, e.what());
ARROWHEAD_LIB_DEBUG(logger, std::string("Remote said: ") + buf.str());
throw e;
}
/* Success, proceed with parsing XML */
ARROWHEAD_LIB_TRACE(logger, "-ServiceRegistryHTTP::unpublish");
return buf.str();
}
} /* namespace Arrowhead */
#endif /* ARROWHEAD_USE_LIBCURL */
<|endoftext|> |
<commit_before>#include "ImgProcThread.h"
#include <time.h>
namespace cvImagePipeline {
namespace Filter {
IMPLEMENT_CVFILTER(ImgProcThread);
ImgProcThread::ImgProcThread()
: runProcessorThread(false), thead_handle(INVALID_HANDLE_VALUE), interval(0),
eventHandle(INVALID_HANDLE_VALUE)
{
::InitializeCriticalSection(&cs);
}
ImgProcThread::~ImgProcThread() {
::DeleteCriticalSection(&cs);
}
void ImgProcThread::addThreadSafeOutput(const std::string& name, ImageProcessor& src) {
threadShareInnerMat.add("ImagePoint", name, false);
threadShareOutputMat.add("ImagePoint", name, false);
threadShareInnerMat[name].setInputMat(src.getOutputMat());
threadShareOutputMat[name].setInputMat(threadShareInnerMat[name].getOutputMat());
}
void ImgProcThread::startThread(int interval /* = 0 */) {
eventHandle = CreateEvent(NULL, false, false, getName().c_str());
runProcessorThread = true;
this->interval = interval;
thead_handle = ::CreateThread(0,0,
(LPTHREAD_START_ROUTINE)ImgProcThread::Thread,(LPVOID)this,
0,NULL);
}
void ImgProcThread::stopThread() {
runProcessorThread = false;
WaitForSingleObject(thead_handle, INFINITE);
CloseHandle(eventHandle);
}
void ImgProcThread::execute() {
ImgProcSet::execute();
EnterCriticalSection();
threadShareInnerMat.execute();
LeaveCriticalSection();
SetEvent(eventHandle);
}
void ImgProcThread::EnterCriticalSection() {
::EnterCriticalSection(&cs);
}
void ImgProcThread::LeaveCriticalSection() {
::LeaveCriticalSection(&cs);
}
bool ImgProcThread::WaitEvent(DWORD timeout) {
DWORD waitResult = WaitForSingleObject(eventHandle, timeout);
return (waitResult == WAIT_OBJECT_0);
}
void ImgProcThread::updateSharedOutputMat() {
EnterCriticalSection();
threadShareOutputMat.execute();
LeaveCriticalSection();
}
const cv::Mat& ImgProcThread::refThreadShareOutput(const std::string& name) const {
return ((ImgProcSet&)threadShareOutputMat)[name].getOutputMat();
}
DWORD WINAPI ImgProcThread::Thread(LPVOID *data) {
ImgProcThread* processor = (ImgProcThread*)data;
std::cerr << processor->getName() << " started." << std::endl;
clock_t t0 = clock();
while(processor->runProcessorThread) {
processor->execute();
if(processor->interval > 0) {
clock_t t1;
while((t1 = clock()) - t0 < processor->interval) {
Sleep(processor->interval / 10);
}
t0 = t1;
} else {
Sleep(0);
}
}
std::cerr << processor->getName() << " end." << std::endl;
return 0;
}
}
}
<commit_msg>print thread info when _DEBUG is defined.<commit_after>#include "ImgProcThread.h"
#include <time.h>
namespace cvImagePipeline {
namespace Filter {
IMPLEMENT_CVFILTER(ImgProcThread);
ImgProcThread::ImgProcThread()
: runProcessorThread(false), thead_handle(INVALID_HANDLE_VALUE), interval(0),
eventHandle(INVALID_HANDLE_VALUE)
{
::InitializeCriticalSection(&cs);
}
ImgProcThread::~ImgProcThread() {
::DeleteCriticalSection(&cs);
}
void ImgProcThread::addThreadSafeOutput(const std::string& name, ImageProcessor& src) {
threadShareInnerMat.add("ImagePoint", name, false);
threadShareOutputMat.add("ImagePoint", name, false);
threadShareInnerMat[name].setInputMat(src.getOutputMat());
threadShareOutputMat[name].setInputMat(threadShareInnerMat[name].getOutputMat());
}
void ImgProcThread::startThread(int interval /* = 0 */) {
eventHandle = CreateEvent(NULL, false, false, getName().c_str());
runProcessorThread = true;
this->interval = interval;
thead_handle = ::CreateThread(0,0,
(LPTHREAD_START_ROUTINE)ImgProcThread::Thread,(LPVOID)this,
0,NULL);
}
void ImgProcThread::stopThread() {
runProcessorThread = false;
WaitForSingleObject(thead_handle, INFINITE);
CloseHandle(eventHandle);
}
void ImgProcThread::execute() {
ImgProcSet::execute();
EnterCriticalSection();
threadShareInnerMat.execute();
LeaveCriticalSection();
SetEvent(eventHandle);
}
void ImgProcThread::EnterCriticalSection() {
::EnterCriticalSection(&cs);
}
void ImgProcThread::LeaveCriticalSection() {
::LeaveCriticalSection(&cs);
}
bool ImgProcThread::WaitEvent(DWORD timeout) {
DWORD waitResult = WaitForSingleObject(eventHandle, timeout);
return (waitResult == WAIT_OBJECT_0);
}
void ImgProcThread::updateSharedOutputMat() {
EnterCriticalSection();
threadShareOutputMat.execute();
LeaveCriticalSection();
}
const cv::Mat& ImgProcThread::refThreadShareOutput(const std::string& name) const {
return ((ImgProcSet&)threadShareOutputMat)[name].getOutputMat();
}
DWORD WINAPI ImgProcThread::Thread(LPVOID *data) {
ImgProcThread* processor = (ImgProcThread*)data;
#ifdef _DEBUG
std::cerr << processor->getName() << " started." << std::endl;
#endif
clock_t t0 = clock();
while(processor->runProcessorThread) {
processor->execute();
if(processor->interval > 0) {
clock_t t1;
while((t1 = clock()) - t0 < processor->interval) {
Sleep(processor->interval / 10);
}
t0 = t1;
} else {
Sleep(0);
}
}
#ifdef _DEBUG
std::cerr << processor->getName() << " end." << std::endl;
#endif
return 0;
}
}
}
<|endoftext|> |
<commit_before>#include "linalg.h"
#include <gsl/gsl_linalg.h>
namespace votca { namespace tools {
void linalg_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b)
{
// now A is a tridiagonal system, solve it!
double* pointer_m = &A(0,0);
double* pointer_b = &b(0);
const int N = x.size();
gsl_matrix_view m
= gsl_matrix_view_array (pointer_m, N, N);
gsl_vector_view gb
= gsl_vector_view_array (pointer_b, N);
gsl_vector *gx = gsl_vector_alloc (N);
gsl_vector *tau = gsl_vector_alloc (N);
gsl_vector *residual = gsl_vector_alloc (N);
gsl_linalg_QR_decomp (&m.matrix, tau);
gsl_linalg_QR_lssolve (&m.matrix, tau, &gb.vector, gx, residual);
for (int i =0 ; i < N; i++) {
x(i) = gsl_vector_get(gx, i);
}
gsl_vector_free (gx);
gsl_vector_free (tau);
gsl_vector_free (residual);
}
void linalg_constrained_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b, ub::matrix<double> &constr)
{
// Transpose constr:
constr = trans(constr);
const int N = b.size();
const int ngrid = x.size()/2;
// temporary variables
ub::matrix<double> Q(2*ngrid, 2*ngrid); // Q matrix: QR decomposition of trans(B)
ub::matrix<double> A2(N, ngrid); // Matrix A2 (see manual)
ub::matrix<double> Q_k(2*ngrid, 2*ngrid);
ub::identity_matrix<double> I (2*ngrid);
ub::vector<double> v(2*ngrid);
Q = ub::zero_matrix<double>(2*ngrid, 2*ngrid);
A2 = ub::zero_matrix<double>(N, ngrid);
Q_k = ub::zero_matrix<double>(2*ngrid, 2*ngrid);
v = ub::zero_vector<double>(2*ngrid);
double* pointer_m = & constr(0,0);
gsl_matrix_view B_t
= gsl_matrix_view_array (pointer_m, constr.size1(), constr.size2());
gsl_vector *tau_qr = gsl_vector_alloc (ngrid);
gsl_linalg_QR_decomp (&B_t.matrix, tau_qr);
Q = I;
for (int k = ngrid; k > 0 ; k--) {
for (int icout = 0; icout < k - 1; icout++) {
v(icout) = 0;
}
v(k - 1) = 1.0;
for (int icout = k; icout < 2*ngrid; icout++) {
v(icout) = gsl_matrix_get(&B_t.matrix, icout, k - 1 );
}
Q_k = I - gsl_vector_get(tau_qr, k - 1 ) * outer_prod ( v, v );
Q = prec_prod(Q, Q_k);
}
Q = trans(Q);
gsl_vector_free (tau_qr);
// Calculate A * Q and store the result in A
A = prec_prod(A, Q);
// A = [A1 A2], so A2 is just a block of A
for (int iraw = 0; iraw < N; iraw++) {
for (int icol = ngrid; icol < 2*ngrid; icol++) {
A2(iraw, icol - ngrid) = A(iraw, icol);
}
}
pointer_m = & A2(0,0);
double* pointer_b = & b(0);
gsl_matrix_view m
= gsl_matrix_view_array (pointer_m, N, ngrid);
gsl_vector_view gsl_b
= gsl_vector_view_array (pointer_b, N);
gsl_vector *z = gsl_vector_alloc (ngrid);
gsl_vector *tau_solve = gsl_vector_alloc (ngrid); // already done!
gsl_vector *residual = gsl_vector_alloc (N);
gsl_linalg_QR_decomp (&m.matrix, tau_solve);
gsl_linalg_QR_lssolve (&m.matrix, tau_solve, &gsl_b.vector, z, residual);
// Next two cycles assemble vector from y (which is zero-vector) and z
// (which we just got by gsl_linalg_QR_lssolve)
for (int i = 0; i < ngrid; i++ ) {
x[i] = 0.0;
}
for (int i = ngrid; i < 2 * ngrid; i++ ) {
x[i] = gsl_vector_get(z, i - ngrid);
}
// To get the final answer this vector should be multiplied by matrix Q
// TODO: here i changed the sign, check again! (victor)
x = -prec_prod( Q, x );
gsl_vector_free (z);
gsl_vector_free (tau_solve);
gsl_vector_free (residual);
}
}}
<commit_msg>qrsolve sizes should be ok now, bit of cleaning<commit_after>#include "linalg.h"
#include <gsl/gsl_linalg.h>
#include <boost/numeric/ublas/matrix_proxy.hpp>
namespace votca { namespace tools {
void linalg_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b)
{
gsl_matrix_view m
= gsl_matrix_view_array (&A(0,0), A.size1(), A.size2());
gsl_vector_view gb
= gsl_vector_view_array (&b(0), b.size());
gsl_vector *gsl_x = gsl_vector_alloc (x.size());
gsl_vector *tau = gsl_vector_alloc (x.size());
gsl_vector *residual = gsl_vector_alloc (b.size());
gsl_linalg_QR_decomp (&m.matrix, tau);
gsl_linalg_QR_lssolve (&m.matrix, tau, &gb.vector, gsl_x, residual);
for (int i =0 ; i < x.size(); i++)
x(i) = gsl_vector_get(gsl_x, i);
gsl_vector_free (gsl_x);
gsl_vector_free (tau);
gsl_vector_free (residual);
}
void linalg_constrained_qrsolve(ub::vector<double> &x, ub::matrix<double> &A, ub::vector<double> &b, ub::matrix<double> &constr)
{
// Transpose constr:
constr = trans(constr);
const int N = b.size();
const int ngrid = x.size()/2;
// temporary variables
ub::matrix<double> Q(2*ngrid, 2*ngrid); // Q matrix: QR decomposition of trans(B)
ub::matrix<double> Q_k(2*ngrid, 2*ngrid);
ub::identity_matrix<double> I (2*ngrid);
ub::vector<double> v(2*ngrid);
Q = ub::zero_matrix<double>(2*ngrid, 2*ngrid);
Q_k = ub::zero_matrix<double>(2*ngrid, 2*ngrid);
v = ub::zero_vector<double>(2*ngrid);
double *tmp = & constr(0,0);
gsl_matrix_view gsl_constr
= gsl_matrix_view_array (tmp, constr.size1(), constr.size2());
tmp = &b(0);
gsl_vector_view gsl_b
= gsl_vector_view_array (tmp, b.size());
gsl_vector *tau_qr = gsl_vector_alloc (ngrid);
gsl_linalg_QR_decomp (&gsl_constr.matrix, tau_qr);
Q = I;
for (int k = ngrid; k > 0 ; k--) {
for (int icout = 0; icout < k - 1; icout++) {
v(icout) = 0;
}
v(k - 1) = 1.0;
for (int icout = k; icout < 2*ngrid; icout++) {
v(icout) = gsl_matrix_get(&gsl_constr.matrix, icout, k - 1 );
}
Q_k = I - gsl_vector_get(tau_qr, k - 1 ) * outer_prod ( v, v );
Q = prec_prod(Q, Q_k);
}
Q = trans(Q);
gsl_vector_free (tau_qr);
// Calculate A * Q and store the result in A
A = prec_prod(A, Q);
// A = [A1 A2], so A2 is just a block of A
ub::matrix<double> A2 = ub::matrix_range<ub::matrix<double> >(A,
ub::range (0, N), ub::range (ngrid, 2*ngrid)
);
tmp = &A2(0,0);
gsl_matrix_view gsl_A2
= gsl_matrix_view_array (tmp, A2.size1(), A2.size2());
gsl_vector *z = gsl_vector_alloc (ngrid);
gsl_vector *tau_solve = gsl_vector_alloc (ngrid); // already done!
gsl_vector *residual = gsl_vector_alloc (N);
gsl_linalg_QR_decomp (&gsl_A2.matrix, tau_solve);
gsl_linalg_QR_lssolve (&gsl_A2.matrix, tau_solve, &gsl_b.vector, z, residual);
// Next two cycles assemble vector from y (which is zero-vector) and z
// (which we just got by gsl_linalg_QR_lssolve)
for (int i = 0; i < ngrid; i++ ) {
x[i] = 0.0;
}
for (int i = ngrid; i < 2 * ngrid; i++ ) {
x[i] = gsl_vector_get(z, i - ngrid);
}
// To get the final answer this vector should be multiplied by matrix Q
// TODO: here i changed the sign, check again! (victor)
x = -prec_prod( Q, x );
gsl_vector_free (z);
gsl_vector_free (tau_solve);
gsl_vector_free (residual);
}
}}
<|endoftext|> |
<commit_before>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2020 projectchrono.org
// All rights 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: Radu Serban
// =============================================================================
//
// Demo for using the third-party library 'filesystem' for file and directory
// operations.
// Note that the version distributed with Chrono includes some extensions:
// path::stem
// extracts the stem (basename) for a file, by stripping extension
// from the filename.
// create_subdirectory
// utility function for creating a hierarchy of nested directories,
// creating all intermediate subdirectories as needed.
//
// =============================================================================
#include <iostream>
#include "chrono_thirdparty/filesystem/path.h"
#include "chrono_thirdparty/filesystem/resolver.h"
#include "chrono/utils/ChUtilsInputOutput.h"
using namespace filesystem;
using namespace chrono;
using std::cout;
using std::endl;
int main(int argc, char** argv) {
#if defined(WIN32)
path path1("C:\\dir 1\\dir 2\\");
#else
path path1("/dir 1/dir 2/");
#endif
path path2("dir 3");
cout << path1.exists() << endl;
cout << path1 << endl;
cout << (path1/path2) << endl;
cout << (path1/path2).parent_path() << endl;
cout << (path1/path2).parent_path().parent_path() << endl;
cout << (path1/path2).parent_path().parent_path().parent_path() << endl;
cout << (path1/path2).parent_path().parent_path().parent_path().parent_path() << endl;
cout << path().parent_path() << endl;
// Absolute path of current directory
cout << endl;
cout << "Current directory = " << path(".").make_absolute() << endl;
// Create output directory and output file
std::string out_dir = GetChronoOutputPath() + "DEMO_FILESYSTEM";
std::string out_file = out_dir + "/foo.txt";
bool out_dir_exists = path(out_dir).exists();
if (out_dir_exists) {
cout << "Output directory already exists" << endl;
} else if (create_directory(path(out_dir))) {
cout << "Create directory = " << path(out_dir).make_absolute() << endl;
} else {
cout << "Error creating output directory" << endl;
return 1;
}
cout << "Output directory exists = " << path(out_dir).exists() << endl;
cout << " dir name: " << out_dir << endl;
cout << " path of dir: " << path(out_dir) << endl;
cout << " abs. path of dir: " << path(out_dir).make_absolute() << endl;
cout << "Create output file" << endl;
cout << " file name: " << out_file << endl;
cout << " path of file: " << path(out_file) << endl;
cout << " abs. path of file: " << path(out_file).make_absolute() << endl;
utils::CSV_writer csv(",");
csv << ChVector<>(1, 2, 3) << ChQuaternion<>(1, 0, 0, 0) << endl;
csv.write_to_file(out_file);
cout << "Output file exists = " << path(out_file).exists() << endl;
cout << "Output file is file = " << path(out_file).is_file() << endl;
cout << endl;
// Create hierarchy of nested directories
#if defined(WIN32)
std::string nested = out_dir + "\\child\\grandchild";
#else
std::string nested = out_dir + "/child/grandchild";
#endif
cout << "nested (as string) = " << nested << endl;
cout << "nested (as path) = " << path(nested) << endl;
cout << "length of nested = " << path(nested).length() << endl;
if (create_subdirectory(path(nested)))
cout << "created nested subdirectories" << endl;
else
cout << "Error creating subdirectories" << endl;
cout << endl;
// Other tests
cout << "some/path.ext:operator==() = " << (path("some/path.ext") == path("some/path.ext")) << endl;
cout << "some/path.ext:operator==() (unequal) = " << (path("some/path.ext") == path("another/path.ext")) << endl;
cout << "nonexistant:exists = " << path("nonexistant").exists() << endl;
cout << "nonexistant:is_file = " << path("nonexistant").is_file() << endl;
cout << "nonexistant:is_directory = " << path("nonexistant").is_directory() << endl;
cout << "nonexistant:filename = " << path("nonexistant").filename() << endl;
cout << "nonexistant:extension = " << path("nonexistant").extension() << endl;
cout << endl;
cout << "out_file:exists = " << path(out_file).exists() << endl;
cout << "out_file:is_file = " << path(out_file).is_file() << endl;
cout << "out_file:is_directory = " << path(out_file).is_directory() << endl;
cout << "out_file:filename = " << path(out_file).filename() << endl;
cout << "out_file:stem = " << path(out_file).stem() << endl;
cout << "out_file:extension = " << path(out_file).extension() << endl;
cout << "out_file:make_absolute = " << path(out_file).make_absolute() << endl;
cout << endl;
cout << "out_dir:exists = " << path(out_dir).exists() << endl;
cout << "out_dir:is_file = " << path(out_dir).is_file() << endl;
cout << "out_dir:is_directory = " << path(out_dir).is_directory() << endl;
cout << "out_dir:filename = " << path(out_dir).filename() << endl;
cout << "out_dir:stem = " << path(out_dir).stem() << endl;
cout << "out_dir:extension = " << path(out_dir).extension() << endl;
cout << "out_dir:make_absolute = " << path(out_dir).make_absolute() << endl;
cout << endl;
cout << "resolve(out_file) = " << resolver().resolve(out_file) << endl;
cout << "resolve(nonexistant) = " << resolver().resolve("nonexistant") << endl;
return 0;
}
<commit_msg>Clean up demo_CH_filesystem<commit_after>// =============================================================================
// PROJECT CHRONO - http://projectchrono.org
//
// Copyright (c) 2020 projectchrono.org
// All rights 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: Radu Serban
// =============================================================================
//
// Demo for using the third-party library 'filesystem' for file and directory
// operations.
// Note that the version distributed with Chrono includes some extensions:
// path::stem
// extracts the stem (basename) for a file, by stripping extension
// from the filename.
// create_subdirectory
// utility function for creating a hierarchy of nested directories,
// creating all intermediate subdirectories as needed.
//
// =============================================================================
#include <iostream>
#include "chrono_thirdparty/filesystem/path.h"
#include "chrono_thirdparty/filesystem/resolver.h"
#include "chrono/utils/ChUtilsInputOutput.h"
using namespace filesystem;
using namespace chrono;
using std::cout;
using std::endl;
int main(int argc, char** argv) {
#if defined(WIN32)
path path1("C:\\dir 1\\dir 2\\");
#else
path path1("/dir 1/dir 2/");
#endif
path path2("dir 3");
cout << path1.exists() << endl;
cout << path1 << endl;
cout << (path1 / path2) << endl;
cout << (path1 / path2).parent_path() << endl;
cout << (path1 / path2).parent_path().parent_path() << endl;
cout << (path1 / path2).parent_path().parent_path().parent_path() << endl;
cout << (path1 / path2).parent_path().parent_path().parent_path().parent_path() << endl;
cout << path().parent_path() << endl;
cout << endl;
// Absolute path of current directory
cout << "Current directory = " << path(".").make_absolute() << endl;
cout << endl;
// Create output directory and output file
std::string out_dir = GetChronoOutputPath() + "DEMO_FILESYSTEM";
std::string out_file = out_dir + "/foo.txt";
cout << "Create output directory; out_dir = " << out_dir << endl;
cout << " out_dir exists? " << path(out_dir).exists() << endl;
if (create_directory(path(out_dir))) {
cout << " ...Created output directory" << endl;
} else {
cout << " ...Error creating output directory" << endl;
return 1;
}
cout << " out_dir exists? " << path(out_dir).exists() << endl;
cout << " out_dir is directory? " << path(out_dir).is_directory() << endl;
cout << " path of out_dir: " << path(out_dir) << endl;
cout << " abs. path of out_dir: " << path(out_dir).make_absolute() << endl;
cout << endl;
cout << "Create output file; out_file = " << out_file << endl;
cout << " out_file exists? " << path(out_file).exists() << endl;
utils::CSV_writer csv(",");
csv << ChVector<>(1, 2, 3) << ChQuaternion<>(1, 0, 0, 0) << endl;
csv.write_to_file(out_file);
cout << " ...Created output file" << endl;
cout << " out_file exists? " << path(out_file).exists() << endl;
cout << " out_file is file? " << path(out_file).is_file() << endl;
cout << " path of out_file: " << path(out_file) << endl;
cout << " abs. path of out_file: " << path(out_file).make_absolute() << endl;
cout << endl;
// Create hierarchy of nested directories
#if defined(WIN32)
std::string nested = out_dir + "\\child\\grandchild";
#else
std::string nested = out_dir + "/child/grandchild";
#endif
cout << "Create nested directories; nested = " << nested << endl;
cout << " nested (as path) = " << path(nested) << endl;
cout << " length of nested = " << path(nested).length() << endl;
cout << " nested exists? " << path(nested).exists() << endl;
if (create_subdirectory(path(nested))) {
cout << " ...Created nested subdirectories" << endl;
} else {
cout << " ...Error creating subdirectories" << endl;
return 1;
}
cout << " nested exists? " << path(nested).exists() << endl;
cout << " nested is directory? " << path(nested).is_directory() << endl;
cout << " path of nested: " << path(nested) << endl;
cout << " abs. path of nested: " << path(nested).make_absolute() << endl;
cout << endl;
// Other tests
cout << "some/path.ext:operator==() = " << (path("some/path.ext") == path("some/path.ext")) << endl;
cout << "some/path.ext:operator==() (unequal) = " << (path("some/path.ext") == path("another/path.ext")) << endl;
cout << "nonexistant:exists = " << path("nonexistant").exists() << endl;
cout << "nonexistant:is_file = " << path("nonexistant").is_file() << endl;
cout << "nonexistant:is_directory = " << path("nonexistant").is_directory() << endl;
cout << "nonexistant:filename = " << path("nonexistant").filename() << endl;
cout << "nonexistant:extension = " << path("nonexistant").extension() << endl;
cout << endl;
cout << "out_file:exists = " << path(out_file).exists() << endl;
cout << "out_file:is_file = " << path(out_file).is_file() << endl;
cout << "out_file:is_directory = " << path(out_file).is_directory() << endl;
cout << "out_file:filename = " << path(out_file).filename() << endl;
cout << "out_file:stem = " << path(out_file).stem() << endl;
cout << "out_file:extension = " << path(out_file).extension() << endl;
cout << "out_file:make_absolute = " << path(out_file).make_absolute() << endl;
cout << endl;
cout << "out_dir:exists = " << path(out_dir).exists() << endl;
cout << "out_dir:is_file = " << path(out_dir).is_file() << endl;
cout << "out_dir:is_directory = " << path(out_dir).is_directory() << endl;
cout << "out_dir:filename = " << path(out_dir).filename() << endl;
cout << "out_dir:stem = " << path(out_dir).stem() << endl;
cout << "out_dir:extension = " << path(out_dir).extension() << endl;
cout << "out_dir:make_absolute = " << path(out_dir).make_absolute() << endl;
cout << endl;
cout << "resolve(out_file) = " << resolver().resolve(out_file) << endl;
cout << "resolve(nonexistant) = " << resolver().resolve("nonexistant") << endl;
return 0;
}
<|endoftext|> |
<commit_before>/**********************************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2014 NAN contributors
*
* MIT +no-false-attribs License <https://github.com/rvagg/nan/blob/master/LICENSE>
**********************************************************************************/
#include <nan.h>
static v8::Persistent<v8::Function> callback;
NAN_GC_CALLBACK(gcPrologueCallback) {
v8::Local<v8::Value> argv[] = {NanNew<v8::String>("prologue")};
NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv);
}
NAN_GC_CALLBACK(gcEpilogueCallback) {
v8::Local<v8::Value> argv[] = {NanNew<v8::String>("epilogue")};
NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv);
}
NAN_METHOD(Hook) {
NanScope();
NanAssignPersistent(callback, args[0].As<v8::Function>());
NanAddGCPrologueCallback(gcPrologueCallback);
NanAddGCEpilogueCallback(gcEpilogueCallback);
NanReturnValue(args.Holder());
}
void Init (v8::Handle<v8::Object> target) {
target->Set(
NanNew<v8::String>("hook")
, NanNew<v8::FunctionTemplate>(Hook)->GetFunction()
);
}
NODE_MODULE(gc, Init)
<commit_msg>Update gc.cpp<commit_after>/**********************************************************************************
* NAN - Native Abstractions for Node.js
*
* Copyright (c) 2014 NAN contributors
*
* MIT License <https://github.com/rvagg/nan/blob/master/LICENSE>
**********************************************************************************/
#include <nan.h>
static v8::Persistent<v8::Function> callback;
NAN_GC_CALLBACK(gcPrologueCallback) {
v8::Local<v8::Value> argv[] = {NanNew<v8::String>("prologue")};
NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv);
}
NAN_GC_CALLBACK(gcEpilogueCallback) {
v8::Local<v8::Value> argv[] = {NanNew<v8::String>("epilogue")};
NanMakeCallback(NanGetCurrentContext()->Global(), NanNew(callback), 1, argv);
}
NAN_METHOD(Hook) {
NanScope();
NanAssignPersistent(callback, args[0].As<v8::Function>());
NanAddGCPrologueCallback(gcPrologueCallback);
NanAddGCEpilogueCallback(gcEpilogueCallback);
NanReturnValue(args.Holder());
}
void Init (v8::Handle<v8::Object> target) {
target->Set(
NanNew<v8::String>("hook")
, NanNew<v8::FunctionTemplate>(Hook)->GetFunction()
);
}
NODE_MODULE(gc, Init)
<|endoftext|> |
<commit_before>#include "listformaction.h"
#include "rssfeed.h"
#include "view.h"
namespace newsboat {
ListFormAction::ListFormAction(View* v,
std::string formstr,
std::string list_name,
ConfigContainer* cfg)
: FormAction(v, formstr, cfg)
, list(list_name, FormAction::f, cfg->get_configvalue_as_int("scrolloff"))
{
}
bool ListFormAction::process_operation(Operation op,
bool,
std::vector<std::string>*)
{
switch (op) {
case OP_CMD_START_1:
FormAction::start_cmdline("1");
break;
case OP_CMD_START_2:
FormAction::start_cmdline("2");
break;
case OP_CMD_START_3:
FormAction::start_cmdline("3");
break;
case OP_CMD_START_4:
FormAction::start_cmdline("4");
break;
case OP_CMD_START_5:
FormAction::start_cmdline("5");
break;
case OP_CMD_START_6:
FormAction::start_cmdline("6");
break;
case OP_CMD_START_7:
FormAction::start_cmdline("7");
break;
case OP_CMD_START_8:
FormAction::start_cmdline("8");
break;
case OP_CMD_START_9:
FormAction::start_cmdline("9");
break;
case OP_SK_UP:
list.move_up(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
case OP_SK_DOWN:
list.move_down(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
case OP_SK_HOME:
list.move_to_first();
break;
case OP_SK_END:
list.move_to_last();
break;
case OP_SK_PGUP:
list.move_page_up(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
case OP_SK_PGDOWN:
list.move_page_down(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
default:
break;
}
return true;
}
nonstd::optional<std::uint8_t> ListFormAction::open_unread_items_in_browser(
std::shared_ptr<RssFeed> feed,
bool markread)
{
int tabcount = 0;
for (const auto& item : feed->items()) {
if (tabcount <
cfg->get_configvalue_as_int("max-browser-tabs")) {
if (item->unread()) {
const bool interactive = true;
const auto exit_code = v->open_in_browser(item->link(), item->feedurl(),
interactive);
if (!exit_code.has_value() || *exit_code != 0) {
return exit_code;
}
tabcount += 1;
if (markread) {
item->set_unread(false);
v->get_ctrl()->mark_article_read(item->guid(), true);
}
}
} else {
break;
}
}
return 0;
}
} // namespace newsboat
<commit_msg>Let remote APIs combine multiple article-read updates<commit_after>#include "listformaction.h"
#include "rssfeed.h"
#include "view.h"
namespace newsboat {
ListFormAction::ListFormAction(View* v,
std::string formstr,
std::string list_name,
ConfigContainer* cfg)
: FormAction(v, formstr, cfg)
, list(list_name, FormAction::f, cfg->get_configvalue_as_int("scrolloff"))
{
}
bool ListFormAction::process_operation(Operation op,
bool,
std::vector<std::string>*)
{
switch (op) {
case OP_CMD_START_1:
FormAction::start_cmdline("1");
break;
case OP_CMD_START_2:
FormAction::start_cmdline("2");
break;
case OP_CMD_START_3:
FormAction::start_cmdline("3");
break;
case OP_CMD_START_4:
FormAction::start_cmdline("4");
break;
case OP_CMD_START_5:
FormAction::start_cmdline("5");
break;
case OP_CMD_START_6:
FormAction::start_cmdline("6");
break;
case OP_CMD_START_7:
FormAction::start_cmdline("7");
break;
case OP_CMD_START_8:
FormAction::start_cmdline("8");
break;
case OP_CMD_START_9:
FormAction::start_cmdline("9");
break;
case OP_SK_UP:
list.move_up(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
case OP_SK_DOWN:
list.move_down(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
case OP_SK_HOME:
list.move_to_first();
break;
case OP_SK_END:
list.move_to_last();
break;
case OP_SK_PGUP:
list.move_page_up(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
case OP_SK_PGDOWN:
list.move_page_down(cfg->get_configvalue_as_bool("wrap-scroll"));
break;
default:
break;
}
return true;
}
nonstd::optional<std::uint8_t> ListFormAction::open_unread_items_in_browser(
std::shared_ptr<RssFeed> feed,
bool markread)
{
int tabcount = 0;
nonstd::optional<std::uint8_t> return_value = 0;
std::vector<std::string> guids_of_read_articles;
for (const auto& item : feed->items()) {
if (tabcount <
cfg->get_configvalue_as_int("max-browser-tabs")) {
if (item->unread()) {
const bool interactive = true;
const auto exit_code = v->open_in_browser(item->link(), item->feedurl(),
interactive);
if (!exit_code.has_value() || *exit_code != 0) {
return_value = exit_code;
break;
}
tabcount += 1;
if (markread) {
item->set_unread(false);
guids_of_read_articles.push_back(item->guid());
}
}
} else {
break;
}
}
if (guids_of_read_articles.size() > 0) {
v->get_ctrl()->mark_all_read(guids_of_read_articles);
}
return return_value;
}
} // namespace newsboat
<|endoftext|> |
<commit_before>#include <string>
#include <memory>
#include <iostream>
#include <limits.h>
#include <llvm/LLVMContext.h>
#include <llvm/Target/TargetSelect.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
//#include <llvm/ModuleProvider.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/ExecutionEngine/JIT.h>
#include "llvm/ExecutionEngine/GenericValue.h"
using namespace std;
using namespace llvm;
#include "TestClass.hpp"
int main()
{
TestClass tc;
tc.setHealth(100);
tc.printHealth();
InitializeNativeTarget();
llvm_start_multithreaded();
LLVMContext context;
string error;
// TODO: Check MemoryBuffer got a file or it will segfault
Module *m = ParseBitcodeFile(MemoryBuffer::getFile("bitcode/damage.bc"), context, &error);
if(!m) {
cout << "ERROR: Failed to load script file." << endl;
return 0;
}
ExecutionEngine *ee = ExecutionEngine::create(m);
// NOTE: Function names are mangled by the compiler.
Function* init_func = ee->FindFunctionNamed("_Z9initilizev");
if(!init_func) {
cout << "ERROR: Failed to find 'initilize' function." << endl;
return 0;
}
Function* attack_func = ee->FindFunctionNamed("_Z6attackP9TestClass");
if(!attack_func) {
cout << "ERROR: Failed to find 'attack' function." << endl;
return 0;
}
typedef void (*init_pfn)();
init_pfn initilize = reinterpret_cast<init_pfn>(ee->getPointerToFunction(init_func));
if(!initilize) {
cout << "ERROR: Failed to cast 'initilize' function." << endl;
return 0;
}
initilize();
cout << "Running attacking script...";
typedef void (*attack_pfn)(TestClass*);
attack_pfn attack = reinterpret_cast<attack_pfn>(ee->getPointerToFunction(attack_func));
if(!attack) {
cout << "ERROR: Failed to cast 'attack' function." << endl;
return 0;
}
attack(&tc);
tc.printHealth();
delete ee;
}
<commit_msg>Added newline to output.<commit_after>#include <string>
#include <memory>
#include <iostream>
#include <limits.h>
#include <llvm/LLVMContext.h>
#include <llvm/Target/TargetSelect.h>
#include <llvm/Bitcode/ReaderWriter.h>
#include <llvm/ExecutionEngine/ExecutionEngine.h>
//#include <llvm/ModuleProvider.h>
#include <llvm/Support/MemoryBuffer.h>
#include <llvm/ExecutionEngine/JIT.h>
#include "llvm/ExecutionEngine/GenericValue.h"
using namespace std;
using namespace llvm;
#include "TestClass.hpp"
int main()
{
TestClass tc;
tc.setHealth(100);
tc.printHealth();
InitializeNativeTarget();
llvm_start_multithreaded();
LLVMContext context;
string error;
// TODO: Check MemoryBuffer got a file or it will segfault
Module *m = ParseBitcodeFile(MemoryBuffer::getFile("bitcode/damage.bc"), context, &error);
if(!m) {
cout << "ERROR: Failed to load script file." << endl;
return 0;
}
ExecutionEngine *ee = ExecutionEngine::create(m);
// NOTE: Function names are mangled by the compiler.
Function* init_func = ee->FindFunctionNamed("_Z9initilizev");
if(!init_func) {
cout << "ERROR: Failed to find 'initilize' function." << endl;
return 0;
}
Function* attack_func = ee->FindFunctionNamed("_Z6attackP9TestClass");
if(!attack_func) {
cout << "ERROR: Failed to find 'attack' function." << endl;
return 0;
}
typedef void (*init_pfn)();
init_pfn initilize = reinterpret_cast<init_pfn>(ee->getPointerToFunction(init_func));
if(!initilize) {
cout << "ERROR: Failed to cast 'initilize' function." << endl;
return 0;
}
initilize();
cout << "Running attacking script..." << endl;
typedef void (*attack_pfn)(TestClass*);
attack_pfn attack = reinterpret_cast<attack_pfn>(ee->getPointerToFunction(attack_func));
if(!attack) {
cout << "ERROR: Failed to cast 'attack' function." << endl;
return 0;
}
attack(&tc);
tc.printHealth();
delete ee;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* Apple specific functions.
*/
#if defined(__APPLE__)
#include "net_rubygrapefruit_platform_internal_jni_MemoryFunctions.h"
#include "net_rubygrapefruit_platform_internal_jni_OsxMemoryFunctions.h"
#include "net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions.h"
#include "generic.h"
#include <string.h>
#include <stdlib.h>
#include <sys/param.h>
#include <sys/ucred.h>
#include <sys/mount.h>
#include <unistd.h>
#include <sys/attr.h>
#include <sys/types.h>
#include <sys/sysctl.h>
#include <mach/mach.h>
typedef struct vol_caps_buf {
u_int32_t size;
vol_capabilities_attr_t caps;
} vol_caps_buf_t;
/*
* File system functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv *env, jclass target, jobject info, jobject result) {
int fs_count = getfsstat(NULL, 0, MNT_NOWAIT);
if (fs_count < 0) {
mark_failed_with_errno(env, "could not stat file systems", result);
return;
}
size_t len = fs_count * sizeof(struct statfs);
struct statfs* buf = (struct statfs*)malloc(len);
if (getfsstat(buf, len, MNT_NOWAIT) < 0 ) {
mark_failed_with_errno(env, "could not stat file systems", result);
free(buf);
return;
}
jclass info_class = env->GetObjectClass(info);
jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V");
for (int i = 0; i < fs_count; i++) {
jboolean caseSensitive = JNI_TRUE;
jboolean casePreserving = JNI_TRUE;
struct attrlist alist;
memset(&alist, 0, sizeof(alist));
alist.bitmapcount = ATTR_BIT_MAP_COUNT;
alist.volattr = ATTR_VOL_CAPABILITIES | ATTR_VOL_INFO;
vol_caps_buf_t buffer;
// getattrlist requires the path to the actual mount point.
int err = getattrlist(buf[i].f_mntonname, &alist, &buffer, sizeof(buffer), 0);
if (err != 0) {
mark_failed_with_errno(env, "could not determine file system attributes", result);
break;
}
if (alist.volattr & ATTR_VOL_CAPABILITIES) {
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE)) {
caseSensitive = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE) != 0;
}
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING)) {
casePreserving = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING) != 0;
}
}
jstring mount_point = char_to_java(env, buf[i].f_mntonname, result);
jstring file_system_type = char_to_java(env, buf[i].f_fstypename, result);
jstring device_name = char_to_java(env, buf[i].f_mntfromname, result);
jboolean remote = (buf[i].f_flags & MNT_LOCAL) == 0;
env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, remote, caseSensitive, casePreserving);
}
free(buf);
}
/**
* Memory functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_MemoryFunctions_getMemoryInfo(JNIEnv *env, jclass type, jobject dest, jobject result) {
jclass destClass = env->GetObjectClass(dest);
jmethodID mid = env->GetMethodID(destClass, "details", "(JJ)V");
if (mid == NULL) {
mark_failed_with_message(env, "could not find method", result);
return;
}
// Get total physical memory
int mib[2];
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
int64_t total_memory = 0;
size_t len = sizeof(total_memory);
if (sysctl(mib, 2, &total_memory, &len, NULL, 0) != 0) {
mark_failed_with_errno(env, "could not query memory size", result);
return;
}
// Get VM stats
vm_size_t page_size;
mach_port_t mach_port;
mach_msg_type_number_t count;
vm_statistics64_data_t vm_stats;
mach_port = mach_host_self();
count = HOST_VM_INFO64_COUNT;
if (KERN_SUCCESS != host_page_size(mach_port, &page_size)) {
mark_failed_with_errno(env, "could not query page size", result);
return;
}
if (KERN_SUCCESS != host_statistics64(mach_port, HOST_VM_INFO, (host_info64_t)&vm_stats, &count)) {
mark_failed_with_errno(env, "could not query host statistics", result);
return;
}
// Calculate available memory
long long available_memory = ((int64_t)vm_stats.free_count
+ (int64_t)vm_stats.inactive_count
- (int64_t)vm_stats.speculative_count)
* (int64_t)page_size;
// Feed Java with details
env->CallVoidMethod(dest, mid, (jlong)total_memory, (jlong)available_memory);
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_OsxMemoryFunctions_getOsxMemoryInfo(JNIEnv *env, jclass type, jobject dest, jobject result) {
jclass destClass = env->GetObjectClass(dest);
jmethodID mid = env->GetMethodID(destClass, "details", "(JJJJJJJJJ)V");
if (mid == NULL) {
mark_failed_with_message(env, "could not find method", result);
return;
}
// Get total physical memory
int mib[2];
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
int64_t total_memory = 0;
size_t len = sizeof(total_memory);
if (sysctl(mib, 2, &total_memory, &len, NULL, 0) != 0) {
mark_failed_with_errno(env, "could not query memory size", result);
return;
}
// Get VM stats
vm_size_t page_size;
mach_port_t mach_port;
vm_statistics64_data_t vm_stats;
unsigned int count;
mach_port = mach_host_self();
count = HOST_VM_INFO64_COUNT;
if (KERN_SUCCESS != host_page_size(mach_port, &page_size)) {
mark_failed_with_errno(env, "could not query page size", result);
return;
}
if (KERN_SUCCESS != host_statistics64(mach_port, HOST_VM_INFO, (host_info64_t)&vm_stats, &count)) {
mark_failed_with_errno(env, "could not query host statistics", result);
return;
}
// Calculate available memory
long long available_memory = ((int64_t)vm_stats.free_count
+ (int64_t)vm_stats.inactive_count
- (int64_t)vm_stats.speculative_count)
* (int64_t)page_size;
// Feed Java with details
env->CallVoidMethod(dest, mid,
(jlong)page_size,
(jlong)vm_stats.free_count,
(jlong)vm_stats.inactive_count,
(jlong)vm_stats.wire_count,
(jlong)vm_stats.active_count,
(jlong)vm_stats.external_page_count,
(jlong)vm_stats.speculative_count,
(jlong)total_memory,
(jlong)available_memory);
}
#endif
<commit_msg>Format apple.cpp<commit_after>/*
* Copyright 2012 Adam Murdoch
*
* 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.
*/
/*
* Apple specific functions.
*/
#if defined(__APPLE__)
#include "generic.h"
#include "net_rubygrapefruit_platform_internal_jni_MemoryFunctions.h"
#include "net_rubygrapefruit_platform_internal_jni_OsxMemoryFunctions.h"
#include "net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions.h"
#include <mach/mach.h>
#include <stdlib.h>
#include <string.h>
#include <sys/attr.h>
#include <sys/mount.h>
#include <sys/param.h>
#include <sys/sysctl.h>
#include <sys/types.h>
#include <sys/ucred.h>
#include <unistd.h>
typedef struct vol_caps_buf {
u_int32_t size;
vol_capabilities_attr_t caps;
} vol_caps_buf_t;
/*
* File system functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_PosixFileSystemFunctions_listFileSystems(JNIEnv* env, jclass target, jobject info, jobject result) {
int fs_count = getfsstat(NULL, 0, MNT_NOWAIT);
if (fs_count < 0) {
mark_failed_with_errno(env, "could not stat file systems", result);
return;
}
size_t len = fs_count * sizeof(struct statfs);
struct statfs* buf = (struct statfs*) malloc(len);
if (getfsstat(buf, len, MNT_NOWAIT) < 0) {
mark_failed_with_errno(env, "could not stat file systems", result);
free(buf);
return;
}
jclass info_class = env->GetObjectClass(info);
jmethodID method = env->GetMethodID(info_class, "add", "(Ljava/lang/String;Ljava/lang/String;Ljava/lang/String;ZZZ)V");
for (int i = 0; i < fs_count; i++) {
jboolean caseSensitive = JNI_TRUE;
jboolean casePreserving = JNI_TRUE;
struct attrlist alist;
memset(&alist, 0, sizeof(alist));
alist.bitmapcount = ATTR_BIT_MAP_COUNT;
alist.volattr = ATTR_VOL_CAPABILITIES | ATTR_VOL_INFO;
vol_caps_buf_t buffer;
// getattrlist requires the path to the actual mount point.
int err = getattrlist(buf[i].f_mntonname, &alist, &buffer, sizeof(buffer), 0);
if (err != 0) {
mark_failed_with_errno(env, "could not determine file system attributes", result);
break;
}
if (alist.volattr & ATTR_VOL_CAPABILITIES) {
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE)) {
caseSensitive = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_SENSITIVE) != 0;
}
if ((buffer.caps.valid[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING)) {
casePreserving = (buffer.caps.capabilities[VOL_CAPABILITIES_FORMAT] & VOL_CAP_FMT_CASE_PRESERVING) != 0;
}
}
jstring mount_point = char_to_java(env, buf[i].f_mntonname, result);
jstring file_system_type = char_to_java(env, buf[i].f_fstypename, result);
jstring device_name = char_to_java(env, buf[i].f_mntfromname, result);
jboolean remote = (buf[i].f_flags & MNT_LOCAL) == 0;
env->CallVoidMethod(info, method, mount_point, file_system_type, device_name, remote, caseSensitive, casePreserving);
}
free(buf);
}
/**
* Memory functions
*/
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_MemoryFunctions_getMemoryInfo(JNIEnv* env, jclass type, jobject dest, jobject result) {
jclass destClass = env->GetObjectClass(dest);
jmethodID mid = env->GetMethodID(destClass, "details", "(JJ)V");
if (mid == NULL) {
mark_failed_with_message(env, "could not find method", result);
return;
}
// Get total physical memory
int mib[2];
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
int64_t total_memory = 0;
size_t len = sizeof(total_memory);
if (sysctl(mib, 2, &total_memory, &len, NULL, 0) != 0) {
mark_failed_with_errno(env, "could not query memory size", result);
return;
}
// Get VM stats
vm_size_t page_size;
mach_port_t mach_port;
mach_msg_type_number_t count;
vm_statistics64_data_t vm_stats;
mach_port = mach_host_self();
count = HOST_VM_INFO64_COUNT;
if (KERN_SUCCESS != host_page_size(mach_port, &page_size)) {
mark_failed_with_errno(env, "could not query page size", result);
return;
}
if (KERN_SUCCESS != host_statistics64(mach_port, HOST_VM_INFO, (host_info64_t) &vm_stats, &count)) {
mark_failed_with_errno(env, "could not query host statistics", result);
return;
}
// Calculate available memory
long long available_memory = ((int64_t) vm_stats.free_count
+ (int64_t) vm_stats.inactive_count
- (int64_t) vm_stats.speculative_count)
* (int64_t) page_size;
// Feed Java with details
env->CallVoidMethod(dest, mid, (jlong) total_memory, (jlong) available_memory);
}
JNIEXPORT void JNICALL
Java_net_rubygrapefruit_platform_internal_jni_OsxMemoryFunctions_getOsxMemoryInfo(JNIEnv* env, jclass type, jobject dest, jobject result) {
jclass destClass = env->GetObjectClass(dest);
jmethodID mid = env->GetMethodID(destClass, "details", "(JJJJJJJJJ)V");
if (mid == NULL) {
mark_failed_with_message(env, "could not find method", result);
return;
}
// Get total physical memory
int mib[2];
mib[0] = CTL_HW;
mib[1] = HW_MEMSIZE;
int64_t total_memory = 0;
size_t len = sizeof(total_memory);
if (sysctl(mib, 2, &total_memory, &len, NULL, 0) != 0) {
mark_failed_with_errno(env, "could not query memory size", result);
return;
}
// Get VM stats
vm_size_t page_size;
mach_port_t mach_port;
vm_statistics64_data_t vm_stats;
unsigned int count;
mach_port = mach_host_self();
count = HOST_VM_INFO64_COUNT;
if (KERN_SUCCESS != host_page_size(mach_port, &page_size)) {
mark_failed_with_errno(env, "could not query page size", result);
return;
}
if (KERN_SUCCESS != host_statistics64(mach_port, HOST_VM_INFO, (host_info64_t) &vm_stats, &count)) {
mark_failed_with_errno(env, "could not query host statistics", result);
return;
}
// Calculate available memory
long long available_memory = ((int64_t) vm_stats.free_count
+ (int64_t) vm_stats.inactive_count
- (int64_t) vm_stats.speculative_count)
* (int64_t) page_size;
// Feed Java with details
env->CallVoidMethod(dest, mid,
(jlong) page_size,
(jlong) vm_stats.free_count,
(jlong) vm_stats.inactive_count,
(jlong) vm_stats.wire_count,
(jlong) vm_stats.active_count,
(jlong) vm_stats.external_page_count,
(jlong) vm_stats.speculative_count,
(jlong) total_memory,
(jlong) available_memory);
}
#endif
<|endoftext|> |
<commit_before>#include <iostream>
#include "map/Level.h"
Level::Level(uint32_t width, uint32_t height, Generator& level_generator)
{
_width = width;
_height = height;
initializeLevel();
level_generator.generateMap(_width, _height, _tiles);
}
Level::~Level()
{
}
void Level::printLevel()
{
for(uint32_t x = 0; x < _width; x++)
{
for(uint32_t y = 0; y < _height; y++)
{
std::cout << _tiles[x][y].getDisplay();
}
std::cout << std::endl;
}
}
void Level::initializeLevel()
{
_tiles = new Tile*[_width];
for(uint32_t i = 0; i < _width; i++)
{
_tiles[i] = new Tile[_height];
}
}
<commit_msg>Add note that Level::~Level needs delete<commit_after>#include <iostream>
#include "map/Level.h"
Level::Level(uint32_t width, uint32_t height, Generator& level_generator)
{
_width = width;
_height = height;
initializeLevel();
level_generator.generateMap(_width, _height, _tiles);
}
/**
* @fixme Need to delete the dynamically-allocated space
*/
Level::~Level()
{
}
void Level::printLevel()
{
for(uint32_t x = 0; x < _width; x++)
{
for(uint32_t y = 0; y < _height; y++)
{
std::cout << _tiles[x][y].getDisplay();
}
std::cout << std::endl;
}
}
void Level::initializeLevel()
{
_tiles = new Tile*[_width];
for(uint32_t i = 0; i < _width; i++)
{
_tiles[i] = new Tile[_height];
}
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// hybrid_scan_executor.cpp
//
// Identification: src/executor/hybrid_scan_executor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <utility>
#include <vector>
#include <string>
#include <unordered_map>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <thread>
#include "common/timer.h"
#include "common/types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/executor_context.h"
#include "expression/abstract_expression.h"
#include "expression/container_tuple.h"
#include "planner/hybrid_scan_plan.h"
#include "executor/hybrid_scan_executor.h"
#include "storage/data_table.h"
#include "storage/tile_group_header.h"
#include "storage/tile.h"
#include "concurrency/transaction_manager_factory.h"
#include "common/logger.h"
namespace peloton {
namespace executor {
HybridScanExecutor::HybridScanExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractScanExecutor(node, executor_context),
indexed_tile_group_offset_(START_OID) {}
bool HybridScanExecutor::DInit() {
auto status = AbstractScanExecutor::DInit();
if (!status) return false;
const planner::HybridScanPlan &node = GetPlanNode<planner::HybridScanPlan>();
table_ = node.GetTable();
index_ = node.GetDataIndex();
type_ = node.GetHybridType();
PL_ASSERT(table_ != nullptr);
// SEQUENTIAL SCAN
if (type_ == HYBRID_SCAN_TYPE_SEQUENTIAL) {
LOG_TRACE("Sequential Scan");
current_tile_group_offset_ = START_OID;
table_tile_group_count_ = table_->GetTileGroupCount();
if (column_ids_.empty()) {
column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(column_ids_.begin(), column_ids_.end(), 0);
}
}
// INDEX SCAN
else if (type_ == HYBRID_SCAN_TYPE_INDEX) {
LOG_TRACE("Index Scan");
index_ = node.GetIndex();
result_itr_ = START_OID;
index_done_ = false;
result_.clear();
PL_ASSERT(index_ != nullptr);
column_ids_ = node.GetColumnIds();
auto key_column_ids_ = node.GetKeyColumnIds();
auto expr_types_ = node.GetExprTypes();
values_ = node.GetValues();
auto runtime_keys_ = node.GetRunTimeKeys();
predicate_ = node.GetPredicate();
key_ready_ = false;
if (runtime_keys_.size() != 0) {
assert(runtime_keys_.size() == values_.size());
if (!key_ready_) {
values_.clear();
for (auto expr : runtime_keys_) {
auto value = expr->Evaluate(nullptr, nullptr, executor_context_);
LOG_TRACE("Evaluated runtime scan key: %s", value.GetInfo().c_str());
values_.push_back(value);
}
key_ready_ = true;
}
}
if (table_ != nullptr) {
LOG_TRACE("Column count : %u", table_->GetSchema()->GetColumnCount());
full_column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(full_column_ids_.begin(), full_column_ids_.end(), 0);
}
}
// HYBRID SCAN
else if (type_ == HYBRID_SCAN_TYPE_HYBRID) {
LOG_TRACE("Hybrid Scan");
table_tile_group_count_ = table_->GetTileGroupCount();
int offset = index_->GetIndexedTileGroupOffset();
indexed_tile_group_offset_ = (offset == -1) ? INVALID_OID : (oid_t)offset;
block_threshold = 0;
if (indexed_tile_group_offset_ == INVALID_OID) {
current_tile_group_offset_ = START_OID;
} else {
current_tile_group_offset_ = indexed_tile_group_offset_ + 1;
std::shared_ptr<storage::TileGroup> tile_group;
if (current_tile_group_offset_ < table_tile_group_count_) {
tile_group = table_->GetTileGroup(current_tile_group_offset_);
} else {
tile_group = table_->GetTileGroup(table_tile_group_count_ - 1);
}
oid_t tuple_id = 0;
ItemPointer location(tile_group->GetTileGroupId(), tuple_id);
block_threshold = location.block;
}
result_itr_ = START_OID;
index_done_ = false;
result_.clear();
column_ids_ = node.GetColumnIds();
auto key_column_ids_ = node.GetKeyColumnIds();
auto expr_types_ = node.GetExprTypes();
values_ = node.GetValues();
auto runtime_keys_ = node.GetRunTimeKeys();
predicate_ = node.GetPredicate();
if (runtime_keys_.size() != 0) {
assert(runtime_keys_.size() == values_.size());
if (!key_ready_) {
values_.clear();
for (auto expr : runtime_keys_) {
auto value = expr->Evaluate(nullptr, nullptr, executor_context_);
LOG_TRACE("Evaluated runtime scan key: %s", value.GetInfo().c_str());
values_.push_back(value);
}
key_ready_ = true;
}
}
if (table_ != nullptr) {
full_column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(full_column_ids_.begin(), full_column_ids_.end(), 0);
}
}
// FALLBACK
else {
throw Exception("Invalid hybrid scan type : " + std::to_string(type_));
}
return true;
}
bool HybridScanExecutor::SeqScanUtil() {
assert(children_.size() == 0);
// LOG_TRACE("Hybrid executor, Seq Scan :: 0 child");
assert(table_ != nullptr);
assert(column_ids_.size() > 0);
auto &transaction_manager =
concurrency::TransactionManagerFactory::GetInstance();
// Retrieve next tile group.
while (current_tile_group_offset_ < table_tile_group_count_) {
LOG_TRACE("Current tile group offset : %u", current_tile_group_offset_);
auto tile_group = table_->GetTileGroup(current_tile_group_offset_++);
auto tile_group_header = tile_group->GetHeader();
oid_t active_tuple_count = tile_group->GetNextTupleSlot();
// Construct position list by looping through tile group
// and applying the predicate.
oid_t upper_bound_block = 0;
if (item_pointers_.size() > 0) {
auto reverse_iter = item_pointers_.rbegin();
upper_bound_block = reverse_iter->block;
}
std::vector<oid_t> position_list;
for (oid_t tuple_id = 0; tuple_id < active_tuple_count; tuple_id++) {
ItemPointer location(tile_group->GetTileGroupId(), tuple_id);
if (type_ == HYBRID_SCAN_TYPE_HYBRID && item_pointers_.size() > 0 &&
location.block <= upper_bound_block) {
if (item_pointers_.find(location) != item_pointers_.end()) {
continue;
}
}
// Check transaction visibility
if (transaction_manager.IsVisible(tile_group_header, tuple_id)) {
// If the tuple is visible, then perform predicate evaluation.
if (predicate_ == nullptr) {
position_list.push_back(tuple_id);
}
else {
expression::ContainerTuple<storage::TileGroup> tuple(tile_group.get(),
tuple_id);
auto eval = predicate_->Evaluate(&tuple, nullptr, executor_context_).IsTrue();
if (eval == true) {
position_list.push_back(tuple_id);
}
}
}
else {
expression::ContainerTuple<storage::TileGroup> tuple(tile_group.get(),
tuple_id);
auto eval =
predicate_->Evaluate(&tuple, nullptr, executor_context_).IsTrue();
if (eval == true) {
position_list.push_back(tuple_id);
auto res = transaction_manager.PerformRead(location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}
}
}
}
// Don't return empty tiles
if (position_list.size() == 0) {
continue;
}
// Construct logical tile.
std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
logical_tile->AddColumns(tile_group, column_ids_);
logical_tile->AddPositionList(std::move(position_list));
LOG_TRACE("Hybrid executor, Seq Scan :: Got a logical tile");
SetOutput(logical_tile.release());
return true;
}
return false;
}
bool HybridScanExecutor::IndexScanUtil() {
// Already performed the index lookup
assert(index_done_);
while (result_itr_ < result_.size()) { // Avoid returning empty tiles
if (result_[result_itr_]->GetTupleCount() == 0) {
result_itr_++;
continue;
}
else {
SetOutput(result_[result_itr_]);
result_itr_++;
return true;
}
} // end while
return false;
}
bool HybridScanExecutor::DExecute() {
// SEQUENTIAL SCAN
if (type_ == HYBRID_SCAN_TYPE_SEQUENTIAL) {
LOG_TRACE("Sequential Scan");
return SeqScanUtil();
}
// INDEX SCAN
else if (type_ == HYBRID_SCAN_TYPE_INDEX) {
LOG_TRACE("Index Scan");
PL_ASSERT(children_.size() == 0);
if (index_done_ == false) {
if (index_->GetIndexType() == INDEX_CONSTRAINT_TYPE_PRIMARY_KEY) {
auto status = ExecPrimaryIndexLookup();
if (status == false) {
return false;
}
}
else {
return false;
}
}
return IndexScanUtil();
}
// HYBRID SCAN
else if (type_ == HYBRID_SCAN_TYPE_HYBRID) {
LOG_TRACE("Hybrid Scan");
// do two part search
if (index_done_ == false) {
if (indexed_tile_group_offset_ == INVALID_OID) {
index_done_ = true;
} else {
ExecPrimaryIndexLookup();
LOG_TRACE("Using index -- tile count : %lu", result_.size());
}
}
if (IndexScanUtil() == true) {
return true;
}
// Scan seq
return SeqScanUtil();
}
// FALLBACK
else {
throw Exception("Invalid hybrid scan type : " + std::to_string(type_));
}
}
bool HybridScanExecutor::ExecPrimaryIndexLookup() {
PL_ASSERT(index_done_ == false);
const planner::HybridScanPlan &node = GetPlanNode<planner::HybridScanPlan>();
auto key_column_ids_ = node.GetKeyColumnIds();
auto expr_type_ = node.GetExprTypes();
std::vector<ItemPointer> tuple_locations;
PL_ASSERT(index_->GetIndexType() == INDEX_CONSTRAINT_TYPE_PRIMARY_KEY);
if (0 == key_column_ids_.size()) {
LOG_TRACE("Scan all keys");
index_->ScanAllKeys(tuple_locations);
} else {
LOG_TRACE("Scan");
index_->Scan(values_,
key_column_ids_,
expr_type_,
SCAN_DIRECTION_TYPE_FORWARD,
tuple_locations);
}
LOG_TRACE("Result tuple count: %lu", tuple_locations.size());
auto &transaction_manager =
concurrency::TransactionManagerFactory::GetInstance();
if (tuple_locations.size() == 0) {
index_done_ = true;
return false;
}
std::map<oid_t, std::vector<oid_t>> visible_tuples;
// for every tuple that is found in the index.
for (auto tuple_location : tuple_locations) {
if (type_ == HYBRID_SCAN_TYPE_HYBRID &&
tuple_location.block >= (block_threshold)) {
item_pointers_.insert(tuple_location);
}
auto &manager = catalog::Manager::GetInstance();
auto tile_group = manager.GetTileGroup(tuple_location.block);
auto tile_group_header = tile_group.get()->GetHeader();
// perform transaction read
size_t chain_length = 0;
while (true) {
++chain_length;
if (transaction_manager.IsVisible(tile_group_header,
tuple_location.offset)) {
visible_tuples[tuple_location.block].push_back(tuple_location.offset);
auto res = transaction_manager.PerformRead(tuple_location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}
break;
} else {
ItemPointer old_item = tuple_location;
cid_t old_end_cid = tile_group_header->GetEndCommitId(old_item.offset);
tuple_location = tile_group_header->GetNextItemPointer(old_item.offset);
// there must exist a visible version.
assert(tuple_location.IsNull() == false);
cid_t max_committed_cid = transaction_manager.GetMaxCommittedCid();
// check whether older version is garbage.
if (old_end_cid < max_committed_cid) {
assert(tile_group_header->GetTransactionId(old_item.offset) ==
INITIAL_TXN_ID ||
tile_group_header->GetTransactionId(old_item.offset) ==
INVALID_TXN_ID);
}
tile_group = manager.GetTileGroup(tuple_location.block);
tile_group_header = tile_group.get()->GetHeader();
}
}
}
// Construct a logical tile for each block
for (auto tuples : visible_tuples) {
auto &manager = catalog::Manager::GetInstance();
auto tile_group = manager.GetTileGroup(tuples.first);
std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
// Add relevant columns to logical tile
logical_tile->AddColumns(tile_group, full_column_ids_);
logical_tile->AddPositionList(std::move(tuples.second));
if (column_ids_.size() != 0) {
logical_tile->ProjectColumns(full_column_ids_, column_ids_);
}
result_.push_back(logical_tile.release());
}
index_done_ = true;
LOG_TRACE("Result tiles : %lu", result_.size());
return true;
}
} // namespace executor
} // namespace peloton
<commit_msg>Fix iota<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// hybrid_scan_executor.cpp
//
// Identification: src/executor/hybrid_scan_executor.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include <memory>
#include <utility>
#include <vector>
#include <string>
#include <unordered_map>
#include <chrono>
#include <iostream>
#include <ctime>
#include <cassert>
#include <thread>
#include <algorithm>
#include "common/timer.h"
#include "common/types.h"
#include "executor/logical_tile.h"
#include "executor/logical_tile_factory.h"
#include "executor/executor_context.h"
#include "expression/abstract_expression.h"
#include "expression/container_tuple.h"
#include "planner/hybrid_scan_plan.h"
#include "executor/hybrid_scan_executor.h"
#include "storage/data_table.h"
#include "storage/tile_group_header.h"
#include "storage/tile.h"
#include "concurrency/transaction_manager_factory.h"
#include "common/logger.h"
namespace peloton {
namespace executor {
HybridScanExecutor::HybridScanExecutor(const planner::AbstractPlan *node,
ExecutorContext *executor_context)
: AbstractScanExecutor(node, executor_context),
indexed_tile_group_offset_(START_OID) {}
bool HybridScanExecutor::DInit() {
auto status = AbstractScanExecutor::DInit();
if (!status) return false;
const planner::HybridScanPlan &node = GetPlanNode<planner::HybridScanPlan>();
table_ = node.GetTable();
index_ = node.GetDataIndex();
type_ = node.GetHybridType();
PL_ASSERT(table_ != nullptr);
// SEQUENTIAL SCAN
if (type_ == HYBRID_SCAN_TYPE_SEQUENTIAL) {
LOG_TRACE("Sequential Scan");
current_tile_group_offset_ = START_OID;
table_tile_group_count_ = table_->GetTileGroupCount();
if (column_ids_.empty()) {
column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(column_ids_.begin(), column_ids_.end(), 0);
}
}
// INDEX SCAN
else if (type_ == HYBRID_SCAN_TYPE_INDEX) {
LOG_TRACE("Index Scan");
index_ = node.GetIndex();
result_itr_ = START_OID;
index_done_ = false;
result_.clear();
PL_ASSERT(index_ != nullptr);
column_ids_ = node.GetColumnIds();
auto key_column_ids_ = node.GetKeyColumnIds();
auto expr_types_ = node.GetExprTypes();
values_ = node.GetValues();
auto runtime_keys_ = node.GetRunTimeKeys();
predicate_ = node.GetPredicate();
key_ready_ = false;
if (runtime_keys_.size() != 0) {
assert(runtime_keys_.size() == values_.size());
if (!key_ready_) {
values_.clear();
for (auto expr : runtime_keys_) {
auto value = expr->Evaluate(nullptr, nullptr, executor_context_);
LOG_TRACE("Evaluated runtime scan key: %s", value.GetInfo().c_str());
values_.push_back(value);
}
key_ready_ = true;
}
}
if (table_ != nullptr) {
LOG_TRACE("Column count : %u", table_->GetSchema()->GetColumnCount());
full_column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(full_column_ids_.begin(), full_column_ids_.end(), 0);
}
}
// HYBRID SCAN
else if (type_ == HYBRID_SCAN_TYPE_HYBRID) {
LOG_TRACE("Hybrid Scan");
table_tile_group_count_ = table_->GetTileGroupCount();
int offset = index_->GetIndexedTileGroupOffset();
indexed_tile_group_offset_ = (offset == -1) ? INVALID_OID : (oid_t)offset;
block_threshold = 0;
if (indexed_tile_group_offset_ == INVALID_OID) {
current_tile_group_offset_ = START_OID;
} else {
current_tile_group_offset_ = indexed_tile_group_offset_ + 1;
std::shared_ptr<storage::TileGroup> tile_group;
if (current_tile_group_offset_ < table_tile_group_count_) {
tile_group = table_->GetTileGroup(current_tile_group_offset_);
} else {
tile_group = table_->GetTileGroup(table_tile_group_count_ - 1);
}
oid_t tuple_id = 0;
ItemPointer location(tile_group->GetTileGroupId(), tuple_id);
block_threshold = location.block;
}
result_itr_ = START_OID;
index_done_ = false;
result_.clear();
column_ids_ = node.GetColumnIds();
auto key_column_ids_ = node.GetKeyColumnIds();
auto expr_types_ = node.GetExprTypes();
values_ = node.GetValues();
auto runtime_keys_ = node.GetRunTimeKeys();
predicate_ = node.GetPredicate();
if (runtime_keys_.size() != 0) {
assert(runtime_keys_.size() == values_.size());
if (!key_ready_) {
values_.clear();
for (auto expr : runtime_keys_) {
auto value = expr->Evaluate(nullptr, nullptr, executor_context_);
LOG_TRACE("Evaluated runtime scan key: %s", value.GetInfo().c_str());
values_.push_back(value);
}
key_ready_ = true;
}
}
if (table_ != nullptr) {
full_column_ids_.resize(table_->GetSchema()->GetColumnCount());
std::iota(full_column_ids_.begin(), full_column_ids_.end(), 0);
}
}
// FALLBACK
else {
throw Exception("Invalid hybrid scan type : " + std::to_string(type_));
}
return true;
}
bool HybridScanExecutor::SeqScanUtil() {
assert(children_.size() == 0);
// LOG_TRACE("Hybrid executor, Seq Scan :: 0 child");
assert(table_ != nullptr);
assert(column_ids_.size() > 0);
auto &transaction_manager =
concurrency::TransactionManagerFactory::GetInstance();
// Retrieve next tile group.
while (current_tile_group_offset_ < table_tile_group_count_) {
LOG_TRACE("Current tile group offset : %u", current_tile_group_offset_);
auto tile_group = table_->GetTileGroup(current_tile_group_offset_++);
auto tile_group_header = tile_group->GetHeader();
oid_t active_tuple_count = tile_group->GetNextTupleSlot();
// Construct position list by looping through tile group
// and applying the predicate.
oid_t upper_bound_block = 0;
if (item_pointers_.size() > 0) {
auto reverse_iter = item_pointers_.rbegin();
upper_bound_block = reverse_iter->block;
}
std::vector<oid_t> position_list;
for (oid_t tuple_id = 0; tuple_id < active_tuple_count; tuple_id++) {
ItemPointer location(tile_group->GetTileGroupId(), tuple_id);
if (type_ == HYBRID_SCAN_TYPE_HYBRID && item_pointers_.size() > 0 &&
location.block <= upper_bound_block) {
if (item_pointers_.find(location) != item_pointers_.end()) {
continue;
}
}
// Check transaction visibility
if (transaction_manager.IsVisible(tile_group_header, tuple_id)) {
// If the tuple is visible, then perform predicate evaluation.
if (predicate_ == nullptr) {
position_list.push_back(tuple_id);
}
else {
expression::ContainerTuple<storage::TileGroup> tuple(tile_group.get(),
tuple_id);
auto eval = predicate_->Evaluate(&tuple, nullptr, executor_context_).IsTrue();
if (eval == true) {
position_list.push_back(tuple_id);
}
}
}
else {
expression::ContainerTuple<storage::TileGroup> tuple(tile_group.get(),
tuple_id);
auto eval =
predicate_->Evaluate(&tuple, nullptr, executor_context_).IsTrue();
if (eval == true) {
position_list.push_back(tuple_id);
auto res = transaction_manager.PerformRead(location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}
}
}
}
// Don't return empty tiles
if (position_list.size() == 0) {
continue;
}
// Construct logical tile.
std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
logical_tile->AddColumns(tile_group, column_ids_);
logical_tile->AddPositionList(std::move(position_list));
LOG_TRACE("Hybrid executor, Seq Scan :: Got a logical tile");
SetOutput(logical_tile.release());
return true;
}
return false;
}
bool HybridScanExecutor::IndexScanUtil() {
// Already performed the index lookup
assert(index_done_);
while (result_itr_ < result_.size()) { // Avoid returning empty tiles
if (result_[result_itr_]->GetTupleCount() == 0) {
result_itr_++;
continue;
}
else {
SetOutput(result_[result_itr_]);
result_itr_++;
return true;
}
} // end while
return false;
}
bool HybridScanExecutor::DExecute() {
// SEQUENTIAL SCAN
if (type_ == HYBRID_SCAN_TYPE_SEQUENTIAL) {
LOG_TRACE("Sequential Scan");
return SeqScanUtil();
}
// INDEX SCAN
else if (type_ == HYBRID_SCAN_TYPE_INDEX) {
LOG_TRACE("Index Scan");
PL_ASSERT(children_.size() == 0);
if (index_done_ == false) {
if (index_->GetIndexType() == INDEX_CONSTRAINT_TYPE_PRIMARY_KEY) {
auto status = ExecPrimaryIndexLookup();
if (status == false) {
return false;
}
}
else {
return false;
}
}
return IndexScanUtil();
}
// HYBRID SCAN
else if (type_ == HYBRID_SCAN_TYPE_HYBRID) {
LOG_TRACE("Hybrid Scan");
// do two part search
if (index_done_ == false) {
if (indexed_tile_group_offset_ == INVALID_OID) {
index_done_ = true;
} else {
ExecPrimaryIndexLookup();
LOG_TRACE("Using index -- tile count : %lu", result_.size());
}
}
if (IndexScanUtil() == true) {
return true;
}
// Scan seq
return SeqScanUtil();
}
// FALLBACK
else {
throw Exception("Invalid hybrid scan type : " + std::to_string(type_));
}
}
bool HybridScanExecutor::ExecPrimaryIndexLookup() {
PL_ASSERT(index_done_ == false);
const planner::HybridScanPlan &node = GetPlanNode<planner::HybridScanPlan>();
auto key_column_ids_ = node.GetKeyColumnIds();
auto expr_type_ = node.GetExprTypes();
std::vector<ItemPointer> tuple_locations;
PL_ASSERT(index_->GetIndexType() == INDEX_CONSTRAINT_TYPE_PRIMARY_KEY);
if (0 == key_column_ids_.size()) {
LOG_TRACE("Scan all keys");
index_->ScanAllKeys(tuple_locations);
} else {
LOG_TRACE("Scan");
index_->Scan(values_,
key_column_ids_,
expr_type_,
SCAN_DIRECTION_TYPE_FORWARD,
tuple_locations);
}
LOG_TRACE("Result tuple count: %lu", tuple_locations.size());
auto &transaction_manager =
concurrency::TransactionManagerFactory::GetInstance();
if (tuple_locations.size() == 0) {
index_done_ = true;
return false;
}
std::map<oid_t, std::vector<oid_t>> visible_tuples;
// for every tuple that is found in the index.
for (auto tuple_location : tuple_locations) {
if (type_ == HYBRID_SCAN_TYPE_HYBRID &&
tuple_location.block >= (block_threshold)) {
item_pointers_.insert(tuple_location);
}
auto &manager = catalog::Manager::GetInstance();
auto tile_group = manager.GetTileGroup(tuple_location.block);
auto tile_group_header = tile_group.get()->GetHeader();
// perform transaction read
size_t chain_length = 0;
while (true) {
++chain_length;
if (transaction_manager.IsVisible(tile_group_header,
tuple_location.offset)) {
visible_tuples[tuple_location.block].push_back(tuple_location.offset);
auto res = transaction_manager.PerformRead(tuple_location);
if (!res) {
transaction_manager.SetTransactionResult(RESULT_FAILURE);
return res;
}
break;
} else {
ItemPointer old_item = tuple_location;
cid_t old_end_cid = tile_group_header->GetEndCommitId(old_item.offset);
tuple_location = tile_group_header->GetNextItemPointer(old_item.offset);
// there must exist a visible version.
assert(tuple_location.IsNull() == false);
cid_t max_committed_cid = transaction_manager.GetMaxCommittedCid();
// check whether older version is garbage.
if (old_end_cid < max_committed_cid) {
assert(tile_group_header->GetTransactionId(old_item.offset) ==
INITIAL_TXN_ID ||
tile_group_header->GetTransactionId(old_item.offset) ==
INVALID_TXN_ID);
}
tile_group = manager.GetTileGroup(tuple_location.block);
tile_group_header = tile_group.get()->GetHeader();
}
}
}
// Construct a logical tile for each block
for (auto tuples : visible_tuples) {
auto &manager = catalog::Manager::GetInstance();
auto tile_group = manager.GetTileGroup(tuples.first);
std::unique_ptr<LogicalTile> logical_tile(LogicalTileFactory::GetTile());
// Add relevant columns to logical tile
logical_tile->AddColumns(tile_group, full_column_ids_);
logical_tile->AddPositionList(std::move(tuples.second));
if (column_ids_.size() != 0) {
logical_tile->ProjectColumns(full_column_ids_, column_ids_);
}
result_.push_back(logical_tile.release());
}
index_done_ = true;
LOG_TRACE("Result tiles : %lu", result_.size());
return true;
}
} // namespace executor
} // namespace peloton
<|endoftext|> |
<commit_before>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* Copyright (c) 2019 by Contributors
* \file pointwise_fusion_pass.cc
* \brief Pass applying pointwise fusion.
* \author Clement Fuji Tsang
*/
#include <mxnet/base.h>
#include <mxnet/operator.h>
#include <mxnet/op_attr_types.h>
#include <nnvm/graph_attr_types.h>
#include <nnvm/pass_functions.h>
#include <algorithm>
#include <queue>
#include "./simple_partition_pass.h"
#include "../operator/fusion/fused_op-inl.h"
#include "../operator/fusion/fused_op.h"
#include "../operator/operator_common.h"
#if MXNET_USE_CUDA
namespace mxnet {
namespace exec {
namespace {
bool IsFusionCompatible(nnvm::Node* n) {
using namespace mxnet::fusion;
if (n->op() == nullptr)
return false;
std::string op_name = n->op()->name;
if (ops_desc.count(op_name))
return true;
if (slice_ops.count(op_name))
return false;
if (std::find(variable_io_ops.begin(),
variable_io_ops.end(),
op_name) !=
variable_io_ops.end())
return true;
return false;
}
bool IsInputsOnlyCompatible(nnvm::Node* n) {
using namespace mxnet::fusion;
if (n->op() == nullptr)
return false;
std::string op_name = n->op()->name;
if (slice_ops.count(op_name)) {
if (op_name == "slice") {
// slice with non-default step attribute is not supported
// currently
if (n->attrs.dict.count("step") &&
!(n->attrs.dict.at("step") == "()" ||
n->attrs.dict.at("step") == "[]")) {
return false;
}
}
return true;
}
return false;
}
nnvm::NodePtr CreateSubgraphNode(const Graph& subgraph, size_t inputs_size) {
nnvm::Symbol subgraph_sym;
auto node = nnvm::Node::Create();
subgraph_sym.outputs = subgraph.outputs;
node->attrs.subgraphs.emplace_back(std::make_shared<nnvm::Symbol>(subgraph_sym));
std::ostringstream name_oss;
// the name of the new node will be the concatenation of all the node names in the subgraph
DFSVisit(subgraph.outputs, [&name_oss](const nnvm::NodePtr n) {
if (n->op() != nullptr)
name_oss << n->op()->name << "_";
});
auto subgraph_name = name_oss.str();
subgraph_name.pop_back();
node->attrs.name = subgraph_name;
node->attrs.dict["num_inputs"] = std::to_string(inputs_size);
node->attrs.dict["num_outputs"] = std::to_string(subgraph.outputs.size());
node->attrs.op = Op::Get("_FusedOp");
node->op()->attr_parser(&(node->attrs));
return node;
}
} // namespace
/*!
* \brief Replace a set of nodes by a subgraph node.
* This function is used specifically in pointwise fusion.
*/
template<typename FCreateNode>
Graph ReplaceSubgraphsPointwise(Graph&& g, const std::vector<NodeRawPtrSet>& subgraph_sets,
FCreateNode create_subgraph_node) {
for (auto subgraph_set : subgraph_sets) {
// Create MXNet subgraph
Graph subgraph;
const auto sub_outputs_in_main = GetSubgraphOutputs(g, subgraph_set);
subgraph.outputs.resize(sub_outputs_in_main.size());
for (auto p : sub_outputs_in_main) {
subgraph.outputs[p.second] = p.first;
}
// To generate a subgraph an input has to be replaced by data node (no op)
// and it has to be agnostic to the node from which it's an output
// (For example, even if two inputs are two different outputs from the same node,
// they need to be replaced by two completely separate data nodes)
auto inputs = GetSubgraphInputs(subgraph, subgraph_set);
auto subgraph_node = create_subgraph_node(subgraph, inputs.size());
subgraph_node->inputs = inputs;
// replug inputs of node out of subgraph to be output of the subgraph node
// if it was a node in the subgraph
DFSVisit(g.outputs,
[&subgraph_node, &subgraph_set, &sub_outputs_in_main](const nnvm::NodePtr node) {
if (!subgraph_set.count(node.get())) {
for (auto &e : node->inputs) {
auto it = sub_outputs_in_main.find(e);
if (it != sub_outputs_in_main.end()) {
e.node = subgraph_node;
e.index = it->second;
}
}
}
});
// replug outputs of the graph to be output of the subgraph node
// if it was a node in the subgraph
for (auto &e : g.outputs) {
auto it = sub_outputs_in_main.find(e);
if (it != sub_outputs_in_main.end()) {
e.node = subgraph_node;
e.index = it->second;
}
}
// move control dependencies between nodes of the subgraph and out of the subgraph
// to a dependencies between the subgraph node and the nodes out of the subgraph
DFSVisit(subgraph.outputs, [&subgraph_node, &subgraph_set](const nnvm::NodePtr& node) {
if (subgraph_set.count(node.get())) {
auto it = node->control_deps.begin();
static auto& is_fusion = Op::GetAttr<exec::TIsFusionHelper>("TIsFusionHelper");
std::vector<nnvm::NodePtr> new_control_deps;
while (it != node->control_deps.end()) {
if (subgraph_set.count(it->get())) {
new_control_deps.push_back(*it);
} else {
if ((*it)->is_variable() || !is_fusion.get((*it)->op(), false)) {
uint32_t node_id = subgraph_node->control_deps.size();
subgraph_node->control_deps.push_back(*it);
auto helper_node = op::MakeNode("_FusedOpOutHelper",
subgraph_node->attrs.name + "_"
+ node->attrs.name + "_outhelper",
nullptr,
nullptr,
nullptr);
helper_node->attrs.parsed =
FusedOpHelperParamPtr(new FusedOpHelperParam(
nnvm::get<FusedOpPtr>(subgraph_node->attrs.parsed),
node_id));
new_control_deps.push_back(helper_node);
} else {
new_control_deps.push_back(*it);
}
}
++it;
}
node->control_deps = new_control_deps;
}
});
const auto& index = subgraph.indexed_graph();
DFSVisit(g.outputs, [&subgraph_node, &subgraph_set, &index](const nnvm::NodePtr& node) {
for (auto &e : node->control_deps) {
if (subgraph_set.count(e.get())) {
uint32_t node_id = index.node_id(e.get());
auto helper_node = op::MakeNode("_FusedOpHelper",
subgraph_node->attrs.name + "_"
+ node->attrs.name + "_helper",
nullptr,
nullptr,
nullptr);
helper_node->attrs.parsed =
FusedOpHelperParamPtr(new FusedOpHelperParam(
nnvm::get<FusedOpPtr>(subgraph_node->attrs.parsed),
node_id));
e = helper_node;
}
}
});
}
Graph new_graph;
new_graph.outputs = g.outputs;
return new_graph;
}
/* \brief Add nodes as inputs to the subgraph. This is used for operations
* which are only compatible when they are the first nodes in the
* subgraph.
*/
template <typename IsCompatible>
void AddInputsOnlyCompatible(const Graph &g,
std::vector<std::unordered_set<nnvm::Node*> >* subsets,
IsCompatible is_compatible) {
std::unordered_map<nnvm::Node*, uint32_t> node2setidx;
size_t subgraphs_fullsize = 0;
for (auto& s : *subsets) {
subgraphs_fullsize += s.size();
}
node2setidx.reserve(subgraphs_fullsize);
for (size_t i = 0; i < subsets->size(); ++i) {
for (auto& n : (*subsets)[i]) {
node2setidx.insert({n, i});
}
}
std::vector<std::vector<nnvm::Node*> > to_add(subsets->size());
DFSVisit(g.outputs, [&is_compatible, &node2setidx, &to_add](const nnvm::NodePtr& n) {
const auto& it = node2setidx.find(n.get());
if (it != node2setidx.end()) {
for (auto& e : n->inputs) {
if (is_compatible(e.node.get()))
to_add[it->second].push_back(e.node.get());
}
}
});
// Avoid duplicating the node that is input of two subsets
std::unordered_set<nnvm::Node*> added;
for (size_t i = 0; i < subsets->size(); ++i) {
std::vector<nnvm::NodeEntry> heads;
for (auto n : subsets->at(i)) {
for (auto e : n->inputs) {
if (!subsets->at(i).count(e.node.get()))
heads.push_back(e);
}
}
for (size_t j = 0; j < to_add[i].size(); ++j) {
if (!added.count(to_add[i][j])) {
bool make_cycle = false;
const auto& node = to_add[i][j];
std::vector<nnvm::NodeEntry> _heads;
std::copy_if(heads.begin(), heads.end(), std::back_inserter(_heads),
[&node](const nnvm::NodeEntry& n) {
return n.node.get() != node;
});
DFSVisit(_heads, [&make_cycle, &node](const nnvm::NodePtr& n) {
if (n.get() == node)
make_cycle = true;
});
if (!make_cycle) {
(*subsets)[i].insert(to_add[i][j]);
added.insert(to_add[i][j]);
}
}
}
}
}
Graph FusePointwiseForward(Graph &&g) {
Graph ret;
g.indexed_graph();
const auto& num_forward_outputs = g.GetAttr<size_t>("num_forward_outputs");
Graph fg;
fg.outputs.insert(fg.outputs.begin(), g.outputs.begin(),
g.outputs.begin() + num_forward_outputs);
auto subsets = GetCompatibleSubsets(fg, IsFusionCompatible);
AddInputsOnlyCompatible(fg, &subsets, IsInputsOnlyCompatible);
g = ReplaceSubgraphsPointwise(std::move(g), subsets, CreateSubgraphNode);
ret.outputs = g.outputs;
return ret;
}
Graph FusePointwiseBackward(Graph &&g) {
Graph ret;
g.indexed_graph();
const auto& num_forward_outputs = g.GetAttr<size_t>("num_forward_outputs");
Graph fg;
fg.outputs.insert(fg.outputs.begin(), g.outputs.begin(),
g.outputs.begin() + num_forward_outputs);
std::unordered_set<nnvm::Node*> exclusion_set;
DFSVisit(fg.outputs, [&exclusion_set](const nnvm::NodePtr& n) {
exclusion_set.insert(n.get());
});
auto subsets = GetCompatibleSubsets(g, [&exclusion_set](nnvm::Node* n) {
if (exclusion_set.count(n))
return false;
return IsFusionCompatible(n);
});
g = ReplaceSubgraphsPointwise(std::move(g), subsets, CreateSubgraphNode);
ret.outputs = g.outputs;
return ret;
}
} // namespace exec
} // namespace mxnet
#endif // MXNET_USE_CUDA
<commit_msg>Fix (#16781)<commit_after>/*
* Licensed to the Apache Software Foundation (ASF) under one
* or more contributor license agreements. See the NOTICE file
* distributed with this work for additional information
* regarding copyright ownership. The ASF licenses this file
* to you 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.
*/
/*!
* Copyright (c) 2019 by Contributors
* \file pointwise_fusion_pass.cc
* \brief Pass applying pointwise fusion.
* \author Clement Fuji Tsang
*/
#include <mxnet/base.h>
#include <mxnet/operator.h>
#include <mxnet/op_attr_types.h>
#include <nnvm/graph_attr_types.h>
#include <nnvm/pass_functions.h>
#include <algorithm>
#include <queue>
#include "./simple_partition_pass.h"
#include "../operator/fusion/fused_op-inl.h"
#include "../operator/fusion/fused_op.h"
#include "../operator/operator_common.h"
#if MXNET_USE_CUDA
namespace mxnet {
namespace exec {
namespace {
bool IsFusionCompatible(nnvm::Node* n) {
using namespace mxnet::fusion;
if (n->op() == nullptr)
return false;
std::string op_name = n->op()->name;
if (ops_desc.count(op_name))
return true;
if (slice_ops.count(op_name))
return false;
if (std::find(variable_io_ops.begin(),
variable_io_ops.end(),
op_name) !=
variable_io_ops.end())
return true;
return false;
}
bool IsInputsOnlyCompatible(nnvm::Node* n) {
using namespace mxnet::fusion;
if (n->op() == nullptr)
return false;
std::string op_name = n->op()->name;
if (slice_ops.count(op_name)) {
if (op_name == "slice") {
// slice with non-default step attribute is not supported
// currently
if (n->attrs.dict.count("step") &&
!(n->attrs.dict.at("step") == "()" ||
n->attrs.dict.at("step") == "[]")) {
return false;
}
}
return true;
}
return false;
}
nnvm::NodePtr CreateSubgraphNode(const Graph& subgraph, size_t inputs_size) {
nnvm::Symbol subgraph_sym;
auto node = nnvm::Node::Create();
subgraph_sym.outputs = subgraph.outputs;
node->attrs.subgraphs.emplace_back(std::make_shared<nnvm::Symbol>(subgraph_sym));
node->attrs.name = "FusedOp";
node->attrs.dict["num_inputs"] = std::to_string(inputs_size);
node->attrs.dict["num_outputs"] = std::to_string(subgraph.outputs.size());
node->attrs.op = Op::Get("_FusedOp");
node->op()->attr_parser(&(node->attrs));
return node;
}
} // namespace
/*!
* \brief Replace a set of nodes by a subgraph node.
* This function is used specifically in pointwise fusion.
*/
template<typename FCreateNode>
Graph ReplaceSubgraphsPointwise(Graph&& g, const std::vector<NodeRawPtrSet>& subgraph_sets,
FCreateNode create_subgraph_node) {
for (auto subgraph_set : subgraph_sets) {
// Create MXNet subgraph
Graph subgraph;
const auto sub_outputs_in_main = GetSubgraphOutputs(g, subgraph_set);
subgraph.outputs.resize(sub_outputs_in_main.size());
for (auto p : sub_outputs_in_main) {
subgraph.outputs[p.second] = p.first;
}
// To generate a subgraph an input has to be replaced by data node (no op)
// and it has to be agnostic to the node from which it's an output
// (For example, even if two inputs are two different outputs from the same node,
// they need to be replaced by two completely separate data nodes)
auto inputs = GetSubgraphInputs(subgraph, subgraph_set);
auto subgraph_node = create_subgraph_node(subgraph, inputs.size());
subgraph_node->inputs = inputs;
// replug inputs of node out of subgraph to be output of the subgraph node
// if it was a node in the subgraph
DFSVisit(g.outputs,
[&subgraph_node, &subgraph_set, &sub_outputs_in_main](const nnvm::NodePtr node) {
if (!subgraph_set.count(node.get())) {
for (auto &e : node->inputs) {
auto it = sub_outputs_in_main.find(e);
if (it != sub_outputs_in_main.end()) {
e.node = subgraph_node;
e.index = it->second;
}
}
}
});
// replug outputs of the graph to be output of the subgraph node
// if it was a node in the subgraph
for (auto &e : g.outputs) {
auto it = sub_outputs_in_main.find(e);
if (it != sub_outputs_in_main.end()) {
e.node = subgraph_node;
e.index = it->second;
}
}
// move control dependencies between nodes of the subgraph and out of the subgraph
// to a dependencies between the subgraph node and the nodes out of the subgraph
DFSVisit(subgraph.outputs, [&subgraph_node, &subgraph_set](const nnvm::NodePtr& node) {
if (subgraph_set.count(node.get())) {
auto it = node->control_deps.begin();
static auto& is_fusion = Op::GetAttr<exec::TIsFusionHelper>("TIsFusionHelper");
std::vector<nnvm::NodePtr> new_control_deps;
// Use the first control dependency to get the inferattr helper
if (it != node->control_deps.end()) {
if (subgraph_set.count(it->get())) {
new_control_deps.push_back(*it);
} else {
if ((*it)->is_variable() || !is_fusion.get((*it)->op(), false)) {
uint32_t node_id = subgraph_node->control_deps.size();
subgraph_node->control_deps.push_back(*it);
auto helper_node = op::MakeNode("_FusedOpOutHelper",
"FusedOp_" + node->attrs.name + "_outhelper",
nullptr,
nullptr,
nullptr);
helper_node->attrs.parsed =
FusedOpHelperParamPtr(new FusedOpHelperParam(
nnvm::get<FusedOpPtr>(subgraph_node->attrs.parsed),
node_id));
new_control_deps.push_back(helper_node);
} else {
new_control_deps.push_back(*it);
}
}
++it;
}
node->control_deps = new_control_deps;
}
});
std::ostringstream name_oss;
// the name of the new node will be the concatenation of all the node names in the subgraph
DFSVisit(subgraph.outputs, [&name_oss](const nnvm::NodePtr n) {
if (n->op() != nullptr) {
name_oss << n->op()->name << "_";
}
});
auto subgraph_name = name_oss.str();
subgraph_name.pop_back();
subgraph_node->attrs.name = subgraph_name;
const auto& index = subgraph.indexed_graph();
DFSVisit(g.outputs, [&subgraph_node, &subgraph_set, &index](const nnvm::NodePtr& node) {
for (auto &e : node->control_deps) {
if (subgraph_set.count(e.get())) {
uint32_t node_id = index.node_id(e.get());
auto helper_node = op::MakeNode("_FusedOpHelper",
subgraph_node->attrs.name + "_"
+ node->attrs.name + "_helper",
nullptr,
nullptr,
nullptr);
helper_node->attrs.parsed =
FusedOpHelperParamPtr(new FusedOpHelperParam(
nnvm::get<FusedOpPtr>(subgraph_node->attrs.parsed),
node_id));
e = helper_node;
}
}
});
}
Graph new_graph;
new_graph.outputs = g.outputs;
return new_graph;
}
/* \brief Add nodes as inputs to the subgraph. This is used for operations
* which are only compatible when they are the first nodes in the
* subgraph.
*/
template <typename IsCompatible>
void AddInputsOnlyCompatible(const Graph &g,
std::vector<std::unordered_set<nnvm::Node*> >* subsets,
IsCompatible is_compatible) {
std::unordered_map<nnvm::Node*, uint32_t> node2setidx;
size_t subgraphs_fullsize = 0;
for (auto& s : *subsets) {
subgraphs_fullsize += s.size();
}
node2setidx.reserve(subgraphs_fullsize);
for (size_t i = 0; i < subsets->size(); ++i) {
for (auto& n : (*subsets)[i]) {
node2setidx.insert({n, i});
}
}
std::vector<std::vector<nnvm::Node*> > to_add(subsets->size());
DFSVisit(g.outputs, [&is_compatible, &node2setidx, &to_add](const nnvm::NodePtr& n) {
const auto& it = node2setidx.find(n.get());
if (it != node2setidx.end()) {
for (auto& e : n->inputs) {
if (is_compatible(e.node.get()))
to_add[it->second].push_back(e.node.get());
}
}
});
// Avoid duplicating the node that is input of two subsets
std::unordered_set<nnvm::Node*> added;
for (size_t i = 0; i < subsets->size(); ++i) {
std::vector<nnvm::NodeEntry> heads;
for (auto n : subsets->at(i)) {
for (auto e : n->inputs) {
if (!subsets->at(i).count(e.node.get()))
heads.push_back(e);
}
}
for (size_t j = 0; j < to_add[i].size(); ++j) {
if (!added.count(to_add[i][j])) {
bool make_cycle = false;
const auto& node = to_add[i][j];
std::vector<nnvm::NodeEntry> _heads;
std::copy_if(heads.begin(), heads.end(), std::back_inserter(_heads),
[&node](const nnvm::NodeEntry& n) {
return n.node.get() != node;
});
DFSVisit(_heads, [&make_cycle, &node](const nnvm::NodePtr& n) {
if (n.get() == node)
make_cycle = true;
});
if (!make_cycle) {
(*subsets)[i].insert(to_add[i][j]);
added.insert(to_add[i][j]);
}
}
}
}
}
Graph FusePointwiseForward(Graph &&g) {
Graph ret;
g.indexed_graph();
const auto& num_forward_outputs = g.GetAttr<size_t>("num_forward_outputs");
Graph fg;
fg.outputs.insert(fg.outputs.begin(), g.outputs.begin(),
g.outputs.begin() + num_forward_outputs);
auto subsets = GetCompatibleSubsets(fg, IsFusionCompatible);
AddInputsOnlyCompatible(fg, &subsets, IsInputsOnlyCompatible);
g = ReplaceSubgraphsPointwise(std::move(g), subsets, CreateSubgraphNode);
ret.outputs = g.outputs;
return ret;
}
Graph FusePointwiseBackward(Graph &&g) {
Graph ret;
g.indexed_graph();
const auto& num_forward_outputs = g.GetAttr<size_t>("num_forward_outputs");
Graph fg;
fg.outputs.insert(fg.outputs.begin(), g.outputs.begin(),
g.outputs.begin() + num_forward_outputs);
std::unordered_set<nnvm::Node*> exclusion_set;
DFSVisit(fg.outputs, [&exclusion_set](const nnvm::NodePtr& n) {
exclusion_set.insert(n.get());
});
auto subsets = GetCompatibleSubsets(g, [&exclusion_set](nnvm::Node* n) {
if (exclusion_set.count(n))
return false;
return IsFusionCompatible(n);
});
g = ReplaceSubgraphsPointwise(std::move(g), subsets, CreateSubgraphNode);
ret.outputs = g.outputs;
return ret;
}
} // namespace exec
} // namespace mxnet
#endif // MXNET_USE_CUDA
<|endoftext|> |
<commit_before>#include <iostream>
using namespace std;
#include "modelFunctions.cpp"
#include "cameraFunctions.cpp"
#if defined(__APPLE__)
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#else
#include<GL/gl.h>
#include<GL/freeglut.h>
#endif
/** TYPE DEFINITIONS **/
#ifndef __POINT_DEF__
#define __POINT_DEF__
struct Point {
double x, y, z;
};
#endif
/** PROGRAM CONSTATNS **/
const int START_HEIGHT = 600;
const int START_WIDTH = 600;
const int NUM_EXPECTED_PARAMETERS = 2;
/** GLOBAL VARIABLES **/
double ANGLE_X, ANGLE_Y, ANGLE_Z;
double SCALE, ROTATION_FACTOR;
unsigned char MODE;
int LAST_MOUSE_X, LAST_MOUSE_Y;
/**
* Close the the program
*/
void close() {
exit(1);
}
/**
* Display help information on default output channel
*/
void help() {
cout << endl;
cout << "---------------> >> HELP INFORMATION << <--------------" << endl;
cout << " Change camera mode [prespectiva | axonometrica]" << endl;
cout << " -> Press 'p' to change" << endl;
cout << " Print status information" << endl;
cout << " -> Press 's' to display" << endl;
cout << " Set the response of mouse events on window" << endl;
cout << " -> Press 'r' to set camera rotation mode" << endl;
// cout << " -> Press 't' to set translation mode" << endl;
cout << " Set the precision of rotation mode" << endl;
cout << " -> Press '+' to increment the rotation speed" << endl;
cout << " -> Press '-' to decrement the rotation speed" << endl;
cout << " Press ESC to exit" << endl;
cout << "-------------------------------------------------------" << endl;
}
/**
* Display program status information on default output channel
*/
void status() {
cout << endl;
cout << "--------------------> >> STATUS << <-------------------" << endl;
cout << " Camera mode : " << getStrCameraMode() << endl;
cout << " Rotation factor: " << ROTATION_FACTOR << " [Def. 10]"<< endl;
cout << "-------------------------------------------------------" << endl;
}
void usage() {
cout << endl;
cout << "Usage: file_with_model" << endl;
}
/**
* Paint the axes of current object
* The rotations and translations can affect to the painted axes
*/
void paintAxes() {
glBegin(GL_LINES);
glColor3f (1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(1, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 1, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 1);
glEnd();
}
void paintFloor() {
glPushMatrix();
glTranslated(0.0, -0.4, 0.0);
glBegin(GL_QUADS);
glColor3f (0.545, 0.271, 0.075);
glVertex3f( 0.75, 0, 0.75);
glVertex3f( 0.75, 0,-0.75);
glVertex3f(-0.75, 0,-0.75);
glVertex3f(-0.75, 0, 0.75);
glEnd();
glPopMatrix();
}
void paintSnowMan() {
glPushMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.4, 20, 20);
glPopMatrix();
glTranslated(0.0, 0.6, 0.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.2, 50, 50);
glPopMatrix();
glColor3f(1.0, 0.5, 0.0);
glTranslated(0.1, 0.0, 0.0);
glRotated(90, 0, 1, 0);
glutSolidCone(0.1, 0.2, 20, 20);
glPopMatrix();
}
/* ----------------------- CALLBACKS ----------------------- */
void refresh () {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotated(0, 1, 0, 0);
glScaled(SCALE, SCALE, SCALE);
paintFloor();
paintSnowMan();
paintModel();
glPopMatrix();
glutSwapBuffers();
}
/**
* Callback for resize events
* @param height New height of window
* @param width New width of window
*/
void onResize(int height, int width) {
double relX = (double)width/(double)(START_WIDTH);
double relY = (double)height/(double)(START_HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-relY, relY, -relX, relX, -1, 1);
setMatrixMode();
glViewport(0, 0, height, width);
}
void onMouseClick(int buton, int evnt, int x, int y) {
if (evnt == GLUT_DOWN) {
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
}
}
void onMouseMotion(int x, int y) {
float height = glutGet(GLUT_WINDOW_HEIGHT);
float width = glutGet(GLUT_WINDOW_WIDTH);
switch (MODE) {
case 'r': incrementEulerAngles(((double)(LAST_MOUSE_Y - y)*ROTATION_FACTOR/height),
((double)(x - LAST_MOUSE_X)*ROTATION_FACTOR/width), 0.0);
setCameraMatrix();
break;
case 't': SCALE = x >= width - y ? (double)((x)*2.0/height) :
(double)((width - (y))*2.0/width);
break;
case 'c': TRANS_Z += (2.0*(y - LAST_MOUSE_Y))/(double)height;
TRANS_X += (2.0*(x - LAST_MOUSE_X))/(double)width;
break;
}
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
glutPostRedisplay();
}
void onKeyboardPulse(unsigned char key, int x, int y) {
switch (key) {
case 'h': help();
break;
case '+': ROTATION_FACTOR *= 1.3;
break;
case '-': ROTATION_FACTOR /= 1.3;
break;
case 's': status();
break;
case 'p': changeCameraMode();
glutPostRedisplay();
break;
case (char)27: close();
break;
}
if (MODE == 'c' && key == 'c') MODE == 'r';
else MODE = key;
}
/* -------------------- END OF CALLBACKS -------------------- */
/* ---------------------- INITIAL CALCS --------------------- */
/**
* Initializate the Global variables of the program
*/
void initGlobalVars() {
SCALE = 1.0;
ROTATION_FACTOR = 10.0;
MODE = 'r';
INIT_MODEL_HEIGHT = 0.5;
TRANS_X = 0.75;
TRANS_Y = -0.4 + INIT_MODEL_HEIGHT/2.0;
TRANS_Z = 0.75;
}
/**
* Initializate the openGL envrionament
*/
void initGL() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
/* ------------------- END OF INITIAL CALCS ------------------ */
/* ----------------------- MAIN FUNCTION --------------------- */
int main(int argc, const char *argv[]) {
// Check num of paramaters
if (argc != NUM_EXPECTED_PARAMETERS) {
usage();
close();
}
// Initialitzation of GLUT
glutInit(&argc, ((char **)argv));
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(START_HEIGHT, START_WIDTH);
glutCreateWindow("IDI: Bloc 3");
// Config rotations mode
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
// Registre de Callbacks
glutDisplayFunc(refresh);
glutReshapeFunc(onResize);
glutMouseFunc(onMouseClick);
glutMotionFunc(onMouseMotion);
glutKeyboardFunc(onKeyboardPulse);
// Initialization of openGL
initGL();
// Initialization of global variables
initCamera();
initGlobalVars();
loadModel(argv[1]);
calcModelVars();
setCameraMatrix();
// GLUT events loop
glutMainLoop();
return 0;
}
<commit_msg>Added reset of euler angles<commit_after>#include <iostream>
using namespace std;
#include "modelFunctions.cpp"
#include "cameraFunctions.cpp"
#if defined(__APPLE__)
#include <OpenGL/OpenGL.h>
#include <GLUT/GLUT.h>
#else
#include<GL/gl.h>
#include<GL/freeglut.h>
#endif
/** TYPE DEFINITIONS **/
#ifndef __POINT_DEF__
#define __POINT_DEF__
struct Point {
double x, y, z;
};
#endif
/** PROGRAM CONSTATNS **/
const int START_HEIGHT = 600;
const int START_WIDTH = 600;
const int NUM_EXPECTED_PARAMETERS = 2;
/** GLOBAL VARIABLES **/
double ANGLE_X, ANGLE_Y, ANGLE_Z;
double SCALE, ROTATION_FACTOR;
unsigned char MODE;
int LAST_MOUSE_X, LAST_MOUSE_Y;
/**
* Close the the program
*/
void close() {
exit(1);
}
/**
* Display help information on default output channel
*/
void help() {
cout << endl;
cout << "---------------> >> HELP INFORMATION << <--------------" << endl;
cout << " Change camera mode [prespectiva | axonometrica]" << endl;
cout << " -> Press 'p' to change" << endl;
cout << " Print status information" << endl;
cout << " -> Press 's' to display" << endl;
cout << " Set the response of mouse events on window" << endl;
cout << " -> Press 'r' to set camera rotation mode" << endl;
// cout << " -> Press 't' to set translation mode" << endl;
cout << " Set the precision of rotation mode" << endl;
cout << " -> Press '+' to increment the rotation speed" << endl;
cout << " -> Press '-' to decrement the rotation speed" << endl;
cout << " Reset the program to starting camera position" << endl;
cout << " -> Press 'i' to reset" << endl;
cout << " Press ESC to exit" << endl;
cout << "-------------------------------------------------------" << endl;
}
/**
* Display program status information on default output channel
*/
void status() {
cout << endl;
cout << "--------------------> >> STATUS << <-------------------" << endl;
cout << " Camera mode : " << getStrCameraMode() << endl;
cout << " Rotation factor: " << ROTATION_FACTOR << " [Def. 10]"<< endl;
cout << "-------------------------------------------------------" << endl;
}
void usage() {
cout << endl;
cout << "Usage: file_with_model" << endl;
}
/**
* Paint the axes of current object
* The rotations and translations can affect to the painted axes
*/
void paintAxes() {
glBegin(GL_LINES);
glColor3f (1, 0, 0);
glVertex3f(0, 0, 0);
glVertex3f(1, 0, 0);
glColor3f(0, 1, 0);
glVertex3f(0, 0, 0);
glVertex3f(0, 1, 0);
glColor3f(0, 0, 1);
glVertex3f(0, 0, 0);
glVertex3f(0, 0, 1);
glEnd();
}
void paintFloor() {
glPushMatrix();
glTranslated(0.0, -0.4, 0.0);
glBegin(GL_QUADS);
glColor3f (0.545, 0.271, 0.075);
glVertex3f( 0.75, 0, 0.75);
glVertex3f( 0.75, 0,-0.75);
glVertex3f(-0.75, 0,-0.75);
glVertex3f(-0.75, 0, 0.75);
glEnd();
glPopMatrix();
}
void paintSnowMan() {
glPushMatrix();
glColor3f(1.0, 1.0, 1.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.4, 20, 20);
glPopMatrix();
glTranslated(0.0, 0.6, 0.0);
glPushMatrix();
glRotated(90, 1, 0, 0);
glutSolidSphere(0.2, 50, 50);
glPopMatrix();
glColor3f(1.0, 0.5, 0.0);
glTranslated(0.1, 0.0, 0.0);
glRotated(90, 0, 1, 0);
glutSolidCone(0.1, 0.2, 20, 20);
glPopMatrix();
}
/* ----------------------- CALLBACKS ----------------------- */
void refresh () {
glClear(GL_COLOR_BUFFER_BIT|GL_DEPTH_BUFFER_BIT);
glPushMatrix();
glRotated(0, 1, 0, 0);
glScaled(SCALE, SCALE, SCALE);
paintFloor();
paintSnowMan();
paintModel();
glPopMatrix();
glutSwapBuffers();
}
/**
* Callback for resize events
* @param height New height of window
* @param width New width of window
*/
void onResize(int height, int width) {
double relX = (double)width/(double)(START_WIDTH);
double relY = (double)height/(double)(START_HEIGHT);
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-relY, relY, -relX, relX, -1, 1);
setMatrixMode();
glViewport(0, 0, height, width);
}
void onMouseClick(int buton, int evnt, int x, int y) {
if (evnt == GLUT_DOWN) {
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
}
}
void onMouseMotion(int x, int y) {
float height = glutGet(GLUT_WINDOW_HEIGHT);
float width = glutGet(GLUT_WINDOW_WIDTH);
switch (MODE) {
case 'r': incrementEulerAngles(((double)(LAST_MOUSE_Y - y)*ROTATION_FACTOR/height),
((double)(x - LAST_MOUSE_X)*ROTATION_FACTOR/width), 0.0);
setCameraMatrix();
break;
case 't': SCALE = x >= width - y ? (double)((x)*2.0/height) :
(double)((width - (y))*2.0/width);
break;
case 'c': TRANS_Z += (2.0*(y - LAST_MOUSE_Y))/(double)height;
TRANS_X += (2.0*(x - LAST_MOUSE_X))/(double)width;
break;
}
LAST_MOUSE_X = x;
LAST_MOUSE_Y = y;
glutPostRedisplay();
}
void onKeyboardPulse(unsigned char key, int x, int y) {
switch (key) {
case 'h': help();
break;
case '+': ROTATION_FACTOR *= 1.3;
break;
case '-': ROTATION_FACTOR /= 1.3;
break;
case 's': status();
break;
case 'p': changeCameraMode();
glutPostRedisplay();
break;
case 'i': initCamera();
setCameraMatrix();
glutPostRedisplay();
break;
case (char)27: close();
break;
}
if (MODE == 'c' && key == 'c') MODE == 'r';
else MODE = key;
}
/* -------------------- END OF CALLBACKS -------------------- */
/* ---------------------- INITIAL CALCS --------------------- */
/**
* Initializate the Global variables of the program
*/
void initGlobalVars() {
SCALE = 1.0;
ROTATION_FACTOR = 10.0;
MODE = 'r';
INIT_MODEL_HEIGHT = 0.5;
TRANS_X = 0.75;
TRANS_Y = -0.4 + INIT_MODEL_HEIGHT/2.0;
TRANS_Z = 0.75;
}
/**
* Initializate the openGL envrionament
*/
void initGL() {
glClearColor(0, 0, 0, 1);
glEnable(GL_DEPTH_TEST);
}
/* ------------------- END OF INITIAL CALCS ------------------ */
/* ----------------------- MAIN FUNCTION --------------------- */
int main(int argc, const char *argv[]) {
// Check num of paramaters
if (argc != NUM_EXPECTED_PARAMETERS) {
usage();
close();
}
// Initialitzation of GLUT
glutInit(&argc, ((char **)argv));
glutInitDisplayMode(GLUT_DEPTH|GLUT_DOUBLE|GLUT_RGBA);
glutInitWindowSize(START_HEIGHT, START_WIDTH);
glutCreateWindow("IDI: Bloc 3");
// Config rotations mode
glMatrixMode(GL_PROJECTION);
glLoadIdentity();
glOrtho(-1, 1, -1, 1, -1, 1);
glMatrixMode(GL_MODELVIEW);
// Registre de Callbacks
glutDisplayFunc(refresh);
glutReshapeFunc(onResize);
glutMouseFunc(onMouseClick);
glutMotionFunc(onMouseMotion);
glutKeyboardFunc(onKeyboardPulse);
// Initialization of openGL
initGL();
// Initialization of global variables
initCamera();
initGlobalVars();
loadModel(argv[1]);
calcModelVars();
setCameraMatrix();
// GLUT events loop
glutMainLoop();
return 0;
}
<|endoftext|> |
<commit_before>#include "nearby.h"
#include "components/position.h"
#include "entity_system.h"
#include <algorithm>
namespace {
constexpr std::tuple<uint16_t, uint16_t> get_grid_position(float x, float y) {
uint16_t gx = x / 1000.f;
uint16_t gy = y / 1000.f;
return {gx, gy};
}
std::tuple<uint16_t, uint16_t> get_grid_position(const RoseCommon::Registry& registry, RoseCommon::Entity e) {
const auto* pos = registry.try_get<Component::Position>(e);
if (!pos) return {0, 0};
return get_grid_position(pos->x, pos->y);
}
std::tuple<uint16_t, uint16_t> get_grid_position(const EntitySystem& entitySystem, RoseCommon::Entity e) {
const auto* pos = entitySystem.try_get_component<Component::Position>(e);
if (!pos) return {0, 0};
return get_grid_position(pos->x, pos->y);
}
}
void Nearby::add_entity(RoseCommon::Registry& registry, RoseCommon::Entity entity) {
if (entity == entt::null) return;
grid[get_grid_position(registry, entity)].push_back(entity);
}
void Nearby::remove_entity(RoseCommon::Registry& registry, RoseCommon::Entity entity) {
if (entity == entt::null) return;
auto& list = grid[get_grid_position(registry, entity)];
list.erase(std::remove(list.begin(), list.end(), entity), list.end());
}
bool Nearby::is_nearby(const EntitySystem& entitySystem, RoseCommon::Entity first, RoseCommon::Entity second) const {
if (first == entt::null || second == entt::null) return false;
auto pos_first = get_grid_position(entitySystem, first);
auto pos_second = get_grid_position(entitySystem, second);
if (std::abs(std::get<0>(pos_first) - std::get<0>(pos_second)) <= 10
&& std::abs(std::get<1>(pos_first) - std::get<1>(pos_second)) <= 10)
return true;
return false;
}
std::vector<RoseCommon::Entity> Nearby::get_nearby(const EntitySystem& entitySystem, RoseCommon::Entity entity) const {
std::vector<RoseCommon::Entity> res;
// TODO: populate res and sort it by entity
auto pos = get_grid_position(entitySystem, entity);
for (uint16_t x = std::max(0, std::get<0>(pos) - 10); x < std::get<0>(pos) + 10; ++x) {
for (uint16_t y = std::max(0, std::get<1>(pos) - 10); y < std::get<1>(pos) + 10; ++y) {
if (const auto it = grid.find({x, y}); it != grid.cend()) {
res.insert(res.end(), it->second.cbegin(), it->second.cend());
}
}
}
return res;
}
void Nearby::update_position(RoseCommon::Entity entity, float old_x, float old_y, float x, float y) {
if (old_x && old_y) {
auto &list = grid[get_grid_position(old_x, old_y)];
std::remove(list.begin(), list.end(), entity);
}
grid[get_grid_position(x, y)].push_back(entity);
}
<commit_msg>Sort nearby values<commit_after>#include "nearby.h"
#include "components/position.h"
#include "entity_system.h"
#include <algorithm>
namespace {
constexpr std::tuple<uint16_t, uint16_t> get_grid_position(float x, float y) {
uint16_t gx = x / 1000.f;
uint16_t gy = y / 1000.f;
return {gx, gy};
}
std::tuple<uint16_t, uint16_t> get_grid_position(const RoseCommon::Registry& registry, RoseCommon::Entity e) {
const auto* pos = registry.try_get<Component::Position>(e);
if (!pos) return {0, 0};
return get_grid_position(pos->x, pos->y);
}
std::tuple<uint16_t, uint16_t> get_grid_position(const EntitySystem& entitySystem, RoseCommon::Entity e) {
const auto* pos = entitySystem.try_get_component<Component::Position>(e);
if (!pos) return {0, 0};
return get_grid_position(pos->x, pos->y);
}
}
void Nearby::add_entity(RoseCommon::Registry& registry, RoseCommon::Entity entity) {
if (entity == entt::null) return;
grid[get_grid_position(registry, entity)].push_back(entity);
}
void Nearby::remove_entity(RoseCommon::Registry& registry, RoseCommon::Entity entity) {
if (entity == entt::null) return;
auto& list = grid[get_grid_position(registry, entity)];
list.erase(std::remove(list.begin(), list.end(), entity), list.end());
}
bool Nearby::is_nearby(const EntitySystem& entitySystem, RoseCommon::Entity first, RoseCommon::Entity second) const {
if (first == entt::null || second == entt::null) return false;
auto pos_first = get_grid_position(entitySystem, first);
auto pos_second = get_grid_position(entitySystem, second);
if (std::abs(std::get<0>(pos_first) - std::get<0>(pos_second)) <= 10
&& std::abs(std::get<1>(pos_first) - std::get<1>(pos_second)) <= 10)
return true;
return false;
}
std::vector<RoseCommon::Entity> Nearby::get_nearby(const EntitySystem& entitySystem, RoseCommon::Entity entity) const {
std::vector<RoseCommon::Entity> res;
// TODO: populate res and sort it by entity
auto pos = get_grid_position(entitySystem, entity);
for (uint16_t x = std::max(0, std::get<0>(pos) - 10); x < std::get<0>(pos) + 10; ++x) {
for (uint16_t y = std::max(0, std::get<1>(pos) - 10); y < std::get<1>(pos) + 10; ++y) {
if (const auto it = grid.find({x, y}); it != grid.cend()) {
res.insert(res.end(), it->second.cbegin(), it->second.cend());
}
}
}
std::sort(res.begin(), res.end());
return res;
}
void Nearby::update_position(RoseCommon::Entity entity, float old_x, float old_y, float x, float y) {
if (old_x && old_y) {
auto &list = grid[get_grid_position(old_x, old_y)];
std::remove(list.begin(), list.end(), entity);
}
grid[get_grid_position(x, y)].push_back(entity);
}
<|endoftext|> |
<commit_before>#include "MACAddr.h"
#ifdef _WIN32
#include <iphlpapi.h>
#endif
MACAddr::MACAddr() : addr(MAC_ADDR_LEN, 0){}
MACAddr::MACAddr(const string & macStr){
addr.resize(6,0);
std::istringstream macStream(macStr);
for (uint8_t & macByte : addr){
int byte;
char colon;
macStream >> std::hex >> byte >> colon;
macByte = byte;
}
}
MACAddr::MACAddr(const int & macAddrInt){
//TODO
}
MACAddr MACAddr::MACAddr_from_devName(const string & devName){
//Extract a MAC address from the the pcap information. A bit of a cross-platorm pain.
#ifdef _WIN32
// winpcap names are different than widows names
// pcap - \Device\NPF_{F47ACE9E-1961-4A8E-BA14-2564E3764BFA}
// windows - {F47ACE9E-1961-4A8E-BA14-2564E3764BFA}
//
// start by triming input name to only {...}
size_t start,end;
start = devName.find('{');
end = devName.find('}');
if (start == std::string::npos || end == std::string::npos) {
FILE_LOG(logERROR) << "getMacAddr: Invalid devInfo name";
return MACAddr();
}
string winName = devName.substr(start, end-start + 1);
// look up mac addresses using GetAdaptersInfo
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365917%28v=vs.85%29.aspx
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = 0;
// call GetAdaptersInfo with length of 0 to get required buffer size in
// ulOutBufLen
GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
// allocated memory for all adapters
pAdapterInfo = (IP_ADAPTER_INFO *) malloc(ulOutBufLen);
if (!pAdapterInfo) {
FILE_LOG(logERROR) << "Error allocating memory needed to call GetAdaptersinfo" << endl;
return MACAddr();
}
// call GetAdaptersInfo a second time to get all adapter information
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
pAdapter = pAdapterInfo;
// loop over adapters and match name strings
while (pAdapter) {
string matchName = string(pAdapter->AdapterName);
if (winName.compare(matchName) == 0) {
// copy address
//TODO: fix me!
// std::copy(pAdapter->Address, pAdapter->Address + MAC_ADDR_LEN, devInfo.macAddr);
// devInfo.description2 = string(pAdapter->Description);
//cout << "Adapter Name: " << string(pAdapter->AdapterName) << endl;
//cout << "Adapter Desc: " << string(pAdapter->Description) << endl;
//cout << "Adpater Addr: " << print_ethernetAddress(pAdapter->Address) << endl;
}
pAdapter = pAdapter->Next;
}
}
if (pAdapterInfo) free(pAdapterInfo);
return MACAddr("silly");
#else
//On Linux we simply look in /sys/class/net/DEVICE_NAME/address
std::ifstream devFile(std::string("/sys/class/net/") + devName + std::string("/address"));
std::string macAddrStr;
getline(devFile, macAddrStr);
return MACAddr(macAddrStr);
#endif
}
string MACAddr::to_string() const{
std::ostringstream ss;
for(const uint8_t curByte : addr){
ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(curByte) << ":";
}
//remove the trailing ":"
string myStr = ss.str();
myStr.pop_back();
return myStr;
}<commit_msg>Fix-up MAC address lookup on Windows.<commit_after>#include "MACAddr.h"
#ifdef _WIN32
#include <iphlpapi.h>
#endif
MACAddr::MACAddr() : addr(MAC_ADDR_LEN, 0){}
MACAddr::MACAddr(const string & macStr){
addr.resize(6,0);
std::istringstream macStream(macStr);
for (uint8_t & macByte : addr){
int byte;
char colon;
macStream >> std::hex >> byte >> colon;
macByte = byte;
}
}
MACAddr::MACAddr(const uint8_t * macAddrBytes){
addr.clear();
for (size_t ct=0; ct<6; ct++){
addr.push_back(macAddrBytes[ct]);
}
}
MACAddr MACAddr::MACAddr_from_devName(const string & devName){
//Extract a MAC address from the the pcap information. A bit of a cross-platform pain.
#ifdef _WIN32
// winpcap names are different than widows names
// pcap - \Device\NPF_{F47ACE9E-1961-4A8E-BA14-2564E3764BFA}
// windows - {F47ACE9E-1961-4A8E-BA14-2564E3764BFA}
//
// start by triming input name to only {...}
size_t start,end;
start = devName.find('{');
end = devName.find('}');
if (start == std::string::npos || end == std::string::npos) {
FILE_LOG(logERROR) << "getMacAddr: Invalid devInfo name";
return MACAddr();
}
string winName = devName.substr(start, end-start + 1);
// look up mac addresses using GetAdaptersInfo
// http://msdn.microsoft.com/en-us/library/windows/desktop/aa365917%28v=vs.85%29.aspx
PIP_ADAPTER_INFO pAdapterInfo;
PIP_ADAPTER_INFO pAdapter = NULL;
DWORD dwRetVal = 0;
ULONG ulOutBufLen = 0;
// call GetAdaptersInfo with length of 0 to get required buffer size in
// ulOutBufLen
GetAdaptersInfo(pAdapterInfo, &ulOutBufLen);
// allocated memory for all adapters
pAdapterInfo = (IP_ADAPTER_INFO *) malloc(ulOutBufLen);
if (!pAdapterInfo) {
FILE_LOG(logERROR) << "Error allocating memory needed to call GetAdaptersinfo" << endl;
return MACAddr();
}
// call GetAdaptersInfo a second time to get all adapter information
if ((dwRetVal = GetAdaptersInfo(pAdapterInfo, &ulOutBufLen)) == NO_ERROR) {
pAdapter = pAdapterInfo;
// loop over adapters and match name strings
while (pAdapter) {
string matchName = string(pAdapter->AdapterName);
if (winName.compare(matchName) == 0) {
myMAC = MACAddr(pAdapter->Address);
free(pAdapterInfo);
return myMAC;
}
pAdapter = pAdapter->Next;
}
}
if (pAdapterInfo) free(pAdapterInfo);
//TODO: throw a proper error
logERROR << "Unable to extract MAC address."
return MACAddr("ERROR");
#else
//On Linux we simply look in /sys/class/net/DEVICE_NAME/address
std::ifstream devFile(std::string("/sys/class/net/") + devName + std::string("/address"));
std::string macAddrStr;
getline(devFile, macAddrStr);
return MACAddr(macAddrStr);
#endif
}
string MACAddr::to_string() const{
std::ostringstream ss;
for(const uint8_t curByte : addr){
ss << std::hex << std::setfill('0') << std::setw(2) << static_cast<int>(curByte) << ":";
}
//remove the trailing ":"
string myStr = ss.str();
myStr.pop_back();
return myStr;
}<|endoftext|> |
<commit_before>#include "vtkAppendFilter.h"
#include "vtkCellData.h"
#include "vtkIntArray.h"
#include "vtkIdTypeArray.h"
#include "vtkVersion.h"
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
#include <string>
#include "mesh_converter.h"
template <typename T>
vtkUnstructuredGrid* read(char* fname)
{
std::cout << "Reading from file: " <<fname<<std::endl;
T* reader= T::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(as_unstructured_grid(reader->GetOutput()));
reader->Delete();
return ugrid;
}
template <typename T>
int write(vtkUnstructuredGrid* data, char* fname)
{
std::cout << "Writing to file: " <<fname<<std::endl;
T* writer = T::New();
writer->SetFileName(fname);
writer->SetInputData(data);
writer->Write();
writer->Delete();
return 0;
}
int main(int argc, char *argv[]) {
std::string input_format="exodus";
std::string output_format="gmsh";
int opt, option_index=0, verbosity=0;
static struct option long_options[] = {
{"input_format", required_argument, 0, 'i' },
{"output_format", required_argument, 0, 'o' },
{"help", no_argument, 0, 'h' },
{"quiet", no_argument, 0, 'v' },
{"verbose", no_argument, 0, 'v' },
{"version", no_argument, 0, 'V'},
};
while ( (opt = getopt_long(argc, argv, "i::o::hvV",
long_options, &option_index)) != -1 ) {
switch ( opt ) {
case 'i':
if (optarg) {
input_format = optarg;
}
break;
case 'o':
if (optarg) {
output_format = optarg;
}
break;
case 'h':
print_help(argv[0]);
return EXIT_SUCCESS;
break;
case 'q':
verbosity = 0;
break;
case 'v':
verbosity = 2;
break;
case 'V':
print_version();
return EXIT_SUCCESS;
break;
case '?':
cerr << "Unknown option: '" << char(optopt) << "'!" << endl;
break;
}
}
if (argc <3) {
print_usage(argv[0]);
return 1;
}
vtkUnstructuredGrid* ugdata = NULL;
if (input_format.compare("exodus")==0 ) {
ugdata = read_exodusII(argv[optind++]);
} else if (input_format.compare("gmsh")==0 ) {
ugdata = read<vtkGmshReader>(argv[optind++]);
} else if (input_format.compare("vtu")==0 ) {
ugdata = read_vtu(argv[optind++]);
} else if (input_format.compare("pvtu")==0 ) {
ugdata = read_pvtu(argv[optind++]);
} else if (input_format.compare("triangle")==0 ) {
ugdata = read_triangle(argv[optind++]);
} else {
std::cout<< "Unrecognised input format: "<< input_format << std::endl;
return 1;
}
int flag;
if (output_format.compare("gmsh")==0) {
flag=write_gmsh(ugdata,argv[optind]);
} else if (output_format.compare("vtu")==0) {
flag=write<vtkXMLUnstructuredGridWriter>(ugdata,argv[optind]);
} else if (output_format.compare("vtm")==0) {
flag=write_vtm(as_multiblock(ugdata),argv[optind]);
} else if (output_format.compare("triangle")==0) {
flag=write_triangle(ugdata,argv[optind]);
} else {
std::cout<< "Unrecognised output format: "<<output_format<<std::endl;
return 1;
}
if (ugdata){
ugdata->Delete();
}
return flag;
}
vtkUnstructuredGrid* as_unstructured_grid(vtkDataObject* data) {
if (data->IsA("vtkUnstructuredGrid")) {
return vtkUnstructuredGrid::SafeDownCast(data);
} else if (data->IsA("vtkMultiBlockDataSet")) {
vtkMultiBlockDataSet* mbdata = vtkMultiBlockDataSet::SafeDownCast(data);
return multiblock_to_unstructured_grid(mbdata);
}
return NULL;
}
vtkMultiBlockDataSet* as_multiblock(vtkDataObject* data) {
return NULL;
}
vtkUnstructuredGrid* multiblock_to_unstructured_grid(vtkMultiBlockDataSet* data) {
vtkAppendFilter* appender = vtkAppendFilter::New();
appender->SetMergePoints(1);
vtkMultiBlockDataSet* sidesets = vtkMultiBlockDataSet::SafeDownCast(data->GetBlock(4));
for (int i=0; i<sidesets->GetNumberOfBlocks(); i++) {
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(sidesets->GetBlock(i));
vtkIntArray* eids = vtkIntArray::New();
eids->SetNumberOfValues(ugrid->GetNumberOfCells());
ugrid->GetCellData()->GetArray("ObjectId")->SetName("PhysicalIds");
for (int j=0; j<ugrid->GetNumberOfCells(); j++) {
eids->SetValue(j,i+1);
}
eids->SetName("ElementaryEntities");
ugrid->GetCellData()->AddArray(eids);
appender->AddInputData(ugrid);
}
vtkMultiBlockDataSet* regions = vtkMultiBlockDataSet::SafeDownCast(data->GetBlock(0));
for (int i=0; i<regions->GetNumberOfBlocks(); i++) {
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(regions->GetBlock(i));
ugrid->GetCellData()->GetArray("ObjectId")->SetName("PhysicalIds");
ugrid->GetCellData()->GetArray("GlobalElementId")->SetName("ElementaryEntities");
appender->AddInputData(ugrid);
}
appender->Update();
vtkUnstructuredGrid* output = vtkUnstructuredGrid::New();
output->ShallowCopy(appender->GetOutput());
appender->Delete();
return output;
}
// Special Readers
vtkUnstructuredGrid* read_exodusII(char* fname){
std::cout << "Reading from file: " <<fname<<std::endl;
vtkExodusIIReader* reader = vtkExodusIIReader::New();
reader->SetFileName(fname);
reader->UpdateInformation();
reader->GenerateGlobalNodeIdArrayOn();
reader->GenerateGlobalElementIdArrayOn();
reader->GenerateObjectIdCellArrayOn();
for (int i=0; i<reader->GetNumberOfSideSetArrays(); i++) {
reader->SetSideSetArrayStatus(reader->GetSideSetArrayName(i),1);
}
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(as_unstructured_grid(reader->GetOutput()));
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_gmsh(char* fname) {
std::cout << "Reading from GMSH file: " <<fname<<std::endl;
vtkGmshReader* reader= vtkGmshReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_vtu(char* fname) {
std::cout << "Reading from VTK unstructured grid file: " <<fname<<std::endl;
vtkXMLUnstructuredGridReader* reader= vtkXMLUnstructuredGridReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_pvtu(char* fname) {
std::cout << "Reading from VTK parallel unstructured grid file: " <<fname<<std::endl;
vtkXMLPUnstructuredGridReader* reader= vtkXMLPUnstructuredGridReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_triangle(char* fname) {
std::cout << "Reading from triangle files: " <<fname<<std::endl;
vtkTriangleReader* reader= vtkTriangleReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
int print_usage(char* name){
std::cout << "usage: " << name << " [-i input_format] [-o output_format] [-hqvV] input_file output_file"<<std::endl;
return 0;
}
int print_help(char* name){
print_usage(name);
std::cout << "\t -i --input_format \t Specify mesh format of input file" << std::endl;
std::cout << "\t -i --output_format \t Specify mesh format for output file" << std::endl;
std::cout << "\t -h --help \t Print this message" << std::endl;
std::cout << "\t -q --quiet \t Suppress output except error reporting" << std::endl;
std::cout << "\t -v --verbose \t Increase verbosity" << std::endl;
std::cout << "\t -V --version \t Report version information" << std::endl;
return 0;
}
int print_version(){
std::cout << "mesh_converter "
<< CONVERTER_MAJOR_VERSION<<"."<<CONVERTER_MINOR_VERSION
<<std::endl;
std::cout << "\t Build against VTK version: " << VTK_VERSION << std::endl;
return 0;
}
// Special Writers
int write_gmsh(vtkUnstructuredGrid* data, char* fname){
std::cout << "Writing to file: " <<fname<<std::endl;
vtkGmshWriter* writer = vtkGmshWriter::New();
writer->SetFileName(fname);
writer->SetInputData(data);
writer->Write();
writer->Delete();
return 0;
}
int write_triangle(vtkUnstructuredGrid* data, char* fname){
std::cout << "Writing to files: " <<fname<<std::endl;
vtkTriangleWriter* writer = vtkTriangleWriter::New();
writer->SetFileName(fname);
writer->SetInputData(data);
writer->Write();
writer->Delete();
return 0;
}
int write_vtm(vtkMultiBlockDataSet* data, char* fname){
std::cout << "Writing to file: " <<fname<<std::endl;
vtkXMLMultiBlockDataWriter* writer = vtkXMLMultiBlockDataWriter::New();
writer->SetFileName(fname);
writer->SetInputData(data);
writer->Write();
writer->Delete();
return 0;
}
<commit_msg>Backport to work with VTK 5.<commit_after>#include "vtkAppendFilter.h"
#include "vtkCellData.h"
#include "vtkIntArray.h"
#include "vtkIdTypeArray.h"
#include "vtkVersion.h"
#include <unistd.h>
#include <stdio.h>
#include <getopt.h>
#include <string>
#include "mesh_converter.h"
template <typename T>
vtkUnstructuredGrid* read(char* fname)
{
std::cout << "Reading from file: " <<fname<<std::endl;
T* reader= T::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(as_unstructured_grid(reader->GetOutput()));
reader->Delete();
return ugrid;
}
template <typename T>
int write(vtkUnstructuredGrid* data, char* fname)
{
std::cout << "Writing to file: " <<fname<<std::endl;
T* writer = T::New();
writer->SetFileName(fname);
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(data);
#else
writer->SetInputData(data);
#endif
writer->Write();
writer->Delete();
return 0;
}
int main(int argc, char *argv[]) {
std::string input_format="exodus";
std::string output_format="gmsh";
int opt, option_index=0, verbosity=0;
static struct option long_options[] = {
{"input_format", required_argument, 0, 'i' },
{"output_format", required_argument, 0, 'o' },
{"help", no_argument, 0, 'h' },
{"quiet", no_argument, 0, 'v' },
{"verbose", no_argument, 0, 'v' },
{"version", no_argument, 0, 'V'},
};
while ( (opt = getopt_long(argc, argv, "i::o::hvV",
long_options, &option_index)) != -1 ) {
switch ( opt ) {
case 'i':
if (optarg) {
input_format = optarg;
}
break;
case 'o':
if (optarg) {
output_format = optarg;
}
break;
case 'h':
print_help(argv[0]);
return EXIT_SUCCESS;
break;
case 'q':
verbosity = 0;
break;
case 'v':
verbosity = 2;
break;
case 'V':
print_version();
return EXIT_SUCCESS;
break;
case '?':
cerr << "Unknown option: '" << char(optopt) << "'!" << endl;
break;
}
}
if (argc <3) {
print_usage(argv[0]);
return 1;
}
vtkUnstructuredGrid* ugdata = NULL;
if (input_format.compare("exodus")==0 ) {
ugdata = read_exodusII(argv[optind++]);
} else if (input_format.compare("gmsh")==0 ) {
ugdata = read<vtkGmshReader>(argv[optind++]);
} else if (input_format.compare("vtu")==0 ) {
ugdata = read_vtu(argv[optind++]);
} else if (input_format.compare("pvtu")==0 ) {
ugdata = read_pvtu(argv[optind++]);
} else if (input_format.compare("triangle")==0 ) {
ugdata = read_triangle(argv[optind++]);
} else {
std::cout<< "Unrecognised input format: "<< input_format << std::endl;
return 1;
}
int flag;
if (output_format.compare("gmsh")==0) {
flag=write_gmsh(ugdata,argv[optind]);
} else if (output_format.compare("vtu")==0) {
flag=write<vtkXMLUnstructuredGridWriter>(ugdata,argv[optind]);
} else if (output_format.compare("vtm")==0) {
flag=write_vtm(as_multiblock(ugdata),argv[optind]);
} else if (output_format.compare("triangle")==0) {
flag=write_triangle(ugdata,argv[optind]);
} else {
std::cout<< "Unrecognised output format: "<<output_format<<std::endl;
return 1;
}
if (ugdata){
ugdata->Delete();
}
return flag;
}
vtkUnstructuredGrid* as_unstructured_grid(vtkDataObject* data) {
if (data->IsA("vtkUnstructuredGrid")) {
return vtkUnstructuredGrid::SafeDownCast(data);
} else if (data->IsA("vtkMultiBlockDataSet")) {
vtkMultiBlockDataSet* mbdata = vtkMultiBlockDataSet::SafeDownCast(data);
return multiblock_to_unstructured_grid(mbdata);
}
return NULL;
}
vtkMultiBlockDataSet* as_multiblock(vtkDataObject* data) {
return NULL;
}
vtkUnstructuredGrid* multiblock_to_unstructured_grid(vtkMultiBlockDataSet* data) {
vtkAppendFilter* appender = vtkAppendFilter::New();
appender->SetMergePoints(1);
vtkMultiBlockDataSet* sidesets = vtkMultiBlockDataSet::SafeDownCast(data->GetBlock(4));
for (int i=0; i<sidesets->GetNumberOfBlocks(); i++) {
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(sidesets->GetBlock(i));
vtkIntArray* eids = vtkIntArray::New();
eids->SetNumberOfValues(ugrid->GetNumberOfCells());
ugrid->GetCellData()->GetArray("ObjectId")->SetName("PhysicalIds");
for (int j=0; j<ugrid->GetNumberOfCells(); j++) {
eids->SetValue(j,i+1);
}
eids->SetName("ElementaryEntities");
ugrid->GetCellData()->AddArray(eids);
appender->AddInputData(ugrid);
}
vtkMultiBlockDataSet* regions = vtkMultiBlockDataSet::SafeDownCast(data->GetBlock(0));
for (int i=0; i<regions->GetNumberOfBlocks(); i++) {
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::SafeDownCast(regions->GetBlock(i));
ugrid->GetCellData()->GetArray("ObjectId")->SetName("PhysicalIds");
ugrid->GetCellData()->GetArray("GlobalElementId")->SetName("ElementaryEntities");
appender->AddInputData(ugrid);
}
appender->Update();
vtkUnstructuredGrid* output = vtkUnstructuredGrid::New();
output->ShallowCopy(appender->GetOutput());
appender->Delete();
return output;
}
// Special Readers
vtkUnstructuredGrid* read_exodusII(char* fname){
std::cout << "Reading from file: " <<fname<<std::endl;
vtkExodusIIReader* reader = vtkExodusIIReader::New();
reader->SetFileName(fname);
reader->UpdateInformation();
reader->GenerateGlobalNodeIdArrayOn();
reader->GenerateGlobalElementIdArrayOn();
reader->GenerateObjectIdCellArrayOn();
for (int i=0; i<reader->GetNumberOfSideSetArrays(); i++) {
reader->SetSideSetArrayStatus(reader->GetSideSetArrayName(i),1);
}
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(as_unstructured_grid(reader->GetOutput()));
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_gmsh(char* fname) {
std::cout << "Reading from GMSH file: " <<fname<<std::endl;
vtkGmshReader* reader= vtkGmshReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_vtu(char* fname) {
std::cout << "Reading from VTK unstructured grid file: " <<fname<<std::endl;
vtkXMLUnstructuredGridReader* reader= vtkXMLUnstructuredGridReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_pvtu(char* fname) {
std::cout << "Reading from VTK parallel unstructured grid file: " <<fname<<std::endl;
vtkXMLPUnstructuredGridReader* reader= vtkXMLPUnstructuredGridReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
vtkUnstructuredGrid* read_triangle(char* fname) {
std::cout << "Reading from triangle files: " <<fname<<std::endl;
vtkTriangleReader* reader= vtkTriangleReader::New();
reader->SetFileName(fname);
reader->Update();
vtkUnstructuredGrid* ugrid = vtkUnstructuredGrid::New();
ugrid->ShallowCopy(reader->GetOutput());
reader->Delete();
return ugrid;
}
int print_usage(char* name){
std::cout << "usage: " << name << " [-i input_format] [-o output_format] [-hqvV] input_file output_file"<<std::endl;
return 0;
}
int print_help(char* name){
print_usage(name);
std::cout << "\t -i --input_format \t Specify mesh format of input file" << std::endl;
std::cout << "\t -i --output_format \t Specify mesh format for output file" << std::endl;
std::cout << "\t -h --help \t Print this message" << std::endl;
std::cout << "\t -q --quiet \t Suppress output except error reporting" << std::endl;
std::cout << "\t -v --verbose \t Increase verbosity" << std::endl;
std::cout << "\t -V --version \t Report version information" << std::endl;
return 0;
}
int print_version(){
std::cout << "mesh_converter "
<< CONVERTER_MAJOR_VERSION<<"."<<CONVERTER_MINOR_VERSION
<<std::endl;
std::cout << "\t Build against VTK version: " << VTK_VERSION << std::endl;
return 0;
}
// Special Writers
int write_gmsh(vtkUnstructuredGrid* data, char* fname){
std::cout << "Writing to file: " <<fname<<std::endl;
vtkGmshWriter* writer = vtkGmshWriter::New();
writer->SetFileName(fname);
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(data);
#else
writer->SetInputData(data);
#endif
writer->Write();
writer->Delete();
return 0;
}
int write_triangle(vtkUnstructuredGrid* data, char* fname){
std::cout << "Writing to files: " <<fname<<std::endl;
vtkTriangleWriter* writer = vtkTriangleWriter::New();
writer->SetFileName(fname);
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(data);
#else
writer->SetInputData(data);
#endif
writer->Write();
writer->Delete();
return 0;
}
int write_vtm(vtkMultiBlockDataSet* data, char* fname){
std::cout << "Writing to file: " <<fname<<std::endl;
vtkXMLMultiBlockDataWriter* writer = vtkXMLMultiBlockDataWriter::New();
writer->SetFileName(fname);
#if VTK_MAJOR_VERSION <= 5
writer->SetInput(data);
#else
writer->SetInputData(data);
#endif
writer->Write();
writer->Delete();
return 0;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2007-2008 by Tommi Rantala <tt.rantala@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/*
* This file contains several variants of MSD radix sort that uses dynamic
* buckets instead of first making the extra sweep over the input to calculate
* each size.
*
* Because strings can be expensive to access (indirect addressing, cache
* misses, memory stalls), these variants are actually rather efficient.
*
* There are several variants that use different choice of the actual dynamic
* memory structure. For each implementation, there is also an adaptive
* version, that uses two byte superalphabet when the size of the subinput is
* large, and normal alphabet otherwise.
*/
#include "routine.h"
#include "util/insertion_sort.h"
#include "util/get_char.h"
#include <cstring>
#include <cstddef>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
#include "vector_realloc.h"
#include "vector_malloc.h"
#include "vector_block.h"
#include "vector_brodnik.h"
#include "vector_bagwell.h"
#include <boost/array.hpp>
// std::list::size() is O(n), so keep track of size manually.
template <typename T>
class counting_list : public std::list<T>
{
public:
counting_list() : _size(0) {}
void push_back(const T& x)
{
++_size;
std::list<T>::push_back(x);
}
size_t size() const
{
return _size;
}
void clear()
{
_size = 0;
std::list<T>::clear();
}
private:
size_t _size;
};
template <typename BucketT, typename OutputIterator>
static inline void
copy(const BucketT& bucket, OutputIterator dst)
{
std::copy(bucket.begin(), bucket.end(), dst);
}
template <typename Bucket, typename BucketsizeType>
static void
msd_D(unsigned char** strings, size_t n, size_t depth, Bucket* buckets)
{
if (n < 32) {
insertion_sort(strings, n, depth);
return;
}
// Use a small cache to reduce memory stalls.
size_t i=0;
for (; i < n-n%32; i+=32) {
unsigned char cache[32];
for (unsigned j=0; j < 32; ++j) {
cache[j] = strings[i+j][depth];
}
for (unsigned j=0; j < 32; ++j) {
buckets[cache[j]].push_back(strings[i+j]);
}
}
for (; i < n; ++i) {
buckets[strings[i][depth]].push_back(strings[i]);
}
boost::array<BucketsizeType, 256> bucketsize;
for (unsigned i=0; i < 256; ++i) {
bucketsize[i] = buckets[i].size();
}
size_t pos = 0;
for (unsigned i=0; i < 256; ++i) {
if (bucketsize[i] == 0) continue;
copy(buckets[i], strings+pos);
pos += bucketsize[i];
}
for (unsigned i=0; i < 256; ++i) {
buckets[i].clear();
}
pos = bucketsize[0];
for (unsigned i=1; i < 256; ++i) {
if (bucketsize[i] == 0) continue;
msd_D<Bucket, BucketsizeType>(strings+pos, bucketsize[i], depth+1, buckets);
pos += bucketsize[i];
}
}
template <typename Bucket>
static void
msd_D_adaptive(unsigned char** strings, size_t n, size_t depth, Bucket* buckets)
{
if (n < 0x10000) {
msd_D<Bucket, uint16_t>(strings, n, depth, buckets);
return;
}
size_t* bucketsize = (size_t*) malloc(0x10000 * sizeof(size_t));
size_t i=0;
for (; i < n-n%16; i+=16) {
uint16_t cache[16];
for (size_t j=0; j < 16; ++j) {
cache[j] = get_char<uint16_t>(strings[i+j], depth);
}
for (size_t j=0; j < 16; ++j) {
buckets[cache[j]].push_back(strings[i+j]);
}
}
for (; i < n; ++i) {
const uint16_t ch = get_char<uint16_t>(strings[i], depth);
buckets[ch].push_back(strings[i]);
}
for (unsigned i=0; i < 0x10000; ++i) {
bucketsize[i] = buckets[i].size();
}
size_t pos = 0;
for (unsigned i=0; i < 0x10000; ++i) {
if (bucketsize[i] == 0) continue;
copy(buckets[i], strings+pos);
pos += bucketsize[i];
}
for (unsigned i=0; i < 0x10000; ++i) {
buckets[i].clear();
}
pos = bucketsize[0];
for (unsigned i=1; i < 0x10000; ++i) {
if (bucketsize[i] == 0) continue;
if (i & 0xFF) msd_D_adaptive(
strings+pos, bucketsize[i],
depth+2, buckets);
pos += bucketsize[i];
}
free(bucketsize);
}
#define MAKE_ALG2(name, vec) \
void msd_D_##name(unsigned char** strings, size_t n) \
{ \
vec<unsigned char*> buckets[256]; \
msd_D<vec<unsigned char*>, size_t>(strings, n, 0, buckets); \
} \
ROUTINE_REGISTER_SINGLECORE(msd_D_##name, "msd_D_"#name) \
void msd_D_##name##_adaptive(unsigned char** strings, size_t n) \
{ \
vec<unsigned char*> buckets[0x10000]; \
msd_D_adaptive(strings, n, 0, buckets); \
} \
ROUTINE_REGISTER_SINGLECORE(msd_D_##name##_adaptive, "msd_D_"#name"_adaptive")
#define MAKE_ALG1(vec) MAKE_ALG2(vec, vec)
MAKE_ALG2(std_vector, std::vector)
MAKE_ALG2(std_deque, std::deque)
MAKE_ALG2(std_list, counting_list)
MAKE_ALG1(vector_realloc)
MAKE_ALG1(vector_malloc)
MAKE_ALG1(vector_realloc_counter_clear)
MAKE_ALG1(vector_malloc_counter_clear)
MAKE_ALG1(vector_realloc_shrink_clear)
MAKE_ALG1(vector_block)
MAKE_ALG1(vector_brodnik)
MAKE_ALG1(vector_bagwell)
<commit_msg>Allocate buckets dynamically to reduce stack usage in msd_D_*_adaptive()<commit_after>/*
* Copyright 2007-2008 by Tommi Rantala <tt.rantala@gmail.com>
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to
* deal in the Software without restriction, including without limitation the
* rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
* sell copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in
* all copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
* FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS
* IN THE SOFTWARE.
*/
/*
* This file contains several variants of MSD radix sort that uses dynamic
* buckets instead of first making the extra sweep over the input to calculate
* each size.
*
* Because strings can be expensive to access (indirect addressing, cache
* misses, memory stalls), these variants are actually rather efficient.
*
* There are several variants that use different choice of the actual dynamic
* memory structure. For each implementation, there is also an adaptive
* version, that uses two byte superalphabet when the size of the subinput is
* large, and normal alphabet otherwise.
*/
#include "routine.h"
#include "util/insertion_sort.h"
#include "util/get_char.h"
#include <cstring>
#include <cstddef>
#include <vector>
#include <list>
#include <deque>
#include <algorithm>
#include "vector_realloc.h"
#include "vector_malloc.h"
#include "vector_block.h"
#include "vector_brodnik.h"
#include "vector_bagwell.h"
#include <boost/array.hpp>
// std::list::size() is O(n), so keep track of size manually.
template <typename T>
class counting_list : public std::list<T>
{
public:
counting_list() : _size(0) {}
void push_back(const T& x)
{
++_size;
std::list<T>::push_back(x);
}
size_t size() const
{
return _size;
}
void clear()
{
_size = 0;
std::list<T>::clear();
}
private:
size_t _size;
};
template <typename BucketT, typename OutputIterator>
static inline void
copy(const BucketT& bucket, OutputIterator dst)
{
std::copy(bucket.begin(), bucket.end(), dst);
}
template <typename Bucket, typename BucketsizeType>
static void
msd_D(unsigned char** strings, size_t n, size_t depth, Bucket* buckets)
{
if (n < 32) {
insertion_sort(strings, n, depth);
return;
}
// Use a small cache to reduce memory stalls.
size_t i=0;
for (; i < n-n%32; i+=32) {
unsigned char cache[32];
for (unsigned j=0; j < 32; ++j) {
cache[j] = strings[i+j][depth];
}
for (unsigned j=0; j < 32; ++j) {
buckets[cache[j]].push_back(strings[i+j]);
}
}
for (; i < n; ++i) {
buckets[strings[i][depth]].push_back(strings[i]);
}
boost::array<BucketsizeType, 256> bucketsize;
for (unsigned i=0; i < 256; ++i) {
bucketsize[i] = buckets[i].size();
}
size_t pos = 0;
for (unsigned i=0; i < 256; ++i) {
if (bucketsize[i] == 0) continue;
copy(buckets[i], strings+pos);
pos += bucketsize[i];
}
for (unsigned i=0; i < 256; ++i) {
buckets[i].clear();
}
pos = bucketsize[0];
for (unsigned i=1; i < 256; ++i) {
if (bucketsize[i] == 0) continue;
msd_D<Bucket, BucketsizeType>(strings+pos, bucketsize[i], depth+1, buckets);
pos += bucketsize[i];
}
}
template <typename Bucket>
static void
msd_D_adaptive(unsigned char** strings, size_t n, size_t depth, Bucket* buckets)
{
if (n < 0x10000) {
msd_D<Bucket, uint16_t>(strings, n, depth, buckets);
return;
}
size_t* bucketsize = (size_t*) malloc(0x10000 * sizeof(size_t));
size_t i=0;
for (; i < n-n%16; i+=16) {
uint16_t cache[16];
for (size_t j=0; j < 16; ++j) {
cache[j] = get_char<uint16_t>(strings[i+j], depth);
}
for (size_t j=0; j < 16; ++j) {
buckets[cache[j]].push_back(strings[i+j]);
}
}
for (; i < n; ++i) {
const uint16_t ch = get_char<uint16_t>(strings[i], depth);
buckets[ch].push_back(strings[i]);
}
for (unsigned i=0; i < 0x10000; ++i) {
bucketsize[i] = buckets[i].size();
}
size_t pos = 0;
for (unsigned i=0; i < 0x10000; ++i) {
if (bucketsize[i] == 0) continue;
copy(buckets[i], strings+pos);
pos += bucketsize[i];
}
for (unsigned i=0; i < 0x10000; ++i) {
buckets[i].clear();
}
pos = bucketsize[0];
for (unsigned i=1; i < 0x10000; ++i) {
if (bucketsize[i] == 0) continue;
if (i & 0xFF) msd_D_adaptive(
strings+pos, bucketsize[i],
depth+2, buckets);
pos += bucketsize[i];
}
free(bucketsize);
}
#define MAKE_ALG2(name, vec) \
void msd_D_##name(unsigned char** strings, size_t n) \
{ \
vec<unsigned char*> buckets[256]; \
msd_D<vec<unsigned char*>, size_t>(strings, n, 0, buckets); \
} \
ROUTINE_REGISTER_SINGLECORE(msd_D_##name, "msd_D_"#name) \
void msd_D_##name##_adaptive(unsigned char** strings, size_t n) \
{ \
vec<unsigned char*>* buckets = new vec<unsigned char*>[0x10000]; \
msd_D_adaptive(strings, n, 0, buckets); \
delete [] buckets; \
} \
ROUTINE_REGISTER_SINGLECORE(msd_D_##name##_adaptive, "msd_D_"#name"_adaptive")
#define MAKE_ALG1(vec) MAKE_ALG2(vec, vec)
MAKE_ALG2(std_vector, std::vector)
MAKE_ALG2(std_deque, std::deque)
MAKE_ALG2(std_list, counting_list)
MAKE_ALG1(vector_realloc)
MAKE_ALG1(vector_malloc)
MAKE_ALG1(vector_realloc_counter_clear)
MAKE_ALG1(vector_malloc_counter_clear)
MAKE_ALG1(vector_realloc_shrink_clear)
MAKE_ALG1(vector_block)
MAKE_ALG1(vector_brodnik)
MAKE_ALG1(vector_bagwell)
<|endoftext|> |
<commit_before>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <atomic>
#include "assert.hpp"
#include "Function.hpp"
#include "mtac/Quadruple.hpp"
#include "mtac/Printer.hpp"
using namespace eddic;
static std::atomic<std::size_t> uid_counter(0);
mtac::Quadruple::Quadruple() : _uid(++uid_counter) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator o) : _uid(++uid_counter), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(std::shared_ptr<Variable> result, mtac::Argument a1, mtac::Operator o) : _uid(++uid_counter), result(result), arg1(a1), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(std::shared_ptr<Variable> result, mtac::Argument a1, mtac::Operator o, mtac::Argument a2) : _uid(++uid_counter), result(result), arg1(a1), arg2(a2), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator o, mtac::Argument a1) : _uid(++uid_counter), arg1(a1), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator o, mtac::Argument a1, mtac::Argument a2) : _uid(++uid_counter), arg1(a1), arg2(a2), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(const std::string& param, mtac::Operator op) : _uid(++uid_counter), op(op), m_param(param){
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator op, mtac::Argument arg, std::shared_ptr<Variable> param, eddic::Function& function) : _uid(++uid_counter), result(param), arg1(arg), op(op), m_function(&function) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator op, mtac::Argument arg, const std::string& param, eddic::Function& function) : _uid(++uid_counter), arg1(arg), op(op), m_function(&function), m_param(param){
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator op, eddic::Function& function, std::shared_ptr<Variable> return1, std::shared_ptr<Variable> return2) : _uid(++uid_counter), result(return1), op(op), secondary(return2), m_function(&function){
eddic_assert(m_function, "Function is mandatory for calls");
}
mtac::Quadruple::Quadruple(mtac::Operator op, mtac::Argument arg, const std::string& label) : _uid(++uid_counter), arg1(arg), op(op), m_param(label) {
//Nothing to init
}
mtac::Quadruple::Quadruple(const mtac::Quadruple& rhs) :
_uid(++uid_counter),
result(rhs.result),
arg1(rhs.arg1),
arg2(rhs.arg2),
op(rhs.op),
size(rhs.size),
address(rhs.address),
depth(rhs.depth),
secondary(rhs.secondary),
m_function(rhs.m_function),
m_param(rhs.m_param),
block(rhs.block)
{
std::cout << "COPY" << std::endl;
//There is a new reference to the called function
if(op == mtac::Operator::CALL){
++m_function->references();
}
}
mtac::Quadruple& mtac::Quadruple::operator=(const mtac::Quadruple& rhs){
std::cout << "COPY" << std::endl;
//No need to assign this into this
if(this == &rhs){
return *this;
}
_uid = ++uid_counter;
result = rhs.result;
arg1 = rhs.arg1;
arg2 = rhs.arg2;
op = rhs.op;
size = rhs.size;
block = rhs.block;
address = rhs.address;
depth = rhs.depth;
m_function = rhs.m_function;
m_param = rhs.m_param;
secondary = rhs.secondary;
//There is a new reference to the called function
if(op == mtac::Operator::CALL){
++m_function->references();
}
return *this;
}
mtac::Quadruple::Quadruple(mtac::Quadruple&& rhs) noexcept :
_uid(std::move(rhs._uid)),
result(std::move(rhs.result)),
arg1(std::move(rhs.arg1)),
arg2(std::move(rhs.arg2)),
op(std::move(rhs.op)),
size(std::move(rhs.size)),
address(std::move(rhs.address)),
depth(std::move(rhs.depth)),
secondary(std::move(rhs.secondary)),
m_function(std::move(rhs.m_function)),
m_param(std::move(rhs.m_param)),
block(std::move(rhs.block))
{
rhs._uid = 0;
}
mtac::Quadruple& mtac::Quadruple::operator=(mtac::Quadruple&& rhs) noexcept {
//No need to assign this into this
if(this == &rhs){
return *this;
}
_uid = std::move(rhs._uid);
result = std::move(rhs.result);
arg1 = std::move(rhs.arg1);
arg2 = std::move(rhs.arg2);
op = std::move(rhs.op);
size = std::move(rhs.size);
block = std::move(rhs.block);
address = std::move(rhs.address);
depth = std::move(rhs.depth);
m_function = std::move(rhs.m_function);
m_param = std::move(rhs.m_param);
secondary = std::move(rhs.secondary);
rhs._uid = 0;
return *this;
}
std::size_t mtac::Quadruple::uid() const {
return _uid;
}
const std::string& mtac::Quadruple::label() const {
return m_param;
}
const std::string& mtac::Quadruple::std_param() const {
return m_param;
}
eddic::Function& mtac::Quadruple::function(){
eddic_assert(m_function, "function() can only be called on operations that support it");
return *m_function;
}
const eddic::Function& mtac::Quadruple::function() const {
eddic_assert(m_function, "function() can only be called on operations that support it");
return *m_function;
}
const std::shared_ptr<Variable>& mtac::Quadruple::param() const {
return result;
}
const std::shared_ptr<Variable>& mtac::Quadruple::return1() const {
return result;
}
const std::shared_ptr<Variable>& mtac::Quadruple::return2() const {
return secondary;
}
bool mtac::Quadruple::is_if(){
return op >= mtac::Operator::IF_UNARY && op <= mtac::Operator::IF_FL;
}
bool mtac::Quadruple::is_if_false(){
return op >= mtac::Operator::IF_FALSE_UNARY && op <= mtac::Operator::IF_FALSE_FL;
}
bool mtac::Quadruple::operator==(const mtac::Quadruple& rhs) const {
return _uid == rhs._uid;
}
bool mtac::Quadruple::operator!=(const mtac::Quadruple& rhs) const {
return !(*this == rhs);
}
std::ostream& eddic::mtac::operator<<(std::ostream& stream, const mtac::Quadruple& quadruple){
mtac::Printer printer;
printer.print_inline(quadruple, stream);
return stream;
}
<commit_msg>Remove logging<commit_after>//=======================================================================
// Copyright Baptiste Wicht 2011-2012.
// Distributed under the Boost Software License, Version 1.0.
// (See accompanying file LICENSE_1_0.txt or copy at
// http://www.boost.org/LICENSE_1_0.txt)
//=======================================================================
#include <atomic>
#include "assert.hpp"
#include "Function.hpp"
#include "mtac/Quadruple.hpp"
#include "mtac/Printer.hpp"
using namespace eddic;
static std::atomic<std::size_t> uid_counter(0);
mtac::Quadruple::Quadruple() : _uid(++uid_counter) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator o) : _uid(++uid_counter), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(std::shared_ptr<Variable> result, mtac::Argument a1, mtac::Operator o) : _uid(++uid_counter), result(result), arg1(a1), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(std::shared_ptr<Variable> result, mtac::Argument a1, mtac::Operator o, mtac::Argument a2) : _uid(++uid_counter), result(result), arg1(a1), arg2(a2), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator o, mtac::Argument a1) : _uid(++uid_counter), arg1(a1), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator o, mtac::Argument a1, mtac::Argument a2) : _uid(++uid_counter), arg1(a1), arg2(a2), op(o) {
//Nothing to init
}
mtac::Quadruple::Quadruple(const std::string& param, mtac::Operator op) : _uid(++uid_counter), op(op), m_param(param){
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator op, mtac::Argument arg, std::shared_ptr<Variable> param, eddic::Function& function) : _uid(++uid_counter), result(param), arg1(arg), op(op), m_function(&function) {
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator op, mtac::Argument arg, const std::string& param, eddic::Function& function) : _uid(++uid_counter), arg1(arg), op(op), m_function(&function), m_param(param){
//Nothing to init
}
mtac::Quadruple::Quadruple(mtac::Operator op, eddic::Function& function, std::shared_ptr<Variable> return1, std::shared_ptr<Variable> return2) : _uid(++uid_counter), result(return1), op(op), secondary(return2), m_function(&function){
eddic_assert(m_function, "Function is mandatory for calls");
}
mtac::Quadruple::Quadruple(mtac::Operator op, mtac::Argument arg, const std::string& label) : _uid(++uid_counter), arg1(arg), op(op), m_param(label) {
//Nothing to init
}
mtac::Quadruple::Quadruple(const mtac::Quadruple& rhs) :
_uid(++uid_counter),
result(rhs.result),
arg1(rhs.arg1),
arg2(rhs.arg2),
op(rhs.op),
size(rhs.size),
address(rhs.address),
depth(rhs.depth),
secondary(rhs.secondary),
m_function(rhs.m_function),
m_param(rhs.m_param),
block(rhs.block)
{
//There is a new reference to the called function
if(op == mtac::Operator::CALL){
++m_function->references();
}
}
mtac::Quadruple& mtac::Quadruple::operator=(const mtac::Quadruple& rhs){
//No need to assign this into this
if(this == &rhs){
return *this;
}
_uid = ++uid_counter;
result = rhs.result;
arg1 = rhs.arg1;
arg2 = rhs.arg2;
op = rhs.op;
size = rhs.size;
block = rhs.block;
address = rhs.address;
depth = rhs.depth;
m_function = rhs.m_function;
m_param = rhs.m_param;
secondary = rhs.secondary;
//There is a new reference to the called function
if(op == mtac::Operator::CALL){
++m_function->references();
}
return *this;
}
mtac::Quadruple::Quadruple(mtac::Quadruple&& rhs) noexcept :
_uid(std::move(rhs._uid)),
result(std::move(rhs.result)),
arg1(std::move(rhs.arg1)),
arg2(std::move(rhs.arg2)),
op(std::move(rhs.op)),
size(std::move(rhs.size)),
address(std::move(rhs.address)),
depth(std::move(rhs.depth)),
secondary(std::move(rhs.secondary)),
m_function(std::move(rhs.m_function)),
m_param(std::move(rhs.m_param)),
block(std::move(rhs.block))
{
rhs._uid = 0;
}
mtac::Quadruple& mtac::Quadruple::operator=(mtac::Quadruple&& rhs) noexcept {
//No need to assign this into this
if(this == &rhs){
return *this;
}
_uid = std::move(rhs._uid);
result = std::move(rhs.result);
arg1 = std::move(rhs.arg1);
arg2 = std::move(rhs.arg2);
op = std::move(rhs.op);
size = std::move(rhs.size);
block = std::move(rhs.block);
address = std::move(rhs.address);
depth = std::move(rhs.depth);
m_function = std::move(rhs.m_function);
m_param = std::move(rhs.m_param);
secondary = std::move(rhs.secondary);
rhs._uid = 0;
return *this;
}
std::size_t mtac::Quadruple::uid() const {
return _uid;
}
const std::string& mtac::Quadruple::label() const {
return m_param;
}
const std::string& mtac::Quadruple::std_param() const {
return m_param;
}
eddic::Function& mtac::Quadruple::function(){
eddic_assert(m_function, "function() can only be called on operations that support it");
return *m_function;
}
const eddic::Function& mtac::Quadruple::function() const {
eddic_assert(m_function, "function() can only be called on operations that support it");
return *m_function;
}
const std::shared_ptr<Variable>& mtac::Quadruple::param() const {
return result;
}
const std::shared_ptr<Variable>& mtac::Quadruple::return1() const {
return result;
}
const std::shared_ptr<Variable>& mtac::Quadruple::return2() const {
return secondary;
}
bool mtac::Quadruple::is_if(){
return op >= mtac::Operator::IF_UNARY && op <= mtac::Operator::IF_FL;
}
bool mtac::Quadruple::is_if_false(){
return op >= mtac::Operator::IF_FALSE_UNARY && op <= mtac::Operator::IF_FALSE_FL;
}
bool mtac::Quadruple::operator==(const mtac::Quadruple& rhs) const {
return _uid == rhs._uid;
}
bool mtac::Quadruple::operator!=(const mtac::Quadruple& rhs) const {
return !(*this == rhs);
}
std::ostream& eddic::mtac::operator<<(std::ostream& stream, const mtac::Quadruple& quadruple){
mtac::Printer printer;
printer.print_inline(quadruple, stream);
return stream;
}
<|endoftext|> |
<commit_before>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <math.h>
#include <votca/tools/histogramnew.h>
#include <votca/tools/tokenizer.h>
#include <votca/csg/csgapplication.h>
using namespace std;
using namespace votca::csg;
using namespace votca::tools;
class CsgDensityApp
: public CsgApplication
{
string ProgramName() { return "csg_density"; }
void HelpText(ostream &out) {
out << "Calculates the mass density distribution along a box axis or radial density profile from reference point";
}
// some program options are added here
void Initialize();
// we want to process a trajectory
bool DoTrajectory() {return true;}
bool DoMapping() {return true;}
bool DoMappingDefault(void) { return false; }
// write out results in EndEvaluate
void EndEvaluate();
void BeginEvaluate(Topology *top, Topology *top_atom);
void EvalConfiguration(Topology *top, Topology *top_ref);
bool EvaluateOptions() {
CsgApplication::EvaluateOptions();
CheckRequired("out", "no output topology specified");
CheckRequired("trj", "no trajectory file specified");
return true;
};
protected:
string _filter, _out;
HistogramNew _dist;
double _rmax;
int _nbin;
double _scale;
int _frames;
int _nblock;
int _block_length;
vec _ref;
vec _axis;
string _axisname;
string _molname;
double _area;
void WriteDensity(int nframes,const string &suffix="");
};
int main(int argc, char** argv)
{
CsgDensityApp app;
return app.Exec(argc, argv);
}
void CsgDensityApp::BeginEvaluate(Topology *top, Topology *top_atom) {
matrix box = top->getBox();
vec a = box.getCol(0);
vec b = box.getCol(1);
vec c = box.getCol(2);
_dist.setPeriodic(true);
_axis=vec(0,0,0);
_area=0;
if(_axisname=="x") {
_axis.setX(1);
_rmax = abs(a);
_area= abs(b^c);
}
else if(_axisname=="y") {
_axis.setY(1);
_rmax = abs(b);
_area= abs(a^c);
}
else if(_axisname=="z") {
_axis.setZ(1);
_rmax = abs(c);
_area= abs(a^b);
}
else if(_axisname=="r") {
_dist.setPeriodic(false);
_rmax = min(min(abs(a/2), abs(b/2)), abs(c/2));
} else {
throw std::runtime_error("unknown axis type");
}
if(OptionsMap().count("rmax"))
_rmax = OptionsMap()["rmax"].as<double>();
if(OptionsMap().count("block-length")){
_block_length=OptionsMap()["block-length"].as<int>();
} else {
_block_length=0;
}
if (_axisname=="r") {
if(!OptionsMap().count("ref"))
_ref = a/2+b/2+c/2;
cout << "Using referece point: " << _ref << endl;
}
else if(OptionsMap().count("ref"))
throw std::runtime_error("reference center can only be used in case of spherical density");
_dist.Initialize(0, _rmax, _nbin);
cout << "rmax: " << _rmax << endl;
cout << "axis: " << _axisname << endl;
cout << "Bins: " << _nbin << endl;
_frames=0;
_nblock=0;
}
void CsgDensityApp::EvalConfiguration(Topology *top, Topology *top_ref)
{
// loop over all molecules
bool did_something = false;
for(MoleculeContainer::iterator imol=top->Molecules().begin(); imol!=top->Molecules().end(); ++imol) {
Molecule *mol = *imol;
if(!wildcmp(_molname.c_str(),mol->getName().c_str()))
continue;
int N = mol->BeadCount();
for(int i=0; i<N; i++) {
Bead *b = mol->getBead(i);
if(!wildcmp(_filter.c_str(), b->getName().c_str()))
continue;
double r;
if (_axisname=="r") {
r = abs(top->BCShortestConnection(_ref, b->getPos()));
} else {
r = b->getPos() * _axis;
}
_dist.Process(r, b->getM());
did_something = true;
}
}
_frames++;
if (!did_something) throw std::runtime_error("No molecule in selection");
if(_block_length != 0) {
if((_nframes % _block_length)==0) {
_nblock++;
string suffix = string("_") + boost::lexical_cast<string>(_nblock);
WriteDensity(_block_length,suffix);
_dist.Clear();
}
}
}
// output everything when processing frames is done
void CsgDensityApp::WriteDensity(int nframes, const string &suffix)
{
if (_axisname=="r") {
_dist.data().y() = _scale/(nframes*_rmax/(double)_nbin *4*M_PI) * element_div( _dist.data().y(),
element_prod(_dist.data().x(), _dist.data().x()));
} else {
_dist.data().y() = _scale/((double)nframes * _area * _rmax/ (double)_nbin ) *_dist.data().y();
}
_dist.data().Save(_out + suffix);
}
void CsgDensityApp::EndEvaluate()
{
if(_block_length == 0)
WriteDensity(_frames);
}
// add our user program options
void CsgDensityApp::Initialize()
{
CsgApplication::Initialize();
// add program option to pick molecule
AddProgramOptions("Specific options:")
("axis", boost::program_options::value<string>(&_axisname)->default_value("r"), "[x|y|z|r] density axis (r=spherical)")
("bins", boost::program_options::value<int>(&_nbin)->default_value(50), "bins")
("block-length", boost::program_options::value<int>(), " write blocks of this length, the averages are cleared after every write")
("out", boost::program_options::value<string>(&_out), "Output file")
("rmax", boost::program_options::value<double>(), "rmax (default for [r] =min of all box vectors/2, else l )")
("scale", boost::program_options::value<double>(&_scale)->default_value(1.0), "scale factor for the density")
("molname", boost::program_options::value<string>(&_molname)->default_value("*"), "molname")
("filter", boost::program_options::value<string>(&_filter)->default_value("*"), "filter bead names")
("ref", boost::program_options::value<vec>(&_ref), "reference zero point");
}
<commit_msg>csg_density: --bins -> --step<commit_after>/*
* Copyright 2009-2011 The VOTCA Development Team (http://www.votca.org)
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*
*/
#include <math.h>
#include <votca/tools/histogramnew.h>
#include <votca/tools/tokenizer.h>
#include <votca/csg/csgapplication.h>
using namespace std;
using namespace votca::csg;
using namespace votca::tools;
class CsgDensityApp
: public CsgApplication
{
string ProgramName() { return "csg_density"; }
void HelpText(ostream &out) {
out << "Calculates the mass density distribution along a box axis or radial density profile from reference point";
}
// some program options are added here
void Initialize();
// we want to process a trajectory
bool DoTrajectory() {return true;}
bool DoMapping() {return true;}
bool DoMappingDefault(void) { return false; }
// write out results in EndEvaluate
void EndEvaluate();
void BeginEvaluate(Topology *top, Topology *top_atom);
void EvalConfiguration(Topology *top, Topology *top_ref);
bool EvaluateOptions() {
CsgApplication::EvaluateOptions();
CheckRequired("out", "no output topology specified");
CheckRequired("trj", "no trajectory file specified");
return true;
};
protected:
string _filter, _out;
HistogramNew _dist;
double _rmax;
int _nbin;
double _scale;
double _step;
int _frames;
int _nblock;
int _block_length;
vec _ref;
vec _axis;
string _axisname;
string _molname;
double _area;
void WriteDensity(int nframes,const string &suffix="");
};
int main(int argc, char** argv)
{
CsgDensityApp app;
return app.Exec(argc, argv);
}
void CsgDensityApp::BeginEvaluate(Topology *top, Topology *top_atom) {
matrix box = top->getBox();
vec a = box.getCol(0);
vec b = box.getCol(1);
vec c = box.getCol(2);
_dist.setPeriodic(true);
_axis=vec(0,0,0);
_area=0;
if(_axisname=="x") {
_axis.setX(1);
_rmax = abs(a);
_area= abs(b^c);
}
else if(_axisname=="y") {
_axis.setY(1);
_rmax = abs(b);
_area= abs(a^c);
}
else if(_axisname=="z") {
_axis.setZ(1);
_rmax = abs(c);
_area= abs(a^b);
}
else if(_axisname=="r") {
_dist.setPeriodic(false);
_rmax = min(min(abs(a/2), abs(b/2)), abs(c/2));
} else {
throw std::runtime_error("unknown axis type");
}
if(OptionsMap().count("rmax"))
_rmax = OptionsMap()["rmax"].as<double>();
if(OptionsMap().count("block-length")){
_block_length=OptionsMap()["block-length"].as<int>();
} else {
_block_length=0;
}
if (_axisname=="r") {
if(!OptionsMap().count("ref"))
_ref = a/2+b/2+c/2;
cout << "Using referece point: " << _ref << endl;
}
else if(OptionsMap().count("ref"))
throw std::runtime_error("reference center can only be used in case of spherical density");
_nbin=(int)floor(_rmax/_step);
_dist.Initialize(0, _rmax, _nbin);
cout << "rmax: " << _rmax << endl;
cout << "axis: " << _axisname << endl;
cout << "Bins: " << _nbin << endl;
_frames=0;
_nblock=0;
}
void CsgDensityApp::EvalConfiguration(Topology *top, Topology *top_ref)
{
// loop over all molecules
bool did_something = false;
for(MoleculeContainer::iterator imol=top->Molecules().begin(); imol!=top->Molecules().end(); ++imol) {
Molecule *mol = *imol;
if(!wildcmp(_molname.c_str(),mol->getName().c_str()))
continue;
int N = mol->BeadCount();
for(int i=0; i<N; i++) {
Bead *b = mol->getBead(i);
if(!wildcmp(_filter.c_str(), b->getName().c_str()))
continue;
double r;
if (_axisname=="r") {
r = abs(top->BCShortestConnection(_ref, b->getPos()));
} else {
r = b->getPos() * _axis;
}
_dist.Process(r, b->getM());
did_something = true;
}
}
_frames++;
if (!did_something) throw std::runtime_error("No molecule in selection");
if(_block_length != 0) {
if((_nframes % _block_length)==0) {
_nblock++;
string suffix = string("_") + boost::lexical_cast<string>(_nblock);
WriteDensity(_block_length,suffix);
_dist.Clear();
}
}
}
// output everything when processing frames is done
void CsgDensityApp::WriteDensity(int nframes, const string &suffix)
{
if (_axisname=="r") {
_dist.data().y() = _scale/(nframes*_rmax/(double)_nbin *4*M_PI) * element_div( _dist.data().y(),
element_prod(_dist.data().x(), _dist.data().x()));
} else {
_dist.data().y() = _scale/((double)nframes * _area * _rmax/ (double)_nbin ) *_dist.data().y();
}
_dist.data().Save(_out + suffix);
}
void CsgDensityApp::EndEvaluate()
{
if(_block_length == 0)
WriteDensity(_frames);
}
// add our user program options
void CsgDensityApp::Initialize()
{
CsgApplication::Initialize();
// add program option to pick molecule
AddProgramOptions("Specific options:")
("axis", boost::program_options::value<string>(&_axisname)->default_value("r"), "[x|y|z|r] density axis (r=spherical)")
("step", boost::program_options::value<double>(&_step)->default_value(0.01), "spacing of density")
("block-length", boost::program_options::value<int>(), " write blocks of this length, the averages are cleared after every write")
("out", boost::program_options::value<string>(&_out), "Output file")
("rmax", boost::program_options::value<double>(), "rmax (default for [r] =min of all box vectors/2, else l )")
("scale", boost::program_options::value<double>(&_scale)->default_value(1.0), "scale factor for the density")
("molname", boost::program_options::value<string>(&_molname)->default_value("*"), "molname")
("filter", boost::program_options::value<string>(&_filter)->default_value("*"), "filter bead names")
("ref", boost::program_options::value<vec>(&_ref), "reference zero point");
}
<|endoftext|> |
<commit_before>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_EVALUATION_PRODUCT_HH
#define DUNE_GDT_EVALUATION_PRODUCT_HH
#include <type_traits>
#include <dune/common/dynvector.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/gdt/basefunctionset/interface.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace LocalEvaluation {
// forward, to be used in the traits
template <class LocalizableFunctionImp>
class Product;
/**
* \brief Traits for the Product evaluation.
*/
template <class LocalizableFunctionImp>
class ProductTraits
{
public:
typedef Product<LocalizableFunctionImp> derived_type;
typedef LocalizableFunctionImp LocalizableFunctionType;
static_assert(std::is_base_of<Dune::Stuff::LocalizableFunction, LocalizableFunctionImp>::value,
"LocalizableFunctionImp is not a Dune::Stuff::LocalizableFunction.");
};
/**
* \brief Computes a product evaluation.
*/
template <class LocalizableFunctionImp>
class Product : public LocalEvaluation::Codim0Interface<ProductTraits<LocalizableFunctionImp>, 1>,
public LocalEvaluation::Codim1Interface<ProductTraits<LocalizableFunctionImp>, 1>
{
public:
typedef ProductTraits<LocalizableFunctionImp> Traits;
typedef typename Traits::LocalizableFunctionType LocalizableFunctionType;
Product(const LocalizableFunctionType& inducingFunction)
: inducingFunction_(inducingFunction)
{
}
template <class EntityType>
std::tuple<typename LocalizableFunctionType::template LocalFunction<EntityType>::Type>
localFunctions(const EntityType& entity) const
{
return std::make_tuple(inducingFunction_.localFunction(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class L, class T, class D, int d, class R, int rT, int rCT>
int order(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase) const
{
const auto& localFunction = std::get<0>(localFuncs);
return order(localFunction, testBase);
} // int order(...)
/**
* \todo add copydoc
* \return localFunction.order() + testBase.order()
*/
template <class L, class T, class D, int d, class R, int rL, int rCL, int rT, int rCT>
int order(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase) const
{
if (localFunction.order() < 0)
return -1;
else
return localFunction.order() + testBase.order();
} // int order(...)
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class L, class T, class D, int d, class R, int rT, int rCT>
void evaluate(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const
{
const auto& localFunction = std::get<0>(localFuncs);
evaluate(localFunction, testBase, localPoint, ret);
}
template <class L, class T, class D, int d, class R, int rL, int rCL, int rT, int rCT>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& /*localFunction*/,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& /*testBase*/,
const Dune::FieldVector<D, d>& /*localPoint*/, Dune::DynamicVector<R>& /*ret*/) const
{
dune_static_assert((Dune::AlwaysFalse<R>::value), "ERROR: not implemented for this combination of dimensions!");
}
/**
* \brief computes a scalar product evaluation.
* \tparam T Traits of the test BaseFunctionSetInterface implementation
* \tparam L Traits of the Dune::Stuff::LocalFunctionInterface implementation
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
*/
template <class L, class T, class D, int d, class R>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, 1, 1>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, 1, 1>& testBase, const Dune::FieldVector<D, d>& localPoint,
Dune::DynamicVector<R>& ret) const
{
// checks
typedef Dune::FieldVector<R, 1> RangeType;
// evaluate local function
const RangeType functionValue = localFunction.evaluate(localPoint);
// evaluate test base
const size_t size = testBase.size();
std::vector<RangeType> testValues(size, RangeType(0));
testBase.evaluate(localPoint, testValues);
// compute product
assert(ret.size() >= size);
for (size_t ii = 0; ii < size; ++ii) {
ret[ii] = functionValue * testValues[ii];
}
} // ... evaluate(...)
template <class L, class T, class IntersectionType, class D, int d, class R, int r, int rC>
void evaluate(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, r, rC>& testBase,
const IntersectionType& intersection, const Dune::FieldVector<D, d - 1>& localPoint,
Dune::DynamicVector<R>& ret) const
{
const auto& localFunction = std::get<0>(localFuncs);
evaluate(localFunction, testBase, intersection, localPoint, ret);
}
template <class L, class T, class IntersectionType, class D, int d, class R, int rL, int rCL, int rT, int rCT>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& /*localFunction*/,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& /*testBase*/,
const IntersectionType& /*intersection*/, const Dune::FieldVector<D, d>& /*localPoint*/,
Dune::DynamicVector<R>& /*ret*/) const
{
dune_static_assert((Dune::AlwaysFalse<R>::value), "ERROR: not implemented for this combination of dimensions!");
}
template <class L, class T, class IntersectionType, class D, int d, class R>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, 1, 1>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, 1, 1>& testBase, const IntersectionType& intersection,
const Dune::FieldVector<D, d - 1>& localPoint, Dune::DynamicVector<R>& ret) const
{
// checks
typedef Dune::FieldVector<D, d> DomainType;
typedef Dune::FieldVector<R, 1> RangeType;
// evaluate local function
const DomainType localPointEntity = intersection.geometryInInside().global(localPoint);
const RangeType functionValue = localFunction.evaluate(localPointEntity);
// evaluate test base
const size_t size = testBase.size();
std::vector<RangeType> testValues(size, RangeType(0));
testBase.evaluate(localPointEntity, testValues);
// compute product
assert(ret.size() >= size);
for (size_t ii = 0; ii < size; ++ii) {
ret[ii] = functionValue * testValues[ii];
}
} // ... evaluate(...)
private:
const LocalizableFunctionType& inducingFunction_;
}; // class Product
} // namespace LocalEvaluation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_EVALUATION_PRODUCT_HH
<commit_msg>[localevaluation.product] is now also a Codim0< ..., 2 > evaluation<commit_after>// This file is part of the dune-gdt project:
// http://users.dune-project.org/projects/dune-gdt
// Copyright holders: Felix Albrecht
// License: BSD 2-Clause License (http://opensource.org/licenses/BSD-2-Clause)
#ifndef DUNE_GDT_EVALUATION_PRODUCT_HH
#define DUNE_GDT_EVALUATION_PRODUCT_HH
#include <type_traits>
#include <dune/common/dynvector.hh>
#include <dune/common/fvector.hh>
#include <dune/stuff/functions/interfaces.hh>
#include <dune/gdt/basefunctionset/interface.hh>
#include "interface.hh"
namespace Dune {
namespace GDT {
namespace LocalEvaluation {
// forward, to be used in the traits
template <class LocalizableFunctionImp>
class Product;
/**
* \brief Traits for the Product evaluation.
*/
template <class LocalizableFunctionImp>
class ProductTraits
{
public:
typedef Product<LocalizableFunctionImp> derived_type;
typedef LocalizableFunctionImp LocalizableFunctionType;
static_assert(std::is_base_of<Dune::Stuff::LocalizableFunction, LocalizableFunctionImp>::value,
"LocalizableFunctionImp is not a Dune::Stuff::LocalizableFunction.");
};
/**
* \brief Computes a product evaluation.
*/
template <class LocalizableFunctionImp>
class Product : public LocalEvaluation::Codim0Interface<ProductTraits<LocalizableFunctionImp>, 1>,
public LocalEvaluation::Codim0Interface<ProductTraits<LocalizableFunctionImp>, 2>,
public LocalEvaluation::Codim1Interface<ProductTraits<LocalizableFunctionImp>, 1>
{
public:
typedef ProductTraits<LocalizableFunctionImp> Traits;
typedef typename Traits::LocalizableFunctionType LocalizableFunctionType;
Product(const LocalizableFunctionType& inducingFunction)
: inducingFunction_(inducingFunction)
{
}
template <class EntityType>
std::tuple<typename LocalizableFunctionType::template LocalFunction<EntityType>::Type>
localFunctions(const EntityType& entity) const
{
return std::make_tuple(inducingFunction_.localFunction(entity));
}
/**
* \brief extracts the local functions and calls the correct order() method
*/
template <class L, class T, class D, int d, class R, int rT, int rCT>
int order(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase) const
{
const auto& localFunction = std::get<0>(localFuncs);
return order(localFunction, testBase);
} // int order(...)
/**
* \todo add copydoc
* \return localFunction.order() + testBase.order()
*/
template <class L, class T, class D, int d, class R, int rL, int rCL, int rT, int rCT>
int order(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase) const
{
if (localFunction.order() < 0)
return -1;
else
return localFunction.order() + testBase.order();
} // int order(...)
template <class L, class T, class A, class D, int d, class R, int rT, int rCT, int rA, int rCA>
int order(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase,
const BaseFunctionSetInterface<A, D, d, R, rA, rCA>& ansatzBase) const
{
const auto& localFunction = std::get<0>(localFuncs);
return order(localFunction, testBase, ansatzBase);
}
template <class L, class T, class A, class D, int d, class R, int rL, int rCL, int rT, int rCT, int rA, int rCA>
int order(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase,
const BaseFunctionSetInterface<A, D, d, R, rA, rCA>& ansatzBase) const
{
if (localFunction.order() < 0)
return -1;
else
return localFunction.order() + testBase.order() + ansatzBase.order();
} // int order(...)
// Codim0< ..., 1 >
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class L, class T, class D, int d, class R, int rT, int rCT>
void evaluate(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicVector<R>& ret) const
{
const auto& localFunction = std::get<0>(localFuncs);
evaluate(localFunction, testBase, localPoint, ret);
}
template <class L, class T, class D, int d, class R, int rL, int rCL, int rT, int rCT>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& /*localFunction*/,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& /*testBase*/,
const Dune::FieldVector<D, d>& /*localPoint*/, Dune::DynamicVector<R>& /*ret*/) const
{
dune_static_assert((Dune::AlwaysFalse<R>::value), "ERROR: not implemented for this combination of dimensions!");
}
/**
* \brief computes a scalar product evaluation.
* \tparam T Traits of the test BaseFunctionSetInterface implementation
* \tparam L Traits of the Dune::Stuff::LocalFunctionInterface implementation
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
*/
template <class L, class T, class D, int d, class R>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, 1, 1>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, 1, 1>& testBase, const Dune::FieldVector<D, d>& localPoint,
Dune::DynamicVector<R>& ret) const
{
// checks
typedef Dune::FieldVector<R, 1> RangeType;
// evaluate local function
const RangeType functionValue = localFunction.evaluate(localPoint);
// evaluate test base
const size_t size = testBase.size();
std::vector<RangeType> testValues(size, RangeType(0));
testBase.evaluate(localPoint, testValues);
// compute product
assert(ret.size() >= size);
for (size_t ii = 0; ii < size; ++ii) {
ret[ii] = functionValue * testValues[ii];
}
} // ... evaluate(...)
// Codim0< ..., 2 >
/**
* \brief extracts the local functions and calls the correct evaluate() method
*/
template <class L, class T, class A, class D, int d, class R, int rT, int rCT, int rA, int rCA>
void evaluate(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& testBase,
const BaseFunctionSetInterface<A, D, d, R, rA, rCA>& ansatzBase,
const Dune::FieldVector<D, d>& localPoint, Dune::DynamicMatrix<R>& ret) const
{
const auto& localFunction = std::get<0>(localFuncs);
evaluate(localFunction, testBase, ansatzBase, localPoint, ret);
}
template <class L, class T, class A, class D, int d, class R, int rL, int rCL, int rT, int rCT, int rA, int rCA>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& /*localFunction*/,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& /*testBase*/,
const BaseFunctionSetInterface<A, D, d, R, rA, rCA>& /*ansatzBase*/,
const Dune::FieldVector<D, d>& /*localPoint*/, Dune::DynamicMatrix<R>& /*ret*/) const
{
dune_static_assert((Dune::AlwaysFalse<R>::value), "ERROR: not implemented for this combination of dimensions!");
}
/**
* \brief computes a scalar product evaluation.
* \tparam T Traits of the test BaseFunctionSetInterface implementation
* \tparam L Traits of the Dune::Stuff::LocalFunctionInterface implementation
* \tparam D DomainFieldType
* \tparam d dimDomain
* \tparam R RangeFieldType
*/
template <class L, class T, class A, class D, int d, class R>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, 1, 1>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, 1, 1>& testBase,
const BaseFunctionSetInterface<A, D, d, R, 1, 1>& ansatzBase, const Dune::FieldVector<D, d>& localPoint,
Dune::DynamicMatrix<R>& ret) const
{
// checks
typedef Dune::FieldVector<R, 1> RangeType;
// evaluate local function
const RangeType functionValue = localFunction.evaluate(localPoint);
// evaluate bases
const size_t rows = testBase.size();
const size_t cols = ansatzBase.size();
std::vector<RangeType> testValues(rows, RangeType(0));
std::vector<RangeType> ansatzValues(cols, RangeType(0));
testBase.evaluate(localPoint, testValues);
ansatzBase.evaluate(localPoint, ansatzValues);
// compute product
assert(ret.rows() >= rows);
assert(ret.cols() >= cols);
for (size_t ii = 0; ii < rows; ++ii) {
auto& retRow = ret[ii];
for (size_t jj = 0; jj < cols; ++jj) {
retRow[jj] = functionValue * (testValues[ii] * ansatzValues[jj]);
}
}
} // ... evaluate(...)
// Codim1< ..., 1 >
template <class L, class T, class IntersectionType, class D, int d, class R, int r, int rC>
void evaluate(const std::tuple<L>& localFuncs, const BaseFunctionSetInterface<T, D, d, R, r, rC>& testBase,
const IntersectionType& intersection, const Dune::FieldVector<D, d - 1>& localPoint,
Dune::DynamicVector<R>& ret) const
{
const auto& localFunction = std::get<0>(localFuncs);
evaluate(localFunction, testBase, intersection, localPoint, ret);
}
template <class L, class T, class IntersectionType, class D, int d, class R, int rL, int rCL, int rT, int rCT>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, rL, rCL>& /*localFunction*/,
const BaseFunctionSetInterface<T, D, d, R, rT, rCT>& /*testBase*/,
const IntersectionType& /*intersection*/, const Dune::FieldVector<D, d>& /*localPoint*/,
Dune::DynamicVector<R>& /*ret*/) const
{
dune_static_assert((Dune::AlwaysFalse<R>::value), "ERROR: not implemented for this combination of dimensions!");
}
template <class L, class T, class IntersectionType, class D, int d, class R>
void evaluate(const Dune::Stuff::LocalFunctionInterface<L, D, d, R, 1, 1>& localFunction,
const BaseFunctionSetInterface<T, D, d, R, 1, 1>& testBase, const IntersectionType& intersection,
const Dune::FieldVector<D, d - 1>& localPoint, Dune::DynamicVector<R>& ret) const
{
// checks
typedef Dune::FieldVector<D, d> DomainType;
typedef Dune::FieldVector<R, 1> RangeType;
// evaluate local function
const DomainType localPointEntity = intersection.geometryInInside().global(localPoint);
const RangeType functionValue = localFunction.evaluate(localPointEntity);
// evaluate test base
const size_t size = testBase.size();
std::vector<RangeType> testValues(size, RangeType(0));
testBase.evaluate(localPointEntity, testValues);
// compute product
assert(ret.size() >= size);
for (size_t ii = 0; ii < size; ++ii) {
ret[ii] = functionValue * testValues[ii];
}
} // ... evaluate(...)
private:
const LocalizableFunctionType& inducingFunction_;
}; // class Product
} // namespace LocalEvaluation
} // namespace GDT
} // namespace Dune
#endif // DUNE_GDT_EVALUATION_PRODUCT_HH
<|endoftext|> |
<commit_before>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#if HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo TODO The report method should go into dune-common
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
BaseType::operator=(other);
}
return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
ExtendedParameterTree sub(const std::string& _sub) const
{
if (!hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nERROR: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return ExtendedParameterTree(BaseType::sub(_sub));
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
std::string reportString(const std::string& prefix = "") const
{
std::stringstream stream;
report(stream, prefix);
return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const
std::string get(const std::string& _key, const char* defaultValue) const
{
return this->get< std::string >(_key, std::string(defaultValue));
}
template< typename T >
T get(const std::string& _key, const T& defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << Dune::Stuff::Common::highlightString("WARNING:", Dune::Stuff::Common::Colors::brown) << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
return BaseType::get< T >(_key, defaultValue);
}
template< class T >
T get(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return BaseType::get< T >(_key);
}
bool hasVector(const std::string& _key) const
{
if (hasKey(_key)) {
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
return (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"));
}
return false;
} // bool hasVector(const std::string& vector) const
template< class T >
std::vector< T > getVector(const std::string& _key, const T& def, const unsigned int minSize) const
{
if (!hasKey(_key)) {
std::cout << Dune::Stuff::Common::highlightString("WARNING:", Dune::Stuff::Common::Colors::brown) << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
return std::vector< T >(minSize, def);
} else {
const std::string str = BaseType::get(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str, "")) {
if (minSize > 0)
std::cout << Dune::Stuff::Common::highlightString("WARNING:", Dune::Stuff::Common::Colors::brown) << " vector '" << _key << "' was too small (0) and has been enlarged to size " << minSize << "!" << std::endl;
return std::vector< T >(minSize, def);
} else if (str.size() < 3) {
std::vector< T > ret;
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
if (ret.size() < minSize) {
std::cout << Dune::Stuff::Common::highlightString("WARNING:", Dune::Stuff::Common::Colors::brown) << " vector '" << _key << "' was too small (" << ret.size() << ") and has been enlarged to size " << minSize << "!" << std::endl;
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
}
return ret;
} else {
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
std::vector< T > ret;
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
std::vector< std::string > tokens;
if (str.size() > 2)
tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
} else if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
|| Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
} else {
ret = std::vector< T >(minSize, Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(str)));
}
return ret;
}
}
} // std::vector< T > getVector(const std::string& key, const T def) const
template< class T >
std::vector< T > getVector(const std::string& _key, const unsigned int minSize) const
{
if (!hasKey(_key)) {
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
} else {
std::vector< T > ret;
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
} else if (minSize == 1)
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
else
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
if (ret.size() < minSize)
DUNE_THROW(Dune::RangeError,
"\nERROR: vector '" << _key
<< "' too short (is " << ret.size() << ", should be at least " << minSize
<< ") in the following Dune::ParameterTree :\n" << reportString(" "));
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
#if HAVE_EIGEN
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key,
const T& def,
const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, def, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key, const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
#endif // HAVE_EIGEN
void assertKey(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
void assertSub(const std::string& _sub) const
{
if (!BaseType::hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nERROR: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\param[out] paramTree
The Dune::ParameterTree that is to be filled.
**/
static ParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
private:
void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
for (auto pair : values)
stream << prefix << pair.first << " = " << pair.second << std::endl;
// stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
for (auto pair : subs) {
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << prefix << "[ " << subPath << pair.first << " ]" << std::endl;
subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
}
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
}; // class ExtendedParameterTree
//! \todo TODO Remove this!
typedef ExtendedParameterTree ParameterTreeX;
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<commit_msg>[common.parameter.tree] fixed colorString()<commit_after>#ifndef DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#define DUNE_STUFF_COMMON_PARAMETER_TREE_HH
#ifdef HAVE_CMAKE_CONFIG
#include "cmake_config.h"
#else
#include "config.h"
#endif // ifdef HAVE_CMAKE_CONFIG
#include <cstring>
#include <sstream>
#include <vector>
#include <boost/algorithm/string/join.hpp>
#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>
#if HAVE_EIGEN
#include <Eigen/Core>
#endif // HAVE_EIGEN
#include <dune/common/exceptions.hh>
#include <dune/common/parametertreeparser.hh>
#include <dune/stuff/common/string.hh>
#include <dune/stuff/common/color.hh>
namespace Dune {
namespace Stuff {
namespace Common {
//! ParameterTree extension for nicer output
//! \todo TODO The report method should go into dune-common
class ExtendedParameterTree
: public Dune::ParameterTree {
public:
typedef Dune::ParameterTree BaseType;
ExtendedParameterTree()
{}
ExtendedParameterTree(int argc, char** argv, std::string filename)
: BaseType(init(argc, argv, filename))
{}
ExtendedParameterTree(const Dune::ParameterTree& other)
: BaseType(other)
{}
ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
{
if (this != &other) {
BaseType::operator=(other);
}
return *this;
} // ExtendedParameterTree& operator=(const Dune::ParameterTree& other)
ExtendedParameterTree sub(const std::string& _sub) const
{
if (!hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nERROR: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return ExtendedParameterTree(BaseType::sub(_sub));
}
void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
{
reportAsSub(stream, prefix, "");
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
std::string reportString(const std::string& prefix = "") const
{
std::stringstream stream;
report(stream, prefix);
return stream.str();
} // std::stringstream reportString(const std::string& prefix = "") const
std::string get(const std::string& _key, const char* defaultValue) const
{
return this->get< std::string >(_key, std::string(defaultValue));
}
template< typename T >
T get(const std::string& _key, const T& defaultValue) const
{
if (!BaseType::hasKey(_key))
std::cout << Dune::Stuff::Common::colorString("WARNING:") << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
return BaseType::get< T >(_key, defaultValue);
}
template< class T >
T get(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
return BaseType::get< T >(_key);
}
bool hasVector(const std::string& _key) const
{
if (hasKey(_key)) {
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
return (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]"));
}
return false;
} // bool hasVector(const std::string& vector) const
template< class T >
std::vector< T > getVector(const std::string& _key, const T& def, const unsigned int minSize) const
{
if (!hasKey(_key)) {
std::cout << Dune::Stuff::Common::colorString("WARNING:") << " missing key '" << _key << "' is replaced by given default value!" << std::endl;
return std::vector< T >(minSize, def);
} else {
const std::string str = BaseType::get(_key, "meaningless_default_value");
if (Dune::Stuff::Common::String::equal(str, "")) {
if (minSize > 0)
std::cout << Dune::Stuff::Common::colorString("WARNING:") << " vector '" << _key << "' was too small (0) and has been enlarged to size " << minSize << "!" << std::endl;
return std::vector< T >(minSize, def);
} else if (str.size() < 3) {
std::vector< T > ret;
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
if (ret.size() < minSize) {
std::cout << Dune::Stuff::Common::colorString("WARNING:") << " vector '" << _key << "' was too small (" << ret.size() << ") and has been enlarged to size " << minSize << "!" << std::endl;
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
}
return ret;
} else {
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
std::vector< T > ret;
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
std::vector< std::string > tokens;
if (str.size() > 2)
tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
for (unsigned int i = ret.size(); i < minSize; ++i)
ret.push_back(def);
} else if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
|| Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
} else {
ret = std::vector< T >(minSize, Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(str)));
}
return ret;
}
}
} // std::vector< T > getVector(const std::string& key, const T def) const
template< class T >
std::vector< T > getVector(const std::string& _key, const unsigned int minSize) const
{
if (!hasKey(_key)) {
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
} else {
std::vector< T > ret;
const std::string str = BaseType::get< std::string >(_key, "meaningless_default_value");
// the dune parametertree strips any leading and trailing whitespace
// so we can be sure that the first and last have to be the brackets [] if this is a vector
if (Dune::Stuff::Common::String::equal(str.substr(0, 1), "[")
&& Dune::Stuff::Common::String::equal(str.substr(str.size() - 1, 1), "]")) {
const std::vector< std::string > tokens = Dune::Stuff::Common::tokenize< std::string >(str.substr(1, str.size() - 2), ";");
for (unsigned int i = 0; i < tokens.size(); ++i)
ret.push_back(Dune::Stuff::Common::fromString< T >(boost::algorithm::trim_copy(tokens[i])));
} else if (minSize == 1)
ret.push_back(Dune::Stuff::Common::fromString< T >(str));
else
DUNE_THROW(Dune::RangeError, "Vectors have to be of the form '[entry_0; entry_1; ... ]'!");
if (ret.size() < minSize)
DUNE_THROW(Dune::RangeError,
"\nERROR: vector '" << _key
<< "' too short (is " << ret.size() << ", should be at least " << minSize
<< ") in the following Dune::ParameterTree :\n" << reportString(" "));
return ret;
}
} // std::vector< T > getVector(const std::string& key, const T def) const
#if HAVE_EIGEN
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key,
const T& def,
const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, def, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
template< class T >
Eigen::Matrix< T, Eigen::Dynamic, 1 > getEigenVector(const std::string& _key, const unsigned int minSize) const
{
// get correspongin vector
std::vector< T > vec = getVector< T >(_key, minSize);
// create eigen vector and return
Eigen::Matrix< T, Eigen::Dynamic, 1 > ret(vec.size());
for (unsigned int i = 0; i < vec.size(); ++i)
ret(i) = vec[i];
return ret;
}
#endif // HAVE_EIGEN
void assertKey(const std::string& _key) const
{
if (!BaseType::hasKey(_key))
DUNE_THROW(Dune::RangeError,
"\nERROR: key '" << _key << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
void assertSub(const std::string& _sub) const
{
if (!BaseType::hasSub(_sub))
DUNE_THROW(Dune::RangeError,
"\nERROR: sub '" << _sub << "' missing in the following Dune::ParameterTree:\n" << reportString(" "));
}
/**
\brief Fills a Dune::ParameterTree given a parameter file or command line arguments.
\param[in] argc
From \c main()
\param[in] argv
From \c main()
\param[out] paramTree
The Dune::ParameterTree that is to be filled.
**/
static ParameterTree init(int argc, char** argv, std::string filename)
{
Dune::ParameterTree paramTree;
if (argc == 1) {
Dune::ParameterTreeParser::readINITree(filename, paramTree);
} else if (argc == 2) {
Dune::ParameterTreeParser::readINITree(argv[1], paramTree);
} else {
Dune::ParameterTreeParser::readOptions(argc, argv, paramTree);
}
if (paramTree.hasKey("paramfile")) {
Dune::ParameterTreeParser::readINITree(paramTree.get< std::string >("paramfile"), paramTree, false);
}
return paramTree;
} // static ExtendedParameterTree init(...)
private:
void reportAsSub(std::ostream& stream, const std::string& prefix, const std::string& subPath) const
{
for (auto pair : values)
stream << prefix << pair.first << " = " << pair.second << std::endl;
// stream << prefix << pair.first << " = \"" << pair.second << "\"" << std::endl;
for (auto pair : subs) {
ExtendedParameterTree subTree(pair.second);
if (subTree.getValueKeys().size())
stream << prefix << "[ " << subPath << pair.first << " ]" << std::endl;
subTree.reportAsSub(stream, prefix, subPath + pair.first + ".");
}
} // void report(std::ostream& stream = std::cout, const std::string& prefix = "") const
}; // class ExtendedParameterTree
//! \todo TODO Remove this!
typedef ExtendedParameterTree ParameterTreeX;
} // namespace Common
} // namespace Stuff
} // namespace Dune
#endif // DUNE_STUFF_COMMON_PARAMETER_TREE_HH
<|endoftext|> |
<commit_before>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/noncopyable.hpp>
#include <qi/future.hpp>
#include <qi/signature.hpp>
#include <qi/anyfunction.hpp>
#include <qi/anyobject.hpp>
qiLogCategory("qitype.functiontype");
namespace qi
{
//make destroy exception-safe for AnyFunction::call
class AnyReferenceArrayDestroyer : private boost::noncopyable {
public:
AnyReferenceArrayDestroyer(AnyReference *toDestroy, void **convertedArgs, bool shouldDelete)
: toDestroy(toDestroy)
, convertedArgs(convertedArgs)
, toDestroyPos(0)
, shouldDelete(shouldDelete)
{
}
~AnyReferenceArrayDestroyer() {
destroy();
}
void destroy() {
if (toDestroy) {
for (unsigned i = 0; i < toDestroyPos; ++i)
toDestroy[i].destroy();
if (shouldDelete)
delete[] toDestroy;
toDestroy = 0;
}
if (shouldDelete && convertedArgs) {
delete[] convertedArgs;
convertedArgs = 0;
}
}
public:
AnyReference* toDestroy;
void** convertedArgs;
unsigned int toDestroyPos;
bool shouldDelete;
};
AnyReference AnyFunction::call(AnyReference arg1, const AnyReferenceVector& remaining)
{
AnyReferenceVector args;
args.reserve(remaining.size()+1);
args.push_back(arg1);
args.insert(args.end(), remaining.begin(), remaining.end());
return call(args);
}
AnyReference AnyFunction::call(const AnyReferenceVector& vargs)
{
if (type == dynamicFunctionTypeInterface())
{
DynamicFunction* f = (DynamicFunction*)value;
if (!transform.dropFirst && !transform.prependValue)
return (*f)(vargs);
AnyReferenceVector args;
if (transform.dropFirst && !transform.prependValue)
{
// VCXX2008 does not accept insert here because GV(GVP) ctor is explicit
args.resize(vargs.size()-1);
for (unsigned i=0; i<vargs.size()-1; ++i)
args[i] = vargs[i+1];
}
else if (transform.dropFirst && transform.prependValue)
{
args = vargs;
args[0] = AnyReference(args[0].type(), transform.boundValue);
}
else // prepend && ! drop
throw std::runtime_error("Cannot prepend argument to dynamic function type");
return (*f)(args);
}
/* We must honor transform, who can have any combination of the following enabled:
* - drop first arg
* - prepend an arg
*/
unsigned deltaCount = (transform.dropFirst? -1:0) + (transform.prependValue?1:0);
const std::vector<TypeInterface*>& target = type->argumentsType();
unsigned sz = vargs.size();
const AnyReference* args = sz > 0 ? &vargs[0] : 0;
if (target.size() != sz + deltaCount)
{
throw std::runtime_error(_QI_LOG_FORMAT("Argument count mismatch, expected %1%, got %2%",
target.size(), sz + deltaCount));
return AnyReference();
}
if (transform.dropFirst)
{
++args;
--sz;
}
unsigned offset = transform.prependValue? 1:0;
#if QI_HAS_VARIABLE_LENGTH_ARRAY
AnyReference sstoDestroy[sz+offset];
void* ssconvertedArgs[sz+offset];
AnyReferenceArrayDestroyer arad(sstoDestroy, ssconvertedArgs, false);
#else
AnyReference* sstoDestroy = new AnyReference[sz+offset];
void** ssconvertedArgs = new void*[sz+offset];
AnyReferenceArrayDestroyer arad(sstoDestroy, ssconvertedArgs, true);
#endif
if (transform.prependValue)
arad.convertedArgs[0] = transform.boundValue;
for (unsigned i=0; i<sz; ++i)
{
//qiLogDebug() << "argument " << i
// << " " << args[i].type->infoString() << ' ' << args[i].value
// << " to " << target[i]->infoString();
if (args[i].type() == target[i+offset] || args[i].type()->info() == target[i+offset]->info())
arad.convertedArgs[i+offset] = args[i].rawValue();
else
{
//qiLogDebug() << "needs conversion "
//<< args[i].type->infoString() << " -> "
//<< target[i]->infoString();
std::pair<AnyReference,bool> v = args[i].convert(target[i+offset]);
if (!v.first.type())
{
// Try pointer dereference
if (args[i].kind() == TypeKind_Pointer)
{
AnyReference deref = *const_cast<AnyReference&>(args[i]);
if (deref.type() == target[i+offset] || deref.type()->info() == target[i+offset]->info())
v = std::make_pair(deref, false);
else
v = deref.convert(target[i+offset]);
}
if (!v.first.type())
{
throw std::runtime_error(_QI_LOG_FORMAT("Call argument number %d conversion failure from %s to %s. Function signature: %s.",
i,
args[i].type()->signature().toPrettySignature(),
target[i]->signature().toPrettySignature(),
this->parametersSignature(this->transform.dropFirst).toPrettySignature()));
return AnyReference();
}
}
if (v.second)
arad.toDestroy[arad.toDestroyPos++] = v.first;
arad.convertedArgs[i+offset] = v.first.rawValue();
}
}
void* res;
res = type->call(value, arad.convertedArgs, sz+offset);
arad.destroy();
return AnyReference(resultType(), res);
}
const AnyFunction& AnyFunction::dropFirstArgument() const
{
transform.dropFirst = true;
return *this;
}
const AnyFunction& AnyFunction::prependArgument(void* arg) const
{
transform.prependValue = true;
transform.boundValue = arg;
return *this;
}
const AnyFunction& AnyFunction::replaceFirstArgument(void* arg) const
{
transform.dropFirst = true;
return prependArgument(arg);
}
TypeInterface* AnyFunction::resultType() const
{
return type->resultType();
}
std::vector<TypeInterface*> AnyFunction::argumentsType() const
{
std::vector<TypeInterface*> res = type->argumentsType();
if (transform.dropFirst && transform.prependValue) // optimize that case
res[0] = typeOf<AnyValue>();
else if (transform.dropFirst)
{
// First argument passed to us will be ignored, so apparent signature
// has one extra arg of any type.
// do not access res[1], it might not exist and invalid access might be
// detected by debug-mode stl
res.push_back(0);
memmove(&res[0]+1, &res[0], (res.size()-1)*sizeof(TypeInterface*));
res[0] = typeOf<AnyValue>();
}
else if (transform.prependValue)
{
// We bind one argument, so it is not present in apparent signature, remove it
memmove(&res[0], &res[0]+1, (res.size()-1)*sizeof(TypeInterface*));
res.pop_back();
}
return res;
}
qi::Signature AnyFunction::parametersSignature(bool dropFirst) const
{
if (type == dynamicFunctionTypeInterface())
return "m";
if (!dropFirst)
return qi::makeTupleSignature(argumentsType());
std::vector<TypeInterface*> vtype = argumentsType();
if (vtype.empty())
throw std::runtime_error("Can't drop the first argument, the argument list is empty");
//ninja! : drop the first TypeInterface*
memmove(&vtype[0], &vtype[0]+1, (vtype.size()-1)*sizeof(TypeInterface*));
vtype.pop_back();
return qi::makeTupleSignature(vtype);
}
qi::Signature AnyFunction::returnSignature() const
{
if (type == dynamicFunctionTypeInterface())
return "m";
// Detect if returned type is a qi::Future and return underlying value type.
TemplateTypeInterface* ft1 = QI_TEMPLATE_TYPE_GET(resultType(), Future);
TemplateTypeInterface* ft2 = QI_TEMPLATE_TYPE_GET(resultType(), FutureSync);
TemplateTypeInterface* futureType = ft1 ? ft1 : ft2;
if (futureType)
return futureType->templateArgument()->signature();
else
return resultType()->signature();
}
qi::Signature CallableTypeInterface::parametersSignature() const
{
if (this == dynamicFunctionTypeInterface())
return "m";
else
return qi::makeTupleSignature(_argumentsType);
}
qi::Signature CallableTypeInterface::returnSignature() const
{
if (this == dynamicFunctionTypeInterface())
return "m";
return _resultType->signature();
}
GenericFunctionParameters::GenericFunctionParameters()
{
}
GenericFunctionParameters::GenericFunctionParameters(const AnyReferenceVector& args)
:AnyReferenceVector(args)
{
}
GenericFunctionParameters GenericFunctionParameters::copy(bool notFirst) const
{
GenericFunctionParameters result(*this);
for (unsigned i=notFirst?1:0; i<size(); ++i)
result[i] = result[i].clone();
return result;
}
void GenericFunctionParameters::destroy(bool notFirst)
{
for (unsigned i = notFirst ? 1 : 0; i < size(); ++i)
(*this)[i].destroy();
}
GenericFunctionParameters
GenericFunctionParameters::convert(const Signature& sig) const
{
GenericFunctionParameters dst;
const AnyReferenceVector& src = *this;
if (sig.children().size() != src.size())
{
qiLogError() << "convert: signature/params size mismatch"
<< sig.toString() << " " << sig.children().size() << " " << src.size();
return dst;
}
const SignatureVector &elts = sig.children();
SignatureVector::const_iterator it = elts.begin();
int idx = 0;
for (;it != elts.end(); ++it,++idx)
{
TypeInterface* compatible = qi::TypeInterface::fromSignature(*it);
if (!compatible)
{
qiLogError() << "convert: unknown type " << (*it).toString();
compatible = src[idx].type();
}
dst.push_back(src[idx].convertCopy(compatible));
}
return dst;
}
Signature GenericFunctionParameters::signature(bool dyn) const
{
const AnyReferenceVector& params = *this;
return qi::makeTupleSignature(params, dyn);
}
class DynamicFunctionTypeInterfaceInterface: public FunctionTypeInterface
{
public:
DynamicFunctionTypeInterfaceInterface()
{
_resultType = typeOf<AnyValue>();
}
virtual void* call(void* func, void** args, unsigned int argc)
{
qiLogError() << "Dynamic function called without type information";
return 0;
}
_QI_BOUNCE_TYPE_METHODS(DefaultTypeImplMethods<DynamicFunction>);
};
FunctionTypeInterface* dynamicFunctionTypeInterface()
{
static FunctionTypeInterface* type = 0;
if (!type)
type = new DynamicFunctionTypeInterfaceInterface();
return type;
}
AnyFunction AnyFunction::fromDynamicFunction(DynamicFunction f)
{
FunctionTypeInterface* d = dynamicFunctionTypeInterface();
AnyFunction result(d, d->clone(d->initializeStorage(&f)));
return result;
}
}
#ifdef QITYPE_TRACK_FUNCTIONTYPE_INSTANCES
#include <qi/application.hpp>
namespace qi
{
namespace detail
{
static std::map<std::string, int> functionTrackMap;
void functionTypeTrack(const std::string& f)
{
functionTrackMap[std::string(f)]++;
}
void functionTypeDump()
{
for (std::map<std::string, int>::iterator it = functionTrackMap.begin();
it != functionTrackMap.end(); ++it)
std::cerr << it->second << '\t' << it->first << std::endl;
}
}
}
#endif
<commit_msg>AnyFunction: fix error printing<commit_after>/*
** Copyright (C) 2012 Aldebaran Robotics
** See COPYING for the license
*/
#include <boost/noncopyable.hpp>
#include <qi/future.hpp>
#include <qi/signature.hpp>
#include <qi/anyfunction.hpp>
#include <qi/anyobject.hpp>
qiLogCategory("qitype.functiontype");
namespace qi
{
//make destroy exception-safe for AnyFunction::call
class AnyReferenceArrayDestroyer : private boost::noncopyable {
public:
AnyReferenceArrayDestroyer(AnyReference *toDestroy, void **convertedArgs, bool shouldDelete)
: toDestroy(toDestroy)
, convertedArgs(convertedArgs)
, toDestroyPos(0)
, shouldDelete(shouldDelete)
{
}
~AnyReferenceArrayDestroyer() {
destroy();
}
void destroy() {
if (toDestroy) {
for (unsigned i = 0; i < toDestroyPos; ++i)
toDestroy[i].destroy();
if (shouldDelete)
delete[] toDestroy;
toDestroy = 0;
}
if (shouldDelete && convertedArgs) {
delete[] convertedArgs;
convertedArgs = 0;
}
}
public:
AnyReference* toDestroy;
void** convertedArgs;
unsigned int toDestroyPos;
bool shouldDelete;
};
AnyReference AnyFunction::call(AnyReference arg1, const AnyReferenceVector& remaining)
{
AnyReferenceVector args;
args.reserve(remaining.size()+1);
args.push_back(arg1);
args.insert(args.end(), remaining.begin(), remaining.end());
return call(args);
}
AnyReference AnyFunction::call(const AnyReferenceVector& vargs)
{
if (type == dynamicFunctionTypeInterface())
{
DynamicFunction* f = (DynamicFunction*)value;
if (!transform.dropFirst && !transform.prependValue)
return (*f)(vargs);
AnyReferenceVector args;
if (transform.dropFirst && !transform.prependValue)
{
// VCXX2008 does not accept insert here because GV(GVP) ctor is explicit
args.resize(vargs.size()-1);
for (unsigned i=0; i<vargs.size()-1; ++i)
args[i] = vargs[i+1];
}
else if (transform.dropFirst && transform.prependValue)
{
args = vargs;
args[0] = AnyReference(args[0].type(), transform.boundValue);
}
else // prepend && ! drop
throw std::runtime_error("Cannot prepend argument to dynamic function type");
return (*f)(args);
}
/* We must honor transform, who can have any combination of the following enabled:
* - drop first arg
* - prepend an arg
*/
unsigned deltaCount = (transform.dropFirst? -1:0) + (transform.prependValue?1:0);
const std::vector<TypeInterface*>& target = type->argumentsType();
unsigned sz = vargs.size();
const AnyReference* args = sz > 0 ? &vargs[0] : 0;
if (target.size() != sz + deltaCount)
{
throw std::runtime_error(_QI_LOG_FORMAT("Argument count mismatch, expected %1%, got %2%",
target.size(), sz + deltaCount));
return AnyReference();
}
if (transform.dropFirst)
{
++args;
--sz;
}
unsigned offset = transform.prependValue? 1:0;
#if QI_HAS_VARIABLE_LENGTH_ARRAY
AnyReference sstoDestroy[sz+offset];
void* ssconvertedArgs[sz+offset];
AnyReferenceArrayDestroyer arad(sstoDestroy, ssconvertedArgs, false);
#else
AnyReference* sstoDestroy = new AnyReference[sz+offset];
void** ssconvertedArgs = new void*[sz+offset];
AnyReferenceArrayDestroyer arad(sstoDestroy, ssconvertedArgs, true);
#endif
if (transform.prependValue)
arad.convertedArgs[0] = transform.boundValue;
for (unsigned i=0; i<sz; ++i)
{
const unsigned ti = i + offset;
//qiLogDebug() << "argument " << i
// << " " << args[i].type->infoString() << ' ' << args[i].value
// << " to " << target[ti]->infoString();
if (args[i].type() == target[ti] || args[i].type()->info() == target[ti]->info())
arad.convertedArgs[ti] = args[i].rawValue();
else
{
//qiLogDebug() << "needs conversion "
//<< args[i].type->infoString() << " -> "
//<< target[ti]->infoString();
std::pair<AnyReference,bool> v = args[i].convert(target[ti]);
if (!v.first.type())
{
// Try pointer dereference
if (args[i].kind() == TypeKind_Pointer)
{
AnyReference deref = *const_cast<AnyReference&>(args[i]);
if (deref.type() == target[ti] || deref.type()->info() == target[ti]->info())
v = std::make_pair(deref, false);
else
v = deref.convert(target[ti]);
}
if (!v.first.type())
{
throw std::runtime_error(_QI_LOG_FORMAT("Call argument number %d conversion failure from %s to %s. Function signature: %s.",
i,
args[i].type()->signature().toPrettySignature(),
target[ti]->signature().toPrettySignature(),
this->parametersSignature(this->transform.dropFirst).toPrettySignature()));
return AnyReference();
}
}
if (v.second)
arad.toDestroy[arad.toDestroyPos++] = v.first;
arad.convertedArgs[ti] = v.first.rawValue();
}
}
void* res;
res = type->call(value, arad.convertedArgs, sz+offset);
arad.destroy();
return AnyReference(resultType(), res);
}
const AnyFunction& AnyFunction::dropFirstArgument() const
{
transform.dropFirst = true;
return *this;
}
const AnyFunction& AnyFunction::prependArgument(void* arg) const
{
transform.prependValue = true;
transform.boundValue = arg;
return *this;
}
const AnyFunction& AnyFunction::replaceFirstArgument(void* arg) const
{
transform.dropFirst = true;
return prependArgument(arg);
}
TypeInterface* AnyFunction::resultType() const
{
return type->resultType();
}
std::vector<TypeInterface*> AnyFunction::argumentsType() const
{
std::vector<TypeInterface*> res = type->argumentsType();
if (transform.dropFirst && transform.prependValue) // optimize that case
res[0] = typeOf<AnyValue>();
else if (transform.dropFirst)
{
// First argument passed to us will be ignored, so apparent signature
// has one extra arg of any type.
// do not access res[1], it might not exist and invalid access might be
// detected by debug-mode stl
res.push_back(0);
memmove(&res[0]+1, &res[0], (res.size()-1)*sizeof(TypeInterface*));
res[0] = typeOf<AnyValue>();
}
else if (transform.prependValue)
{
// We bind one argument, so it is not present in apparent signature, remove it
memmove(&res[0], &res[0]+1, (res.size()-1)*sizeof(TypeInterface*));
res.pop_back();
}
return res;
}
qi::Signature AnyFunction::parametersSignature(bool dropFirst) const
{
if (type == dynamicFunctionTypeInterface())
return "m";
if (!dropFirst)
return qi::makeTupleSignature(argumentsType());
std::vector<TypeInterface*> vtype = argumentsType();
if (vtype.empty())
throw std::runtime_error("Can't drop the first argument, the argument list is empty");
//ninja! : drop the first TypeInterface*
memmove(&vtype[0], &vtype[0]+1, (vtype.size()-1)*sizeof(TypeInterface*));
vtype.pop_back();
return qi::makeTupleSignature(vtype);
}
qi::Signature AnyFunction::returnSignature() const
{
if (type == dynamicFunctionTypeInterface())
return "m";
// Detect if returned type is a qi::Future and return underlying value type.
TemplateTypeInterface* ft1 = QI_TEMPLATE_TYPE_GET(resultType(), Future);
TemplateTypeInterface* ft2 = QI_TEMPLATE_TYPE_GET(resultType(), FutureSync);
TemplateTypeInterface* futureType = ft1 ? ft1 : ft2;
if (futureType)
return futureType->templateArgument()->signature();
else
return resultType()->signature();
}
qi::Signature CallableTypeInterface::parametersSignature() const
{
if (this == dynamicFunctionTypeInterface())
return "m";
else
return qi::makeTupleSignature(_argumentsType);
}
qi::Signature CallableTypeInterface::returnSignature() const
{
if (this == dynamicFunctionTypeInterface())
return "m";
return _resultType->signature();
}
GenericFunctionParameters::GenericFunctionParameters()
{
}
GenericFunctionParameters::GenericFunctionParameters(const AnyReferenceVector& args)
:AnyReferenceVector(args)
{
}
GenericFunctionParameters GenericFunctionParameters::copy(bool notFirst) const
{
GenericFunctionParameters result(*this);
for (unsigned i=notFirst?1:0; i<size(); ++i)
result[i] = result[i].clone();
return result;
}
void GenericFunctionParameters::destroy(bool notFirst)
{
for (unsigned i = notFirst ? 1 : 0; i < size(); ++i)
(*this)[i].destroy();
}
GenericFunctionParameters
GenericFunctionParameters::convert(const Signature& sig) const
{
GenericFunctionParameters dst;
const AnyReferenceVector& src = *this;
if (sig.children().size() != src.size())
{
qiLogError() << "convert: signature/params size mismatch"
<< sig.toString() << " " << sig.children().size() << " " << src.size();
return dst;
}
const SignatureVector &elts = sig.children();
SignatureVector::const_iterator it = elts.begin();
int idx = 0;
for (;it != elts.end(); ++it,++idx)
{
TypeInterface* compatible = qi::TypeInterface::fromSignature(*it);
if (!compatible)
{
qiLogError() << "convert: unknown type " << (*it).toString();
compatible = src[idx].type();
}
dst.push_back(src[idx].convertCopy(compatible));
}
return dst;
}
Signature GenericFunctionParameters::signature(bool dyn) const
{
const AnyReferenceVector& params = *this;
return qi::makeTupleSignature(params, dyn);
}
class DynamicFunctionTypeInterfaceInterface: public FunctionTypeInterface
{
public:
DynamicFunctionTypeInterfaceInterface()
{
_resultType = typeOf<AnyValue>();
}
virtual void* call(void* func, void** args, unsigned int argc)
{
qiLogError() << "Dynamic function called without type information";
return 0;
}
_QI_BOUNCE_TYPE_METHODS(DefaultTypeImplMethods<DynamicFunction>);
};
FunctionTypeInterface* dynamicFunctionTypeInterface()
{
static FunctionTypeInterface* type = 0;
if (!type)
type = new DynamicFunctionTypeInterfaceInterface();
return type;
}
AnyFunction AnyFunction::fromDynamicFunction(DynamicFunction f)
{
FunctionTypeInterface* d = dynamicFunctionTypeInterface();
AnyFunction result(d, d->clone(d->initializeStorage(&f)));
return result;
}
}
#ifdef QITYPE_TRACK_FUNCTIONTYPE_INSTANCES
#include <qi/application.hpp>
namespace qi
{
namespace detail
{
static std::map<std::string, int> functionTrackMap;
void functionTypeTrack(const std::string& f)
{
functionTrackMap[std::string(f)]++;
}
void functionTypeDump()
{
for (std::map<std::string, int>::iterator it = functionTrackMap.begin();
it != functionTrackMap.end(); ++it)
std::cerr << it->second << '\t' << it->first << std::endl;
}
}
}
#endif
<|endoftext|> |
<commit_before>#include "MAVLinkDecoder.h"
#include "UASManager.h"
MAVLinkDecoder::MAVLinkDecoder(MAVLinkProtocol* protocol, QObject *parent) :
QObject(parent)
{
mavlink_message_info_t msg[256] = MAVLINK_MESSAGE_INFO;
memcpy(messageInfo, msg, sizeof(mavlink_message_info_t)*256);
memset(receivedMessages, 0, sizeof(mavlink_message_t)*256);
// Fill filter
messageFilter.insert(MAVLINK_MSG_ID_HEARTBEAT, false);
messageFilter.insert(MAVLINK_MSG_ID_SYS_STATUS, false);
messageFilter.insert(MAVLINK_MSG_ID_STATUSTEXT, false);
messageFilter.insert(MAVLINK_MSG_ID_COMMAND, false);
messageFilter.insert(MAVLINK_MSG_ID_COMMAND_ACK, false);
messageFilter.insert(MAVLINK_MSG_ID_PARAM_SET, false);
messageFilter.insert(MAVLINK_MSG_ID_PARAM_VALUE, false);
messageFilter.insert(MAVLINK_MSG_ID_MISSION_ITEM, false);
messageFilter.insert(MAVLINK_MSG_ID_MISSION_COUNT, false);
messageFilter.insert(MAVLINK_MSG_ID_MISSION_ACK, false);
connect(protocol, SIGNAL(messageReceived(LinkInterface*,mavlink_message_t)), this, SLOT(receiveMessage(LinkInterface*,mavlink_message_t)));
}
void MAVLinkDecoder::receiveMessage(LinkInterface* link,mavlink_message_t message)
{
Q_UNUSED(link);
memcpy(receivedMessages+message.msgid, &message, sizeof(mavlink_message_t));
uint8_t msgid = message.msgid;
QString messageName("%1 (#%2)");
messageName = messageName.arg(messageInfo[msgid].name).arg(msgid);
// See if first value is a time value
quint64 time = 0;
uint8_t fieldid = 0;
uint8_t* m = ((uint8_t*)(receivedMessages+msgid))+8;
if (QString(messageInfo[msgid].fields[fieldid].name) == QString("time_boot_ms") && messageInfo[msgid].fields[fieldid].type == MAVLINK_TYPE_UINT32_T)
{
time = *((quint32*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
}
else if (QString(messageInfo[msgid].fields[fieldid].name) == QString("time_usec") && messageInfo[msgid].fields[fieldid].type == MAVLINK_TYPE_UINT64_T)
{
time = *((quint64*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
}
else
{
// First value is not time, send out value 0
emitFieldValue(&message, fieldid, time);
}
// Send out field values from 1..n
for (unsigned int i = 1; i < messageInfo[msgid].num_fields; ++i)
{
emitFieldValue(&message, i, time);
}
// Send out combined math expressions
// FIXME XXX TODO
}
void MAVLinkDecoder::emitFieldValue(mavlink_message_t* msg, int fieldid, quint64 time)
{
// Add field tree widget item
uint8_t msgid = msg->msgid;
if (messageFilter.contains(msgid)) return;
QString fieldName(messageInfo[msgid].fields[fieldid].name);
QString fieldType;
uint8_t* m = ((uint8_t*)(receivedMessages+msgid))+8;
QString name("%1.%2");
QString unit("");
name = name.arg(messageInfo[msgid].name, fieldName);
switch (messageInfo[msgid].fields[fieldid].type)
{
case MAVLINK_TYPE_CHAR:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
char* str = (char*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
str[messageInfo[msgid].fields[fieldid].array_length-1] = '\0';
QString string(name + ": " + str);
emit textMessageReceived(msg->sysid, msg->compid, 0, string);
}
else
{
// Single char
char b = *((char*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
unit = QString("char[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
emit valueChanged(msg->sysid, name, unit, b, time);
}
break;
case MAVLINK_TYPE_UINT8_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint8_t* nums = m+messageInfo[msgid].fields[fieldid].wire_offset;
fieldType = QString("uint8_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
uint8_t u = *(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = "uint8_t";
emit valueChanged(msg->sysid, name, fieldType, u, time);
}
break;
case MAVLINK_TYPE_INT8_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int8_t* nums = (int8_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int8_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int8_t n = *((int8_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int8_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_UINT16_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint16_t* nums = (uint16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("uint16_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
uint16_t n = *((uint16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "uint16_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_INT16_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int16_t* nums = (int16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int16_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int16_t n = *((int16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int16_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_UINT32_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint32_t* nums = (uint32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("uint32_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
float n = *((uint32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "uint32_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_INT32_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int32_t* nums = (int32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int32_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int32_t n = *((int32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int32_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_FLOAT:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
float* nums = (float*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("float[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
float f = *((float*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "float";
emit valueChanged(msg->sysid, name, fieldType, f, time);
}
break;
case MAVLINK_TYPE_DOUBLE:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
double* nums = (double*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("double[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
double f = *((double*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "double";
emit valueChanged(msg->sysid, name, fieldType, f, time);
}
break;
case MAVLINK_TYPE_UINT64_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint64_t* nums = (uint64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("uint64_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
uint64_t n = *((uint64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "uint64_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_INT64_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int64_t* nums = (int64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int64_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int64_t n = *((int64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int64_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
}
}
<commit_msg>Mainwindow cleanup, fixed short value filter in Linechart, working on Python XML parser support<commit_after>#include "MAVLinkDecoder.h"
#include "UASManager.h"
MAVLinkDecoder::MAVLinkDecoder(MAVLinkProtocol* protocol, QObject *parent) :
QObject(parent)
{
mavlink_message_info_t msg[256] = MAVLINK_MESSAGE_INFO;
memcpy(messageInfo, msg, sizeof(mavlink_message_info_t)*256);
memset(receivedMessages, 0, sizeof(mavlink_message_t)*256);
// Fill filter
messageFilter.insert(MAVLINK_MSG_ID_HEARTBEAT, false);
messageFilter.insert(MAVLINK_MSG_ID_SYS_STATUS, false);
messageFilter.insert(MAVLINK_MSG_ID_STATUSTEXT, false);
messageFilter.insert(MAVLINK_MSG_ID_COMMAND_SHORT, false);
messageFilter.insert(MAVLINK_MSG_ID_COMMAND_LONG, false);
messageFilter.insert(MAVLINK_MSG_ID_COMMAND_ACK, false);
messageFilter.insert(MAVLINK_MSG_ID_PARAM_SET, false);
messageFilter.insert(MAVLINK_MSG_ID_PARAM_VALUE, false);
messageFilter.insert(MAVLINK_MSG_ID_MISSION_ITEM, false);
messageFilter.insert(MAVLINK_MSG_ID_MISSION_COUNT, false);
messageFilter.insert(MAVLINK_MSG_ID_MISSION_ACK, false);
connect(protocol, SIGNAL(messageReceived(LinkInterface*,mavlink_message_t)), this, SLOT(receiveMessage(LinkInterface*,mavlink_message_t)));
}
void MAVLinkDecoder::receiveMessage(LinkInterface* link,mavlink_message_t message)
{
Q_UNUSED(link);
memcpy(receivedMessages+message.msgid, &message, sizeof(mavlink_message_t));
uint8_t msgid = message.msgid;
QString messageName("%1 (#%2)");
messageName = messageName.arg(messageInfo[msgid].name).arg(msgid);
// See if first value is a time value
quint64 time = 0;
uint8_t fieldid = 0;
uint8_t* m = ((uint8_t*)(receivedMessages+msgid))+8;
if (QString(messageInfo[msgid].fields[fieldid].name) == QString("time_boot_ms") && messageInfo[msgid].fields[fieldid].type == MAVLINK_TYPE_UINT32_T)
{
time = *((quint32*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
}
else if (QString(messageInfo[msgid].fields[fieldid].name) == QString("time_usec") && messageInfo[msgid].fields[fieldid].type == MAVLINK_TYPE_UINT64_T)
{
time = *((quint64*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
}
else
{
// First value is not time, send out value 0
emitFieldValue(&message, fieldid, time);
}
// Send out field values from 1..n
for (unsigned int i = 1; i < messageInfo[msgid].num_fields; ++i)
{
emitFieldValue(&message, i, time);
}
// Send out combined math expressions
// FIXME XXX TODO
}
void MAVLinkDecoder::emitFieldValue(mavlink_message_t* msg, int fieldid, quint64 time)
{
// Add field tree widget item
uint8_t msgid = msg->msgid;
if (messageFilter.contains(msgid)) return;
QString fieldName(messageInfo[msgid].fields[fieldid].name);
QString fieldType;
uint8_t* m = ((uint8_t*)(receivedMessages+msgid))+8;
QString name("%1.%2");
QString unit("");
name = name.arg(messageInfo[msgid].name, fieldName);
switch (messageInfo[msgid].fields[fieldid].type)
{
case MAVLINK_TYPE_CHAR:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
char* str = (char*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
// Enforce null termination
str[messageInfo[msgid].fields[fieldid].array_length-1] = '\0';
QString string(name + ": " + str);
emit textMessageReceived(msg->sysid, msg->compid, 0, string);
}
else
{
// Single char
char b = *((char*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
unit = QString("char[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
emit valueChanged(msg->sysid, name, unit, b, time);
}
break;
case MAVLINK_TYPE_UINT8_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint8_t* nums = m+messageInfo[msgid].fields[fieldid].wire_offset;
fieldType = QString("uint8_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[fieldid].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
uint8_t u = *(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = "uint8_t";
emit valueChanged(msg->sysid, name, fieldType, u, time);
}
break;
case MAVLINK_TYPE_INT8_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int8_t* nums = (int8_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int8_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int8_t n = *((int8_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int8_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_UINT16_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint16_t* nums = (uint16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("uint16_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
uint16_t n = *((uint16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "uint16_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_INT16_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int16_t* nums = (int16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int16_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int16_t n = *((int16_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int16_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_UINT32_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint32_t* nums = (uint32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("uint32_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
float n = *((uint32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "uint32_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_INT32_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int32_t* nums = (int32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int32_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int32_t n = *((int32_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int32_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_FLOAT:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
float* nums = (float*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("float[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
float f = *((float*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "float";
emit valueChanged(msg->sysid, name, fieldType, f, time);
}
break;
case MAVLINK_TYPE_DOUBLE:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
double* nums = (double*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("double[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
double f = *((double*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "double";
emit valueChanged(msg->sysid, name, fieldType, f, time);
}
break;
case MAVLINK_TYPE_UINT64_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
uint64_t* nums = (uint64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("uint64_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
uint64_t n = *((uint64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "uint64_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
case MAVLINK_TYPE_INT64_T:
if (messageInfo[msgid].fields[fieldid].array_length > 0)
{
int64_t* nums = (int64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset);
fieldType = QString("int64_t[%1]").arg(messageInfo[msgid].fields[fieldid].array_length);
for (unsigned int j = 0; j < messageInfo[msgid].fields[j].array_length; ++j)
{
emit valueChanged(msg->sysid, QString("%1.%2").arg(name).arg(j), fieldType, nums[j], time);
}
}
else
{
// Single value
int64_t n = *((int64_t*)(m+messageInfo[msgid].fields[fieldid].wire_offset));
fieldType = "int64_t";
emit valueChanged(msg->sysid, name, fieldType, n, time);
}
break;
}
}
<|endoftext|> |
<commit_before>#include <unistd.h>
#include <getopt.h>
#include <libgen.h> // FIXME
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <map>
#include "cppunit-header.h"
typedef std::map<std::string, CppUnit::Outputter *> OutputterMap;
typedef std::map<std::string, CppUnit::TestListener *> ListenerMap;
//////////////////////////////////////////////////////////////////////
void usage()
{
}
//////////////////////////////////////////////////////////////////////
void dump(CppUnit::Test * test)
{
if (test)
{
std::cout << test->getName() << std::endl;
if (test->getChildTestCount())
{
for (int i = 0; i < test->getChildTestCount(); i++)
{
dump(test->getChildTestAt(i));
}
}
}
}
//////////////////////////////////////////////////////////////////////
CppUnit::Test * find(CppUnit::Test * root, const std::string & name)
{
CppUnit::Test * found = nullptr;
if (root)
{
if (name == root->getName())
found = root;
else if (root->getChildTestCount())
{
for (int i = 0; (!found) && i < root->getChildTestCount(); ++i)
found = find(root->getChildTestAt(i), name);
}
}
return found;
}
//////////////////////////////////////////////////////////////////////
int main(int argc, char ** argv)
{
CppUnit::TestResult result;
CppUnit::TestResultCollector collector;
result.addListener(&collector);
OutputterMap allOutputters{
{ "compiler", new CppUnit::CompilerOutputter(&collector, std::cout)},
{ "text", new CppUnit::TextOutputter(&collector, std::cout) },
{ "xml", new CppUnit::XmlOutputter(&collector, std::cout) },
{"none", nullptr },
};
ListenerMap allListeners{
{ "dots", new CppUnit::TextTestProgressListener() },
{ "brief", new CppUnit::BriefTestProgressListener() },
{ "none", nullptr },
};
CppUnit::Outputter * outputter = allOutputters.find("compiler")->second;
CppUnit::TestListener * listener = allListeners.find("dots")->second;
char flag = 0;
std::string runTest = basename(argv[0]);
if (!find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest))
{
runTest = "All Tests";
}
int repeat = 1;
while ((flag = getopt(argc, argv, "r:t:o:p:lh")) != -1)
{
switch(flag)
{
case 'r':
repeat = atoi(optarg);
break;
case 'o':
{
OutputterMap::const_iterator it = allOutputters.find(optarg);
if (it == allOutputters.end())
{
std::cerr << "Unknown outputter: " << optarg << std::endl;
return 1;
}
outputter = it->second;
}
break;
case 'p':
{
std::string progress(optarg);
ListenerMap::const_iterator it = allListeners.find(optarg);
if (it == allListeners.end())
{
std::cerr << "Unknown listener: " << optarg << std::endl;
return 1;
}
listener = it->second;
}
break;
case 'l':
dump(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
return 0;
break; // not reached
case 't':
runTest = optarg;
break;
case 'h':
default:
usage();
return 1;
break; // not reached
}
}
if (listener != nullptr)
result.addListener(listener);
CppUnit::Test * run = find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest);
if (run == nullptr)
{
std::cerr << "Unknown test case: " << runTest << std::endl;
return 1;
}
CppUnit::TestRunner runner;
runner.addTest(run);
for (int i = 0; i < repeat; i++) {
runner.run(result);
}
if (outputter) outputter->write();
return collector.testErrors() + collector.testFailures();
}
<commit_msg>Added a much overdue help message to the test driver<commit_after>#include <unistd.h>
#include <getopt.h>
#include <libgen.h> // FIXME
#include <iostream>
#include <fstream>
#include <memory>
#include <string>
#include <map>
#include "cppunit-header.h"
typedef std::map<std::string, CppUnit::Outputter *> OutputterMap;
typedef std::map<std::string, CppUnit::TestListener *> ListenerMap;
//////////////////////////////////////////////////////////////////////
void usage(const char * name)
{
std::cerr << "usage: " << name
<< " "
"[-r repeatnumber] "
"[-t testname] "
"[-o {compiler|text|xml|none}] "
"[-p {dots|brief|none}] [-l] [-h]"
<< std::endl;
}
//////////////////////////////////////////////////////////////////////
void dump(CppUnit::Test * test)
{
if (test)
{
std::cout << test->getName() << std::endl;
if (test->getChildTestCount())
{
for (int i = 0; i < test->getChildTestCount(); i++)
{
dump(test->getChildTestAt(i));
}
}
}
}
//////////////////////////////////////////////////////////////////////
CppUnit::Test * find(CppUnit::Test * root, const std::string & name)
{
CppUnit::Test * found = nullptr;
if (root)
{
if (name == root->getName())
found = root;
else if (root->getChildTestCount())
{
for (int i = 0; (!found) && i < root->getChildTestCount(); ++i)
found = find(root->getChildTestAt(i), name);
}
}
return found;
}
//////////////////////////////////////////////////////////////////////
int main(int argc, char ** argv)
{
CppUnit::TestResult result;
CppUnit::TestResultCollector collector;
result.addListener(&collector);
OutputterMap allOutputters{
{ "compiler", new CppUnit::CompilerOutputter(&collector, std::cout)},
{ "text", new CppUnit::TextOutputter(&collector, std::cout) },
{ "xml", new CppUnit::XmlOutputter(&collector, std::cout) },
{"none", nullptr },
};
ListenerMap allListeners{
{ "dots", new CppUnit::TextTestProgressListener() },
{ "brief", new CppUnit::BriefTestProgressListener() },
{ "none", nullptr },
};
CppUnit::Outputter * outputter = allOutputters.find("compiler")->second;
CppUnit::TestListener * listener = allListeners.find("dots")->second;
char flag = 0;
std::string runTest = basename(argv[0]);
if (!find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest))
{
runTest = "All Tests";
}
int repeat = 1;
while ((flag = getopt(argc, argv, "r:t:o:p:lh")) != -1)
{
switch(flag)
{
case 'r':
repeat = atoi(optarg);
break;
case 'o':
{
OutputterMap::const_iterator it = allOutputters.find(optarg);
if (it == allOutputters.end())
{
std::cerr << "Unknown outputter: " << optarg << std::endl;
return 1;
}
outputter = it->second;
}
break;
case 'p':
{
std::string progress(optarg);
ListenerMap::const_iterator it = allListeners.find(optarg);
if (it == allListeners.end())
{
std::cerr << "Unknown listener: " << optarg << std::endl;
return 1;
}
listener = it->second;
}
break;
case 'l':
dump(CppUnit::TestFactoryRegistry::getRegistry().makeTest());
return 0;
break; // not reached
case 't':
runTest = optarg;
break;
case 'h':
default:
usage(argv[0]);
return 1;
break; // not reached
}
}
if (listener != nullptr)
result.addListener(listener);
CppUnit::Test * run = find(CppUnit::TestFactoryRegistry::getRegistry().makeTest(), runTest);
if (run == nullptr)
{
std::cerr << "Unknown test case: " << runTest << std::endl;
return 1;
}
CppUnit::TestRunner runner;
runner.addTest(run);
for (int i = 0; i < repeat; i++) {
runner.run(result);
}
if (outputter) outputter->write();
return collector.testErrors() + collector.testFailures();
}
<|endoftext|> |
<commit_before>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2009, Distributed Systems Architecture Group, Universidad */
/* Complutense de Madrid (dsa-research.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "LibVirtDriver.h"
#include "Nebula.h"
#include <sstream>
#include <fstream>
int LibVirtDriver::deployment_description(
const VirtualMachine * vm,
const string& file_name) const
{
ofstream file;
int num;
vector<const Attribute *> attrs;
string vcpu;
string memory;
int memory_in_kb = 0;
string kernel = "";
string initrd = "";
string boot = "";
string root = "";
string kernel_cmd = "";
string bootloader = "";
const VectorAttribute * disk;
string type = "";
string target = "";
string bus = "";
string ro = "";
bool readonly;
const VectorAttribute * nic;
string mac = "";
string bridge = "";
string script = "";
const VectorAttribute * graphics;
string listen = "";
string port = "";
string passwd = "";
const VectorAttribute * input;
const VectorAttribute * features;
string pae = "";
string acpi = "";
const VectorAttribute * raw;
string data;
// ------------------------------------------------------------------------
file.open(file_name.c_str(), ios::out);
if (file.fail() == true)
{
goto error_file;
}
// ------------------------------------------------------------------------
// Starting XML document
// ------------------------------------------------------------------------
file << "<domain type='" << emulator << "'>" << endl;
// ------------------------------------------------------------------------
// Domain name
// ------------------------------------------------------------------------
file << "\t<name>one-" << vm->get_oid() << "</name>" << endl;
// ------------------------------------------------------------------------
// CPU
// ------------------------------------------------------------------------
vm->get_template_attribute("VCPU", vcpu);
if(vcpu.empty())
{
get_default("VCPU", vcpu);
}
if (!vcpu.empty())
{
file << "\t<vcpu>" << vcpu << "</vcpu>" << endl;
}
// ------------------------------------------------------------------------
// Memory
// ------------------------------------------------------------------------
vm->get_template_attribute("MEMORY",memory);
if (memory.empty())
{
get_default("MEMORY",memory);
}
if (!memory.empty())
{
memory_in_kb = atoi(memory.c_str()) * 1024;
file << "\t<memory>" << memory_in_kb << "</memory>" << endl;
}
else
{
goto error_memory;
}
// ------------------------------------------------------------------------
// OS and boot options
// ------------------------------------------------------------------------
file << "\t<os>" << endl;
if (emulator == "kvm")
{
file << "\t\t<type>hvm</type>" << endl;
}
num = vm->get_template_attribute("OS",attrs);
// Get values & defaults
if ( num >= 0 )
{
const VectorAttribute * os;
os = dynamic_cast<const VectorAttribute *>(attrs[0]);
if( os != 0 )
{
kernel = os->vector_value("KERNEL");
initrd = os->vector_value("INITRD");
boot = os->vector_value("BOOT");
root = os->vector_value("ROOT");
kernel_cmd = os->vector_value("KERNEL_CMD");
bootloader = os->vector_value("BOOTLOADER");
}
}
if ( kernel.empty() )
{
get_default("OS","KERNEL",kernel);
}
if ( initrd.empty() )
{
get_default("OS","INITRD",initrd);
}
if ( bootloader.empty() )
{
get_default("OS","BOOTLOADER",bootloader);
}
if ( boot.empty() )
{
get_default("OS","BOOT",boot);
if ( boot.empty() )
{
goto error_boot;
}
}
if ( root.empty() )
{
get_default("OS","ROOT",root);
}
if ( kernel_cmd.empty() )
{
get_default("OS","KERNEL_CMD",kernel_cmd);
}
// Start writing to the file with the info we got
if ( !kernel.empty() )
{
file << "\t\t<kernel>" << kernel << "</kernel>" << endl;
if ( !initrd.empty() )
{
file << "\t\t<initrd>" << initrd << "</initrd>" << endl;
}
if ( !root.empty() )
{
kernel_cmd = "root=/dev/" + root + " " + kernel_cmd;
}
if (!kernel_cmd.empty())
{
file << "\t\t<cmdline>" << kernel_cmd << "</cmdline>" << endl;
}
}
else if ( !bootloader.empty() )
{
file << "\t\t<bootloader>" << bootloader << "</bootloader>" << endl;
}
file << "\t\t<boot dev='" << boot << "'/>" << endl;
file << "\t</os>" << endl;
attrs.clear();
// ------------------------------------------------------------------------
// Disks
// ------------------------------------------------------------------------
file << "\t<devices>" << endl;
if (emulator == "kvm")
{
file << "\t\t<emulator>/usr/bin/kvm</emulator>" << endl;
}
num = vm->get_template_attribute("DISK",attrs);
for (int i=0; i < num ;i++,target="",ro="")
{
disk = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( disk == 0 )
{
continue;
}
type = disk->vector_value("TYPE");
target = disk->vector_value("TARGET");
ro = disk->vector_value("READONLY");
bus = disk->vector_value("BUS");
if (target.empty())
{
goto error_disk;
}
readonly = false;
if ( !ro.empty() )
{
transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);
if ( ro == "YES" )
{
readonly = true;
}
}
if ( type.empty() )
{
type = "disk";
}
else
{
string type_=type;
transform(type_.begin(),type_.end(),type_.begin(),(int(*)(int))toupper);
if ( type_ == "SWAP" )
{
type="disk";
}
}
file << "\t\t<disk type='file' device='" << type << "'>" << endl;
file << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << i
<< "'/>" << endl;
file << "\t\t\t<target dev='" << target << "'";
if (!bus.empty())
{
file << " bus='" << bus << "'/>" << endl;
}
else
{
file << "/>" << endl;
}
if (readonly)
{
file << "\t\t\t<readonly/>" << endl;
}
file << "\t\t</disk>" << endl;
}
attrs.clear();
// ------------------------------------------------------------------------
// Network interfaces
// ------------------------------------------------------------------------
num = vm->get_template_attribute("NIC",attrs);
for(int i=0; i<num;i++,mac="",bridge="",target="",script="")
{
nic = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( nic == 0 )
{
continue;
}
bridge = nic->vector_value("BRIDGE");
if ( bridge.empty() )
{
file << "\t\t<interface type='ethernet'>" << endl;
}
else
{
file << "\t\t<interface type='bridge'>" << endl;
file << "\t\t\t<source bridge='" << bridge << "'/>" << endl;
}
mac = nic->vector_value("MAC");
if( !mac.empty() )
{
file << "\t\t\t<mac address='" << mac << "'/>" << endl;
}
target = nic->vector_value("TARGET");
if( !target.empty() )
{
file << "\t\t\t<target dev='" << target << "'/>" << endl;
}
script = nic->vector_value("SCRIPT");
if( !script.empty() )
{
file << "\t\t\t<script path='" << script << "'/>" << endl;
}
file << "\t\t</interface>" << endl;
}
attrs.clear();
// ------------------------------------------------------------------------
// Graphics
// ------------------------------------------------------------------------
if ( vm->get_template_attribute("GRAPHICS",attrs) > 0 )
{
graphics = dynamic_cast<const VectorAttribute *>(attrs[0]);
if ( graphics != 0 )
{
type = graphics->vector_value("TYPE");
listen = graphics->vector_value("LISTEN");
port = graphics->vector_value("PORT");
passwd = graphics->vector_value("PASSWD");
if ( type == "vnc" || type == "VNC" )
{
file << "\t\t<graphics type='vnc'";
if ( !listen.empty() )
{
file << " listen='" << listen << "'";
}
if ( !port.empty() )
{
file << " port='" << port << "'";
}
if ( !passwd.empty() )
{
file << " password='" << passwd << "'";
}
file << "/>" << endl;
}
else
{
vm->log("VMM", Log::WARNING, "Not supported graphics type, ignored.");
}
}
}
attrs.clear();
// ------------------------------------------------------------------------
// Input
// ------------------------------------------------------------------------
if ( vm->get_template_attribute("INPUT",attrs) > 0 )
{
input = dynamic_cast<const VectorAttribute *>(attrs[0]);
if ( input != 0 )
{
type = input->vector_value("TYPE");
bus = input->vector_value("BUS");
if ( !type.empty() )
{
file << "\t\t<input type='" << type << "'";
if ( !bus.empty() )
{
file << " bus='" << bus << "'";
}
file << "/>" << endl;
}
}
}
attrs.clear();
file << "\t</devices>" << endl;
// ------------------------------------------------------------------------
// Features
// ------------------------------------------------------------------------
num = vm->get_template_attribute("FEATURES",attrs);
if ( num > 0 )
{
features = dynamic_cast<const VectorAttribute *>(attrs[0]);
if ( features != 0 )
{
pae = features->vector_value("PAE");
acpi = features->vector_value("ACPI");
file << "\t<features>" << endl;
if ( pae == "yes" )
{
file << "\t\t<pae/>" << endl;
}
if ( acpi == "no" )
{
file << "\t\t<acpi/>" << endl;
}
file << "\t</features>" << endl;
}
}
attrs.clear();
// ------------------------------------------------------------------------
// Raw KVM attributes
// ------------------------------------------------------------------------
num = vm->get_template_attribute("RAW",attrs);
for(int i=0; i<num;i++)
{
raw = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( raw == 0 )
{
continue;
}
type = raw->vector_value("TYPE");
transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
if ( type == "KVM" )
{
data = raw->vector_value("DATA");
file << "\t" << data << endl;
}
}
file << "</domain>" << endl;
file.close();
return 0;
error_file:
vm->log("VMM", Log::ERROR, "Could not open KVM deployment file.");
return -1;
error_memory:
vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided.");
file.close();
return -1;
error_boot:
vm->log("VMM", Log::ERROR, "No BOOT device defined and no default provided.");
file.close();
return -1;
error_disk:
vm->log("VMM", Log::ERROR, "Wrong target value in DISK.");
file.close();
return -1;
}
<commit_msg>Fix core in the LibVirtDriver when there is no OS in the template<commit_after>/* -------------------------------------------------------------------------- */
/* Copyright 2002-2009, Distributed Systems Architecture Group, Universidad */
/* Complutense de Madrid (dsa-research.org) */
/* */
/* Licensed under the Apache License, Version 2.0 (the "License"); you may */
/* not use this file except in compliance with the License. You may obtain */
/* a copy of the License at */
/* */
/* http://www.apache.org/licenses/LICENSE-2.0 */
/* */
/* Unless required by applicable law or agreed to in writing, software */
/* distributed under the License is distributed on an "AS IS" BASIS, */
/* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. */
/* See the License for the specific language governing permissions and */
/* limitations under the License. */
/* -------------------------------------------------------------------------- */
#include "LibVirtDriver.h"
#include "Nebula.h"
#include <sstream>
#include <fstream>
int LibVirtDriver::deployment_description(
const VirtualMachine * vm,
const string& file_name) const
{
ofstream file;
int num;
vector<const Attribute *> attrs;
string vcpu;
string memory;
int memory_in_kb = 0;
string kernel = "";
string initrd = "";
string boot = "";
string root = "";
string kernel_cmd = "";
string bootloader = "";
const VectorAttribute * disk;
string type = "";
string target = "";
string bus = "";
string ro = "";
bool readonly;
const VectorAttribute * nic;
string mac = "";
string bridge = "";
string script = "";
const VectorAttribute * graphics;
string listen = "";
string port = "";
string passwd = "";
const VectorAttribute * input;
const VectorAttribute * features;
string pae = "";
string acpi = "";
const VectorAttribute * raw;
string data;
// ------------------------------------------------------------------------
file.open(file_name.c_str(), ios::out);
if (file.fail() == true)
{
goto error_file;
}
// ------------------------------------------------------------------------
// Starting XML document
// ------------------------------------------------------------------------
file << "<domain type='" << emulator << "'>" << endl;
// ------------------------------------------------------------------------
// Domain name
// ------------------------------------------------------------------------
file << "\t<name>one-" << vm->get_oid() << "</name>" << endl;
// ------------------------------------------------------------------------
// CPU
// ------------------------------------------------------------------------
vm->get_template_attribute("VCPU", vcpu);
if(vcpu.empty())
{
get_default("VCPU", vcpu);
}
if (!vcpu.empty())
{
file << "\t<vcpu>" << vcpu << "</vcpu>" << endl;
}
// ------------------------------------------------------------------------
// Memory
// ------------------------------------------------------------------------
vm->get_template_attribute("MEMORY",memory);
if (memory.empty())
{
get_default("MEMORY",memory);
}
if (!memory.empty())
{
memory_in_kb = atoi(memory.c_str()) * 1024;
file << "\t<memory>" << memory_in_kb << "</memory>" << endl;
}
else
{
goto error_memory;
}
// ------------------------------------------------------------------------
// OS and boot options
// ------------------------------------------------------------------------
file << "\t<os>" << endl;
if (emulator == "kvm")
{
file << "\t\t<type>hvm</type>" << endl;
}
num = vm->get_template_attribute("OS",attrs);
// Get values & defaults
if ( num > 0 )
{
const VectorAttribute * os;
os = dynamic_cast<const VectorAttribute *>(attrs[0]);
if( os != 0 )
{
kernel = os->vector_value("KERNEL");
initrd = os->vector_value("INITRD");
boot = os->vector_value("BOOT");
root = os->vector_value("ROOT");
kernel_cmd = os->vector_value("KERNEL_CMD");
bootloader = os->vector_value("BOOTLOADER");
}
}
if ( kernel.empty() )
{
get_default("OS","KERNEL",kernel);
}
if ( initrd.empty() )
{
get_default("OS","INITRD",initrd);
}
if ( bootloader.empty() )
{
get_default("OS","BOOTLOADER",bootloader);
}
if ( boot.empty() )
{
get_default("OS","BOOT",boot);
if ( boot.empty() )
{
goto error_boot;
}
}
if ( root.empty() )
{
get_default("OS","ROOT",root);
}
if ( kernel_cmd.empty() )
{
get_default("OS","KERNEL_CMD",kernel_cmd);
}
// Start writing to the file with the info we got
if ( !kernel.empty() )
{
file << "\t\t<kernel>" << kernel << "</kernel>" << endl;
if ( !initrd.empty() )
{
file << "\t\t<initrd>" << initrd << "</initrd>" << endl;
}
if ( !root.empty() )
{
kernel_cmd = "root=/dev/" + root + " " + kernel_cmd;
}
if (!kernel_cmd.empty())
{
file << "\t\t<cmdline>" << kernel_cmd << "</cmdline>" << endl;
}
}
else if ( !bootloader.empty() )
{
file << "\t\t<bootloader>" << bootloader << "</bootloader>" << endl;
}
file << "\t\t<boot dev='" << boot << "'/>" << endl;
file << "\t</os>" << endl;
attrs.clear();
// ------------------------------------------------------------------------
// Disks
// ------------------------------------------------------------------------
file << "\t<devices>" << endl;
if (emulator == "kvm")
{
file << "\t\t<emulator>/usr/bin/kvm</emulator>" << endl;
}
num = vm->get_template_attribute("DISK",attrs);
for (int i=0; i < num ;i++,target="",ro="")
{
disk = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( disk == 0 )
{
continue;
}
type = disk->vector_value("TYPE");
target = disk->vector_value("TARGET");
ro = disk->vector_value("READONLY");
bus = disk->vector_value("BUS");
if (target.empty())
{
goto error_disk;
}
readonly = false;
if ( !ro.empty() )
{
transform(ro.begin(),ro.end(),ro.begin(),(int(*)(int))toupper);
if ( ro == "YES" )
{
readonly = true;
}
}
if ( type.empty() )
{
type = "disk";
}
else
{
string type_=type;
transform(type_.begin(),type_.end(),type_.begin(),(int(*)(int))toupper);
if ( type_ == "SWAP" )
{
type="disk";
}
}
file << "\t\t<disk type='file' device='" << type << "'>" << endl;
file << "\t\t\t<source file='" << vm->get_remote_dir() << "/disk." << i
<< "'/>" << endl;
file << "\t\t\t<target dev='" << target << "'";
if (!bus.empty())
{
file << " bus='" << bus << "'/>" << endl;
}
else
{
file << "/>" << endl;
}
if (readonly)
{
file << "\t\t\t<readonly/>" << endl;
}
file << "\t\t</disk>" << endl;
}
attrs.clear();
// ------------------------------------------------------------------------
// Network interfaces
// ------------------------------------------------------------------------
num = vm->get_template_attribute("NIC",attrs);
for(int i=0; i<num;i++,mac="",bridge="",target="",script="")
{
nic = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( nic == 0 )
{
continue;
}
bridge = nic->vector_value("BRIDGE");
if ( bridge.empty() )
{
file << "\t\t<interface type='ethernet'>" << endl;
}
else
{
file << "\t\t<interface type='bridge'>" << endl;
file << "\t\t\t<source bridge='" << bridge << "'/>" << endl;
}
mac = nic->vector_value("MAC");
if( !mac.empty() )
{
file << "\t\t\t<mac address='" << mac << "'/>" << endl;
}
target = nic->vector_value("TARGET");
if( !target.empty() )
{
file << "\t\t\t<target dev='" << target << "'/>" << endl;
}
script = nic->vector_value("SCRIPT");
if( !script.empty() )
{
file << "\t\t\t<script path='" << script << "'/>" << endl;
}
file << "\t\t</interface>" << endl;
}
attrs.clear();
// ------------------------------------------------------------------------
// Graphics
// ------------------------------------------------------------------------
if ( vm->get_template_attribute("GRAPHICS",attrs) > 0 )
{
graphics = dynamic_cast<const VectorAttribute *>(attrs[0]);
if ( graphics != 0 )
{
type = graphics->vector_value("TYPE");
listen = graphics->vector_value("LISTEN");
port = graphics->vector_value("PORT");
passwd = graphics->vector_value("PASSWD");
if ( type == "vnc" || type == "VNC" )
{
file << "\t\t<graphics type='vnc'";
if ( !listen.empty() )
{
file << " listen='" << listen << "'";
}
if ( !port.empty() )
{
file << " port='" << port << "'";
}
if ( !passwd.empty() )
{
file << " password='" << passwd << "'";
}
file << "/>" << endl;
}
else
{
vm->log("VMM", Log::WARNING, "Not supported graphics type, ignored.");
}
}
}
attrs.clear();
// ------------------------------------------------------------------------
// Input
// ------------------------------------------------------------------------
if ( vm->get_template_attribute("INPUT",attrs) > 0 )
{
input = dynamic_cast<const VectorAttribute *>(attrs[0]);
if ( input != 0 )
{
type = input->vector_value("TYPE");
bus = input->vector_value("BUS");
if ( !type.empty() )
{
file << "\t\t<input type='" << type << "'";
if ( !bus.empty() )
{
file << " bus='" << bus << "'";
}
file << "/>" << endl;
}
}
}
attrs.clear();
file << "\t</devices>" << endl;
// ------------------------------------------------------------------------
// Features
// ------------------------------------------------------------------------
num = vm->get_template_attribute("FEATURES",attrs);
if ( num > 0 )
{
features = dynamic_cast<const VectorAttribute *>(attrs[0]);
if ( features != 0 )
{
pae = features->vector_value("PAE");
acpi = features->vector_value("ACPI");
file << "\t<features>" << endl;
if ( pae == "yes" )
{
file << "\t\t<pae/>" << endl;
}
if ( acpi == "no" )
{
file << "\t\t<acpi/>" << endl;
}
file << "\t</features>" << endl;
}
}
attrs.clear();
// ------------------------------------------------------------------------
// Raw KVM attributes
// ------------------------------------------------------------------------
num = vm->get_template_attribute("RAW",attrs);
for(int i=0; i<num;i++)
{
raw = dynamic_cast<const VectorAttribute *>(attrs[i]);
if ( raw == 0 )
{
continue;
}
type = raw->vector_value("TYPE");
transform(type.begin(),type.end(),type.begin(),(int(*)(int))toupper);
if ( type == "KVM" )
{
data = raw->vector_value("DATA");
file << "\t" << data << endl;
}
}
file << "</domain>" << endl;
file.close();
return 0;
error_file:
vm->log("VMM", Log::ERROR, "Could not open KVM deployment file.");
return -1;
error_memory:
vm->log("VMM", Log::ERROR, "No MEMORY defined and no default provided.");
file.close();
return -1;
error_boot:
vm->log("VMM", Log::ERROR, "No BOOT device defined and no default provided.");
file.close();
return -1;
error_disk:
vm->log("VMM", Log::ERROR, "Wrong target value in DISK.");
file.close();
return -1;
}
<|endoftext|> |
<commit_before>// __BEGIN_LICENSE__
// Copyright (C) 2006-2009 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
// System includes
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
// Time
#ifdef WIN32
#include <Windows.h>
#else // For Linux
#include <sys/time.h>
#endif
// BOOST includes
#include <boost/thread/once.hpp>
// VisionWorkbench includes
#include <vw/Core/Debugging.h>
#include <vw/Core/Exception.h>
// Self
#include <vw/Core/Stopwatch.h>
using std::endl;
using std::map;
using std::pair;
using std::string;
using std::vector;
namespace vw {
// Stopwatch
unsigned long long Stopwatch::microtime(bool use_cpu_time) {
#ifdef WIN32
if (use_cpu_time) {
// TODO: Find the analogous function for "clock()" for windows
throw NoImplErr();
} else {
return ((long long)GetTickCount() * 1000);
}
#else
if (use_cpu_time) {
return ((long long)clock() * 1000000 / CLOCKS_PER_SEC);
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
return ((long long) tv.tv_sec * (long long) 1000000 +
(long long) tv.tv_usec);
}
#endif
}
bool pair_string_stopwatch_elapsed_gt(const pair<string, Stopwatch> &a,
const pair<string, Stopwatch> &b)
{
return a.second.elapsed_microseconds() > b.second.elapsed_microseconds();
}
// StopwatchSet
string StopwatchSet::report() const {
Mutex::Lock lock(m_mutex);
vector<pair<string, Stopwatch> > sorted(m_stopwatches.begin(), m_stopwatches.end());
sort(sorted.begin(), sorted.end(), pair_string_stopwatch_elapsed_gt);
std::ostringstream out;
out << "StopwatchSet lifetime: " << elapsed_seconds_since_construction() << endl;
out << "Elapsed seconds for all stopwatches:" << endl;
for (unsigned int i= 0; i< sorted.size(); i++) {
const std::string &name(sorted[i].first);
const Stopwatch &sw(sorted[i].second);
double elapsed = sw.elapsed_seconds();
int n = sw.num_stops();
out << elapsed;
if (n) out << " (avg " << elapsed / n << " x " << n << ")";
out << ": " << name;
if (sw.is_running()) out << " (still running!)";
out << endl;
}
return out.str();
}
// Global StopwatchSet
namespace GlobalStopwatchSet {
static StopwatchSet *_g_global_stopwatch_set;
void _create() {
_g_global_stopwatch_set = new StopwatchSet();
}
};
// Return the global StopwatchSet
//
// We want to be able to use this during globals and statics construction, so we cannot
// assume that constructors in this file have already been called
StopwatchSet *global_stopwatch_set() {
static RunOnce once = VW_RUNONCE_INIT;
once.run(GlobalStopwatchSet::_create);
return GlobalStopwatchSet::_g_global_stopwatch_set;
}
}; // namespace vw
<commit_msg>add a comment warning :/<commit_after>// __BEGIN_LICENSE__
// Copyright (C) 2006-2009 United States Government as represented by
// the Administrator of the National Aeronautics and Space Administration.
// All Rights Reserved.
// __END_LICENSE__
// System includes
#include <iostream>
#include <vector>
#include <algorithm>
#include <sstream>
// Time
#ifdef WIN32
#include <Windows.h>
#else // For Linux
#include <sys/time.h>
#endif
// BOOST includes
#include <boost/thread/once.hpp>
// VisionWorkbench includes
#include <vw/Core/Debugging.h>
#include <vw/Core/Exception.h>
// Self
#include <vw/Core/Stopwatch.h>
using std::endl;
using std::map;
using std::pair;
using std::string;
using std::vector;
namespace vw {
// Stopwatch
unsigned long long Stopwatch::microtime(bool use_cpu_time) {
#ifdef WIN32
if (use_cpu_time) {
// TODO: Find the analogous function for "clock()" for windows
throw NoImplErr();
} else {
return ((long long)GetTickCount() * 1000);
}
#else
if (use_cpu_time) {
// XXX: This provides no useful information. On any linux system after
// 2003 or so, the clock rate is not a constant.
return ((long long)clock() * 1000000 / CLOCKS_PER_SEC);
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
return ((long long) tv.tv_sec * (long long) 1000000 +
(long long) tv.tv_usec);
}
#endif
}
bool pair_string_stopwatch_elapsed_gt(const pair<string, Stopwatch> &a,
const pair<string, Stopwatch> &b)
{
return a.second.elapsed_microseconds() > b.second.elapsed_microseconds();
}
// StopwatchSet
string StopwatchSet::report() const {
Mutex::Lock lock(m_mutex);
vector<pair<string, Stopwatch> > sorted(m_stopwatches.begin(), m_stopwatches.end());
sort(sorted.begin(), sorted.end(), pair_string_stopwatch_elapsed_gt);
std::ostringstream out;
out << "StopwatchSet lifetime: " << elapsed_seconds_since_construction() << endl;
out << "Elapsed seconds for all stopwatches:" << endl;
for (unsigned int i= 0; i< sorted.size(); i++) {
const std::string &name(sorted[i].first);
const Stopwatch &sw(sorted[i].second);
double elapsed = sw.elapsed_seconds();
int n = sw.num_stops();
out << elapsed;
if (n) out << " (avg " << elapsed / n << " x " << n << ")";
out << ": " << name;
if (sw.is_running()) out << " (still running!)";
out << endl;
}
return out.str();
}
// Global StopwatchSet
namespace GlobalStopwatchSet {
static StopwatchSet *_g_global_stopwatch_set;
void _create() {
_g_global_stopwatch_set = new StopwatchSet();
}
};
// Return the global StopwatchSet
//
// We want to be able to use this during globals and statics construction, so we cannot
// assume that constructors in this file have already been called
StopwatchSet *global_stopwatch_set() {
static RunOnce once = VW_RUNONCE_INIT;
once.run(GlobalStopwatchSet::_create);
return GlobalStopwatchSet::_g_global_stopwatch_set;
}
}; // namespace vw
<|endoftext|> |
<commit_before>
/*
poedit, a wxWindows i18n catalogs editor
---------------
gexecute.cpp
Gettext execution code
(c) Vaclav Slavik, 2000-2003
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include <wx/wxprec.h>
#include <wx/utils.h>
#include <wx/log.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
#include <wx/string.h>
#include <wx/intl.h>
struct MyProcessData
{
bool Running;
int ExitCode;
wxArrayString Stderr;
wxArrayString Stdout;
};
class MyPipedProcess : public wxProcess
{
public:
MyPipedProcess(MyProcessData *data) : wxProcess(), m_data(data)
{
m_data->Running = true;
m_data->Stderr.Empty();
m_data->Stdout.Empty();
Redirect();
}
bool HasInput()
{
bool hasInput = false;
wxInputStream* is = GetInputStream();
if (is && !is->Eof())
{
wxTextInputStream tis(*is);
m_data->Stdout.Add(tis.ReadLine());
hasInput = true;
}
wxInputStream* es = GetErrorStream();
if (es && !es->Eof())
{
wxTextInputStream tis(*es);
m_data->Stderr.Add(tis.ReadLine());
hasInput = true;
}
return hasInput;
}
void OnTerminate(int pid, int status)
{
while (HasInput()) {}
m_data->Running = false;
m_data->ExitCode = status;
wxProcess::OnTerminate(pid, status);
}
private:
MyProcessData *m_data;
};
#ifdef __UNIX__
// we have to do this because otherwise xgettext might
// speak in native language, not English, and we cannot parse
// it correctly (not yet)
class TempLocaleSwitcher
{
public:
TempLocaleSwitcher(const wxString& locale)
{
wxGetEnv(_T("LC_ALL"), &m_all);
wxGetEnv(_T("LC_MESSAGES"), &m_messages);
wxGetEnv(_T("LC_LANG"), &m_lang);
wxSetEnv(_T("LC_ALL"), locale);
wxSetEnv(_T("LC_MESSAGES"), locale);
wxSetEnv(_T("LANG"), locale);
}
~TempLocaleSwitcher()
{
wxSetEnv(_T("LC_ALL"), m_all);
wxSetEnv(_T("LC_MESSAGES"), m_messages);
wxSetEnv(_T("LANG"), m_lang);
}
private:
wxString m_all, m_messages, m_lang;
};
#endif
bool ExecuteGettext(const wxString& cmdline)
{
#ifdef __UNIX__
TempLocaleSwitcher localeSwitcher(_T("en"));
#endif
size_t i;
MyProcessData pdata;
MyPipedProcess *process;
process = new MyPipedProcess(&pdata);
int pid = wxExecute(cmdline, false, process);
if (pid == 0)
{
wxLogError(_("Cannot execute program: ") + cmdline.BeforeFirst(_T(' ')));
return false;
}
while (pdata.Running)
{
process->HasInput();
wxUsleep(50);
wxYield();
}
bool isMsgmerge = (cmdline.BeforeFirst(_T(' ')) == _T("msgmerge"));
wxString dummy;
for (i = 0; i < pdata.Stderr.GetCount(); i++)
{
if (pdata.Stderr[i].empty()) continue;
if (isMsgmerge)
{
dummy = pdata.Stderr[i];
dummy.Replace(_T("."), wxEmptyString);
if (dummy.empty() || dummy == _T(" done")) continue;
//msgmerge outputs *progress* to stderr, damn it!
}
wxLogError(_T("%s"), pdata.Stderr[i].c_str());
}
return pdata.ExitCode == 0;
}
<commit_msg>fixed piping of executed commmand if the pipe doesn't contain any new data<commit_after>
/*
poedit, a wxWindows i18n catalogs editor
---------------
gexecute.cpp
Gettext execution code
(c) Vaclav Slavik, 2000-2003
*/
#ifdef __GNUG__
#pragma implementation
#endif
#include <wx/wxprec.h>
#include <wx/utils.h>
#include <wx/log.h>
#include <wx/process.h>
#include <wx/txtstrm.h>
#include <wx/string.h>
#include <wx/intl.h>
struct MyProcessData
{
bool Running;
int ExitCode;
wxArrayString Stderr;
wxArrayString Stdout;
};
class MyPipedProcess : public wxProcess
{
public:
MyPipedProcess(MyProcessData *data) : wxProcess(), m_data(data)
{
m_data->Running = true;
m_data->Stderr.Empty();
m_data->Stdout.Empty();
Redirect();
}
bool HasInput()
{
bool hasInput = false;
wxInputStream* is = GetInputStream();
if (is && is->CanRead() && !is->Eof())
{
wxTextInputStream tis(*is);
m_data->Stdout.Add(tis.ReadLine());
hasInput = true;
}
wxInputStream* es = GetErrorStream();
if (es && es->CanRead() && !es->Eof())
{
wxTextInputStream tis(*es);
m_data->Stderr.Add(tis.ReadLine());
hasInput = true;
}
return hasInput;
}
void OnTerminate(int pid, int status)
{
while (HasInput()) {}
m_data->Running = false;
m_data->ExitCode = status;
wxProcess::OnTerminate(pid, status);
}
private:
MyProcessData *m_data;
};
#ifdef __UNIX__
// we have to do this because otherwise xgettext might
// speak in native language, not English, and we cannot parse
// it correctly (not yet)
class TempLocaleSwitcher
{
public:
TempLocaleSwitcher(const wxString& locale)
{
wxGetEnv(_T("LC_ALL"), &m_all);
wxGetEnv(_T("LC_MESSAGES"), &m_messages);
wxGetEnv(_T("LC_LANG"), &m_lang);
wxSetEnv(_T("LC_ALL"), locale);
wxSetEnv(_T("LC_MESSAGES"), locale);
wxSetEnv(_T("LANG"), locale);
}
~TempLocaleSwitcher()
{
wxSetEnv(_T("LC_ALL"), m_all);
wxSetEnv(_T("LC_MESSAGES"), m_messages);
wxSetEnv(_T("LANG"), m_lang);
}
private:
wxString m_all, m_messages, m_lang;
};
#endif
bool ExecuteGettext(const wxString& cmdline)
{
#ifdef __UNIX__
TempLocaleSwitcher localeSwitcher(_T("en"));
#endif
size_t i;
MyProcessData pdata;
MyPipedProcess *process;
process = new MyPipedProcess(&pdata);
int pid = wxExecute(cmdline, false, process);
if (pid == 0)
{
wxLogError(_("Cannot execute program: ") + cmdline.BeforeFirst(_T(' ')));
return false;
}
while (pdata.Running)
{
process->HasInput();
wxUsleep(50);
wxYield();
}
bool isMsgmerge = (cmdline.BeforeFirst(_T(' ')) == _T("msgmerge"));
wxString dummy;
for (i = 0; i < pdata.Stderr.GetCount(); i++)
{
if (pdata.Stderr[i].empty()) continue;
if (isMsgmerge)
{
dummy = pdata.Stderr[i];
dummy.Replace(_T("."), wxEmptyString);
if (dummy.empty() || dummy == _T(" done")) continue;
//msgmerge outputs *progress* to stderr, damn it!
}
wxLogError(_T("%s"), pdata.Stderr[i].c_str());
}
return pdata.ExitCode == 0;
}
<|endoftext|> |
<commit_before>#include "convolution2d.hpp"
void convolution2d
(
const cv::Mat& src,
cv::Mat& dst,
const cv::Mat& kernel
)
{
const int half_size = (kernel.cols / 2);
for (int y = half_size; y < (src.rows - half_size); y++)
{
for (int x = half_size; x < (src.cols - half_size); x++)
{
double sum = 0.0;
for (int dy = -half_size; dy <= half_size; dy++)
{
for (int dx = -half_size; dx <= half_size; dx++)
{
sum += (src.ptr<uchar>(y+dy)[x+dx] * kernel.ptr<float>(dy+half_size)[dx+half_size]);
}
}
dst.ptr<uchar>(y)[x] = sum;
}
}
}
double launch_convolution2d
(
const cv::Mat& src,
cv::Mat& dst,
const cv::Mat& kernel,
const int loop_num
)
{
double f = 1000.0 / cv::getTickFrequency();
int64 start = 0, end = 0;
double time = 0.0;
for (int i = 0; i <= loop_num; i++)
{
start = cv::getTickCount();
convolution2d(src, dst, kernel);
end = cv::getTickCount();
time += (i > 0) ? ((end - start) * f) : 0;
}
time /= loop_num;
return time;
}
<commit_msg>fixed calculation<commit_after>#include "convolution2d.hpp"
void convolution2d
(
const cv::Mat& src,
cv::Mat& dst,
const cv::Mat& kernel
)
{
const int half_size = (kernel.cols / 2);
for (int y = half_size; y < (src.rows - half_size); y++)
{
for (int x = half_size; x < (src.cols - half_size); x++)
{
float sum = 0.0f;
for (int dy = -half_size; dy <= half_size; dy++)
{
for (int dx = -half_size; dx <= half_size; dx++)
{
sum += (kernel.ptr<float>(dy+half_size)[dx+half_size] * src.ptr<uchar>(y+dy)[x+dx]);
}
}
dst.ptr<uchar>(y)[x] = sum;
}
}
}
double launch_convolution2d
(
const cv::Mat& src,
cv::Mat& dst,
const cv::Mat& kernel,
const int loop_num
)
{
double f = 1000.0 / cv::getTickFrequency();
int64 start = 0, end = 0;
double time = 0.0;
for (int i = 0; i <= loop_num; i++)
{
start = cv::getTickCount();
convolution2d(src, dst, kernel);
end = cv::getTickCount();
time += (i > 0) ? ((end - start) * f) : 0;
}
time /= loop_num;
return time;
}
<|endoftext|> |
<commit_before>// tests.cpp
#include <gtest/gtest.h>
#include <math.h>
double squareRoot(const double a)
{
double b = sqrt(a);
if (b != b) // nan check
{
return -1.0;
}
else
{
return sqrt(a);
}
}
TEST(SquareRootTest, PositiveNos)
{
ASSERT_EQ(6, squareRoot(36.0));
ASSERT_EQ(18.0, squareRoot(324.0));
ASSERT_EQ(25.4, squareRoot(645.16));
ASSERT_EQ(0, squareRoot(0.0));
}
TEST(SquareRootTest, NegativeNos)
{
ASSERT_EQ(-1.0, squareRoot(-15.0));
ASSERT_EQ(-1.0, squareRoot(-0.2));
}
int main(int argc, char **argv)
{
testing::InitGoogleTest(&argc, argv);
return RUN_ALL_TESTS();
}<commit_msg>Deleted old sample test file<commit_after><|endoftext|> |
<commit_before>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <complex>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::abs;
using af::cfloat;
using af::cdouble;
///////////////////////////////// CPP ////////////////////////////////////
//
template<typename T>
af::array makeSparse(af::array A, int factor)
{
A = floor(A * 1000);
A = A * ((A % factor) == 0) / 1000;
return A;
}
template<>
af::array makeSparse<cfloat>(af::array A, int factor)
{
af::array r = real(A);
r = floor(r * 1000);
r = r * ((r % factor) == 0) / 1000;
af::array i = real(A);
i = floor(i * 1000);
i = i * ((i % factor) == 0) / 1000;
A = af::complex(r, i);
return A;
}
template<>
af::array makeSparse<cdouble>(af::array A, int factor)
{
af::array r = real(A);
r = floor(r * 1000);
r = r * ((r % factor) == 0) / 1000;
af::array i = real(A);
i = floor(i * 1000);
i = i * ((i % factor) == 0) / 1000;
A = af::complex(r, i);
return A;
}
template<typename T>
void sparseTester(const int m, const int n, const int k, int factor, double eps)
{
af::deviceGC();
if (noDoubleTests<T>()) return;
#if 1
af::array A = cpu_randu<T>(af::dim4(m, n));
af::array B = cpu_randu<T>(af::dim4(n, k));
af::array C = cpu_randu<T>(af::dim4(m, k));
#else
af::array A = af::randu(m, n, (af::dtype)af::dtype_traits<T>::af_type);
af::array B = af::randu(n, k, (af::dtype)af::dtype_traits<T>::af_type);
#endif
A = makeSparse<T>(A, factor);
// Result of GEMM
af::array dRes1 = matmul(A, B);
af::array dRes2 = matmul(A, C, AF_MAT_TRANS, AF_MAT_NONE);
af::array dRes3 = matmul(A, C, AF_MAT_CTRANS, AF_MAT_NONE);
// Create Sparse Array From Dense
af::array sA = af::createSparseArray(A, AF_STORAGE_CSR);
// Sparse Matmul
af::array sRes1 = matmul(sA, B);
af::array sRes2 = matmul(sA, C, AF_MAT_TRANS, AF_MAT_NONE);
af::array sRes3 = matmul(sA, C, AF_MAT_CTRANS, AF_MAT_NONE);
// Verify Results
ASSERT_NEAR(0, af::sum<double>(af::abs(real(dRes1 - sRes1))) / (m * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(imag(dRes1 - sRes1))) / (m * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(real(dRes2 - sRes2))) / (n * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(imag(dRes2 - sRes2))) / (n * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(real(dRes3 - sRes3))) / (n * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(imag(dRes3 - sRes3))) / (n * k), eps);
}
#define SPARSE_TESTS(T, eps) \
TEST(SPARSE, T##Square) \
{ \
sparseTester<T>(1000, 1000, 100, 5, eps); \
} \
TEST(SPARSE, T##RectMultiple) \
{ \
sparseTester<T>(2048, 1024, 512, 3, eps); \
} \
TEST(SPARSE, T##RectDense) \
{ \
sparseTester<T>(500, 1000, 250, 1, eps); \
} \
SPARSE_TESTS(float, 0.01)
SPARSE_TESTS(double, 1E-5)
SPARSE_TESTS(cfloat, 0.01)
SPARSE_TESTS(cdouble, 1E-5)
#undef SPARSE_TESTS
<commit_msg>TESTS: Improvements to sparse tests<commit_after>/*******************************************************
* Copyright (c) 2014, ArrayFire
* All rights reserved.
*
* This file is distributed under 3-clause BSD license.
* The complete license agreement can be obtained at:
* http://arrayfire.com/licenses/BSD-3-Clause
********************************************************/
#include <gtest/gtest.h>
#include <arrayfire.h>
#include <af/dim4.hpp>
#include <af/defines.h>
#include <af/traits.hpp>
#include <vector>
#include <iostream>
#include <complex>
#include <string>
#include <testHelpers.hpp>
using std::vector;
using std::string;
using std::cout;
using std::endl;
using std::abs;
using af::cfloat;
using af::cdouble;
///////////////////////////////// CPP ////////////////////////////////////
//
template<typename T>
af::array makeSparse(af::array A, int factor)
{
A = floor(A * 1000);
A = A * ((A % factor) == 0) / 1000;
return A;
}
template<>
af::array makeSparse<cfloat>(af::array A, int factor)
{
af::array r = real(A);
r = floor(r * 1000);
r = r * ((r % factor) == 0) / 1000;
af::array i = r / 2;
A = af::complex(r, i);
return A;
}
template<>
af::array makeSparse<cdouble>(af::array A, int factor)
{
af::array r = real(A);
r = floor(r * 1000);
r = r * ((r % factor) == 0) / 1000;
af::array i = r / 2;
A = af::complex(r, i);
return A;
}
template<typename T>
void sparseTester(const int m, const int n, const int k, int factor, double eps)
{
af::deviceGC();
if (noDoubleTests<T>()) return;
#if 1
af::array A = cpu_randu<T>(af::dim4(m, n));
af::array B = cpu_randu<T>(af::dim4(n, k));
#else
af::array A = af::randu(m, n, (af::dtype)af::dtype_traits<T>::af_type);
af::array B = af::randu(n, k, (af::dtype)af::dtype_traits<T>::af_type);
#endif
A = makeSparse<T>(A, factor);
// Result of GEMM
af::array dRes1 = matmul(A, B);
// Create Sparse Array From Dense
af::array sA = af::createSparseArray(A, AF_STORAGE_CSR);
// Sparse Matmul
af::array sRes1 = matmul(sA, B);
// Verify Results
ASSERT_NEAR(0, af::sum<double>(af::abs(real(dRes1 - sRes1))) / (m * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(imag(dRes1 - sRes1))) / (m * k), eps);
}
template<typename T>
void sparseTransposeTester(const int m, const int n, const int k, int factor, double eps)
{
af::deviceGC();
if (noDoubleTests<T>()) return;
#if 1
af::array A = cpu_randu<T>(af::dim4(m, n));
af::array B = cpu_randu<T>(af::dim4(m, k));
#else
af::array A = af::randu(m, n, (af::dtype)af::dtype_traits<T>::af_type);
af::array B = af::randu(m, k, (af::dtype)af::dtype_traits<T>::af_type);
#endif
A = makeSparse<T>(A, factor);
// Result of GEMM
af::array dRes2 = matmul(A, B, AF_MAT_TRANS, AF_MAT_NONE);
af::array dRes3 = matmul(A, B, AF_MAT_CTRANS, AF_MAT_NONE);
// Create Sparse Array From Dense
af::array sA = af::createSparseArray(A, AF_STORAGE_CSR);
// Sparse Matmul
af::array sRes2 = matmul(sA, B, AF_MAT_TRANS, AF_MAT_NONE);
af::array sRes3 = matmul(sA, B, AF_MAT_CTRANS, AF_MAT_NONE);
// Verify Results
ASSERT_NEAR(0, af::sum<double>(af::abs(real(dRes2 - sRes2))) / (n * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(imag(dRes2 - sRes2))) / (n * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(real(dRes3 - sRes3))) / (n * k), eps);
ASSERT_NEAR(0, af::sum<double>(af::abs(imag(dRes3 - sRes3))) / (n * k), eps);
}
#define SPARSE_TESTS(T, eps) \
TEST(SPARSE, T##Square) \
{ \
sparseTester<T>(1000, 1000, 100, 5, eps); \
} \
TEST(SPARSE, T##RectMultiple) \
{ \
sparseTester<T>(2048, 1024, 512, 3, eps); \
} \
TEST(SPARSE, T##RectDense) \
{ \
sparseTester<T>(500, 1000, 250, 1, eps); \
} \
TEST(SPARSE, T##MatVec) \
{ \
sparseTester<T>(625, 1331, 1, 2, eps); \
} \
TEST(SPARSE_TRANSPOSE, T##Square) \
{ \
sparseTransposeTester<T>(1000, 1000, 100, 5, eps); \
} \
TEST(SPARSE_TRANSPOSE, T##RectMultiple) \
{ \
sparseTransposeTester<T>(2048, 1024, 512, 3, eps); \
} \
TEST(SPARSE_TRANSPOSE, T##RectDense) \
{ \
sparseTransposeTester<T>(453, 751, 397, 1, eps); \
} \
TEST(SPARSE_TRANSPOSE, T##MatVec) \
{ \
sparseTransposeTester<T>(625, 1331, 1, 2, eps); \
} \
SPARSE_TESTS(float, 0.01)
SPARSE_TESTS(double, 1E-5)
SPARSE_TESTS(cfloat, 0.01)
SPARSE_TESTS(cdouble, 1E-5)
#undef SPARSE_TESTS
<|endoftext|> |
<commit_before>/*
Special class, initializers for windows
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <winsock2.h>
#ifdef _MSC_VER
#include "mailstream_ssl_private.h"
#include "mmapstring_private.h"
#endif
class win_init {
public:
win_init() {
wsocket_init();
#ifdef _MSC_VER
/* Initialise Mutexs */
mmapstring_init_lock();
#ifdef USE_SSL
{
mailstream_ssl_init_lock();
}
#endif
#endif
}
~win_init() {
WSACleanup();
}
private:
WSADATA winsockData;
void wsocket_init() {
int success = WSAStartup((WORD)0x0101, &winsockData);
if (success != 0)
{
throw "Cannot startup windows sockets api.";
}
}
};
/* Initialise */
static win_init windows_startup;
<commit_msg>Removed extra braces<commit_after>/*
Special class, initializers for windows
*/
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif
#include <winsock2.h>
#ifdef _MSC_VER
#include "mailstream_ssl_private.h"
#include "mmapstring_private.h"
#endif
class win_init {
public:
win_init() {
wsocket_init();
#ifdef _MSC_VER
/* Initialise Mutexs */
mmapstring_init_lock();
#ifdef USE_SSL
mailstream_ssl_init_lock();
#endif
#endif
}
~win_init() {
WSACleanup();
}
private:
WSADATA winsockData;
void wsocket_init() {
int success = WSAStartup((WORD)0x0101, &winsockData);
if (success != 0)
{
throw "Cannot startup windows sockets api.";
}
}
};
/* Initialise */
static win_init windows_startup;
<|endoftext|> |
<commit_before>/*
Copyright 2016 Fixstars Corporation
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.
*/
#ifndef SGM_WINNER_TAKES_ALL_HPP
#define SGM_WINNER_TAKES_ALL_HPP
#include "device_buffer.hpp"
#include "types.hpp"
namespace sgm {
template <size_t MAX_DISPARITY>
class WinnerTakesAll {
private:
DeviceBuffer<output_type> m_left_buffer;
DeviceBuffer<output_type> m_right_buffer;
public:
WinnerTakesAll();
const output_type *get_left_output() const {
return m_left_buffer.data();
}
const output_type *get_right_output() const {
return m_right_buffer.data();
}
void enqueue(
const cost_type *src,
size_t width,
size_t height,
float uniqueness,
cudaStream_t stream);
void enqueue(
output_type *left,
output_type *right,
const cost_type *src,
size_t width,
size_t height,
float uniqueness,
cudaStream_t stream);
};
}
#endif
<commit_msg>Change interface of WinnerTakesAll<commit_after>/*
Copyright 2016 Fixstars Corporation
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.
*/
#ifndef SGM_WINNER_TAKES_ALL_HPP
#define SGM_WINNER_TAKES_ALL_HPP
#include "device_buffer.hpp"
#include "types.hpp"
namespace sgm {
template <size_t MAX_DISPARITY, typename _ComputeDisparity>
class WinnerTakesAll {
using output_type = typename _ComputeDisparity::value_type;
private:
DeviceBuffer<output_type> m_left_buffer;
DeviceBuffer<output_type> m_right_buffer;
_ComputeDisparity m_compute;
public:
WinnerTakesAll(_ComputeDisparity compute_);
const output_type *get_left_output() const {
return m_left_buffer.data();
}
const output_type *get_right_output() const {
return m_right_buffer.data();
}
[[deprecated]]
void enqueue(
const cost_type *src,
size_t width,
size_t height,
float uniqueness,
cudaStream_t stream);
[[deprecated]]
void enqueue(
output_type *left,
output_type *right,
const cost_type *src,
size_t width,
size_t height,
float uniqueness,
cudaStream_t stream);
void enqueue(
const cost_type *src,
size_t width,
size_t height,
cudaStream_t stream);
void enqueue(
output_type *left,
output_type *right,
const cost_type *src,
size_t width,
size_t height,
cudaStream_t stream);
};
namespace detail {
struct Hoge { using value_type = uint16_t; };
}
}
#endif
<|endoftext|> |
<commit_before>
#include "Library.h"
#include "Debug.h"
#if NV_OS_WIN32
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <windows.h>
#else
#include <dlfcn.h>
#endif
void * nvLoadLibrary(const char * name)
{
#if NV_OS_WIN32
return LoadLibraryExA( name, NULL, 0 );
#else
return dlopen(name, RTLD_LAZY);
#endif
}
void nvUnloadLibrary(void * handle)
{
nvDebugCheck(handle != NULL);
#if NV_OS_WIN32
FreeLibrary(handle);
#else
dlclose(handle);
#endif
}
void * nvBindSymbol(void * handle, const char * symbol)
{
#if NV_OS_WIN32
return (void *)GetProcAddressA(handle, symbol);
#else
return (void *)dlsym(handle, symbol);
#endif
}
<commit_msg>Win32 fixes.<commit_after>
#include "Library.h"
#include "Debug.h"
#if NV_OS_WIN32
#define WIN32_LEAN_AND_MEAN
#define VC_EXTRALEAN
#include <windows.h>
#else
#include <dlfcn.h>
#endif
void * nvLoadLibrary(const char * name)
{
#if NV_OS_WIN32
return (void *)LoadLibraryExA( name, NULL, 0 );
#else
return dlopen(name, RTLD_LAZY);
#endif
}
void nvUnloadLibrary(void * handle)
{
nvDebugCheck(handle != NULL);
#if NV_OS_WIN32
FreeLibrary((HMODULE)handle);
#else
dlclose(handle);
#endif
}
void * nvBindSymbol(void * handle, const char * symbol)
{
#if NV_OS_WIN32
return (void *)GetProcAddress((HMODULE)handle, symbol);
#else
return (void *)dlsym(handle, symbol);
#endif
}
<|endoftext|> |
<commit_before>#include <cmath>
#include <chrono>
#include <numeric>
#include <unistd.h>
#include "openservorobot.h"
#include <yaml-cpp/yaml.h>
#define MEDIAN_WINDOW 20
using namespace openservo;
float scale_servo_to_joint(const MotorData& si, float ad_pos) {
float pos_deg = (ad_pos - si.AD_center) * si.factor;
return round(pos_deg * 100.0) / 100.0;
}
float scale_joint_to_servo(const MotorData& si, float pos) {
float pos_ad = (pos / si.factor) + si.AD_center;
return pos_ad;
}
OpenServoManipulator::OpenServoManipulator(const string& device,
const string& model_file, const string& calibration_file) {
read_rate = 30;
_state.state = MANIPULATORSTATETYPE_UNKNOWN;
_description.name = "i2c Robot Manipulator";
_description.version = 0.2f;
if (bus.open(device))
_state.state = MANIPULATORSTATETYPE_ACTIVE;
int num = bus.scan();
load_description(model_file, calibration_file);
if (num < servos.size())
throw ManipulatorException("Not enough servos detected.");
}
OpenServoManipulator::~OpenServoManipulator() {
}
bool parse_calibration(const string& filename, vector<MotorData>& servos) {
YAML::Node doc = YAML::LoadFile(filename);
servos.clear();
for (int i = 0; i < doc.size(); i++) {
MotorData d;
d.servo_id = doc[i]["id"].as<int>();
d.joint_id = -1;
d.AD_min = doc[i]["min"].as<int>();
d.AD_max = doc[i]["max"].as<int>();
d.AD_center = doc[i]["center"].as<int>();
d.factor = doc[i]["factor"].as<float>();
servos.push_back(d);
}
return true;
}
int OpenServoManipulator::load_description(const string& modelfile, const string& calibfile) {
if (!parse_description(modelfile, _description)) {
throw ManipulatorException("Unable to parse manipulator model description");
}
if (!parse_calibration(calibfile, servos)) {
throw ManipulatorException("Unable to parse manipulator calibration description");
}
_state.joints.resize(_description.joints.size());
int j = 0;
for (int i = 0; i < _description.joints.size(); i++) {
_state.joints[i].type = JOINTSTATETYPE_IDLE;
if (_description.joints[i].type == JOINTTYPE_FIXED)
continue;
if (j >= servos.size())
throw ManipulatorException("Not enough motors in calibration data.");
runtime_data.resize(runtime_data.size() + 1);
runtime_data[runtime_data.size() - 1].address = servos[j].servo_id;
servos[j].joint_id = i;
_description.joints[i].dh_min = scale_servo_to_joint(servos[j], servos[j].AD_min);
_description.joints[i].dh_max = scale_servo_to_joint(servos[j], servos[j].AD_max);
cout << "Verifying min-max data." << endl;
ServoHandler sv = bus.find(servos[j].servo_id);
if (sv->getMinSeek() != servos[j].AD_min || sv->getMaxSeek() != servos[j].AD_max) {
cout << "Detected incorrect parameters, writing min-max data to motor " << i << endl;
sv->unlock();
sv->set("seek.max", servos[j].AD_max);
sv->set("seek.min", servos[j].AD_min);
bus.update();
sv->registersCommit();
}
j++;
}
cout << "Joints: " << _description.joints.size() << " Motors: " << runtime_data.size() << endl;
if (j != servos.size())
throw ManipulatorException("Unassigned motors remaining.");
return 1;
}
int OpenServoManipulator::size() {
return _description.joints.size();
}
bool OpenServoManipulator::move(int joint, float position, float speed) {
int motor = joint_to_motor(joint);
if (motor < 0)
return false;
ServoHandler sv = bus.find(runtime_data[motor].address);
if (!sv)
return false;
float pos = ::round(scale_joint_to_servo(servos[motor], position));
sv->setSeekPosition((int)pos);
runtime_data[motor].goal_median.clear();
runtime_data[motor].goal_median.assign(MEDIAN_WINDOW, (int)pos);
return true;
}
#define MEDIAN_WINDOW 20
ManipulatorDescription OpenServoManipulator::describe() {
return _description;
}
ManipulatorState OpenServoManipulator::state() {
return _state;
}
int OpenServoManipulator::joint_to_motor(int j) {
if (j < 0 || j >= _description.joints.size()) return -1;
if (_description.joints[j].type == JOINTTYPE_FIXED) return -1;
int m = 0;
for (int i = 0; i < j; i++) {
if (_description.joints[i].type != JOINTTYPE_FIXED)
m++;
}
return m;
}
int OpenServoManipulator::motor_to_joint(int m) {
int mt = m;
int j = 0;
while (m > 0) {
j++; m--;
if (_description.joints[j].type == JOINTTYPE_FIXED)
j++;
}
return j;
}
bool OpenServoManipulator::process() {
if (!bus.update()) {
cout << bus.getLastError() << endl;
//return false;
}
// refresh state data
for (int q = 0; q < _description.joints.size(); q++) {
int motor = joint_to_motor(q);
if (motor < 0) continue;
ServoHandler sv = bus.find(runtime_data[motor].address);
if (!sv) continue;
runtime_data[motor].position_median.push_back(sv->getPosition());
runtime_data[motor].goal_median.push_back(sv->getSeekPosition());
if (runtime_data[motor].position_median.size() > MEDIAN_WINDOW)
runtime_data[motor].position_median.pop_front();
if (runtime_data[motor].goal_median.size() > MEDIAN_WINDOW)
runtime_data[motor].goal_median.pop_front();
vector<int> sorted_position(runtime_data[motor].position_median.begin(),
runtime_data[motor].position_median.end());
vector<int> sorted_goal(runtime_data[motor].goal_median.begin(),
runtime_data[motor].goal_median.end());
std::nth_element(sorted_position.begin(),
sorted_position.begin() + sorted_position.size() / 2, sorted_position.end());
float position = sorted_position[sorted_position.size() / 2];
std::nth_element(sorted_goal.begin(),
sorted_goal.begin() + sorted_goal.size() / 2, sorted_goal.end());
float goal = sorted_goal[sorted_goal.size() / 2];
_state.joints[q].position = scale_servo_to_joint(servos[motor], position);
_state.joints[q].goal = scale_servo_to_joint(servos[motor], goal);
_state.joints[q].speed = 1;
}
return true;
}
#define REFRESH_DELTA 20
using namespace std::chrono;
int main(int argc, char** argv) {
if (argc < 3) {
cerr << "Missing manipulator description and calibration file paths." << endl;
return -1;
}
string device;
if (argc > 3) {
device = string(argv[3]);
}
cout << "Starting OpenServo manipulator" << endl;
shared_ptr<OpenServoManipulator> manipulator =
shared_ptr<OpenServoManipulator>(new OpenServoManipulator(
device, string(argv[1]), string(argv[2])));
SharedClient client = echolib::connect();
ManipulatorManager manager(client, manipulator);
int duration = 0;
while (true) {
if (!echolib::wait(std::max(1, 20 - duration))) break;
steady_clock::time_point start = steady_clock::now();
manager.update();
if (!manipulator->process()) break;
duration = duration_cast<milliseconds>(steady_clock::now() - start).count();
}
exit(0);
}
<commit_msg>Moves will not block without this.<commit_after>#include <cmath>
#include <chrono>
#include <numeric>
#include <unistd.h>
#include "openservorobot.h"
#include <yaml-cpp/yaml.h>
#define MEDIAN_WINDOW 20
using namespace openservo;
float scale_servo_to_joint(const MotorData& si, float ad_pos) {
float pos_deg = (ad_pos - si.AD_center) * si.factor;
return round(pos_deg * 100.0) / 100.0;
}
float scale_joint_to_servo(const MotorData& si, float pos) {
float pos_ad = (pos / si.factor) + si.AD_center;
return pos_ad;
}
OpenServoManipulator::OpenServoManipulator(const string& device,
const string& model_file, const string& calibration_file) {
read_rate = 30;
_state.state = MANIPULATORSTATETYPE_UNKNOWN;
_description.name = "i2c Robot Manipulator";
_description.version = 0.2f;
if (bus.open(device))
_state.state = MANIPULATORSTATETYPE_ACTIVE;
int num = bus.scan();
load_description(model_file, calibration_file);
if (num < servos.size())
throw ManipulatorException("Not enough servos detected.");
}
OpenServoManipulator::~OpenServoManipulator() {
}
bool parse_calibration(const string& filename, vector<MotorData>& servos) {
YAML::Node doc = YAML::LoadFile(filename);
servos.clear();
for (int i = 0; i < doc.size(); i++) {
MotorData d;
d.servo_id = doc[i]["id"].as<int>();
d.joint_id = -1;
d.AD_min = doc[i]["min"].as<int>();
d.AD_max = doc[i]["max"].as<int>();
d.AD_center = doc[i]["center"].as<int>();
d.factor = doc[i]["factor"].as<float>();
servos.push_back(d);
}
return true;
}
int OpenServoManipulator::load_description(const string& modelfile, const string& calibfile) {
if (!parse_description(modelfile, _description)) {
throw ManipulatorException("Unable to parse manipulator model description");
}
if (!parse_calibration(calibfile, servos)) {
throw ManipulatorException("Unable to parse manipulator calibration description");
}
_state.joints.resize(_description.joints.size());
int j = 0;
for (int i = 0; i < _description.joints.size(); i++) {
_state.joints[i].type = JOINTSTATETYPE_IDLE;
if (_description.joints[i].type == JOINTTYPE_FIXED)
continue;
if (j >= servos.size())
throw ManipulatorException("Not enough motors in calibration data.");
runtime_data.resize(runtime_data.size() + 1);
runtime_data[runtime_data.size() - 1].address = servos[j].servo_id;
servos[j].joint_id = i;
_description.joints[i].dh_min = scale_servo_to_joint(servos[j], servos[j].AD_min);
_description.joints[i].dh_max = scale_servo_to_joint(servos[j], servos[j].AD_max);
cout << "Verifying min-max data." << endl;
ServoHandler sv = bus.find(servos[j].servo_id);
if (sv->getMinSeek() != servos[j].AD_min || sv->getMaxSeek() != servos[j].AD_max) {
cout << "Detected incorrect parameters, writing min-max data to motor " << i << endl;
sv->unlock();
sv->set("seek.max", servos[j].AD_max);
sv->set("seek.min", servos[j].AD_min);
bus.update();
sv->registersCommit();
}
j++;
}
cout << "Joints: " << _description.joints.size() << " Motors: " << runtime_data.size() << endl;
if (j != servos.size())
throw ManipulatorException("Unassigned motors remaining.");
return 1;
}
int OpenServoManipulator::size() {
return _description.joints.size();
}
bool OpenServoManipulator::move(int joint, float position, float speed) {
int motor = joint_to_motor(joint);
if (motor < 0)
return false;
ServoHandler sv = bus.find(runtime_data[motor].address);
if (!sv)
return false;
float pos = ::round(scale_joint_to_servo(servos[motor], position));
sv->setSeekPosition((int)pos);
runtime_data[motor].goal_median.clear();
runtime_data[motor].goal_median.assign(MEDIAN_WINDOW, (int)pos);
_state.joints[joint].goal = position;
return true;
}
#define MEDIAN_WINDOW 20
ManipulatorDescription OpenServoManipulator::describe() {
return _description;
}
ManipulatorState OpenServoManipulator::state() {
return _state;
}
int OpenServoManipulator::joint_to_motor(int j) {
if (j < 0 || j >= _description.joints.size()) return -1;
if (_description.joints[j].type == JOINTTYPE_FIXED) return -1;
int m = 0;
for (int i = 0; i < j; i++) {
if (_description.joints[i].type != JOINTTYPE_FIXED)
m++;
}
return m;
}
int OpenServoManipulator::motor_to_joint(int m) {
int mt = m;
int j = 0;
while (m > 0) {
j++; m--;
if (_description.joints[j].type == JOINTTYPE_FIXED)
j++;
}
return j;
}
bool OpenServoManipulator::process() {
if (!bus.update()) {
cout << bus.getLastError() << endl;
//return false;
}
// refresh state data
for (int q = 0; q < _description.joints.size(); q++) {
int motor = joint_to_motor(q);
if (motor < 0) continue;
ServoHandler sv = bus.find(runtime_data[motor].address);
if (!sv) continue;
runtime_data[motor].position_median.push_back(sv->getPosition());
runtime_data[motor].goal_median.push_back(sv->getSeekPosition());
if (runtime_data[motor].position_median.size() > MEDIAN_WINDOW)
runtime_data[motor].position_median.pop_front();
if (runtime_data[motor].goal_median.size() > MEDIAN_WINDOW)
runtime_data[motor].goal_median.pop_front();
vector<int> sorted_position(runtime_data[motor].position_median.begin(),
runtime_data[motor].position_median.end());
vector<int> sorted_goal(runtime_data[motor].goal_median.begin(),
runtime_data[motor].goal_median.end());
std::nth_element(sorted_position.begin(),
sorted_position.begin() + sorted_position.size() / 2, sorted_position.end());
float position = sorted_position[sorted_position.size() / 2];
std::nth_element(sorted_goal.begin(),
sorted_goal.begin() + sorted_goal.size() / 2, sorted_goal.end());
float goal = sorted_goal[sorted_goal.size() / 2];
_state.joints[q].position = scale_servo_to_joint(servos[motor], position);
_state.joints[q].goal = scale_servo_to_joint(servos[motor], goal);
_state.joints[q].speed = 1;
}
return true;
}
#define REFRESH_DELTA 20
using namespace std::chrono;
int main(int argc, char** argv) {
if (argc < 3) {
cerr << "Missing manipulator description and calibration file paths." << endl;
return -1;
}
string device;
if (argc > 3) {
device = string(argv[3]);
}
cout << "Starting OpenServo manipulator" << endl;
shared_ptr<OpenServoManipulator> manipulator =
shared_ptr<OpenServoManipulator>(new OpenServoManipulator(
device, string(argv[1]), string(argv[2])));
SharedClient client = echolib::connect();
ManipulatorManager manager(client, manipulator);
int duration = 0;
while (true) {
if (!echolib::wait(std::max(1, 20 - duration))) break;
steady_clock::time_point start = steady_clock::now();
manager.update();
if (!manipulator->process()) break;
duration = duration_cast<milliseconds>(steady_clock::now() - start).count();
}
exit(0);
}
<|endoftext|> |
<commit_before>//===----------------------------------------------------------------------===//
//
// Peloton
//
// rule.h
//
// Identification: src/optimizer/rule.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/rule_impls.h"
#include "optimizer/group_expression.h"
namespace peloton {
namespace optimizer {
int Rule::Promise(GroupExpression *group_expr, OptimizeContext *context) const {
(void)context;
auto root_type = match_pattern->Type();
// This rule is not applicable
if (root_type != OpType::Leaf && root_type != group_expr->Op().GetType()) {
return 0;
}
if (IsPhysical()) return PHYS_PROMISE;
return LOG_PROMISE;
}
RuleSet::RuleSet() {
AddTransformationRule(new InnerJoinCommutativity());
AddImplementationRule(new LogicalDeleteToPhysical());
AddImplementationRule(new LogicalUpdateToPhysical());
AddImplementationRule(new LogicalInsertToPhysical());
AddImplementationRule(new LogicalInsertSelectToPhysical());
AddImplementationRule(new LogicalGroupByToHashGroupBy());
AddImplementationRule(new LogicalAggregateToPhysical());
AddImplementationRule(new GetToDummyScan());
AddImplementationRule(new GetToSeqScan());
AddImplementationRule(new GetToIndexScan());
AddImplementationRule(new LogicalQueryDerivedGetToPhysical());
AddImplementationRule(new InnerJoinToInnerNLJoin());
AddImplementationRule(new InnerJoinToInnerHashJoin());
AddImplementationRule(new ImplementDistinct());
AddImplementationRule(new ImplementLimit());
AddRewriteRule(RewriteRuleSetName::PREDICATE_PUSH_DOWN, new PushFilterThroughJoin());
AddRewriteRule(RewriteRuleSetName::PREDICATE_PUSH_DOWN, new CombineConsecutiveFilter());
AddRewriteRule(RewriteRuleSetName::PREDICATE_PUSH_DOWN, new EmbedFilterIntoGet());
AddRewriteRule(RewriteRuleSetName::UNNEST_SUBQUERY, new PullFilterThroughMarkJoin());
AddRewriteRule(RewriteRuleSetName::UNNEST_SUBQUERY, new MarkJoinInnerJoinToInnerJoin());
AddRewriteRule(RewriteRuleSetName::UNNEST_SUBQUERY, new MarkJoinGetToInnerJoin());
}
} // namespace optimizer
} // namespace peloton
<commit_msg>Added rule to ruleset<commit_after>//===----------------------------------------------------------------------===//
//
// Peloton
//
// rule.h
//
// Identification: src/optimizer/rule.cpp
//
// Copyright (c) 2015-16, Carnegie Mellon University Database Group
//
//===----------------------------------------------------------------------===//
#include "optimizer/rule_impls.h"
#include "optimizer/group_expression.h"
namespace peloton {
namespace optimizer {
int Rule::Promise(GroupExpression *group_expr, OptimizeContext *context) const {
(void)context;
auto root_type = match_pattern->Type();
// This rule is not applicable
if (root_type != OpType::Leaf && root_type != group_expr->Op().GetType()) {
return 0;
}
if (IsPhysical()) return PHYS_PROMISE;
return LOG_PROMISE;
}
RuleSet::RuleSet() {
AddTransformationRule(new InnerJoinCommutativity());
AddTransformationRule(new InnerJoinAssociativity());
AddImplementationRule(new LogicalDeleteToPhysical());
AddImplementationRule(new LogicalUpdateToPhysical());
AddImplementationRule(new LogicalInsertToPhysical());
AddImplementationRule(new LogicalInsertSelectToPhysical());
AddImplementationRule(new LogicalGroupByToHashGroupBy());
AddImplementationRule(new LogicalAggregateToPhysical());
AddImplementationRule(new GetToDummyScan());
AddImplementationRule(new GetToSeqScan());
AddImplementationRule(new GetToIndexScan());
AddImplementationRule(new LogicalQueryDerivedGetToPhysical());
AddImplementationRule(new InnerJoinToInnerNLJoin());
AddImplementationRule(new InnerJoinToInnerHashJoin());
AddImplementationRule(new ImplementDistinct());
AddImplementationRule(new ImplementLimit());
AddRewriteRule(RewriteRuleSetName::PREDICATE_PUSH_DOWN, new PushFilterThroughJoin());
AddRewriteRule(RewriteRuleSetName::PREDICATE_PUSH_DOWN, new CombineConsecutiveFilter());
AddRewriteRule(RewriteRuleSetName::PREDICATE_PUSH_DOWN, new EmbedFilterIntoGet());
AddRewriteRule(RewriteRuleSetName::UNNEST_SUBQUERY, new PullFilterThroughMarkJoin());
AddRewriteRule(RewriteRuleSetName::UNNEST_SUBQUERY, new MarkJoinInnerJoinToInnerJoin());
AddRewriteRule(RewriteRuleSetName::UNNEST_SUBQUERY, new MarkJoinGetToInnerJoin());
}
} // namespace optimizer
} // namespace peloton
<|endoftext|> |
<commit_before>//------------------------------------------------------------------------------
// oryol-shdc
//------------------------------------------------------------------------------
#include "ExportUtil/CmdLineArgs.h"
#include "ExportUtil/Log.h"
#include "spirv_hlsl.hpp"
#include "spirv_msl.hpp"
#include "pystring.h"
#include "cJSON.h"
#include <stdio.h>
using namespace OryolTools;
using namespace spv;
using namespace spirv_cross;
using namespace std;
//------------------------------------------------------------------------------
vector<uint32_t> read_spirv_file(const string& path) {
FILE* fp = fopen(path.c_str(), "rb");
if (!fp) {
Log::Fatal("Failed to open SPIRV file '%s'\n", path.c_str());
}
fseek(fp, 0, SEEK_END);
long len = ftell(fp) / sizeof(uint32_t);
fseek(fp, 0, SEEK_SET);
vector<uint32_t> spirv(len);
if (fread(spirv.data(), sizeof(uint32_t), len, fp) != size_t(len)) {
Log::Fatal("Error reading SPIRV file '%s'\n", path.c_str());
}
fclose(fp);
return spirv;
}
//------------------------------------------------------------------------------
void write_source_file(const string& path, const string& content) {
FILE* fp = fopen(path.c_str(), "w");
if (!fp) {
Log::Fatal("Failed to open '%s' for writing\n", path.c_str());
}
fwrite(content.c_str(), 1, content.length(), fp);
fclose(fp);
}
//------------------------------------------------------------------------------
const char* type_to_oryol_uniform_type(const SPIRType& type) {
if (type.basetype == SPIRType::Float) {
if (type.columns == 1) {
// scalar or vec
switch (type.vecsize) {
case 1: return "UniformType::Float";
case 2: return "UniformType::Vec2";
case 3: return "UniformType::Vec3";
case 4: return "UniformType::Vec4";
}
}
else {
// a matrix
if ((type.vecsize == 2) && (type.columns == 2)) {
return "UniformType::Mat2";
}
else if ((type.vecsize == 3) && (type.columns == 3)) {
return "UniformType::Mat3";
}
else if ((type.vecsize == 4) && (type.columns == 4)) {
return "UniformType::Mat4";
}
}
}
else if (type.basetype == SPIRType::Int) {
return "UniformType::Int";
}
else if (type.basetype == SPIRType::Boolean) {
return "UniformType::Bool";
}
Log::Fatal("Invalid member type in uniform block! (expected: float, vec2, vec3, vec4, mat2, mat3, mat4)\n");
return nullptr;
}
//------------------------------------------------------------------------------
const char* type_to_oryol_vertex_format(const SPIRType& type) {
if (type.basetype == SPIRType::Float && type.columns == 1) {
switch (type.vecsize) {
case 1: return "VertexFormat::Float";
case 2: return "VertexFormat::Float2";
case 3: return "VertexFormat::Float3";
case 4: return "VertexFormat::Float4";
}
}
Log::Fatal("Invalid vertex attribute type! (expected: float, vec2, vec3, vec4)\n");
return nullptr;
}
//------------------------------------------------------------------------------
cJSON* extract_resource_info(Compiler* compiler) {
cJSON* root = cJSON_CreateObject();
// shader stage
const char* stage_str = nullptr;
switch (compiler->get_execution_model()) {
case ExecutionModelVertex: stage_str = "ShaderStage::VS"; break;
case ExecutionModelFragment: stage_str = "ShaderStage::FS"; break;
default: break;
}
if (stage_str) {
cJSON_AddItemToObject(root, "stage", cJSON_CreateString(stage_str));
}
else {
Log::Fatal("only vertex- or fragment-shaders allowed!\n");
}
// uniform blocks
ShaderResources res = compiler->get_shader_resources();
if (res.uniform_buffers.size() > 0) {
cJSON* ub_array = cJSON_CreateArray();
cJSON_AddItemToObject(root, "uniform_blocks", ub_array);
for (const Resource& ub_res : res.uniform_buffers) {
const SPIRType& ub_type = compiler->get_type(ub_res.base_type_id);
cJSON* ub = cJSON_CreateObject();
cJSON_AddItemToArray(ub_array, ub);
cJSON_AddItemToObject(ub, "type", cJSON_CreateString(ub_res.name.c_str()));
cJSON_AddItemToObject(ub, "name", cJSON_CreateString(compiler->get_name(ub_res.id).c_str()));
cJSON* ub_members = cJSON_CreateArray();
cJSON_AddItemToObject(ub, "members", ub_members);
for (int m_index = 0; m_index < int(ub_type.member_types.size()); m_index++) {
cJSON* ub_member = cJSON_CreateObject();
cJSON_AddItemToArray(ub_members, ub_member);
string m_name = compiler->get_member_name(ub_res.base_type_id, m_index);
const SPIRType& m_type = compiler->get_type(ub_type.member_types[m_index]);
const char* m_type_str = type_to_oryol_uniform_type(m_type);
cJSON_AddItemToObject(ub_member, "name", cJSON_CreateString(m_name.c_str()));
cJSON_AddItemToObject(ub_member, "type", cJSON_CreateString(m_type_str));
int dim = 1;
if (m_type.array.size() > 0) {
dim = m_type.array[0];
}
cJSON_AddItemToObject(ub_member, "dim", cJSON_CreateNumber(dim));
}
}
}
// textures
if (res.sampled_images.size() > 0) {
cJSON* tex_array = cJSON_CreateArray();
cJSON_AddItemToObject(root, "textures", tex_array);
for (const Resource& img_res : res.sampled_images) {
const SPIRType& img_type = compiler->get_type(img_res.type_id);
cJSON* tex = cJSON_CreateObject();
cJSON_AddItemToArray(tex_array, tex);
const char* tex_type_str = nullptr;
if (img_type.image.arrayed) {
if (img_type.image.dim == Dim2D) {
tex_type_str = "TextureType::TextureArray";
}
}
else {
switch (img_type.image.dim) {
case Dim2D: tex_type_str = "TextureType::Texture2D"; break;
case DimCube: tex_type_str = "TextureType::TextureCube"; break;
case Dim3D: tex_type_str = "TextureType::Texture3D"; break;
default: break;
}
}
if (!tex_type_str) {
Log::Fatal("Invalid texture type! (expected: 2D, Cube, 3D or 2D-array)\n");
}
cJSON_AddItemToObject(tex, "name", cJSON_CreateString(img_res.name.c_str()));
cJSON_AddItemToObject(tex, "type", cJSON_CreateString(tex_type_str));
}
}
// vertex attributes
if (compiler->get_execution_model() == ExecutionModelVertex) {
cJSON* attr_array = cJSON_CreateArray();
cJSON_AddItemToObject(root, "inputs", attr_array);
for (const Resource& input : res.stage_inputs) {
cJSON* attr = cJSON_CreateObject();
cJSON_AddItemToArray(attr_array, attr);
const SPIRType& type = compiler->get_type(input.base_type_id);
const char* attr_type_str = type_to_oryol_vertex_format(type);
uint32_t loc = compiler->get_decoration(input.id, DecorationLocation);
cJSON_AddItemToObject(attr, "name", cJSON_CreateString(input.name.c_str()));
cJSON_AddItemToObject(attr, "type", cJSON_CreateString(attr_type_str));
cJSON_AddItemToObject(attr, "slot", cJSON_CreateNumber(loc));
}
}
return root;
}
//------------------------------------------------------------------------------
void fix_vertex_attr_locations(Compiler* compiler) {
if (compiler->get_execution_model() == ExecutionModelVertex) {
ShaderResources res = compiler->get_shader_resources();
for (const auto& input : res.stage_inputs) {
int loc = -1;
if (input.name == "position") loc = 0;
else if (input.name == "normal") loc = 1;
else if (input.name == "texcoord0") loc = 2;
else if (input.name == "texcoord1") loc = 3;
else if (input.name == "texcoord2") loc = 4;
else if (input.name == "texcoord3") loc = 5;
else if (input.name == "tangent") loc = 6;
else if (input.name == "binormal") loc = 7;
else if (input.name == "weights") loc = 8;
else if (input.name == "indices") loc = 9;
else if (input.name == "color0") loc = 10;
else if (input.name == "color1") loc = 11;
else if (input.name == "instance0") loc = 12;
else if (input.name == "instance1") loc = 13;
else if (input.name == "instance2") loc = 14;
else if (input.name == "instance3") loc = 15;
if (-1 != loc) {
compiler->set_decoration(input.id, DecorationLocation, (uint32_t)loc);
}
}
}
}
//------------------------------------------------------------------------------
void to_reflection_json(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
fix_vertex_attr_locations(&compiler);
cJSON* json = extract_resource_info(&compiler);
char* json_raw_str = cJSON_Print(json);
string json_str(json_raw_str);
std::free(json_raw_str);
cJSON_Delete(json);
write_source_file(base_path + ".json", json_str);
}
//------------------------------------------------------------------------------
void to_glsl_100(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 100;
opts.es = true;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL v100 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsl100.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_glsl_120(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 120;
opts.es = false;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL v120 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsl120.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_glsl_es3(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 300;
opts.es = true;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL es3 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsles3.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_glsl_330(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 330;
opts.es = false;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL v330 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsl330.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_hlsl_sm5(const vector<uint32_t>& spirv, const string& base_path) {
CompilerHLSL compiler(spirv);
auto opts = compiler.get_options();
opts.shader_model = 50;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile HLSL5 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".hlsl", src);
}
}
//------------------------------------------------------------------------------
void to_mlsl(const vector<uint32_t>& spirv, const string& base_path) {
CompilerMSL compiler(spirv);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile MetalSL source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".metal", src);
}
}
//------------------------------------------------------------------------------
int main(int argc, const char** argv) {
CmdLineArgs args;
args.AddBool("-help", "show help");
args.AddString("-spirv", "SPIR-V input file", "");
if (!args.Parse(argc, argv)) {
Log::Warn("Failed to parse args!\n");
return 10;
}
if (args.HasArg("-help")) {
Log::Info("Oryol SPIR-V to GLSL/HLSL/MSL cross-compiler\n"
"Based on SPIRV-Cross: https://github.com/KhronosGroup/SPIRV-Cross\n");
args.ShowHelp();
return 0;
}
string spirv_path = args.GetString("-spirv");
if (spirv_path.empty()) {
Log::Fatal("-spirv arg expected");
}
// load SPIRV byte code
auto spirv = read_spirv_file(spirv_path);
// ...translate and write to output files...
string base_path, ext;
pystring::os::path::splitext(base_path, ext, spirv_path);
to_reflection_json(spirv, base_path);
to_glsl_100(spirv, base_path);
to_glsl_120(spirv, base_path);
to_glsl_es3(spirv, base_path);
to_glsl_330(spirv, base_path);
// to_hlsl_sm5(spirv, base_path);
// to_mlsl(spirv, base_path);
return 0;
}
<commit_msg>shdc: fixed an error msg<commit_after>//------------------------------------------------------------------------------
// oryol-shdc
//------------------------------------------------------------------------------
#include "ExportUtil/CmdLineArgs.h"
#include "ExportUtil/Log.h"
#include "spirv_hlsl.hpp"
#include "spirv_msl.hpp"
#include "pystring.h"
#include "cJSON.h"
#include <stdio.h>
using namespace OryolTools;
using namespace spv;
using namespace spirv_cross;
using namespace std;
//------------------------------------------------------------------------------
vector<uint32_t> read_spirv_file(const string& path) {
FILE* fp = fopen(path.c_str(), "rb");
if (!fp) {
Log::Fatal("Failed to open SPIRV file '%s'\n", path.c_str());
}
fseek(fp, 0, SEEK_END);
long len = ftell(fp) / sizeof(uint32_t);
fseek(fp, 0, SEEK_SET);
vector<uint32_t> spirv(len);
if (fread(spirv.data(), sizeof(uint32_t), len, fp) != size_t(len)) {
Log::Fatal("Error reading SPIRV file '%s'\n", path.c_str());
}
fclose(fp);
return spirv;
}
//------------------------------------------------------------------------------
void write_source_file(const string& path, const string& content) {
FILE* fp = fopen(path.c_str(), "w");
if (!fp) {
Log::Fatal("Failed to open '%s' for writing\n", path.c_str());
}
fwrite(content.c_str(), 1, content.length(), fp);
fclose(fp);
}
//------------------------------------------------------------------------------
const char* type_to_oryol_uniform_type(const SPIRType& type) {
if (type.basetype == SPIRType::Float) {
if (type.columns == 1) {
// scalar or vec
switch (type.vecsize) {
case 1: return "UniformType::Float";
case 2: return "UniformType::Vec2";
case 3: return "UniformType::Vec3";
case 4: return "UniformType::Vec4";
}
}
else {
// a matrix
if ((type.vecsize == 2) && (type.columns == 2)) {
return "UniformType::Mat2";
}
else if ((type.vecsize == 3) && (type.columns == 3)) {
return "UniformType::Mat3";
}
else if ((type.vecsize == 4) && (type.columns == 4)) {
return "UniformType::Mat4";
}
}
}
else if (type.basetype == SPIRType::Int) {
return "UniformType::Int";
}
else if (type.basetype == SPIRType::Boolean) {
return "UniformType::Bool";
}
Log::Fatal("Invalid member type in uniform block! (expected: float, vec2, vec3, vec4, mat2, mat3, mat4, int, bool)\n");
return nullptr;
}
//------------------------------------------------------------------------------
const char* type_to_oryol_vertex_format(const SPIRType& type) {
if (type.basetype == SPIRType::Float && type.columns == 1) {
switch (type.vecsize) {
case 1: return "VertexFormat::Float";
case 2: return "VertexFormat::Float2";
case 3: return "VertexFormat::Float3";
case 4: return "VertexFormat::Float4";
}
}
Log::Fatal("Invalid vertex attribute type! (expected: float, vec2, vec3, vec4)\n");
return nullptr;
}
//------------------------------------------------------------------------------
cJSON* extract_resource_info(Compiler* compiler) {
cJSON* root = cJSON_CreateObject();
// shader stage
const char* stage_str = nullptr;
switch (compiler->get_execution_model()) {
case ExecutionModelVertex: stage_str = "ShaderStage::VS"; break;
case ExecutionModelFragment: stage_str = "ShaderStage::FS"; break;
default: break;
}
if (stage_str) {
cJSON_AddItemToObject(root, "stage", cJSON_CreateString(stage_str));
}
else {
Log::Fatal("only vertex- or fragment-shaders allowed!\n");
}
// uniform blocks
ShaderResources res = compiler->get_shader_resources();
if (res.uniform_buffers.size() > 0) {
cJSON* ub_array = cJSON_CreateArray();
cJSON_AddItemToObject(root, "uniform_blocks", ub_array);
for (const Resource& ub_res : res.uniform_buffers) {
const SPIRType& ub_type = compiler->get_type(ub_res.base_type_id);
cJSON* ub = cJSON_CreateObject();
cJSON_AddItemToArray(ub_array, ub);
cJSON_AddItemToObject(ub, "type", cJSON_CreateString(ub_res.name.c_str()));
cJSON_AddItemToObject(ub, "name", cJSON_CreateString(compiler->get_name(ub_res.id).c_str()));
cJSON* ub_members = cJSON_CreateArray();
cJSON_AddItemToObject(ub, "members", ub_members);
for (int m_index = 0; m_index < int(ub_type.member_types.size()); m_index++) {
cJSON* ub_member = cJSON_CreateObject();
cJSON_AddItemToArray(ub_members, ub_member);
string m_name = compiler->get_member_name(ub_res.base_type_id, m_index);
const SPIRType& m_type = compiler->get_type(ub_type.member_types[m_index]);
const char* m_type_str = type_to_oryol_uniform_type(m_type);
cJSON_AddItemToObject(ub_member, "name", cJSON_CreateString(m_name.c_str()));
cJSON_AddItemToObject(ub_member, "type", cJSON_CreateString(m_type_str));
int dim = 1;
if (m_type.array.size() > 0) {
dim = m_type.array[0];
}
cJSON_AddItemToObject(ub_member, "dim", cJSON_CreateNumber(dim));
}
}
}
// textures
if (res.sampled_images.size() > 0) {
cJSON* tex_array = cJSON_CreateArray();
cJSON_AddItemToObject(root, "textures", tex_array);
for (const Resource& img_res : res.sampled_images) {
const SPIRType& img_type = compiler->get_type(img_res.type_id);
cJSON* tex = cJSON_CreateObject();
cJSON_AddItemToArray(tex_array, tex);
const char* tex_type_str = nullptr;
if (img_type.image.arrayed) {
if (img_type.image.dim == Dim2D) {
tex_type_str = "TextureType::TextureArray";
}
}
else {
switch (img_type.image.dim) {
case Dim2D: tex_type_str = "TextureType::Texture2D"; break;
case DimCube: tex_type_str = "TextureType::TextureCube"; break;
case Dim3D: tex_type_str = "TextureType::Texture3D"; break;
default: break;
}
}
if (!tex_type_str) {
Log::Fatal("Invalid texture type! (expected: 2D, Cube, 3D or 2D-array)\n");
}
cJSON_AddItemToObject(tex, "name", cJSON_CreateString(img_res.name.c_str()));
cJSON_AddItemToObject(tex, "type", cJSON_CreateString(tex_type_str));
}
}
// vertex attributes
if (compiler->get_execution_model() == ExecutionModelVertex) {
cJSON* attr_array = cJSON_CreateArray();
cJSON_AddItemToObject(root, "inputs", attr_array);
for (const Resource& input : res.stage_inputs) {
cJSON* attr = cJSON_CreateObject();
cJSON_AddItemToArray(attr_array, attr);
const SPIRType& type = compiler->get_type(input.base_type_id);
const char* attr_type_str = type_to_oryol_vertex_format(type);
uint32_t loc = compiler->get_decoration(input.id, DecorationLocation);
cJSON_AddItemToObject(attr, "name", cJSON_CreateString(input.name.c_str()));
cJSON_AddItemToObject(attr, "type", cJSON_CreateString(attr_type_str));
cJSON_AddItemToObject(attr, "slot", cJSON_CreateNumber(loc));
}
}
return root;
}
//------------------------------------------------------------------------------
void fix_vertex_attr_locations(Compiler* compiler) {
if (compiler->get_execution_model() == ExecutionModelVertex) {
ShaderResources res = compiler->get_shader_resources();
for (const auto& input : res.stage_inputs) {
int loc = -1;
if (input.name == "position") loc = 0;
else if (input.name == "normal") loc = 1;
else if (input.name == "texcoord0") loc = 2;
else if (input.name == "texcoord1") loc = 3;
else if (input.name == "texcoord2") loc = 4;
else if (input.name == "texcoord3") loc = 5;
else if (input.name == "tangent") loc = 6;
else if (input.name == "binormal") loc = 7;
else if (input.name == "weights") loc = 8;
else if (input.name == "indices") loc = 9;
else if (input.name == "color0") loc = 10;
else if (input.name == "color1") loc = 11;
else if (input.name == "instance0") loc = 12;
else if (input.name == "instance1") loc = 13;
else if (input.name == "instance2") loc = 14;
else if (input.name == "instance3") loc = 15;
if (-1 != loc) {
compiler->set_decoration(input.id, DecorationLocation, (uint32_t)loc);
}
}
}
}
//------------------------------------------------------------------------------
void to_reflection_json(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
fix_vertex_attr_locations(&compiler);
cJSON* json = extract_resource_info(&compiler);
char* json_raw_str = cJSON_Print(json);
string json_str(json_raw_str);
std::free(json_raw_str);
cJSON_Delete(json);
write_source_file(base_path + ".json", json_str);
}
//------------------------------------------------------------------------------
void to_glsl_100(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 100;
opts.es = true;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL v100 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsl100.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_glsl_120(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 120;
opts.es = false;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL v120 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsl120.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_glsl_es3(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 300;
opts.es = true;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL es3 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsles3.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_glsl_330(const vector<uint32_t>& spirv, const string& base_path) {
CompilerGLSL compiler(spirv);
auto opts = compiler.get_options();
opts.version = 330;
opts.es = false;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile GLSL v330 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".glsl330.glsl", src);
}
}
//------------------------------------------------------------------------------
void to_hlsl_sm5(const vector<uint32_t>& spirv, const string& base_path) {
CompilerHLSL compiler(spirv);
auto opts = compiler.get_options();
opts.shader_model = 50;
compiler.set_options(opts);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile HLSL5 source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".hlsl", src);
}
}
//------------------------------------------------------------------------------
void to_mlsl(const vector<uint32_t>& spirv, const string& base_path) {
CompilerMSL compiler(spirv);
fix_vertex_attr_locations(&compiler);
string src = compiler.compile();
if (src.empty()) {
Log::Fatal("Failed to compile MetalSL source for '%s'!\n", base_path.c_str());
}
else {
write_source_file(base_path + ".metal", src);
}
}
//------------------------------------------------------------------------------
int main(int argc, const char** argv) {
CmdLineArgs args;
args.AddBool("-help", "show help");
args.AddString("-spirv", "SPIR-V input file", "");
if (!args.Parse(argc, argv)) {
Log::Warn("Failed to parse args!\n");
return 10;
}
if (args.HasArg("-help")) {
Log::Info("Oryol SPIR-V to GLSL/HLSL/MSL cross-compiler\n"
"Based on SPIRV-Cross: https://github.com/KhronosGroup/SPIRV-Cross\n");
args.ShowHelp();
return 0;
}
string spirv_path = args.GetString("-spirv");
if (spirv_path.empty()) {
Log::Fatal("-spirv arg expected");
}
// load SPIRV byte code
auto spirv = read_spirv_file(spirv_path);
// ...translate and write to output files...
string base_path, ext;
pystring::os::path::splitext(base_path, ext, spirv_path);
to_reflection_json(spirv, base_path);
to_glsl_100(spirv, base_path);
to_glsl_120(spirv, base_path);
to_glsl_es3(spirv, base_path);
to_glsl_330(spirv, base_path);
// to_hlsl_sm5(spirv, base_path);
// to_mlsl(spirv, base_path);
return 0;
}
<|endoftext|> |
<commit_before>/* author: dongchangzhang */
/* time: Sat 01 Apr 2017 12:10:03 AM CST */
#include "grammar.h"
#include "error.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
Grammar::Grammar(std::string grammarf)
{
int code;
bool first_which = true;
std::ifstream in(grammarf);
if (!in) {
print_error(NO_GRAMMAR);
exit(1);
}
std::string which;
std::string start, comment, line;
std::vector<Token> ptmp;
std::vector<std::vector<Token> > productions;
while (std::getline(in, line)) {
std::istringstream is(line);
is >> start;
if (start == "->") {
is >> which;
if (first_which) {
start_state = which;
first_which = false;
}
} else if (start == "#") {
comment = line;
} else if (start != "") {
ptmp.clear();
while (true) {
if (start == "identity") {
// id
Token token(ID, start);
ptmp.push_back(token);
} else if (start == "value") {
// value
Token token(VALUE, start);
ptmp.push_back(token);
} else if (start == "null") {
Token token;
ptmp.push_back(token);
} else if ((code = get_code(start)) != ID) {
// key word, separator or operator
Token token(code, start);
ptmp.push_back(token);
} else {
// state
Token token(start);
ptmp.push_back(token);
}
if (!(is >> start))
break;
}
Token parent(which);
if (grammar.find(parent) != grammar.end()) {
grammar[parent].push_back(ptmp);
} else {
productions.clear();
productions.push_back(ptmp);
grammar[parent] = productions;
}
}
}
}
void Grammar::check_grammar()
{
for (auto& p : grammar) {
// which
std::cout << (p.first).get_state() << std::endl;
for (auto& v1 : p.second) {
// production
for (auto e : v1) {
std::cout << e.get_token() << " " << e.get_attr() << " ";
}
std::cout << std::endl;
}
std::cout << " ---------- " << std::endl;
}
}
std::vector<Token> Grammar::get_production(const std::string& which, size_t id) const
{
Token parent(which);
if (grammar.find(parent) != grammar.end() && grammar.at(parent).size() > id) {
return grammar.at(parent).at(id);
} else {
std::cout << "not find grammar 1 at grammar.cpp : "
<< which << " " << id << std::endl;
std::vector<Token> tmp;
return tmp;
}
}
std::vector<std::vector<Token> > Grammar::get_production(const Token& token) const
{
if (grammar.find(token) != grammar.end()) {
return grammar.at(token);
} else {
std::cout << "not find grammar 2 at grammar.cpp : "
<< token.get_state() << std::endl;
std::vector<std::vector<Token> > tmp;
return tmp;
}
}
<commit_msg>fix bugs<commit_after>/* author: dongchangzhang */
/* time: Sat 01 Apr 2017 12:10:03 AM CST */
#include "grammar.h"
#include "error.h"
#include <algorithm>
#include <fstream>
#include <iostream>
#include <sstream>
Grammar::Grammar(std::string grammarf)
{
int code;
bool first_which = true;
std::ifstream in(grammarf);
if (!in) {
print_error(NO_GRAMMAR);
exit(1);
}
std::string which;
std::string start, comment, line;
std::vector<Token> ptmp;
std::vector<std::vector<Token> > productions;
while (std::getline(in, line)) {
std::istringstream is(line);
is >> start;
if (start == "")
continue;
if (start == "->") {
is >> which;
if (first_which) {
start_state = which;
first_which = false;
}
} else if (start == "#") {
comment = line;
} else if (start != "") {
ptmp.clear();
while (true) {
if (start == "identity") {
// id
Token token(ID, start);
ptmp.push_back(token);
} else if (start == "value") {
// value
Token token(VALUE, start);
ptmp.push_back(token);
} else if (start == "null") {
Token token;
ptmp.push_back(token);
} else if ((code = get_code(start)) != ID) {
// key word, separator or operator
Token token(code, start);
ptmp.push_back(token);
} else {
// state
Token token(start);
ptmp.push_back(token);
}
if (!(is >> start))
break;
}
Token parent(which);
if (grammar.find(parent) != grammar.end()) {
grammar[parent].push_back(ptmp);
} else {
productions.clear();
productions.push_back(ptmp);
grammar[parent] = productions;
}
}
}
}
void Grammar::check_grammar()
{
for (auto& p : grammar) {
// which
std::cout << (p.first).get_state() << std::endl;
for (auto& v1 : p.second) {
// production
for (auto e : v1) {
std::cout << e.get_token() << " " << e.get_attr() << " ";
}
std::cout << std::endl;
}
std::cout << " ---------- " << std::endl;
}
}
std::vector<Token> Grammar::get_production(const std::string& which, size_t id) const
{
Token parent(which);
if (grammar.find(parent) != grammar.end() && grammar.at(parent).size() > id) {
return grammar.at(parent).at(id);
} else {
std::cout << "not find grammar 1 at grammar.cpp : "
<< which << " " << id << std::endl;
std::vector<Token> tmp;
return tmp;
}
}
std::vector<std::vector<Token> > Grammar::get_production(const Token& token) const
{
if (grammar.find(token) != grammar.end()) {
return grammar.at(token);
} else {
std::cout << "not find grammar 2 at grammar.cpp : "
<< token.get_state() << std::endl;
std::vector<std::vector<Token> > tmp;
return tmp;
}
}
<|endoftext|> |
<commit_before>#include "tarch/logging/Log.h"
#include "tarch/tests/TestCaseRegistry.h"
#include "tarch/logging/CommandLineLogger.h"
#include "tarch/parallel/Node.h"
#include "peano/peano.h"
#include "peanoclaw/runners/Runner.h"
tarch::logging::Log _log("");
int main(int argc, char** argv) {
peano::fillLookupTables();
int parallelSetup = peano::initParallelEnvironment(&argc,&argv);
if ( parallelSetup!=0 ) {
#ifdef Parallel
// Please do not use the logging if MPI doesn't work properly.
std::cerr << "mpi initialisation wasn't successful. Application shut down" << std::endl;
#else
_log.error("main()", "mpi initialisation wasn't successful. Application shut down");
#endif
return parallelSetup;
}
int sharedMemorySetup = peano::initSharedMemoryEnvironment();
if (sharedMemorySetup!=0) {
logError("main()", "shared memory initialisation wasn't successful. Application shut down");
return sharedMemorySetup;
}
int programExitCode = 0;
// @todo Please insert your code here and reset programExitCode
// if something goes wrong.
// ============================================================
// Configure the output
tarch::logging::CommandLineLogger::getInstance().clearFilterList();
tarch::logging::CommandLineLogger::getInstance().addFilterListEntry( ::tarch::logging::CommandLineLogger::FilterListEntry( "info", false ) );
tarch::logging::CommandLineLogger::getInstance().addFilterListEntry( ::tarch::logging::CommandLineLogger::FilterListEntry( "debug", true ) );
// tarch::logging::CommandLineLogger::getInstance().setLogFormat( ... please consult source code documentation );
// Runs the unit tests
tarch::tests::TestCaseRegistry::getInstance().getTestCaseCollection().run();
programExitCode = tarch::tests::TestCaseRegistry::getInstance().getTestCaseCollection().getNumberOfErrors();
// Runs the integration tests
//if (programExitCode==0) {
// tarch::tests::TestCaseRegistry::getInstance().getIntegrationTestCaseCollection().run();
// programExitCode = tarch::tests::TestCaseRegistry::getInstance().getIntegrationTestCaseCollection().getNumberOfErrors();
//}
// dummy call to runner
if (programExitCode==0) {
tarch::logging::CommandLineLogger::getInstance().addFilterListEntry( ::tarch::logging::CommandLineLogger::FilterListEntry( "debug", -1, "peanoclaw", false ) );
peanoclaw::runners::Runner runner;
programExitCode = runner.run();
}
// ============================================================
if (programExitCode==0) {
#ifdef Parallel
if (tarch::parallel::Node::getInstance().isGlobalMaster()) {
logInfo( "main()", "Peano terminates successfully" );
}
#else
logInfo( "main()", "Peano terminates successfully" );
#endif
}
else {
logInfo( "main()", "quit with error code " << programExitCode );
}
peano::shutdownParallelEnvironment();
peano::shutdownSharedMemoryEnvironment();
return programExitCode;
}
<commit_msg>deleted main.cpp<commit_after><|endoftext|> |
<commit_before>static const char rcsid[] = "$Id: Clock.cpp,v 1.5 2001-04-10 14:39:09 bastiaan Exp $";
/*
* See the COPYING file for the terms of usage and distribution.
*/
#include <stdlib.h>
#include <sys/time.h> // for struct timeval
#ifdef __osf__
# include <machine/builtins.h> // for __RPCC()
#elif __linux__
# include <asm/msr.h> // for rdtscl()
#endif
#include <iostream>
#include "Clock.hh"
namespace
{
const usec_t UsecPerSec = INT64_CONSTANT(1000000);
}
bool Clock::UsingCPU = ::getenv("CLOCK_USE_CPU") ? true : false;
// -----------------------------------------------------------------------------
usec_t Clock::time(void)
{
if (UsingCPU) {
static bool warn = true;
if (warn) {
std::cout << "Using CPU clock." << std::endl;
warn = false;
}
#ifdef __osf__
return (usec_t) __RPCC();
#elif __linux__
{
unsigned long tsc;
rdtscl(tsc);
return (usec_t) tsc;
}
#else
{
std::cerr << "CPU clock not implemented for this architecture" << endl;
UsingCPU = false;
return Clock::time();
}
#endif
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
return (usec_t) (tv.tv_sec * UsecPerSec + tv.tv_usec);
}
}
// -----------------------------------------------------------------------------
Clock::Clock(void)
: _start(0),
_elapsed(0),
_active(false)
{
start();
}
// -----------------------------------------------------------------------------
Clock::~Clock(void)
{
;
}
// -----------------------------------------------------------------------------
usec_t Clock::elapsed(void) const
{
if (!active())
return _elapsed;
return time() - _start;
}
// -----------------------------------------------------------------------------
usec_t Clock::start(void)
{
_active = true;
return _start = time();
}
// -----------------------------------------------------------------------------
usec_t Clock::stop(void)
{
_elapsed = elapsed();
_active = false;
return _elapsed;
}
<commit_msg>add missing 'std::'.<commit_after>static const char rcsid[] = "$Id: Clock.cpp,v 1.6 2002-02-05 22:52:46 bastiaan Exp $";
/*
* See the COPYING file for the terms of usage and distribution.
*/
#include <stdlib.h>
#include <sys/time.h> // for struct timeval
#ifdef __osf__
# include <machine/builtins.h> // for __RPCC()
#elif __linux__
# include <asm/msr.h> // for rdtscl()
#endif
#include <iostream>
#include "Clock.hh"
namespace
{
const usec_t UsecPerSec = INT64_CONSTANT(1000000);
}
bool Clock::UsingCPU = ::getenv("CLOCK_USE_CPU") ? true : false;
// -----------------------------------------------------------------------------
usec_t Clock::time(void)
{
if (UsingCPU) {
static bool warn = true;
if (warn) {
std::cout << "Using CPU clock." << std::endl;
warn = false;
}
#ifdef __osf__
return (usec_t) __RPCC();
#elif __linux__
{
unsigned long tsc;
rdtscl(tsc);
return (usec_t) tsc;
}
#else
{
std::cerr << "CPU clock not implemented for this architecture" << std::endl;
UsingCPU = false;
return Clock::time();
}
#endif
} else {
struct timeval tv;
gettimeofday(&tv, NULL);
return (usec_t) (tv.tv_sec * UsecPerSec + tv.tv_usec);
}
}
// -----------------------------------------------------------------------------
Clock::Clock(void)
: _start(0),
_elapsed(0),
_active(false)
{
start();
}
// -----------------------------------------------------------------------------
Clock::~Clock(void)
{
;
}
// -----------------------------------------------------------------------------
usec_t Clock::elapsed(void) const
{
if (!active())
return _elapsed;
return time() - _start;
}
// -----------------------------------------------------------------------------
usec_t Clock::start(void)
{
_active = true;
return _start = time();
}
// -----------------------------------------------------------------------------
usec_t Clock::stop(void)
{
_elapsed = elapsed();
_active = false;
return _elapsed;
}
<|endoftext|> |
<commit_before>#include "../Fixed.h"
#include <iostream>
#include <cassert>
using Fixed = numeric::Fixed<16, 16>;
#if __cplusplus >= 201402L
#define STATIC_ASSERT14(expr) static_assert((expr), "")
#else
#define STATIC_ASSERT14(expr) assert((expr))
#endif
int main() {
Fixed f = 10.5f;
std::cout << f << std::endl;
// TODO(eteran): perform these tests on the bit-patterns, as float comparisons aren't ideal to use
STATIC_ASSERT14((Fixed(10.5) * 3) == 31.5);
STATIC_ASSERT14((Fixed(10.5) * Fixed(3)) == 31.5);
STATIC_ASSERT14((3 * Fixed(10.5)) == 31.5);
STATIC_ASSERT14((Fixed(10.5) * 3.0) == 31.5);
STATIC_ASSERT14((Fixed(10.5) * Fixed(3.0)) == 31.5);
STATIC_ASSERT14((3.0 * Fixed(10.5)) == 31.5);
STATIC_ASSERT14(Fixed(50) / Fixed(5) == Fixed(10));
STATIC_ASSERT14(-Fixed(10) == -10);
STATIC_ASSERT14(+Fixed(10) == +10);
STATIC_ASSERT14(-Fixed(10) - 5 == -15);
STATIC_ASSERT14(++Fixed(5) == Fixed(6));
STATIC_ASSERT14(Fixed(5)++ == Fixed(5));
STATIC_ASSERT14(--Fixed(5) == Fixed(4));
STATIC_ASSERT14(Fixed(5)-- == Fixed(5));
// test some constexpr comparisons stuff
static_assert(Fixed{1} > Fixed{0}, "");
static_assert(Fixed{0.5} < Fixed{1}, "");
static_assert(Fixed{1} == Fixed{1}, "");
static_assert(Fixed{0} != Fixed{1}, "");
static_assert(Fixed{1} >= Fixed{0}, "");
static_assert(Fixed{0.5} <= Fixed{1}, "");
static_assert(Fixed{1} > 0, "");
static_assert(Fixed{0.5} < 1, "");
static_assert(Fixed{1} == 1, "");
static_assert(Fixed{0} != 1, "");
static_assert(Fixed{1} >= 0, "");
static_assert(Fixed{0.5} <= 1, "");
static_assert(1 > Fixed{0}, "");
static_assert(0.5 < Fixed{1}, "");
static_assert(1 == Fixed{1}, "");
static_assert(0 != Fixed{1}, "");
static_assert(1 >= Fixed{0}, "");
static_assert(0.5 <= Fixed{1}, "");
}
<commit_msg>whitespace<commit_after>#include "../Fixed.h"
#include <iostream>
#include <cassert>
using Fixed = numeric::Fixed<16, 16>;
#if __cplusplus >= 201402L
#define STATIC_ASSERT14(expr) static_assert((expr), "")
#else
#define STATIC_ASSERT14(expr) assert((expr))
#endif
int main() {
Fixed f = 10.5f;
std::cout << f << std::endl;
// TODO(eteran): perform these tests on the bit-patterns, as float comparisons aren't ideal to use
STATIC_ASSERT14((Fixed(10.5) * 3) == 31.5);
STATIC_ASSERT14((Fixed(10.5) * Fixed(3)) == 31.5);
STATIC_ASSERT14((3 * Fixed(10.5)) == 31.5);
STATIC_ASSERT14((Fixed(10.5) * 3.0) == 31.5);
STATIC_ASSERT14((Fixed(10.5) * Fixed(3.0)) == 31.5);
STATIC_ASSERT14((3.0 * Fixed(10.5)) == 31.5);
STATIC_ASSERT14(Fixed(50) / Fixed(5) == Fixed(10));
STATIC_ASSERT14(-Fixed(10) == -10);
STATIC_ASSERT14(+Fixed(10) == +10);
STATIC_ASSERT14(-Fixed(10) - 5 == -15);
STATIC_ASSERT14(++Fixed(5) == Fixed(6));
STATIC_ASSERT14(Fixed(5)++ == Fixed(5));
STATIC_ASSERT14(--Fixed(5) == Fixed(4));
STATIC_ASSERT14(Fixed(5)-- == Fixed(5));
// test some constexpr comparisons stuff
static_assert(Fixed{1} > Fixed{0}, "");
static_assert(Fixed{0.5} < Fixed{1}, "");
static_assert(Fixed{1} == Fixed{1}, "");
static_assert(Fixed{0} != Fixed{1}, "");
static_assert(Fixed{1} >= Fixed{0}, "");
static_assert(Fixed{0.5} <= Fixed{1}, "");
static_assert(Fixed{1} > 0, "");
static_assert(Fixed{0.5} < 1, "");
static_assert(Fixed{1} == 1, "");
static_assert(Fixed{0} != 1, "");
static_assert(Fixed{1} >= 0, "");
static_assert(Fixed{0.5} <= 1, "");
static_assert(1 > Fixed{0}, "");
static_assert(0.5 < Fixed{1}, "");
static_assert(1 == Fixed{1}, "");
static_assert(0 != Fixed{1}, "");
static_assert(1 >= Fixed{0}, "");
static_assert(0.5 <= Fixed{1}, "");
}
<|endoftext|> |
<commit_before>// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | FileCheck %s
typedef double * __attribute__((align_value(64))) aligned_double;
void foo(aligned_double x, double * y __attribute__((align_value(32))),
double & z __attribute__((align_value(128)))) { };
// CHECK: define void @_Z3fooPdS_Rd(double* align 64 %x, double* align 32 %y, double* dereferenceable(8) align 128 %z)
struct ad_struct {
aligned_double a;
};
double *foo(ad_struct& x) {
// CHECK-LABEL: @_Z3fooR9ad_struct
// CHECK: [[PTRINT1:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR1:%.+]] = and i64 [[PTRINT1]], 63
// CHECK: [[MASKCOND1:%.+]] = icmp eq i64 [[MASKEDPTR1]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND1]])
return x.a;
}
double *goo(ad_struct *x) {
// CHECK-LABEL: @_Z3gooP9ad_struct
// CHECK: [[PTRINT2:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR2:%.+]] = and i64 [[PTRINT2]], 63
// CHECK: [[MASKCOND2:%.+]] = icmp eq i64 [[MASKEDPTR2]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND2]])
return x->a;
}
double *bar(aligned_double *x) {
// CHECK-LABEL: @_Z3barPPd
// CHECK: [[PTRINT3:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR3:%.+]] = and i64 [[PTRINT3]], 63
// CHECK: [[MASKCOND3:%.+]] = icmp eq i64 [[MASKEDPTR3]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND3]])
return *x;
}
double *car(aligned_double &x) {
// CHECK-LABEL: @_Z3carRPd
// CHECK: [[PTRINT4:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR4:%.+]] = and i64 [[PTRINT4]], 63
// CHECK: [[MASKCOND4:%.+]] = icmp eq i64 [[MASKEDPTR4]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND4]])
return x;
}
double *dar(aligned_double *x) {
// CHECK-LABEL: @_Z3darPPd
// CHECK: [[PTRINT5:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR5:%.+]] = and i64 [[PTRINT5]], 63
// CHECK: [[MASKCOND5:%.+]] = icmp eq i64 [[MASKEDPTR5]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND5]])
return x[5];
}
aligned_double eep();
double *ret() {
// CHECK-LABEL: @_Z3retv
// CHECK: [[PTRINT6:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR6:%.+]] = and i64 [[PTRINT6]], 63
// CHECK: [[MASKCOND6:%.+]] = icmp eq i64 [[MASKEDPTR6]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND6]])
return eep();
}
double **no1(aligned_double *x) {
// CHECK-LABEL: @_Z3no1PPd
return x;
// CHECK-NOT: call void @llvm.assume
}
double *&no2(aligned_double &x) {
// CHECK-LABEL: @_Z3no2RPd
return x;
// CHECK-NOT: call void @llvm.assume
}
double **no3(aligned_double &x) {
// CHECK-LABEL: @_Z3no3RPd
return &x;
// CHECK-NOT: call void @llvm.assume
}
double no3(aligned_double x) {
// CHECK-LABEL: @_Z3no3Pd
return *x;
// CHECK-NOT: call void @llvm.assume
}
double *no4(aligned_double x) {
// CHECK-LABEL: @_Z3no4Pd
return x;
// CHECK-NOT: call void @llvm.assume
}
<commit_msg>Fix test failure from r265361<commit_after>// RUN: %clang_cc1 -triple x86_64-unknown-unknown -emit-llvm -o - %s | FileCheck %s
typedef double * __attribute__((align_value(64))) aligned_double;
void foo(aligned_double x, double * y __attribute__((align_value(32))),
double & z __attribute__((align_value(128)))) { };
// CHECK: define void @_Z3fooPdS_Rd(double* align 64 %x, double* align 32 %y, double* align 128 dereferenceable(8) %z)
struct ad_struct {
aligned_double a;
};
double *foo(ad_struct& x) {
// CHECK-LABEL: @_Z3fooR9ad_struct
// CHECK: [[PTRINT1:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR1:%.+]] = and i64 [[PTRINT1]], 63
// CHECK: [[MASKCOND1:%.+]] = icmp eq i64 [[MASKEDPTR1]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND1]])
return x.a;
}
double *goo(ad_struct *x) {
// CHECK-LABEL: @_Z3gooP9ad_struct
// CHECK: [[PTRINT2:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR2:%.+]] = and i64 [[PTRINT2]], 63
// CHECK: [[MASKCOND2:%.+]] = icmp eq i64 [[MASKEDPTR2]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND2]])
return x->a;
}
double *bar(aligned_double *x) {
// CHECK-LABEL: @_Z3barPPd
// CHECK: [[PTRINT3:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR3:%.+]] = and i64 [[PTRINT3]], 63
// CHECK: [[MASKCOND3:%.+]] = icmp eq i64 [[MASKEDPTR3]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND3]])
return *x;
}
double *car(aligned_double &x) {
// CHECK-LABEL: @_Z3carRPd
// CHECK: [[PTRINT4:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR4:%.+]] = and i64 [[PTRINT4]], 63
// CHECK: [[MASKCOND4:%.+]] = icmp eq i64 [[MASKEDPTR4]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND4]])
return x;
}
double *dar(aligned_double *x) {
// CHECK-LABEL: @_Z3darPPd
// CHECK: [[PTRINT5:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR5:%.+]] = and i64 [[PTRINT5]], 63
// CHECK: [[MASKCOND5:%.+]] = icmp eq i64 [[MASKEDPTR5]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND5]])
return x[5];
}
aligned_double eep();
double *ret() {
// CHECK-LABEL: @_Z3retv
// CHECK: [[PTRINT6:%.+]] = ptrtoint
// CHECK: [[MASKEDPTR6:%.+]] = and i64 [[PTRINT6]], 63
// CHECK: [[MASKCOND6:%.+]] = icmp eq i64 [[MASKEDPTR6]], 0
// CHECK: call void @llvm.assume(i1 [[MASKCOND6]])
return eep();
}
double **no1(aligned_double *x) {
// CHECK-LABEL: @_Z3no1PPd
return x;
// CHECK-NOT: call void @llvm.assume
}
double *&no2(aligned_double &x) {
// CHECK-LABEL: @_Z3no2RPd
return x;
// CHECK-NOT: call void @llvm.assume
}
double **no3(aligned_double &x) {
// CHECK-LABEL: @_Z3no3RPd
return &x;
// CHECK-NOT: call void @llvm.assume
}
double no3(aligned_double x) {
// CHECK-LABEL: @_Z3no3Pd
return *x;
// CHECK-NOT: call void @llvm.assume
}
double *no4(aligned_double x) {
// CHECK-LABEL: @_Z3no4Pd
return x;
// CHECK-NOT: call void @llvm.assume
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2015, 2016, 2017, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <mpi.h>
#include <string.h>
#include "gtest/gtest.h"
#include "SharedMemory.hpp"
class MPISharedMemoryTest: public :: testing :: Test
{
public:
MPISharedMemoryTest();
virtual ~MPISharedMemoryTest();
std::string m_shm_key;
};
MPISharedMemoryTest::MPISharedMemoryTest()
: m_shm_key("/geopm_shared_memory_test")
{
int rank;
std::string shm_key(m_shm_key.c_str());
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (!rank) {
shm_unlink(shm_key.c_str());
}
MPI_Barrier(MPI_COMM_WORLD);
}
MPISharedMemoryTest::~MPISharedMemoryTest()
{
}
TEST_F(MPISharedMemoryTest, hello)
{
int rank;
const char *test_string = "THIS IS THE TEST STRING";
geopm::SharedMemory *sm = NULL;
geopm::SharedMemoryUser *smu = NULL;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
sm = new geopm::SharedMemory(m_shm_key, 128);
strcpy((char *)sm->pointer(), test_string);
}
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 1) {
smu = new geopm::SharedMemoryUser(m_shm_key, 5);
EXPECT_EQ(0, strncmp((char *)smu->pointer(), test_string, strlen(test_string)));
}
MPI_Barrier(MPI_COMM_WORLD);
delete sm;
delete smu;
}
<commit_msg>Convert strcpy() to strncpy() in test code.<commit_after>/*
* Copyright (c) 2015, 2016, 2017, Intel Corporation
*
* 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 Intel Corporation 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 LOG OF THE USE
* OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
*/
#include <sys/mman.h>
#include <stdlib.h>
#include <unistd.h>
#include <mpi.h>
#include <string.h>
#include "gtest/gtest.h"
#include "SharedMemory.hpp"
class MPISharedMemoryTest: public :: testing :: Test
{
public:
MPISharedMemoryTest();
virtual ~MPISharedMemoryTest();
std::string m_shm_key;
};
MPISharedMemoryTest::MPISharedMemoryTest()
: m_shm_key("/geopm_shared_memory_test")
{
int rank;
std::string shm_key(m_shm_key.c_str());
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (!rank) {
shm_unlink(shm_key.c_str());
}
MPI_Barrier(MPI_COMM_WORLD);
}
MPISharedMemoryTest::~MPISharedMemoryTest()
{
}
TEST_F(MPISharedMemoryTest, hello)
{
int rank;
const char *test_string = "THIS IS THE TEST STRING";
geopm::SharedMemory *sm = NULL;
geopm::SharedMemoryUser *smu = NULL;
MPI_Comm_rank(MPI_COMM_WORLD, &rank);
if (rank == 0) {
sm = new geopm::SharedMemory(m_shm_key, 128);
strncpy((char *)sm->pointer(), test_string, 127);
}
MPI_Barrier(MPI_COMM_WORLD);
if (rank == 1) {
smu = new geopm::SharedMemoryUser(m_shm_key, 5);
EXPECT_EQ(0, strncmp((char *)smu->pointer(), test_string, strlen(test_string)));
}
MPI_Barrier(MPI_COMM_WORLD);
delete sm;
delete smu;
}
<|endoftext|> |
<commit_before>#include "Platform.hpp"
#include "genome.pb.h"
#include "CellComponent.hpp"
#include "ActivityStats.hpp"
#include "Neuron.hpp"
#include "Branch.hpp"
#include "Synapse.hpp"
#include "Base64.hpp"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "genome.pb.h"
#include <time.h>
namespace Elysia {
void testTwoConnectedNeurons() {
ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment();
Brain *brain= new Brain(myProteinEnvironment);
FILE *dendriteTree=NULL;
dendriteTree = fopen("Dendritic_Tree.txt", "w");
for(float i=0;i<2;i++){
Genome::Gene gene;//FIXME set source and target regions to match the desired behavior
Genome::TemporalBoundingBox *sourcebb=gene.add_bounds();
Genome::TemporalBoundingBox *targetbb=gene.add_bounds();
sourcebb->set_minx(i);
sourcebb->set_miny(i);
sourcebb->set_minz(i);
sourcebb->set_maxx(i);
sourcebb->set_maxy(i);
sourcebb->set_maxz(i);
targetbb->set_minx(1-i);
targetbb->set_miny(1-i);
targetbb->set_minz(1-i);
targetbb->set_maxx(1-i);
targetbb->set_maxy(1-i);
targetbb->set_maxz(1-i);
Vector3f v;
v.x = i;
v.y = i;
v.z = i;
Neuron *n;
srand(time(NULL));
brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene));
n->developSynapse(n->getActivityStats());
size_t parent;
parent = 0;
n->visualizeTree(dendriteTree, parent);
n->activateComponent(*brain,100);
n->tick();
//const Vector3f &location): mNeuronLocation(location){));
}
fclose(dendriteTree);
}
void testResultHelper(const std::vector<std::pair<Elysia::Genome::Effect, float> >&combinedResult, float&grow_leaf_count,float&grow_neuron_count,float&other_count){
using namespace Elysia::Genome;
grow_leaf_count=0;
grow_leaf_count=0;
other_count=0;
for (size_t i=0;i<combinedResult.size();++i) {
switch(combinedResult[i].first) {
case GROW_NEURON:
grow_neuron_count+=combinedResult[i].second;
break;
case GROW_LEAF:
grow_leaf_count+=combinedResult[i].second;
break;
default:
other_count+=combinedResult[i].second;
break;
}
}
}
void testProteinEnvironment() {
using namespace Elysia::Genome;
Elysia::Genome::Genome twoOverlappingGenes;
Elysia::Genome::Chromosome *father=twoOverlappingGenes.mutable_fathers();
Elysia::Genome::Gene firstGene;
Elysia::Genome::Protein firstProtein;
firstProtein.set_protein_code(GROW_NEURON);//so we can easily identify where
firstProtein.set_density(0.125);
Elysia::Genome::Protein firstAuxProtein;
firstProtein.set_protein_code(GROW_LEAF);//so we see that they are additive
firstProtein.set_density(0.25);
*firstGene.add_external_proteins()=firstProtein;
*firstGene.add_external_proteins()=firstAuxProtein;
Elysia::Genome::TemporalBoundingBox firstRegion;
firstRegion.set_minx(0);
firstRegion.set_miny(0);
firstRegion.set_minz(0);
firstRegion.set_maxx(2);
firstRegion.set_maxy(2);
firstRegion.set_maxz(2);
*firstGene.add_bounds()=firstRegion;
Elysia::Genome::Gene secondGene;
Elysia::Genome::Protein secondProtein;
secondProtein.set_protein_code(GROW_LEAF);
secondProtein.set_density(0.5);
*secondGene.add_external_proteins()=secondProtein;
Elysia::Genome::TemporalBoundingBox secondRegion;
secondRegion.set_minx(-1);
secondRegion.set_miny(-1);
secondRegion.set_minz(-1);
secondRegion.set_maxx(1);
secondRegion.set_maxy(1);
secondRegion.set_maxz(1);
*secondGene.add_bounds()=secondRegion;
*father->add_genes()=firstGene;
*father->add_genes()=secondGene;
ProteinEnvironment * pe=new SimpleProteinEnvironment;
pe->initialize(twoOverlappingGenes);
std::vector<std::pair<Elysia::Genome::Effect, float> > combinedResult=pe->getCompleteProteinDensity(Vector3f(.5,.5,.5));
//check that firstResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > firstResult=pe->getCompleteProteinDensity(Vector3f(1.5,1.5,1.5));
//check that secondResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > secondResult=pe->getCompleteProteinDensity(Vector3f(-.5,-.5,-.5));
float grow_leaf_count=0;
float grow_neuron_count=0;
float other_count=0;
testResultHelper(combinedResult,grow_leaf_count,grow_neuron_count,other_count);
assert(grow_leaf_count==.75);
assert(grow_neuron_count==.125);
assert(other_count==0);
testResultHelper(firstResult,grow_leaf_count,grow_neuron_count,other_count);
assert(grow_leaf_count==.25);
assert(grow_neuron_count==.125);
assert(other_count==0);
testResultHelper(secondResult,grow_leaf_count,grow_neuron_count,other_count);
assert(grow_leaf_count==.5);
assert(grow_neuron_count==0);
assert(other_count==0);
delete pe;
}
}
int runtest(){
Elysia::testTwoConnectedNeurons();
//Elysia::testProteinEnvironment();
//getchar();
return 1;
}
<commit_msg>set the auxProtein to GROW_LEAF, not the protein<commit_after>#include "Platform.hpp"
#include "genome.pb.h"
#include "CellComponent.hpp"
#include "ActivityStats.hpp"
#include "Neuron.hpp"
#include "Branch.hpp"
#include "Synapse.hpp"
#include "Base64.hpp"
#include "Brain.hpp"
#include "SimpleProteinEnvironment.hpp"
#include "genome.pb.h"
#include <time.h>
namespace Elysia {
void testTwoConnectedNeurons() {
ProteinEnvironment *myProteinEnvironment= new SimpleProteinEnvironment();
Brain *brain= new Brain(myProteinEnvironment);
FILE *dendriteTree=NULL;
dendriteTree = fopen("Dendritic_Tree.txt", "w");
for(float i=0;i<2;i++){
Genome::Gene gene;//FIXME set source and target regions to match the desired behavior
Genome::TemporalBoundingBox *sourcebb=gene.add_bounds();
Genome::TemporalBoundingBox *targetbb=gene.add_bounds();
sourcebb->set_minx(i);
sourcebb->set_miny(i);
sourcebb->set_minz(i);
sourcebb->set_maxx(i);
sourcebb->set_maxy(i);
sourcebb->set_maxz(i);
targetbb->set_minx(1-i);
targetbb->set_miny(1-i);
targetbb->set_minz(1-i);
targetbb->set_maxx(1-i);
targetbb->set_maxy(1-i);
targetbb->set_maxz(1-i);
Vector3f v;
v.x = i;
v.y = i;
v.z = i;
Neuron *n;
srand(time(NULL));
brain->mAllNeurons.insert(n = new Neuron(brain, 2, 3, 4, v,gene));
n->developSynapse(n->getActivityStats());
size_t parent;
parent = 0;
n->visualizeTree(dendriteTree, parent);
n->activateComponent(*brain,100);
n->tick();
//const Vector3f &location): mNeuronLocation(location){));
}
fclose(dendriteTree);
}
void testResultHelper(const std::vector<std::pair<Elysia::Genome::Effect, float> >&combinedResult, float&grow_leaf_count,float&grow_neuron_count,float&other_count){
using namespace Elysia::Genome;
grow_leaf_count=0;
grow_leaf_count=0;
other_count=0;
for (size_t i=0;i<combinedResult.size();++i) {
switch(combinedResult[i].first) {
case GROW_NEURON:
grow_neuron_count+=combinedResult[i].second;
break;
case GROW_LEAF:
grow_leaf_count+=combinedResult[i].second;
break;
default:
other_count+=combinedResult[i].second;
break;
}
}
}
void testProteinEnvironment() {
using namespace Elysia::Genome;
Elysia::Genome::Genome twoOverlappingGenes;
Elysia::Genome::Chromosome *father=twoOverlappingGenes.mutable_fathers();
Elysia::Genome::Gene firstGene;
Elysia::Genome::Protein firstProtein;
firstProtein.set_protein_code(GROW_NEURON);//so we can easily identify where
firstProtein.set_density(0.125);
Elysia::Genome::Protein firstAuxProtein;
firstAuxProtein.set_protein_code(GROW_LEAF);//so we see that they are additive
firstAuxProtein.set_density(0.25);
*firstGene.add_external_proteins()=firstProtein;
assert(firstGene.external_proteins(0).protein_code()==GROW_NEURON);
*firstGene.add_external_proteins()=firstAuxProtein;
assert(firstGene.external_proteins(0).protein_code()==GROW_LEAF);
Elysia::Genome::TemporalBoundingBox firstRegion;
firstRegion.set_minx(0);
firstRegion.set_miny(0);
firstRegion.set_minz(0);
firstRegion.set_maxx(2);
firstRegion.set_maxy(2);
firstRegion.set_maxz(2);
*firstGene.add_bounds()=firstRegion;
Elysia::Genome::Gene secondGene;
Elysia::Genome::Protein secondProtein;
secondProtein.set_protein_code(GROW_LEAF);
secondProtein.set_density(0.5);
*secondGene.add_external_proteins()=secondProtein;
Elysia::Genome::TemporalBoundingBox secondRegion;
secondRegion.set_minx(-1);
secondRegion.set_miny(-1);
secondRegion.set_minz(-1);
secondRegion.set_maxx(1);
secondRegion.set_maxy(1);
secondRegion.set_maxz(1);
*secondGene.add_bounds()=secondRegion;
*father->add_genes()=firstGene;
*father->add_genes()=secondGene;
ProteinEnvironment * pe=new SimpleProteinEnvironment;
pe->initialize(twoOverlappingGenes);
std::vector<std::pair<Elysia::Genome::Effect, float> > combinedResult=pe->getCompleteProteinDensity(Vector3f(.5,.5,.5));
//check that firstResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > firstResult=pe->getCompleteProteinDensity(Vector3f(1.5,1.5,1.5));
//check that secondResult matches expectations
std::vector<std::pair<Elysia::Genome::Effect, float> > secondResult=pe->getCompleteProteinDensity(Vector3f(-.5,-.5,-.5));
float grow_leaf_count=0;
float grow_neuron_count=0;
float other_count=0;
testResultHelper(combinedResult,grow_leaf_count,grow_neuron_count,other_count);
assert(grow_leaf_count==.75);
assert(grow_neuron_count==.125);
assert(other_count==0);
testResultHelper(firstResult,grow_leaf_count,grow_neuron_count,other_count);
assert(grow_leaf_count==.25);
assert(grow_neuron_count==.125);
assert(other_count==0);
testResultHelper(secondResult,grow_leaf_count,grow_neuron_count,other_count);
assert(grow_leaf_count==.5);
assert(grow_neuron_count==0);
assert(other_count==0);
/*
Gene * grow_neuron_gene = pe->retrieveGene(Vector3f(0.5,0.5,0.5),
GROW_NEURON);
Gene * combined_grow_leaf_gene = pe->retrieveGene(Vector3f(0.5,0.5,0.5),
GROW_LEAF);
Gene * first_grow_leaf_gene = pe->retrieveGene(Vector3f(1.5,1.5,1.5),
GROW_LEAF);
Gene * second_grow_leaf_gene = pe->retrieveGene(Vector3f(-0.5,-0.5,-0.5),
GROW_LEAF);
*/
delete pe;
}
}
int runtest(){
Elysia::testTwoConnectedNeurons();
//Elysia::testProteinEnvironment();
//getchar();
return 1;
}
<|endoftext|> |
<commit_before>#include "base_simulation_test.h"
#include <fstream>
#include <chrono>
#include <iostream>
#include "json/json.h"
#include "physics/default_force.h"
#include "physics/physical_node_movement_listener.h"
namespace bdm {
using std::ofstream;
using cells::Cell;
using local_biology::CellElement;
using physics::PhysicalNode;
using physics::DefaultForce;
using physics::PhysicalObject;
using physics::PhysicalNodeMovementListener;
using spatial_organization::SpaceNode;
using synapse::Excrescence;
bool BaseSimulationTest::update_sim_state_reference_file_ = false;
bool BaseSimulationTest::disable_assertions_ = false;
BaseSimulationTest::BaseSimulationTest() {
}
BaseSimulationTest::~BaseSimulationTest() {
}
void BaseSimulationTest::SetUp() {
ECM::getInstance()->clearAll();
Cell::reset();
CellElement::reset();
PhysicalNode::reset();
SpaceNode < PhysicalNode > ::reset();
Random::setSeed(1L);
PhysicalObject::setInterObjectForce(DefaultForce::UPtr(new DefaultForce()));
}
void BaseSimulationTest::TearDown() {
}
void BaseSimulationTest::run() {
// run simulation
long start = timestamp();
simulate();
long end = timestamp();
runtime_ = end - start;
std::cout << "RUNTIME " << getTestName() << " " << (end-start) << std::endl;
// ensure correct result
if (!disable_assertions_) {
assertSimulationState();
}
}
void BaseSimulationTest::assertSimulationState() {
// create Json string of simulation state
StringBuilder sb;
ECM::getInstance()->simStateToJson(sb);
string reference_file_name = "test_resources/" + getTestName() + ".json";
if (update_sim_state_reference_file_) {
// update reference file
std::cout << "NOTE: parameter --update-references specified: Reference File will be updated and "
"no assertions will be performed" << std::endl;
string content = sb.str();
writeToFile("../test/resources/" + getTestName() + ".json", content);
return;
}
// read in reference simulation state
string expected_string;
readFromFile(reference_file_name, expected_string);
// create Json objects
Json::Reader reader;
Json::Value actual;
Json::Value expected;
Json::Value::epsilon_ = 1e-6;
reader.parse(sb.str(), actual);
reader.parse(expected_string, expected);
// compare Json objects for equality
bool equal = expected == actual;
EXPECT_TRUE(equal);
if (equal) {
persistRuntime();
} else {
writeToFile("failed_" + getTestName() + "_actual", actual);
writeToFile("failed_" + getTestName() + "_expected", expected);
}
}
void BaseSimulationTest::persistRuntime() {
// get last commit
auto last_commit = exec("git rev-parse HEAD").substr(0, 40);
// read in csv file with runtimes
string filename = "../test/resources/" + getTestName() + ".csv";
string runtime_csv;
readFromFile(filename, runtime_csv);
// if entry with this commit exists: remove it;
auto found = runtime_csv.find(last_commit);
if (found != string::npos) {
runtime_csv = runtime_csv.substr(0, found);
}
// append new runtime
stringstream ss;
ss << last_commit << ';' << runtime_ << std::endl; // convert runtime_ to seconds
runtime_csv += ss.str();
writeToFile(filename, runtime_csv);
}
long BaseSimulationTest::timestamp() {
namespace sc = std::chrono;
auto time = sc::system_clock::now();
auto since_epoch = time.time_since_epoch();
auto millis = sc::duration_cast < sc::milliseconds > (since_epoch);
return millis.count();
}
void BaseSimulationTest::readFromFile(const string &file_path, string &content) {
std::ifstream ifs(file_path);
content.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
template<class T>
void BaseSimulationTest::writeToFile(const string& file_path, T& content) {
ofstream ofs(file_path);
ofs << content;
}
string BaseSimulationTest::exec(const char* cmd) {
char buffer[128];
string result = "";
std::shared_ptr < FILE > pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (!feof(pipe.get())) {
if (fgets(buffer, 128, pipe.get()) != NULL) {
result += buffer;
}
}
return result;
}
void BaseSimulationTest::initPhysicalNodeMovementListener() {
PhysicalNodeMovementListener::setMovementOperationId((int) (10000 * Random::nextDouble()));
}
} // namespace bdm
<commit_msg>Don't print additional run-time information, gtest does it.<commit_after>#include "base_simulation_test.h"
#include <fstream>
#include <chrono>
#include <iostream>
#include "json/json.h"
#include "physics/default_force.h"
#include "physics/physical_node_movement_listener.h"
namespace bdm {
using std::ofstream;
using cells::Cell;
using local_biology::CellElement;
using physics::PhysicalNode;
using physics::DefaultForce;
using physics::PhysicalObject;
using physics::PhysicalNodeMovementListener;
using spatial_organization::SpaceNode;
using synapse::Excrescence;
bool BaseSimulationTest::update_sim_state_reference_file_ = false;
bool BaseSimulationTest::disable_assertions_ = false;
BaseSimulationTest::BaseSimulationTest() {
}
BaseSimulationTest::~BaseSimulationTest() {
}
void BaseSimulationTest::SetUp() {
ECM::getInstance()->clearAll();
Cell::reset();
CellElement::reset();
PhysicalNode::reset();
SpaceNode < PhysicalNode > ::reset();
Random::setSeed(1L);
PhysicalObject::setInterObjectForce(DefaultForce::UPtr(new DefaultForce()));
}
void BaseSimulationTest::TearDown() {
}
void BaseSimulationTest::run() {
// run simulation
long start = timestamp();
simulate();
long end = timestamp();
runtime_ = end - start;
//std::cout << "RUNTIME " << getTestName() << " " << (end-start) << std::endl;
// ensure correct result
if (!disable_assertions_) {
assertSimulationState();
}
}
void BaseSimulationTest::assertSimulationState() {
// create Json string of simulation state
StringBuilder sb;
ECM::getInstance()->simStateToJson(sb);
string reference_file_name = "test_resources/" + getTestName() + ".json";
if (update_sim_state_reference_file_) {
// update reference file
std::cout << "NOTE: parameter --update-references specified: Reference File will be updated and "
"no assertions will be performed" << std::endl;
string content = sb.str();
writeToFile("../test/resources/" + getTestName() + ".json", content);
return;
}
// read in reference simulation state
string expected_string;
readFromFile(reference_file_name, expected_string);
// create Json objects
Json::Reader reader;
Json::Value actual;
Json::Value expected;
Json::Value::epsilon_ = 1e-6;
reader.parse(sb.str(), actual);
reader.parse(expected_string, expected);
// compare Json objects for equality
bool equal = expected == actual;
EXPECT_TRUE(equal);
if (equal) {
persistRuntime();
} else {
writeToFile("failed_" + getTestName() + "_actual", actual);
writeToFile("failed_" + getTestName() + "_expected", expected);
}
}
void BaseSimulationTest::persistRuntime() {
// get last commit
auto last_commit = exec("git rev-parse HEAD").substr(0, 40);
// read in csv file with runtimes
string filename = "../test/resources/" + getTestName() + ".csv";
string runtime_csv;
readFromFile(filename, runtime_csv);
// if entry with this commit exists: remove it;
auto found = runtime_csv.find(last_commit);
if (found != string::npos) {
runtime_csv = runtime_csv.substr(0, found);
}
// append new runtime
stringstream ss;
ss << last_commit << ';' << runtime_ << std::endl; // convert runtime_ to seconds
runtime_csv += ss.str();
writeToFile(filename, runtime_csv);
}
long BaseSimulationTest::timestamp() {
namespace sc = std::chrono;
auto time = sc::system_clock::now();
auto since_epoch = time.time_since_epoch();
auto millis = sc::duration_cast < sc::milliseconds > (since_epoch);
return millis.count();
}
void BaseSimulationTest::readFromFile(const string &file_path, string &content) {
std::ifstream ifs(file_path);
content.assign(std::istreambuf_iterator<char>(ifs), std::istreambuf_iterator<char>());
}
template<class T>
void BaseSimulationTest::writeToFile(const string& file_path, T& content) {
ofstream ofs(file_path);
ofs << content;
}
string BaseSimulationTest::exec(const char* cmd) {
char buffer[128];
string result = "";
std::shared_ptr < FILE > pipe(popen(cmd, "r"), pclose);
if (!pipe) {
throw std::runtime_error("popen() failed!");
}
while (!feof(pipe.get())) {
if (fgets(buffer, 128, pipe.get()) != NULL) {
result += buffer;
}
}
return result;
}
void BaseSimulationTest::initPhysicalNodeMovementListener() {
PhysicalNodeMovementListener::setMovementOperationId((int) (10000 * Random::nextDouble()));
}
} // namespace bdm
<|endoftext|> |
<commit_before>// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <random>
#include <benchmark/benchmark.h>
#include "perfetto/base/time.h"
#include "perfetto/ext/traced/traced.h"
#include "perfetto/ext/tracing/core/trace_packet.h"
#include "perfetto/tracing/core/trace_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/gtest_and_gmock.h"
#include "test/task_runner_thread.h"
#include "test/task_runner_thread_delegates.h"
#include "test/test_helper.h"
#include "protos/perfetto/config/test_config.gen.h"
#include "protos/perfetto/trace/test_event.gen.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
bool IsBenchmarkFunctionalOnly() {
return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr;
}
void BenchmarkProducer(benchmark::State& state) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
FakeProducer* producer = helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(512);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
static constexpr uint32_t kRandomSeed = 42;
uint32_t message_count = static_cast<uint32_t>(state.range(0));
uint32_t message_bytes = static_cast<uint32_t>(state.range(1));
uint32_t mb_per_s = static_cast<uint32_t>(state.range(2));
uint32_t messages_per_s = mb_per_s * 1024 * 1024 / message_bytes;
uint32_t time_for_messages_ms =
10000 + (messages_per_s == 0 ? 0 : message_count * 1000 / messages_per_s);
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(message_count);
ds_config->mutable_for_testing()->set_message_size(message_bytes);
ds_config->mutable_for_testing()->set_max_messages_per_second(messages_per_s);
helper.StartTracing(trace_config);
helper.WaitForProducerEnabled();
uint64_t wall_start_ns = static_cast<uint64_t>(base::GetWallTimeNs().count());
uint64_t service_start_ns = helper.service_thread()->GetThreadCPUTimeNs();
uint64_t producer_start_ns = helper.producer_thread()->GetThreadCPUTimeNs();
uint32_t iterations = 0;
for (auto _ : state) {
auto cname = "produced.and.committed." + std::to_string(iterations++);
auto on_produced_and_committed = task_runner.CreateCheckpoint(cname);
producer->ProduceEventBatch(helper.WrapTask(on_produced_and_committed));
task_runner.RunUntilCheckpoint(cname, time_for_messages_ms);
}
uint64_t service_ns =
helper.service_thread()->GetThreadCPUTimeNs() - service_start_ns;
uint64_t producer_ns =
helper.producer_thread()->GetThreadCPUTimeNs() - producer_start_ns;
uint64_t wall_ns =
static_cast<uint64_t>(base::GetWallTimeNs().count()) - wall_start_ns;
state.counters["Ser CPU"] = benchmark::Counter(100.0 * service_ns / wall_ns);
state.counters["Ser ns/m"] =
benchmark::Counter(1.0 * service_ns / message_count);
state.counters["Pro CPU"] = benchmark::Counter(100.0 * producer_ns / wall_ns);
state.SetBytesProcessed(iterations * message_bytes * message_count);
// Read back the buffer just to check correctness.
helper.ReadData();
helper.WaitForReadData();
bool is_first_packet = true;
std::minstd_rand0 rnd_engine(kRandomSeed);
for (const auto& packet : helper.trace()) {
ASSERT_TRUE(packet.has_for_testing());
if (is_first_packet) {
rnd_engine = std::minstd_rand0(packet.for_testing().seq_value());
is_first_packet = false;
} else {
ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
}
}
}
static void BenchmarkConsumer(benchmark::State& state) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
FakeProducer* producer = helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
static const uint32_t kBufferSizeBytes =
IsBenchmarkFunctionalOnly() ? 16 * 1024 : 2 * 1024 * 1024;
trace_config.add_buffers()->set_size_kb(kBufferSizeBytes / 1024);
static constexpr uint32_t kRandomSeed = 42;
uint32_t message_bytes = static_cast<uint32_t>(state.range(0));
uint32_t mb_per_s = static_cast<uint32_t>(state.range(1));
bool is_saturated_producer = mb_per_s == 0;
uint32_t message_count = kBufferSizeBytes / message_bytes;
uint32_t messages_per_s = mb_per_s * 1024 * 1024 / message_bytes;
uint32_t number_of_batches =
is_saturated_producer ? 0 : std::max(1u, message_count / messages_per_s);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(message_count);
ds_config->mutable_for_testing()->set_message_size(message_bytes);
ds_config->mutable_for_testing()->set_max_messages_per_second(messages_per_s);
helper.StartTracing(trace_config);
helper.WaitForProducerEnabled();
uint64_t wall_start_ns = static_cast<uint64_t>(base::GetWallTimeNs().count());
uint64_t service_start_ns =
static_cast<uint64_t>(helper.service_thread()->GetThreadCPUTimeNs());
uint64_t consumer_start_ns =
static_cast<uint64_t>(base::GetThreadCPUTimeNs().count());
uint64_t read_time_taken_ns = 0;
uint64_t iterations = 0;
uint32_t counter = 0;
for (auto _ : state) {
auto cname = "produced.and.committed." + std::to_string(iterations++);
auto on_produced_and_committed = task_runner.CreateCheckpoint(cname);
producer->ProduceEventBatch(helper.WrapTask(on_produced_and_committed));
if (is_saturated_producer) {
// If the producer is running in saturated mode, wait until it flushes
// data.
task_runner.RunUntilCheckpoint(cname);
// Then time how long it takes to read back the data.
int64_t start = base::GetWallTimeNs().count();
helper.ReadData(counter);
helper.WaitForReadData(counter++);
read_time_taken_ns +=
static_cast<uint64_t>(base::GetWallTimeNs().count() - start);
} else {
// If the producer is not running in saturated mode, every second the
// producer will send a batch of data over. Wait for a second before
// performing readback; do this for each batch the producer sends.
for (uint32_t i = 0; i < number_of_batches; i++) {
auto batch_cname = "batch.checkpoint." + std::to_string(counter);
auto batch_checkpoint = task_runner.CreateCheckpoint(batch_cname);
task_runner.PostDelayedTask(batch_checkpoint, 1000);
task_runner.RunUntilCheckpoint(batch_cname);
int64_t start = base::GetWallTimeNs().count();
helper.ReadData(counter);
helper.WaitForReadData(counter++);
read_time_taken_ns +=
static_cast<uint64_t>(base::GetWallTimeNs().count() - start);
}
}
}
uint64_t service_ns =
helper.service_thread()->GetThreadCPUTimeNs() - service_start_ns;
uint64_t consumer_ns =
static_cast<uint64_t>(base::GetThreadCPUTimeNs().count()) -
consumer_start_ns;
uint64_t wall_ns =
static_cast<uint64_t>(base::GetWallTimeNs().count()) - wall_start_ns;
state.counters["Ser CPU"] = benchmark::Counter(100.0 * service_ns / wall_ns);
state.counters["Ser ns/m"] =
benchmark::Counter(1.0 * service_ns / message_count);
state.counters["Con CPU"] = benchmark::Counter(100.0 * consumer_ns / wall_ns);
state.counters["Con Speed"] =
benchmark::Counter(iterations * 1000.0 * 1000 * 1000 * kBufferSizeBytes /
read_time_taken_ns);
}
void SaturateCpuProducerArgs(benchmark::internal::Benchmark* b) {
int min_message_count = 16;
int max_message_count = IsBenchmarkFunctionalOnly() ? 1024 : 1024 * 1024;
int min_payload = 8;
int max_payload = IsBenchmarkFunctionalOnly() ? 256 : 2048;
for (int count = min_message_count; count <= max_message_count; count *= 2) {
for (int bytes = min_payload; bytes <= max_payload; bytes *= 2) {
b->Args({count, bytes, 0 /* speed */});
}
}
}
void ConstantRateProducerArgs(benchmark::internal::Benchmark* b) {
int message_count = IsBenchmarkFunctionalOnly() ? 2 * 1024 : 128 * 1024;
int min_speed = IsBenchmarkFunctionalOnly() ? 64 : 8;
int max_speed = 128;
for (int speed = min_speed; speed <= max_speed; speed *= 2) {
b->Args({message_count, 128, speed});
b->Args({message_count, 256, speed});
}
}
void SaturateCpuConsumerArgs(benchmark::internal::Benchmark* b) {
int min_payload = 8;
int max_payload = IsBenchmarkFunctionalOnly() ? 16 : 64 * 1024;
for (int bytes = min_payload; bytes <= max_payload; bytes *= 2) {
b->Args({bytes, 0 /* speed */});
}
}
void ConstantRateConsumerArgs(benchmark::internal::Benchmark* b) {
int min_speed = IsBenchmarkFunctionalOnly() ? 128 : 1;
int max_speed = IsBenchmarkFunctionalOnly() ? 128 : 2;
for (int speed = min_speed; speed <= max_speed; speed *= 2) {
b->Args({2, speed});
b->Args({4, speed});
}
}
} // namespace
static void BM_EndToEnd_Producer_SaturateCpu(benchmark::State& state) {
BenchmarkProducer(state);
}
BENCHMARK(BM_EndToEnd_Producer_SaturateCpu)
->Unit(benchmark::kMicrosecond)
->UseRealTime()
->Apply(SaturateCpuProducerArgs);
static void BM_EndToEnd_Producer_ConstantRate(benchmark::State& state) {
BenchmarkProducer(state);
}
BENCHMARK(BM_EndToEnd_Producer_ConstantRate)
->Unit(benchmark::kMicrosecond)
->UseRealTime()
->Apply(ConstantRateProducerArgs);
static void BM_EndToEnd_Consumer_SaturateCpu(benchmark::State& state) {
BenchmarkConsumer(state);
}
BENCHMARK(BM_EndToEnd_Consumer_SaturateCpu)
->Unit(benchmark::kMicrosecond)
->UseRealTime()
->Apply(SaturateCpuConsumerArgs);
static void BM_EndToEnd_Consumer_ConstantRate(benchmark::State& state) {
BenchmarkConsumer(state);
}
BENCHMARK(BM_EndToEnd_Consumer_ConstantRate)
->Unit(benchmark::kMillisecond)
->UseRealTime()
->Apply(ConstantRateConsumerArgs);
} // namespace perfetto
<commit_msg>Fix CI timeout on android-clang-arm-asan benchmark<commit_after>// Copyright (C) 2018 The Android Open Source Project
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
#include <random>
#include <benchmark/benchmark.h>
#include "perfetto/base/time.h"
#include "perfetto/ext/traced/traced.h"
#include "perfetto/ext/tracing/core/trace_packet.h"
#include "perfetto/tracing/core/trace_config.h"
#include "src/base/test/test_task_runner.h"
#include "test/gtest_and_gmock.h"
#include "test/task_runner_thread.h"
#include "test/task_runner_thread_delegates.h"
#include "test/test_helper.h"
#include "protos/perfetto/config/test_config.gen.h"
#include "protos/perfetto/trace/test_event.gen.h"
#include "protos/perfetto/trace/trace_packet.pbzero.h"
namespace perfetto {
namespace {
bool IsBenchmarkFunctionalOnly() {
return getenv("BENCHMARK_FUNCTIONAL_TEST_ONLY") != nullptr;
}
void BenchmarkProducer(benchmark::State& state) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
FakeProducer* producer = helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
trace_config.add_buffers()->set_size_kb(512);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
static constexpr uint32_t kRandomSeed = 42;
uint32_t message_count = static_cast<uint32_t>(state.range(0));
uint32_t message_bytes = static_cast<uint32_t>(state.range(1));
uint32_t mb_per_s = static_cast<uint32_t>(state.range(2));
uint32_t messages_per_s = mb_per_s * 1024 * 1024 / message_bytes;
uint32_t time_for_messages_ms =
10000 + (messages_per_s == 0 ? 0 : message_count * 1000 / messages_per_s);
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(message_count);
ds_config->mutable_for_testing()->set_message_size(message_bytes);
ds_config->mutable_for_testing()->set_max_messages_per_second(messages_per_s);
helper.StartTracing(trace_config);
helper.WaitForProducerEnabled();
uint64_t wall_start_ns = static_cast<uint64_t>(base::GetWallTimeNs().count());
uint64_t service_start_ns = helper.service_thread()->GetThreadCPUTimeNs();
uint64_t producer_start_ns = helper.producer_thread()->GetThreadCPUTimeNs();
uint32_t iterations = 0;
for (auto _ : state) {
auto cname = "produced.and.committed." + std::to_string(iterations++);
auto on_produced_and_committed = task_runner.CreateCheckpoint(cname);
producer->ProduceEventBatch(helper.WrapTask(on_produced_and_committed));
task_runner.RunUntilCheckpoint(cname, time_for_messages_ms);
}
uint64_t service_ns =
helper.service_thread()->GetThreadCPUTimeNs() - service_start_ns;
uint64_t producer_ns =
helper.producer_thread()->GetThreadCPUTimeNs() - producer_start_ns;
uint64_t wall_ns =
static_cast<uint64_t>(base::GetWallTimeNs().count()) - wall_start_ns;
state.counters["Ser CPU"] = benchmark::Counter(100.0 * service_ns / wall_ns);
state.counters["Ser ns/m"] =
benchmark::Counter(1.0 * service_ns / message_count);
state.counters["Pro CPU"] = benchmark::Counter(100.0 * producer_ns / wall_ns);
state.SetBytesProcessed(iterations * message_bytes * message_count);
// Read back the buffer just to check correctness.
helper.ReadData();
helper.WaitForReadData();
bool is_first_packet = true;
std::minstd_rand0 rnd_engine(kRandomSeed);
for (const auto& packet : helper.trace()) {
ASSERT_TRUE(packet.has_for_testing());
if (is_first_packet) {
rnd_engine = std::minstd_rand0(packet.for_testing().seq_value());
is_first_packet = false;
} else {
ASSERT_EQ(packet.for_testing().seq_value(), rnd_engine());
}
}
}
static void BenchmarkConsumer(benchmark::State& state) {
base::TestTaskRunner task_runner;
TestHelper helper(&task_runner);
helper.StartServiceIfRequired();
FakeProducer* producer = helper.ConnectFakeProducer();
helper.ConnectConsumer();
helper.WaitForConsumerConnect();
TraceConfig trace_config;
static const uint32_t kBufferSizeBytes =
IsBenchmarkFunctionalOnly() ? 16 * 1024 : 2 * 1024 * 1024;
trace_config.add_buffers()->set_size_kb(kBufferSizeBytes / 1024);
static constexpr uint32_t kRandomSeed = 42;
uint32_t message_bytes = static_cast<uint32_t>(state.range(0));
uint32_t mb_per_s = static_cast<uint32_t>(state.range(1));
bool is_saturated_producer = mb_per_s == 0;
uint32_t message_count = kBufferSizeBytes / message_bytes;
uint32_t messages_per_s = mb_per_s * 1024 * 1024 / message_bytes;
uint32_t number_of_batches =
is_saturated_producer ? 0 : std::max(1u, message_count / messages_per_s);
auto* ds_config = trace_config.add_data_sources()->mutable_config();
ds_config->set_name("android.perfetto.FakeProducer");
ds_config->set_target_buffer(0);
ds_config->mutable_for_testing()->set_seed(kRandomSeed);
ds_config->mutable_for_testing()->set_message_count(message_count);
ds_config->mutable_for_testing()->set_message_size(message_bytes);
ds_config->mutable_for_testing()->set_max_messages_per_second(messages_per_s);
helper.StartTracing(trace_config);
helper.WaitForProducerEnabled();
uint64_t wall_start_ns = static_cast<uint64_t>(base::GetWallTimeNs().count());
uint64_t service_start_ns =
static_cast<uint64_t>(helper.service_thread()->GetThreadCPUTimeNs());
uint64_t consumer_start_ns =
static_cast<uint64_t>(base::GetThreadCPUTimeNs().count());
uint64_t read_time_taken_ns = 0;
uint64_t iterations = 0;
uint32_t counter = 0;
for (auto _ : state) {
auto cname = "produced.and.committed." + std::to_string(iterations++);
auto on_produced_and_committed = task_runner.CreateCheckpoint(cname);
producer->ProduceEventBatch(helper.WrapTask(on_produced_and_committed));
if (is_saturated_producer) {
// If the producer is running in saturated mode, wait until it flushes
// data.
task_runner.RunUntilCheckpoint(cname);
// Then time how long it takes to read back the data.
int64_t start = base::GetWallTimeNs().count();
helper.ReadData(counter);
helper.WaitForReadData(counter++);
read_time_taken_ns +=
static_cast<uint64_t>(base::GetWallTimeNs().count() - start);
} else {
// If the producer is not running in saturated mode, every second the
// producer will send a batch of data over. Wait for a second before
// performing readback; do this for each batch the producer sends.
for (uint32_t i = 0; i < number_of_batches; i++) {
auto batch_cname = "batch.checkpoint." + std::to_string(counter);
auto batch_checkpoint = task_runner.CreateCheckpoint(batch_cname);
task_runner.PostDelayedTask(batch_checkpoint, 1000);
task_runner.RunUntilCheckpoint(batch_cname);
int64_t start = base::GetWallTimeNs().count();
helper.ReadData(counter);
helper.WaitForReadData(counter++);
read_time_taken_ns +=
static_cast<uint64_t>(base::GetWallTimeNs().count() - start);
}
}
}
uint64_t service_ns =
helper.service_thread()->GetThreadCPUTimeNs() - service_start_ns;
uint64_t consumer_ns =
static_cast<uint64_t>(base::GetThreadCPUTimeNs().count()) -
consumer_start_ns;
uint64_t wall_ns =
static_cast<uint64_t>(base::GetWallTimeNs().count()) - wall_start_ns;
state.counters["Ser CPU"] = benchmark::Counter(100.0 * service_ns / wall_ns);
state.counters["Ser ns/m"] =
benchmark::Counter(1.0 * service_ns / message_count);
state.counters["Con CPU"] = benchmark::Counter(100.0 * consumer_ns / wall_ns);
state.counters["Con Speed"] =
benchmark::Counter(iterations * 1000.0 * 1000 * 1000 * kBufferSizeBytes /
read_time_taken_ns);
}
void SaturateCpuProducerArgs(benchmark::internal::Benchmark* b) {
int min_message_count = 16;
int max_message_count = IsBenchmarkFunctionalOnly() ? 16 : 1024 * 1024;
int min_payload = 8;
int max_payload = IsBenchmarkFunctionalOnly() ? 8 : 2048;
for (int count = min_message_count; count <= max_message_count; count *= 2) {
for (int bytes = min_payload; bytes <= max_payload; bytes *= 2) {
b->Args({count, bytes, 0 /* speed */});
}
}
}
void ConstantRateProducerArgs(benchmark::internal::Benchmark* b) {
int message_count = IsBenchmarkFunctionalOnly() ? 2 * 1024 : 128 * 1024;
int min_speed = IsBenchmarkFunctionalOnly() ? 64 : 8;
int max_speed = 128;
for (int speed = min_speed; speed <= max_speed; speed *= 2) {
b->Args({message_count, 128, speed});
b->Args({message_count, 256, speed});
}
}
void SaturateCpuConsumerArgs(benchmark::internal::Benchmark* b) {
int min_payload = 8;
int max_payload = IsBenchmarkFunctionalOnly() ? 16 : 64 * 1024;
for (int bytes = min_payload; bytes <= max_payload; bytes *= 2) {
b->Args({bytes, 0 /* speed */});
}
}
void ConstantRateConsumerArgs(benchmark::internal::Benchmark* b) {
int min_speed = IsBenchmarkFunctionalOnly() ? 128 : 1;
int max_speed = IsBenchmarkFunctionalOnly() ? 128 : 2;
for (int speed = min_speed; speed <= max_speed; speed *= 2) {
b->Args({2, speed});
b->Args({4, speed});
}
}
} // namespace
static void BM_EndToEnd_Producer_SaturateCpu(benchmark::State& state) {
BenchmarkProducer(state);
}
BENCHMARK(BM_EndToEnd_Producer_SaturateCpu)
->Unit(benchmark::kMicrosecond)
->UseRealTime()
->Apply(SaturateCpuProducerArgs);
static void BM_EndToEnd_Producer_ConstantRate(benchmark::State& state) {
BenchmarkProducer(state);
}
BENCHMARK(BM_EndToEnd_Producer_ConstantRate)
->Unit(benchmark::kMicrosecond)
->UseRealTime()
->Apply(ConstantRateProducerArgs);
static void BM_EndToEnd_Consumer_SaturateCpu(benchmark::State& state) {
BenchmarkConsumer(state);
}
BENCHMARK(BM_EndToEnd_Consumer_SaturateCpu)
->Unit(benchmark::kMicrosecond)
->UseRealTime()
->Apply(SaturateCpuConsumerArgs);
static void BM_EndToEnd_Consumer_ConstantRate(benchmark::State& state) {
BenchmarkConsumer(state);
}
BENCHMARK(BM_EndToEnd_Consumer_ConstantRate)
->Unit(benchmark::kMillisecond)
->UseRealTime()
->Apply(ConstantRateConsumerArgs);
} // namespace perfetto
<|endoftext|> |
<commit_before>#include "prog_translator.h"
#include <algorithm>
#include "CoinPackedVector.hpp"
#include "OsiSolverInterface.hpp"
#include "cyc_limits.h"
#include "exchange_graph.h"
namespace cyclus {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,
bool exclusive)
: g_(g),
iface_(iface),
excl_(exclusive) {
arc_offset_ = g_->arcs().size();
int n_cols = arc_offset_ + g_->request_groups().size();
ctx_.obj_coeffs.resize(n_cols);
ctx_.col_ubs.resize(n_cols);
ctx_.col_lbs.resize(n_cols);
ctx_.m = CoinPackedMatrix(false, 0, 0);
min_row_coeff_ = std::numeric_limits<double>::max();
max_obj_coeff_ = 0;
cost_add_ = 1;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Translate() {
// number of variables = number of arcs + 1 faux arc per request group
int n_cols = g_->arcs().size() + g_->request_groups().size();
ctx_.m.setDimensions(0, n_cols);
bool request;
std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups();
for (int i = 0; i != sgs.size(); i++) {
request = false;
XlateGrp_(sgs[i].get(), request);
}
std::vector<RequestGroup::Ptr>& rgs = g_->request_groups();
for (int i = 0; i != rgs.size(); i++) {
request = true;
XlateGrp_(rgs[i].get(), request);
}
// add each false arc
double inf = iface_->getInfinity();
double max_cost = max_obj_coeff_ / min_row_coeff_ + cost_add_;
for (int i = g_->arcs().size(); i != arc_offset_; i++) {
ctx_.obj_coeffs[i] = max_cost;
ctx_.col_lbs[i] = 0;
ctx_.col_ubs[i] = inf;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Populate() {
iface_->setObjSense(1.0); // minimize
// load er up!
iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0],
&ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]);
if (excl_) {
std::vector<Arc>& arcs = g_->arcs();
for (int i = 0; i != arcs.size(); i++) {
Arc& a = arcs[i];
if (a.exclusive()) {
iface_->setInteger(g_->arc_ids()[a]);
}
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::ToProg() {
Translate();
Populate();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool request) {
double inf = iface_->getInfinity();
std::vector<double>& caps = grp->capacities();
std::vector<CoinPackedVector> cap_rows;
std::vector<CoinPackedVector> excl_rows;
for (int i = 0; i != caps.size(); i++) {
cap_rows.push_back(CoinPackedVector());
}
std::vector<ExchangeNode::Ptr>& nodes = grp->nodes();
for (int i = 0; i != nodes.size(); i++) {
std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities;
std::map<Arc, std::vector<double> >::iterator cap_it;
// add each arc
for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) {
const Arc& a = cap_it->first;
std::vector<double>& ucaps = cap_it->second;
int arc_id = g_->arc_ids()[a];
// add each unit capacity coefficient
for (int j = 0; j != ucaps.size(); j++) {
double coeff = ucaps[j];
if (excl_ && a.exclusive()) {
coeff *= a.excl_val();
}
cap_rows[j].insert(arc_id, coeff);
double compare = coeff; // caps[j];
if (min_row_coeff_ > compare) {
min_row_coeff_ = compare;
}
}
if (request) {
// add obj coeff for arc
double pref = nodes[i]->prefs[a];
double col_ub = std::min(nodes[i]->qty, inf);
double obj_coeff = a.exclusive() ? a.excl_val() / pref : 1 / pref;
if (max_obj_coeff_ < obj_coeff) {
max_obj_coeff_ = obj_coeff;
}
ctx_.obj_coeffs[arc_id] = obj_coeff;
ctx_.col_lbs[arc_id] = 0;
ctx_.col_ubs[arc_id] = a.exclusive() ? 1 : col_ub;
}
}
}
int faux_id;
if (request) {
faux_id = arc_offset_++;
}
// add all capacity rows
for (int i = 0; i != cap_rows.size(); i++) {
if (request) {
cap_rows[i].insert(faux_id, 1.0); // faux arc
}
ctx_.row_lbs.push_back(request ? caps[i] : 0);
ctx_.row_ubs.push_back(request ? inf : caps[i]);
ctx_.m.appendRow(cap_rows[i]);
}
// add exclusive arcs
std::vector< std::vector<ExchangeNode::Ptr> >& exngs =
grp->excl_node_groups();
for (int i = 0; i != exngs.size(); i++) {
CoinPackedVector excl_row;
std::vector<ExchangeNode::Ptr>& nodes = exngs[i];
for (int j = 0; j != nodes.size(); j++) {
std::vector<Arc>& arcs = g_->node_arc_map()[nodes[j]];
for (int k = 0; k != arcs.size(); k++) {
excl_row.insert(g_->arc_ids()[arcs[k]], 1.0);
}
}
if (excl_row.getNumElements() > 0) {
excl_rows.push_back(excl_row);
}
}
// add all exclusive rows
for (int i = 0; i != excl_rows.size(); i++) {
ctx_.row_lbs.push_back(0.0);
ctx_.row_ubs.push_back(1.0);
ctx_.m.appendRow(excl_rows[i]);
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::FromProg() {
const double* sol = iface_->getColSolution();
std::vector<Arc>& arcs = g_->arcs();
double flow;
for (int i = 0; i < arcs.size(); i++) {
Arc& a = g_->arc_by_id().at(i);
flow = sol[i];
flow = (a.exclusive()) ? flow * a.excl_val() : flow;
if (flow > cyclus::eps()) {
g_->AddMatch(a, flow);
}
}
}
} // namespace cyclus
<commit_msg>fixed bugs where bounds were not being correctly set with non-excl prgo solver<commit_after>#include "prog_translator.h"
#include <algorithm>
#include "CoinPackedVector.hpp"
#include "OsiSolverInterface.hpp"
#include "cyc_limits.h"
#include "exchange_graph.h"
namespace cyclus {
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
ProgTranslator::ProgTranslator(ExchangeGraph* g, OsiSolverInterface* iface,
bool exclusive)
: g_(g),
iface_(iface),
excl_(exclusive) {
arc_offset_ = g_->arcs().size();
int n_cols = arc_offset_ + g_->request_groups().size();
ctx_.obj_coeffs.resize(n_cols);
ctx_.col_ubs.resize(n_cols);
ctx_.col_lbs.resize(n_cols);
ctx_.m = CoinPackedMatrix(false, 0, 0);
min_row_coeff_ = std::numeric_limits<double>::max();
max_obj_coeff_ = 0;
cost_add_ = 1;
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Translate() {
// number of variables = number of arcs + 1 faux arc per request group
int n_cols = g_->arcs().size() + g_->request_groups().size();
ctx_.m.setDimensions(0, n_cols);
bool request;
std::vector<ExchangeNodeGroup::Ptr>& sgs = g_->supply_groups();
for (int i = 0; i != sgs.size(); i++) {
request = false;
XlateGrp_(sgs[i].get(), request);
}
std::vector<RequestGroup::Ptr>& rgs = g_->request_groups();
for (int i = 0; i != rgs.size(); i++) {
request = true;
XlateGrp_(rgs[i].get(), request);
}
// add each false arc
double inf = iface_->getInfinity();
double max_cost = max_obj_coeff_ / min_row_coeff_ + cost_add_;
for (int i = g_->arcs().size(); i != arc_offset_; i++) {
ctx_.obj_coeffs[i] = max_cost;
ctx_.col_lbs[i] = 0;
ctx_.col_ubs[i] = inf;
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::Populate() {
iface_->setObjSense(1.0); // minimize
// load er up!
iface_->loadProblem(ctx_.m, &ctx_.col_lbs[0], &ctx_.col_ubs[0],
&ctx_.obj_coeffs[0], &ctx_.row_lbs[0], &ctx_.row_ubs[0]);
if (excl_) {
std::vector<Arc>& arcs = g_->arcs();
for (int i = 0; i != arcs.size(); i++) {
Arc& a = arcs[i];
if (a.exclusive()) {
iface_->setInteger(g_->arc_ids()[a]);
}
}
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::ToProg() {
Translate();
Populate();
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::XlateGrp_(ExchangeNodeGroup* grp, bool request) {
double inf = iface_->getInfinity();
std::vector<double>& caps = grp->capacities();
std::vector<CoinPackedVector> cap_rows;
std::vector<CoinPackedVector> excl_rows;
for (int i = 0; i != caps.size(); i++) {
cap_rows.push_back(CoinPackedVector());
}
std::vector<ExchangeNode::Ptr>& nodes = grp->nodes();
for (int i = 0; i != nodes.size(); i++) {
std::map<Arc, std::vector<double> >& ucap_map = nodes[i]->unit_capacities;
std::map<Arc, std::vector<double> >::iterator cap_it;
// add each arc
for (cap_it = ucap_map.begin(); cap_it != ucap_map.end(); ++cap_it) {
const Arc& a = cap_it->first;
std::vector<double>& ucaps = cap_it->second;
int arc_id = g_->arc_ids()[a];
// add each unit capacity coefficient
for (int j = 0; j != ucaps.size(); j++) {
double coeff = ucaps[j];
if (excl_ && a.exclusive()) {
coeff *= a.excl_val();
}
cap_rows[j].insert(arc_id, coeff);
double compare = coeff; // caps[j];
if (min_row_coeff_ > compare) {
min_row_coeff_ = compare;
}
}
if (request) {
// add obj coeff for arc
double pref = nodes[i]->prefs[a];
double col_ub = std::min(nodes[i]->qty, inf);
double obj_coeff = (excl_ && a.exclusive()) ? a.excl_val() / pref : 1 / pref;
if (max_obj_coeff_ < obj_coeff) {
max_obj_coeff_ = obj_coeff;
}
ctx_.obj_coeffs[arc_id] = obj_coeff;
ctx_.col_lbs[arc_id] = 0;
ctx_.col_ubs[arc_id] = (excl_ && a.exclusive()) ? 1 : col_ub;
}
}
}
int faux_id;
if (request) {
faux_id = arc_offset_++;
}
// add all capacity rows
for (int i = 0; i != cap_rows.size(); i++) {
if (request) {
cap_rows[i].insert(faux_id, 1.0); // faux arc
}
ctx_.row_lbs.push_back(request ? caps[i] : 0);
ctx_.row_ubs.push_back(request ? inf : caps[i]);
ctx_.m.appendRow(cap_rows[i]);
}
// add exclusive arcs
std::vector< std::vector<ExchangeNode::Ptr> >& exngs =
grp->excl_node_groups();
for (int i = 0; i != exngs.size(); i++) {
CoinPackedVector excl_row;
std::vector<ExchangeNode::Ptr>& nodes = exngs[i];
for (int j = 0; j != nodes.size(); j++) {
std::vector<Arc>& arcs = g_->node_arc_map()[nodes[j]];
for (int k = 0; k != arcs.size(); k++) {
excl_row.insert(g_->arc_ids()[arcs[k]], 1.0);
}
}
if (excl_row.getNumElements() > 0) {
excl_rows.push_back(excl_row);
}
}
// add all exclusive rows
for (int i = 0; i != excl_rows.size(); i++) {
ctx_.row_lbs.push_back(0.0);
ctx_.row_ubs.push_back(1.0);
ctx_.m.appendRow(excl_rows[i]);
}
}
// - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
void ProgTranslator::FromProg() {
const double* sol = iface_->getColSolution();
std::vector<Arc>& arcs = g_->arcs();
double flow;
for (int i = 0; i < arcs.size(); i++) {
Arc& a = g_->arc_by_id().at(i);
flow = sol[i];
flow = (excl_ && a.exclusive()) ? flow * a.excl_val() : flow;
if (flow > cyclus::eps()) {
g_->AddMatch(a, flow);
}
}
}
} // namespace cyclus
<|endoftext|> |
<commit_before>// Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.
// Use of this source code is governed by the BSD license that can be found in
// the LICENSE file.
#include "buffer.h"
#include "testkit.h"
TEST(kl::Buffer, Constructor, 1024) { ASSERT(Cap() == 1024); }
TEST(kl::Buffer, ExtendTo) {
size_t cap = Cap();
ExtendTo(2 * cap);
ASSERT(Cap() == 2 * cap);
ExtendTo(cap);
ASSERT(Cap() == 2 * cap);
}
int main() { return KL_TEST(); }
<commit_msg>add test<commit_after>// Copyright (c) 2017 Kai Luo <gluokai@gmail.com>. All rights reserved.
// Use of this source code is governed by the BSD license that can be found in
// the LICENSE file.
#include "buffer.h"
#include "testkit.h"
TEST(kl::Buffer, Constructor, 1024) { ASSERT(Cap() == 1024); }
TEST(kl::Buffer, ExtendTo) {
size_t cap = Cap();
ExtendTo(2 * cap);
ASSERT(Cap() == 2 * cap);
ExtendTo(cap);
ASSERT(Cap() == 2 * cap);
}
TEST(kl::Buffer, Idle) {
size_t cap = Cap();
ReadFrom("wtf", 3);
Peek(1);
ASSERT(Len() == 2);
ASSERT(Cap() == cap);
ASSERT(1 + Avail() == Idle());
}
int main() { return KL_TEST(); }
<|endoftext|> |
<commit_before>#define PY_ARRAY_UNIQUE_SYMBOL rank_filter_PyArray_API
//#define NO_IMPORT_ARRAY
#include <iostream>
#include <string>
#include <utility>
#include "rank_filter.hxx"
#include <Python.h>
#include <boost/python.hpp>
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
namespace rank_filter
{
template < unsigned int N, class SrcPixelType >
vigra::NumpyAnyArray pythonLineRankOrderFilter(const vigra::NumpyArray< N, vigra::Singleband<SrcPixelType> > & image,
unsigned long half_length, double rank, int axis = N - 1,
vigra::NumpyArray< N, vigra::Singleband<SrcPixelType> > res = boost::python::object())
{
std::string description("rank order filter over 1-Dimension, axis=");
description += vigra::asString(axis);
vigra_precondition((-static_cast<int>(N) <= axis) && (axis < static_cast<int>(N)),
"lineRankOrderFilter(): Axis out of range.");
if (axis < 0)
{
axis += N;
}
vigra_precondition(0 <= half_length,
"lineRankOrderFilter(): Window must be non-negative.");
vigra_precondition((half_length + 1) <= image.shape(axis),
"lineRankOrderFilter(): Window must be no bigger than the image.");
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"lineRankOrderFilter(): Output array has wrong shape.");
{
vigra::PyAllowThreads _pythread;
rank_filter::lineRankOrderFilter(image, res, half_length, rank, static_cast<unsigned int>(axis));
}
return(res);
}
void defineRankFilter()
{
using namespace boost::python;
docstring_options doc_options(true, true, false);
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<1, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(1-1), arg("out")=object()),
"Convolution along a single dimension of a 1D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<2, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(2-1), arg("out")=object()),
"Convolution along a single dimension of a 2D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<3, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(3-1), arg("out")=object()),
"Convolution along a single dimension of a 3D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<4, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(4-1), arg("out")=object()),
"Convolution along a single dimension of a 4D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<5, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(5-1), arg("out")=object()),
"Convolution along a single dimension of a 5D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<1, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(1-1), arg("out")=object()),
"Convolution along a single dimension of a 1D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<2, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(2-1), arg("out")=object()),
"Convolution along a single dimension of a 2D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<3, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(3-1), arg("out")=object()),
"Convolution along a single dimension of a 3D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<4, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(4-1), arg("out")=object()),
"Convolution along a single dimension of a 4D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<5, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(5-1), arg("out")=object()),
"Convolution along a single dimension of a 5D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
}
}
BOOST_PYTHON_MODULE_INIT(rank_filter)
{
vigra::import_vigranumpy();
rank_filter::defineRankFilter();
}
<commit_msg>src/rank_filter_py.cxx: Drop the `iostream` header as it is unused.<commit_after>#define PY_ARRAY_UNIQUE_SYMBOL rank_filter_PyArray_API
//#define NO_IMPORT_ARRAY
#include <string>
#include <utility>
#include "rank_filter.hxx"
#include <Python.h>
#include <boost/python.hpp>
#include <vigra/numpy_array.hxx>
#include <vigra/numpy_array_converters.hxx>
namespace rank_filter
{
template < unsigned int N, class SrcPixelType >
vigra::NumpyAnyArray pythonLineRankOrderFilter(const vigra::NumpyArray< N, vigra::Singleband<SrcPixelType> > & image,
unsigned long half_length, double rank, int axis = N - 1,
vigra::NumpyArray< N, vigra::Singleband<SrcPixelType> > res = boost::python::object())
{
std::string description("rank order filter over 1-Dimension, axis=");
description += vigra::asString(axis);
vigra_precondition((-static_cast<int>(N) <= axis) && (axis < static_cast<int>(N)),
"lineRankOrderFilter(): Axis out of range.");
if (axis < 0)
{
axis += N;
}
vigra_precondition(0 <= half_length,
"lineRankOrderFilter(): Window must be non-negative.");
vigra_precondition((half_length + 1) <= image.shape(axis),
"lineRankOrderFilter(): Window must be no bigger than the image.");
res.reshapeIfEmpty(image.taggedShape().setChannelDescription(description),
"lineRankOrderFilter(): Output array has wrong shape.");
{
vigra::PyAllowThreads _pythread;
rank_filter::lineRankOrderFilter(image, res, half_length, rank, static_cast<unsigned int>(axis));
}
return(res);
}
void defineRankFilter()
{
using namespace boost::python;
docstring_options doc_options(true, true, false);
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<1, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(1-1), arg("out")=object()),
"Convolution along a single dimension of a 1D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<2, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(2-1), arg("out")=object()),
"Convolution along a single dimension of a 2D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<3, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(3-1), arg("out")=object()),
"Convolution along a single dimension of a 3D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<4, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(4-1), arg("out")=object()),
"Convolution along a single dimension of a 4D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<5, float>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(5-1), arg("out")=object()),
"Convolution along a single dimension of a 5D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<1, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(1-1), arg("out")=object()),
"Convolution along a single dimension of a 1D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<2, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(2-1), arg("out")=object()),
"Convolution along a single dimension of a 2D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<3, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(3-1), arg("out")=object()),
"Convolution along a single dimension of a 3D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<4, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(4-1), arg("out")=object()),
"Convolution along a single dimension of a 4D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
def("lineRankOrderFilter",
vigra::registerConverters(&pythonLineRankOrderFilter<5, double>),
(arg("image"), arg("half_length"), arg("rank"), arg("axis")=(5-1), arg("out")=object()),
"Convolution along a single dimension of a 5D scalar or multiband image. "
"'kernel' must be an instance of Kernel1D.\n"
"\n"
"For details see convolveMultiArrayOneDimension_ in the vigra C++ documentation.\n");
}
}
BOOST_PYTHON_MODULE_INIT(rank_filter)
{
vigra::import_vigranumpy();
rank_filter::defineRankFilter();
}
<|endoftext|> |
<commit_before>//
// src/recursive/mkdir.cc
// tbd
//
// Created by inoahdev on 10/15/17.
// Copyright © 2017 - 2018 inoahdev. All rights reserved.
//
#include <cerrno>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "../utils/path.h"
#include "mkdir.h"
namespace recursive::mkdir {
inline bool _create_directory(char *path) noexcept {
return ::mkdir(path, 0755) == 0;
}
inline result create_directories_ignoring_last(char *path, char *path_end, char *begin) noexcept {
auto path_component_end = begin;
do {
auto next_path_component_begin = utils::path::find_end_of_row_of_slashes(path_component_end, path_end);
if (next_path_component_begin == path_end) {
break;
}
auto path_component_end_chr = *path_component_end;
*path_component_end = '\0';
if (!_create_directory(path)) {
return result::failed_to_create_intermediate_directories;
}
*path_component_end = path_component_end_chr;
path_component_end = utils::path::find_next_slash(next_path_component_begin, path_end);
} while (true);
return result::ok;
}
result create_directories_if_missing_ignoring_last(char *path, char **terminator) noexcept {
auto end = utils::string::find_end_of_null_terminated_string(path);
auto &back = end[-1];
// In the case where path ends with a series of slashes
// set end to the front most slash in that series
if (back == '/' || back == '\\') {
end = utils::path::find_last_slash_in_front_of_pattern(path, end);
}
// Start from second-to-last path-component, as we
// are after all, ignoring the last path-component
auto path_component_end = utils::path::find_last_slash_in_front_of_pattern(path, end);
auto prev_path_component_end = end;
// Walk backwards, from the second-to-last
// path-component, all the way back to the first
// This is done in this way so as to minimize
// syscalls on directories that most likely exist
// (the first few path-components) versus those that
// most likely don't exist (the last few path-components)
while (path_component_end != path) {
// Terminate string at path-component end,
// so as to get the entire path of the current
// path-component
auto path_component_end_chr = *path_component_end;
*path_component_end = '\0';
if (access(path, F_OK) == 0) {
// if prev_path_component_end points
// to end,it means we are at the first
// path component, and all path-components,
// save the last, which we are to ignore
// exist
if (prev_path_component_end == end) {
*path_component_end = '/';
break;
}
if (terminator != nullptr) {
*terminator = prev_path_component_end;
}
*path_component_end = path_component_end_chr;
return create_directories_ignoring_last(path, end, prev_path_component_end);
}
prev_path_component_end = path_component_end;
path_component_end = utils::path::find_last_slash_in_front_of_pattern(path, path_component_end);
*prev_path_component_end = path_component_end_chr;
}
return result::ok;
}
result perform(char *path, char **terminator) noexcept {
if (const auto result = create_directories_if_missing_ignoring_last(path, terminator); result != result::ok) {
return result;
}
const auto result = _create_directory(path);
if (result || (!result && errno == EEXIST)) {
if (terminator != nullptr) {
if (*terminator == nullptr) {
*terminator = utils::string::find_end_of_null_terminated_string(path);
}
}
return result::ok;
}
return result::failed_to_create_last_as_directory;
}
result perform_ignorning_last(char *path, char **terminator) noexcept {
return create_directories_if_missing_ignoring_last(path, terminator);
}
result perform_with_last_as_file(char *path, char **terminator, int *last_descriptor) noexcept {
if (const auto result = create_directories_if_missing_ignoring_last(path, terminator); result != result::ok) {
return result;
}
const auto descriptor = open(path, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
if (descriptor == -1) {
if (errno == EEXIST) {
return result::ok;
}
return result::failed_to_create_last_as_file;
}
if (terminator != nullptr) {
if (*terminator == nullptr) {
*terminator = utils::string::find_end_of_null_terminated_string(path);
}
}
if (last_descriptor != nullptr) {
*last_descriptor = descriptor;
} else {
close(descriptor);
}
return result::ok;
}
}
<commit_msg>Change minor details in the implementation of recursive-mkdir<commit_after>//
// src/recursive/mkdir.cc
// tbd
//
// Created by inoahdev on 10/15/17.
// Copyright © 2017 - 2018 inoahdev. All rights reserved.
//
#include <cerrno>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "../utils/path.h"
#include "mkdir.h"
namespace recursive::mkdir {
inline bool _create_directory(char *path) noexcept {
return ::mkdir(path, 0755) == 0;
}
inline result create_directories_ignoring_last(char *path, char *path_end, char *begin) noexcept {
auto path_component_end = begin;
do {
auto next_path_component_begin = utils::path::find_end_of_row_of_slashes(path_component_end, path_end);
if (next_path_component_begin == path_end) {
break;
}
auto path_component_end_chr = *path_component_end;
*path_component_end = '\0';
if (!_create_directory(path)) {
return result::failed_to_create_intermediate_directories;
}
*path_component_end = path_component_end_chr;
path_component_end = utils::path::find_next_slash(next_path_component_begin, path_end);
} while (true);
return result::ok;
}
result create_directories_if_missing_ignoring_last(char *path, char **terminator) noexcept {
auto end = utils::string::find_end_of_null_terminated_string(path);
auto &back = end[-1];
// In the case where path ends with a series of slashes
// set end to the front most slash in that series
if (back == '/' || back == '\\') {
end = utils::path::find_last_slash_in_front_of_pattern(path, end);
}
// Start from second-to-last path-component, as we
// are after all, ignoring the last path-component
auto path_component_end = utils::path::find_last_slash_in_front_of_pattern(path, end);
auto prev_path_component_end = end;
// Walk backwards, from the second-to-last
// path-component, all the way back to the first
// This is done in this way so as to minimize
// syscalls on directories that most likely exist
// (the first few path-components) versus those that
// most likely don't exist (the last few path-components)
while (path_component_end != path) {
// Terminate string at path-component end,
// so as to get the entire path of the current
// path-component
auto path_component_end_chr = *path_component_end;
*path_component_end = '\0';
if (access(path, F_OK) == 0) {
// if prev_path_component_end points
// to end,it means we are at the first
// path component, and all path-components,
// save the last, which we are to ignore
// exist
if (prev_path_component_end == end) {
*path_component_end = '/';
break;
}
if (terminator != nullptr) {
*terminator = prev_path_component_end;
}
*path_component_end = path_component_end_chr;
return create_directories_ignoring_last(path, end, prev_path_component_end);
}
prev_path_component_end = path_component_end;
path_component_end = utils::path::find_last_slash_in_front_of_pattern(path, path_component_end);
*prev_path_component_end = path_component_end_chr;
}
return result::ok;
}
result perform(char *path, char **terminator) noexcept {
if (const auto result = create_directories_if_missing_ignoring_last(path, terminator); result != result::ok) {
return result;
}
if (_create_directory(path)) {
if (terminator != nullptr) {
if (*terminator == nullptr) {
*terminator = utils::string::find_end_of_null_terminated_string(path);
}
}
return result::ok;
}
if (errno == EEXIST) {
return result::ok;
}
return result::failed_to_create_last_as_directory;
}
result perform_ignorning_last(char *path, char **terminator) noexcept {
return create_directories_if_missing_ignoring_last(path, terminator);
}
result perform_with_last_as_file(char *path, char **terminator, int *last_descriptor) noexcept {
if (const auto result = create_directories_if_missing_ignoring_last(path, terminator); result != result::ok) {
return result;
}
const auto descriptor = open(path, O_WRONLY | O_CREAT | O_TRUNC, DEFFILEMODE);
if (descriptor != -1) {
if (terminator != nullptr) {
if (*terminator == nullptr) {
*terminator = utils::string::find_end_of_null_terminated_string(path);
}
}
if (last_descriptor != nullptr) {
*last_descriptor = descriptor;
} else {
close(descriptor);
}
return result::ok;
}
if (errno == EEXIST) {
return result::ok;
}
return result::failed_to_create_last_as_file;
}
}
<|endoftext|> |
<commit_before>/*
* Copyright (c) 2012, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Ana Huaman <ahuaman3@gatech.edu>
* Date: 03-08-2012
*
* Geoorgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* 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.
* 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 HOLDER 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.
**
* @file World.cpp
*/
#include <iostream>
#include "World.h"
#include <kinematics/BodyNode.h>
#include <kinematics/Shape.h>
#include <collision/CollisionSkeleton.h>
#include <integration/EulerIntegrator.h>
#include <dynamics/ContactDynamics.h>
#include <dynamics/SkeletonDynamics.h>
#include <robotics/Robot.h>
using namespace Eigen;
namespace robotics {
/**
* @function World
* @brief Constructor
*/
World::World() :
mTime(0.0),
mTimeStep(0.001)
{
mRobots.resize(0);
mObjects.resize(0);
mSkeletons.resize(0);
mIndices.push_back(0);
mGravity = Eigen::Vector3d(0, 0, -9.81);
}
/**
* @function ~World
* @brief Destructor
*/
World::~World() {
for( size_t i = 0; i < mRobots.size(); ++i ) {
delete mRobots[i];
}
mRobots.clear();
for( size_t i = 0; i < mObjects.size(); ++i ) {
delete mObjects[i];
}
mObjects.clear();
mSkeletons.clear();
}
void World::rebuildCollision()
{
// for(unsigned int i = 0; i < mSkeletons.size(); i++)
// mSkeletons[i]->initDynamics();
mCollisionHandle = new dynamics::ContactDynamics(mSkeletons, mTimeStep);
}
/**
* @function addRobot
* @brief Add a pointer to a new robot in the World
*/
int World::addRobot( Robot* _robot ) {
// add item
mRobots.push_back( _robot );
mSkeletons.push_back( _robot );
_robot->initDynamics();
mIndices.push_back(mIndices.back() + _robot->getNumDofs());
if(!_robot->getImmobileState()) {
_robot->computeDynamics(mGravity, _robot->getQDotVector(), false); // Not sure if we need this
}
// create collision dynamics object
// rebuildCollision();
assert(mObjects.size() + mRobots.size() == mSkeletons.size());
return mRobots.size();
}
/**
* @function addObject
* @brief Add a pointer to a new object in the World
*/
int World::addObject( Robot* _object ) {
// add item
mObjects.push_back( _object );
mSkeletons.push_back( _object );
_object->initDynamics();
mIndices.push_back(mIndices.back() + _object->getNumDofs());
if(!_object->getImmobileState()) {
_object->computeDynamics(mGravity, _object->getQDotVector(), false); // Not sure if we need this
}
// create collision dynanmics object
// rebuildCollision();
assert(mObjects.size() + mRobots.size() == mSkeletons.size());
return mObjects.size();
}
/**
* @function printInfo
* @brief Print info w.r.t. robots and objects in World
*/
void World::printInfo() {
std::cout << "* World Info * " << std::endl;
std::cout << "----------------------" << std::endl;
//-- Robots
for( size_t i = 0; i < mRobots.size(); ++i ) {
std::cout << "* Robot["<<i<<"]: "<< mRobots[i]->getName()<<" : "<< mRobots[i]->getNumDofs() <<" DOFs " << std::endl;
}
//-- Objects
for( size_t i = 0; i < mObjects.size(); ++i ) {
std::cout << "* Object["<<i<<"]: "<< mObjects[i]->getName() << std::endl;
}
}
/**
* @function getObject
*/
Robot* World::getObject( int _i ) {
return mObjects[_i];
}
/**
* @function getRobot
*/
Robot* World::getRobot( int _i ) {
return mRobots[_i];
}
/**
* @function getSkeleton
*/
dynamics::SkeletonDynamics* World::getSkeleton( int _i ) {
return mSkeletons[_i];
}
dynamics::SkeletonDynamics* World::getSkeleton(const std::string& _name) {\
for(unsigned int i = 0; i < mSkeletons.size(); i++) {
if(mSkeletons[i]->getName().compare(_name) == 0) {
return mSkeletons[i];
}
}
return NULL;
}
bool World::checkCollision(bool checkAllCollisions) {
return mCollisionHandle->getCollisionChecker()->checkCollision(checkAllCollisions, false);
}
void World::step() {
mIntegrator.integrate(this, mTimeStep);
mTime += mTimeStep;
}
VectorXd World::getState() {
VectorXd state(mIndices.back() * 2);
for (int i = 0; i < getNumSkeletons(); i++) {
int start = mIndices[i] * 2;
int size = getSkeleton(i)->getNumDofs();
state.segment(start, size) = getSkeleton(i)->getPose();
state.segment(start + size, size) = getSkeleton(i)->getQDotVector();
}
return state;
}
VectorXd World::evalDeriv() {
// compute contact forces
mCollisionHandle->applyContactForces();
// compute derivatives for integration
VectorXd deriv = VectorXd::Zero(mIndices.back() * 2);
for (int i = 0; i < getNumSkeletons(); i++) {
// skip immobile objects in forward simulation
if (getSkeleton(i)->getImmobileState())
continue;
int start = mIndices[i] * 2;
int size = getSkeleton(i)->getNumDofs();
VectorXd qddot = getSkeleton(i)->getMassMatrix().fullPivHouseholderQr().solve(
- getSkeleton(i)->getCombinedVector() + getSkeleton(i)->getExternalForces()
+ mCollisionHandle->getConstraintForce(i) + getSkeleton(i)->getInternalForces());
deriv.segment(start, size) = getSkeleton(i)->getQDotVector() + (qddot * mTimeStep); // set velocities
deriv.segment(start + size, size) = qddot; // set qddot (accelerations)
}
return deriv;
}
void World::setState(const VectorXd &newState) {
for (int i = 0; i < getNumSkeletons(); i++) {
int start = mIndices[i] * 2;
int size = getSkeleton(i)->getNumDofs();
VectorXd pose = newState.segment(start, size);
VectorXd qDot = newState.segment(start + size, size);
getSkeleton(i)->clampRotation(pose, qDot);
if (getSkeleton(i)->getImmobileState()) {
// need to update node transformation for collision
getSkeleton(i)->setPose(pose, true, false);
} else {
// need to update first derivatives for collision
getSkeleton(i)->setPose(pose, false, true);
getSkeleton(i)->computeDynamics(mGravity, qDot, true);
}
}
}
} // end namespace robotics
// Local Variables:
// c-basic-offset: 2
// End:
<commit_msg>When calling Skeleton::setPose() we do not need to calculate the Jacobians since that is also done by SkeletonDynamics::computeDynamics()<commit_after>/*
* Copyright (c) 2012, Georgia Tech Research Corporation
* All rights reserved.
*
* Author(s): Ana Huaman <ahuaman3@gatech.edu>
* Date: 03-08-2012
*
* Geoorgia Tech Graphics Lab and Humanoid Robotics Lab
*
* Directed by Prof. C. Karen Liu and Prof. Mike Stilman
* <karenliu@cc.gatech.edu> <mstilman@cc.gatech.edu>
*
* This file is provided under the following "BSD-style" License:
* 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.
* 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 HOLDER 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.
**
* @file World.cpp
*/
#include <iostream>
#include "World.h"
#include <kinematics/BodyNode.h>
#include <kinematics/Shape.h>
#include <collision/CollisionSkeleton.h>
#include <integration/EulerIntegrator.h>
#include <dynamics/ContactDynamics.h>
#include <dynamics/SkeletonDynamics.h>
#include <robotics/Robot.h>
using namespace Eigen;
namespace robotics {
/**
* @function World
* @brief Constructor
*/
World::World() :
mTime(0.0),
mTimeStep(0.001)
{
mRobots.resize(0);
mObjects.resize(0);
mSkeletons.resize(0);
mIndices.push_back(0);
mGravity = Eigen::Vector3d(0, 0, -9.81);
}
/**
* @function ~World
* @brief Destructor
*/
World::~World() {
for( size_t i = 0; i < mRobots.size(); ++i ) {
delete mRobots[i];
}
mRobots.clear();
for( size_t i = 0; i < mObjects.size(); ++i ) {
delete mObjects[i];
}
mObjects.clear();
mSkeletons.clear();
}
void World::rebuildCollision()
{
// for(unsigned int i = 0; i < mSkeletons.size(); i++)
// mSkeletons[i]->initDynamics();
mCollisionHandle = new dynamics::ContactDynamics(mSkeletons, mTimeStep);
}
/**
* @function addRobot
* @brief Add a pointer to a new robot in the World
*/
int World::addRobot( Robot* _robot ) {
// add item
mRobots.push_back( _robot );
mSkeletons.push_back( _robot );
_robot->initDynamics();
mIndices.push_back(mIndices.back() + _robot->getNumDofs());
if(!_robot->getImmobileState()) {
_robot->computeDynamics(mGravity, _robot->getQDotVector(), false); // Not sure if we need this
}
// create collision dynamics object
// rebuildCollision();
assert(mObjects.size() + mRobots.size() == mSkeletons.size());
return mRobots.size();
}
/**
* @function addObject
* @brief Add a pointer to a new object in the World
*/
int World::addObject( Robot* _object ) {
// add item
mObjects.push_back( _object );
mSkeletons.push_back( _object );
_object->initDynamics();
mIndices.push_back(mIndices.back() + _object->getNumDofs());
if(!_object->getImmobileState()) {
_object->computeDynamics(mGravity, _object->getQDotVector(), false); // Not sure if we need this
}
// create collision dynanmics object
// rebuildCollision();
assert(mObjects.size() + mRobots.size() == mSkeletons.size());
return mObjects.size();
}
/**
* @function printInfo
* @brief Print info w.r.t. robots and objects in World
*/
void World::printInfo() {
std::cout << "* World Info * " << std::endl;
std::cout << "----------------------" << std::endl;
//-- Robots
for( size_t i = 0; i < mRobots.size(); ++i ) {
std::cout << "* Robot["<<i<<"]: "<< mRobots[i]->getName()<<" : "<< mRobots[i]->getNumDofs() <<" DOFs " << std::endl;
}
//-- Objects
for( size_t i = 0; i < mObjects.size(); ++i ) {
std::cout << "* Object["<<i<<"]: "<< mObjects[i]->getName() << std::endl;
}
}
/**
* @function getObject
*/
Robot* World::getObject( int _i ) {
return mObjects[_i];
}
/**
* @function getRobot
*/
Robot* World::getRobot( int _i ) {
return mRobots[_i];
}
/**
* @function getSkeleton
*/
dynamics::SkeletonDynamics* World::getSkeleton( int _i ) {
return mSkeletons[_i];
}
dynamics::SkeletonDynamics* World::getSkeleton(const std::string& _name) {\
for(unsigned int i = 0; i < mSkeletons.size(); i++) {
if(mSkeletons[i]->getName().compare(_name) == 0) {
return mSkeletons[i];
}
}
return NULL;
}
bool World::checkCollision(bool checkAllCollisions) {
return mCollisionHandle->getCollisionChecker()->checkCollision(checkAllCollisions, false);
}
void World::step() {
mIntegrator.integrate(this, mTimeStep);
mTime += mTimeStep;
}
VectorXd World::getState() {
VectorXd state(mIndices.back() * 2);
for (int i = 0; i < getNumSkeletons(); i++) {
int start = mIndices[i] * 2;
int size = getSkeleton(i)->getNumDofs();
state.segment(start, size) = getSkeleton(i)->getPose();
state.segment(start + size, size) = getSkeleton(i)->getQDotVector();
}
return state;
}
VectorXd World::evalDeriv() {
// compute contact forces
mCollisionHandle->applyContactForces();
// compute derivatives for integration
VectorXd deriv = VectorXd::Zero(mIndices.back() * 2);
for (int i = 0; i < getNumSkeletons(); i++) {
// skip immobile objects in forward simulation
if (getSkeleton(i)->getImmobileState())
continue;
int start = mIndices[i] * 2;
int size = getSkeleton(i)->getNumDofs();
VectorXd qddot = getSkeleton(i)->getMassMatrix().fullPivHouseholderQr().solve(
- getSkeleton(i)->getCombinedVector() + getSkeleton(i)->getExternalForces()
+ mCollisionHandle->getConstraintForce(i) + getSkeleton(i)->getInternalForces());
deriv.segment(start, size) = getSkeleton(i)->getQDotVector() + (qddot * mTimeStep); // set velocities
deriv.segment(start + size, size) = qddot; // set qddot (accelerations)
}
return deriv;
}
void World::setState(const VectorXd &newState) {
for (int i = 0; i < getNumSkeletons(); i++) {
int start = mIndices[i] * 2;
int size = getSkeleton(i)->getNumDofs();
VectorXd pose = newState.segment(start, size);
VectorXd qDot = newState.segment(start + size, size);
getSkeleton(i)->clampRotation(pose, qDot);
if (getSkeleton(i)->getImmobileState()) {
// need to update node transformation for collision
getSkeleton(i)->setPose(pose, true, false);
} else {
// need to update first derivatives for collision
getSkeleton(i)->setPose(pose, false, false);
getSkeleton(i)->computeDynamics(mGravity, qDot, true);
}
}
}
} // end namespace robotics
// Local Variables:
// c-basic-offset: 2
// End:
<|endoftext|> |
<commit_before>#include "cinder/app/AppBasic.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "cinder/Timeline.h"
using namespace ci;
using namespace ci::app;
using namespace std;
// Simple class to demonstrate custom lerping
struct Box {
Box() : mColor( Color( 1, 0.5f, 0.25f ) ), mPos( 320, 240 ), mSize( 10, 10 ) {}
Box( Color color, vec2 pos, vec2 size )
: mColor( color ), mPos( pos ), mSize( size )
{}
void draw() const {
gl::color( mColor );
gl::drawSolidRect( Rectf( mPos, mPos + mSize ) );
}
Color mColor;
vec2 mPos, mSize;
};
// custom lerp function which simply lerps all of the member variables individually
Box boxLerp( const Box &start, const Box &end, float t )
{
return Box( lerp( start.mColor, end.mColor, t ), lerp( start.mPos, end.mPos, t), lerp( start.mSize, end.mSize, t ) );
}
class CustomLerpApp : public AppBasic {
public:
void setup();
void mouseDown( MouseEvent event );
Box randomBox( vec2 center );
void draw();
Anim<Box> mBox;
};
void CustomLerpApp::setup()
{
mBox = randomBox( getWindowCenter() );
}
void CustomLerpApp::mouseDown( MouseEvent event )
{
timeline().apply( &mBox, randomBox( event.getPos() ), 2.0f, EaseOutCubic(), boxLerp );
}
Box CustomLerpApp::randomBox( vec2 center )
{
Color color( CM_HSV, Rand::randFloat(), 1, 1 );
float size( Rand::randFloat( 20, 40 ) );
vec2 pos = center - vec2( size, size ) / 2;
return Box( color, pos, vec2( size, size ) );
}
void CustomLerpApp::draw()
{
// clear out the window with black
gl::clear( Color( 0.7f, 0.7f, 0.7f ) );
mBox().draw();
}
CINDER_APP_BASIC( CustomLerpApp, RendererGl )
<commit_msg>Fix CustomLerp for glm.<commit_after>#include "cinder/app/AppBasic.h"
#include "cinder/app/RendererGl.h"
#include "cinder/gl/gl.h"
#include "cinder/Rand.h"
#include "cinder/Timeline.h"
using namespace ci;
using namespace ci::app;
using namespace std;
// Simple class to demonstrate custom lerping
struct Box {
Box() : mColor( Color( 1, 0.5f, 0.25f ) ), mPos( 320, 240 ), mSize( 10, 10 ) {}
Box( Color color, vec2 pos, vec2 size )
: mColor( color ), mPos( pos ), mSize( size )
{}
void draw() const {
gl::color( mColor );
gl::drawSolidRect( Rectf( mPos, mPos + mSize ) );
}
Color mColor;
vec2 mPos, mSize;
};
// custom lerp function which simply lerps all of the member variables individually
Box boxLerp( const Box &start, const Box &end, float t )
{
return Box( lerp( start.mColor, end.mColor, t ), lerp( start.mPos, end.mPos, t), lerp( start.mSize, end.mSize, t ) );
}
class CustomLerpApp : public AppBasic {
public:
void setup();
void mouseDown( MouseEvent event );
Box randomBox( vec2 center );
void draw();
Anim<Box> mBox;
};
void CustomLerpApp::setup()
{
mBox = randomBox( getWindowCenter() );
}
void CustomLerpApp::mouseDown( MouseEvent event )
{
timeline().apply( &mBox, randomBox( event.getPos() ), 2.0f, EaseOutCubic(), boxLerp );
}
Box CustomLerpApp::randomBox( vec2 center )
{
Color color( CM_HSV, Rand::randFloat(), 1, 1 );
float size( Rand::randFloat( 20, 40 ) );
vec2 pos = center - vec2( size, size ) / 2.0f;
return Box( color, pos, vec2( size, size ) );
}
void CustomLerpApp::draw()
{
// clear out the window with black
gl::clear( Color( 0.7f, 0.7f, 0.7f ) );
mBox().draw();
}
CINDER_APP_BASIC( CustomLerpApp, RendererGl )
<|endoftext|> |
<commit_before>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "Filter.h"
#include "../query_framework/QueryRegistry.h"
#include "../query_framework/QueryParsingException.h"
#include "ModelBase/src/util/SymbolMatcher.h"
namespace InformationScripting {
Optional<TupleSet> Filter::executeLinear(TupleSet input)
{
auto filterTag = arguments_.positionalArgument(0);
auto filterBy = removeOuterQuotes(arguments_.positionalArgument(1));
if (!filterTag.contains("."))
return {"filter: requires tagged value to filter by, i.e. tag.value."};
auto tagParts = filterTag.split(".");
if (tagParts.size() > 2)
return {"filter: tagged value should contain a single dot"};
QString tupleTag = tagParts[0];
QString tupleValueTag = tagParts[1];
TupleSet result;
for (const auto& candidate : input.take(tupleTag))
{
auto it = candidate.find(tupleValueTag);
if (it == candidate.end())
return {QString("Tuple %1 does not contain %2").arg(tupleTag, tupleValueTag)};
Property value = it->second;
if (!value.isConvertibleTo<QString>())
return {"filter only works on string values"};
QString valueString = value;
auto matcher = Model::SymbolMatcher::guessMatcher(filterBy);
if (matcher.matches(valueString))
result.add(candidate);
}
return result;
}
void Filter::registerDefaultQueries()
{
QueryRegistry::registerQuery<Filter>("filter");
}
Filter::Filter(Model::Node* target, QStringList args)
: LinearQuery{target}, arguments_{{
PositionalArgument{"tag", "The tag to filter on"},
PositionalArgument{"by", "The value by which we should filter"}
}, args}
{
if (arguments_.numPositionalArguments() < 2)
throw QueryParsingException(arguments_.queryName() + " Requires two arguments");
}
QString Filter::removeOuterQuotes(const QString& from)
{
QString result = from;
if (result.startsWith("\""))
result = result.mid(1);
if (result.endsWith("\""))
result = result.left(result.size() - 1);
return result;
}
} /* namespace InformationScripting */
<commit_msg>Make it possible to only filter by tag.<commit_after>/***********************************************************************************************************************
**
** Copyright (c) 2011, 2015 ETH Zurich
** All rights reserved.
**
** Redistribution and use in source and binary forms, with or without modification, are permitted provided that the
** following conditions are met:
**
** * Redistributions of source code must retain the above copyright notice, this list of conditions and the following
** disclaimer.
** * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the
** following disclaimer in the documentation and/or other materials provided with the distribution.
** * Neither the name of the ETH Zurich 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 HOLDER OR CONTRIBUTORS BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL,
** SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
** SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY,
** WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE
** OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
**
***********************************************************************************************************************/
#include "Filter.h"
#include "../query_framework/QueryRegistry.h"
#include "../query_framework/QueryParsingException.h"
#include "ModelBase/src/util/SymbolMatcher.h"
namespace InformationScripting {
Optional<TupleSet> Filter::executeLinear(TupleSet input)
{
auto filterTag = arguments_.positionalArgument(0);
if (!filterTag.contains("."))
return {"filter: requires tagged value to filter by, i.e. tag.value."};
auto tagParts = filterTag.split(".");
QString tupleTag = tagParts[0];
if (tagParts.size() < 2)
return TupleSet(input.take(tupleTag).toList());
if (arguments_.numPositionalArguments() < 2)
return {"filter: when filtering by value, a value is required."};
auto filterBy = removeOuterQuotes(arguments_.positionalArgument(1));
QString tupleValueTag = tagParts[1];
TupleSet result;
for (const auto& candidate : input.take(tupleTag))
{
auto it = candidate.find(tupleValueTag);
if (it == candidate.end())
return {QString("Tuple %1 does not contain %2").arg(tupleTag, tupleValueTag)};
Property value = it->second;
if (!value.isConvertibleTo<QString>())
return {"filter only works on string values"};
QString valueString = value;
auto matcher = Model::SymbolMatcher::guessMatcher(filterBy);
if (matcher.matches(valueString))
result.add(candidate);
}
return result;
}
void Filter::registerDefaultQueries()
{
QueryRegistry::registerQuery<Filter>("filter");
}
Filter::Filter(Model::Node* target, QStringList args)
: LinearQuery{target}, arguments_{{
PositionalArgument{"tag", "The tag to filter on"},
PositionalArgument{"by", "The value by which we should filter"}
}, args}
{
if (arguments_.numPositionalArguments() < 1)
throw QueryParsingException(arguments_.queryName() + " Requires at least one arguments");
}
QString Filter::removeOuterQuotes(const QString& from)
{
QString result = from;
if (result.startsWith("\""))
result = result.mid(1);
if (result.endsWith("\""))
result = result.left(result.size() - 1);
return result;
}
} /* namespace InformationScripting */
<|endoftext|> |
<commit_before>#include "Halide.h"
using namespace Halide;
int main(int argc, char** argv) {
ImageParam input1(type_of<float>(), 1);
ImageParam input2(type_of<float>(), 2);
Func output{"output"};
Var x{"x"}, y{"y"};
Expr a = input1(0);
Expr b = input2(x, y);
output(x, y) = a - a * b;
output.vectorize(x, 8, TailStrategy::GuardWithIf);
output.compile_to_static_library("tst", {input1, input2});
printf("Success!\n");
return 0;
}
<commit_msg>Remove broken test<commit_after><|endoftext|> |
<commit_before>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/native_theme_chromeos.h"
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "gfx/insets.h"
#include "gfx/rect.h"
#include "gfx/size.h"
#include "gfx/skbitmap_operations.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkShader.h"
namespace {
bool IntersectsClipRectInt(
skia::PlatformCanvas* canvas, int x, int y, int w, int h) {
SkRect clip;
return canvas->getClipBounds(&clip) &&
clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w),
SkIntToScalar(y + h));
}
void DrawBitmapInt(
skia::PlatformCanvas* canvas, const SkBitmap& bitmap,
int src_x, int src_y, int src_w, int src_h,
int dest_x, int dest_y, int dest_w, int dest_h) {
DLOG_ASSERT(src_x + src_w < std::numeric_limits<int16_t>::max() &&
src_y + src_h < std::numeric_limits<int16_t>::max());
if (src_w <= 0 || src_h <= 0 || dest_w <= 0 || dest_h <= 0) {
NOTREACHED() << "Attempting to draw bitmap to/from an empty rect!";
return;
}
if (!IntersectsClipRectInt(canvas, dest_x, dest_y, dest_w, dest_h))
return;
SkRect dest_rect = { SkIntToScalar(dest_x),
SkIntToScalar(dest_y),
SkIntToScalar(dest_x + dest_w),
SkIntToScalar(dest_y + dest_h) };
if (src_w == dest_w && src_h == dest_h) {
// Workaround for apparent bug in Skia that causes image to occasionally
// shift.
SkIRect src_rect = { src_x, src_y, src_x + src_w, src_y + src_h };
canvas->drawBitmapRect(bitmap, &src_rect, dest_rect);
return;
}
// Make a bitmap shader that contains the bitmap we want to draw. This is
// basically what SkCanvas.drawBitmap does internally, but it gives us
// more control over quality and will use the mipmap in the source image if
// it has one, whereas drawBitmap won't.
SkShader* shader = SkShader::CreateBitmapShader(bitmap,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkMatrix shader_scale;
shader_scale.setScale(SkFloatToScalar(static_cast<float>(dest_w) / src_w),
SkFloatToScalar(static_cast<float>(dest_h) / src_h));
shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y));
shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y));
shader->setLocalMatrix(shader_scale);
// The rect will be filled by the bitmap.
SkPaint p;
p.setFilterBitmap(true);
p.setShader(shader);
shader->unref();
canvas->drawRect(dest_rect, p);
}
}
/* static */
gfx::NativeThemeLinux* gfx::NativeThemeLinux::instance() {
// The global NativeThemeChromeos instance.
static NativeThemeChromeos s_native_theme;
return &s_native_theme;
}
NativeThemeChromeos::NativeThemeChromeos() {
}
NativeThemeChromeos::~NativeThemeChromeos() {
}
gfx::Size NativeThemeChromeos::GetSize(Part part) const {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int scrollbar_width = rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND)->width();
int width = 0, height = 0;
switch (part) {
case kScrollbarUpArrow:
width = scrollbar_width;
height = rb.GetBitmapNamed(IDR_SCROLL_ARROW_UP)->height();
break;
case kScrollbarDownArrow:
width = scrollbar_width;
height = rb.GetBitmapNamed(IDR_SCROLL_ARROW_DOWN)->height();
break;
case kScrollbarLeftArrow:
width = rb.GetBitmapNamed(IDR_SCROLL_ARROW_UP)->height();
height = scrollbar_width;
break;
case kScrollbarRightArrow:
width = rb.GetBitmapNamed(IDR_SCROLL_ARROW_DOWN)->height();
height = scrollbar_width;
break;
case kScrollbarHorizontalTrack:
width = 0;
height = scrollbar_width;
break;
case kScrollbarVerticalTrack:
width = scrollbar_width;
height = 0;
break;
case kScrollbarHorizontalThumb:
case kScrollbarVerticalThumb:
// allow thumb to be square but no shorter.
width = scrollbar_width;
height = scrollbar_width;
break;
}
return gfx::Size(width, height);
}
void NativeThemeChromeos::PaintTrack(skia::PlatformCanvas* canvas,
Part part, State state,
const ScrollbarTrackExtraParams& extra_params, const gfx::Rect& rect) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
if (part == kScrollbarVerticalTrack) {
SkBitmap* background =
rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND);
SkBitmap* border_up =
rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_UP);
SkBitmap* border_down =
rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_DOWN);
// Draw track background.
DrawBitmapInt(
canvas, *background,
0, 0, background->width(), 1,
rect.x(), rect.y(), rect.width(), rect.height());
// Draw up button lower border.
canvas->drawBitmap(*border_up, extra_params.track_x, extra_params.track_y);
// Draw down button upper border.
canvas->drawBitmap(
*border_down,
extra_params.track_x,
extra_params.track_y + extra_params.track_height - border_down->height()
);
} else {
SkBitmap* background =
GetHorizontalBitmapNamed(IDR_SCROLL_BACKGROUND);
SkBitmap* border_left =
GetHorizontalBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_UP);
SkBitmap* border_right =
GetHorizontalBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_DOWN);
// Draw track background.
DrawBitmapInt(
canvas, *background,
0, 0, 1, background->height(),
rect.x(), rect.y(), rect.width(), rect.height());
// Draw left button right border.
canvas->drawBitmap(*border_left,extra_params.track_x, extra_params.track_y);
// Draw right button left border.
canvas->drawBitmap(
*border_right,
extra_params.track_x + extra_params.track_width - border_right->width(),
extra_params.track_y);
}
}
void NativeThemeChromeos::PaintThumb(skia::PlatformCanvas* canvas,
Part part, State state, const gfx::Rect& rect) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int resource_id = IDR_SCROLL_THUMB;
if (state == kHover)
resource_id++;
else if (state == kPressed)
resource_id += 2;
if (part == kScrollbarVerticalThumb) {
SkBitmap* bitmap = rb.GetBitmapNamed(resource_id);
// Top
DrawBitmapInt(
canvas, *bitmap,
0, 1, bitmap->width(), 5,
rect.x(), rect.y(), rect.width(), 5);
// Middle
DrawBitmapInt(
canvas, *bitmap,
0, 7, bitmap->width(), 1,
rect.x(), rect.y() + 5, rect.width(), rect.height() - 10);
// Bottom
DrawBitmapInt(
canvas, *bitmap,
0, 8, bitmap->width(), 5,
rect.x(), rect.y() + rect.height() - 5, rect.width(), 5);
} else {
SkBitmap* bitmap = GetHorizontalBitmapNamed(resource_id);
// Left
DrawBitmapInt(
canvas, *bitmap,
1, 0, 5, bitmap->height(),
rect.x(), rect.y(), 5, rect.height());
// Middle
DrawBitmapInt(
canvas, *bitmap,
7, 0, 1, bitmap->height(),
rect.x() + 5, rect.y(), rect.width() - 10, rect.height());
// Right
DrawBitmapInt(
canvas, *bitmap,
8, 0, 5, bitmap->height(),
rect.x() + rect.width() - 5, rect.y(), 5, rect.height());
}
}
void NativeThemeChromeos::PaintArrowButton(skia::PlatformCanvas* canvas,
const gfx::Rect& rect, Part part, State state) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int resource_id =
(part == kScrollbarUpArrow || part == kScrollbarLeftArrow) ?
IDR_SCROLL_ARROW_UP : IDR_SCROLL_ARROW_DOWN;
if (state == kHover)
resource_id++;
else if (state == kPressed)
resource_id += 2;
SkBitmap* bitmap;
if (part == kScrollbarUpArrow || part == kScrollbarDownArrow)
bitmap = rb.GetBitmapNamed(resource_id);
else
bitmap = GetHorizontalBitmapNamed(resource_id);
canvas->drawBitmap(*bitmap, rect.x(), rect.y());
}
SkBitmap* NativeThemeChromeos::GetHorizontalBitmapNamed(int resource_id) {
SkImageMap::const_iterator found = horizontal_bitmaps_.find(resource_id);
if (found != horizontal_bitmaps_.end())
return found->second;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SkBitmap* vertical_bitmap = rb.GetBitmapNamed(resource_id);
if (vertical_bitmap) {
SkBitmap transposed_bitmap =
SkBitmapOperations::CreateTransposedBtmap(*vertical_bitmap);
SkBitmap* horizontal_bitmap = new SkBitmap(transposed_bitmap);
horizontal_bitmaps_[resource_id] = horizontal_bitmap;
return horizontal_bitmap;
}
return NULL;
}
<commit_msg>Add limits include for arm compiler to fix build break. TBR: piman BUG=None TEST=None<commit_after>// Copyright (c) 2010 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.
#include "chrome/browser/chromeos/native_theme_chromeos.h"
#include <limits>
#include "app/resource_bundle.h"
#include "base/logging.h"
#include "gfx/insets.h"
#include "gfx/rect.h"
#include "gfx/size.h"
#include "gfx/skbitmap_operations.h"
#include "grit/theme_resources.h"
#include "third_party/skia/include/core/SkShader.h"
namespace {
bool IntersectsClipRectInt(
skia::PlatformCanvas* canvas, int x, int y, int w, int h) {
SkRect clip;
return canvas->getClipBounds(&clip) &&
clip.intersect(SkIntToScalar(x), SkIntToScalar(y), SkIntToScalar(x + w),
SkIntToScalar(y + h));
}
void DrawBitmapInt(
skia::PlatformCanvas* canvas, const SkBitmap& bitmap,
int src_x, int src_y, int src_w, int src_h,
int dest_x, int dest_y, int dest_w, int dest_h) {
DLOG_ASSERT(src_x + src_w < std::numeric_limits<int16_t>::max() &&
src_y + src_h < std::numeric_limits<int16_t>::max());
if (src_w <= 0 || src_h <= 0 || dest_w <= 0 || dest_h <= 0) {
NOTREACHED() << "Attempting to draw bitmap to/from an empty rect!";
return;
}
if (!IntersectsClipRectInt(canvas, dest_x, dest_y, dest_w, dest_h))
return;
SkRect dest_rect = { SkIntToScalar(dest_x),
SkIntToScalar(dest_y),
SkIntToScalar(dest_x + dest_w),
SkIntToScalar(dest_y + dest_h) };
if (src_w == dest_w && src_h == dest_h) {
// Workaround for apparent bug in Skia that causes image to occasionally
// shift.
SkIRect src_rect = { src_x, src_y, src_x + src_w, src_y + src_h };
canvas->drawBitmapRect(bitmap, &src_rect, dest_rect);
return;
}
// Make a bitmap shader that contains the bitmap we want to draw. This is
// basically what SkCanvas.drawBitmap does internally, but it gives us
// more control over quality and will use the mipmap in the source image if
// it has one, whereas drawBitmap won't.
SkShader* shader = SkShader::CreateBitmapShader(bitmap,
SkShader::kRepeat_TileMode,
SkShader::kRepeat_TileMode);
SkMatrix shader_scale;
shader_scale.setScale(SkFloatToScalar(static_cast<float>(dest_w) / src_w),
SkFloatToScalar(static_cast<float>(dest_h) / src_h));
shader_scale.preTranslate(SkIntToScalar(-src_x), SkIntToScalar(-src_y));
shader_scale.postTranslate(SkIntToScalar(dest_x), SkIntToScalar(dest_y));
shader->setLocalMatrix(shader_scale);
// The rect will be filled by the bitmap.
SkPaint p;
p.setFilterBitmap(true);
p.setShader(shader);
shader->unref();
canvas->drawRect(dest_rect, p);
}
}
/* static */
gfx::NativeThemeLinux* gfx::NativeThemeLinux::instance() {
// The global NativeThemeChromeos instance.
static NativeThemeChromeos s_native_theme;
return &s_native_theme;
}
NativeThemeChromeos::NativeThemeChromeos() {
}
NativeThemeChromeos::~NativeThemeChromeos() {
}
gfx::Size NativeThemeChromeos::GetSize(Part part) const {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int scrollbar_width = rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND)->width();
int width = 0, height = 0;
switch (part) {
case kScrollbarUpArrow:
width = scrollbar_width;
height = rb.GetBitmapNamed(IDR_SCROLL_ARROW_UP)->height();
break;
case kScrollbarDownArrow:
width = scrollbar_width;
height = rb.GetBitmapNamed(IDR_SCROLL_ARROW_DOWN)->height();
break;
case kScrollbarLeftArrow:
width = rb.GetBitmapNamed(IDR_SCROLL_ARROW_UP)->height();
height = scrollbar_width;
break;
case kScrollbarRightArrow:
width = rb.GetBitmapNamed(IDR_SCROLL_ARROW_DOWN)->height();
height = scrollbar_width;
break;
case kScrollbarHorizontalTrack:
width = 0;
height = scrollbar_width;
break;
case kScrollbarVerticalTrack:
width = scrollbar_width;
height = 0;
break;
case kScrollbarHorizontalThumb:
case kScrollbarVerticalThumb:
// allow thumb to be square but no shorter.
width = scrollbar_width;
height = scrollbar_width;
break;
}
return gfx::Size(width, height);
}
void NativeThemeChromeos::PaintTrack(skia::PlatformCanvas* canvas,
Part part, State state,
const ScrollbarTrackExtraParams& extra_params, const gfx::Rect& rect) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
if (part == kScrollbarVerticalTrack) {
SkBitmap* background =
rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND);
SkBitmap* border_up =
rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_UP);
SkBitmap* border_down =
rb.GetBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_DOWN);
// Draw track background.
DrawBitmapInt(
canvas, *background,
0, 0, background->width(), 1,
rect.x(), rect.y(), rect.width(), rect.height());
// Draw up button lower border.
canvas->drawBitmap(*border_up, extra_params.track_x, extra_params.track_y);
// Draw down button upper border.
canvas->drawBitmap(
*border_down,
extra_params.track_x,
extra_params.track_y + extra_params.track_height - border_down->height()
);
} else {
SkBitmap* background =
GetHorizontalBitmapNamed(IDR_SCROLL_BACKGROUND);
SkBitmap* border_left =
GetHorizontalBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_UP);
SkBitmap* border_right =
GetHorizontalBitmapNamed(IDR_SCROLL_BACKGROUND_BORDER_DOWN);
// Draw track background.
DrawBitmapInt(
canvas, *background,
0, 0, 1, background->height(),
rect.x(), rect.y(), rect.width(), rect.height());
// Draw left button right border.
canvas->drawBitmap(*border_left,extra_params.track_x, extra_params.track_y);
// Draw right button left border.
canvas->drawBitmap(
*border_right,
extra_params.track_x + extra_params.track_width - border_right->width(),
extra_params.track_y);
}
}
void NativeThemeChromeos::PaintThumb(skia::PlatformCanvas* canvas,
Part part, State state, const gfx::Rect& rect) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int resource_id = IDR_SCROLL_THUMB;
if (state == kHover)
resource_id++;
else if (state == kPressed)
resource_id += 2;
if (part == kScrollbarVerticalThumb) {
SkBitmap* bitmap = rb.GetBitmapNamed(resource_id);
// Top
DrawBitmapInt(
canvas, *bitmap,
0, 1, bitmap->width(), 5,
rect.x(), rect.y(), rect.width(), 5);
// Middle
DrawBitmapInt(
canvas, *bitmap,
0, 7, bitmap->width(), 1,
rect.x(), rect.y() + 5, rect.width(), rect.height() - 10);
// Bottom
DrawBitmapInt(
canvas, *bitmap,
0, 8, bitmap->width(), 5,
rect.x(), rect.y() + rect.height() - 5, rect.width(), 5);
} else {
SkBitmap* bitmap = GetHorizontalBitmapNamed(resource_id);
// Left
DrawBitmapInt(
canvas, *bitmap,
1, 0, 5, bitmap->height(),
rect.x(), rect.y(), 5, rect.height());
// Middle
DrawBitmapInt(
canvas, *bitmap,
7, 0, 1, bitmap->height(),
rect.x() + 5, rect.y(), rect.width() - 10, rect.height());
// Right
DrawBitmapInt(
canvas, *bitmap,
8, 0, 5, bitmap->height(),
rect.x() + rect.width() - 5, rect.y(), 5, rect.height());
}
}
void NativeThemeChromeos::PaintArrowButton(skia::PlatformCanvas* canvas,
const gfx::Rect& rect, Part part, State state) {
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
int resource_id =
(part == kScrollbarUpArrow || part == kScrollbarLeftArrow) ?
IDR_SCROLL_ARROW_UP : IDR_SCROLL_ARROW_DOWN;
if (state == kHover)
resource_id++;
else if (state == kPressed)
resource_id += 2;
SkBitmap* bitmap;
if (part == kScrollbarUpArrow || part == kScrollbarDownArrow)
bitmap = rb.GetBitmapNamed(resource_id);
else
bitmap = GetHorizontalBitmapNamed(resource_id);
canvas->drawBitmap(*bitmap, rect.x(), rect.y());
}
SkBitmap* NativeThemeChromeos::GetHorizontalBitmapNamed(int resource_id) {
SkImageMap::const_iterator found = horizontal_bitmaps_.find(resource_id);
if (found != horizontal_bitmaps_.end())
return found->second;
ResourceBundle& rb = ResourceBundle::GetSharedInstance();
SkBitmap* vertical_bitmap = rb.GetBitmapNamed(resource_id);
if (vertical_bitmap) {
SkBitmap transposed_bitmap =
SkBitmapOperations::CreateTransposedBtmap(*vertical_bitmap);
SkBitmap* horizontal_bitmap = new SkBitmap(transposed_bitmap);
horizontal_bitmaps_[resource_id] = horizontal_bitmap;
return horizontal_bitmap;
}
return NULL;
}
<|endoftext|> |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.