<commit_before>#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"

#include <include/amici.h>
#include <cstring>
#include "wrapfunctions.h"
#include "src/ami_hdf5.h"

#define HDFFILE "../expectedResults.h5"
#define TEST_EPSILON 1e-12

#ifndef __APPLE__
#include <iostream>
#endif

TEST_GROUP(group1)
{
    void setup() {

    }

    void teardown() {

    }
};

UserData *getTestUserData() {
    UserData *udata = new UserData;
    memset(udata, 0, sizeof(*udata));

    init_modeldims(udata);

    udata->am_qpositivex = new double[udata->am_nx];
    udata->am_p = new double[udata->am_np];
    udata->am_k = new double[udata->am_nk];
    udata->am_idlist = new realtype[udata->am_np]();
    for(int i = 0; i < udata->am_np; ++i)
        udata->am_idlist[i] = 0;

    processUserData(udata);

    return udata;
}

ExpData *getTestExpData() {
    ExpData *edata = new ExpData;
    memset(edata, 0, sizeof(*edata));

    return edata;
}

/*
 * Test for mem leaks in UserData initalization / destruction
 */
TEST(group1, testCreateAndFreeUserData) {
    UserData *udata = getTestUserData();

    freeUserData(udata);
}

/*
 * Test for mem leaks in ExpData initalization / destruction
 */

TEST(group1, testCreateAndFreeExpData) {
    ExpData *edata = getTestExpData();

    freeExpData(edata);
}

/*
 * Test for mem leaks in ReturnData initalization / destruction
 */

TEST(group1, testCreateAndFreeReturnData) {
    ReturnData *rdata = new ReturnData;
    memset(rdata, 0, sizeof(*rdata));

    freeReturnData(rdata);
}

void checkEqualArray(const double *expected, const double *actual, int length) {
    for(int i = 0; i < length; ++i)
    {
#ifndef __APPLE__
        if(expected[i] != actual[i])
            std::cout<<i<<"/"<<length<<" "<<expected[i]<<" "<<actual[i]<<std::endl;
#endif
        DOUBLES_EQUAL(expected[i], actual[i], TEST_EPSILON);
    }
}

void verifyReturnData(const char* resultPath, const ReturnData *rdata, const UserData*udata) {
    CHECK_TRUE(isinf(*rdata->am_llhdata) || isnan(*rdata->am_llhdata));

    // compare to saved data in hdf file
    hid_t file_id = H5Fopen(HDFFILE, H5F_ACC_RDONLY, H5P_DEFAULT);

    hsize_t m, n, o;

    double *expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "x", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_xdata, udata->am_nt * udata->am_nx);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "J", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_Jdata, udata->am_nx * udata->am_nx);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numrhsevals", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_numrhsevalsdata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numsteps", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_numstepsdata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "order", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_orderdata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "y", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_ydata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "sigmay", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_sigmaydata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "xdot", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_xdotdata, udata->am_nx);
    delete[] expected;

    if(udata->am_sensi > 0) {
        AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "sllh", &expected, &m, &n);
        checkEqualArray(expected, rdata->am_sllhdata, udata->am_np);
        delete[] expected;

        AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numrhsevalsS", &expected, &m, &n);
        checkEqualArray(expected, rdata->am_numrhsevalsSdata, udata->am_nt);
        delete[] expected;

        AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numstepsS", &expected, &m, &n);
        checkEqualArray(expected, rdata->am_numstepsSdata, udata->am_nt);
        delete[] expected;

        AMI_HDF5_getDoubleArrayAttribute3D(file_id, resultPath, "ssigmay", &expected, &m, &n, &o);
        checkEqualArray(expected, rdata->am_ssigmaydata, udata->am_nt * udata->am_ny * udata->am_nplist);
        delete[] expected;

        if(udata->am_sensi_meth == 1) {
            // TODO: there are deviations in sx and sy CHECK!
//            AMI_HDF5_getDoubleArrayAttribute3D(file_id, resultPath, "sx", &expected, &m, &n, &o);
//            checkEqualArray(expected, rdata->am_sxdata, udata->am_nt * udata->am_nx * udata->am_nplist);
//            delete[] expected;

//            AMI_HDF5_getDoubleArrayAttribute3D(file_id, resultPath, "sy", &expected, &m, &n, &o);
//            checkEqualArray(expected, rdata->am_sydata, udata->am_nt * udata->am_ny * udata->am_nplist);
//            delete[] expected;

        }

    } else {
        POINTERS_EQUAL(NULL, rdata->am_sllhdata);
        POINTERS_EQUAL(NULL, rdata->am_numrhsevalsSdata);
        POINTERS_EQUAL(NULL, rdata->am_numstepsSdata);

    }

    H5Fclose(file_id);
}

TEST(group1, testSimulation) {
    // read simulation options
    UserData *udata = AMI_HDF5_readSimulationUserDataFromFileName(HDFFILE, "/model_dirac/nosensi/options");
    ExpData *edata = getTestExpData();

    int status;
    ReturnData *rdata = getSimulationResults(udata, edata, &status);
    CHECK_EQUAL(0, status);

    // TODO proper paths /testDirac1/...
    verifyReturnData("/model_dirac/nosensi/results", rdata, udata);

    freeReturnData(rdata);
    freeExpData(edata);
    freeUserData(udata);
}

TEST(group1, testSimulationExpData) {

}

TEST(group1, testSensitivityForward) {
    // read simulation options
    UserData *udata = AMI_HDF5_readSimulationUserDataFromFileName(HDFFILE, "/model_dirac/sensiforward/options");
    ExpData *edata = getTestExpData();

    int status;
    ReturnData *rdata = getSimulationResults(udata, edata, &status);
    CHECK_EQUAL(0, status);

    // TODO proper paths /testDirac1/...
    verifyReturnData("/model_dirac/sensiforward/results", rdata, udata);

    freeReturnData(rdata);
    freeExpData(edata);
    freeUserData(udata);
}

TEST(group1, testSensitivityState) {

}

TEST(group1, testSensitivityAdjoint) {

}

<commit_msg>Reenable checks for sx and sy<commit_after>#include "CppUTest/TestHarness.h"
#include "CppUTestExt/MockSupport.h"

#include <include/amici.h>
#include <cstring>
#include "wrapfunctions.h"
#include "src/ami_hdf5.h"

#define HDFFILE "../expectedResults.h5"
#define TEST_EPSILON 1e-12

#ifndef __APPLE__
#include <iostream>
#endif

TEST_GROUP(group1)
{
    void setup() {

    }

    void teardown() {

    }
};

UserData *getTestUserData() {
    UserData *udata = new UserData;
    memset(udata, 0, sizeof(*udata));

    init_modeldims(udata);

    udata->am_qpositivex = new double[udata->am_nx];
    udata->am_p = new double[udata->am_np];
    udata->am_k = new double[udata->am_nk];
    udata->am_idlist = new realtype[udata->am_np]();
    for(int i = 0; i < udata->am_np; ++i)
        udata->am_idlist[i] = 0;

    processUserData(udata);

    return udata;
}

ExpData *getTestExpData() {
    ExpData *edata = new ExpData;
    memset(edata, 0, sizeof(*edata));

    return edata;
}

/*
 * Test for mem leaks in UserData initalization / destruction
 */
TEST(group1, testCreateAndFreeUserData) {
    UserData *udata = getTestUserData();

    freeUserData(udata);
}

/*
 * Test for mem leaks in ExpData initalization / destruction
 */

TEST(group1, testCreateAndFreeExpData) {
    ExpData *edata = getTestExpData();

    freeExpData(edata);
}

/*
 * Test for mem leaks in ReturnData initalization / destruction
 */

TEST(group1, testCreateAndFreeReturnData) {
    ReturnData *rdata = new ReturnData;
    memset(rdata, 0, sizeof(*rdata));

    freeReturnData(rdata);
}

void checkEqualArray(const double *expected, const double *actual, int length) {
    for(int i = 0; i < length; ++i)
    {
#ifndef __APPLE__
        if(expected[i] != actual[i])
            std::cout<<i<<"/"<<length<<" "<<expected[i]<<" "<<actual[i]<<std::endl;
#endif
        DOUBLES_EQUAL(expected[i], actual[i], TEST_EPSILON);
    }
}

void verifyReturnData(const char* resultPath, const ReturnData *rdata, const UserData*udata) {
    CHECK_TRUE(isinf(*rdata->am_llhdata) || isnan(*rdata->am_llhdata));

    // compare to saved data in hdf file
    hid_t file_id = H5Fopen(HDFFILE, H5F_ACC_RDONLY, H5P_DEFAULT);

    hsize_t m, n, o;

    double *expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "x", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_xdata, udata->am_nt * udata->am_nx);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "J", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_Jdata, udata->am_nx * udata->am_nx);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numrhsevals", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_numrhsevalsdata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numsteps", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_numstepsdata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "order", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_orderdata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "y", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_ydata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "sigmay", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_sigmaydata, udata->am_nt);
    delete[] expected;

    AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "xdot", &expected, &m, &n);
    checkEqualArray(expected, rdata->am_xdotdata, udata->am_nx);
    delete[] expected;

    if(udata->am_sensi > 0) {
        AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "sllh", &expected, &m, &n);
        checkEqualArray(expected, rdata->am_sllhdata, udata->am_np);
        delete[] expected;

        AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numrhsevalsS", &expected, &m, &n);
        checkEqualArray(expected, rdata->am_numrhsevalsSdata, udata->am_nt);
        delete[] expected;

        AMI_HDF5_getDoubleArrayAttribute2D(file_id, resultPath, "numstepsS", &expected, &m, &n);
        checkEqualArray(expected, rdata->am_numstepsSdata, udata->am_nt);
        delete[] expected;

        AMI_HDF5_getDoubleArrayAttribute3D(file_id, resultPath, "ssigmay", &expected, &m, &n, &o);
        checkEqualArray(expected, rdata->am_ssigmaydata, udata->am_nt * udata->am_ny * udata->am_nplist);
        delete[] expected;

        if(udata->am_sensi_meth == 1) {
            AMI_HDF5_getDoubleArrayAttribute3D(file_id, resultPath, "sx", &expected, &m, &n, &o);
            checkEqualArray(expected, rdata->am_sxdata, udata->am_nt * udata->am_nx * udata->am_nplist);
            delete[] expected;

            AMI_HDF5_getDoubleArrayAttribute3D(file_id, resultPath, "sy", &expected, &m, &n, &o);
            checkEqualArray(expected, rdata->am_sydata, udata->am_nt * udata->am_ny * udata->am_nplist);
            delete[] expected;

        }

    } else {
        POINTERS_EQUAL(NULL, rdata->am_sllhdata);
        POINTERS_EQUAL(NULL, rdata->am_numrhsevalsSdata);
        POINTERS_EQUAL(NULL, rdata->am_numstepsSdata);

    }

    H5Fclose(file_id);
}

TEST(group1, testSimulation) {
    // read simulation options
    UserData *udata = AMI_HDF5_readSimulationUserDataFromFileName(HDFFILE, "/model_dirac/nosensi/options");
    ExpData *edata = getTestExpData();

    int status;
    ReturnData *rdata = getSimulationResults(udata, edata, &status);
    CHECK_EQUAL(0, status);

    // TODO proper paths /testDirac1/...
    verifyReturnData("/model_dirac/nosensi/results", rdata, udata);

    freeReturnData(rdata);
    freeExpData(edata);
    freeUserData(udata);
}

