<commit_before>// Copyright 2019 Google LLC
//
// 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
//
//     https://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 "array.h"
#include "test.h"

namespace nda {

TEST(array_default_constructor) {
  dense_array<int, 1> a(make_dense_shape(10));
  for (int x = 0; x < 10; x++) {
    ASSERT_EQ(a(x), 0);
  }

  dense_array<int, 2> b({7, 3});
  ASSERT_EQ(b.width(), 7);
  ASSERT_EQ(b.height(), 3);
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 7; x++) {
      ASSERT_EQ(b(x, y), 0);
    }
  }

  dense_array<int, 3> c({5, 9, 3});
  ASSERT_EQ(c.width(), 5);
  ASSERT_EQ(c.height(), 9);
  ASSERT_EQ(c.channels(), 3);
  for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 9; y++) {
      for (int x = 0; x < 5; x++) {
        ASSERT_EQ(c(x, y, z), 0);
      }
    }
  }

  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20));
  array<int, shape<dim<>, dim<>>> sparse(sparse_shape);
  ASSERT_EQ(sparse.rows(), 5);
  ASSERT_EQ(sparse.columns(), 10);
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 0);
    }
  }

  sparse.clear();
  ASSERT(sparse.empty());
  sparse.clear();
}

TEST(array_fill_constructor) {
  dense_array<int, 1> a(make_dense_shape(10), 3);
  for (int x = 0; x < 10; x++) {
    ASSERT_EQ(a(x), 3);
  }

  dense_array<int, 2> b({7, 3}, 5);
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 7; x++) {
      ASSERT_EQ(b(x, y), 5);
    }
  }

  dense_array<int, 3> c({5, 9, 3}, 7);
  for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 9; y++) {
      for (int x = 0; x < 5; x++) {
        ASSERT_EQ(c(x, y, z), 7);
      }
    }
  }

  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20));
  array<int, shape<dim<>, dim<>>> sparse(sparse_shape, 13);
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 13);
    }
  }
}

TEST(array_fill_assign) {
  dense_array<int, 1> a;
  a.assign(make_dense_shape(10), 3);
  for (int x = 0; x < 10; x++) {
    ASSERT_EQ(a(x), 3);
  }

  dense_array<int, 2> b;
  b.assign({7, 3}, 5);
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 7; x++) {
      ASSERT_EQ(b(x, y), 5);
    }
  }

  dense_array<int, 3> c;
  c.assign({5, 9, 3}, 7);
  for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 9; y++) {
      for (int x = 0; x < 5; x++) {
        ASSERT_EQ(c(x, y, z), 7);
      }
    }
  }

  array<int, shape<dim<>, dim<>>> sparse;
  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10));
  ASSERT(sparse_shape.flat_extent() > sparse_shape.size());

  sparse.assign(sparse_shape, 13);
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 13);
    }
  }
}

TEST(sparse_array) {
  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10));
  ASSERT(sparse_shape.flat_extent() > sparse_shape.size());

  array<int, shape<dim<>, dim<>>> sparse(sparse_shape);
  // Fill the storage with a constant.
  for (size_t i = 0; i < sparse_shape.flat_extent(); i++) {
    sparse.data()[i] = 7;
  }
  // Assign a different constant.
  sparse.assign(sparse_shape, 3);

  // Check that we assigned all of the elements of the array.
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 3);
    }
  }

  // Check that only the elements of the array were assigned.
  size_t sevens = 0;
  for (size_t i = 0; i < sparse_shape.flat_extent(); i++) {
    if (sparse.data()[i] == 7) {
      sevens++;
    }
  }
  ASSERT_EQ(sevens + sparse.size(), sparse_shape.flat_extent());
}

TEST(array_equality) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);
  array_of_rank<int, 3> b({4, 5, 6});
  fill_pattern(b);
  // A sparse array with a different stride than the above should still be equal to the above.
  array_of_rank<int, 3> c({dim<>(0, 4, 2), 5, 6});
  fill_pattern(c);

  ASSERT(a == b);
  ASSERT(a == c);

  a(1, 2, 3) = 5;
  ASSERT(a != b);
  ASSERT(a != c);
}

TEST(array_copy) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);

  dense_array<int, 3> b({4, 5, 6});
  copy(a, b);
  check_pattern(b);

  array_of_rank<int, 3> c({dim<>(0, 4, 2), 5, 6});
  copy(b, c);
  check_pattern(c);

  array_of_rank<int, 3> d = make_copy(a, c.shape());
  ASSERT_EQ(c.shape(), d.shape());
  check_pattern(d);

  dense_array<int, 3> e = make_copy(a, b.shape());
  ASSERT_EQ(b.shape(), e.shape());
  check_pattern(e);

  try {
    // The destination wants indices out of range of the source.
    array_of_rank<int, 3> f({5, 5, 6});
    copy(a, f);
    ASSERT(false);
  } catch(const std::out_of_range&) {
  }

  dense_array<int, 3> g({{1, 2}, {1, 3}, {1, 4}});
  copy(a, g);
  check_pattern(g);
}

TEST(array_move) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);

  dense_array<int, 3> b({4, 5, 6});
  move(a, b);
  check_pattern(b);

  array_of_rank<int, 3> c({dim<>(0, 4, 2), 5, 6});
  move(b, c);
  check_pattern(c);

  array_of_rank<int, 3> d = make_move(a, c.shape());
  ASSERT_EQ(c.shape(), d.shape());
  check_pattern(d);

  dense_array<int, 3> e = make_move(a, b.shape());
  ASSERT_EQ(b.shape(), e.shape());
  check_pattern(e);

  try {
    // The destination wants indices out of range of the source.
    array_of_rank<int, 3> f({5, 5, 6});
    move(a, f);
    ASSERT(false);
  } catch(const std::out_of_range&) {
  }

  dense_array<int, 3> g({4, {1, 2}, 5});
  move(a, g);
  check_pattern(g);
}

TEST(array_dense_copy) {
  array_of_rank<int, 3> source({dim<>(-3, 4, 2), 5, 6});
  fill_pattern(source);
  ASSERT(!source.is_compact());

  dense_array<int, 3> dense_copy = make_dense_copy(source);
  ASSERT(dense_copy.is_compact());
  check_pattern(dense_copy);
}

TEST(array_dense_move) {
  array_of_rank<int, 3> source({dim<>(-3, 4, 2), 5, 6});
  fill_pattern(source);
  ASSERT(!source.is_compact());

  dense_array<int, 3> dense_move = make_dense_move(source);
  ASSERT(dense_move.is_compact());
  check_pattern(dense_move);
}

TEST(array_tricky_copy) {
  array_of_rank<int, 2> source({{0, 4, 6}, {0, 6, 1}});
  fill_pattern(source);

  array_of_rank<int, 2> dest({{0, 4, 6}, {0, 3, 2}});
  copy(source, dest);
  check_pattern(dest);
}

TEST(array_for_each_value_scalar) {
  array_of_rank<int, 0> scalar;
  scalar.for_each_value([](int& v) {
    v = 3;
  });
  ASSERT_EQ(scalar(), 3);
}

TEST(array_for_each_value) {
  array_of_rank<int, 3> in_order({dim<>(0, 4, 1), dim<>(0, 4, 4), dim<>(0, 4, 16)});
  array_of_rank<int, 3> out_of_order({dim<>(0, 4, 16), dim<>(0, 4, 1), dim<>(0, 4, 4)});

  int out_of_order_counter = 0;
  out_of_order.for_each_value([&](int& v) {
    v = out_of_order_counter++;
  });

  int in_order_counter = 0;
  in_order.for_each_value([&](int& v) {
    v = in_order_counter++;
  });

  in_order_counter = 0;
  for (int z : in_order.z()) {
    for (int y : in_order.y()) {
      for (int x : in_order.x()) {
      	int expected = in_order_counter++;
      	ASSERT_EQ(in_order(x, y, z), expected);
      }
    }
  }

  out_of_order_counter = 0;
  for (int x : out_of_order.x()) {
    for (int z : out_of_order.z()) {
      for (int y : out_of_order.y()) {
      	int expected = out_of_order_counter++;
      	ASSERT_EQ(out_of_order(x, y, z), expected);
      }
    }
  }
}

TEST(array_reshape) {
  array_of_rank<int, 3> a({{-1, 10}, {-2, 10}, {-3, 10}});
  fill_pattern(a);
  a.reshape({5, 5, 5});
  check_pattern(a);
  ASSERT_EQ(a.shape().flat_extent(), 125);
}

TEST(array_negative_strides) {
  array_of_rank<int, 2> a({{0, 10, 3}, {0, 3, -1}});
  ASSERT_EQ(a.x().stride(), 3);
  for_all_indices(a.shape(), [&](int x, int y) {
    a(x, y) = y;
  });

  dense_array<int, 2> b = make_dense_copy(a);
  for_each_index(b.shape(), [&](const dense_array<int, 2>::index_type& i) {
    ASSERT_EQ(b(i), std::get<1>(i));
  });
}

}  // namespace nda
<commit_msg>Add more tests of array::operator=.<commit_after>// Copyright 2019 Google LLC
//
// 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
//
//     https://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 "array.h"
#include "test.h"

namespace nda {

TEST(array_default_constructor) {
  dense_array<int, 1> a(make_dense_shape(10));
  for (int x = 0; x < 10; x++) {
    ASSERT_EQ(a(x), 0);
  }

  dense_array<int, 2> b({7, 3});
  ASSERT_EQ(b.width(), 7);
  ASSERT_EQ(b.height(), 3);
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 7; x++) {
      ASSERT_EQ(b(x, y), 0);
    }
  }

  dense_array<int, 3> c({5, 9, 3});
  ASSERT_EQ(c.width(), 5);
  ASSERT_EQ(c.height(), 9);
  ASSERT_EQ(c.channels(), 3);
  for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 9; y++) {
      for (int x = 0; x < 5; x++) {
        ASSERT_EQ(c(x, y, z), 0);
      }
    }
  }

  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20));
  array<int, shape<dim<>, dim<>>> sparse(sparse_shape);
  ASSERT_EQ(sparse.rows(), 5);
  ASSERT_EQ(sparse.columns(), 10);
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 0);
    }
  }

  sparse.clear();
  ASSERT(sparse.empty());
  sparse.clear();
}

TEST(array_fill_constructor) {
  dense_array<int, 1> a(make_dense_shape(10), 3);
  for (int x = 0; x < 10; x++) {
    ASSERT_EQ(a(x), 3);
  }

  dense_array<int, 2> b({7, 3}, 5);
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 7; x++) {
      ASSERT_EQ(b(x, y), 5);
    }
  }

  dense_array<int, 3> c({5, 9, 3}, 7);
  for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 9; y++) {
      for (int x = 0; x < 5; x++) {
        ASSERT_EQ(c(x, y, z), 7);
      }
    }
  }

  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10, 20));
  array<int, shape<dim<>, dim<>>> sparse(sparse_shape, 13);
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 13);
    }
  }
}

TEST(array_assign) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);

  array_of_rank<int, 3> b = array_of_rank<int, 3>({4, 5, 6});
  fill_pattern(b);
  ASSERT(a == b);

  array_of_rank<int, 3> c;
  c = array_of_rank<int, 3>({4, 5, 6});
  fill_pattern(c);
  ASSERT(a == c);

  c = array_of_rank<int, 3>({4, 5, 6});
  ASSERT(a != c);
  fill_pattern(c);
  ASSERT(a == c);

  c = array_of_rank<int, 3>({7, 5, 6});
  ASSERT(a != c);

  {
    array_of_rank<int, 3> d({4, 5, 6});
    fill_pattern(d);
    c = d;
  }
  ASSERT(a == c);
}

TEST(array_fill_assign) {
  dense_array<int, 1> a;
  a.assign(make_dense_shape(10), 3);
  for (int x = 0; x < 10; x++) {
    ASSERT_EQ(a(x), 3);
  }

  dense_array<int, 2> b;
  b.assign({7, 3}, 5);
  for (int y = 0; y < 3; y++) {
    for (int x = 0; x < 7; x++) {
      ASSERT_EQ(b(x, y), 5);
    }
  }

  dense_array<int, 3> c;
  c.assign({5, 9, 3}, 7);
  for (int z = 0; z < 3; z++) {
    for (int y = 0; y < 9; y++) {
      for (int x = 0; x < 5; x++) {
        ASSERT_EQ(c(x, y, z), 7);
      }
    }
  }

  array<int, shape<dim<>, dim<>>> sparse;
  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10));
  ASSERT(sparse_shape.flat_extent() > sparse_shape.size());

  sparse.assign(sparse_shape, 13);
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 13);
    }
  }
}

TEST(sparse_array) {
  auto sparse_shape = make_shape(dim<>(-2, 5, 2), dim<>(4, 10));
  ASSERT(sparse_shape.flat_extent() > sparse_shape.size());

  array<int, shape<dim<>, dim<>>> sparse(sparse_shape);
  // Fill the storage with a constant.
  for (size_t i = 0; i < sparse_shape.flat_extent(); i++) {
    sparse.data()[i] = 7;
  }
  // Assign a different constant.
  sparse.assign(sparse_shape, 3);

  // Check that we assigned all of the elements of the array.
  for (int y = 4; y < 14; y++) {
    for (int x = -2; x < 3; x++) {
      ASSERT_EQ(sparse(x, y), 3);
    }
  }

  // Check that only the elements of the array were assigned.
  size_t sevens = 0;
  for (size_t i = 0; i < sparse_shape.flat_extent(); i++) {
    if (sparse.data()[i] == 7) {
      sevens++;
    }
  }
  ASSERT_EQ(sevens + sparse.size(), sparse_shape.flat_extent());
}

TEST(array_equality) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);
  array_of_rank<int, 3> b({4, 5, 6});
  fill_pattern(b);
  // A sparse array with a different stride than the above should still be equal to the above.
  array_of_rank<int, 3> c({dim<>(0, 4, 2), 5, 6});
  fill_pattern(c);

  ASSERT(a == b);
  ASSERT(a == c);

  a(1, 2, 3) = 5;
  ASSERT(a != b);
  ASSERT(a != c);
}

TEST(array_copy) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);

  dense_array<int, 3> b({4, 5, 6});
  copy(a, b);
  check_pattern(b);

  array_of_rank<int, 3> c({dim<>(0, 4, 2), 5, 6});
  copy(b, c);
  check_pattern(c);

  array_of_rank<int, 3> d = make_copy(a, c.shape());
  ASSERT_EQ(c.shape(), d.shape());
  check_pattern(d);

  dense_array<int, 3> e = make_copy(a, b.shape());
  ASSERT_EQ(b.shape(), e.shape());
  check_pattern(e);

  try {
    // The destination wants indices out of range of the source.
    array_of_rank<int, 3> f({5, 5, 6});
    copy(a, f);
    ASSERT(false);
  } catch(const std::out_of_range&) {
  }

  dense_array<int, 3> g({{1, 2}, {1, 3}, {1, 4}});
  copy(a, g);
  check_pattern(g);
}

TEST(array_move) {
  array_of_rank<int, 3> a({4, 5, 6});
  fill_pattern(a);

  dense_array<int, 3> b({4, 5, 6});
  move(a, b);
  check_pattern(b);

  array_of_rank<int, 3> c({dim<>(0, 4, 2), 5, 6});
  move(b, c);
  check_pattern(c);

  array_of_rank<int, 3> d = make_move(a, c.shape());
  ASSERT_EQ(c.shape(), d.shape());
  check_pattern(d);

  dense_array<int, 3> e = make_move(a, b.shape());
  ASSERT_EQ(b.shape(), e.shape());
  check_pattern(e);

  try {
    // The destination wants indices out of range of the source.
    array_of_rank<int, 3> f({5, 5, 6});
    move(a, f);
    ASSERT(false);
  } catch(const std::out_of_range&) {
  }

  dense_array<int, 3> g({4, {1, 2}, 5});
  move(a, g);
  check_pattern(g);
}

TEST(array_dense_copy) {
  array_of_rank<int, 3> source({dim<>(-3, 4, 2), 5, 6});
  fill_pattern(source);
  ASSERT(!source.is_compact());

  dense_array<int, 3> dense_copy = make_dense_copy(source);
  ASSERT(dense_copy.is_compact());
  check_pattern(dense_copy);
}

TEST(array_dense_move) {
  array_of_rank<int, 3> source({dim<>(-3, 4, 2), 5, 6});
  fill_pattern(source);
  ASSERT(!source.is_compact());

  dense_array<int, 3> dense_move = make_dense_move(source);
  ASSERT(dense_move.is_compact());
  check_pattern(dense_move);
}

TEST(array_tricky_copy) {
  array_of_rank<int, 2> source({{0, 4, 6}, {0, 6, 1}});
  fill_pattern(source);

  array_of_rank<int, 2> dest({{0, 4, 6}, {0, 3, 2}});
  copy(source, dest);
  check_pattern(dest);
}

TEST(array_for_each_value_scalar) {
  array_of_rank<int, 0> scalar;
  scalar.for_each_value([](int& v) {
    v = 3;
  });
  ASSERT_EQ(scalar(), 3);
}

TEST(array_for_each_value) {
  array_of_rank<int, 3> in_order({dim<>(0, 4, 1), dim<>(0, 4, 4), dim<>(0, 4, 16)});
  array_of_rank<int, 3> out_of_order({dim<>(0, 4, 16), dim<>(0, 4, 1), dim<>(0, 4, 4)});

  int out_of_order_counter = 0;
  out_of_order.for_each_value([&](int& v) {
    v = out_of_order_counter++;
  });

  int in_order_counter = 0;
  in_order.for_each_value([&](int& v) {
    v = in_order_counter++;
  });

  in_order_counter = 0;
  for (int z : in_order.z()) {
    for (int y : in_order.y()) {
      for (int x : in_order.x()) {
      	int expected = in_order_counter++;
      	ASSERT_EQ(in_order(x, y, z), expected);
      }
    }
  }

  out_of_order_counter = 0;
  for (int x : out_of_order.x()) {
    for (int z : out_of_order.z()) {
      for (int y : out_of_order.y()) {
      	int expected = out_of_order_counter++;
      	ASSERT_EQ(out_of_order(x, y, z), expected);
      }
    }
  }
}

TEST(array_reshape) {
  array_of_rank<int, 3> a({{-1, 10}, {-2, 10}, {-3, 10}});
  fill_pattern(a);
  a.reshape({5, 5, 5});
  check_pattern(a);
  ASSERT_EQ(a.shape().flat_extent(), 125);
}

TEST(array_negative_strides) {
  array_of_rank<int, 2> a({{0, 10, 3}, {0, 3, -1}});
  ASSERT_EQ(a.x().stride(), 3);
  for_all_indices(a.shape(), [&](int x, int y) {
    a(x, y) = y;
  });

  dense_array<int, 2> b = make_dense_copy(a);
  for_each_index(b.shape(), [&](const dense_array<int, 2>::index_type& i) {
    ASSERT_EQ(b(i), std::get<1>(i));
  });
}

}  // namespace nda
<|endoftext|>


<commit_before>#pragma once
#include <src/batchringbuffer.h>

#include <iostream>
#include <time.h>
#include <sys/time.h>

#include <gtest/gtest.h>

#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif

#define MILLIS 1000000LL
#define NANOS 1000000000LL

class Bench_4_4_1024_buffer : public testing::Test {
protected:
	brb_buffer * buffer;
};

timespec
diff(timespec start, timespec end) {
	timespec temp;
	if ((end.tv_nsec-start.tv_nsec)<0) {
		temp.tv_sec = end.tv_sec-start.tv_sec-1;
		temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
	} else {
		temp.tv_sec = end.tv_sec-start.tv_sec;
		temp.tv_nsec = end.tv_nsec-start.tv_nsec;
	}
	return temp;
}

void
get_timespec(timespec * ts) {
#ifdef __MACH__ /* OS X does not have clock_gettime, use clock_get_time */
	clock_serv_t cclock;
	mach_timespec_t mts;
	host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
	clock_get_time(cclock, &mts);
	mach_port_deallocate(mach_task_self(), cclock);
	ts->tv_sec = mts.tv_sec;
	ts->tv_nsec = mts.tv_nsec;

#else
	clock_gettime(CLOCK_REALTIME, ts);
#endif
}

double
bench(int n)
{
	timespec time1, time2;

	brb_buffer * buffer;
	brb_batch * batch;
	char cancel;

	brb_init_buffer(&buffer, 4, 4, 1024);
	get_timespec(&time1);
	for (int i = 0; i< n; i++) {

		brb_claim(buffer, &batch, 1, &cancel);
		brb_publish(buffer, batch);
		brb_release(buffer, batch);

	}
	get_timespec(&time2);
	brb_free_buffer(&buffer);
	return (double)diff(time1,time2).tv_nsec / (double)n;
}

TEST_F(Bench_4_4_1024_buffer, _claim_publish_release) {
	double ns_per_op;
	double ops_per_ms;
	double ops_per_s;
	int count;
	/* warmup */
	bench(1000);
	for(count = 1000; count <= 10000000; count *= 10) {
		ns_per_op = bench(count);
		ops_per_ms = MILLIS / ns_per_op;
		ops_per_s = NANOS / ns_per_op;
		printf("[%10d]\t%8.4f ns/op\t\t%12.4f op/ms\t\t%12.4f op/s\n", count, ns_per_op, ops_per_ms, ops_per_s);
	}
}
<commit_msg>Addung using namespace std;...<commit_after>#pragma once
#include <src/batchringbuffer.h>

#include <iostream>
#include <time.h>
#include <sys/time.h>

using namespace std;

#include <gtest/gtest.h>

#ifdef __MACH__
#include <mach/clock.h>
#include <mach/mach.h>
#endif

#define MILLIS 1000000LL
#define NANOS 1000000000LL

class Bench_4_4_1024_buffer : public testing::Test {
protected:
	brb_buffer * buffer;
};

timespec
diff(timespec start, timespec end) {
	timespec temp;
	if ((end.tv_nsec-start.tv_nsec)<0) {
		temp.tv_sec = end.tv_sec-start.tv_sec-1;
		temp.tv_nsec = 1000000000+end.tv_nsec-start.tv_nsec;
	} else {
		temp.tv_sec = end.tv_sec-start.tv_sec;
		temp.tv_nsec = end.tv_nsec-start.tv_nsec;
	}
	return temp;
}