TEST(group1, testSimulationExpData) {

}

TEST(group1, testSensitivityForward) {
    // read simulation options
    UserData *udata = AMI_HDF5_readSimulationUserDataFromFileName(HDFFILE, "/model_dirac/sensiforward/options");
    ExpData *edata = getTestExpData();

    int status;
    ReturnData *rdata = getSimulationResults(udata, edata, &status);
    CHECK_EQUAL(0, status);

    // TODO proper paths /testDirac1/...
    verifyReturnData("/model_dirac/sensiforward/results", rdata, udata);

    freeReturnData(rdata);
    freeExpData(edata);
    freeUserData(udata);
}

TEST(group1, testSensitivityState) {

}

TEST(group1, testSensitivityAdjoint) {

}

<|endoftext|>


<commit_before>#include "cc/dual_net/factory.h"

#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "gflags/gflags.h"

#ifdef MG_ENABLE_REMOTE_DUAL_NET
#include <thread>
#include "cc/dual_net/inference_server.h"
#ifndef MG_DEFAULT_ENGINE
#define MG_DEFAULT_ENGINE "remote"
#endif  // MG_DEFAULT_ENGINE
#endif  // MG_ENABLE_REMOTE_DUAL_NET

#ifdef MG_ENABLE_TF_DUAL_NET
#include "cc/dual_net/tf_dual_net.h"
#ifndef MG_DEFAULT_ENGINE
#define MG_DEFAULT_ENGINE "tf"
#endif  // MG_DEFAULT_ENGINE
#endif  // MG_ENABLE_TF_DUAL_NET

#ifdef MG_ENABLE_LITE_DUAL_NET
#include "cc/dual_net/lite_dual_net.h"
#ifndef MG_DEFAULT_ENGINE
#define MG_DEFAULT_ENGINE "lite"
#endif  // MG_DEFAULT_ENGINE
#endif  // MG_ENABLE_LITE_DUAL_NET

DEFINE_string(engine, MG_DEFAULT_ENGINE,
              "The inference engine to use. Accepted values:"
#ifdef MG_ENABLE_REMOTE_DUAL_NET
              " \"remote\""
#endif
#ifdef MG_ENABLE_TF_DUAL_NET
              " \"tf\""
#endif
#ifdef MG_ENABLE_LITE_DUAL_NET
              " \"lite\""
#endif
);

DEFINE_string(checkpoint_dir, "",
              "Path to a directory containing TensorFlow model checkpoints. "
              "The inference worker will monitor this when a new checkpoint "
              "is found, load the model and use it for futher inferences. "
              "Only valid when remote inference is enabled.");
DEFINE_bool(use_tpu, true,
            "If true, the remote inference will be run on a TPU. Ignored when "
            "remote_inference=false.");
DEFINE_string(tpu_name, "", "Cloud TPU name, e.g. grpc://10.240.2.2:8470.");
DEFINE_int32(conv_width, 256, "Width of the model's convolution filters.");
DEFINE_int32(parallel_tpus, 8,
             "If model=remote, the number of TPU cores to run on in parallel.");
DEFINE_int32(port, 50051, "The port opened by the InferenceService server.");
DECLARE_int32(virtual_losses);

namespace minigo {

namespace {

#ifdef MG_ENABLE_REMOTE_DUAL_NET
class RemoteDualNetFactory : public DualNetFactory {
 public:
  explicit RemoteDualNetFactory(std::string model_path, int parallel_games)
      : DualNetFactory(std::move(model_path)) {
    inference_worker_thread_ = std::thread([this]() {
      std::vector<std::string> cmd_parts = {
          absl::StrCat("BOARD_SIZE=", kN),
          "python",
          "inference_worker.py",
          absl::StrCat("--model=", model()),
          absl::StrCat("--checkpoint_dir=", FLAGS_checkpoint_dir),
          absl::StrCat("--use_tpu=", FLAGS_use_tpu),
          absl::StrCat("--tpu_name=", FLAGS_tpu_name),
          absl::StrCat("--conv_width=", FLAGS_conv_width),
          absl::StrCat("--parallel_tpus=", FLAGS_parallel_tpus),
      };
      auto cmd = absl::StrJoin(cmd_parts, " ");
      FILE* f = popen(cmd.c_str(), "r");
      for (;;) {
        int c = fgetc(f);
        if (c == EOF) {
          break;
        }
        fputc(c, stderr);
      }
      fputc('\n', stderr);
    });

    int games_per_inference = std::max(1, parallel_games / 2);
    server_ = absl::make_unique<InferenceServer>(
        FLAGS_virtual_losses, games_per_inference, FLAGS_port);
  }

  ~RemoteDualNetFactory() override {
    server_.reset(nullptr);
    inference_worker_thread_.join();
  }

  std::unique_ptr<DualNet> New() override { return server_->NewDualNet(); }

 private:
  std::thread inference_worker_thread_;
  std::unique_ptr<InferenceServer> server_;
};
#endif  // MG_ENABLE_REMOTE_DUAL_NET

#ifdef MG_ENABLE_TF_DUAL_NET
class TfDualNetFactory : public DualNetFactory {
 public:
  TfDualNetFactory(std::string model_path)
      : DualNetFactory(std::move(model_path)) {}

  std::unique_ptr<DualNet> New() override {
    return absl::make_unique<TfDualNet>(model());
  }
};
#endif  // MG_ENABLE_TF_DUAL_NET

#ifdef MG_ENABLE_LITE_DUAL_NET
class LiteDualNetFactory : public DualNetFactory {
 public:
  LiteDualNetFactory(std::string model_path)
      : DualNetFactory(std::move(model_path)) {}

  std::unique_ptr<DualNet> New() override {
    return absl::make_unique<LiteDualNet>(model());
  }
};
#endif  // MG_ENABLE_LITE_DUAL_NET

}  // namespace

DualNetFactory::~DualNetFactory() = default;

std::unique_ptr<DualNetFactory> NewDualNetFactory(std::string model_path,
                                                  int parallel_games) {
  if (FLAGS_engine == "remote") {
#ifdef MG_ENABLE_REMOTE_DUAL_NET
    return absl::make_unique<RemoteDualNetFactory>(std::move(model_path),
                                                   parallel_games);
#else
    MG_FATAL() << "Binary wasn't compiled with remote inference support";
#endif  // MG_ENABLE_REMOTE_DUAL_NET
  }

  if (FLAGS_engine == "tf") {
#ifdef MG_ENABLE_TF_DUAL_NET
    return absl::make_unique<TfDualNetFactory>(std::move(model_path));
#else
    MG_FATAL() << "Binary wasn't compiled with tf inference support";
#endif  // MG_ENABLE_TF_DUAL_NET
  }

  if (FLAGS_engine == "lite") {
#ifdef MG_ENABLE_LITE_DUAL_NET
    return absl::make_unique<LiteDualNetFactory>(std::move(model_path));
#else
    MG_FATAL() << "Binary wasn't compiled with lite inference support";
#endif  // MG_ENABLE_LITE_DUAL_NET
  }

  MG_FATAL() << "Unrecognized inference engine \"" << FLAGS_engine << "\"";
  return nullptr;
}

}  // namespace minigo
<commit_msg>Add fc_width flag for remote inference<commit_after>#include "cc/dual_net/factory.h"

#include "absl/memory/memory.h"
#include "absl/strings/str_cat.h"
#include "absl/strings/str_join.h"
#include "gflags/gflags.h"

#ifdef MG_ENABLE_REMOTE_DUAL_NET
#include <thread>
#include "cc/dual_net/inference_server.h"
#ifndef MG_DEFAULT_ENGINE
#define MG_DEFAULT_ENGINE "remote"
#endif  // MG_DEFAULT_ENGINE
#endif  // MG_ENABLE_REMOTE_DUAL_NET

#ifdef MG_ENABLE_TF_DUAL_NET
#include "cc/dual_net/tf_dual_net.h"
#ifndef MG_DEFAULT_ENGINE
#define MG_DEFAULT_ENGINE "tf"
#endif  // MG_DEFAULT_ENGINE
#endif  // MG_ENABLE_TF_DUAL_NET

#ifdef MG_ENABLE_LITE_DUAL_NET
#include "cc/dual_net/lite_dual_net.h"
#ifndef MG_DEFAULT_ENGINE
#define MG_DEFAULT_ENGINE "lite"
#endif  // MG_DEFAULT_ENGINE
#endif  // MG_ENABLE_LITE_DUAL_NET

DEFINE_string(engine, MG_DEFAULT_ENGINE,
              "The inference engine to use. Accepted values:"
#ifdef MG_ENABLE_REMOTE_DUAL_NET
              " \"remote\""
#endif
#ifdef MG_ENABLE_TF_DUAL_NET
              " \"tf\""
#endif
#ifdef MG_ENABLE_LITE_DUAL_NET
              " \"lite\""
#endif
);

DEFINE_string(checkpoint_dir, "",
              "Path to a directory containing TensorFlow model checkpoints. "
              "The inference worker will monitor this when a new checkpoint "
              "is found, load the model and use it for futher inferences. "
              "Only valid when remote inference is enabled.");
DEFINE_bool(use_tpu, true,
            "If true, the remote inference will be run on a TPU. Ignored when "
            "remote_inference=false.");
DEFINE_string(tpu_name, "", "Cloud TPU name, e.g. grpc://10.240.2.2:8470.");
DEFINE_int32(conv_width, 256, "Width of the model's convolution filters.");
DEFINE_int32(fc_width, 256,
             "Width of the model's fully connected layer in value head.");
DEFINE_int32(parallel_tpus, 8,
             "If model=remote, the number of TPU cores to run on in parallel.");
DEFINE_int32(port, 50051, "The port opened by the InferenceService server.");
DECLARE_int32(virtual_losses);

namespace minigo {

namespace {

#ifdef MG_ENABLE_REMOTE_DUAL_NET
class RemoteDualNetFactory : public DualNetFactory {
 public:
  explicit RemoteDualNetFactory(std::string model_path, int parallel_games)
      : DualNetFactory(std::move(model_path)) {
    inference_worker_thread_ = std::thread([this]() {
      std::vector<std::string> cmd_parts = {
          absl::StrCat("BOARD_SIZE=", kN),
          "python",
          "inference_worker.py",
          absl::StrCat("--model=", model()),
          absl::StrCat("--checkpoint_dir=", FLAGS_checkpoint_dir),
          absl::StrCat("--use_tpu=", FLAGS_use_tpu),
          absl::StrCat("--tpu_name=", FLAGS_tpu_name),
          absl::StrCat("--conv_width=", FLAGS_conv_width),
          absl::StrCat("--fc_width=", FLAGS_fc_width),
          absl::StrCat("--parallel_tpus=", FLAGS_parallel_tpus),
      };
      auto cmd = absl::StrJoin(cmd_parts, " ");
      FILE* f = popen(cmd.c_str(), "r");
      for (;;) {
        int c = fgetc(f);
        if (c == EOF) {
          break;
        }
        fputc(c, stderr);
      }
      fputc('\n', stderr);
    });

    int games_per_inference = std::max(1, parallel_games / 2);
    server_ = absl::make_unique<InferenceServer>(
        FLAGS_virtual_losses, games_per_inference, FLAGS_port);
  }