void
get_timespec(timespec * ts) {
#ifdef __MACH__ /* OS X does not have clock_gettime, use clock_get_time */
	clock_serv_t cclock;
	mach_timespec_t mts;
	host_get_clock_service(mach_host_self(), CALENDAR_CLOCK, &cclock);
	clock_get_time(cclock, &mts);
	mach_port_deallocate(mach_task_self(), cclock);
	ts->tv_sec = mts.tv_sec;
	ts->tv_nsec = mts.tv_nsec;

#else
	clock_gettime(CLOCK_REALTIME, ts);
#endif
}

double
bench(int n)
{
	timespec time1, time2;

	brb_buffer * buffer;
	brb_batch * batch;
	char cancel;

	brb_init_buffer(&buffer, 4, 4, 1024);
	get_timespec(&time1);
	for (int i = 0; i< n; i++) {

		brb_claim(buffer, &batch, 1, &cancel);
		brb_publish(buffer, batch);
		brb_release(buffer, batch);

	}
	get_timespec(&time2);
	brb_free_buffer(&buffer);
	return (double)diff(time1,time2).tv_nsec / (double)n;
}

TEST_F(Bench_4_4_1024_buffer, _claim_publish_release) {
	double ns_per_op;
	double ops_per_ms;
	double ops_per_s;
	int count;
	/* warmup */
	bench(1000);
	for(count = 1000; count <= 10000000; count *= 10) {
		ns_per_op = bench(count);
		ops_per_ms = MILLIS / ns_per_op;
		ops_per_s = NANOS / ns_per_op;
		printf("[%10d]\t%8.4f ns/op\t\t%12.4f op/ms\t\t%12.4f op/s\n", count, ns_per_op, ops_per_ms, ops_per_s);
	}
}
<|endoftext|>


<commit_before>#ifndef SIMPLE_HERO_HPP_
#define SIMPLE_HERO_HPP_

#include "GraphMap.hpp"
#include "vertex.hpp"
#include "Actor.hpp"

#include <vector>

using namespace std;

class Simple_Hero : public Actor {

	protected:
	public:
		int graph_width;
		int graph_height;
		bool made_graph;

		Simple_Hero( int type );
		virtual ~Simple_Hero();
		virtual int select_neighbor( GraphMap* map, int x, int y );
		virtual Simple_Hero* duplicate();
		virtual const char* getActorId();
		virtual const char* getNetId();

		void update_vertices( GraphMap* map );
		Vertex& get_vertex( int x, int y );
		void make_graph( GraphMap* map );

		vector< Vertex > actor_list;
		vector< vector< Vertex > > graph;

		int find_path( Vertex v );
		int where_go( GraphMap* map, int x1, int y1, int x2, int y2 );
};

#endif
<commit_msg>Added definitions<commit_after>#ifndef SIMPLE_HERO_HPP_
#define SIMPLE_HERO_HPP_

#include "GraphMap.hpp"
#include "vertex.hpp"
#include "Actor.hpp"

#include <vector>

using namespace std;

class Simple_Hero : public Actor {
	private:
	protected:
	public:
		int graph_width;
		int graph_height;
		bool made_graph;

		vector< Vertex > actor_list;
		vector< vector< Vertex > > graph;
		vector< Vertex > ranked_actors;

		Simple_Hero( int type );
		virtual ~Simple_Hero();
		virtual int select_neighbor( GraphMap* map, int x, int y );
		virtual Simple_Hero* duplicate();
		virtual const char* getActorId();
		virtual const char* getNetId();

		void update_vertices( GraphMap* map );
		Vertex& get_vertex( int x, int y );
		void make_graph( GraphMap* map );
		void rank_actors( GraphMap* map, int x_start, int y_start );

		int find_path( Vertex v );
		int where_go( GraphMap* map, int x1, int y1, int x2, int y2 );

};

#endif
<|endoftext|>


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

#ifndef LUA_ITEM_SCRIPT_HPP
#define LUA_ITEM_SCRIPT_HPP

#include <map>
#include <string>
#include "LuaScript.hpp"
#include "ItemLookAt.hpp"
#include "TableStructs.hpp"

class World;
class Field;
class Character;
class ScriptItem;

class LuaItemScript : public LuaScript {
public:
    LuaItemScript();
    LuaItemScript(const std::string &filename, ItemStruct comstr);
    LuaItemScript(const std::string &code, const std::string &codename, ItemStruct comstr);
    ~LuaItemScript() override;
    LuaItemScript(const LuaItemScript &) = delete;
    auto operator=(const LuaItemScript &) -> LuaItemScript & = delete;

    void UseItem(Character *User, const ScriptItem &SourceItem, unsigned char ltastate);
    auto actionDisturbed(Character *performer, Character *disturber) -> bool;
    auto LookAtItem(Character *who, const ScriptItem &t_item) -> ItemLookAt;
    auto MoveItemBeforeMove(Character *who, const ScriptItem &sourceItem, const ScriptItem &targetItem) -> bool;
    void MoveItemAfterMove(Character *who, const ScriptItem &sourceItem, const ScriptItem &targetItem);
    void CharacterOnField(Character *who);

private:
    ItemStruct _comstr;
    void init_functions() const;
};

#endif

<commit_msg>Fix incorrect forward declaration<commit_after>/*
 *  illarionserver - server for the game Illarion
 *  Copyright 2011 Illarion e.V.
 *
 *  This file is part of illarionserver.
 *
 *  illarionserver is free software: you can redistribute it and/or modify
 *  it under the terms of the GNU Affero General Public License as published by
 *  the Free Software Foundation, either version 3 of the License, or
 *  (at your option) any later version.
 *
 *  illarionserver is distributed in the hope that it will be useful,
 *  but WITHOUT ANY WARRANTY; without even the implied warranty of
 *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 *  GNU Affero General Public License for more details.
 *
 *  You should have received a copy of the GNU Affero General Public License
 *  along with illarionserver.  If not, see <http://www.gnu.org/licenses/>.
 */

#ifndef LUA_ITEM_SCRIPT_HPP
#define LUA_ITEM_SCRIPT_HPP

#include <map>
#include <string>
#include "LuaScript.hpp"
#include "ItemLookAt.hpp"
#include "TableStructs.hpp"

class World;
namespace map {
    class Field;
}
class Character;
class ScriptItem;

class LuaItemScript : public LuaScript {
public:
    LuaItemScript();
    LuaItemScript(const std::string &filename, ItemStruct comstr);
    LuaItemScript(const std::string &code, const std::string &codename, ItemStruct comstr);
    ~LuaItemScript() override;
    LuaItemScript(const LuaItemScript &) = delete;
    auto operator=(const LuaItemScript &) -> LuaItemScript & = delete;

    void UseItem(Character *User, const ScriptItem &SourceItem, unsigned char ltastate);
    auto actionDisturbed(Character *performer, Character *disturber) -> bool;
    auto LookAtItem(Character *who, const ScriptItem &t_item) -> ItemLookAt;
    auto MoveItemBeforeMove(Character *who, const ScriptItem &sourceItem, const ScriptItem &targetItem) -> bool;
    void MoveItemAfterMove(Character *who, const ScriptItem &sourceItem, const ScriptItem &targetItem);
    void CharacterOnField(Character *who);

private:
    ItemStruct _comstr;
    void init_functions() const;
};

#endif

<|endoftext|>


<commit_before>#ifndef H_GIL_SIMPLE_VIEW
#define H_GIL_SIMPLE_VIEW

namespace boost{ namespace gil{ struct image_view; }}

namespace gil_simple_view
{
	enum struct channel_type
	{
		bits8  ,	//  uint8_t
		bits8s ,	//   int8_t
		bits16 ,	// uint16_t
		bits16s,	//  int16_t
		bits32 ,	// uint32_t
		bits32s,	//  int32_t
		bits32f 	//   double
	};

	enum struct color_type
	{
		gray_t   ,	// [gray]scale
		alpha_t  ,	// [a]rgb
		red_t    ,	// a[r]gb
		green_t  ,	// ar[g]b
		blue_t   ,	// arg[b]
		cyan_t   ,	// [c]myk
		magenta_t,	// c[m]yk
		yellow_t ,	// cm[y]k
		black_t   	// cmy[k]
	};

	namespace color_space_type
	{
		std::vector<color_type> gray({ color_type::gray_t });
		std::vector<color_type> rgb ({ color_type::red_t  , color_type::green_t  , color_type::blue_t  });
		std::vector<color_type> bgr ({ color_type::blue_t , color_type::green_t  , color_type::red_t   });
		std::vector<color_type> argb({ color_type::alpha_t, color_type::red_t    , color_type::green_t , color_type::blue_t  });
		std::vector<color_type> abgr({ color_type::alpha_t, color_type::blue_t   , color_type::green_t , color_type::red_t   });
		std::vector<color_type> rgba({ color_type::red_t  , color_type::green_t  , color_type::blue_t  , color_type::alpha_t });
		std::vector<color_type> bgra({ color_type::blue_t , color_type::green_t  , color_type::red_t   , color_type::alpha_t });
		std::vector<color_type> cmyk({ color_type::cyan_t , color_type::magenta_t, color_type::yellow_t, color_type::black_t };
	}

	struct simple_view
	{
		channel_type channel;
		std::vector<color_type> color_space;
		boost::gil::image_view* src_view;
	};

	// check channel type bit-wise
	bool is_8bit      (simple_view& v);
	bool is_16bit     (simple_view& v);
	bool is_32bit     (simple_view& v);

	// check channel type representation-wise
	bool is_unsigned  (simple_view& v);
	bool is_signed    (simple_view& v);
	bool is_float     (simple_view& v);

	// check color space type disregarding the order
	bool is_grayscale (simple_view& v);
	bool is_rgb       (simple_view& v);
	bool is_argb      (simple_view& v);
	bool is_cmyk      (simple_view& v);

	// create a simple_view from a boost::gil view
	simple_view create_simple_view (boost::gil::image_view& v);
}

#endif
<commit_msg>Added create_simple_view prototypes<commit_after>#ifndef H_GIL_SIMPLE_VIEW
#define H_GIL_SIMPLE_VIEW

namespace boost{ namespace gil{ struct image_view; }}

namespace gil_simple_view
{
	enum struct channel_type
	{
		bits8  ,	//  uint8_t
		bits8s ,	//   int8_t
		bits16 ,	// uint16_t
		bits16s,	//  int16_t
		bits32 ,	// uint32_t
		bits32s,	//  int32_t
		bits32f 	//   double
	};

	enum struct color_type
	{
		gray_t   ,	// [gray]scale
		alpha_t  ,	// [a]rgb
		red_t    ,	// a[r]gb
		green_t  ,	// ar[g]b
		blue_t   ,	// arg[b]
		cyan_t   ,	// [c]myk
		magenta_t,	// c[m]yk
		yellow_t ,	// cm[y]k
		black_t   	// cmy[k]
	};