  ~RemoteDualNetFactory() override {
    server_.reset(nullptr);
    inference_worker_thread_.join();
  }

  std::unique_ptr<DualNet> New() override { return server_->NewDualNet(); }

 private:
  std::thread inference_worker_thread_;
  std::unique_ptr<InferenceServer> server_;
};
#endif  // MG_ENABLE_REMOTE_DUAL_NET

#ifdef MG_ENABLE_TF_DUAL_NET
class TfDualNetFactory : public DualNetFactory {
 public:
  TfDualNetFactory(std::string model_path)
      : DualNetFactory(std::move(model_path)) {}

  std::unique_ptr<DualNet> New() override {
    return absl::make_unique<TfDualNet>(model());
  }
};
#endif  // MG_ENABLE_TF_DUAL_NET

#ifdef MG_ENABLE_LITE_DUAL_NET
class LiteDualNetFactory : public DualNetFactory {
 public:
  LiteDualNetFactory(std::string model_path)
      : DualNetFactory(std::move(model_path)) {}

  std::unique_ptr<DualNet> New() override {
    return absl::make_unique<LiteDualNet>(model());
  }
};
#endif  // MG_ENABLE_LITE_DUAL_NET

}  // namespace

DualNetFactory::~DualNetFactory() = default;

std::unique_ptr<DualNetFactory> NewDualNetFactory(std::string model_path,
                                                  int parallel_games) {
  if (FLAGS_engine == "remote") {
#ifdef MG_ENABLE_REMOTE_DUAL_NET
    return absl::make_unique<RemoteDualNetFactory>(std::move(model_path),
                                                   parallel_games);
#else
    MG_FATAL() << "Binary wasn't compiled with remote inference support";
#endif  // MG_ENABLE_REMOTE_DUAL_NET
  }

  if (FLAGS_engine == "tf") {
#ifdef MG_ENABLE_TF_DUAL_NET
    return absl::make_unique<TfDualNetFactory>(std::move(model_path));
#else
    MG_FATAL() << "Binary wasn't compiled with tf inference support";
#endif  // MG_ENABLE_TF_DUAL_NET
  }

  if (FLAGS_engine == "lite") {
#ifdef MG_ENABLE_LITE_DUAL_NET
    return absl::make_unique<LiteDualNetFactory>(std::move(model_path));
#else
    MG_FATAL() << "Binary wasn't compiled with lite inference support";
#endif  // MG_ENABLE_LITE_DUAL_NET
  }

  MG_FATAL() << "Unrecognized inference engine \"" << FLAGS_engine << "\"";
  return nullptr;
}

}  // namespace minigo
<|endoftext|>


<commit_before>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: msg.cxx,v $
 *
 *  $Revision: 1.4 $
 *
 *  last change: $Author: obo $ $Date: 2006-09-17 16:27:18 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef GCC
#endif

#include "msg.hxx"

//====================================================================

SfxSlotKind SfxSlot::GetKind() const
{
    if( !nMasterSlotId && !nValue)
        return (SfxSlotKind) SFX_KIND_STANDARD;
    if ( nMasterSlotId && fnExec==0 && fnState==0 )
    {
        if ( pType->Type() == TYPE(SfxBoolItem) )
            return (SfxSlotKind) SFX_KIND_ENUM;
        else
        {
            DBG_ERROR( "invalid slot kind detected" );
            return SFX_KIND_ENUM;
        }
    }
    else
        return (SfxSlotKind) SFX_KIND_ATTR;
}

//--------------------------------------------------------------------

USHORT SfxSlot::GetWhich( const SfxItemPool &rPool ) const
{
    if ( !nMasterSlotId || nMasterSlotId == USHRT_MAX )
        ((SfxSlot*) this) -> nMasterSlotId = rPool.GetWhich(nSlotId);
    return nMasterSlotId;
}

<commit_msg>INTEGRATION: CWS vgbugs07 (1.4.218); FILE MERGED 2007/06/04 13:34:45 vg 1.4.218.1: #i76605# Remove -I .../inc/module hack introduced by hedaburemove01<commit_after>/*************************************************************************
 *
 *  OpenOffice.org - a multi-platform office productivity suite
 *
 *  $RCSfile: msg.cxx,v $
 *
 *  $Revision: 1.5 $
 *
 *  last change: $Author: hr $ $Date: 2007-06-27 23:06:26 $
 *
 *  The Contents of this file are made available subject to
 *  the terms of GNU Lesser General Public License Version 2.1.
 *
 *
 *    GNU Lesser General Public License Version 2.1
 *    =============================================
 *    Copyright 2005 by Sun Microsystems, Inc.
 *    901 San Antonio Road, Palo Alto, CA 94303, USA
 *
 *    This library is free software; you can redistribute it and/or
 *    modify it under the terms of the GNU Lesser General Public
 *    License version 2.1, as published by the Free Software Foundation.
 *
 *    This library is distributed in the hope that it will be useful,
 *    but WITHOUT ANY WARRANTY; without even the implied warranty of
 *    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
 *    Lesser General Public License for more details.
 *
 *    You should have received a copy of the GNU Lesser General Public
 *    License along with this library; if not, write to the Free Software
 *    Foundation, Inc., 59 Temple Place, Suite 330, Boston,
 *    MA  02111-1307  USA
 *
 ************************************************************************/

// MARKER(update_precomp.py): autogen include statement, do not remove
#include "precompiled_sfx2.hxx"

#ifndef _SFXITEMPOOL_HXX //autogen
#include <svtools/itempool.hxx>
#endif
#ifndef _SFXENUMITEM_HXX //autogen
#include <svtools/eitem.hxx>
#endif
#ifndef GCC
#endif

#include <sfx2/msg.hxx>

//====================================================================

SfxSlotKind SfxSlot::GetKind() const
{
    if( !nMasterSlotId && !nValue)
        return (SfxSlotKind) SFX_KIND_STANDARD;
    if ( nMasterSlotId && fnExec==0 && fnState==0 )
    {
        if ( pType->Type() == TYPE(SfxBoolItem) )
            return (SfxSlotKind) SFX_KIND_ENUM;
        else
        {
            DBG_ERROR( "invalid slot kind detected" );
            return SFX_KIND_ENUM;
        }
    }
    else
        return (SfxSlotKind) SFX_KIND_ATTR;
}

//--------------------------------------------------------------------

USHORT SfxSlot::GetWhich( const SfxItemPool &rPool ) const
{
    if ( !nMasterSlotId || nMasterSlotId == USHRT_MAX )
        ((SfxSlot*) this) -> nMasterSlotId = rPool.GetWhich(nSlotId);
    return nMasterSlotId;
}

<|endoftext|>


<commit_before>#include <QtGui>
#include <QMessageBox>
#include <QFileDialog>
#include <QGraphicsScene>
#include <iostream>
#include <algorithm>
#include "main_window.hpp"

#include <QDebug>

#include "geometry_msgs/Pose.h"

using namespace Qt;

namespace map_marker {

	const double map_min = -5;
	const double map_max = 5;
	const double map_pix = 992;

	const QColor red = QColor(180, 40, 0);
	const QColor blue = QColor(30, 30, 140);
	const QColor green = QColor(50, 140, 30);
	const QColor orange = QColor(230, 120, 0);

	MainWindow::MainWindow(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode(argc,argv) {
		ui.setupUi(this);
		qnode.init();

		/* HOEFT NIET
		QObject::connect(ui.btnLoadYaml, SIGNAL(clicked(bool)), this, SLOT(on_btnLoadYaml_clicked()));
		QObject::connect(ui.btnLoadMap, SIGNAL(clicked(bool)), this, SLOT(on_btnLoadMap_clicked()));
		QObject::connect(ui.btnWriteYaml, SIGNAL(clicked(bool)), this, SLOT(on_btnWriteYaml_clicked()));
		QObject::connect(ui.btnClearYaml, SIGNAL(clicked(bool)), this, SLOT(on_btnClearYaml_clicked()));
		QObject::connect(ui.btnAddCurrentPose, SIGNAL(clicked(bool)), this, SLOT(on_btnAddCurrentPose_clicked()));
		QObject::connect(ui.btnAddCustomPose, SIGNAL(clicked(bool)), this, SLOT(on_btnAddCustomPose_clicked()));
		*/

		QObject::connect(ui.tableWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(DrawRobotOnImage()));

		QString url = "/home/lars/git/ESA-PROJ/maps/legomap3-cropped.pgm";
		map = new QPixmap(url);

		// Ttable editing
		ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
		ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
		ui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);

		// Create map image
		lblMapImage = new ClickableLabel(this);
		lblMapImage->setAlignment(Qt::AlignBottom | Qt::AlignRight);
		lblMapImage->setGeometry(QRect(0, 0, map_pix, map_pix));
		lblMapImage->setPixmap(*map);
		QObject::connect(lblMapImage, SIGNAL(clicked(QPoint)), this, SLOT(lblMapImage_clicked(QPoint)));

		// Set validator for input fields
		ui.inpCustomX->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomX));
		ui.inpCustomY->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomY));
		ui.inpCustomAngle->setValidator(new QDoubleValidator(0, 360, 5, ui.inpCustomAngle));

		// Panic button color
		ui.btnPanic->setStyleSheet("color: rgb(192,0,0);");

		Marker m(1.0, 2.0, 40.0, Navigation);
		AddMarker(m);

		UpdateTable();
	}

	MainWindow::~MainWindow() {
		delete map;
		delete lblMapImage;

	}

	void MainWindow::lblMapImage_clicked(QPoint a) {
		QString x = QString::number(ConvertPixelToRobot(a.x()));
		QString y = QString::number(ConvertPixelToRobot(a.y()));
		ui.inpCustomX->setText(x);
		ui.inpCustomY->setText(y);
	}

	void MainWindow::on_btnLoadYaml_clicked() {

		//yaml.printYaml("/home/viki/git/ESA-PROJ/maps/legomap-cropped.yaml");
		yaml.loadYaml("/home/viki/git/ESA-PROJ/maps/legomap-cropped.yaml");
	}

	void MainWindow::on_btnLoadMap_clicked() {
		QFileDialog dialog(this);
		dialog.setFileMode(QFileDialog::AnyFile);
		dialog.setNameFilter(tr("Map image file (*.pbm *.pgm *.ppm)"));

		QStringList fileNames;
		if (dialog.exec())
		fileNames = dialog.selectedFiles();

		map = new QPixmap(fileNames[0]);
			lblMapImage->setPixmap(*map);
	}

	void MainWindow::on_btnWriteYaml_clicked() {
		ROS_ERROR("Not implemented yet :(");
	}

	void MainWindow::on_btnClearYaml_clicked() {
		ROS_ERROR("Not implemented yet :(");
	}

	void MainWindow::on_btnAddCurrentPose_clicked() {
		geometry_msgs::Pose pos = qnode.GetRobotPosition();

		MarkerType type;
		if(ui.radioNav->isChecked()) {
			type = Navigation;
		} else if (ui.radioWorkspace->isChecked()) {
			type = Workspace;
		}

		AddMarker(Marker(pos, type));
		UpdateTable();
	}

	void MainWindow::on_btnAddCustomPose_clicked() {
		double x = ui.inpCustomX->text().toDouble();
		double y = ui.inpCustomY->text().toDouble();
		double angle = ui.inpCustomAngle->text().toDouble();

		MarkerType type;
		if(ui.radioNav->isChecked()) {
			type = Navigation;
		} else if (ui.radioWorkspace->isChecked()) {
			type = Workspace;
		}

		AddMarker(Marker(x, y, angle, type));
		UpdateTable();
	}

	void MainWindow::on_btnMoveRobot_clicked() {
		int index = GetSelectedMarker();
		if(index == -1) {
			ROS_WARN("No marker selected");
			return;
		}
		Marker * m = &markers[index];
		qnode.MoveRobotToPose(m->GetPose());
	}

	void MainWindow::on_btnRemoveMarker_clicked() {
		int index = GetSelectedMarker();
		if(index == -1) {
			ROS_WARN("No marker selected");
			return;
		}
		markers.erase(markers.begin()+index);
		UpdateTable();
	}

	void MainWindow::on_btnPanic_clicked() {
		qnode.Panic();
		ROS_INFO("Panic button pressed, stopped robot...");
	}

	void MainWindow::on_btnMoveMarkerUp_clicked() {
		int selectedMarker = GetSelectedMarker();
		MoveMarkerUp(selectedMarker);
		UpdateTable();
	}

	void MainWindow::on_btnMoveMarkerDown_clicked() {
		int selectedMarker = GetSelectedMarker();
		MoveMarkerDown(selectedMarker);
		UpdateTable();
	}

	void MainWindow::on_btnClearAllMarkers_clicked() {
		markers.clear();
		UpdateTable();
	}

	int MainWindow::GetSelectedMarker() {
		int j = -1;
		QModelIndexList indexes = ui.tableWidget->selectionModel()->selectedRows();

		for (int i = 0; i < indexes.count(); ++i) {
			j = indexes.at(i).row();
		}

		return j;
	}

	void MainWindow::AddMarker(Marker marker) {
		markers.push_back(marker);
	}

	void MainWindow::MoveMarkerUp(int selectedMarker) {
		if(selectedMarker + 1 < markers.size() && selectedMarker >= 0) {
			std::swap(markers.at(selectedMarker), markers.at(selectedMarker + 1));
		} else {
			ROS_WARN("No marker selected");
		}
	}

	void MainWindow::MoveMarkerDown(int selectedMarker) {
		if(selectedMarker > 0) {
			std::swap(markers.at(selectedMarker), markers.at(selectedMarker - 1));
		} else {
			ROS_WARN("No marker selected");
		}
	}

	void MainWindow::UpdateTable() {
		ui.tableWidget->setRowCount(0);
		for(int i=0; i < markers.size(); i++) {
			ui.tableWidget->insertRow ( ui.tableWidget->rowCount() );
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 0, new QTableWidgetItem(QString::fromStdString(markers[i].GetTypeStr())));
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 1, new QTableWidgetItem(QString::number(markers[i].GetX())));
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 2, new QTableWidgetItem(QString::number(markers[i].GetY())));
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 3, new QTableWidgetItem(QString::number(markers[i].GetAngle())));
		}
		DrawRobotOnImage();
	}

	void MainWindow::DrawRobotOnImage() {
		geometry_msgs::Pose pos = qnode.GetRobotPosition();

		QImage tmp(map->toImage());
		QPainter painter(&tmp);
		QPen paintpen(blue);
		QPoint p1;
		paintpen.setWidth(10);
		p1.setX(ConvertRobotToPixel(pos.position.x));
		p1.setY(ConvertRobotToPixel(pos.position.y));
		painter.setPen(paintpen);
		painter.drawPoint(p1);

		lblMapImage->setPixmap(QPixmap::fromImage(tmp));

		DrawMarkersOnImage();
	}

	void MainWindow::DrawMarkersOnImage() {

		QImage tmp(lblMapImage->pixmap()->toImage());
		QPainter painter(&tmp);
		QPen paintpen(orange);
		QPoint p1;
		paintpen.setWidth(10);

		for(int i; i < markers.size(); i++) {

			if(i == GetSelectedMarker()) {
				paintpen.setColor(red);
				//ROS_WARN("HOI");
			} else if(markers[i].GetType() == Workspace) {
				paintpen.setColor(green);
				//ROS_WARN("GOENN");
			} else {
				paintpen.setColor(orange);
				//ROS_WARN("ORANJEEE");
			}

			p1.setX(ConvertRobotToPixel(markers[i].GetX()));
			p1.setY(ConvertRobotToPixel(markers[i].GetY()));
			painter.setPen(paintpen);
			painter.drawPoint(p1);
		}
		lblMapImage->setPixmap(QPixmap::fromImage(tmp));

		/*QPoint p2;
		p2.setX(ConvertRobotToPixel(pos.position.x));
		p2.setY(ConvertRobotToPixel(pos.position.y));
		painter.setPen(paintpen);
		painter.drawPoint(p2);
		lblMapImage->setPixmap(QPixmap::fromImage(tmp));*/
	}

	int MainWindow::ConvertRobotToPixel(double a) {
		return (a - map_min) * (map_pix - 0) / (map_max - map_min);
	}

	double MainWindow::ConvertPixelToRobot(int a) {
		return (a) * (map_max - map_min) / (map_pix) + map_min;
	}
}

/*
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}*/
<commit_msg>Updated btnLoadYaml to use browse<commit_after>#include <QtGui>
#include <QMessageBox>
#include <QFileDialog>
#include <QGraphicsScene>
#include <iostream>
#include <algorithm>
#include "main_window.hpp"

#include <QDebug>

#include "geometry_msgs/Pose.h"

using namespace Qt;

namespace map_marker {

	const double map_min = -5;
	const double map_max = 5;
	const double map_pix = 992;

	const QColor red = QColor(180, 40, 0);
	const QColor blue = QColor(30, 30, 140);
	const QColor green = QColor(50, 140, 30);
	const QColor orange = QColor(230, 120, 0);