	namespace color_space_type
	{
		std::vector<color_type> gray({ color_type::gray_t });
		std::vector<color_type> rgb ({ color_type::red_t  , color_type::green_t  , color_type::blue_t  });
		std::vector<color_type> bgr ({ color_type::blue_t , color_type::green_t  , color_type::red_t   });
		std::vector<color_type> argb({ color_type::alpha_t, color_type::red_t    , color_type::green_t , color_type::blue_t  });
		std::vector<color_type> abgr({ color_type::alpha_t, color_type::blue_t   , color_type::green_t , color_type::red_t   });
		std::vector<color_type> rgba({ color_type::red_t  , color_type::green_t  , color_type::blue_t  , color_type::alpha_t });
		std::vector<color_type> bgra({ color_type::blue_t , color_type::green_t  , color_type::red_t   , color_type::alpha_t });
		std::vector<color_type> cmyk({ color_type::cyan_t , color_type::magenta_t, color_type::yellow_t, color_type::black_t };
	}

	struct simple_view
	{
		channel_type channel;
		std::vector<color_type> color_space;
		boost::gil::image_view* src_view;
	};

	// check channel type bit-wise
	bool is_8bit      (simple_view& v);
	bool is_16bit     (simple_view& v);
	bool is_32bit     (simple_view& v);

	// check channel type representation-wise
	bool is_unsigned  (simple_view& v);
	bool is_signed    (simple_view& v);
	bool is_float     (simple_view& v);

	// check color space type disregarding the order
	bool is_grayscale (simple_view& v);
	bool is_rgb       (simple_view& v);
	bool is_argb      (simple_view& v);
	bool is_cmyk      (simple_view& v);

	// create a simple_view from a boost::gil view
	template<typename T> simple_view create_simple_view (T& v);

	template<typename L> simple_view create_simple_view (boost::gil::image_view<L>& v);

	simple_view create_simple_view (boost::gil::image_view<gray8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<gray32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<rgb8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgb32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<bgr8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgr32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<argb8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<argb32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<abgr8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<abgr32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<rgba8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<rgba32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<bgra8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<bgra32f_loc_t>& v);