	MainWindow::MainWindow(int argc, char** argv, QWidget *parent) : QMainWindow(parent), qnode(argc,argv) {
		ui.setupUi(this);
		qnode.init();

		/* HOEFT NIET
		QObject::connect(ui.btnLoadYaml, SIGNAL(clicked(bool)), this, SLOT(on_btnLoadYaml_clicked()));
		QObject::connect(ui.btnLoadMap, SIGNAL(clicked(bool)), this, SLOT(on_btnLoadMap_clicked()));
		QObject::connect(ui.btnWriteYaml, SIGNAL(clicked(bool)), this, SLOT(on_btnWriteYaml_clicked()));
		QObject::connect(ui.btnClearYaml, SIGNAL(clicked(bool)), this, SLOT(on_btnClearYaml_clicked()));
		QObject::connect(ui.btnAddCurrentPose, SIGNAL(clicked(bool)), this, SLOT(on_btnAddCurrentPose_clicked()));
		QObject::connect(ui.btnAddCustomPose, SIGNAL(clicked(bool)), this, SLOT(on_btnAddCustomPose_clicked()));
		*/

		QObject::connect(ui.tableWidget->selectionModel(), SIGNAL(selectionChanged(const QItemSelection &, const QItemSelection &)), SLOT(DrawRobotOnImage()));

		QString url = "/home/lars/git/ESA-PROJ/maps/legomap3-cropped.pgm";
		map = new QPixmap(url);

		// Ttable editing
		ui.tableWidget->setEditTriggers(QAbstractItemView::NoEditTriggers);
		ui.tableWidget->setSelectionBehavior(QAbstractItemView::SelectRows);
		ui.tableWidget->setSelectionMode(QAbstractItemView::SingleSelection);

		// Create map image
		lblMapImage = new ClickableLabel(this);
		lblMapImage->setAlignment(Qt::AlignBottom | Qt::AlignRight);
		lblMapImage->setGeometry(QRect(0, 0, map_pix, map_pix));
		lblMapImage->setPixmap(*map);
		QObject::connect(lblMapImage, SIGNAL(clicked(QPoint)), this, SLOT(lblMapImage_clicked(QPoint)));

		// Set validator for input fields
		ui.inpCustomX->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomX));
		ui.inpCustomY->setValidator(new QDoubleValidator(-100, 100, 5, ui.inpCustomY));
		ui.inpCustomAngle->setValidator(new QDoubleValidator(0, 360, 5, ui.inpCustomAngle));

		// Panic button color
		ui.btnPanic->setStyleSheet("color: rgb(192,0,0);");

		Marker m(1.0, 2.0, 40.0, Navigation);
		AddMarker(m);

		UpdateTable();
	}

	MainWindow::~MainWindow() {
		delete map;
		delete lblMapImage;

	}

	void MainWindow::lblMapImage_clicked(QPoint a) {
		QString x = QString::number(ConvertPixelToRobot(a.x()));
		QString y = QString::number(ConvertPixelToRobot(a.y()));
		ui.inpCustomX->setText(x);
		ui.inpCustomY->setText(y);
	}

	void MainWindow::on_btnLoadYaml_clicked() {
		QFileDialog dialog(this);
		dialog.setFileMode(QFileDialog::AnyFile);
		dialog.setNameFilter(tr("Map image file (*.yaml)"));

		QStringList fileNames;
		if (dialog.exec())
		fileNames = dialog.selectedFiles();

		yaml.loadYaml(fileNames[0].toUtf8().constData());
	}

	void MainWindow::on_btnLoadMap_clicked() {
		QFileDialog dialog(this);
		dialog.setFileMode(QFileDialog::AnyFile);
		dialog.setNameFilter(tr("Map image file (*.pbm *.pgm *.ppm)"));

		QStringList fileNames;
		if (dialog.exec())
		fileNames = dialog.selectedFiles();

		map = new QPixmap(fileNames[0]);
			lblMapImage->setPixmap(*map);
	}

	void MainWindow::on_btnWriteYaml_clicked() {
		ROS_ERROR("Not implemented yet :(");
	}

	void MainWindow::on_btnClearYaml_clicked() {
		ROS_ERROR("Not implemented yet :(");
	}

	void MainWindow::on_btnAddCurrentPose_clicked() {
		geometry_msgs::Pose pos = qnode.GetRobotPosition();

		MarkerType type;
		if(ui.radioNav->isChecked()) {
			type = Navigation;
		} else if (ui.radioWorkspace->isChecked()) {
			type = Workspace;
		}

		AddMarker(Marker(pos, type));
		UpdateTable();
	}

	void MainWindow::on_btnAddCustomPose_clicked() {
		double x = ui.inpCustomX->text().toDouble();
		double y = ui.inpCustomY->text().toDouble();
		double angle = ui.inpCustomAngle->text().toDouble();

		MarkerType type;
		if(ui.radioNav->isChecked()) {
			type = Navigation;
		} else if (ui.radioWorkspace->isChecked()) {
			type = Workspace;
		}

		AddMarker(Marker(x, y, angle, type));
		UpdateTable();
	}

	void MainWindow::on_btnMoveRobot_clicked() {
		int index = GetSelectedMarker();
		if(index == -1) {
			ROS_WARN("No marker selected");
			return;
		}
		Marker * m = &markers[index];
		qnode.MoveRobotToPose(m->GetPose());
	}

	void MainWindow::on_btnRemoveMarker_clicked() {
		int index = GetSelectedMarker();
		if(index == -1) {
			ROS_WARN("No marker selected");
			return;
		}
		markers.erase(markers.begin()+index);
		UpdateTable();
	}

	void MainWindow::on_btnPanic_clicked() {
		qnode.Panic();
		ROS_INFO("Panic button pressed, stopped robot...");
	}

	void MainWindow::on_btnMoveMarkerUp_clicked() {
		int selectedMarker = GetSelectedMarker();
		MoveMarkerUp(selectedMarker);
		UpdateTable();
	}

	void MainWindow::on_btnMoveMarkerDown_clicked() {
		int selectedMarker = GetSelectedMarker();
		MoveMarkerDown(selectedMarker);
		UpdateTable();
	}

	void MainWindow::on_btnClearAllMarkers_clicked() {
		markers.clear();
		UpdateTable();
	}

	int MainWindow::GetSelectedMarker() {
		int j = -1;
		QModelIndexList indexes = ui.tableWidget->selectionModel()->selectedRows();

		for (int i = 0; i < indexes.count(); ++i) {
			j = indexes.at(i).row();
		}

		return j;
	}

	void MainWindow::AddMarker(Marker marker) {
		markers.push_back(marker);
	}

	void MainWindow::MoveMarkerUp(int selectedMarker) {
		if(selectedMarker + 1 < markers.size() && selectedMarker >= 0) {
			std::swap(markers.at(selectedMarker), markers.at(selectedMarker + 1));
		} else {
			ROS_WARN("No marker selected");
		}
	}

	void MainWindow::MoveMarkerDown(int selectedMarker) {
		if(selectedMarker > 0) {
			std::swap(markers.at(selectedMarker), markers.at(selectedMarker - 1));
		} else {
			ROS_WARN("No marker selected");
		}
	}

	void MainWindow::UpdateTable() {
		ui.tableWidget->setRowCount(0);
		for(int i=0; i < markers.size(); i++) {
			ui.tableWidget->insertRow ( ui.tableWidget->rowCount() );
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 0, new QTableWidgetItem(QString::fromStdString(markers[i].GetTypeStr())));
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 1, new QTableWidgetItem(QString::number(markers[i].GetX())));
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 2, new QTableWidgetItem(QString::number(markers[i].GetY())));
			ui.tableWidget->setItem(ui.tableWidget->rowCount()-1, 3, new QTableWidgetItem(QString::number(markers[i].GetAngle())));
		}
		DrawRobotOnImage();
	}

	void MainWindow::DrawRobotOnImage() {
		geometry_msgs::Pose pos = qnode.GetRobotPosition();

		QImage tmp(map->toImage());
		QPainter painter(&tmp);
		QPen paintpen(blue);
		QPoint p1;
		paintpen.setWidth(10);
		p1.setX(ConvertRobotToPixel(pos.position.x));
		p1.setY(ConvertRobotToPixel(pos.position.y));
		painter.setPen(paintpen);
		painter.drawPoint(p1);

		lblMapImage->setPixmap(QPixmap::fromImage(tmp));

		DrawMarkersOnImage();
	}

	void MainWindow::DrawMarkersOnImage() {

		QImage tmp(lblMapImage->pixmap()->toImage());
		QPainter painter(&tmp);
		QPen paintpen(orange);
		QPoint p1;
		paintpen.setWidth(10);

		for(int i; i < markers.size(); i++) {

			if(i == GetSelectedMarker()) {
				paintpen.setColor(red);
				//ROS_WARN("HOI");
			} else if(markers[i].GetType() == Workspace) {
				paintpen.setColor(green);
				//ROS_WARN("GOENN");
			} else {
				paintpen.setColor(orange);
				//ROS_WARN("ORANJEEE");
			}

			p1.setX(ConvertRobotToPixel(markers[i].GetX()));
			p1.setY(ConvertRobotToPixel(markers[i].GetY()));
			painter.setPen(paintpen);
			painter.drawPoint(p1);
		}
		lblMapImage->setPixmap(QPixmap::fromImage(tmp));

		/*QPoint p2;
		p2.setX(ConvertRobotToPixel(pos.position.x));
		p2.setY(ConvertRobotToPixel(pos.position.y));
		painter.setPen(paintpen);
		painter.drawPoint(p2);
		lblMapImage->setPixmap(QPixmap::fromImage(tmp));*/
	}

	int MainWindow::ConvertRobotToPixel(double a) {
		return (a - map_min) * (map_pix - 0) / (map_max - map_min);
	}

	double MainWindow::ConvertPixelToRobot(int a) {
		return (a) * (map_max - map_min) / (map_pix) + map_min;
	}
}

/*
long map(long x, long in_min, long in_max, long out_min, long out_max)
{
  return (x - in_min) * (out_max - out_min) / (in_max - in_min) + out_min;
}*/
<|endoftext|>


<commit_before>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/unit.hpp>
#include <agency/detail/unique_ptr.hpp>
#include <type_traits>

namespace agency
{
namespace detail
{

struct unit_ptr : unit
{
  using element_type = unit;

  __AGENCY_ANNOTATION
  unit& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const unit& operator*() const
  {
    return *this;
  }
};

template<class T>
struct state_requires_storage
  : std::integral_constant<
      bool,
      std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
   >
{};

struct construct_ready_t {};
struct construct_not_ready_t {};

constexpr static construct_ready_t     construct_ready{};
constexpr static construct_not_ready_t construct_not_ready{};

// XXX this is suffixed with _impl because of nvbug 1700337
//     eliminate the suffix when that bug is resolved
// XXX should try to collapse the implementation of this as much as possible between the two
template<class T,
         class Alloc = std::allocator<T>,
         bool requires_storage = state_requires_storage<T>::value>
class asynchronous_state_impl
{
  public:
    using value_type = T;
    using pointer = value_type*;
    using storage_type = unique_ptr<T,deleter<Alloc>>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() = default;

    // constructs an immediately ready state
    __agency_hd_warning_disable__
    template<class... Args,
             class = typename std::enable_if<
               std::is_constructible<T,Args...>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, Args&&... ready_args)
      : storage_(allocate_unique<T>(Alloc(), std::forward<Args>(ready_args)...))
    {}

    // constructs a not ready state
    // XXX we should avoid creating an object here
    //     instead, we should just create it uninitialized
    // XXX the destructor should check whether the state requires destruction
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t)
      : asynchronous_state_impl(construct_ready, T{})
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) = default;

    template<class OtherT,
             class OtherAlloc,
             class = typename std::enable_if<
               std::is_constructible<storage_type, typename asynchronous_state_impl<OtherT,OtherAlloc>::storage_type&&>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : storage_(std::move(other.storage_))
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&&) = default;

    __AGENCY_ANNOTATION
    pointer data() const
    {
      return storage_.get();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      T result = std::move(*storage_);

      storage_.reset();

      return std::move(result);
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return storage_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      storage_.swap(other.storage_);
    }

  private:
    template<class, class, bool>
    friend class asynchronous_state_impl;

    storage_type storage_;
};

// when a type is empty, we can create instances on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
  using element_type = T;

  __AGENCY_ANNOTATION
  T& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const T& operator*() const
  {
    return *this;
  }
};

template<>
struct empty_type_ptr<void> : unit_ptr {};

// zero storage optimization
template<class T, class Alloc>
class asynchronous_state_impl<T,Alloc,true>
{
  public:
    using value_type = T;
    using pointer = empty_type_ptr<T>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() : valid_(false) {}

    // constructs an immediately ready state
    template<class OtherT,
             class = typename std::enable_if<
               std::is_constructible<T,OtherT&&>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, OtherT&&) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t) : valid_(true) {}

    // constructs a not ready state
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) : valid_(other.valid_)
    {
      other.valid_ = false;
    }

    // 1. allow moves to void states (this simply discards the state)
    // 2. allow moves to empty types if the type can be constructed from an empty argument list
    // 3. allow upcasts to a base T from a derived U
    template<class OtherT,
             class OtherAlloc,
             class T1 = T,
             class = typename std::enable_if<
               std::is_void<T1>::value ||
               (std::is_empty<T>::value && std::is_void<OtherT>::value && std::is_constructible<T>::value) ||
               std::is_base_of<T,OtherT>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : valid_(other.valid())
    {
      if(valid())
      {
        // invalidate the old state by calling .get() if it was valid when we received it
        other.get();
      }
    }

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&& other)
    {
      valid_ = other.valid_;
      other.valid_ = false;

      return *this;
    }

    __AGENCY_ANNOTATION
    empty_type_ptr<T> data() const
    {
      return empty_type_ptr<T>();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      valid_ = false;

      return get_impl(std::is_void<T>());
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return valid_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      bool other_valid_old = other.valid_;
      other.valid_ = valid_;
      valid_ = other_valid_old;
    }

  private:
    __AGENCY_ANNOTATION
    static T get_impl(std::false_type)
    {
      return T{};
    }

    __AGENCY_ANNOTATION
    static T get_impl(std::true_type)
    {
      return;
    }

    bool valid_;
};

// XXX this extra indirection is due to nvbug 1700337
//     eliminate this class when that bug is resolved
template<class T, class Alloc = std::allocator<T>>
class asynchronous_state : public asynchronous_state_impl<T,Alloc>
{
  public:
    using asynchronous_state_impl<T,Alloc>::asynchronous_state_impl;
};

} // end detail
} // end agency

<commit_msg>Add missing include<commit_after>#pragma once

#include <agency/detail/config.hpp>
#include <agency/detail/unit.hpp>
#include <agency/detail/unique_ptr.hpp>
#include <agency/detail/tuple.hpp>
#include <type_traits>

namespace agency
{
namespace detail
{

struct unit_ptr : unit
{
  using element_type = unit;

  __AGENCY_ANNOTATION
  unit& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const unit& operator*() const
  {
    return *this;
  }
};

template<class T>
struct state_requires_storage
  : std::integral_constant<
      bool,
      std::is_empty<T>::value || std::is_void<T>::value || agency::detail::is_empty_tuple<T>::value
   >
{};

struct construct_ready_t {};
struct construct_not_ready_t {};

constexpr static construct_ready_t     construct_ready{};
constexpr static construct_not_ready_t construct_not_ready{};

// XXX this is suffixed with _impl because of nvbug 1700337
//     eliminate the suffix when that bug is resolved
// XXX should try to collapse the implementation of this as much as possible between the two
template<class T,
         class Alloc = std::allocator<T>,
         bool requires_storage = state_requires_storage<T>::value>
class asynchronous_state_impl
{
  public:
    using value_type = T;
    using pointer = value_type*;
    using storage_type = unique_ptr<T,deleter<Alloc>>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() = default;

    // constructs an immediately ready state
    __agency_hd_warning_disable__
    template<class... Args,
             class = typename std::enable_if<
               std::is_constructible<T,Args...>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, Args&&... ready_args)
      : storage_(allocate_unique<T>(Alloc(), std::forward<Args>(ready_args)...))
    {}

    // constructs a not ready state
    // XXX we should avoid creating an object here
    //     instead, we should just create it uninitialized
    // XXX the destructor should check whether the state requires destruction
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t)
      : asynchronous_state_impl(construct_ready, T{})
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) = default;

    template<class OtherT,
             class OtherAlloc,
             class = typename std::enable_if<
               std::is_constructible<storage_type, typename asynchronous_state_impl<OtherT,OtherAlloc>::storage_type&&>::value
             >::type
            >
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : storage_(std::move(other.storage_))
    {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&&) = default;

    __AGENCY_ANNOTATION
    pointer data() const
    {
      return storage_.get();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      T result = std::move(*storage_);

      storage_.reset();

      return std::move(result);
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return storage_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      storage_.swap(other.storage_);
    }

  private:
    template<class, class, bool>
    friend class asynchronous_state_impl;

    storage_type storage_;
};

// when a type is empty, we can create instances on the fly upon dereference
template<class T>
struct empty_type_ptr : T
{
  using element_type = T;

  __AGENCY_ANNOTATION
  T& operator*()
  {
    return *this;
  }

  __AGENCY_ANNOTATION
  const T& operator*() const
  {
    return *this;
  }
};

template<>
struct empty_type_ptr<void> : unit_ptr {};

// zero storage optimization
template<class T, class Alloc>
class asynchronous_state_impl<T,Alloc,true>
{
  public:
    using value_type = T;
    using pointer = empty_type_ptr<T>;

    // constructs an invalid state
    __AGENCY_ANNOTATION
    asynchronous_state_impl() : valid_(false) {}

    // constructs an immediately ready state
    template<class OtherT,
             class = typename std::enable_if<
               std::is_constructible<T,OtherT&&>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t, OtherT&&) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_ready_t) : valid_(true) {}

    // constructs a not ready state
    __AGENCY_ANNOTATION
    asynchronous_state_impl(construct_not_ready_t) : valid_(true) {}

    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl&& other) : valid_(other.valid_)
    {
      other.valid_ = false;
    }

    // 1. allow moves to void states (this simply discards the state)
    // 2. allow moves to empty types if the type can be constructed from an empty argument list
    // 3. allow upcasts to a base T from a derived U
    template<class OtherT,
             class OtherAlloc,
             class T1 = T,
             class = typename std::enable_if<
               std::is_void<T1>::value ||
               (std::is_empty<T>::value && std::is_void<OtherT>::value && std::is_constructible<T>::value) ||
               std::is_base_of<T,OtherT>::value
             >::type>
    __AGENCY_ANNOTATION
    asynchronous_state_impl(asynchronous_state_impl<OtherT,OtherAlloc>&& other)
      : valid_(other.valid())
    {
      if(valid())
      {
        // invalidate the old state by calling .get() if it was valid when we received it
        other.get();
      }
    }

    __AGENCY_ANNOTATION
    asynchronous_state_impl& operator=(asynchronous_state_impl&& other)
    {
      valid_ = other.valid_;
      other.valid_ = false;

      return *this;
    }

    __AGENCY_ANNOTATION
    empty_type_ptr<T> data() const
    {
      return empty_type_ptr<T>();
    }

    __AGENCY_ANNOTATION
    T get()
    {
      valid_ = false;

      return get_impl(std::is_void<T>());
    }

    __AGENCY_ANNOTATION
    bool valid() const
    {
      return valid_;
    }

    __AGENCY_ANNOTATION
    void swap(asynchronous_state_impl& other)
    {
      bool other_valid_old = other.valid_;
      other.valid_ = valid_;
      valid_ = other_valid_old;
    }

  private:
    __AGENCY_ANNOTATION
    static T get_impl(std::false_type)
    {
      return T{};
    }

    __AGENCY_ANNOTATION
    static T get_impl(std::true_type)
    {
      return;
    }

    bool valid_;
};

// XXX this extra indirection is due to nvbug 1700337
//     eliminate this class when that bug is resolved
template<class T, class Alloc = std::allocator<T>>
class asynchronous_state : public asynchronous_state_impl<T,Alloc>
{
  public:
    using asynchronous_state_impl<T,Alloc>::asynchronous_state_impl;
};

} // end detail
} // end agency

<|endoftext|>


<commit_before>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "clustering_serv.hpp"

#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "jubatus/util/lang/cast.h"
#include "jubatus/util/text/json.h"
#include "jubatus/core/clustering/clustering_config.hpp"
#include "jubatus/core/clustering/clustering.hpp"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/jsonconfig.hpp"
#include "jubatus/core/fv_converter/converter_config.hpp"
#include "../common/logger/logger.hpp"
#include "../framework/mixer/mixer_factory.hpp"

using jubatus::util::lang::lexical_cast;
using jubatus::util::lang::shared_ptr;
using jubatus::server::framework::mixer::create_mixer;

namespace jubatus {
namespace server {
namespace {

struct clustering_serv_config {
  std::string method;
  jubatus::util::data::optional<core::common::jsonconfig::config> parameter;
  core::fv_converter::converter_config converter;

  template<typename Ar>
  void serialize(Ar& ar) {
    ar & JUBA_MEMBER(method) & JUBA_MEMBER(parameter) & JUBA_MEMBER(converter);
  }
};

}  // anonymous namespace

clustering_serv::clustering_serv(
    const framework::server_argv& a,
    const shared_ptr<common::lock_service>& zk)
    : server_base(a),
      mixer_(create_mixer(a, zk, rw_mutex(), user_data_version())) {
}

clustering_serv::~clustering_serv() {
}

void clustering_serv::get_status(status_t& status) const {
  // TODO(beam2d): Add some status of clustering
}

uint64_t clustering_serv::user_data_version() const {
  return 1;  // should be inclemented when model data is modified
}

void clustering_serv::set_config(const std::string& config) {
  core::common::jsonconfig::config config_root(
      lexical_cast<jubatus::util::text::json::json>(config));
  clustering_serv_config conf =
      core::common::jsonconfig::config_cast_check<clustering_serv_config>(
          config_root);

  config_ = config;
  shared_ptr<core::fv_converter::datum_to_fv_converter> converter =
    core::fv_converter::make_fv_converter(conf.converter, &so_loader_);

  core::common::jsonconfig::config param;
  if (conf.parameter) {
    param = *conf.parameter;
  }

  const std::string name =
      argv().eth + lexical_cast<std::string>(argv().port);
  core::clustering::clustering_config cluster_conf =
      core::common::jsonconfig::config_cast_check<
          core::clustering::clustering_config>(param);
  clustering_.reset(new core::driver::clustering(
                        shared_ptr<core::clustering::clustering>(
                            new core::clustering::clustering(
                                name,
                                conf.method,
                                cluster_conf)),
                        converter));
  mixer_->set_driver(clustering_.get());

  LOG(INFO) << "config loaded: " << config;
}

std::string clustering_serv::get_config() const {
  return config_;
}

bool clustering_serv::push(
    const std::vector<core::fv_converter::datum>& points) {
  check_set_config();
  clustering_->push(points);
  return true;
}

core::fv_converter::datum clustering_serv::get_nearest_center(
    const core::fv_converter::datum& point) const {
  check_set_config();
  return clustering_->get_nearest_center(point);
}

std::vector<std::pair<double, core::fv_converter::datum> >
    clustering_serv::get_nearest_members(
        const core::fv_converter::datum& point) const {
  check_set_config();
  return clustering_->get_nearest_members(point);
}

std::vector<core::fv_converter::datum> clustering_serv::get_k_center() const {
  check_set_config();
  return clustering_->get_k_center();
}

std::vector<std::vector<std::pair<double, core::fv_converter::datum> > >
clustering_serv::get_core_members() const {
  check_set_config();
  return clustering_->get_core_members();
}

size_t clustering_serv::get_revision() const {
  check_set_config();
  return clustering_->get_revision();
}

void clustering_serv::check_set_config() const {
  if (!clustering_) {
    throw JUBATUS_EXCEPTION(core::common::config_not_set());
  }
}

}  // namespace server
}  // namespace jubatus
<commit_msg>fix clustering instance ID<commit_after>// Jubatus: Online machine learning framework for distributed environment
// Copyright (C) 2013 Preferred Networks and Nippon Telegraph and Telephone Corporation.
//
// This library is free software; you can redistribute it and/or
// modify it under the terms of the GNU Lesser General Public
// License version 2.1 as published by the Free Software Foundation.
//
// This library is distributed in the hope that it will be useful,
// but WITHOUT ANY WARRANTY; without even the implied warranty of
// MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
// Lesser General Public License for more details.
//
// You should have received a copy of the GNU Lesser General Public
// License along with this library; if not, write to the Free Software
// Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301  USA

#include "clustering_serv.hpp"

#include <sstream>
#include <string>
#include <utility>
#include <vector>
#include "jubatus/util/lang/cast.h"
#include "jubatus/util/text/json.h"
#include "jubatus/core/clustering/clustering_config.hpp"
#include "jubatus/core/clustering/clustering.hpp"
#include "jubatus/core/common/exception.hpp"
#include "jubatus/core/common/jsonconfig.hpp"
#include "jubatus/core/fv_converter/converter_config.hpp"
#include "../common/logger/logger.hpp"
#include "../framework/mixer/mixer_factory.hpp"

using jubatus::util::lang::lexical_cast;
using jubatus::util::lang::shared_ptr;
using jubatus::server::framework::mixer::create_mixer;

namespace jubatus {
namespace server {
namespace {

struct clustering_serv_config {
  std::string method;
  jubatus::util::data::optional<core::common::jsonconfig::config> parameter;
  core::fv_converter::converter_config converter;