	simple_view create_simple_view (boost::gil::image_view<cmyk8_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk8s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk16_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk16s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk32_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk32s_loc_t>& v);
	simple_view create_simple_view (boost::gil::image_view<cmyk32f_loc_t>& v);

}

#endif
<|endoftext|>


<commit_before>#include <iostream>
#include <cstring>
#include <stdlib.h>

using namespace std;

int main ()
{
    string input;
    while(input!="exit")
    {
        cout<<"gsh >>";
        getline(cin,input);
        system((const char*)input.c_str());

    }
}<commit_msg>created basic dist<commit_after>#include <iostream>
#include <cstring>
#include <stdlib.h>

using namespace std;

int main ()
{
    string input;
    while(input!="exit")
    {
        cout<<"gsh >>";
        getline(cin,input);
        //convert to const*
        system((const char*)input.c_str());

    }
}<|endoftext|>


<commit_before>// The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@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.

#ifndef CV_IGNORE_GUI // ignore compilation of the source file.

#include "../include/gui.hpp"
#include "../include/array.hpp"

namespace cv {

image_window::image_window(QWidget *parent): QDialog(parent) {
	QHBoxLayout *lay = new QHBoxLayout(this);
	lay->setContentsMargins(QMargins(0, 0, 0, 0));
	image_lbl = new QLabel("", this);
	lay->addWidget(image_lbl);
	this->setLayout(lay);
	this->resize(500, 500);
}

image_window::~image_window() {

}

void image_window::set_image(const image_array &image) {
	if (!image.is_valid()) {
		return;
	}
	QImage::Format format;
	switch (image.depth()) {
		case 1:
		{
			switch (image.channels()) {
				case 1: format = QImage::Format_Indexed8; break;
				case 3: format = QImage::Format_RGB888; break;
#ifdef WINDOWS
				case 4: format = QImage::Format_RGBA8888; break;
#endif
				default: std::cerr << "Unsupported image format.\n"; return;
			}
		}
		break;
		case 2:
		{
			switch (image.channels()) {
				case 3: format = QImage::Format_RGB16;
				default: std::cerr << "Unsupported image format.\n"; return;
			}
		}
		break;
		case 4:
		{
			switch (image.channels()) {
				case 3: format = QImage::Format_RGB32;
				default: std::cerr << "Unsupported image format.\n"; return;
			}
		}
		default:
			std::cerr << "Unsupported image format.\n";
			return;
	}

	// TODO: find neat way to show non-contiguous images.
	if (image.is_contiguous()) {
		this->image_lbl->setPixmap(
				QPixmap::fromImage(QImage(reinterpret_cast<byte*>(image.data()),
						image.cols(), image.rows(), format)));
	} else {
		auto im_c = image.clone();
		this->image_lbl->setPixmap(
				QPixmap::fromImage(QImage(reinterpret_cast<byte*>(im_c.data()),
						im_c.cols(), im_c.rows(), format)));
	}

	this->resize(image.cols(), image.rows());
}

void image_window::keyPressEvent(QKeyEvent *e) {
	global_image_application::singleton()->assign_key(e->text()[0].toAscii());
}

void image_window::closeEvent(QCloseEvent *e) {
}

/****************************************************************************
** Meta object code from reading C++ file 'gui.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'gui.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_cv__image_window[] = {

 // content:
       6,       // revision
       0,       // classname
       0,    0, // classinfo
       0,    0, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       0,       // signalCount

       0        // eod
};

static const char qt_meta_stringdata_cv__image_window[] = {
    "cv::image_window\0"
};

void cv::image_window::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    Q_UNUSED(_o);
    Q_UNUSED(_id);
    Q_UNUSED(_c);
    Q_UNUSED(_a);
}

const QMetaObjectExtraData cv::image_window::staticMetaObjectExtraData = {
    0,  qt_static_metacall
};

const QMetaObject cv::image_window::staticMetaObject = {
    { &QDialog::staticMetaObject, qt_meta_stringdata_cv__image_window,
      qt_meta_data_cv__image_window, &staticMetaObjectExtraData }
};

#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &cv::image_window::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION

const QMetaObject *cv::image_window::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}

void *cv::image_window::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_cv__image_window))
        return static_cast<void*>(const_cast< image_window*>(this));
    return QDialog::qt_metacast(_clname);
}

int cv::image_window::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QDialog::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    return _id;
}
QT_END_MOC_NAMESPACE

// MOC Generated code end /////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////
// class global_image_application

global_image_application* global_image_application::_singleton = nullptr;

global_image_application::global_image_application(int &argc, char** argv) : QApplication(argc, argv), _last_key('\0') {

}

global_image_application::~global_image_application() {
	this->destroy_all_windows();
}

global_image_application *global_image_application::singleton() {
	if (!global_image_application::_singleton) {
		int argc_simulation = 1;
		char *argv_simulation[] = {" ", " "};
		global_image_application::_singleton = new global_image_application(argc_simulation, argv_simulation);
	}
	return global_image_application::_singleton;
}

void global_image_application::force_quit() {
	this->quit();
}

void global_image_application::assign_key(char key) {
	this->_last_key = key;
	for (auto w : this->_windows) {
		w->close();
	}
}

char global_image_application::get_last_key() const {
	return this->_last_key;
}

void global_image_application::create_window(const std::string &name, const image_array &image) {
	image_window *newWindow = new image_window;
	newWindow->setWindowTitle(name.c_str());
	newWindow->set_image(image);
	newWindow->show();
	this->_windows.push_back(newWindow);
}

void global_image_application::destroy_window(const std::string &name) {
	int winId = -1;
	for (int i = 0; i < this->_windows.size(); i++) {
		if (this->_windows[i]->windowTitle() == name.c_str()) {
			winId = i;
			break;
		}
	}
	if (winId != -1) {
		this->_windows[winId]->close();
		delete this->_windows[winId];
		this->_windows.erase(this->_windows.begin() + winId);
	} else {
		std::cerr << ("Window by name " + name + " does not exist.\n");
	}
}

void global_image_application::destroy_all_windows() {
	for (auto window : this->_windows) {
		window->close();
		delete window;
	}
	this->_windows.clear();
}

void imshow(const std::string &name, const image_array &image) {
	ASSERT(image.is_valid() && (image.channels() == 1 || image.channels() == 3 || image.channels() == 4));
	if (image.depth() != 1) {
		image_array byte_copy = image.clone();
		byte_copy.convert_to<byte>();
		global_image_application::singleton()->create_window(name, byte_copy);
	} else {
		global_image_application::singleton()->create_window(name, image);
	}
}

void imclose(const std::string &name) {
	global_image_application::singleton()->destroy_window(name);
}

void imclose_all() {
	global_image_application::singleton()->destroy_all_windows();
}

char wait_key() {
	auto ga_inst = global_image_application::singleton();
	ga_inst->exec();
	return ga_inst->get_last_key();
}

}

#endif // CV_IGNORE_GUI
<commit_msg>minor code cleanup<commit_after>// The MIT License (MIT)
//
// Copyright (c) 2015 Relja Ljubobratovic, ljubobratovic.relja@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.

#ifndef CV_IGNORE_GUI // ignore compilation of the source file.

#include "../include/gui.hpp"
#include "../include/array.hpp"

namespace cv {

image_window::image_window(QWidget *parent): QDialog(parent) {
	QHBoxLayout *lay = new QHBoxLayout(this);
	lay->setContentsMargins(QMargins(0, 0, 0, 0));
	image_lbl = new QLabel("", this);
	lay->addWidget(image_lbl);
	this->setLayout(lay);
	this->resize(500, 500);
}

image_window::~image_window() {

}

void image_window::set_image(const image_array &image) {
	if (!image.is_valid()) {
		return;
	}
	QImage::Format format;
	switch (image.depth()) {
		case 1:
		{
			switch (image.channels()) {
				case 1: format = QImage::Format_Indexed8; break;
				case 3: format = QImage::Format_RGB888; break;
#ifdef WINDOWS
				case 4: format = QImage::Format_RGBA8888; break;
#endif
				default: std::cerr << "Unsupported image format.\n"; return;
			}
		}
		break;
		case 2:
		{
			switch (image.channels()) {
				case 3: format = QImage::Format_RGB16;
				default: std::cerr << "Unsupported image format.\n"; return;
			}
		}
		break;
		case 4:
		{
			switch (image.channels()) {
				case 3: format = QImage::Format_RGB32;
				default: std::cerr << "Unsupported image format.\n"; return;
			}
		}
		default:
			std::cerr << "Unsupported image format.\n";
			return;
	}

	// TODO: find neat way to show non-contiguous images.
	if (image.is_contiguous()) {
		this->image_lbl->setPixmap(
				QPixmap::fromImage(QImage(reinterpret_cast<byte*>(image.data()),
						image.cols(), image.rows(), format)));
	} else {
		auto im_c = image.clone();
		this->image_lbl->setPixmap(
				QPixmap::fromImage(QImage(reinterpret_cast<byte*>(im_c.data()),
						im_c.cols(), im_c.rows(), format)));
	}

	this->resize(image.cols(), image.rows());
}

void image_window::keyPressEvent(QKeyEvent *e) {
	global_image_application::singleton()->assign_key(e->text()[0].toAscii());
}

void image_window::closeEvent(QCloseEvent *e) {
}

/****************************************************************************
** Meta object code from reading C++ file 'gui.hpp'
**
** Created by: The Qt Meta Object Compiler version 63 (Qt 4.8.6)
**
** WARNING! All changes made in this file will be lost!
*****************************************************************************/

#if !defined(Q_MOC_OUTPUT_REVISION)
#error "The header file 'gui.hpp' doesn't include <QObject>."
#elif Q_MOC_OUTPUT_REVISION != 63
#error "This file was generated using the moc from 4.8.6. It"
#error "cannot be used with the include files from this version of Qt."
#error "(The moc has changed too much.)"
#endif

QT_BEGIN_MOC_NAMESPACE
static const uint qt_meta_data_cv__image_window[] = {

 // content:
       6,       // revision
       0,       // classname
       0,    0, // classinfo
       0,    0, // methods
       0,    0, // properties
       0,    0, // enums/sets
       0,    0, // constructors
       0,       // flags
       0,       // signalCount

       0        // eod
};

static const char qt_meta_stringdata_cv__image_window[] = {
    "cv::image_window\0"
};

void cv::image_window::qt_static_metacall(QObject *_o, QMetaObject::Call _c, int _id, void **_a)
{
    Q_UNUSED(_o);
    Q_UNUSED(_id);
    Q_UNUSED(_c);
    Q_UNUSED(_a);
}

const QMetaObjectExtraData cv::image_window::staticMetaObjectExtraData = {
    0,  qt_static_metacall
};

const QMetaObject cv::image_window::staticMetaObject = {
    { &QDialog::staticMetaObject, qt_meta_stringdata_cv__image_window,
      qt_meta_data_cv__image_window, &staticMetaObjectExtraData }
};

#ifdef Q_NO_DATA_RELOCATION
const QMetaObject &cv::image_window::getStaticMetaObject() { return staticMetaObject; }
#endif //Q_NO_DATA_RELOCATION

const QMetaObject *cv::image_window::metaObject() const
{
    return QObject::d_ptr->metaObject ? QObject::d_ptr->metaObject : &staticMetaObject;
}

void *cv::image_window::qt_metacast(const char *_clname)
{
    if (!_clname) return 0;
    if (!strcmp(_clname, qt_meta_stringdata_cv__image_window))
        return static_cast<void*>(const_cast< image_window*>(this));
    return QDialog::qt_metacast(_clname);
}

int cv::image_window::qt_metacall(QMetaObject::Call _c, int _id, void **_a)
{
    _id = QDialog::qt_metacall(_c, _id, _a);
    if (_id < 0)
        return _id;
    return _id;
}
QT_END_MOC_NAMESPACE

// MOC Generated code end /////////////////////////////////////////////

///////////////////////////////////////////////////////////////////////
// class global_image_application

global_image_application* global_image_application::_singleton = nullptr;

global_image_application::global_image_application(int &argc, char** argv) : QApplication(argc, argv), _last_key('\0') {

}

global_image_application::~global_image_application() {
	this->destroy_all_windows();
}

global_image_application *global_image_application::singleton() {
	if (!global_image_application::_singleton) {
		int argc_simulation = 1;
		char *argv_simulation[] = {" ", " "};
		global_image_application::_singleton = new global_image_application(argc_simulation, argv_simulation);
	}
	return global_image_application::_singleton;
}

void global_image_application::force_quit() {
	this->quit();
}

void global_image_application::assign_key(char key) {
	this->_last_key = key;
	for (auto w : this->_windows) {
		w->close();
	}
}

char global_image_application::get_last_key() const {
	return this->_last_key;
}

void global_image_application::create_window(const std::string &name, const image_array &image) {
	image_window *newWindow = new image_window;
	newWindow->setWindowTitle(name.c_str());
	newWindow->set_image(image);
	newWindow->show();
	this->_windows.push_back(newWindow);
}

void global_image_application::destroy_window(const std::string &name) {
	int winId = -1;
	for (int i = 0; i < this->_windows.size(); i++) {
		if (this->_windows[i]->windowTitle() == name.c_str()) {
			winId = i;
			break;
		}
	}
	if (winId != -1) {
		this->_windows[winId]->close();
		delete this->_windows[winId];
		this->_windows.erase(this->_windows.begin() + winId);
	} else {
		std::cerr << ("Window by name " + name + " does not exist.\n");
	}
}

void global_image_application::destroy_all_windows() {
	for (auto window : this->_windows) {
		window->close();
		delete window;
	}
	this->_windows.clear();
}

void imshow(const std::string &name, const image_array &image) {
	ASSERT(image.is_valid() && (image.channels() == 1 || image.channels() == 3 || image.channels() == 4));
	if (image.depth() != 1) {
		auto byte_copy = image.clone();
		byte_copy.convert_to<byte>();
		global_image_application::singleton()->create_window(name, byte_copy);
	} else {
		global_image_application::singleton()->create_window(name, image);
	}
}

void imclose(const std::string &name) {
	global_image_application::singleton()->destroy_window(name);
}

void imclose_all() {
	global_image_application::singleton()->destroy_all_windows();
}

char wait_key() {
	auto ga_inst = global_image_application::singleton();
	ga_inst->exec();
	return ga_inst->get_last_key();
}

}

#endif // CV_IGNORE_GUI
<|endoftext|>


<commit_before>/******************************************************************************
 * Copyright 2017 The Apollo 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 "modules/prediction/predictor/sequence/sequence_predictor.h"

#include <cmath>
#include <limits>
#include <memory>
#include <utility>

#include "modules/common/adapters/proto/adapter_config.pb.h"

#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/road_graph.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::LaneInfo;

void SequencePredictor::Predict(Obstacle* obstacle) {
  Clear();

  CHECK_NOTNULL(obstacle);
  CHECK_GT(obstacle->history_size(), 0);
}

void SequencePredictor::Clear() { Predictor::Clear(); }

std::string SequencePredictor::ToString(const LaneSequence& sequence) {
  std::string str_lane_sequence = "";
  if (sequence.lane_segment_size() > 0) {
    str_lane_sequence += sequence.lane_segment(0).lane_id();
  }
  for (int i = 1; i < sequence.lane_segment_size(); ++i) {
    str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
  }
  return str_lane_sequence;
}

void SequencePredictor::FilterLaneSequences(
    const LaneGraph& lane_graph, const std::string& lane_id,
    std::vector<bool>* enable_lane_sequence) {
  int num_lane_sequence = lane_graph.lane_sequence_size();
  std::vector<LaneChangeType> lane_change_type(num_lane_sequence,
                                               LaneChangeType::INVALID);
  std::pair<int, double> change(-1, -1.0);
  std::pair<int, double> all(-1, -1.0);

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);
    lane_change_type[i] = GetLaneChangeType(lane_id, sequence);

    if (lane_change_type[i] != LaneChangeType::LEFT &&
        lane_change_type[i] != LaneChangeType::RIGHT &&
        lane_change_type[i] != LaneChangeType::ONTO_LANE) {
      ADEBUG "Ignore lane sequence [" << ToString(sequence) << "].";
      continue;
    }

    // The obstacle has interference with ADC within a small distance
    double distance = GetLaneChangeDistanceWithADC(sequence);
    ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6)
           << distance;
    if (distance < FLAGS_lane_change_dist) {
      (*enable_lane_sequence)[i] = false;
      ADEBUG << "Filter trajectory [" << ToString(sequence)
             << "] due to small distance " << distance << ".";
    }
  }

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    if (!(*enable_lane_sequence)[i]) {
      ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
      continue;
    }

    double probability = sequence.probability();
    if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) {
      all.first = i;
      all.second = probability;
    }
    if (LaneChangeWithMaxProb(lane_change_type[i], probability,
                              change.second)) {
      change.first = i;
      change.second = probability;
    }
  }

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    if (!(*enable_lane_sequence)[i]) {
      ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
      continue;
    }

    double probability = sequence.probability();
    if (probability < FLAGS_lane_sequence_threshold && i != all.first) {
      (*enable_lane_sequence)[i] = false;
    } else if (change.first >= 0 && change.first < num_lane_sequence &&
               (lane_change_type[i] == LaneChangeType::LEFT ||
                lane_change_type[i] == LaneChangeType::RIGHT) &&
               lane_change_type[i] != lane_change_type[change.first]) {
      (*enable_lane_sequence)[i] = false;
    }
  }
}

SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType(
    const std::string& lane_id, const LaneSequence& lane_sequence) {
  PredictionMap* map = PredictionMap::instance();

  if (lane_id.empty()) {
    return LaneChangeType::ONTO_LANE;
  }

  std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
  if (lane_id == lane_change_id) {
    return LaneChangeType::STRAIGHT;
  } else {
    if (map->IsLeftNeighborLane(map->LaneById(lane_change_id),
                                map->LaneById(lane_id))) {
      return LaneChangeType::LEFT;
    } else if (map->IsRightNeighborLane(map->LaneById(lane_change_id),
                                        map->LaneById(lane_id))) {
      return LaneChangeType::RIGHT;
    }
  }
  return LaneChangeType::INVALID;
}

double SequencePredictor::GetLaneChangeDistanceWithADC(
    const LaneSequence& lane_sequence) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  if (!adc_container->HasOverlap(lane_sequence)) {
    return std::numeric_limits<double>::max();
  }

  Eigen::Vector2d adc_position;
  if (pose_container->ToPerceptionObstacle() != nullptr) {
    adc_position[0] = pose_container->ToPerceptionObstacle()->position().x();
    adc_position[1] = pose_container->ToPerceptionObstacle()->position().y();

    PredictionMap* map = PredictionMap::instance();
    std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
    double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();
    double lane_s = 0.0;
    double lane_l = 0.0;
    ADEBUG << "Obstacle lane " << obstacle_lane_id << " and s "
           << obstacle_lane_s;
    if (map->GetProjection(adc_position, map->LaneById(obstacle_lane_id),
                           &lane_s, &lane_l)) {
      ADEBUG << "ADC on lane s " << lane_s;
      return std::fabs(lane_s - obstacle_lane_s);
    }
  }
  return std::numeric_limits<double>::max();
}

bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type,
                                                const double& probability,
                                                const double& max_prob) {
  if (probability > max_prob) {
    return true;
  } else {
    double prob_diff = std::fabs(probability - max_prob);
    if (prob_diff <= std::numeric_limits<double>::epsilon() &&
        type == LaneChangeType::STRAIGHT) {
      return true;
    }
  }
  return false;
}

bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type,
                                              const double& probability,
                                              const double& max_prob) {
  if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) {
    if (probability > max_prob) {
      return true;
    }
  }
  return false;
}

}  // namespace prediction
}  // namespace apollo
<commit_msg>Prediction: added some debug info<commit_after>/******************************************************************************
 * Copyright 2017 The Apollo 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 "modules/prediction/predictor/sequence/sequence_predictor.h"

#include <cmath>
#include <limits>
#include <memory>
#include <utility>

#include "modules/common/adapters/proto/adapter_config.pb.h"

#include "modules/common/math/vec2d.h"
#include "modules/prediction/common/prediction_gflags.h"
#include "modules/prediction/common/prediction_map.h"
#include "modules/prediction/common/road_graph.h"
#include "modules/prediction/container/adc_trajectory/adc_trajectory_container.h"
#include "modules/prediction/container/container_manager.h"
#include "modules/prediction/container/pose/pose_container.h"

namespace apollo {
namespace prediction {

using ::apollo::common::PathPoint;
using ::apollo::common::TrajectoryPoint;
using ::apollo::common::adapter::AdapterConfig;
using ::apollo::common::math::Vec2d;
using ::apollo::hdmap::LaneInfo;

void SequencePredictor::Predict(Obstacle* obstacle) {
  Clear();

  CHECK_NOTNULL(obstacle);
  CHECK_GT(obstacle->history_size(), 0);
}

void SequencePredictor::Clear() { Predictor::Clear(); }

std::string SequencePredictor::ToString(const LaneSequence& sequence) {
  std::string str_lane_sequence = "";
  if (sequence.lane_segment_size() > 0) {
    str_lane_sequence += sequence.lane_segment(0).lane_id();
  }
  for (int i = 1; i < sequence.lane_segment_size(); ++i) {
    str_lane_sequence += ("->" + sequence.lane_segment(i).lane_id());
  }
  return str_lane_sequence;
}

void SequencePredictor::FilterLaneSequences(
    const LaneGraph& lane_graph, const std::string& lane_id,
    std::vector<bool>* enable_lane_sequence) {
  int num_lane_sequence = lane_graph.lane_sequence_size();
  std::vector<LaneChangeType> lane_change_type(num_lane_sequence,
                                               LaneChangeType::INVALID);
  std::pair<int, double> change(-1, -1.0);
  std::pair<int, double> all(-1, -1.0);

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);
    lane_change_type[i] = GetLaneChangeType(lane_id, sequence);

    if (lane_change_type[i] != LaneChangeType::LEFT &&
        lane_change_type[i] != LaneChangeType::RIGHT &&
        lane_change_type[i] != LaneChangeType::ONTO_LANE) {
      ADEBUG "Ignore lane sequence [" << ToString(sequence) << "].";
      continue;
    }

    // The obstacle has interference with ADC within a small distance
    double distance = GetLaneChangeDistanceWithADC(sequence);
    ADEBUG << "Distance to ADC " << std::fixed << std::setprecision(6)
           << distance;
    if (distance < FLAGS_lane_change_dist) {
      (*enable_lane_sequence)[i] = false;
      ADEBUG << "Filter trajectory [" << ToString(sequence)
             << "] due to small distance " << distance << ".";
    }
  }

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    if (!(*enable_lane_sequence)[i]) {
      ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
      continue;
    }

    double probability = sequence.probability();
    if (LaneSequenceWithMaxProb(lane_change_type[i], probability, all.second)) {
      all.first = i;
      all.second = probability;
    }
    if (LaneChangeWithMaxProb(lane_change_type[i], probability,
                              change.second)) {
      change.first = i;
      change.second = probability;
    }
  }

  for (int i = 0; i < num_lane_sequence; ++i) {
    const LaneSequence& sequence = lane_graph.lane_sequence(i);

    if (!(*enable_lane_sequence)[i]) {
      ADEBUG << "Disabled lane sequence [" << ToString(sequence) << "].";
      continue;
    }

    double probability = sequence.probability();
    if (probability < FLAGS_lane_sequence_threshold && i != all.first) {
      (*enable_lane_sequence)[i] = false;
    } else if (change.first >= 0 && change.first < num_lane_sequence &&
               (lane_change_type[i] == LaneChangeType::LEFT ||
                lane_change_type[i] == LaneChangeType::RIGHT) &&
               lane_change_type[i] != lane_change_type[change.first]) {
      (*enable_lane_sequence)[i] = false;
    }
  }
}

SequencePredictor::LaneChangeType SequencePredictor::GetLaneChangeType(
    const std::string& lane_id, const LaneSequence& lane_sequence) {
  PredictionMap* map = PredictionMap::instance();

  if (lane_id.empty()) {
    return LaneChangeType::ONTO_LANE;
  }

  std::string lane_change_id = lane_sequence.lane_segment(0).lane_id();
  if (lane_id == lane_change_id) {
    return LaneChangeType::STRAIGHT;
  } else {
    if (map->IsLeftNeighborLane(map->LaneById(lane_change_id),
                                map->LaneById(lane_id))) {
      return LaneChangeType::LEFT;
    } else if (map->IsRightNeighborLane(map->LaneById(lane_change_id),
                                        map->LaneById(lane_id))) {
      return LaneChangeType::RIGHT;
    }
  }
  return LaneChangeType::INVALID;
}

double SequencePredictor::GetLaneChangeDistanceWithADC(
    const LaneSequence& lane_sequence) {
  PoseContainer* pose_container = dynamic_cast<PoseContainer*>(
      ContainerManager::instance()->GetContainer(AdapterConfig::LOCALIZATION));
  ADCTrajectoryContainer* adc_container = dynamic_cast<ADCTrajectoryContainer*>(
      ContainerManager::instance()->GetContainer(
          AdapterConfig::PLANNING_TRAJECTORY));
  CHECK_NOTNULL(pose_container);
  CHECK_NOTNULL(adc_container);

  if (!adc_container->HasOverlap(lane_sequence)) {
    ADEBUG << "The sequence [" << ToString(lane_sequence)
           << "] has no overlap with ADC.";
    return std::numeric_limits<double>::max();
  }

  Eigen::Vector2d adc_position;
  if (pose_container->ToPerceptionObstacle() != nullptr) {
    adc_position[0] = pose_container->ToPerceptionObstacle()->position().x();
    adc_position[1] = pose_container->ToPerceptionObstacle()->position().y();

    PredictionMap* map = PredictionMap::instance();
    std::string obstacle_lane_id = lane_sequence.lane_segment(0).lane_id();
    double obstacle_lane_s = lane_sequence.lane_segment(0).start_s();
    double lane_s = 0.0;
    double lane_l = 0.0;
    if (map->GetProjection(adc_position, map->LaneById(obstacle_lane_id),
                           &lane_s, &lane_l)) {
      ADEBUG << "Distance with ADC is " << std::fabs(lane_s - obstacle_lane_s);
      return std::fabs(lane_s - obstacle_lane_s);
    }
  }

  ADEBUG << "Invalid ADC pose.";
  return std::numeric_limits<double>::max();
}

bool SequencePredictor::LaneSequenceWithMaxProb(const LaneChangeType& type,
                                                const double& probability,
                                                const double& max_prob) {
  if (probability > max_prob) {
    return true;
  } else {
    double prob_diff = std::fabs(probability - max_prob);
    if (prob_diff <= std::numeric_limits<double>::epsilon() &&
        type == LaneChangeType::STRAIGHT) {
      return true;
    }
  }
  return false;
}

bool SequencePredictor::LaneChangeWithMaxProb(const LaneChangeType& type,
                                              const double& probability,
                                              const double& max_prob) {
  if (type == LaneChangeType::LEFT || type == LaneChangeType::RIGHT) {
    if (probability > max_prob) {
      return true;
    }
  }
  return false;
}

}  // namespace prediction
}  // namespace apollo
<|endoftext|>


<commit_before>
#include "WifiScan.h"
#include "application.h"
#include "wlan.h"

int WifiScan::startScan() {
   const unsigned long intervalTime[16] = { 2000, 2000, 2000, 2000,  2000,
        2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000 };

    wlan_ioctl_set_scan_params(4000, 20, 100, 5, 0x7FF, -120, 0, 300,
        (unsigned long * ) &intervalTime);

    return 0;
}

/**
 * Determine if a given region of memory is empty - i.e. all zeros.
 */
bool is_empty(void* data, unsigned len) {
    for (unsigned i=0; i<len; i++)
        if (((uint8_t*)data)[i])
            return false;
    return true;
}

bool WifiScan::next(WifiScanResults_t& scanResult) {
    // clear the result
    memset(&scanResult, 0, sizeof(scanResult));
    long err = wlan_ioctl_get_scan_results(0, (uint8_t* ) &scanResult);
    return (!err && scanResult.valid && !is_empty(scanResult.bssid, sizeof(scanResult.bssid)));
}

<commit_msg>Update wifiscan.cpp<commit_after>
//#include "WifiScan.h"
#include "application.h"
#include "wlan.h"

int WifiScan::startScan() {
   const unsigned long intervalTime[16] = { 2000, 2000, 2000, 2000,  2000,
        2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000, 2000 };

    wlan_ioctl_set_scan_params(4000, 20, 100, 5, 0x7FF, -120, 0, 300,
        (unsigned long * ) &intervalTime);

    return 0;
}

/**
 * Determine if a given region of memory is empty - i.e. all zeros.
 */
bool is_empty(void* data, unsigned len) {
    for (unsigned i=0; i<len; i++)
        if (((uint8_t*)data)[i])
            return false;
    return true;
}

bool WifiScan::next(WifiScanResults_t& scanResult) {
    // clear the result
    memset(&scanResult, 0, sizeof(scanResult));
    long err = wlan_ioctl_get_scan_results(0, (uint8_t* ) &scanResult);
    return (!err && scanResult.valid && !is_empty(scanResult.bssid, sizeof(scanResult.bssid)));
}

<|endoftext|>


<commit_before>#include "UnsupportedContentHandler.h"
#include "WebPage.h"
#include <QNetworkReply>

UnsupportedContentHandler::UnsupportedContentHandler(WebPage *page, QNetworkReply *reply, QObject *parent) : QObject(parent) {
  m_page = page;
  m_reply = reply;
}

void UnsupportedContentHandler::renderNonHtmlContent() {
  QByteArray text = m_reply->readAll();
  m_page->mainFrame()->setContent(text, QString("text/plain"), m_reply->url());
  m_page->unsupportedContentFinishedReply(m_reply);
  m_page->loadFinished(true);
  this->deleteLater();
}

void UnsupportedContentHandler::waitForReplyToFinish() {
  connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
  disconnect(m_page, SIGNAL(loadFinished(bool)), m_page, SLOT(loadFinished(bool)));
}

void UnsupportedContentHandler::replyFinished() {
  renderNonHtmlContent();
  connect(m_page, SIGNAL(loadFinished(bool)), m_page, SLOT(loadFinished(bool)));
}
<commit_msg>Don't disconnect loadFinished in UnsupportedContentHandler<commit_after>#include "UnsupportedContentHandler.h"
#include "WebPage.h"
#include <QNetworkReply>

UnsupportedContentHandler::UnsupportedContentHandler(WebPage *page, QNetworkReply *reply, QObject *parent) : QObject(parent) {
  m_page = page;
  m_reply = reply;
}

void UnsupportedContentHandler::renderNonHtmlContent() {
  QByteArray text = m_reply->readAll();
  m_page->mainFrame()->setContent(text, QString("text/plain"), m_reply->url());
  m_page->unsupportedContentFinishedReply(m_reply);
  this->deleteLater();
}

void UnsupportedContentHandler::waitForReplyToFinish() {
  connect(m_reply, SIGNAL(finished()), this, SLOT(replyFinished()));
}

void UnsupportedContentHandler::replyFinished() {
  renderNonHtmlContent();
}
<|endoftext|>


<commit_before>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProbeFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkProbeFilter.h"
#include "vtkObjectFactory.h"
#include "vtkImageData.h"

vtkCxxRevisionMacro(vtkProbeFilter, "1.72");
vtkStandardNewMacro(vtkProbeFilter);

//----------------------------------------------------------------------------
vtkProbeFilter::vtkProbeFilter()
{
  this->SpatialMatch = 0;
  this->ValidPoints = vtkIdTypeArray::New();
}

//----------------------------------------------------------------------------
vtkProbeFilter::~vtkProbeFilter()
{
  this->ValidPoints->Delete();
  this->ValidPoints = NULL;
}

//----------------------------------------------------------------------------
void vtkProbeFilter::SetSource(vtkDataSet *input)
{
  this->vtkProcessObject::SetNthInput(1, input);
}

//----------------------------------------------------------------------------
vtkDataSet *vtkProbeFilter::GetSource()
{
  if (this->NumberOfInputs < 2)
    {
    return NULL;
    }

  return (vtkDataSet *)(this->Inputs[1]);
}

//----------------------------------------------------------------------------
void vtkProbeFilter::Execute()
{
  vtkIdType ptId, numPts;
  float *x, tol2;
  vtkCell *cell;
  vtkPointData *pd, *outPD;
  int subId;
  vtkDataSet *source = this->GetSource();
  vtkDataSet *input = this->GetInput();
  vtkDataSet *output= this->GetOutput();
  float pcoords[3], *weights;
  float fastweights[256];

  vtkDebugMacro(<<"Probing data");

  if (source == NULL)
    {
    vtkErrorMacro (<< "Source is NULL.");
    return;
    }

  pd = source->GetPointData();

  // lets use a stack allocated array if possible for performance reasons
  int mcs = source->GetMaxCellSize();
  if (mcs<=256)
    {
    weights = fastweights;
    }
  else
    {
    weights = new float[mcs];
    }

  // First, copy the input to the output as a starting point
  output->CopyStructure( input );

  numPts = input->GetNumberOfPoints();
  this->ValidPoints->Allocate(numPts);

  // Allocate storage for output PointData
  //
  outPD = output->GetPointData();
  outPD->InterpolateAllocate(pd);

  // Use tolerance as a function of size of source data
  //
  tol2 = source->GetLength();
  tol2 = tol2 ? tol2*tol2 / 1000.0 : 0.001;

  // Loop over all input points, interpolating source data
  //
  int abort=0;
  vtkIdType progressInterval=numPts/20 + 1;
  for (ptId=0; ptId < numPts && !abort; ptId++)
    {
    if ( !(ptId % progressInterval) )
      {
      this->UpdateProgress((float)ptId/numPts);
      abort = GetAbortExecute();
      }

    // Get the xyz coordinate of the point in the input dataset
    x = input->GetPoint(ptId);

    // Find the cell that contains xyz and get it
    cell = source->FindAndGetCell(x,NULL,-1,tol2,subId,pcoords,weights);
    if (cell)
      {
      // Interpolate the point data
      outPD->InterpolatePoint(pd,ptId,cell->PointIds,weights);
      this->ValidPoints->InsertNextValue(ptId);
      }
    else
      {
      outPD->NullPoint(ptId);
      }
    }
  // BUG FIX: JB.
  // Output gets setup from input, but when output is imagedata, scalartype
  // depends on source scalartype not input scalartype
  if (output->IsA("vtkImageData"))
    {
    vtkImageData *out = (vtkImageData*)output;
    vtkDataArray *s = outPD->GetScalars();
    out->SetScalarType(s->GetDataType());
    out->SetNumberOfScalarComponents(s->GetNumberOfComponents());
    }
  if (mcs>256)
    {
    delete [] weights;
    }
}

//----------------------------------------------------------------------------
void vtkProbeFilter::ExecuteInformation()
{
  // Copy whole extent ...
  this->vtkSource::ExecuteInformation();

  if (this->GetInput() == NULL || this->GetSource() == NULL)
    {
    vtkErrorMacro("Missing input or source");
    return;
    }
}

//----------------------------------------------------------------------------
void vtkProbeFilter::ComputeInputUpdateExtents( vtkDataObject *output )
{
  vtkDataObject *input = this->GetInput();
  vtkDataObject *source = this->GetSource();
  int usePiece = 0;

  if (input == NULL || source == NULL)
    {
    vtkErrorMacro("Missing input or source.");
    return;
    }

  // What ever happend to CopyUpdateExtent in vtkDataObject?
  // Copying both piece and extent could be bad.  Setting the piece
  // of a structured data set will affect the extent.
  if (output->IsA("vtkUnstructuredGrid") || output->IsA("vtkPolyData"))
    {
    usePiece = 1;
    }

  input->RequestExactExtentOn();

  if ( ! this->SpatialMatch)
    {
    source->SetUpdateExtent(0, 1, 0);
    }
  else if (this->SpatialMatch == 1)
    {
    if (usePiece)
      {
      // Request an extra ghost level because the probe
      // gets external values with computation prescision problems.
      // I think the probe should be changed to have an epsilon ...
      source->SetUpdateExtent(output->GetUpdatePiece(),
                              output->GetUpdateNumberOfPieces(),
                              output->GetUpdateGhostLevel()+1);
      }
    else
      {
      source->SetUpdateExtent(output->GetUpdateExtent());
      }
    }

  if (usePiece)
    {
    input->SetUpdateExtent(output->GetUpdatePiece(),
                           output->GetUpdateNumberOfPieces(),
                           output->GetUpdateGhostLevel());
    }
  else
    {
    input->SetUpdateExtent(output->GetUpdateExtent());
    }

  // Use the whole input in all processes, and use the requested update
  // extent of the output to divide up the source.
  if (this->SpatialMatch == 2)
    {
    input->SetUpdateExtent(0, 1, 0);
    source->SetUpdateExtent(output->GetUpdatePiece(),
                            output->GetUpdateNumberOfPieces(),
                            output->GetUpdateGhostLevel());
    }
}

//----------------------------------------------------------------------------
void vtkProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSet *source = this->GetSource();