  template<typename Ar>
  void serialize(Ar& ar) {
    ar & JUBA_MEMBER(method) & JUBA_MEMBER(parameter) & JUBA_MEMBER(converter);
  }
};

}  // anonymous namespace

clustering_serv::clustering_serv(
    const framework::server_argv& a,
    const shared_ptr<common::lock_service>& zk)
    : server_base(a),
      mixer_(create_mixer(a, zk, rw_mutex(), user_data_version())) {
}

clustering_serv::~clustering_serv() {
}

void clustering_serv::get_status(status_t& status) const {
  // TODO(beam2d): Add some status of clustering
}

uint64_t clustering_serv::user_data_version() const {
  return 1;  // should be inclemented when model data is modified
}

void clustering_serv::set_config(const std::string& config) {
  core::common::jsonconfig::config config_root(
      lexical_cast<jubatus::util::text::json::json>(config));
  clustering_serv_config conf =
      core::common::jsonconfig::config_cast_check<clustering_serv_config>(
          config_root);

  config_ = config;
  shared_ptr<core::fv_converter::datum_to_fv_converter> converter =
    core::fv_converter::make_fv_converter(conf.converter, &so_loader_);

  core::common::jsonconfig::config param;
  if (conf.parameter) {
    param = *conf.parameter;
  }

  const std::string name = get_server_identifier(argv());
  core::clustering::clustering_config cluster_conf =
      core::common::jsonconfig::config_cast_check<
          core::clustering::clustering_config>(param);
  clustering_.reset(new core::driver::clustering(
                        shared_ptr<core::clustering::clustering>(
                            new core::clustering::clustering(
                                name,
                                conf.method,
                                cluster_conf)),
                        converter));
  mixer_->set_driver(clustering_.get());

  LOG(INFO) << "config loaded: " << config;
}

std::string clustering_serv::get_config() const {
  return config_;
}

bool clustering_serv::push(
    const std::vector<core::fv_converter::datum>& points) {
  check_set_config();
  clustering_->push(points);
  return true;
}

core::fv_converter::datum clustering_serv::get_nearest_center(
    const core::fv_converter::datum& point) const {
  check_set_config();
  return clustering_->get_nearest_center(point);
}

std::vector<std::pair<double, core::fv_converter::datum> >
    clustering_serv::get_nearest_members(
        const core::fv_converter::datum& point) const {
  check_set_config();
  return clustering_->get_nearest_members(point);
}

std::vector<core::fv_converter::datum> clustering_serv::get_k_center() const {
  check_set_config();
  return clustering_->get_k_center();
}

std::vector<std::vector<std::pair<double, core::fv_converter::datum> > >
clustering_serv::get_core_members() const {
  check_set_config();
  return clustering_->get_core_members();
}

size_t clustering_serv::get_revision() const {
  check_set_config();
  return clustering_->get_revision();
}

void clustering_serv::check_set_config() const {
  if (!clustering_) {
    throw JUBATUS_EXCEPTION(core::common::config_not_set());
  }
}

}  // namespace server
}  // namespace jubatus
<|endoftext|>


<commit_before>// Copyright 2021 Google LLC.

#include "experimental/sktext/src/LogicalRun.h"

namespace skia {
namespace text {

LogicalRun::LogicalRun(const SkShaper::RunHandler::RunInfo& info, TextIndex textStart, SkScalar glyphOffset)
    : fFont(info.fFont)
    , fBidiLevel(info.fBidiLevel)
    , fAdvance(info.fAdvance)
    , fUtf8Range(info.utf8Range)
    , fTextMetrics(info.fFont)
    , fRunStart(textStart)
    , fRunOffset(glyphOffset)
    , fRunType(LogicalRunType::kText) {
    fGlyphs.push_back_n(info.glyphCount);
    fBounds.push_back_n(info.glyphCount);
    fPositions.push_back_n(info.glyphCount + 1);
    fOffsets.push_back_n(info.glyphCount);
    fClusters.push_back_n(info.glyphCount + 1);
}

} // namespace text
} // namespace skia
<commit_msg>Fixing Android build bug<commit_after>// Copyright 2021 Google LLC.

#include "experimental/sktext/src/LogicalRun.h"

namespace skia {
namespace text {

LogicalRun::LogicalRun(const SkShaper::RunHandler::RunInfo& info, TextIndex textStart, SkScalar glyphOffset)
    : fFont(info.fFont)
    , fTextMetrics(info.fFont)
    , fRunType(LogicalRunType::kText)
    , fAdvance(info.fAdvance)
    , fUtf8Range(info.utf8Range)
    , fRunStart(textStart)
    , fRunOffset(glyphOffset)
    , fBidiLevel(info.fBidiLevel)
{
    fGlyphs.push_back_n(info.glyphCount);
    fBounds.push_back_n(info.glyphCount);
    fPositions.push_back_n(info.glyphCount + 1);
    fOffsets.push_back_n(info.glyphCount);
    fClusters.push_back_n(info.glyphCount + 1);
}

} // namespace text
} // namespace skia
<|endoftext|>


<commit_before>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "MultiAppPostprocessorNearestElementTransfer.h"
#include "FEProblem.h"
#include "MooseMesh.h"
#include "MooseTypes.h"
#include "MooseVariableFE.h"
#include "MultiApp.h"
#include "SystemBase.h"

registerMooseObject("MooseApp", MultiAppPostprocessorNearestElementTransfer);

InputParameters
MultiAppPostprocessorNearestElementTransfer::validParams()
{
  InputParameters params = MultiAppTransfer::validParams();
  params.addClassDescription(
      "Reconstruct the value of a CONSTANT MONOMIAL variable associating the "
      "value of each element to the value of the postprocessor in the closest "
      "MultiApp.");
  params.addRequiredParam<PostprocessorName>(
      "postprocessor", "The name of the postprocessor in the MultiApp to transfer the value from.");
  params.addRequiredParam<VariableName>("source_variable",
                                        "The CONSTANT "
                                        "MONOMIAL variable to transfer to.");
  params.addParam<unsigned int>("source_variable_component", 0, "The component of source variable");
  return params;
}

MultiAppPostprocessorNearestElementTransfer::MultiAppPostprocessorNearestElementTransfer(
    const InputParameters & parameters)
  : MultiAppTransfer(parameters),
    _postprocessor_name(getParam<PostprocessorName>("postprocessor")),
    _to_var_name(getParam<VariableName>("source_variable")),
    _to_problem(getFromMultiApp()->problemBase()),
    _to_var(_to_problem.getVariable(0, _to_var_name)),
    _to_sys(_to_var.sys().system()),
    _to_mesh(_to_problem.mesh().getMesh()),
    _to_sys_num(_to_sys.number()),
    _to_var_num(_to_sys.variable_number(
        _to_var.componentName(getParam<unsigned int>("source_variable_component"))))
{
  // Check the number of transfer directions.
  if (_directions.size() != 1 && _directions.get(0) != FROM_MULTIAPP)
    mooseError("MultiAppPostprocessorNearestElementTransfer works only with direction equal to "
               "FROM_MULTIAPP");

  // Check that the variable is a CONSTANT MONOMIAL.
  auto & to_fe_type = _to_sys.variable_type(_to_var_num);
  if (to_fe_type.order != CONSTANT || to_fe_type.family != MONOMIAL)
    mooseError(parameters.blockLocation() + " " + parameters.blockFullpath() +
               "\nMultiAppPostprocessorNearestElementTransfer works with CONSTANT MONOMIAL "
               "variables only");
}

void
MultiAppPostprocessorNearestElementTransfer::initialSetup()
{
  // Cache the Multiapp position ID for every element.
  unsigned int multiapp_pos_id = 0;
  for (auto & elem :
       as_range(_to_mesh.active_local_elements_begin(), _to_mesh.active_local_elements_end()))
  {
    // Exclude the elements without dofs.
    if (elem->n_dofs(_to_sys_num, _to_var_num) > 0)
    {
      Real distance = std::numeric_limits<Real>::max();
      for (unsigned int j = 0; j < getFromMultiApp()->numGlobalApps(); ++j)
      {
        Real current_distance = (getFromMultiApp()->position(j) - elem->true_centroid()).norm();
        if (current_distance < distance)
        {
          distance = current_distance;
          multiapp_pos_id = j;
        }
      }
      _cached_multiapp_pos_ids.push_back(multiapp_pos_id);
    }
  }
}

void
MultiAppPostprocessorNearestElementTransfer::execute()
{
  // Check that transfer direction is FROM_MULTIAPP.
  if (_current_direction != FROM_MULTIAPP)
    paramError("direction", "This transfer works only with direction equal to FROM_MULTIAPP");

  // Retrieve the vector of the variable values.
  NumericVector<Real> & solution = *_to_sys.solution;

  // Store the local multiapps postprocessor values.
  const unsigned int n_subapps = getFromMultiApp()->numGlobalApps();
  std::vector<Real> pp_values(n_subapps, std::numeric_limits<Real>::max());
  std::vector<Real> duplicate(n_subapps, -std::numeric_limits<Real>::max());
  for (const auto i : make_range(n_subapps))
    if (getFromMultiApp()->hasLocalApp(i))
    {
      pp_values[i] = getFromMultiApp()->appPostprocessorValue(i, _postprocessor_name);
      duplicate[i] = pp_values[i];
    }

  // Gather all the multiapps postprocessor values.
  _communicator.min(pp_values);
  _communicator.max(duplicate);
  for (const auto i : make_range(n_subapps))
    if (pp_values[i] != duplicate[i])
      mooseError("There should be only one processor setting a subapp postprocessor but now this "
                 "appears not true.");

  // Assign the multiapps postprocessor values to the local elements.
  unsigned int i = 0;
  for (auto & elem :
       as_range(_to_mesh.active_local_elements_begin(), _to_mesh.active_local_elements_end()))
  {
    // Exclude the elements without dofs
    if (elem->n_dofs(_to_sys_num, _to_var_num) > 0)
    {
      dof_id_type dof = elem->dof_number(_to_sys_num, _to_var_num, 0);
      solution.set(dof, pp_values[_cached_multiapp_pos_ids[i]]);
      ++i;
    }
  }
  solution.close();
}
<commit_msg>Only do second all-to-all communication in debug mode<commit_after>//* This file is part of the MOOSE framework
//* https://www.mooseframework.org
//*
//* All rights reserved, see COPYRIGHT for full restrictions
//* https://github.com/idaholab/moose/blob/master/COPYRIGHT
//*
//* Licensed under LGPL 2.1, please see LICENSE for details
//* https://www.gnu.org/licenses/lgpl-2.1.html

#include "MultiAppPostprocessorNearestElementTransfer.h"
#include "FEProblem.h"
#include "MooseMesh.h"
#include "MooseTypes.h"
#include "MooseVariableFE.h"
#include "MultiApp.h"
#include "SystemBase.h"

registerMooseObject("MooseApp", MultiAppPostprocessorNearestElementTransfer);

InputParameters
MultiAppPostprocessorNearestElementTransfer::validParams()
{
  InputParameters params = MultiAppTransfer::validParams();
  params.addClassDescription(
      "Reconstruct the value of a CONSTANT MONOMIAL variable associating the "
      "value of each element to the value of the postprocessor in the closest "
      "MultiApp.");
  params.addRequiredParam<PostprocessorName>(
      "postprocessor", "The name of the postprocessor in the MultiApp to transfer the value from.");
  params.addRequiredParam<VariableName>("source_variable",
                                        "The CONSTANT "
                                        "MONOMIAL variable to transfer to.");
  params.addParam<unsigned int>("source_variable_component", 0, "The component of source variable");
  return params;
}

MultiAppPostprocessorNearestElementTransfer::MultiAppPostprocessorNearestElementTransfer(
    const InputParameters & parameters)
  : MultiAppTransfer(parameters),
    _postprocessor_name(getParam<PostprocessorName>("postprocessor")),
    _to_var_name(getParam<VariableName>("source_variable")),
    _to_problem(getFromMultiApp()->problemBase()),
    _to_var(_to_problem.getVariable(0, _to_var_name)),
    _to_sys(_to_var.sys().system()),
    _to_mesh(_to_problem.mesh().getMesh()),
    _to_sys_num(_to_sys.number()),
    _to_var_num(_to_sys.variable_number(
        _to_var.componentName(getParam<unsigned int>("source_variable_component"))))
{
  // Check the number of transfer directions.
  if (_directions.size() != 1 && _directions.get(0) != FROM_MULTIAPP)
    mooseError("MultiAppPostprocessorNearestElementTransfer works only with direction equal to "
               "FROM_MULTIAPP");

  // Check that the variable is a CONSTANT MONOMIAL.
  auto & to_fe_type = _to_sys.variable_type(_to_var_num);
  if (to_fe_type.order != CONSTANT || to_fe_type.family != MONOMIAL)
    mooseError(parameters.blockLocation() + " " + parameters.blockFullpath() +
               "\nMultiAppPostprocessorNearestElementTransfer works with CONSTANT MONOMIAL "
               "variables only");
}