  this->Superclass::PrintSelf(os,indent);
  os << indent << "Source: " << source << "\n";
  if (this->SpatialMatch)
    {
    os << indent << "SpatialMatchOn\n";
    }
  else
    {
    os << indent << "SpatialMatchOff\n";
    }
  os << indent << "ValidPoints: " << this->ValidPoints << "\n";
}
<commit_msg>Fix for paraview rpobe bug.<commit_after>/*=========================================================================

  Program:   Visualization Toolkit
  Module:    vtkProbeFilter.cxx
  Language:  C++
  Date:      $Date$
  Version:   $Revision$

  Copyright (c) 1993-2002 Ken Martin, Will Schroeder, Bill Lorensen
  All rights reserved.
  See Copyright.txt or http://www.kitware.com/Copyright.htm for details.

     This software is distributed WITHOUT ANY WARRANTY; without even
     the implied warranty of MERCHANTABILITY or FITNESS FOR A PARTICULAR
     PURPOSE.  See the above copyright notice for more information.

=========================================================================*/
#include "vtkProbeFilter.h"
#include "vtkObjectFactory.h"
#include "vtkImageData.h"

vtkCxxRevisionMacro(vtkProbeFilter, "1.73");
vtkStandardNewMacro(vtkProbeFilter);

//----------------------------------------------------------------------------
vtkProbeFilter::vtkProbeFilter()
{
  this->SpatialMatch = 0;
  this->ValidPoints = vtkIdTypeArray::New();
}

//----------------------------------------------------------------------------
vtkProbeFilter::~vtkProbeFilter()
{
  this->ValidPoints->Delete();
  this->ValidPoints = NULL;
}

//----------------------------------------------------------------------------
void vtkProbeFilter::SetSource(vtkDataSet *input)
{
  this->vtkProcessObject::SetNthInput(1, input);
}

//----------------------------------------------------------------------------
vtkDataSet *vtkProbeFilter::GetSource()
{
  if (this->NumberOfInputs < 2)
    {
    return NULL;
    }

  return (vtkDataSet *)(this->Inputs[1]);
}

//----------------------------------------------------------------------------
void vtkProbeFilter::Execute()
{
  vtkIdType ptId, numPts;
  float *x, tol2;
  vtkCell *cell;
  vtkPointData *pd, *outPD;
  int subId;
  vtkDataSet *source = this->GetSource();
  vtkDataSet *input = this->GetInput();
  vtkDataSet *output= this->GetOutput();
  float pcoords[3], *weights;
  float fastweights[256];

  vtkDebugMacro(<<"Probing data");

  if (source == NULL)
    {
    vtkErrorMacro (<< "Source is NULL.");
    return;
    }

  pd = source->GetPointData();

  // lets use a stack allocated array if possible for performance reasons
  int mcs = source->GetMaxCellSize();
  if (mcs<=256)
    {
    weights = fastweights;
    }
  else
    {
    weights = new float[mcs];
    }

  // First, copy the input to the output as a starting point
  output->CopyStructure( input );

  numPts = input->GetNumberOfPoints();
  this->ValidPoints->Allocate(numPts);

  // Allocate storage for output PointData
  //
  outPD = output->GetPointData();
  outPD->InterpolateAllocate(pd);

  // Use tolerance as a function of size of source data
  //
  tol2 = source->GetLength();
  tol2 = tol2 ? tol2*tol2 / 1000.0 : 0.001;

  // Loop over all input points, interpolating source data
  //
  int abort=0;
  vtkIdType progressInterval=numPts/20 + 1;
  for (ptId=0; ptId < numPts && !abort; ptId++)
    {
    if ( !(ptId % progressInterval) )
      {
      this->UpdateProgress((float)ptId/numPts);
      abort = GetAbortExecute();
      }

    // Get the xyz coordinate of the point in the input dataset
    x = input->GetPoint(ptId);

    // Find the cell that contains xyz and get it
    cell = source->FindAndGetCell(x,NULL,-1,tol2,subId,pcoords,weights);
    if (cell)
      {
      // Interpolate the point data
      outPD->InterpolatePoint(pd,ptId,cell->PointIds,weights);
      this->ValidPoints->InsertNextValue(ptId);
      }
    else
      {
      outPD->NullPoint(ptId);
      }
    }
  // BUG FIX: JB.
  // Output gets setup from input, but when output is imagedata, scalartype
  // depends on source scalartype not input scalartype
  if (output->IsA("vtkImageData"))
    {
    vtkImageData *out = (vtkImageData*)output;
    vtkDataArray *s = outPD->GetScalars();
    out->SetScalarType(s->GetDataType());
    out->SetNumberOfScalarComponents(s->GetNumberOfComponents());
    }
  if (mcs>256)
    {
    delete [] weights;
    }
}

//----------------------------------------------------------------------------
void vtkProbeFilter::ExecuteInformation()
{
  if (this->GetInput() == NULL || this->GetSource() == NULL)
    {
    vtkErrorMacro("Missing input or source");
    return;
    }

  // Copy whole extent ...
  this->vtkSource::ExecuteInformation();

  // Special case for ParaView.
  if (this->SpatialMatch == 2)
    {
    this->GetOutput()->SetMaximumNumberOfPieces(this->GetSource()->GetMaximumNumberOfPieces());
    }

  if (this->SpatialMatch == 1)
    {
    int m1 = this->GetInput()->GetMaximumNumberOfPieces();
    int m2 = this->GetSource()->GetMaximumNumberOfPieces();
    if (m1 < 0 && m2 < 0)
      {
      this->GetOutput()->SetMaximumNumberOfPieces(-1);
      }
    else
      {
      if (m1 < -1)
        {
        m1 = VTK_LARGE_INTEGER;
        }
      if (m2 < -1)
        {
        m2 = VTK_LARGE_INTEGER;
        }
      if (m2 < m1)
        {
        m1 = m2;
        }
      this->GetOutput()->SetMaximumNumberOfPieces(m1);
      }
    }
}

//----------------------------------------------------------------------------
void vtkProbeFilter::ComputeInputUpdateExtents( vtkDataObject *output )
{
  vtkDataObject *input = this->GetInput();
  vtkDataObject *source = this->GetSource();
  int usePiece = 0;

  if (input == NULL || source == NULL)
    {
    vtkErrorMacro("Missing input or source.");
    return;
    }

  // What ever happend to CopyUpdateExtent in vtkDataObject?
  // Copying both piece and extent could be bad.  Setting the piece
  // of a structured data set will affect the extent.
  if (output->IsA("vtkUnstructuredGrid") || output->IsA("vtkPolyData"))
    {
    usePiece = 1;
    }

  input->RequestExactExtentOn();

  if ( ! this->SpatialMatch)
    {
    source->SetUpdateExtent(0, 1, 0);
    }
  else if (this->SpatialMatch == 1)
    {
    if (usePiece)
      {
      // Request an extra ghost level because the probe
      // gets external values with computation prescision problems.
      // I think the probe should be changed to have an epsilon ...
      source->SetUpdateExtent(output->GetUpdatePiece(),
                              output->GetUpdateNumberOfPieces(),
                              output->GetUpdateGhostLevel()+1);
      }
    else
      {
      source->SetUpdateExtent(output->GetUpdateExtent());
      }
    }

  if (usePiece)
    {
    input->SetUpdateExtent(output->GetUpdatePiece(),
                           output->GetUpdateNumberOfPieces(),
                           output->GetUpdateGhostLevel());
    }
  else
    {
    input->SetUpdateExtent(output->GetUpdateExtent());
    }

  // Use the whole input in all processes, and use the requested update
  // extent of the output to divide up the source.
  if (this->SpatialMatch == 2)
    {
    input->SetUpdateExtent(0, 1, 0);
    source->SetUpdateExtent(output->GetUpdatePiece(),
                            output->GetUpdateNumberOfPieces(),
                            output->GetUpdateGhostLevel());
    }
}

//----------------------------------------------------------------------------
void vtkProbeFilter::PrintSelf(ostream& os, vtkIndent indent)
{
  vtkDataSet *source = this->GetSource();

  this->Superclass::PrintSelf(os,indent);
  os << indent << "Source: " << source << "\n";
  if (this->SpatialMatch)
    {
    os << indent << "SpatialMatchOn\n";
    }
  else
    {
    os << indent << "SpatialMatchOff\n";
    }
  os << indent << "ValidPoints: " << this->ValidPoints << "\n";
}
<|endoftext|>


<commit_before>
// Copyright (c) 2015 Pierre MOULON.

// 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 "image_describer.hpp"

#include <openMVG/config.hpp>
#include <openMVG/features/image_describer_akaze.hpp>
#include <openMVG/features/sift/SIFT_describer.hpp>
#include <openMVG/features/sift/SIFT_vlfeat_float_describer.hpp>
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
#include <openMVG/features/cctag/CCTAG_describer.hpp>
#endif //OPENMVG_HAVE_CCTAG
#include <openMVG/features/openCV/AKAZE_openCV_describer.hpp>
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
#include <openMVG/features/openCV/SIFT_openCV_describer.hpp>
#endif //OPENMVG_USE_OCVSIFT

#include <stdexcept>

namespace openMVG{
namespace features{

EDESCRIBER_PRESET describerPreset_stringToEnum(const std::string& sPreset)
{
  if(sPreset == "LOW")
    return LOW_PRESET;
  if (sPreset == "MEDIUM")
    return MEDIUM_PRESET;
  if(sPreset == "NORMAL")
    return NORMAL_PRESET;
  if (sPreset == "HIGH")
    return HIGH_PRESET;
  if (sPreset == "ULTRA")
    return ULTRA_PRESET;
  throw std::invalid_argument("Invalid descriptor preset: " + sPreset);
}

std::string describerPreset_enumToString(const EDESCRIBER_PRESET preset)
{
  if(preset == LOW_PRESET)
    return "LOW";
  if (preset == MEDIUM_PRESET)
    return "MEDIUM";
  if(preset == NORMAL_PRESET)
    return "NORMAL";
  if (preset == HIGH_PRESET)
    return "HIGH";
  if (preset == ULTRA_PRESET)
    return "ULTRA";
  throw std::invalid_argument("Unrecognized EDESCRIBER_PRESET "+std::to_string(preset));
}

std::ostream& operator<<(std::ostream& os, EDESCRIBER_PRESET p)
{
    return os << describerPreset_enumToString(p);
}

std::istream& operator>>(std::istream& in, EDESCRIBER_PRESET& p)
{
    std::string token;
    in >> token;
    p = describerPreset_stringToEnum(token);
    return in;
}

std::unique_ptr<Image_describer> createImageDescriber(EImageDescriberType imageDescriberType)
{
  std::unique_ptr<Image_describer> describerPtr;

  switch(imageDescriberType)
  {
    case EImageDescriberType::SIFT:        describerPtr.reset(new SIFT_ImageDescriber(SiftParams())); break;
    case EImageDescriberType::SIFT_FLOAT:  describerPtr.reset(new SIFT_vlfeat_float_ImageDescriber(SiftParams())); break;
    case EImageDescriberType::AKAZE:       describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MSURF))); break;
    case EImageDescriberType::AKAZE_MLDB:  describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MLDB))); break;
    case EImageDescriberType::AKAZE_LIOP:  describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_LIOP))); break;

#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
    case EImageDescriberType::CCTAG3:      describerPtr.reset(new CCTAG_Image_describer(3)); break;
    case EImageDescriberType::CCTAG4:      describerPtr.reset(new CCTAG_Image_describer(4)); break;
#endif //OPENMVG_HAVE_CCTAG

#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_OPENCV)
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
  case EImageDescriberType::SIFT_OCV:      describerPtr.reset(new SIFT_openCV_ImageDescriber()); break;
#endif //OPENMVG_USE_OCVSIFT
  case EImageDescriberType::AKAZE_OCV:     describerPtr.reset(new AKAZE_openCV_ImageDescriber()); break;
#endif //OPENMVG_HAVE_OPENCV

    default: throw std::out_of_range("Invalid imageDescriber enum");
  }
  assert(describerPtr != nullptr);

  return describerPtr;
}

}//namespace features
}//namespace openMVG
<commit_msg>[features] fix: AKAZE_openCV_describer include without OPENMVG_HAVE_OPENCV check<commit_after>
// Copyright (c) 2015 Pierre MOULON.

// 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 "image_describer.hpp"

#include <openMVG/config.hpp>
#include <openMVG/features/image_describer_akaze.hpp>
#include <openMVG/features/sift/SIFT_describer.hpp>
#include <openMVG/features/sift/SIFT_vlfeat_float_describer.hpp>
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
#include <openMVG/features/cctag/CCTAG_describer.hpp>
#endif //OPENMVG_HAVE_CCTAG
#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_OPENCV)
#include <openMVG/features/openCV/AKAZE_openCV_describer.hpp>
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
#include <openMVG/features/openCV/SIFT_openCV_describer.hpp>
#endif //OPENMVG_USE_OCVSIFT
#endif //OPENMVG_HAVE_OPENCV