void
MultiAppPostprocessorNearestElementTransfer::initialSetup()
{
  // Cache the Multiapp position ID for every element.
  unsigned int multiapp_pos_id = 0;
  for (auto & elem :
       as_range(_to_mesh.active_local_elements_begin(), _to_mesh.active_local_elements_end()))
  {
    // Exclude the elements without dofs.
    if (elem->n_dofs(_to_sys_num, _to_var_num) > 0)
    {
      Real distance = std::numeric_limits<Real>::max();
      for (unsigned int j = 0; j < getFromMultiApp()->numGlobalApps(); ++j)
      {
        Real current_distance = (getFromMultiApp()->position(j) - elem->true_centroid()).norm();
        if (current_distance < distance)
        {
          distance = current_distance;
          multiapp_pos_id = j;
        }
      }
      _cached_multiapp_pos_ids.push_back(multiapp_pos_id);
    }
  }
}

void
MultiAppPostprocessorNearestElementTransfer::execute()
{
  // Check that transfer direction is FROM_MULTIAPP.
  if (_current_direction != FROM_MULTIAPP)
    paramError("direction", "This transfer works only with direction equal to FROM_MULTIAPP");

  // Retrieve the vector of the variable values.
  NumericVector<Real> & solution = *_to_sys.solution;

  // Store the local multiapps postprocessor values.
  const unsigned int n_subapps = getFromMultiApp()->numGlobalApps();
  std::vector<Real> pp_values(n_subapps, std::numeric_limits<Real>::max());
#ifdef DEBUG
  std::vector<Real> duplicate(n_subapps, -std::numeric_limits<Real>::max());
#endif
  for (const auto i : make_range(n_subapps))
    if (getFromMultiApp()->hasLocalApp(i))
    {
      pp_values[i] = getFromMultiApp()->appPostprocessorValue(i, _postprocessor_name);
#ifdef DEBUG
      duplicate[i] = pp_values[i];
#endif
    }

  // Gather all the multiapps postprocessor values.
  _communicator.min(pp_values);
#ifdef DEBUG
  _communicator.max(duplicate);
  for (const auto i : make_range(n_subapps))
    if (pp_values[i] != duplicate[i])
      mooseError("There should be only one processor setting a subapp postprocessor but now this "
                 "appears not true.");
#endif

  // Assign the multiapps postprocessor values to the local elements.
  unsigned int i = 0;
  for (auto & elem :
       as_range(_to_mesh.active_local_elements_begin(), _to_mesh.active_local_elements_end()))
  {
    // Exclude the elements without dofs
    if (elem->n_dofs(_to_sys_num, _to_var_num) > 0)
    {
      dof_id_type dof = elem->dof_number(_to_sys_num, _to_var_num, 0);
      solution.set(dof, pp_values[_cached_multiapp_pos_ids[i]]);
      ++i;
    }
  }
  solution.close();
}
<|endoftext|>


<commit_before>// 6.exercise.10.cpp
//
// A permutation is an ordered subset of a set. For example, say you wanted to
// pick a combination to a vault. There are 60 possible numbers, and you need
// three different numbers for the combination. There are P(60,3) permutations
// for the combination, where P is defined by the formula
//
//                a!
//     P(a,b) = ------,
//              (a-b)!
//
// where ! is used as a suffix factorial operator. For example, 4! is
// 4\*3\*2\*1.
//
// Combinations are similar to permutations, except that the order of the
// objects doesn't matter. For example, if you were making a "banana split"
// sundea and wished to use three different flavors of ice cream out of five
// that you had, you wouldn't care if you used a scoop of vanilla at the
// beginning or the end; you would still have used vanilla. The formula for
// combination is
//
//              P(a,b)
//     C(a,b) = ------.
//                b!
//
// Design a program that asks users for two numbers, asks them whether they
// want to calculate permutations or combinations, and prints out the result.
// This will have several parts. Do an analysis of the above requeriments.
// Write exactly what the program will have to do. Then go into design phase.
// Write pseudo code for the program, and break it into sub-components. This
// program should have error checking. Make sure that all erroneous inputs will
// generate good error messages
//
// Comments: See 6.exercise.10.md

#include "std_lib_facilities.h"

const string ex_msg_pmul_with_negs = "check_pmul() called with negative integers.";
const string ex_msg_product_overflows = "integer multiplication overflows.";

int get_natural()
// Currently it only reads a integer without any check. It's an straight
// version to check other functions implementation.
{
    int n;
    cin >> n;
    return n;
}

bool check_pmul(int a, int b)
// Partial implementation from SECURE CODING INT32C.
// It do not throw since is its work to tell if multiplication could
// be performed or not. Using exceptions is, I think, BLAHBLAHBLAH
// Precondition:
//      Both arguments must be positive.
{
    if (a < 0 || b < 0)
        throw runtime_error(ex_msg_pmul_with_negs);

    if ( a > (numeric_limits<int>::max() / b) )
        return false;

    return true;
}

int perm(int n, int k)
// Calculates the k-permutations of n elements, what we call P(n, k).
// This is not done with the factorial formula expressed in the statement but
// with a limited product. See 6.exercise.10.md for details.
// If either n or k equals zero, the permutation is 1.
//
// Preconditions:
//      - n and k must be positive and n >= k. We will not check this
//      precondition here since we assume it is assured by previous calls to
//      get_natural() and check_input().
{
    if (n == 0 || k == 0) return 1;

    int prod = 1;

    for (int i = n-k+1; i <= n; ++i)
        if (check_pmul(prod, i))
            prod *= i;
        else
            throw runtime_error(ex_msg_product_overflows);

    return prod;
}

int main(void)
try
{
    int setc = 0;
    int subc = 0;
    char cont = 'y';

    while (cont == 'y' || cont == 'Y') {
        cout << "Set cardinality?\n";
        setc = get_natural();
        cout << "Subset cardinality?\n";
        subc = get_natural();
        cout << perm(setc, subc) << '\n';
        cout << perm(-1, subc) << '\n';
    }

    return 0;
}
catch(exception& e)
{
    cerr << e.what() << '\n';
    return 1;
}
catch(...)
{
    cerr << "Oops! Unknown exception.\n";
    return 2;
}
<commit_msg>Another proof of concept.<commit_after>// 6.exercise.10.cpp
//
// A permutation is an ordered subset of a set. For example, say you wanted to
// pick a combination to a vault. There are 60 possible numbers, and you need
// three different numbers for the combination. There are P(60,3) permutations
// for the combination, where P is defined by the formula
//
//                a!
//     P(a,b) = ------,
//              (a-b)!
//
// where ! is used as a suffix factorial operator. For example, 4! is
// 4\*3\*2\*1.
//
// Combinations are similar to permutations, except that the order of the
// objects doesn't matter. For example, if you were making a "banana split"
// sundea and wished to use three different flavors of ice cream out of five
// that you had, you wouldn't care if you used a scoop of vanilla at the
// beginning or the end; you would still have used vanilla. The formula for
// combination is
//
//              P(a,b)
//     C(a,b) = ------.
//                b!
//
// Design a program that asks users for two numbers, asks them whether they
// want to calculate permutations or combinations, and prints out the result.
// This will have several parts. Do an analysis of the above requeriments.
// Write exactly what the program will have to do. Then go into design phase.
// Write pseudo code for the program, and break it into sub-components. This
// program should have error checking. Make sure that all erroneous inputs will
// generate good error messages
//
// Comments: See 6.exercise.10.md

#include "std_lib_facilities.h"

const string ex_msg_pmul_with_negs = "called with negative integers.";
const string ex_msg_product_overflows = "integer multiplication overflows.";

int get_natural()
// Currently it only reads a integer without any check. It's an straight
// version to check other functions implementation.
{
    int n;
    cin >> n;
    return n;
}

bool check_pmul(int a, int b)
// Partial implementation from SECURE CODING INT32C.
// It do not throw since is its work to tell if multiplication could
// be performed or not. Using exceptions is, I think, BLAHBLAHBLAH
// Precondition:
//      Both arguments must be positive.
{
    if (a < 0 || b < 0)
        throw runtime_error("check_pmul(): " + ex_msg_pmul_with_negs);

    if ( a > (numeric_limits<int>::max() / b) )
        return false;

    return true;
}

int perm(int n, int k)
// Calculates the k-permutations of n elements, what we call P(n, k).
// This is not done with the factorial formula expressed in the statement but
// with a limited product. See 6.exercise.10.md for details.
// If either n or k equals zero, the permutation is 1.
//
// Preconditions:
//      - n and k must be positive and n >= k. We will not check this
//      precondition here since we assume it is assured by previous calls to
//      get_natural() and check_input().
{
    if (n == 0 || k == 0) return 1;

    int prod = 1;

    for (int i = n-k+1; i <= n; ++i)
        if (check_pmul(prod, i))
            prod *= i;
        else
            throw runtime_error("perm(): " + ex_msg_product_overflows);

    return prod;
}

int comb(int n, int k)
// Calculates the k-combinations of n elements, what we call C(n, k).
// This is not done with the factorial formula expressed in the statement but,
// being the k-combinations of n element also known as the binomial
// coefficient, using the multiplicative formual as stated in
// https://en.wikipedia.org/wiki/Binomial_coefficient#Multiplicative_formula
//
// Preconditions:
//      - n and k must be positive and n >= k. We will not check this
//      precondition here since we assume it is assured by previous calls to
//      get_natural() and check_input().
{
    if (n == 0 || k == 0) return 1;

    int prod = 1;

    for (int i = 1; i <= k; ++i)
        if (check_pmul(prod, n+1-i))
            // Multiplying first by the numerator ensure the division to have
            // no reminder.
            prod = (prod * (n+1-i)) / i;
        else
            throw runtime_error("comb(): " + ex_msg_product_overflows);

    return prod;
}

int main(void)
try
{
    int setc = 0;
    int subc = 0;
    char cont = 'y';

    while (cont == 'y' || cont == 'Y') {
        cout << "Set cardinality?\n";
        setc = get_natural();
        cout << "Subset cardinality?\n";
        subc = get_natural();

        try {
            cout << "P(" << setc << ", " << subc << ") = " << perm(setc, subc) << '\n';
        } catch(exception &e) {
            cerr << "Exception -> " << e.what() << '\n';
        }

        try {
            cout << "C(" << setc << ", " << subc << ") = " << comb(setc, subc) << '\n';
        } catch(exception &e) {
            cerr << "Exception -> " << e.what() << '\n';
        }
    }

    return 0;
}
catch(exception& e)
{
    cerr << e.what() << '\n';
    return 1;
}
catch(...)
{
    cerr << "Oops! Unknown exception.\n";
    return 2;
}
<|endoftext|>