#include <stdexcept>

namespace openMVG{
namespace features{

EDESCRIBER_PRESET describerPreset_stringToEnum(const std::string& sPreset)
{
  if(sPreset == "LOW")
    return LOW_PRESET;
  if (sPreset == "MEDIUM")
    return MEDIUM_PRESET;
  if(sPreset == "NORMAL")
    return NORMAL_PRESET;
  if (sPreset == "HIGH")
    return HIGH_PRESET;
  if (sPreset == "ULTRA")
    return ULTRA_PRESET;
  throw std::invalid_argument("Invalid descriptor preset: " + sPreset);
}

std::string describerPreset_enumToString(const EDESCRIBER_PRESET preset)
{
  if(preset == LOW_PRESET)
    return "LOW";
  if (preset == MEDIUM_PRESET)
    return "MEDIUM";
  if(preset == NORMAL_PRESET)
    return "NORMAL";
  if (preset == HIGH_PRESET)
    return "HIGH";
  if (preset == ULTRA_PRESET)
    return "ULTRA";
  throw std::invalid_argument("Unrecognized EDESCRIBER_PRESET "+std::to_string(preset));
}

std::ostream& operator<<(std::ostream& os, EDESCRIBER_PRESET p)
{
    return os << describerPreset_enumToString(p);
}

std::istream& operator>>(std::istream& in, EDESCRIBER_PRESET& p)
{
    std::string token;
    in >> token;
    p = describerPreset_stringToEnum(token);
    return in;
}

std::unique_ptr<Image_describer> createImageDescriber(EImageDescriberType imageDescriberType)
{
  std::unique_ptr<Image_describer> describerPtr;

  switch(imageDescriberType)
  {
    case EImageDescriberType::SIFT:        describerPtr.reset(new SIFT_ImageDescriber(SiftParams())); break;
    case EImageDescriberType::SIFT_FLOAT:  describerPtr.reset(new SIFT_vlfeat_float_ImageDescriber(SiftParams())); break;
    case EImageDescriberType::AKAZE:       describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MSURF))); break;
    case EImageDescriberType::AKAZE_MLDB:  describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_MLDB))); break;
    case EImageDescriberType::AKAZE_LIOP:  describerPtr.reset(new AKAZE_Image_describer(AKAZEParams(AKAZEConfig(), features::AKAZE_LIOP))); break;

#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_CCTAG)
    case EImageDescriberType::CCTAG3:      describerPtr.reset(new CCTAG_Image_describer(3)); break;
    case EImageDescriberType::CCTAG4:      describerPtr.reset(new CCTAG_Image_describer(4)); break;
#endif //OPENMVG_HAVE_CCTAG

#if OPENMVG_IS_DEFINED(OPENMVG_HAVE_OPENCV)
#if OPENMVG_IS_DEFINED(OPENMVG_USE_OCVSIFT)
  case EImageDescriberType::SIFT_OCV:      describerPtr.reset(new SIFT_openCV_ImageDescriber()); break;
#endif //OPENMVG_USE_OCVSIFT
  case EImageDescriberType::AKAZE_OCV:     describerPtr.reset(new AKAZE_openCV_ImageDescriber()); break;
#endif //OPENMVG_HAVE_OPENCV

    default: throw std::out_of_range("Invalid imageDescriber enum");
  }
  assert(describerPtr != nullptr);

  return describerPtr;
}

}//namespace features
}//namespace openMVG
<|endoftext|>